merge main

This commit is contained in:
Dallin Romney 2025-01-14 18:17:10 -08:00
commit fd90652df7
160 changed files with 4748 additions and 3319 deletions

View file

@ -6,6 +6,7 @@
},
"plugins": ["@typescript-eslint", "import"],
"rules": {
"@typescript-eslint/naming-convention": "off",
"@typescript-eslint/semi": "warn",
"curly": "warn",
"eqeqeq": "warn",

View file

@ -0,0 +1,60 @@
---
name: 📖 Documentation Issue Report
description: Report issues related to the documentation
labels: [area:docs]
body:
- type: markdown
attributes:
value: |
## Thank you for helping us improve our documentation!
We appreciate your feedback. Before submitting, please check if a similar issue already exists.
### Quick Contribution Tips:
- Click "Edit this page" at the bottom of any page on [docs.continue.dev](https://docs.continue.dev) to contribute directly.
- For local development, see [CONTRIBUTING.md](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md#-updating--improving-documentation).
- type: dropdown
id: doc-issue-category
attributes:
label: Issue Category
description: Select the category that best describes your issue.
options:
- Undocumented feature or missing documentation
- Incorrect or outdated information
- Suggestion for existing article
- Broken or dead link
- Documentation organization issue
- Other (please describe in the details section)
validations:
required: true
- type: input
id: page-url
attributes:
label: Affected Documentation Page URL
description: Provide the URL of the specific page where you encountered the issue.
placeholder: "https://docs.continue.dev/path/to/page"
validations:
required: false
- type: textarea
id: details
attributes:
label: Issue Description
description: Please describe the issue in detail. Include specifics about missing information, outdated content, or improvements needed.
placeholder: |
Examples:
- Missing section on [topic]
- Incorrect information about [subject]
- Outdated example code for [feature]
- Suggestion to improve [section] by [details]
validations:
required: true
- type: textarea
id: expected-content
attributes:
label: Expected Content
description: If applicable, provide the content you believe should be added or updated.
placeholder: "Suggested details or changes for the documentation..."

View file

@ -96,7 +96,7 @@ jobs:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
install-gui:
needs: [install-root, install-core]
needs: [ install-root, install-core ]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -157,7 +157,7 @@ jobs:
npx tsc --noEmit
binary-checks:
needs: [install-root, install-core]
needs: [ install-root, install-core ]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -193,7 +193,7 @@ jobs:
npx tsc --noEmit
install-vscode:
needs: [install-root, install-core]
needs: [ install-root, install-core ]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -277,7 +277,7 @@ jobs:
vscode-get-test-file-matrix:
runs-on: ubuntu-latest
needs: [install-root, install-vscode]
needs: [ install-root, install-vscode ]
outputs:
test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}
steps:
@ -306,7 +306,7 @@ jobs:
vscode-package-extension:
runs-on: ubuntu-latest
needs: [install-vscode, install-core]
needs: [ install-vscode, install-core ]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
@ -338,7 +338,7 @@ jobs:
vscode-download-e2e-dependencies:
runs-on: ubuntu-latest
needs: [install-vscode, install-core]
needs: [ install-vscode, install-core ]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
@ -445,7 +445,7 @@ jobs:
path: extensions/vscode/e2e/storage/screenshots
gui-tests:
needs: [install-gui, install-core]
needs: [ install-gui, install-core ]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -476,7 +476,7 @@ jobs:
npm test
jetbrains-tests:
needs: [install-root, install-core]
needs: [ install-root, core-checks ]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -573,3 +573,5 @@ jobs:
name: jb-failure-report
path: |
${{ github.workspace }}/extensions/intellij/build/reports

View file

@ -188,7 +188,7 @@ After you've written your context provider, make sure to complete the following:
### Adding an LLM Provider
Continue has support for more than a dozen different LLM "providers", making it easy to use models running on OpenAI, Ollama, Together, Novita AI, LM Studio, Msty, and more. You can find all of the existing providers [here](https://github.com/continuedev/continue/tree/main/core/llm/llms), and if you see one missing, you can add it with the following steps:
Continue has support for more than a dozen different LLM "providers", making it easy to use models running on OpenAI, Ollama, Together, LM Studio, Msty, and more. You can find all of the existing providers [here](https://github.com/continuedev/continue/tree/main/core/llm/llms), and if you see one missing, you can add it with the following steps:
1. Create a new file in the `core/llm/llms` directory. The name of the file should be the name of the provider, and it should export a class that extends `BaseLLM`. This class should contain the following minimal implementation. We recommend viewing pre-existing providers for more details. The [LlamaCpp Provider](./core/llm/llms/LlamaCpp.ts) is a good simple example.
@ -209,7 +209,7 @@ While any model that works with a supported provider can be used with Continue,
1. Add a `ModelPackage` entry for the model into [configs/models.ts](./gui/src/pages/AddNewModel/configs/models.ts), following the lead of the many examples near the top of the file
2. Add the model within its provider's array to [AddNewModel.tsx](./gui/src/pages/AddNewModel/AddNewModel.tsx) (add provider if needed)
- [index.d.ts](./core/index.d.ts) - This file defines the TypeScript types used throughout Continue. You'll find a `ModelName` type. Be sure to add the name of your model to this.
- LLM Providers: Since many providers use their own custom strings to identify models, you'll have to add the translation from Continue's model name (the one you added to `index.d.ts`) and the model string for each of these providers: [Ollama](./core/llm/llms/Ollama.ts), [Together](./core/llm/llms/Together.ts), [Novita AI](./core/llm/llms/Novita.ts), and [Replicate](./core/llm/llms/Replicate.ts). You can find their full model lists here: [Ollama](https://ollama.ai/library), [Together](https://docs.together.ai/docs/inference-models), [Novita AI](https://novita.ai/llm-api?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link), [Replicate](https://replicate.com/collections/streaming-language-models).
- LLM Providers: Since many providers use their own custom strings to identify models, you'll have to add the translation from Continue's model name (the one you added to `index.d.ts`) and the model string for each of these providers: [Ollama](./core/llm/llms/Ollama.ts), [Together](./core/llm/llms/Together.ts), and [Replicate](./core/llm/llms/Replicate.ts). You can find their full model lists here: [Ollama](https://ollama.ai/library), [Together](https://docs.together.ai/docs/inference-models), [Replicate](https://replicate.com/collections/streaming-language-models).
- [Prompt Templates](./core/llm/index.ts) - In this file you'll find the `autodetectTemplateType` function. Make sure that for the model name you just added, this function returns the correct template type. This is assuming that the chat template for that model is already built in Continue. If not, you will have to add the template type and corresponding edit and chat templates.
### Adding Pre-indexed Documentation

View file

@ -118,6 +118,7 @@
"@types/jest": "^29.5.12",
"@types/jquery": "^3.5.29",
"@types/jsdom": "^21.1.6",
"@types/json-schema": "^7.0.15",
"@types/mozilla-readability": "^0.2.1",
"@types/mustache": "^4.2.5",
"@types/node-fetch": "^2.6.11",

View file

@ -1,5 +1,4 @@
import { streamLines } from "../../../diff/util";
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../../../util/parameters";
import { PosthogFeatureFlag, Telemetry } from "../../../util/posthog";
import { HelperVars } from "../../util/HelperVars";
@ -74,12 +73,10 @@ export class StreamTransformPipeline {
fullStop,
);
const timeoutValue =
helper.options.showWhateverWeHaveAtXMs ??
(await Telemetry.getValueForFeatureFlag(
PosthogFeatureFlag.AutocompleteTimeout,
)) ??
DEFAULT_AUTOCOMPLETE_OPTS.showWhateverWeHaveAtXMs;
const timeoutValue = await Telemetry.getValueForFeatureFlag(
PosthogFeatureFlag.AutocompleteTimeout,
);
// helper.options.showWhateverWeHaveAtXMs ?? DEFAULT_AUTOCOMPLETE_OPTS.showWhateverWeHaveAtXMs
lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, timeoutValue!);

View file

@ -59,8 +59,8 @@ export async function testAutocompleteFiltering(
line,
character,
},
recentlyEditedFiles: [],
recentlyEditedRanges: [],
recentlyVisitedRanges: [],
};
// Generate a completion

View file

@ -3,6 +3,7 @@ import { findUriInDirs } from "../../util/uri";
import { ContextRetrievalService } from "../context/ContextRetrievalService";
import { GetLspDefinitionsFunction } from "../types";
import { HelperVars } from "../util/HelperVars";
import {
AutocompleteClipboardSnippet,
AutocompleteCodeSnippet,
@ -15,6 +16,7 @@ export interface SnippetPayload {
importDefinitionSnippets: AutocompleteCodeSnippet[];
ideSnippets: AutocompleteCodeSnippet[];
recentlyEditedRangeSnippets: AutocompleteCodeSnippet[];
recentlyVisitedRangesSnippets: AutocompleteCodeSnippet[];
diffSnippets: AutocompleteDiffSnippet[];
clipboardSnippets: AutocompleteClipboardSnippet[];
}
@ -135,5 +137,6 @@ export const getAllSnippets = async ({
recentlyEditedRangeSnippets,
diffSnippets,
clipboardSnippets,
recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges,
};
};

View file

@ -111,13 +111,13 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = {
return snippet.content;
}
return `+++++ ${relativePaths[i]}\n${snippet.content}`;
return `+++++ ${relativePaths[i].uri} \n${snippet.content}`;
})
.join("\n\n");
return [
`${otherFiles}\n\n+++++ ${
relativePaths[relativePaths.length - 1]
relativePaths[relativePaths.length - 1].uri
}\n${prefix}`,
suffix,
];

View file

@ -5,6 +5,7 @@ import {
AutocompleteSnippet,
} from "../snippets/types";
import { HelperVars } from "../util/HelperVars";
import { isValidSnippet } from "./validation";
const getRemainingTokenCount = (helper: HelperVars): number => {
@ -44,6 +45,7 @@ export const getSnippets = (
const snippets = [
...payload.diffSnippets,
...payload.clipboardSnippets,
...payload.recentlyVisitedRangesSnippets,
...shuffleArray(
filterSnippetsAlreadyInCaretWindow(
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],

View file

@ -5,6 +5,7 @@ import {
RangeInFileWithContents,
TabAutocompleteOptions,
} from "../..";
import { AutocompleteCodeSnippet } from "../snippets/types";
export type RecentlyEditedRange = RangeInFile & {
timestamp: number;
@ -17,7 +18,7 @@ export interface AutocompleteInput {
completionId: string;
filepath: string;
pos: Position;
recentlyEditedFiles: RangeInFileWithContents[];
recentlyVisitedRanges: AutocompleteCodeSnippet[];
recentlyEditedRanges: RecentlyEditedRange[];
// Used for notebook files
manuallyPassFileContents?: string;

View file

@ -1,5 +1,6 @@
import { SlashCommand } from "../../index.js";
import { removeQuotesAndEscapes } from "../../util/index.js";
import { streamResponse } from "../../llm/stream.js";
const HttpSlashCommand: SlashCommand = {
name: "http",
@ -23,14 +24,8 @@ const HttpSlashCommand: SlashCommand = {
if (response.body === null) {
throw new Error("Response body is null");
}
const reader = response.body.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
const decoded = new TextDecoder("utf-8").decode(value);
yield decoded;
for await (const chunk of streamResponse(response)) {
yield chunk;
}
},
};

View file

@ -33,7 +33,6 @@ import {
} from "../commands/index.js";
import { AllRerankers } from "../context/allRerankers";
import { MCPManagerSingleton } from "../context/mcp";
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider";
import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider";
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
import FileContextProvider from "../context/providers/FileContextProvider";
@ -46,6 +45,8 @@ import CustomLLMClass from "../llm/llms/CustomLLM";
import FreeTrial from "../llm/llms/FreeTrial";
import { LLMReranker } from "../llm/llms/llm";
import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider";
import { slashCommandFromPromptFileV1 } from "../promptFiles/v1/slashCommandFromPromptFile";
import { getAllPromptFiles } from "../promptFiles/v2/getPromptFiles";
import { allTools } from "../tools";
import { copyOf } from "../util";
import { GlobalContext } from "../util/GlobalContext";
@ -61,8 +62,6 @@ import {
getEsbuildBinaryPath,
} from "../util/paths";
import { slashCommandFromPromptFileV1 } from "../promptFiles/v1/slashCommandFromPromptFile";
import { getAllPromptFiles } from "../promptFiles/v2/getPromptFiles";
import {
defaultContextProvidersJetBrains,
defaultContextProvidersVsCode,
@ -70,6 +69,7 @@ import {
defaultSlashCommandsVscode,
} from "./default";
import { getSystemPromptDotFile } from "./getSystemPromptDotFile";
// import { isSupportedLanceDbCpuTarget } from "./util";
import { ConfigValidationError, validateConfig } from "./validation.js";
export interface ConfigResult<T> {
@ -112,6 +112,7 @@ function loadSerializedConfig(
ideSettings: IdeSettings,
ideType: IdeType,
overrideConfigJson: SerializedContinueConfig | undefined,
ide: IDE,
): ConfigResult<SerializedContinueConfig> {
const configPath = getConfigJsonPath(ideType);
let config: SerializedContinueConfig = overrideConfigJson!;
@ -174,6 +175,11 @@ function loadSerializedConfig(
? [...defaultSlashCommandsVscode]
: [...defaultSlashCommandsJetBrains];
// Temporarily disabling this check until we can verify the commands are accuarate
// if (!isSupportedLanceDbCpuTarget(ide)) {
// config.disableIndexing = true;
// }
return { config, errors, configLoadInterrupted: false };
}
@ -229,6 +235,13 @@ function isContextProviderWithParams(
return (contextProvider as ContextProviderWithParams).name !== undefined;
}
const getCodebaseProvider = async (params: any) => {
const { default: CodebaseContextProvider } = await import(
"../context/providers/CodebaseContextProvider"
);
return new CodebaseContextProvider(params);
};
/** Only difference between intermediate and final configs is the `models` array */
async function intermediateToFinalConfig(
config: Config,
@ -388,9 +401,14 @@ async function intermediateToFinalConfig(
| ContextProviderWithParams
| undefined
)?.params || {};
const DEFAULT_CONTEXT_PROVIDERS = [
new FileContextProvider({}),
new CodebaseContextProvider(codebaseContextParams),
// Add codebase provider if indexing is enabled
...(!config.disableIndexing
? [await getCodebaseProvider(codebaseContextParams)]
: []),
// Add prompt files provider if enabled
...(loadPromptFiles ? [new PromptFilesContextProvider({})] : []),
];
@ -767,6 +785,7 @@ async function loadFullConfigNode(
ideSettings,
ideType,
overrideConfigJson,
ide,
);
if (!serialized || configLoadInterrupted) {

View file

@ -717,7 +717,6 @@ declare global {
type ContextProviderName =
| "diff"
| "github"
| "terminal"
| "debugger"
| "open"

View file

@ -1,10 +1,15 @@
import { execSync } from "child_process";
import os from "os";
import {
ContextProviderWithParams,
ContinueConfig,
IDE,
ILLM,
ModelDescription,
ModelRoles,
} from "../";
import { GlobalContext } from "../util/GlobalContext";
import { editConfigJson } from "../util/paths";
function stringify(obj: any, indentation?: number): string {
@ -96,3 +101,84 @@ export function getModelByRole<T extends keyof ModelRoles>(
return matchingModel;
}
/**
* This check is to determine if the user is on an unsupported CPU
* target for our Lance DB binaries.
*
* See here for details: https://github.com/continuedev/continue/issues/940
*/
export function isSupportedLanceDbCpuTarget(ide: IDE) {
const CPU_FEATURES_TO_CHECK = ["avx2", "fma"] as const;
const globalContext = new GlobalContext();
const globalContextVal = globalContext.get("isSupportedLanceDbCpuTarget");
// If we've already checked the CPU target, return the cached value
if (globalContextVal !== undefined) {
return globalContextVal;
}
const arch = os.arch();
const platform = os.platform();
// This check only applies to x64
//https://github.com/lancedb/lance/issues/2195#issuecomment-2057841311
if (arch !== "x64") {
globalContext.update("isSupportedLanceDbCpuTarget", true);
return true;
}
try {
const cpuFlags = (() => {
switch (platform) {
case "darwin":
return execSync("sysctl -n machdep.cpu.features")
.toString()
.toLowerCase();
case "linux":
return execSync("cat /proc/cpuinfo").toString().toLowerCase();
case "win32":
return execSync("wmic cpu get caption /format:list")
.toString()
.toLowerCase();
default:
return "";
}
})();
const isSupportedLanceDbCpuTarget = cpuFlags
? CPU_FEATURES_TO_CHECK.every((feature) => cpuFlags.includes(feature))
: true;
// If it's not a supported CPU target, and it's the first time we are checking,
// show a toast to inform the user that we are going to disable indexing.
if (!isSupportedLanceDbCpuTarget) {
// We offload our async toast to `showUnsupportedCpuToast` to prevent making
// our config loading async upstream of `isSupportedLanceDbCpuTarget`
void showUnsupportedCpuToast(ide);
}
globalContext.update(
"isSupportedLanceDbCpuTarget",
isSupportedLanceDbCpuTarget,
);
return isSupportedLanceDbCpuTarget;
} catch (error) {
// If we can't determine CPU features, default to true
return true;
}
}
async function showUnsupportedCpuToast(ide: IDE) {
const shouldOpenLink = await ide.showToast(
"warning",
"Codebase indexing is disabled due to CPU incompatibility",
"Learn more",
);
if (shouldOpenLink) {
void ide.openUrl("https://github.com/continuedev/continue/pull/3551");
}
}

View file

@ -11,7 +11,7 @@ class DebugLocalsProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "debugger",
displayTitle: "Debugger",
description: "Reference the contents of the local variables in the debugger",
description: "Local variables",
type: "submenu",
renderInlineAs: "",
};

View file

@ -17,7 +17,9 @@ class DiffContextProvider extends BaseContextProvider {
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const diff = await extras.ide.getDiff(this.options.includeUnstaged ?? true);
const diff = await extras.ide.getDiff(
this.options?.includeUnstaged ?? true,
);
return [
{
description: "The current git diff",

View file

@ -32,7 +32,7 @@ class DiscordContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "discord",
displayTitle: "Discord",
description: "Reference Discord messages from a channel",
description: "Select a channel",
type: "submenu",
};

View file

@ -82,6 +82,7 @@ class DocsContextProvider extends BaseContextProvider {
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const nRetrieve = this.options?.nRetrieve ?? DocsContextProvider.nRetrieve;
const useReranking = this.options?.useReranking ?? true;
// Get docs service
const docsService = DocsService.getSingleton();
@ -104,8 +105,8 @@ class DocsContextProvider extends BaseContextProvider {
// We found chunks, so check if there's a favicon for the docs page
const favicon = await docsService.getFavicon(query);
// Rerank if there's a rerankder
if (extras.reranker) {
// Rerank if there's a reranker
if (useReranking && extras.reranker) {
chunks = await this._rerankChunks(
chunks,
extras.reranker,

View file

@ -0,0 +1,75 @@
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../../index.js";
import { BaseContextProvider } from "../index.js";
import { fileURLToPath} from "node:url";
class GitCommitContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "commit",
displayTitle: "Commits",
description: "Type to search",
type: "submenu",
};
async getContextItems(query: string, extras: ContextProviderExtras): Promise<ContextItem[]> {
const lastXCommitsDepth = this.options?.LastXCommitsDepth ?? 10;
const topLevelDir = fileURLToPath((await extras.ide.getWorkspaceDirs())[0]);
try{
if(query.includes("last ")){
return [
{
name: query,
description: query,
content: (await extras.ide.subprocess(`git --no-pager log --pretty=format:"%H,%h,%an,%ae,%ad,%P,%s,%b" -p -n ${lastXCommitsDepth}`, topLevelDir))[0],
}
]
}
else{
return [
{
name: query,
description: `commit ${query}`,
content: (await extras.ide.subprocess(`git --no-pager show --pretty=format:"%H,%h,%an,%ae,%ad,%P,%s,%b" ${query}`, topLevelDir))[0],
}
]
}
}catch(err){
return [];
}
}
async loadSubmenuItems(
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
const depth = this.options?.Depth ?? 50;
const lastXCommitsDepth = this.options?.LastXCommitsDepth ?? 10;
const topLevelDir = fileURLToPath((await args.ide.getWorkspaceDirs())[0]);
try{
const [gitResult] = await args.ide.subprocess(`git --no-pager log --pretty=format:"%H%x00%s" -n ${depth}`, topLevelDir);
const recentCommits = [{ id: `last ${lastXCommitsDepth} commits`, title: `last ${lastXCommitsDepth} commits`, description: "recent commits" }];
const allCommits = gitResult
.trim()
.split('\n')
.map(line => {
const [hash, message] = line.split("\0");
return {
id: hash,
title: message,
description: hash
};
}
);
return recentCommits.concat(allCommits);
}catch(err: any){
//could be nice to toast the error eg. not a git repo or git is not installed
return [];
}
}
}
export default GitCommitContextProvider;

View file

@ -73,7 +73,15 @@ class MCPContextProvider extends BaseContextProvider {
async loadSubmenuItems(
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
return (this.options as MCPContextProviderOptions).submenuItems;
return (this.options as MCPContextProviderOptions).submenuItems.map(
(item, index) => ({
...item,
id: JSON.stringify({
mcpId: String(index),
uri: item.id,
}),
}),
);
}
}

View file

@ -38,7 +38,10 @@ class RepoMapContextProvider extends BaseContextProvider {
content: await generateRepoMap(extras.llm, extras.ide, {
dirUris: query === ENTIRE_PROJECT_ITEM.id ? undefined : [query],
outputRelativeUriPaths: true,
includeSignatures: false,
// Doesn't ALWAYS depend on indexing, so not setting dependsOnIndexing = true, just checking for it
includeSignatures: extras.config.disableIndexing
? false
: (this.options?.includeSignatures ?? false),
}),
},
];

View file

@ -1,7 +1,7 @@
import { BaseContextProvider } from "../";
import { ContextProviderName } from "../../";
import ClipboardContextProvider from "./ClipboardContextProvider";
import ClipboardContextProvider from "./ClipboardContextProvider";
import CodeContextProvider from "./CodeContextProvider";
import ContinueProxyContextProvider from "./ContinueProxyContextProvider";
import CurrentFileContextProvider from "./CurrentFileContextProvider";
@ -12,6 +12,7 @@ import DiscordContextProvider from "./DiscordContextProvider";
import DocsContextProvider from "./DocsContextProvider";
import FileTreeContextProvider from "./FileTreeContextProvider";
import FolderContextProvider from "./FolderContextProvider";
import GitCommitContextProvider from "./GitCommitContextProvider";
import GitHubIssuesContextProvider from "./GitHubIssuesContextProvider";
import GitLabMergeRequestContextProvider from "./GitLabMergeRequestContextProvider";
import GoogleContextProvider from "./GoogleContextProvider";
@ -63,6 +64,7 @@ export const Providers: (typeof BaseContextProvider)[] = [
GreptileContextProvider,
WebContextProvider,
MCPContextProvider,
GitCommitContextProvider,
ClipboardContextProvider,
];

View file

@ -2,10 +2,12 @@ import path from "path";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import ignore from "ignore";
import * as URI from "uri-js";
import { v4 as uuidv4 } from "uuid";
import { CompletionProvider } from "./autocomplete/CompletionProvider";
import { ConfigHandler } from "./config/ConfigHandler";
import { SYSTEM_PROMPT_DOT_FILE } from "./config/getSystemPromptDotFile";
import {
setupBestConfig,
setupLocalConfig,
@ -26,6 +28,7 @@ import Ollama from "./llm/llms/Ollama";
import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile";
import { callTool } from "./tools/callTool";
import { ChatDescriber } from "./util/chatDescriber";
import { clipboardCache } from "./util/clipboardCache";
import { logDevData } from "./util/devdata";
import { DevDataSqliteDb } from "./util/devdataSqlite";
import { GlobalContext } from "./util/GlobalContext";
@ -35,18 +38,15 @@ import {
getConfigJsonPath,
setupInitialDotContinueDirectory,
} from "./util/paths";
import { localPathToUri } from "./util/pathToUri";
import { Telemetry } from "./util/posthog";
import { getSymbolsForManyFiles } from "./util/treeSitter";
import { TTS } from "./util/tts";
import { type ContextItemId, type IDE, type IndexingProgressUpdate } from ".";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import * as URI from "uri-js";
import { SYSTEM_PROMPT_DOT_FILE } from "./config/getSystemPromptDotFile";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import type { IMessenger, Message } from "./protocol/messenger";
import { localPathToUri } from "./util/pathToUri";
import { clipboardCache } from "./util/clipboardCache";
export class Core {
// implements IMessenger<ToCoreProtocol, FromCoreProtocol>
@ -299,7 +299,6 @@ export class Core {
});
on("context/loadSubmenuItems", async (msg) => {
console.log("Load SUMBENU ITEMS", msg);
const config = await this.config();
if (!config) {
return [];
@ -384,9 +383,12 @@ export class Core {
});
on("clipboardCache/add", (msg) => {
console.log("ADD TO CLIPBOARD", msg);
clipboardCache.add(uuidv4(), msg.data.content);
this.messenger.send("refreshSubmenuItems", undefined);
const added = clipboardCache.add(uuidv4(), msg.data.content);
if (added) {
this.messenger.send("refreshSubmenuItems", {
providers: ["clipboard"],
});
}
});
async function* llmStreamChat(
@ -665,7 +667,6 @@ export class Core {
abortedMessageIds.delete(msg.messageId);
break;
}
console.log(diffLine);
yield { content: diffLine };
}
@ -951,7 +952,9 @@ export class Core {
}
}
this.messenger.send("refreshSubmenuItems", undefined);
this.messenger.send("refreshSubmenuItems", {
providers: "dependsOnIndexing",
});
this.indexingCancellationController = undefined;
}
@ -982,7 +985,9 @@ export class Core {
}
}
this.messenger.send("refreshSubmenuItems", undefined);
this.messenger.send("refreshSubmenuItems", {
providers: "dependsOnIndexing",
});
}
// private

View file

@ -172,7 +172,7 @@ export async function deterministicApplyLazyEdit(
oldText.slice(endIndex);
} else {
console.warn("No matching node found for lazy block");
return [];
return undefined;
}
}
}

18
core/index.d.ts vendored
View file

@ -216,6 +216,10 @@ export interface ContextSubmenuItem {
metadata?: any;
}
export interface ContextSubmenuItemWithProvider extends ContextSubmenuItem {
providerTitle: string;
}
export interface SiteIndexingConfig {
title: string;
startUrl: string;
@ -638,7 +642,7 @@ export interface IDE {
openUrl(url: string): Promise<void>;
runCommand(command: string): Promise<void>;
runCommand(command: string, options?: TerminalOptions): Promise<void>;
saveFile(fileUri: string): Promise<void>;
@ -732,7 +736,6 @@ export type StepName =
export type ContextProviderName =
| "diff"
| "github"
| "terminal"
| "debugger"
| "open"
@ -759,6 +762,9 @@ export type ContextProviderName =
| "issue"
| "repo-map"
| "url"
| "commit"
| "web"
| "discord"
| "clipboard"
| string;
@ -1074,7 +1080,6 @@ export interface ExperimentalConfig {
* This is needed to crawl a large number of documentation sites that are dynamically rendered.
*/
useChromiumForDocsCrawling?: boolean;
useTools?: boolean;
modelContextProtocolServers?: MCPOptions[];
}
@ -1238,4 +1243,9 @@ export type PackageDocsResult = {
} & (
| { error: string; details?: never }
| { details: PackageDetailsSuccess; error?: never }
);
);
export interface TerminalOptions {
reuseTerminal?: boolean,
terminalName?: string,
}

View file

@ -581,9 +581,9 @@ export default class DocsService {
void this.ide.showToast("info", `Successfully indexed ${startUrl}`);
if (this.messenger) {
this.messenger.send("refreshSubmenuItems", undefined);
}
this.messenger?.send("refreshSubmenuItems", {
providers: ["docs"],
});
} catch (e) {
console.error("Error indexing docs", e);
this.handleStatusUpdate({
@ -1109,6 +1109,8 @@ export default class DocsService {
this.abort(startUrl);
await this.deleteIndexes(startUrl);
this.deleteFromConfig(startUrl);
this.messenger?.send("refreshSubmenuItems", undefined);
this.messenger?.send("refreshSubmenuItems", {
providers: ["docs"],
});
}
}

View file

@ -35,6 +35,7 @@ import {
xWinCoderEditPrompt,
zephyrEditPrompt,
} from "./templates/edit.js";
import { PROVIDER_TOOL_SUPPORT } from "./toolSupport.js";
const PROVIDER_HANDLES_TEMPLATING: string[] = [
"lmstudio",
@ -87,11 +88,11 @@ const MODEL_SUPPORTS_IMAGES: string[] = [
];
function modelSupportsTools(modelName: string, provider: string) {
return (
provider === "anthropic" &&
modelName.includes("claude") &&
(modelName.includes("3-5") || modelName.includes("3.5"))
);
const providerSupport = PROVIDER_TOOL_SUPPORT[provider];
if (!providerSupport) {
return false;
}
return providerSupport(modelName) ?? false;
}
function modelSupportsImages(

View file

@ -71,20 +71,17 @@ function constructSystemPrompt(
provider: string,
useTools: boolean,
): string | null {
if (
useTools &&
CUSTOM_SYS_MSG_MODEL_FAMILIES.some((family) => model.includes(family))
) {
return SYSTEM_MESSAGE + "\n\n" + TOOL_USE_RULES;
} else if (
CUSTOM_SYS_MSG_MODEL_FAMILIES.some((family) => model.includes(family))
) {
return SYSTEM_MESSAGE;
} else if (useTools && modelSupportsTools(model, provider)) {
return TOOL_USE_RULES;
let systemMessage = "";
if (CUSTOM_SYS_MSG_MODEL_FAMILIES.some((family) => model.includes(family))) {
systemMessage = SYSTEM_MESSAGE;
}
return null;
if (useTools && modelSupportsTools(model, provider)) {
if (systemMessage) {
systemMessage += "\n\n";
}
systemMessage += TOOL_USE_RULES;
}
return systemMessage || null;
}
const CANCELED_TOOL_CALL_MESSAGE =
@ -96,18 +93,21 @@ export function constructMessages(
provider: string,
useTools: boolean,
): ChatMessage[] {
const filteredHistory = history.filter(
(item) => item.message.role !== "system",
);
const msgs: ChatMessage[] = [];
const systemMessage = constructSystemPrompt(model, provider, useTools);
if (systemMessage) {
msgs.push({
role: "system" as const,
role: "system",
content: systemMessage,
});
}
for (let i = 0; i < history.length; i++) {
const historyItem = history[i];
for (let i = 0; i < filteredHistory.length; i++) {
const historyItem = filteredHistory[i];
if (historyItem.message.role === "user") {
// Gather context items for user messages

View file

@ -448,11 +448,7 @@ function compileChatMessages(
functionTokens + maxTokens + TOKEN_BUFFER_FOR_SAFETY,
);
if (
systemMessage &&
history.length >= 2 &&
history[history.length - 2].role === "system"
) {
if (history.length >= 2 && history[history.length - 2].role === "system") {
const movedSystemMessage = history.splice(-2, 1)[0];
history.unshift(movedSystemMessage);
}

View file

@ -55,6 +55,7 @@ import {
toCompleteBody,
toFimBody,
} from "./openaiTypeConverters.js";
import { isOllamaInstalled } from "../util/ollamaHelper.js";
export abstract class BaseLLM implements ILLM {
static providerName: string;
@ -414,9 +415,11 @@ export abstract class BaseLLM implements ILLM {
e.code === "ECONNREFUSED" &&
e.message.includes("http://127.0.0.1:11434")
) {
throw new Error(
"Failed to connect to local Ollama instance, please ensure Ollama is both installed and running. You can download Ollama from https://ollama.ai.",
);
const message = (await isOllamaInstalled()) ?
"Unable to connect to local Ollama instance. Ollama may not be running." :
"Unable to connect to local Ollama instance. Ollama may not be installed or may not running."
;
throw new Error(message);
}
}
throw new Error(e.message);

View file

@ -1,10 +1,19 @@
import { ChatMessage, CompletionOptions } from "../../index.js";
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
import { BaseLLM } from "../index.js";
type MockMessage = ChatMessage | "REPEAT_LAST_MSG";
class MockLLM extends BaseLLM {
public completion: string = "Test Completion";
public chatStreams: MockMessage[][] | undefined;
static providerName = "mock";
constructor(options: LLMOptions) {
super(options);
this.templateMessages = undefined;
this.chatStreams = options.requestOptions?.extraBodyProperties?.chatStream;
}
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
@ -18,6 +27,29 @@ class MockLLM extends BaseLLM {
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
if (this.chatStreams) {
const chatStream =
this.chatStreams?.[
messages.filter((m) => m.role === "user" || m.role === "tool")
.length - 1
];
if (chatStream) {
for (const message of chatStream) {
switch (message) {
case "REPEAT_LAST_MSG":
yield {
role: "assistant",
content: messages[messages.length - 1].content,
};
break;
default:
yield message;
}
}
}
return;
}
for (const char of this.completion) {
yield {
role: "assistant",

View file

@ -1,12 +1,24 @@
import { JSONSchema7Object, JSONSchema7Type } from "json-schema";
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";
type OllamaChatMessage = ChatMessage & { images?: string[] };
type OllamaChatMessage = {
role: "tool" | "user" | "assistant" | "system";
content: string;
images?: string[] | null;
tool_calls?: {
function: {
name: string;
arguments: Record<string, JSONSchema7Type>;
};
}[];
};
// See https://github.com/ollama/ollama/blob/main/docs/modelfile.md for details on each parameter
interface ModelFileParams {
interface OllamaModelFileParams {
mirostat?: number;
mirostat_eta?: number;
mirostat_tau?: number;
@ -21,23 +33,35 @@ interface ModelFileParams {
top_k?: number;
top_p?: number;
min_p?: number;
// deprecated?
// deprecated or not directly supported here:
num_thread?: number;
use_mmap?: boolean;
num_gqa?: number;
num_gpu?: number;
num_keep?: number;
typical_p?: number;
presence_penalty?: number;
frequency_penalty?: number;
penalize_newline?: boolean;
numa?: boolean;
num_batch?: number;
main_gpu?: number;
low_vram?: boolean;
vocab_only?: boolean;
use_mlock?: boolean;
}
// See https://github.com/ollama/ollama/blob/main/docs/api.md
interface BaseOptions {
interface OllamaBaseOptions {
model: string; // the model name
options?: ModelFileParams; // additional model parameters listed in the documentation for the Modelfile such as temperature
options?: OllamaModelFileParams; // additional model parameters listed in the documentation for the Modelfile such as temperature
format?: "json"; // the format to return a response in. Currently, the only accepted value is json
stream?: boolean; // if false the response will be returned as a single response object, rather than a stream of objects
keep_alive?: number; // controls how long the model will stay loaded into memory following the request (default: 5m)
}
interface GenerateOptions extends BaseOptions {
interface OllamaRawOptions extends OllamaBaseOptions {
prompt: string; // the prompt to generate a response for
suffix?: string; // the text after the model response
images?: string[]; // a list of base64-encoded images (for multimodal models such as llava)
@ -47,12 +71,58 @@ interface GenerateOptions extends BaseOptions {
raw?: boolean; // if true no formatting will be applied to the prompt. You may choose to use the raw parameter if you are specifying a full templated prompt in your request to the API
}
interface ChatOptions extends BaseOptions {
interface OllamaChatOptions extends OllamaBaseOptions {
messages: OllamaChatMessage[]; // the messages of the chat, this can be used to keep a chat memory
tools?: OllamaTool[]; // the tools of the chat, this can be used to keep a tool memory
// Not supported yet - tools: tools for the model to use if supported. Requires stream to be set to false
// And correspondingly, tool calls in OllamaChatMessage
}
type OllamaBaseResponse = {
model: string;
created_at: string;
} & (
| {
done: false;
}
| {
done: true;
done_reason: string;
total_duration: number; // Time spent generating the response in nanoseconds
load_duration: number; // Time spent loading the model in nanoseconds
prompt_eval_count: number; // Number of tokens in the prompt
prompt_eval_duration: number; // Time spent evaluating the prompt in nanoseconds
eval_count: number; // Number of tokens in the response
eval_duration: number; // Time spent generating the response in nanoseconds
context: number[]; // An encoding of the conversation used in this response; can be sent in the next request to keep conversational memory
}
);
type OllamaErrorResponse = {
error: string;
};
type OllamaRawResponse =
| OllamaErrorResponse
| (OllamaBaseResponse & {
response: string; // the generated response
});
type OllamaChatResponse =
| OllamaErrorResponse
| (OllamaBaseResponse & {
message: OllamaChatMessage;
});
interface OllamaTool {
type: "function";
function: {
name: string;
description?: string;
parameters?: JSONSchema7Object;
};
}
class Ollama extends BaseLLM {
static providerName = "ollama";
static defaultOptions: Partial<LLMOptions> = {
@ -130,56 +200,59 @@ class Ollama extends BaseLLM {
});
}
// Map of "continue model name" to Ollama actual model name
private modelMap: Record<string, string> = {
"mistral-7b": "mistral:7b",
"mixtral-8x7b": "mixtral:8x7b",
"llama2-7b": "llama2:7b",
"llama2-13b": "llama2:13b",
"codellama-7b": "codellama:7b",
"codellama-13b": "codellama:13b",
"codellama-34b": "codellama:34b",
"codellama-70b": "codellama:70b",
"llama3-8b": "llama3:8b",
"llama3-70b": "llama3:70b",
"llama3.1-8b": "llama3.1:8b",
"llama3.1-70b": "llama3.1:70b",
"llama3.1-405b": "llama3.1:405b",
"llama3.2-1b": "llama3.2:1b",
"llama3.2-3b": "llama3.2:3b",
"llama3.2-11b": "llama3.2:11b",
"llama3.2-90b": "llama3.2:90b",
"phi-2": "phi:2.7b",
"phind-codellama-34b": "phind-codellama:34b-v2",
"qwen2.5-coder-0.5b": "qwen2.5-coder:0.5b",
"qwen2.5-coder-1.5b": "qwen2.5-coder:1.5b",
"qwen2.5-coder-3b": "qwen2.5-coder:3b",
"qwen2.5-coder-7b": "qwen2.5-coder:7b",
"qwen2.5-coder-14b": "qwen2.5-coder:14b",
"qwen2.5-coder-32b": "qwen2.5-coder:32b",
"wizardcoder-7b": "wizardcoder:7b-python",
"wizardcoder-13b": "wizardcoder:13b-python",
"wizardcoder-34b": "wizardcoder:34b-python",
"zephyr-7b": "zephyr:7b",
"codeup-13b": "codeup:13b",
"deepseek-1b": "deepseek-coder:1.3b",
"deepseek-7b": "deepseek-coder:6.7b",
"deepseek-33b": "deepseek-coder:33b",
"neural-chat-7b": "neural-chat:7b-v3.3",
"starcoder-1b": "starcoder:1b",
"starcoder-3b": "starcoder:3b",
"starcoder2-3b": "starcoder2:3b",
"stable-code-3b": "stable-code:3b",
"granite-code-3b": "granite-code:3b",
"granite-code-8b": "granite-code:8b",
"granite-code-20b": "granite-code:20b",
"granite-code-34b": "granite-code:34b",
};
private _getModel() {
return (
{
"mistral-7b": "mistral:7b",
"mixtral-8x7b": "mixtral:8x7b",
"llama2-7b": "llama2:7b",
"llama2-13b": "llama2:13b",
"codellama-7b": "codellama:7b",
"codellama-13b": "codellama:13b",
"codellama-34b": "codellama:34b",
"codellama-70b": "codellama:70b",
"llama3-8b": "llama3:8b",
"llama3-70b": "llama3:70b",
"llama3.1-8b": "llama3.1:8b",
"llama3.1-70b": "llama3.1:70b",
"llama3.1-405b": "llama3.1:405b",
"llama3.2-1b": "llama3.2:1b",
"llama3.2-3b": "llama3.2:3b",
"llama3.2-11b": "llama3.2:11b",
"llama3.2-90b": "llama3.2:90b",
"phi-2": "phi:2.7b",
"phind-codellama-34b": "phind-codellama:34b-v2",
"qwen2.5-coder-0.5b": "qwen2.5-coder:0.5b",
"qwen2.5-coder-1.5b": "qwen2.5-coder:1.5b",
"qwen2.5-coder-3b": "qwen2.5-coder:3b",
"qwen2.5-coder-7b": "qwen2.5-coder:7b",
"qwen2.5-coder-14b": "qwen2.5-coder:14b",
"qwen2.5-coder-32b": "qwen2.5-coder:32b",
"wizardcoder-7b": "wizardcoder:7b-python",
"wizardcoder-13b": "wizardcoder:13b-python",
"wizardcoder-34b": "wizardcoder:34b-python",
"zephyr-7b": "zephyr:7b",
"codeup-13b": "codeup:13b",
"deepseek-1b": "deepseek-coder:1.3b",
"deepseek-7b": "deepseek-coder:6.7b",
"deepseek-33b": "deepseek-coder:33b",
"neural-chat-7b": "neural-chat:7b-v3.3",
"starcoder-1b": "starcoder:1b",
"starcoder-3b": "starcoder:3b",
"starcoder2-3b": "starcoder2:3b",
"stable-code-3b": "stable-code:3b",
"granite-code-3b": "granite-code:3b",
"granite-code-8b": "granite-code:8b",
"granite-code-20b": "granite-code:20b",
"granite-code-34b": "granite-code:34b",
}[this.model] ?? this.model
);
return this.modelMap[this.model] ?? this.model;
}
private _getModelFileParams(options: CompletionOptions): ModelFileParams {
private _getModelFileParams(
options: CompletionOptions,
): OllamaModelFileParams {
return {
temperature: options.temperature,
top_p: options.topP,
@ -194,50 +267,38 @@ class Ollama extends BaseLLM {
};
}
private _convertMessage(message: ChatMessage) {
if (message.role === "tool") {
return null;
}
private _convertToOllamaMessage(message: ChatMessage): OllamaChatMessage {
const ollamaMessage: OllamaChatMessage = {
role: message.role,
content: "",
};
if (typeof message.content === "string") {
return message;
}
const images: string[] = [];
message.content.forEach((part) => {
if (part.type === "imageUrl" && part.imageUrl) {
const image = part.imageUrl?.url.split(",").at(-1);
if (image) {
images.push(image);
ollamaMessage.content = message.content;
} else {
ollamaMessage.content = renderChatMessage(message);
const images: string[] = [];
message.content.forEach((part) => {
if (part.type === "imageUrl" && part.imageUrl) {
const image = part.imageUrl?.url.split(",").at(-1);
if (image) {
images.push(image);
}
}
});
if (images.length > 0) {
ollamaMessage.images = images;
}
});
}
return {
role: message.role,
content: renderChatMessage(message),
images,
};
}
private _getChatOptions(
options: CompletionOptions,
messages: ChatMessage[],
): ChatOptions {
return {
model: this._getModel(),
messages: messages.map(this._convertMessage).filter(Boolean) as any,
options: this._getModelFileParams(options),
keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes
stream: options.stream,
// format: options.format, // Not currently in base completion options
};
return ollamaMessage;
}
private _getGenerateOptions(
options: CompletionOptions,
prompt: string,
suffix?: string,
): GenerateOptions {
): OllamaRawOptions {
return {
model: this._getModel(),
prompt,
@ -286,12 +347,11 @@ class Ollama extends BaseLLM {
const chunk = chunks[i];
if (chunk.trim() !== "") {
try {
const j = JSON.parse(chunk);
if ("response" in j) {
yield j.response;
} else if ("error" in j) {
const j = JSON.parse(chunk) as OllamaRawResponse;
if ("error" in j) {
throw new Error(j.error);
}
yield j.response;
} catch (e) {
throw new Error(`Error parsing Ollama response: ${e} ${chunk}`);
}
@ -305,39 +365,94 @@ class Ollama extends BaseLLM {
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const ollamaMessages = messages.map(this._convertToOllamaMessage);
const chatOptions: OllamaChatOptions = {
model: this._getModel(),
messages: ollamaMessages,
options: this._getModelFileParams(options),
keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes
stream: options.stream,
// format: options.format, // Not currently in base completion options
};
// This logic is because tools can ONLY be included with user message for ollama
if (options.tools?.length && ollamaMessages.at(-1)?.role === "user") {
chatOptions.tools = options.tools.map((tool) => ({
type: "function",
function: {
name: tool.function.name,
description: tool.function.description,
parameters: tool.function.parameters,
},
}));
chatOptions.stream = false; // Cannot set stream = true for tools calls
}
const response = await this.fetch(this.getEndpoint("api/chat"), {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify(this._getChatOptions(options, messages)),
body: JSON.stringify(chatOptions),
signal,
});
let buffer = "";
for await (const value of streamResponse(response)) {
// Append the received chunk to the buffer
buffer += value;
// Split the buffer into individual JSON chunks
const chunks = buffer.split("\n");
buffer = chunks.pop() ?? "";
function convertChatMessage(res: OllamaChatResponse): ChatMessage {
if ("error" in res) {
throw new Error(res.error);
}
if (res.message.role === "tool") {
throw new Error(
"Unexpected message received from ollama with role = tool",
);
}
if (res.message.role === "assistant") {
const chatMessage: ChatMessage = {
role: "assistant",
content: res.message.content,
};
if (res.message.tool_calls) {
// Continue handles the response as a tool call delta but
// But ollama returns the full object in one response with no streaming
chatMessage.toolCalls = res.message.tool_calls.map((tc) => ({
type: "function",
function: {
name: tc.function.name,
arguments: JSON.stringify(tc.function.arguments),
},
}));
}
return chatMessage;
} else {
return {
role: res.message.role,
content: res.message.content,
};
}
}
for (let i = 0; i < chunks.length; i++) {
const chunk = chunks[i];
if (chunk.trim() !== "") {
try {
const j = JSON.parse(chunk);
if (j.message?.content) {
yield {
role: "assistant",
content: j.message.content,
};
} else if (j.error) {
throw new Error(j.error);
if (chatOptions.stream === false) {
const json = (await response.json()) as OllamaChatResponse;
yield convertChatMessage(json);
} else {
let buffer = "";
for await (const value of streamResponse(response)) {
// Append the received chunk to the buffer
buffer += value;
// Split the buffer into individual JSON chunks
const chunks = buffer.split("\n");
buffer = chunks.pop() ?? "";
for (let i = 0; i < chunks.length; i++) {
const chunk = chunks[i];
if (chunk.trim() !== "") {
try {
const j = JSON.parse(chunk) as OllamaChatResponse;
const chatMessage = convertChatMessage(j);
yield chatMessage;
} catch (e) {
throw new Error(`Error parsing Ollama response: ${e} ${chunk}`);
}
} catch (e) {
throw new Error(`Error parsing Ollama response: ${e} ${chunk}`);
}
}
}

View file

@ -253,6 +253,13 @@ class OpenAI extends BaseLLM {
body.max_completion_tokens = undefined;
}
if (body.tools?.length) {
// To ensure schema adherence: https://platform.openai.com/docs/guides/function-calling#parallel-function-calling-and-structured-outputs
// In practice, setting this to true and asking for multiple tool calls
// leads to "arguments" being something like '{"file": "test.ts"}{"file": "test.js"}'
body.parallel_tool_calls = false;
}
return body;
}
@ -309,14 +316,6 @@ class OpenAI extends BaseLLM {
const body = this._convertArgs(options, messages);
// Empty messages cause an error in LM Studio
body.messages = body.messages.map((m: any) => ({
...m,
content: m.content === "" ? " " : m.content,
// We call it toolCalls, they call it tool_calls
tool_calls: m.toolCalls,
tool_call_id: m.toolCallId,
})) as any;
const response = await this.fetch(this._getEndpoint("chat/completions"), {
method: "POST",
headers: this._getHeaders(),

View file

@ -1,3 +1,4 @@
import { FimCreateParamsStreaming } from "@continuedev/openai-adapters/dist/apis/base";
import {
ChatCompletion,
ChatCompletionChunk,
@ -6,7 +7,6 @@ import {
CompletionCreateParams,
} from "openai/resources/index";
import { FimCreateParamsStreaming } from "@continuedev/openai-adapters/dist/apis/base";
import { ChatMessage, CompletionOptions } from "..";
export function toChatMessage(
@ -19,54 +19,56 @@ export function toChatMessage(
tool_call_id: message.toolCallId,
};
}
if (typeof message.content === "string") {
if (message.role === "system") {
return {
role: message.role,
role: "system",
content: message.content,
};
} else if (!message.content.some((item) => item.type !== "text")) {
// If no multi-media is in the message, just send as text
// for compatibility with OpenAI-"compatible" servers
// that don't support multi-media format
return {
...message,
content: message.content.map((item) => item.text).join(""),
};
}
const parts = message.content.map((part) => {
const msg: any = {
type: part.type,
text: part.text,
};
if (part.type === "imageUrl") {
msg.image_url = { ...part.imageUrl, detail: "auto" };
msg.type = "image_url";
}
return msg;
});
return {
...message,
content: parts,
let msg: ChatCompletionMessageParam = {
role: message.role,
content:
typeof message.content === "string"
? message.content || " " // LM Studio (and other providers) don't accept empty content
: !message.content.some((item) => item.type !== "text")
? // If no multi-media is in the message, just send as text
// for compatibility with OpenAI-"compatible" servers
// that don't support multi-media format
message.content.map((item) => item.text).join("") || " "
: message.content.map((part) => {
const msg: any = {
type: part.type,
text: part.text,
};
if (part.type === "imageUrl") {
msg.image_url = { ...part.imageUrl, detail: "auto" };
msg.type = "image_url";
}
return msg;
}),
};
if (
msg.role === "assistant" &&
message.role === "assistant" &&
message.toolCalls
) {
msg.tool_calls = message.toolCalls.map((toolCall) => ({
id: toolCall.id!,
type: toolCall.type!,
function: {
name: toolCall.function?.name!,
arguments: toolCall.function?.arguments!,
},
}));
}
return msg;
}
export function toChatBody(
messages: ChatMessage[],
options: CompletionOptions,
): ChatCompletionCreateParams {
const tools = options.tools?.map((tool) => ({
type: tool.type,
function: {
name: tool.function.name,
description: tool.function.description,
parameters: tool.function.parameters,
strict: tool.function.strict,
},
}));
const params: ChatCompletionCreateParams = {
messages: messages.map(toChatMessage),
model: options.model,
@ -79,9 +81,19 @@ export function toChatBody(
stop: options.stop,
prediction: options.prediction,
};
if (tools?.length) {
params.tools = tools;
if (options.tools?.length) {
params.tools = options.tools.map((tool) => ({
type: tool.type,
function: {
name: tool.function.name,
description: tool.function.description,
parameters: tool.function.parameters,
strict: tool.function.strict,
},
}));
}
return params;
}

52
core/llm/toolSupport.ts Normal file
View file

@ -0,0 +1,52 @@
export const PROVIDER_TOOL_SUPPORT: Record<
string,
(model: string) => boolean | undefined
> = {
anthropic: (model) => {
if (
["claude-3-5", "claude-3.5"].some((part) =>
model.toLowerCase().startsWith(part),
)
) {
return true;
}
},
openai: (model) => {
// https://platform.openai.com/docs/guides/function-calling#models-supporting-function-calling
if (model.toLowerCase().startsWith("gpt-4")) {
return true;
}
},
// https://ollama.com/search?c=tools
ollama: (model) => {
if (
["vision", "math", "guard", "mistrallite", "mistral-openorca"].some(
(part) => model.toLowerCase().includes(part),
)
) {
return false;
}
if (
[
"llama3.3",
"qwq",
"llama3.2",
"llama3.1",
"qwen2",
"mixtral",
"command-r",
"smollm2",
"hermes3",
"athene-v2",
"nemotron",
"llama3-groq",
"granite3",
"aya-expanse",
"firefunction-v2",
"mistral",
].some((part) => model.toLowerCase().startsWith(part))
) {
return true;
}
},
};

View file

@ -83,6 +83,7 @@
"@types/jest": "^29.5.12",
"@types/jquery": "^3.5.29",
"@types/jsdom": "^21.1.6",
"@types/json-schema": "^7.0.15",
"@types/mozilla-readability": "^0.2.1",
"@types/mustache": "^4.2.5",
"@types/node-fetch": "^2.6.11",
@ -5311,6 +5312,12 @@
"parse5": "^7.0.0"
}
},
"node_modules/@types/json-schema": {
"version": "7.0.15",
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
"integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",
"dev": true
},
"node_modules/@types/json5": {
"version": "0.0.29",
"resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz",

View file

@ -22,6 +22,7 @@
"@types/jest": "^29.5.12",
"@types/jquery": "^3.5.29",
"@types/jsdom": "^21.1.6",
"@types/json-schema": "^7.0.15",
"@types/mozilla-readability": "^0.2.1",
"@types/mustache": "^4.2.5",
"@types/node-fetch": "^2.6.11",

View file

@ -14,6 +14,7 @@ import type {
Range,
RangeInFile,
Thread,
TerminalOptions
} from "../";
export interface GetGhTokenArgs {
@ -28,7 +29,7 @@ export type ToIdeFromWebviewOrCoreProtocol = {
showVirtualFile: [{ name: string; content: string }, void];
openFile: [{ path: string }, void];
openUrl: [string, void];
runCommand: [{ command: string }, void];
runCommand: [{ command: string, options?: TerminalOptions }, void];
getSearchResults: [{ query: string }, string];
subprocess: [{ command: string; cwd?: string }, [string, string]];
saveFile: [{ filepath: string }, void];

View file

@ -62,10 +62,6 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
setInactive: [undefined, void];
submitMessage: [{ message: any }, void]; // any -> JSONContent from TipTap
updateSubmenuItems: [
{ provider: string; submenuItems: ContextSubmenuItem[] },
void,
];
newSessionWithPrompt: [{ prompt: string }, void];
userInput: [{ input: string }, void];
focusContinueInput: [undefined, void];

View file

@ -13,6 +13,7 @@ import type {
Problem,
Range,
RangeInFile,
TerminalOptions,
Thread,
} from "../..";
@ -151,8 +152,8 @@ export class MessageIde implements IDE {
await this.request("openUrl", url);
}
async runCommand(command: string): Promise<void> {
await this.request("runCommand", { command });
async runCommand(command: string, options?: TerminalOptions): Promise<void> {
await this.request("runCommand", { command, options });
}
async saveFile(fileUri: string): Promise<void> {

View file

@ -62,6 +62,8 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
];
// Message types to pass through from core to webview
// Note: If updating these values, make a corresponding update in
// extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt
export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
[
"configUpdate",

View file

@ -4,6 +4,8 @@ import { ConfigValidationError } from "../config/validation.js";
import type {
BrowserSerializedContinueConfig,
ContextItemWithId,
ContextProviderName,
ContextSubmenuItem,
IndexingProgressUpdate,
IndexingStatus,
PackageDocsResult,
@ -21,7 +23,12 @@ export type ToWebviewFromIdeOrCoreProtocol = {
getDefaultModelTitle: [undefined, string];
indexProgress: [IndexingProgressUpdate, void]; // Codebase
"indexing/statusUpdate": [IndexingStatus, void]; // Docs, etc.
refreshSubmenuItems: [undefined, void];
refreshSubmenuItems: [
{
providers: "all" | "dependsOnIndexing" | ContextProviderName[];
},
void,
];
isContinueInputFocused: [undefined, boolean];
addContextItem: [
{

View file

@ -15,6 +15,7 @@ export type GlobalContextType = {
hasDismissedConfigTsNoticeJetBrains: boolean;
hasAlreadyCreatedAPromptFile: boolean;
showConfigUpdateToast: boolean;
isSupportedLanceDbCpuTarget: boolean;
};
/**

View file

@ -8,10 +8,28 @@ class ClipboardCache {
this.order = [];
}
add(id: string, content: string): void {
/*
Returns true if added, false if not.
*/
add(id: string, content: string): boolean {
if (!content) {
return;
return false;
}
// Check if the content already exists in the cache
for (const [existingId, existingContent] of this.cache.entries()) {
if (existingContent === content) {
// Remove the existing entry with the same content
this.cache.delete(existingId);
const index = this.order.indexOf(existingId);
if (index > -1) {
this.order.splice(index, 1);
}
return false;
}
}
// Remove the oldest entry if the cache exceeds the maximum size
if (this.order.length >= this.maxSize) {
const oldest = this.order.pop();
if (oldest) {
@ -19,14 +37,13 @@ class ClipboardCache {
}
}
// Add the new entry to the cache and update the order
this.cache.set(id, content);
this.order.unshift(id);
return true;
}
getNItems(count: number): {
id: string;
content: string;
}[] {
getNItems(count: number): { id: string; content: string }[] {
return this.order.slice(0, count).map((id) => ({
id,
content: this.cache.get(id) || "",

View file

@ -13,6 +13,7 @@ import {
Problem,
Range,
RangeInFile,
TerminalOptions,
Thread,
ToastType,
} from "../index.js";
@ -190,7 +191,7 @@ class FileSystemIde implements IDE {
return Promise.resolve();
}
runCommand(command: string): Promise<void> {
runCommand(command: string, options?: TerminalOptions): Promise<void> {
return Promise.resolve();
}

41
core/util/ollamaHelper.ts Normal file
View file

@ -0,0 +1,41 @@
import path from "node:path";
import { IDE } from "..";
import { exec } from "node:child_process";
export async function isOllamaInstalled(): Promise<boolean> {
return new Promise((resolve, _reject) => {
const command = process.platform === "win32" ? "where.exe ollama" : "which ollama";
exec(command, (error, _stdout, _stderr) => {
resolve(!error);
});
});
}
export async function startLocalOllama(ide: IDE): Promise<void> {
let startCommand: string | undefined;
switch (process.platform) {
case "darwin"://MacOS
startCommand = "open -a Ollama.app\n";
break;
case "win32"://Windows
startCommand = `& "ollama app.exe"\n`;
break;
default: //Linux...
const start_script_path = path.resolve(__dirname, './start_ollama.sh');
if (await ide.fileExists(`file:/${start_script_path}`)) {
startCommand = `set -e && chmod +x ${start_script_path} && ${start_script_path}\n`;
console.log(`Ollama Linux startup script at : ${start_script_path}`);
} else {
ide.showToast("error", `Cannot start Ollama: could not find ${start_script_path}!`)
}
}
if (startCommand) {
return ide.runCommand(startCommand, {
reuseTerminal: true,
terminalName: "Start Ollama"
});
}
}

View file

@ -334,15 +334,6 @@ export function getLogsDirPath(): string {
return logsPath;
}
export function getLogFilePath(): string {
const logFilePath = path.join(getContinueGlobalPath(), "continue.log");
// Make sure the file/directory exist
if (!fs.existsSync(logFilePath)) {
fs.writeFileSync(logFilePath, "");
}
return logFilePath;
}
export function getCoreLogsPath(): string {
return path.join(getLogsDirPath(), "core.log");
}

View file

@ -2,15 +2,17 @@ import os from "node:os";
import { TeamAnalytics } from "../control-plane/TeamAnalytics.js";
import { IdeInfo } from "../index.js";
import type { PostHog as PostHogType } from "posthog-node";
export enum PosthogFeatureFlag {
AutocompleteTimeout = "autocomplete-timeout",
RecentlyVisitedRangesNumSurroundingLines = "recently-visited-ranges-num-surrounding-lines",
}
export const EXPERIMENTS: {
[key in PosthogFeatureFlag]: {
[key: string]: { value: number };
[key: string]: { value: any };
};
} = {
[PosthogFeatureFlag.AutocompleteTimeout]: {
@ -19,6 +21,13 @@ export const EXPERIMENTS: {
"350": { value: 350 },
"450": { value: 450 },
},
[PosthogFeatureFlag.RecentlyVisitedRangesNumSurroundingLines]: {
control: { value: null },
"5": { value: 5 },
"10": { value: 10 },
"15": { value: 15 },
"20": { value: 20 },
},
};
export class Telemetry {
@ -97,12 +106,21 @@ export class Telemetry {
}
}
private static featureValueCache: Record<string, any> = {};
static async getFeatureFlag(flag: PosthogFeatureFlag) {
return Telemetry.client?.getFeatureFlag(flag, Telemetry.uniqueId);
const value = Telemetry.client?.getFeatureFlag(flag, Telemetry.uniqueId);
Telemetry.featureValueCache[flag] = value;
return value;
}
static async getValueForFeatureFlag(flag: PosthogFeatureFlag) {
try {
if (Telemetry.featureValueCache[flag]) {
return Telemetry.featureValueCache[flag];
}
const userGroup = await Telemetry.getFeatureFlag(flag);
if (typeof userGroup === "string") {
return EXPERIMENTS[flag][userGroup].value;

84
core/util/start_ollama.sh Executable file
View file

@ -0,0 +1,84 @@
#!/bin/bash
# Timeout for waiting for Ollama to start (in seconds)
readonly TIMEOUT=60
readonly OLLAMA_API_URL="http://localhost:11434/api/version"
# Check if a command exists
command_exists() {
command -v "$1" >/dev/null 2>&1
}
# Check if Ollama is already running
ollama_is_running() {
VERSION=$(curl -s --fail --max-time 1 "$OLLAMA_API_URL" | grep '"version"' | awk -F: '{ print $2 }' | sed -e 's/.*"\([^"]*\)".*/\1/')
test -n "$VERSION"
}
# Determine if running in a container environment
in_container() {
[[ -f /.dockerenv || -f /run/.containerenv ]]
}
# Start Ollama service or background process
start_ollama() {
local start_method="${1:-background}"
echo "Starting Ollama ($start_method)..."
if [[ "$start_method" == "service" ]]; then
if in_container; then
service ollama start || return $?
else
sudo systemctl start ollama || return $?
fi
else
nohup ollama serve >/dev/null 2>&1 &
fi
# Wait for Ollama to start. TIMEOUT * 4, since we sleep 1/4 sec on each iteration
for _ in $(seq 1 $((TIMEOUT * 4))); do
if ollama_is_running; then
echo -e "\nOllama started successfully."
return 0
fi
(( _ % 2 == 0 )) && printf "."
sleep 0.25
done
echo -e "\nTimeout: Failed to start Ollama."
return 1
}
# Main script execution
main() {
# Early exit if Ollama is already running
if ollama_is_running; then
echo "Ollama is already running."
return 0
fi
# Try starting via service if possible
if in_container; then
if service --status-all 2>&1 | grep -qw 'ollama'; then
start_ollama service || return $?
return 0
fi
elif command_exists systemctl; then
if systemctl list-unit-files ollama.service >/dev/null 2>&1; then
start_ollama service || return $?
return 0
fi
fi
# Fallback to background process
if command_exists ollama; then
start_ollama || return 1
else
echo "Error: Ollama is not installed or not in the PATH." >&2
return 1
fi
}
# Run the main function and exit with its status
main
exit $?

View file

@ -5,6 +5,10 @@ keywords: [model, autocomplete]
sidebar_position: 2
---
:::info
This page recommends models and providers for Autocomplete. Read more about how to set up your `config.json` [here](../reference.md).
:::
## Best overall experience
For the best Autocomplete experience, we recommend using Codestral through the [Mistral API](https://console.mistral.ai/). This model offers high-quality completions with an excellent understanding of code context:
@ -26,7 +30,7 @@ The API keys for Codestral and the general Mistral APIs are different. If you ar
## Local, offline / self-hosted experience
For those preferring local execution or self-hosting,`Qwen2.5-Coder 1.5B` offers a good balance of performance and quality for most users:
For those preferring local execution or self-hosting,`Qwen2.5-Coder 1.5B` offers a good balance of performance and quality for most users (e.g. using [Ollama](../customize/model-providers/top-level/ollama.md) or [LM Studio](../customize/model-providers/more/lmstudio.md)).
```json title="config.json""
{
@ -45,7 +49,20 @@ Have more compute? Use `qwen2.5-coder:7b-base` for potentially higher-quality su
For LM Studio users, navigate to the "My Models" section, find your desired model, and copy the path (e.g., `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF/qwen2.5-coder-1.5b-instruct-q4_k_m.gguf`). Use this path as the `model` value in your configuration.
:::
### Using a remote instance
When using a remote instance you need to set the `"apiBase"` value in the configuration:
```json title="config.json""
{
"tabAutocompleteModel": {
"title": "Qwen2.5-Coder 1.5B",
"model": "qwen2.5-coder:1.5b-base",
"provider": "ollama"
"apiBase": "http://<my endpoint>:11434"
}
}
```
## Other experiences
There are many more models and providers you can use with Autocomplete. Check them out [here](../customize/model-types/autocomplete.md).
There are many more models and providers you can use with Autocomplete. Check them out [here](../customize/model-types/autocomplete.md). You can also see more examples of Autocomplete configuration [here](../customize/deep-dives/autocomplete.md)

View file

@ -15,7 +15,7 @@ The highlighted code you’ve selected by pressing <kbd>cmd/ctrl</kbd> + <kbd>L<
## Active file
You can include the currently open file as context by pressing <kbd>cmd</kbd> + <kbd>opt</kbd> + <kbd>enter</kbd> (Mac) or <kbd>alt</kbd> + <kbd>enter</kbd> (Windows) when you send your request at Chat window(Prompt can't be empty).
You can include the currently open file as context by pressing <kbd>opt</kbd> + <kbd>enter</kbd> (Mac) or <kbd>alt</kbd> + <kbd>enter</kbd> (Windows) when you send your request at Chat window(Prompt can't be empty).
## Specific file

View file

@ -33,7 +33,7 @@ Our current top recommendation is Claude Sonnet 3.5 from [Anthropic](../customiz
### Llama 3.1 405B from Meta
If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your best option right now. You will need to decide if you use it through a SaaS model provider (e.g. [Together](../customize/model-providers/more/together.md) or [Novita AI](../customize/model-providers/more/novita.md) or [Groq](../customize/model-providers/more/groq.md)) or self-host it (e.g. using [vLLM](../customize/model-providers//more/vllm.md) or [Ollama](../customize/model-providers/top-level/ollama.md)).
If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your best option right now. You will need to decide if you use it through a SaaS model provider (e.g. [Together](../customize/model-providers/more/together.md) or [Groq](../customize/model-providers/more/groq.md)) or self-host it (e.g. using [vLLM](../customize/model-providers//more/vllm.md) or [Ollama](../customize/model-providers/top-level/ollama.md)).
<Tabs groupId="providers">
<TabItem value="Together">
@ -48,18 +48,6 @@ If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your
]
```
</TabItem>
<TabItem value="Novita">
```json title="config.json"
"models": [
{
"title": "Llama 3.1 405B",
"provider": "novita",
"model": "meta-llama/llama-3.1-405b-instruct",
"apiKey": "[NOVITA_API_KEY]"
}
]
```
</TabItem>
<TabItem value="Groq">
```json title="config.json"
"models": [
@ -94,18 +82,6 @@ If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your
]
```
</TabItem>
<TabItem value="Nebius">
```json title="config.json"
"models": [
{
"title": "Llama 3.1 405B",
"provider": "nebius",
"model": "llama3.1-405b",
"apiKey": "[NEBIUS_API_KEY]"
}
]
```
</TabItem>
</Tabs>
### GPT-4o from OpenAI

View file

@ -123,11 +123,16 @@ Reference the contents of all of your open files. Set `onlyPinned` to `true` to
Reference relevant pages from across the web, automatically determined from your input.
Optionally, set "n" to limit the number of results returned (default 6).
```json title="config.json"
{
"contextProviders": [
{
"name": "web"
"name": "web",
"params": {
"n": 5
}
}
]
}
@ -193,6 +198,20 @@ Reference the markdown converted contents of a given URL.
}
```
### `@Clipboard`
Reference recent clipboard items
```json title="config.json"
{
"contextProviders": [
{
"name": "clipboard"
}
]
}
```
### `@Tree`
Reference the structure of your current workspace.
@ -207,26 +226,103 @@ Reference the structure of your current workspace.
}
```
### `@Google`
### `@Problems`
Reference the results of a Google search.
Get Problems from the current file.
```json title="config.json"
{
"contextProviders": [
{
"name": "google",
"name": "problems"
}
]
}
```
### `@Debugger`
Reference the contents of the local variables in the debugger. Currently only available in VS Code.
```json title="config.json"
{
"contextProviders": [
{
"name": "debugger",
"params": {
"serperApiKey": "<your serper.dev api key>"
"stackDepth": 3
}
}
]
}
```
For example, type "@Google python tutorial" if you want to search and discuss ways of learning Python.
Uses the top _n_ levels (defaulting to 3) of the call stack for that thread.
Note: You can get an API key for free at [serper.dev](https://serper.dev).
### `@Repository Map`
Reference the outline of your codebase.
`includeSignatures` params can be used to include signatures for all files in the repo. Use with caution as will increase context size significantly. `includeSignatures` will not work if indexing is disabled.
```json title="config.json"
{
"contextProviders": [
{
"name": "repo-map",
"params": {
"includeSignatures": false
}
}
]
}
```
Provides a list of files and the call signatures of top-level classes, functions, and methods in those files. This helps the model better understand how a particular piece of code relates to the rest of the codebase.
In the submenu that appears, you can select either `Entire codebase`, or specify a subfolder to generate the repostiory map from.
This context provider is inpsired by [Aider's repository map](https://aider.chat/2023/10/22/repomap.html).
### `@Operating System`
Reference the architecture and platform of your current operating system.
```json title="config.json"
{
"contextProviders": [
{
"name": "os"
}
]
}
```
### Model Context Protocol
The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then configure your `config.json` like this:
```json
{
"experimental": {
"modelContextProtocolServers": [
{
"transport": {
"type": "stdio",
"command": "uvx",
"args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"]
}
}
]
}
}
```
You'll then be able to type "@" and see "MCP" in the context providers dropdown.
### Prompt Files
See [Prompt Files](/customize/deep-dives/prompt-files). Prompt files are not added directly to the config file; prompt files are parsed and injected into the config automatically, to be used like other context providers.
### `@Issue`
@ -253,6 +349,110 @@ Reference the conversation in a GitHub issue.
Make sure to include your own [GitHub personal access token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-fine-grained-personal-access-token) to avoid being rate-limited.
### `@Database`
Reference table schemas from Sqlite, Postgres, MSSQL, and MySQL databases.
```json title="config.json"
{
"contextProviders": [
{
"name": "database",
"params": {
"connections": [
{
"name": "examplePostgres",
"connection_type": "postgres",
"connection": {
"user": "username",
"host": "localhost",
"database": "exampleDB",
"password": "yourPassword",
"port": 5432
}
},
{
"name": "exampleMssql",
"connection_type": "mssql",
"connection": {
"user": "username",
"server": "localhost",
"database": "exampleDB",
"password": "yourPassword"
}
},
{
"name": "exampleSqlite",
"connection_type": "sqlite",
"connection": {
"filename": "/path/to/your/sqlite/database.db"
}
}
]
}
}
]
}
```
Each connection should include a unique name, the `connection_type`, and the necessary connection parameters specific to each database type.
Available connection types:
- `postgres`
- `mysql`
- `sqlite`
### `@Postgres`
Reference the schema of a table, and some sample rows
```json title="config.json"
{
"contextProviders": [
{
"name": "postgres",
"params": {
"host": "localhost",
"port": 5436,
"user": "myuser",
"password": "catsarecool",
"database": "animals",
"schema": "public",
"sampleRows": 3
}
}
]
}
```
The only required settings are those for creating the database connection: `host`, `port`, `user`, `password`, and `database`.
By default, the `schema` filter is set to `public`, and the `sampleRows` is set to 3. You may unset the schema if you want to include tables from all schemas.
[Here is a short demo.](https://github.com/continuedev/continue/pull/859)
### `@Google`
Reference the results of a Google search.
```json title="config.json"
{
"contextProviders": [
{
"name": "google",
"params": {
"serperApiKey": "<your serper.dev api key>"
}
}
]
}
```
For example, type "@Google python tutorial" if you want to search and discuss ways of learning Python.
Note: You can get an API key for free at [serper.dev](https://serper.dev).
### `@Gitlab Merge Request`
Reference an open MR for this branch on GitLab.
@ -373,164 +573,6 @@ Reference the messages in a Discord channel.
Make sure to include your own [Bot Token](https://discord.com/developers/applications), and join it to your related server . If you want more granular control over which channels are searched, you can specify a list of channel IDs to search in. If you don't want to specify any channels, just include the guild id(Server ID) and all channels will be included. The provider only reads text channels.
### `@Postgres`
Reference the schema of a table, and some sample rows
```json title="config.json"
{
"contextProviders": [
{
"name": "postgres",
"params": {
"host": "localhost",
"port": 5436,
"user": "myuser",
"password": "catsarecool",
"database": "animals",
"schema": "public",
"sampleRows": 3
}
}
]
}
```
The only required settings are those for creating the database connection: `host`, `port`, `user`, `password`, and `database`.
By default, the `schema` filter is set to `public`, and the `sampleRows` is set to 3. You may unset the schema if you want to include tables from all schemas.
[Here is a short demo.](https://github.com/continuedev/continue/pull/859)
### `@Database`
Reference table schemas from Sqlite, Postgres, MSSQL, and MySQL databases.
```json title="config.json"
{
"contextProviders": [
{
"name": "database",
"params": {
"connections": [
{
"name": "examplePostgres",
"connection_type": "postgres",
"connection": {
"user": "username",
"host": "localhost",
"database": "exampleDB",
"password": "yourPassword",
"port": 5432
}
},
{
"name": "exampleMssql",
"connection_type": "mssql",
"connection": {
"user": "username",
"server": "localhost",
"database": "exampleDB",
"password": "yourPassword"
}
},
{
"name": "exampleSqlite",
"connection_type": "sqlite",
"connection": {
"filename": "/path/to/your/sqlite/database.db"
}
}
]
}
}
]
}
```
Each connection should include a unique name, the `connection_type`, and the necessary connection parameters specific to each database type.
Available connection types:
- `postgres`
- `mysql`
- `sqlite`
### `@Debugger`
Reference the contents of the local variables in the debugger. Currently only available in VS Code.
```json title="config.json"
{
"contextProviders": [
{
"name": "debugger",
"params": {
"stackDepth": 3
}
}
]
}
```
Uses the top _n_ levels (defaulting to 3) of the call stack for that thread.
### `@Repository Map`
Reference the outline of your codebase.
```json title="config.json"
{
"contextProviders": [
{
"name": "repo-map"
}
]
}
```
Provides a list of files and the call signatures of top-level classes, functions, and methods in those files. This helps the model better understand how a particular piece of code relates to the rest of the codebase.
In the submenu that appears, you can select either `Entire codebase`, or specify a subfolder to generate the repostiory map from.
This context provider is inpsired by [Aider's repository map](https://aider.chat/2023/10/22/repomap.html).
### `@Operating System`
Reference the architecture and platform of your current operating system.
```json title="config.json"
{
"contextProviders": [
{
"name": "os"
}
]
}
```
### Model Context Protocol
The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then configure your `config.json` like this:
```json
{
"experimental": {
"modelContextProtocolServers": [
{
"transport": {
"type": "stdio",
"command": "uvx",
"args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"]
}
}
]
}
}
```
You'll then be able to type "@" and see "MCP" in the context providers dropdown.
### `@HTTP`
The HttpContextProvider makes a POST request to the url passed in the configuration. The server must return 200 OK with a ContextItem object or an array of ContextItems.
@ -550,7 +592,7 @@ The HttpContextProvider makes a POST request to the url passed in the configurat
The receiving URL should expect to receive the following parameters:
```json title="POST parameters"
```js title="POST parameters"
{
query: string,
fullInput: string
@ -576,6 +618,27 @@ The response 200 OK should be a JSON object with the following structure:
}
```
### `@Commits`
Reference specific git commit metadata and diff or all of the recent commits.
```json title="config.json"
{
"contextProviders": [
{
"name": "commit",
"params": {
"Depth": 50,
"LastXCommitsDepth": 10
}
}
]
}
```
The depth is how many commits will be loaded into the submenu, defaults to 50.
The LastXCommitsDepth is how many recent commits will be included, defaults to 10.
### `@Clipboard`
Reference recent clipboard items
@ -590,6 +653,24 @@ Reference recent clipboard items
}
```
### `@Greptile`
Query a [Greptile](https://www.greptile.com/) index of the current repo/branch.
```json title="config.json"
{
"contextProviders": [
{
"name": "greptile",
"params": {
"GreptileToken": "...",
"GithubToken": "..."
}
}
]
}
```
### Requesting Context Providers
Not seeing what you want? Create an issue [here](https://github.com/continuedev/continue/issues/new?assignees=TyDunn&labels=enhancement&projects=&template=feature-request-%F0%9F%92%AA.md&title=) to request a new Context Provider.

View file

@ -1,22 +1,59 @@
# vLLM
Run the OpenAI-compatible server by vLLM using `vllm serve`. See their [server documentation](https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html) and the [engine arguments documentation](https://docs.vllm.ai/en/latest/models/engine_args.html).
vLLM is an open-source library for fast LLM inference which typically is used to serve multiple users at the same. It can also be used to run a large model on multiple GPU:s (e.g. when it doesn´t fit in a single GPU). Run their OpenAI-compatible server using `vllm serve`. See their [server documentation](https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html) and the [engine arguments documentation](https://docs.vllm.ai/en/latest/usage/engine_args.html).
```shell
vllm serve NousResearch/Meta-Llama-3-8B-Instruct --max-model-len 1024
vllm serve meta-llama/Meta-Llama-3.1-8B-Instruct
```
## Chat model
The continue implementation uses [OpenAI](../top-level/openai.md) under the hood and automatically selects the available model. You only need to set the `apiBase` like this:
We recommend configuring **Llama3.1 8B** as your chat model.
```json title="config.json"
{
"models": [
{
"title": "My vLLM OpenAI-compatible server",
"apiBase": "http://localhost:8000/v1"
"title": "Llama3.1 8B Instruct",
"provider": "vllm",
"model": "meta-llama/Meta-Llama-3.1-8B-Instruct"
"apiBase": "http://<vllm chat endpoint>/v1"
}
]
}
```
[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Vllm.ts)
## Autocomplete model
We recommend configuring **Qwen2.5-Coder 1.5B** as your autocomplete model.
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Qwen2.5-Coder 1.5B",
"provider": "vllm",
"model": "Qwen/Qwen2.5-Coder-1.5B"
"apiBase": "http://<vllm autocomplete endpoint>/v1"
}
}
```
## Embeddings model
We recommend configuring **Nomic Embed Text** as your embeddings model.
```json title="config.json"
{
"embeddingsProvider": {
"provider": "vllm",
"model": "nomic-ai/nomic-embed-text-v1"
"apiBase": "http://<vllm embed endpoint>/v1"
}
}
```
## Reranking model
[Click here](../../model-types/reranking.md) to see a list of reranking model providers.
The continue implementation uses [OpenAI](../top-level/openai.md) under the hood. [View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Vllm.ts)

View file

@ -53,3 +53,20 @@ We recommend configuring **Nomic Embed Text** as your embeddings model.
Ollama currently does not offer any reranking models.
[Click here](../../model-types/reranking.md) to see a list of reranking model providers.
## Using a remote instance
To configure a remote instance of Ollama, add the `"apiBase"` property to your model in config.json:
```json title="config.json"
{
"models": [
{
"title": "Llama3.1 8B",
"provider": "ollama",
"model": "llama3.1:8b",
"apiBase": "http://<my endpoint>:11434"
}
]
}
```

View file

@ -4,7 +4,12 @@ description: Tool use and customization
keywords: [tool, use, function calling, claude, automatic]
---
Tools allow Continue to take action in your IDE and beyond (when you give permission). Currently, they are only supported with [Anthropic](./model-providers/top-level/anthropic.md). To use tools, click on the icon in the input toolbar like below.
Tools allow Continue to take action in your IDE and beyond (when you give permission). Currently, they are only supported for the following providers:
- [Anthropic](./model-providers/top-level/anthropic.md) - see recommended models [here](https://docs.anthropic.com/en/docs/build-with-claude/tool-use#choosing-a-model).
- [Ollama](./model-providers/top-level/ollama.md) - see recommended models [here](https://ollama.com/search?c=tools).
To use tools, click on the icon in the input toolbar like below.
![tools](/img/tool-use-example.png)

View file

@ -71,28 +71,6 @@ Together AI provides fast and reliable inference of open-source models. You'll b
}
```
## Novita AI
[Novita AI](https://novita.ai?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) offers an affordable, reliable, and simple inference platform with scalable [LLM API](https://novita.ai/docs/model-api/reference/introduction.html), empowering developers to build AI applications. Try the [Novita AI Llama 3 API Demo](https://novita.ai/model-api/product/llm-api/playground/meta-llama-llama-3.1-70b-instruct?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) today!
1. Create an account [here](https://novita.ai/user/login?&redirect=/&utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link)
2. Copy your API key that appears on the welcome screen
3. Update your Continue config file like this:
```json title="config.json"
{
"models": [
{
"title": "Llama 3.1 405b",
"provider": "novita",
"model": "meta-llama/llama-3.1-405b-instruct",
"apiKey": "<API_KEY>"
}
]
}
```
## Replicate
Replicate makes it easy to host and run open-source AI with an API.

View file

@ -251,16 +251,6 @@ Example
]
```
### `analytics`
Configuration for analytics tracking.
**Properties:**
- `provider`: Analytics provider (`"posthog"` or `"logstash"`).
- `url`: URL for analytics data.
- `clientKey`: Client key for analytics.
### `slashCommands`
Custom commands initiated by typing "/" in the sidebar. Commands include predefined functionality or may be user-defined.
@ -419,8 +409,8 @@ Several experimental config parameters are available, as described below:
- `docstring`: Prompt for adding docstrings.
- `fix`: Prompt for fixing code.
- `optimize`: Prompt for optimizing code.
- `fixGrammar`: Prompt for fixing grammar or spelling.
- `useChromiumForDocsCrawling`: Use Chromium to crawl docs locally. Useful if the default Cheerio crawler fails on sites that require JavaScript rendering. Downloads and installs Chromium to `~/.continue/.utils`..
- `modelContextProtocolServers`: See [Model Context Protocol](/customize/context-providers#model-context-protocol)
Example
@ -442,7 +432,16 @@ Example
"fixGrammar": "Fix grammar in the above but allow for typos."
},
"readResponseTTS": false,
"useChromiumForDocsCrawling": true
"useChromiumForDocsCrawling": true,
"modelContextProtocolServers": [
{
"transport": {
"type": "stdio",
"command": "uvx",
"args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"]
}
}
]
}
}
```

265
docs/docs/yaml-migration.md Normal file
View file

@ -0,0 +1,265 @@
---
title: Config Migration to YAML
description: Reference for migrating from JSON to YAML Continue configuration.
keywords: [config, yaml, configuration, customize, customization, migration]
---
# Migrating Config to YAML
Continue's YAML configuration format provides more readable, maintainable, consistent configuration files, as well as new configuration options and removal of some old configuration options. YAML is the preferred format and will be used to integrate with future Continue products. Below is a brief guide for migration from `config.json` to `config.yaml`.
See also
- [Intro to YAML](https://yaml.org/)
- [JSON Continue Config Reference](/reference)
- [YAML Continue Config Reference](/yaml-reference)
### 1. Create YAML file
Create a `config.yaml` file in your Continue Global Directory (`~/.continue` on Mac, `%USERPROFILE%\.continue`) alongside your current `config.json` file. If a `config.yaml` file is present, it will be loaded instead of `config.json`.
Give your configuration a `name` and a `version`:
```yaml title="config.yaml"
name: my-configuration
version: 0.0.1
```
### 2. Map Models
Add all model configurations in `config.json`, including models in `models`, `tabAutocompleteModel`, `embeddingsProvider`, and `reranker`, to the `models` section of your new YAML config file. A new `roles` YAML field specifies which roles a model can be used for, with possible values `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`.
- `models` in config should have `roles: chat`
- `tabAutocompleteModel`(s) in config should have `roles: autocomplete`
- `embeddingsProvider` in config should have `roles: embed`
- `reranker` in config should have `roles: rerank`
- `experimental.modelRoles` is replaced by simply adding roles to the model
- `inlineEdit` -> e.g. `roles: [chat, edit]`
- `applyCodeBlock` -> e.g. `roles: [chat, apply]`
Model-level `requestOptions` remain, with minor changes. See [YAML Continue Config Reference](/yaml-reference#requestoptions)
Model-level `completionOptions` are replaced by `defaultCompletionOptions`, with minor changes. See [YAML Continue Config Reference](/yaml-reference#completionoptions)
<!-- TODO - API KEY -> apiKeySecret? -->
<!-- TODO - ollama autodetect supported? -->
**Before**
```json title="config.json"
{
"models": [
{
"title": "GPT-4",
"provider": "openai",
"model": "gpt-4",
"apiKey": "YOUR_API_KEY",
"completionOptions": {
"temperature": 0.5,
"maxTokens": 2000
}
},
{
"title": "Ollama",
"provider": "ollama",
"model": "AUTODETECT"
},
{
"title": "My Open AI Compatible Model",
"provider": "openai",
"apiBase": "http://3.3.3.3/v1",
"model": "my-openai-compatible-model",
"requestOptions": {
"headers": { "X-Auth-Token": "<API_KEY>" }
}
}
],
"tabAutocompleteModel": {
"title": "My Starcoder",
"provider": "ollama",
"model": "starcoder2:3b"
},
"embeddingsProvider": {
"provider": "openai",
"model": "text-embedding-ada-002",
"apiKey": "<API_KEY>",
"maxChunkSize": 256,
"maxBatchSize": 5
},
"reranker": {
"name": "voyage",
"params": {
"model": "rerank-2",
"apiKey": "<VOYAGE_API_KEY>"
}
}
}
```
**After**
```yaml title="config.yaml"
models:
- name: GPT-4
provider: openai
model: gpt-4
defaultCompletionOptions:
temperature: 0.5
maxTokens: 2000'
roles: [chat, edit]
apiKey: <API_KEY>
- name: My Voyage Reranker
provider: voyage
roles: rerank
apiKey: <API_KEY>
- name: My Starcoder
provider: ollama
model: starcoder2:3b
roles: autocomplete
- name: My Ada Embedder
provider: openai
roles: embed
apiKey: <API_KEY>
- name: Ollama Autodetect
provider: ollama
model: AUTODETECT
- name: My Open AI Compatible Model - Apply
provider: openai
apiBase: http://3.3.3.3/v1
model: my-openai-compatible-model
requestOptions:
headers:
X-Auth-Token: <API_KEY>
roles: [chat, apply]
```
Note that the `repoMapFileSelection` experimental model role has been deprecated.
### 3. Map Context Providers
The JSON `contextProviders` and `docs` fields are replaced by the YAML `context` array.
- JSON `name` maps to `uses`
- JSON `params` map to `with`
- Use multiple `docs` entries rather than the array of docs in the JSON format
<!-- TODO is this docs not correct ?^ -->
**Before**
```json title="config.json"
{
"contextProviders": [
{
"name": "docs",
"params": {
"startUrl": "https://docs.continue.dev/intro"
}
},
{
"name": "codebase",
"params": {
"nRetrieve": 30,
"nFinal": 3
}
},
{
"name": "diff",
"params": {}
}
],
"docs": [
{
"startUrl": "https://docs.nestjs.com/",
"title": "nest.js"
},
{
"startUrl": "https://mysite.com/docs/",
"title": "My site"
}
]
}
```
**After**
```yaml title="config.yaml"
context:
- uses: docs
with:
startUrl: https://docs.nestjs.com/
title: nest.js
- uses: docs
with:
startUrl: https://mysite.com/docs/
title: My Site
- uses: codebase
with:
nRetrieve: 30
nFinal: 3
- uses: diff
```
## Map MCP Servers
<!-- TODO this is definitely wrong -->
**Properties:**
- `name` (**required**): The name of the MCP server.
- `command` (**required**): The command used to start the server.
- `args`: An optional array of arguments for the command.
- `env`: An optional map of environment variables for the server process.
**Before**
```json title="config.json"
{
"experimental": {
"modelContextProtocolServers": [
{
"transport": {
"type": "stdio",
"command": "uvx",
"args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"]
}
}
]
}
}
```
**After**
```yaml title="config.yaml"
mcpServers:
- name: My MCP Server
command: uvx
args:
- mcp-server-sqlite
- --db-path
- /Users/NAME/test.db
```
---
## Deprecated configuration options
The following top-level fields from `config.json` have been deprecated
- Slash commands (JSON `slashCommands`)
- top-level `requestOptions`
- top-level `completionOptions`
- `tabAutocompleteOptions`
- `analytics`
- `customCommands`
- `disableSessionTitles`
- `experimental`
- `allowAnonymousTelemetry` (moved to user/IDE level)
- `ui` (moved to user/IDE level)
- `userToken`
- `systemMessage`
- `disableIndexing` (moved to user/IDE level)
## New Configuration options
The YAML configuration format offers new configuration options not available in the JSON format. See the [YAML Config Reference](/yaml-reference) for more information.

294
docs/docs/yaml-reference.md Normal file
View file

@ -0,0 +1,294 @@
---
title: Config YAML Reference
description: Reference for the Continue configuration YAML file
keywords: [config, yaml, configuration, customize, customization]
---
# Config YAML Reference
<!-- TODO - data and packages sections -->
Continue can be configured using a YAML file `config.yaml` which for local configuration can be placed in your global `.continue` folder (`~/.continue` on Mac, `%USERPROFILE%\.continue`)
Below are details for each property that can be set in `config.yaml`.
:::info
Config YAML does not work alongside `config.json` - it replaces it. View the **[Migration Guide](/yaml-migration)**. `config.yaml` currently only works in VS Code pre-release.
:::
**All properties at all levels are optional unless explicitly marked as required.**
## Properties
The top-level properties in the `config.yaml` configuration file are:
- [`name`](#name) (**required**)
<!-- - [`packages`](#packages) -->
- [`version`](#version) (**required**)
- [`models`](#models)
- [`context`](#context)
- [`rules`](#rules)
- [`docs`](#docs)
<!-- - [`data`](#data) -->
<!-- - [`tools`](#tools) -->
- [`mcpServers`](#mcpservers)
---
### `name`
The `name` property specifies the name of your project or configuration.
```yaml title="config.yaml"
name: MyProject
```
### `version`
The `version` property specifies the version of your project or configuration.
---
### `models`
The `models` section defines the language models used in your configuration. Models are used for functionalities such as chat, editing, and summarizing.
**Properties:**
- `name` (**required**): A unique name to identify the model within your configuration.
- `provider` (**required**): The provider of the model (e.g., `openai`, `ollama`).
- `model` (**required**): The specific model name (e.g., `gpt-4`, `starcoder`).
- `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`.
- `defaultCompletionOptions`: Default completion options for model settings.
**Properties:**
- `contextLength`: Maximum context length of the model, typically in tokens.
- `maxTokens`: Maximum number of tokens to generate in a completion.
- `temperature`: Controls the randomness of the completion. Values range from `0.0` (deterministic) to `1.0` (random).
- `topP`: The cumulative probability for nucleus sampling.
- `topK`: Maximum number of tokens considered at each step.
- `stop`: An array of stop tokens that will terminate the completion.
- `n`: Number of completions to generate.
- `requestOptions`: HTTP request options specific to the model.
**Properties:**
- `timeout`: Timeout for each request to the language model.
- `verifySsl`: Whether to verify SSL certificates for requests.
- `caBundlePath`: Path to a custom CA bundle for HTTP requests.
- `proxy`: Proxy URL for HTTP requests.
- `headers`: Custom headers for HTTP requests.
- `extraBodyProperties`: Additional properties to merge with the HTTP request body.
- `noProxy`: List of hostnames that should bypass the specified proxy.
- `clientCertificate`: Client certificate for HTTP requests.
- `cert`: Path to the client certificate file.
- `key`: Path to the client certificate key file.
- `passphrase`: Optional passphrase for the client certificate key file.
#### Example:
```yaml title="config.yaml"
models:
- name: GPT-4o
provider: openai
model: gpt-4o
roles:
- chat
- edit
- apply
defaultCompletionOptions:
temperature: 0.7
maxTokens: 1500
- name: Codestral
provider: mistral
model: codestral-latest
roles:
- autocomplete
```
---
### `context`
The `context` section defines context providers, which supply additional information or context to the language models. Each context provider can be configured with specific parameters.
More information about usage/params for each context provider can be found [here](/customize/context-providers)
**Properties:**
- `uses` (**required**): The identifier or name of the context provider (e.g., `code`, `docs`, `web`).
- `with`: Optional parameters to configure the context provider's behavior.
**Example:**
```yaml title="config.yaml"
context:
- uses: files
- uses: code
- uses: codebase
with:
nFinal: 10
- uses: docs
- uses: diff
- uses: folder
- uses: terminal
```
---
### `rules`
List of rules that the LLM should follow. These are inserted into the system message for all chat requests.
Example
```yaml title="config.yaml"
rules:
- Always annotate Python functions with their parameter and return types
- Always write Google style docstrings for functions and classes
```
---
### `docs`
List of documentation sites to index.
**Properties:**
- `name` (**required**): Name of the documentation site, displayed in dropdowns, etc.
- `startUrl` (**required**): Start page for crawling - usually root or intro page for docs
- `rootUrl`: Crawler will only index docs within this domain - pages that contain this URL
- `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`).
Example
```yaml title="config.yaml"
docs:
- name: Continue
startUrl: https://docs.continue.dev/intro
rootUrl: https://docs.continue.dev
favicon: https://docs.continue.dev/favicon.ico
```
---
### `tools`
<!-- TODO how does this actually work -->
The `tools` section specifies external tools or APIs that can be used within your configuration.
**Properties:**
- `url` (**required**): The URL of the tool's API or endpoint.
- `apiKey`: An optional API key required by the tool.
**Example:**
```yaml title="config.yaml"
tools:
- url: https://api.exampletool.com/tool1
apiKey: YOUR_API_KEY
```
---
### `mcpServers`
<!-- TODO is this correct? -->
The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider.
**Properties:**
- `name` (**required**): The name of the MCP server.
- `command` (**required**): The command used to start the server.
- `args`: An optional array of arguments for the command.
- `env`: An optional map of environment variables for the server process.
**Example:**
```yaml title="config.yaml"
mcpServers:
- name: My MCP Server
command: uvx
args:
- mcp-server-sqlite
- --db-path
- /Users/NAME/test.db
```
<!-- ### `data`
The `data` section specifies data providers used in your configuration. Data providers supply data or resources for use in various operations.
**Properties:**
- `provider` (**required**): The name of the data provider.
**Example:**
```yaml title="config.yaml"
data:
- provider: embeddings
```
--- -->
---
## Complete YAML Config Example
Putting it all together, here's a complete example of a `config.yaml` configuration file:
```yaml title="config.yaml"
name: MyProject
models:
- name: GPT-4
provider: openai
model: gpt-4
roles:
- chat
- edit
defaultCompletionOptions:
temperature: 0.5
maxTokens: 2000
requestOptions:
headers:
Authorization: Bearer YOUR_OPENAI_API_KEY
- name: Ollama Starcoder
provider: ollama
model: starcoder
roles:
- autocomplete
defaultCompletionOptions:
temperature: 0.3
stop:
- "\n"
context:
- uses: diff
- uses: docs
with:
startUrl: https://docs.example.com/introduction
rootUrl: https://docs.example.com
maxDepth: 3
tools:
- url: https://api.exampletool.com
apiKey: YOUR_TOOL_API_KEY
mcpServers:
- name: DevServer
command: npm
args:
- run
- dev
env:
PORT: "3000"
```

View file

@ -13,7 +13,6 @@ const config = {
experimental_faster: true,
},
title: "Continue",
tagline:
"the open-source library for accelerating software development with language models",

View file

@ -33,7 +33,7 @@ import TabItem from "@theme/TabItem";
### 来自 Meta 的 Llama 3.1 405B
如果你倾向于使用开放权重模型,那么来自 Meta 的 Llama 3.1 405B 是你当前的最好选择。你需要决定,通过 SaaS 模型提供者使用它(比如 [Together](../customize/model-providers/more/together.md) 、[Novita AI](../customize/model-providers/more/novita.md)或 [Groq](../customize/model-providers/more/groq.md))或者自托管使用它(比如使用 [vLLM](../customize/model-providers//more/vllm.md) 或 [Ollama](../customize/model-providers/top-level/ollama.md)) 。
如果你倾向于使用开放权重模型,那么来自 Meta 的 Llama 3.1 405B 是你当前的最好选择。你需要决定,通过 SaaS 模型提供者使用它(比如 [Together](../customize/model-providers/more/together.md)或 [Groq](../customize/model-providers/more/groq.md))或者自托管使用它(比如使用 [vLLM](../customize/model-providers//more/vllm.md) 或 [Ollama](../customize/model-providers/top-level/ollama.md)) 。
<Tabs groupId="providers">
<TabItem value="Together">

View file

@ -71,27 +71,6 @@ Together AI 提供开源模型的快速和可信任的推理。你可以以良
}
```
## Novita AI
[Novita AI](https://novita.ai?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) 提供了一个经济实惠、可靠且简单的推理平台。你可以以良好的速度运行 405b 模型。
1. 创建账号 [在这里](https://novita.ai/user/login?&redirect=/&utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link)
2. 复制[Key Management](https://novita.ai/settings/key-management?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link)中的你的 API key
3. 更新你的 Continue 配置文件,像这样:
```json title="config.json"
{
"models": [
{
"title": "Llama 3.1 405b",
"provider": "novita",
"model": "meta-llama/llama-3.1-405b-instruct",
"apiKey": "<API_KEY>"
}
]
}
```
## Replicate
Replicate 让使用 API 托管和运行开源 AI 变得简单。

2702
docs/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -16,10 +16,10 @@
"write-heading-ids": "docusaurus write-heading-ids"
},
"dependencies": {
"@docusaurus/core": "^3.6.3",
"@docusaurus/faster": "^3.6.3",
"@docusaurus/plugin-client-redirects": "^3.6.3",
"@docusaurus/preset-classic": "^3.6.3",
"@docusaurus/core": "^3.7.0",
"@docusaurus/faster": "^3.7.0",
"@docusaurus/plugin-client-redirects": "^3.7.0",
"@docusaurus/preset-classic": "^3.7.0",
"@mdx-js/react": "^3.0.0",
"clsx": "^2.1.0",
"prism-react-renderer": "^2.3.1",
@ -27,7 +27,7 @@
"react-dom": "^18.2.0"
},
"devDependencies": {
"@docusaurus/module-type-aliases": "^3.6.3",
"@docusaurus/module-type-aliases": "^3.7.0",
"nodemon": "^3.1.4"
},
"browserslist": {

View file

@ -138,6 +138,16 @@ const sidebars = {
label: "Reference",
href: "/reference",
},
// {
// type: "link",
// label: "YAML Reference",
// href: "/yaml-reference",
// },
// {
// type: "link",
// label: "YAML Migration",
// href: "/yaml-migration",
// },
],
};

View file

@ -3,4 +3,6 @@ src/main/resources/webview
src/main/resources/bin
src/main/resources/config_schema.json
src/main/resources/continue_rc_schema.json
video
video
src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue/*
!src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue/config.json

View file

@ -1,31 +1,31 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Run Extension" type="GradleRunConfiguration" factoryName="Gradle">
<ExternalSystemSettings>
<option name="env">
<map>
<entry key="GUI_URL" value="http://localhost:5173/jetbrains_index.html" />
<entry key="ORG_GRADLE_PROJECT_platformVersion" value="2024.1" />
<entry key="USE_TCP" value="true" />
</map>
</option>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$/extensions/intellij" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="runIde" />
</list>
</option>
<option name="vmOptions" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
<configuration default="false" name="Run Extension" type="GradleRunConfiguration" factoryName="Gradle">
<ExternalSystemSettings>
<option name="env">
<map>
<entry key="GUI_URL" value="http://localhost:5173/jetbrains_index.html"/>
<entry key="ORG_GRADLE_PROJECT_platformVersion" value="2024.1"/>
<entry key="USE_TCP" value="true"/>
</map>
</option>
<option name="executionName"/>
<option name="externalProjectPath" value="$PROJECT_DIR$/extensions/intellij"/>
<option name="externalSystemIdString" value="GRADLE"/>
<option name="scriptParameters" value=""/>
<option name="taskDescriptions">
<list/>
</option>
<option name="taskNames">
<list>
<option value="runIde"/>
</list>
</option>
<option name="vmOptions"/>
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2"/>
</configuration>
</component>

View file

@ -1,25 +0,0 @@
<!--<component name="ProjectRunConfigurationManager">-->
<!-- <configuration default="false" name="Run IDE for UI Tests" type="GradleRunConfiguration" factoryName="Gradle">-->
<!-- <log_file alias="idea.log" path="$PROJECT_DIR$/build/idea-sandbox/system/log/idea.log" />-->
<!-- <ExternalSystemSettings>-->
<!-- <option name="executionName" />-->
<!-- <option name="externalProjectPath" value="$PROJECT_DIR$" />-->
<!-- <option name="externalSystemIdString" value="GRADLE" />-->
<!-- <option name="scriptParameters" value="" />-->
<!-- <option name="taskDescriptions">-->
<!-- <list />-->
<!-- </option>-->
<!-- <option name="taskNames">-->
<!-- <list>-->
<!-- <option value="runIdeForUiTests" />-->
<!-- </list>-->
<!-- </option>-->
<!-- <option name="vmOptions" />-->
<!-- </ExternalSystemSettings>-->
<!-- <ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>-->
<!-- <ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>-->
<!-- <DebugAllEnabled>false</DebugAllEnabled>-->
<!-- <RunAsTest>false</RunAsTest>-->
<!-- <method v="2" />-->
<!-- </configuration>-->
<!--</component>-->

View file

@ -0,0 +1,27 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Run Test IDE" type="GradleRunConfiguration" factoryName="Gradle">
<ExternalSystemSettings>
<option name="executionName"/>
<option name="externalProjectPath" value="$PROJECT_DIR$/extensions/intellij"/>
<option name="externalSystemIdString" value="GRADLE"/>
<option name="scriptParameters" value=""/>
<option name="taskDescriptions">
<list/>
</option>
<option name="taskNames">
<list>
<option value="runIdeForUiTests"/>
</list>
</option>
<option name="vmOptions"/>
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2">
<option name="Gradle.BeforeRunTask" enabled="true" tasks="clean"
externalProjectPath="$PROJECT_DIR$/extensions/intellij" vmOptions="" scriptParameters=""/>
</method>
</configuration>
</component>

View file

@ -0,0 +1,24 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Run Tests" type="GradleRunConfiguration" factoryName="Gradle" focusToolWindowBeforeRun="true">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$/extensions/intellij" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="test" />
</list>
</option>
<option name="vmOptions" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
</component>

View file

@ -0,0 +1,7 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Run e2e tests" type="CompoundRunConfigurationType">
<toRun name="Run Test IDE" type="GradleRunConfiguration" />
<toRun name="Run Tests" type="GradleRunConfiguration" />
<method v="2" />
</configuration>
</component>

View file

@ -1,16 +1,17 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Start Core Dev Server (CE)" type="ShConfigurationType">
<option name="SCRIPT_TEXT" value="export CONTINUE_DEVELOPMENT=true &amp;&amp; export CONTINUE_GLOBAL_DIR=$PROJECT_DIR$/extensions/.continue-debug &amp;&amp; node out/index.js" />
<option name="SCRIPT_TEXT" value="export CONTINUE_DEVELOPMENT=true &amp;&amp; export CONTINUE_GLOBAL_DIR=$PROJECT_DIR$/../.continue-debug &amp;&amp; node out/index.js" />
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
<option name="SCRIPT_PATH" value="" />
<option name="SCRIPT_OPTIONS" value="" />
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$/binary" />
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$/../../binary" />
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
<option name="INTERPRETER_PATH" value="" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="EXECUTE_IN_TERMINAL" value="false" />
<option name="EXECUTE_SCRIPT_FILE" value="false" />
<envs />
<method v="2" />
</configuration>
</component>

View file

@ -5,7 +5,7 @@
<option name="SCRIPT_PATH" value="" />
<option name="SCRIPT_OPTIONS" value="" />
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$/gui" />
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$/../../gui" />
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
<option name="INTERPRETER_PATH" value="/bin/zsh" />
<option name="INTERPRETER_OPTIONS" value="" />

View file

@ -6,7 +6,7 @@ and is generated by [Changie](https://github.com/miniscruff/changie).
Pre-release Changes
### Fixed
### Fixed
* Off-screen rendering to solve white flash on load and lack of changing cursor type
* OSR-related fixes for non-Mac users
* Fixes for inline edit in JetBrains

View file

@ -101,7 +101,9 @@ toolbar.
_Run | Debugging Actions | Reload Changed Classes`_
- This will often fail on new imports, schema changes etc. In that case, you need to stop and restart the extension
- `gui`: Changes will be reloaded automatically
- `core`: Run `npm run build` from the `binary` directory (requires restarting the `Start Core Dev Server` task)
- `core`: Run `npm run build -- --os [darwin | linux | win32]` from the `binary` directory (requires
restarting the
`Start Core Dev Server` task)
### Setting breakpoints

View file

@ -130,7 +130,10 @@ tasks {
// Configure UI tests plugin
// Read more: https://github.com/JetBrains/intellij-ui-test-robot
runIdeForUiTests {
environment("CONTINUE_GLOBAL_DIR", "src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue")
environment(
"CONTINUE_GLOBAL_DIR",
"${rootProject.projectDir}/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue"
)
systemProperty("robot-server.port", "8082")
systemProperty("ide.mac.message.dialogs.as.sheets", "false")
systemProperty("jb.privacy.policy.text", "<!--999.999-->")
@ -141,6 +144,7 @@ tasks {
systemProperty("idea.trust.all.projects", "true")
systemProperty("ide.show.tips.on.startup.default.value", "false")
systemProperty("ide.browser.jcef.jsQueryPoolSize", "10000")
systemProperty("ide.browser.jcef.contextMenu.devTools.enabled", "true")
// This is to ensure we load the GUI with OSR enabled. We have logic that
// renders with OSR disabled below a particular IDE version.
@ -180,6 +184,5 @@ tasks {
test {
useJUnitPlatform()
environment("CONTINUE_GLOBAL_DIR", "src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue")
}
}

View file

@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension
pluginName=continue-intellij-extension
pluginRepositoryUrl=https://github.com/continuedev/continue
# SemVer format -> https://semver.org
pluginVersion=0.0.84
pluginVersion=0.0.85
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
pluginSinceBuild=223
# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension

View file

@ -10,7 +10,7 @@ import com.github.continuedev.continueintellijextension.listeners.ContinuePlugin
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.services.SettingsListener
import com.intellij.openapi.Disposable
import com.github.continuedev.continueintellijextension.utils.toUriOrNull
import com.intellij.openapi.actionSystem.KeyboardShortcut
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ApplicationNamesInfo
@ -162,7 +162,7 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
override fun after(events: List<VFileEvent>) {
// Collect all relevant URIs for deletions
val deletedURIs = events.filterIsInstance<VFileDeleteEvent>()
.map { event -> event.file.url }
.mapNotNull { event -> event.file.toUriOrNull() }
// Send "files/deleted" message if there are any deletions
if (deletedURIs.isNotEmpty()) {
@ -172,7 +172,7 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
// Collect all relevant URIs for content changes
val changedURIs = events.filterIsInstance<VFileContentChangeEvent>()
.map { event -> event.file.url }
.mapNotNull { event -> event.file.toUriOrNull() }
// Send "files/changed" message if there are any content changes
if (changedURIs.isNotEmpty()) {
@ -220,7 +220,7 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
// Reload the WebView
continuePluginService?.let { pluginService ->
val allModulePaths = ModuleManager.getInstance(project).modules
.flatMap { module -> ModuleRootManager.getInstance(module).contentRoots.map { it.url } }
.flatMap { module -> ModuleRootManager.getInstance(module).contentRoots.mapNotNull { it.toUriOrNull() } }
val topLevelModulePaths = allModulePaths
.filter { modulePath -> allModulePaths.none { it != modulePath && modulePath.startsWith(it) } }

View file

@ -22,4 +22,4 @@ class AcceptAutocompleteAction : EditorAction(object : EditorActionHandler() {
&& autocompleteService.pendingCompletion?.text != null
return enabled
}
}) {}
})

View file

@ -2,6 +2,7 @@ package com.github.continuedev.continueintellijextension.autocomplete
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.utils.toUriOrNull
import com.github.continuedev.continueintellijextension.utils.uuid
import com.intellij.injected.editor.VirtualFileWindow
import com.intellij.openapi.application.*
@ -10,8 +11,10 @@ import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.InlayProperties
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.wm.WindowManager
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
@ -32,9 +35,24 @@ fun PsiElement.isInjectedText(): Boolean {
return false
}
fun Editor.addInlayElement(
lines: List<String>,
offset: Int,
properties: InlayProperties
) {
if (this is EditorImpl) {
if (lines[0].isNotEmpty()) {
inlayModel.addInlineElement(offset, properties, ContinueInlayRenderer(listOf(lines[0])))
}
if (lines.size > 1) {
inlayModel.addBlockElement(offset, properties, ContinueInlayRenderer(lines.drop(1)))
}
}
}
@Service(Service.Level.PROJECT)
class AutocompleteService(private val project: Project) {
var pendingCompletion: PendingCompletion? = null;
var pendingCompletion: PendingCompletion? = null
private val autocompleteLookupListener = project.service<AutocompleteLookupListener>()
private var widget: AutocompleteSpinnerWidget? = null
@ -66,23 +84,23 @@ class AutocompleteService(private val project: Project) {
// Request a completion from the core
val virtualFile = FileDocumentManager.getInstance().getFile(editor.document)
val uri = virtualFile?.toUriOrNull() ?: return
val line = editor.caretModel.primaryCaret.logicalPosition.line
val column = editor.caretModel.primaryCaret.logicalPosition.column
val input = mapOf(
"completionId" to completionId,
"filepath" to virtualFile?.url,
"filepath" to uri,
"pos" to mapOf(
"line" to editor.caretModel.primaryCaret.logicalPosition.line,
"line" to line,
"character" to column
),
"recentlyEditedFiles" to emptyList<String>(),
"recentlyEditedRanges" to emptyList<String>(),
"clipboardText" to ""
"clipboardText" to "",
"recentlyEditedRanges" to emptyList<Any>(),
"recentlyVisitedRanges" to emptyList<Any>(),
)
val lineStart = editor.document.getLineStartOffset(editor.caretModel.primaryCaret.logicalPosition.line)
val lineEnd = editor.document.getLineEndOffset(editor.caretModel.primaryCaret.logicalPosition.line)
val lineLength = lineEnd - lineStart
project.service<ContinuePluginService>().coreMessenger?.request(
"autocomplete/complete",
input,
@ -95,24 +113,28 @@ class AutocompleteService(private val project: Project) {
val completion = completions[0].toString()
val finalTextToInsert = deduplicateCompletion(editor, offset, completion)
if (shouldRenderCompletion(finalTextToInsert, column, lineLength, editor)) {
if (shouldRenderCompletion(finalTextToInsert, offset, line, editor)) {
renderCompletion(editor, offset, finalTextToInsert)
pendingCompletion = PendingCompletion(editor, offset, completionId, finalTextToInsert)
// Hide auto-popup
// AutoPopupController.getInstance(project).cancelAllRequests()
}
}
})
)
}
private fun shouldRenderCompletion(completion: String, column: Int, lineLength: Int, editor: Editor): Boolean {
if (completion.isEmpty()) {
private fun shouldRenderCompletion(completion: String, offset: Int, line: Int, editor: Editor): Boolean {
if (completion.isEmpty() || runReadAction { offset != editor.caretModel.offset }) {
return false
}
if (completion.lines().size == 1) {
return true
}
val endOffset = editor.document.getLineEndOffset(line)
// Do not render if completion is multi-line and caret is in middle of line
return !(completion.lines().size > 1 && column < lineLength)
return offset <= endOffset && editor.document.getText(TextRange(offset, endOffset)).isBlank()
}
private fun deduplicateCompletion(editor: Editor, offset: Int, completion: String): String {
@ -126,9 +148,9 @@ class AutocompleteService(private val project: Project) {
val N = 10
var textAfterCursor = if (caretOffset + N <= document.textLength) {
document.getText(com.intellij.openapi.util.TextRange(caretOffset, caretOffset + N))
document.getText(TextRange(caretOffset, caretOffset + N))
} else {
document.getText(com.intellij.openapi.util.TextRange(caretOffset, document.textLength))
document.getText(TextRange(caretOffset, document.textLength))
}
// Avoid truncating the completion text when the text after the cursor is blank
@ -171,19 +193,9 @@ class AutocompleteService(private val project: Project) {
properties.relatesToPrecedingText(true)
properties.disableSoftWrapping(true)
if (completion.lines().size > 1) {
editor.inlayModel.addBlockElement(
offset,
properties,
ContinueMultilineCustomElementRenderer(editor, completion)
)
} else {
editor.inlayModel.addInlineElement(
offset,
properties,
ContinueCustomElementRenderer(editor, completion)
)
}
val lines = completion.lines()
pendingCompletion = pendingCompletion?.copy(text = lines.joinToString("\n"))
editor.addInlayElement(lines, offset, properties)
// val attributes = TextAttributes().apply {
// backgroundColor = JBColor.GREEN
@ -211,7 +223,7 @@ class AutocompleteService(private val project: Project) {
({})
)
invokeLater {
clearCompletions(editor)
clearCompletions(editor, completion)
}
}
@ -274,23 +286,14 @@ class AutocompleteService(private val project: Project) {
project.service<ContinuePluginService>().coreMessenger?.request("autocomplete/cancel", null, null, ({}))
}
fun clearCompletions(editor: Editor) {
fun clearCompletions(editor: Editor, completion: PendingCompletion? = pendingCompletion) {
if (isInjectedFile(editor)) return
if (pendingCompletion != null) {
cancelCompletion(pendingCompletion!!)
pendingCompletion = null
}
editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength).forEach {
if (it.renderer is ContinueCustomElementRenderer) {
it.dispose()
}
}
editor.inlayModel.getBlockElementsInRange(0, editor.document.textLength).forEach {
if (it.renderer is ContinueMultilineCustomElementRenderer) {
it.dispose()
}
if (completion != null) {
cancelCompletion(completion)
if (completion.completionId == pendingCompletion?.completionId) pendingCompletion = null
}
disposeInlayRenderer(editor)
}
private fun isInjectedFile(editor: Editor): Boolean {
@ -305,13 +308,17 @@ class AutocompleteService(private val project: Project) {
fun hideCompletions(editor: Editor) {
if (isInjectedFile(editor)) return
disposeInlayRenderer(editor)
}
private fun disposeInlayRenderer(editor: Editor) {
editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength).forEach {
if (it.renderer is ContinueCustomElementRenderer) {
if (it.renderer is ContinueInlayRenderer) {
it.dispose()
}
}
editor.inlayModel.getBlockElementsInRange(0, editor.document.textLength).forEach {
if (it.renderer is ContinueMultilineCustomElementRenderer) {
if (it.renderer is ContinueInlayRenderer) {
it.dispose()
}
}

View file

@ -1,45 +0,0 @@
package com.github.continuedev.continueintellijextension.autocomplete
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorCustomElementRenderer
import com.intellij.openapi.editor.Inlay
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.editor.impl.FontInfo
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.ui.JBColor
import com.intellij.util.ui.UIUtil
import java.awt.Font
import java.awt.Graphics
import java.awt.Rectangle
import kotlin.math.ceil
class ContinueCustomElementRenderer(
val editor: Editor,
val text: String,
) : EditorCustomElementRenderer {
override fun calcWidthInPixels(inlay: Inlay<*>): Int {
val width = (inlay.editor as EditorImpl).getFontMetrics(Font.PLAIN).stringWidth(this.text)
return width
}
private fun font(editor: Editor): Font {
val editorFont = editor.colorsScheme.getFont(EditorFontType.PLAIN)
return UIUtil.getFontWithFallbackIfNeeded(editorFont, text).deriveFont(editor.colorsScheme.editorFontSize)
}
private fun offsetY(editor: Editor): Int {
val metrics =
FontInfo.getFontMetrics(font(editor), FontInfo.getFontRenderContext(editor.contentComponent))
val fontHeight =
font(editor).createGlyphVector(metrics.fontRenderContext, text).visualBounds.height
val height = (editor.lineHeight + fontHeight) / 2
return ceil(height).toInt()
}
override fun paint(inlay: Inlay<*>, g: Graphics, targetRegion: Rectangle, textAttributes: TextAttributes) {
g.color = JBColor.GRAY
g.font = font(inlay.editor)
g.drawString(this.text, targetRegion.x, targetRegion.y + inlay.editor.ascent)
}
}

View file

@ -0,0 +1,58 @@
package com.github.continuedev.continueintellijextension.autocomplete
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorCustomElementRenderer
import com.intellij.openapi.editor.Inlay
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.ui.JBColor
import com.intellij.util.ui.UIUtil
import java.awt.Font
import java.awt.Graphics
import java.awt.Rectangle
/**
* The `ContinueInlayRenderer` class is responsible for rendering custom inlay elements within an editor.
* It implements the [EditorCustomElementRenderer] interface to provide custom rendering logic for inlays.
*
* This renderer is designed to display a list of text lines (`lines`) within the editor, calculating the
* necessary width and height based on the content and rendering each line with appropriate font and color.
*
* @author lk
*/
class ContinueInlayRenderer(val lines: List<String>) : EditorCustomElementRenderer {
override fun calcWidthInPixels(inlay: Inlay<*>): Int {
var maxLen = 0;
for (line in lines) {
val len = (inlay.editor as EditorImpl).getFontMetrics(Font.PLAIN).stringWidth(line)
if (len > maxLen) {
maxLen = len
}
}
return maxLen
}
override fun calcHeightInPixels(inlay: Inlay<*>): Int {
return (inlay.editor as EditorImpl).lineHeight * lines.size
}
private fun font(editor: Editor): Font {
val editorFont = editor.colorsScheme.getFont(EditorFontType.PLAIN)
return UIUtil.getFontWithFallbackIfNeeded(editorFont, lines.joinToString("\n"))
.deriveFont(editor.colorsScheme.editorFontSize)
}
override fun paint(inlay: Inlay<*>, g: Graphics, targetRegion: Rectangle, textAttributes: TextAttributes) {
val editor = inlay.editor
g.color = JBColor.GRAY
g.font = font(editor)
var additionalYOffset = 0
val ascent = editor.ascent
val lineHeight = editor.lineHeight
for (line in lines) {
g.drawString(line, targetRegion.x, targetRegion.y + ascent + additionalYOffset)
additionalYOffset += lineHeight
}
}
}

View file

@ -1,81 +0,0 @@
package com.github.continuedev.continueintellijextension.autocomplete
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorCustomElementRenderer
import com.intellij.openapi.editor.Inlay
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.editor.impl.FontInfo
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.ui.JBColor
import com.intellij.util.ui.UIUtil
import java.awt.Font
import java.awt.Graphics
import java.awt.Rectangle
import kotlin.math.ceil
import kotlin.math.max
class ContinueMultilineCustomElementRenderer(
val editor: Editor,
val text: String,
) : EditorCustomElementRenderer {
override fun calcWidthInPixels(inlay: Inlay<*>): Int {
val lines = text.lines()
var maxLen = 0;
for (line in lines) {
val len = (inlay.editor as EditorImpl).getFontMetrics(Font.PLAIN).stringWidth(line)
if (len > maxLen) {
maxLen = len
}
}
return maxLen
}
override fun calcHeightInPixels(inlay: Inlay<*>): Int {
return (inlay.editor as EditorImpl).lineHeight * text.lines().size
}
protected val font: Font
get() {
val editorFont = editor.colorsScheme.getFont(EditorFontType.PLAIN)
return UIUtil.getFontWithFallbackIfNeeded(editorFont, text).deriveFont(editor.colorsScheme.editorFontSize)
}
private fun offsetY(): Int {
val metrics =
FontInfo.getFontMetrics(font, FontInfo.getFontRenderContext(editor.contentComponent))
val fontHeight =
font.createGlyphVector(metrics.fontRenderContext, text).visualBounds.height
val height = (editor.lineHeight + fontHeight) / 2
return ceil(height).toInt()
}
private fun offsetX(): Int {
val currentLine = editor.caretModel.primaryCaret.logicalPosition.line
val currentColumn = editor.caretModel.primaryCaret.logicalPosition.column
val metrics =
FontInfo.getFontMetrics(font, FontInfo.getFontRenderContext(editor.contentComponent))
val fontWidth =
font.createGlyphVector(metrics.fontRenderContext, text).visualBounds.width
val widthBeforeCaret = (editor as EditorImpl).getFontMetrics(Font.PLAIN).stringWidth(
text.substring(0, minOf(currentColumn, text.length))
)
return max(0, widthBeforeCaret - (editor as EditorImpl).scrollingModel.horizontalScrollOffset)
}
override fun paint(inlay: Inlay<*>, g: Graphics, targetRegion: Rectangle, textAttributes: TextAttributes) {
g.color = JBColor.GRAY
g.font = font
var additionalYOffset = -editor.lineHeight;
var isFirstLine = true
for (line in text.lines()) {
g.drawString(
line,
if (isFirstLine) targetRegion.x + offsetX() else targetRegion.x,
targetRegion.y + inlay.editor.ascent + additionalYOffset
)
additionalYOffset += editor.lineHeight
isFirstLine = false
}
}
}

View file

@ -50,13 +50,78 @@ class MessageTypes {
"showToast",
)
// Note: If updating these values, make a corresponding update in
// core/protocol/passThrough.ts
val PASS_THROUGH_TO_WEBVIEW = listOf(
"configUpdate",
"getDefaultModelTitle",
"indexProgress",
"indexProgress", // Codebase
"indexing/statusUpdate", // Docs, etc.
"addContextItem",
"refreshSubmenuItems",
"isContinueInputFocused",
"didChangeAvailableProfiles",
"addContextItem"
"setTTSActive",
"getWebviewHistoryLength",
"getCurrentSessionId",
"signInToControlPlane",
"openDialogMessage",
"docs/suggestions",
)
// Note: If updating these values, make a corresponding update in
// core/protocol/passThrough.ts
val PASS_THROUGH_TO_CORE = listOf(
"abort",
"history/list",
"history/delete",
"history/load",
"history/save",
"devdata/log",
"config/addModel",
"config/addContextProvider",
"config/newPromptFile",
"config/ideSettingsUpdate",
"config/getSerializedProfileInfo",
"config/deleteModel",
"config/listProfiles",
"config/openProfile",
"context/getContextItems",
"context/getSymbolsForFiles",
"context/loadSubmenuItems",
"context/addDocs",
"context/removeDocs",
"context/indexDocs",
"autocomplete/complete",
"autocomplete/cancel",
"autocomplete/accept",
"command/run",
"tts/kill",
"llm/complete",
"llm/streamComplete",
"llm/streamChat",
"llm/listModels",
"streamDiffLines",
"chatDescriber/describe",
"stats/getTokensPerDay",
"stats/getTokensPerModel",
// Codebase
"index/setPaused",
"index/forceReIndex",
"index/forceReIndexFiles",
"index/indexingProgressBarInitialized",
// Docs, etc.
"indexing/reindex",
"indexing/abort",
"indexing/setPaused",
"docs/getSuggestedDocs",
"docs/initStatuses",
//
"completeOnboarding",
"addAutocompleteModel",
"profiles/switch",
"didChangeSelectedProfile",
"tools/call",
)
}
}

View file

@ -549,12 +549,14 @@ class IdeProtocolClient(
val startChar = startOffset - document.getLineStartOffset(startLine)
val endChar = endOffset - document.getLineStartOffset(endLine)
return@runReadAction RangeInFileWithContents(
virtualFile.url, Range(
Position(startLine, startChar),
Position(endLine, endChar)
), selectedText
)
return@runReadAction virtualFile.toUriOrNull()?.let {
RangeInFileWithContents(
it, Range(
Position(startLine, startChar),
Position(endLine, endChar)
), selectedText
)
}
}
return result

View file

@ -5,6 +5,7 @@ import com.github.continuedev.continueintellijextension.services.ContinuePluginS
import com.github.continuedev.continueintellijextension.utils.OS
import com.github.continuedev.continueintellijextension.utils.getMachineUniqueID
import com.github.continuedev.continueintellijextension.utils.getOS
import com.github.continuedev.continueintellijextension.utils.toUriOrNull
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.util.ExecUtil
@ -180,7 +181,7 @@ class IntelliJIDE(
for (workspaceDir in workspaceDirs) {
val dir = VirtualFileManager.getInstance().findFileByUrl(workspaceDir)
if (dir != null) {
val contents = dir.children.map { it.url }
val contents = dir.children.mapNotNull { it.toUriOrNull() }
// Find any .continuerc.json files
for (file in contents) {
@ -261,7 +262,7 @@ class IntelliJIDE(
content
} else {
val file = File(URI(filepath))
if (!file.exists()) return ""
if (!file.exists() || file.isDirectory) return ""
withContext(Dispatchers.IO) {
FileInputStream(file).use { fis ->
val sizeToRead = minOf(100000, file.length()).toInt()
@ -269,6 +270,8 @@ class IntelliJIDE(
val bytesRead = fis.read(buffer, 0, sizeToRead)
if (bytesRead <= 0) return@use ""
String(buffer, 0, bytesRead, Charset.forName("UTF-8"))
// `\r` takes up unnecessary tokens
.lineSequence().joinToString("\n")
}
}
}
@ -307,16 +310,16 @@ class IntelliJIDE(
override suspend fun getOpenFiles(): List<String> {
val fileEditorManager = FileEditorManager.getInstance(project)
return fileEditorManager.openFiles.map { it.url }.toList()
return fileEditorManager.openFiles.mapNotNull { it.toUriOrNull() }.toList()
}
override suspend fun getCurrentFile(): Map<String, Any>? {
val fileEditorManager = FileEditorManager.getInstance(project)
val editor = fileEditorManager.selectedTextEditor
val virtualFile = editor?.document?.let { FileDocumentManager.getInstance().getFile(it) }
return virtualFile?.let {
return virtualFile?.toUriOrNull()?.let {
mapOf(
"path" to it.url,
"path" to it,
"contents" to editor.document.text,
"isUntitled" to false
)
@ -382,7 +385,7 @@ class IntelliJIDE(
problems.add(
Problem(
filepath = psiFile.virtualFile?.url ?: "",
filepath = psiFile.virtualFile?.toUriOrNull() ?: "",
range = Range(
start = Position(
line = startLineNumber,
@ -513,7 +516,7 @@ class IntelliJIDE(
override suspend fun listDir(dir: String): List<List<Any>> {
val files = File(URI(dir)).listFiles()?.map {
listOf(it.name, if (it.isDirectory) FileType.DIRECTORY else FileType.FILE)
listOf(it.name, if (it.isDirectory) FileType.DIRECTORY.value else FileType.FILE.value)
} ?: emptyList()
return files
@ -561,6 +564,6 @@ class IntelliJIDE(
return dirs
}
return listOfNotNull(project.guessProjectDir()?.url).toTypedArray()
return listOfNotNull(project.guessProjectDir()?.toUriOrNull()).toTypedArray()
}
}

View file

@ -179,8 +179,8 @@ class ContinuePluginSelectionListener(
val lineStartOffset = document.getLineStartOffset(lineNumber)
val lineEndOffset = document.getLineEndOffset(lineNumber)
val lineText = document.getText(TextRange(lineStartOffset, lineEndOffset)).trimEnd()
val endOfLinePos = LogicalPosition(lineNumber, lineText.length)
return editor.logicalPositionToXY(endOfLinePos).x
val visualPosition = editor.offsetToVisualPosition(lineStartOffset + lineText.length)
return editor.visualPositionToXY(visualPosition).x
}
val offset = 40

View file

@ -2,6 +2,7 @@ package com.github.continuedev.continueintellijextension.toolWindow
import com.github.continuedev.continueintellijextension.activities.ContinuePluginDisposable
import com.github.continuedev.continueintellijextension.constants.MessageTypes
import com.github.continuedev.continueintellijextension.constants.MessageTypes.Companion.PASS_THROUGH_TO_CORE
import com.github.continuedev.continueintellijextension.factories.CustomSchemeHandlerFactory
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
@ -18,59 +19,6 @@ import org.cef.browser.CefBrowser
import org.cef.handler.CefLoadHandlerAdapter
class ContinueBrowser(val project: Project, url: String) {
private val PASS_THROUGH_TO_CORE = listOf(
"abort",
"history/list",
"history/delete",
"history/load",
"history/save",
"devdata/log",
"config/addModel",
"config/addContextProvider",
"config/newPromptFile",
"config/ideSettingsUpdate",
"config/getSerializedProfileInfo",
"config/deleteModel",
"config/listProfiles",
"config/openProfile",
"context/getContextItems",
"context/getSymbolsForFiles",
"context/loadSubmenuItems",
"context/addDocs",
"context/removeDocs",
"context/indexDocs",
"autocomplete/complete",
"autocomplete/cancel",
"autocomplete/accept",
"command/run",
"tts/kill",
"llm/complete",
"llm/streamComplete",
"llm/streamChat",
"llm/listModels",
"streamDiffLines",
"chatDescriber/describe",
"stats/getTokensPerDay",
"stats/getTokensPerModel",
// Codebase
"index/setPaused",
"index/forceReIndex",
"index/indexingProgressBarInitialized",
// Docs, etc.
"indexing/reindex",
"indexing/abort",
"indexing/setPaused",
"docs/getSuggestedDocs",
"docs/initStatuses",
"docs/getDetails",
//
"completeOnboarding",
"addAutocompleteModel",
"profiles/switch",
"didChangeSelectedProfile",
"tools/call",
)
private fun registerAppSchemeHandler() {
CefApp.getInstance().registerSchemeHandlerFactory(
"http",
@ -83,14 +31,9 @@ class ContinueBrowser(val project: Project, url: String) {
init {
val isOSREnabled = ServiceManager.getService(ContinueExtensionSettings::class.java).continueState.enableOSR
this.browser = JBCefBrowser.createBuilder().setOffScreenRendering(isOSREnabled).build()
browser.jbCefClient.setProperty(
JBCefClient.Properties.JS_QUERY_POOL_SIZE,
JS_QUERY_POOL_SIZE
)
registerAppSchemeHandler()
browser.loadURL(url);
Disposer.register(ContinuePluginDisposable.getInstance(project), browser)

View file

@ -1,5 +1,6 @@
package com.github.continuedev.continueintellijextension.utils
import com.intellij.openapi.vfs.VirtualFile
import java.net.NetworkInterface
import java.util.*
import java.awt.event.KeyEvent.*
@ -77,4 +78,6 @@ fun getMachineUniqueID(): String {
fun uuid(): String {
return UUID.randomUUID().toString()
}
}
fun VirtualFile.toUriOrNull(): String? = fileSystem.getNioPath(this)?.toUri()?.toString()?.removeSuffix("/")

View file

@ -0,0 +1,73 @@
package com.github.continuedev.continueintellijextension.e2e
import com.automation.remarks.junit5.Video
import com.github.continuedev.continueintellijextension.fixtures.dialog
import com.github.continuedev.continueintellijextension.fixtures.idea
import com.github.continuedev.continueintellijextension.fixtures.welcomeFrame
import com.github.continuedev.continueintellijextension.utils.RemoteRobotExtension
import com.github.continuedev.continueintellijextension.utils.StepsLogger
import com.intellij.remoterobot.RemoteRobot
import com.intellij.remoterobot.fixtures.ComponentFixture
import com.intellij.remoterobot.search.locators.byXpath
import com.intellij.remoterobot.steps.CommonSteps
import com.intellij.remoterobot.utils.keyboard
import com.intellij.remoterobot.utils.waitFor
import com.intellij.remoterobot.utils.waitForIgnoringError
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import java.time.Duration.ofMinutes
import java.time.Duration.ofSeconds
@ExtendWith(RemoteRobotExtension::class)
class Autocomplete {
init {
StepsLogger.init()
}
@BeforeEach
fun waitForIde(remoteRobot: RemoteRobot) {
waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") }
}
@AfterEach
fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject()
// @Test
@Video
fun displayCompletion(remoteRobot: RemoteRobot): Unit = with(remoteRobot) {
welcomeFrame {
createNewProjectLink.click()
dialog("New Project") {
findText("Java").click()
checkBox("Add sample code").select()
button("Create").click()
}
}
// Wait for the default "Main.java" tab to load
// Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus.
waitFor(ofSeconds(20)) {
findAll<ComponentFixture>(
byXpath("//div[@accessiblename='Main.java' and @class='EditorTabLabel']")
).isNotEmpty()
}
idea {
with(textEditor()) {
val userMsg = "TEST_USER_MESSAGE_0"
editor.insertTextAtLine(0, 0, userMsg)
editor.clickOnOffset(userMsg.length)
keyboard {
enterText(" ")
}
waitFor(ofSeconds(10)) {
editor.hasText("TEST_LLM_RESPONSE_0")
}
}
}
}
}

View file

@ -0,0 +1,96 @@
/**
* Currently we can't test any actions in the GUI that involve clicks.
* See this open issue for details: https://github.com/JetBrains/intellij-ui-test-robot/issues/491
*/
package com.github.continuedev.continueintellijextension.e2e
import com.automation.remarks.junit5.Video
import com.github.continuedev.continueintellijextension.fixtures.*
import com.github.continuedev.continueintellijextension.utils.RemoteRobotExtension
import com.github.continuedev.continueintellijextension.utils.StepsLogger
import com.github.continuedev.continueintellijextension.utils.getMetaKey
import com.intellij.remoterobot.RemoteRobot
import com.intellij.remoterobot.fixtures.ComponentFixture
import com.intellij.remoterobot.search.locators.byXpath
import com.intellij.remoterobot.steps.CommonSteps
import com.intellij.remoterobot.stepsProcessing.step
import com.intellij.remoterobot.utils.keyboard
import com.intellij.remoterobot.utils.waitFor
import com.intellij.remoterobot.utils.waitForIgnoringError
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import java.awt.event.KeyEvent.*
import java.time.Duration.ofMinutes
import java.time.Duration.ofSeconds
@ExtendWith(RemoteRobotExtension::class)
class GUI {
init {
StepsLogger.init()
}
@BeforeEach
fun waitForIde(remoteRobot: RemoteRobot) {
waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") }
}
@AfterEach
fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject()
// @Test
@Video
fun highlightCode(remoteRobot: RemoteRobot): Unit = with(remoteRobot) {
welcomeFrame {
createNewProjectLink.click()
dialog("New Project") {
findText("Java").click()
checkBox("Add sample code").select()
button("Create").click()
}
}
// Wait for the default "Main.java" tab to load
// Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus.
// If we don't wait for this, clicking on the GUI may fail because a popup displays
// while the `continue_tutorial.java` is loading.
waitFor(ofSeconds(20)) {
findAll<ComponentFixture>(
byXpath("//div[@accessiblename='Main.java' and @class='EditorTabLabel']")
).isNotEmpty()
}
idea {
step("Manually open the webview") {
// Manually open the webview
find<ComponentFixture>(byXpath("//div[@text='Continue']"), ofSeconds((10))).click()
waitFor(ofSeconds(10)) {
browser().isShowing
}
// Arbitrary timeout due to a bug where the webview will refresh
// and clear the editor state on first load
Thread.sleep(5000)
}
step("Verify we can highlight code and add to webview") {
val textToInsert = "Hello world!"
with(textEditor()) {
editor.insertTextAtLine(0, 0, textToInsert)
editor.selectText(textToInsert)
keyboard {
hotKey(getMetaKey(), VK_J)
}
}
waitFor(ofSeconds(10)) {
browser().findElementByContainsText(textToInsert).html.isNotEmpty()
}
}
}
}
}

View file

@ -0,0 +1,85 @@
package com.github.continuedev.continueintellijextension.e2e
import com.automation.remarks.junit5.Video
import com.github.continuedev.continueintellijextension.fixtures.dialog
import com.github.continuedev.continueintellijextension.fixtures.idea
import com.github.continuedev.continueintellijextension.fixtures.welcomeFrame
import com.github.continuedev.continueintellijextension.utils.RemoteRobotExtension
import com.github.continuedev.continueintellijextension.utils.StepsLogger
import com.intellij.remoterobot.RemoteRobot
import com.intellij.remoterobot.fixtures.ComponentFixture
import com.intellij.remoterobot.search.locators.byXpath
import com.intellij.remoterobot.steps.CommonSteps
import com.intellij.remoterobot.stepsProcessing.step
import com.intellij.remoterobot.utils.waitFor
import com.intellij.remoterobot.utils.waitForIgnoringError
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import java.time.Duration.ofMinutes
import java.time.Duration.ofSeconds
@ExtendWith(RemoteRobotExtension::class)
class Onboarding {
init {
StepsLogger.init()
}
@BeforeEach
fun waitForIde(remoteRobot: RemoteRobot) {
waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") }
}
@AfterEach
fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject()
// @Test
@Video
fun onboarding(remoteRobot: RemoteRobot): Unit = with(remoteRobot) {
welcomeFrame {
createNewProjectLink.click()
dialog("New Project") {
findText("Java").click()
checkBox("Add sample code").select()
button("Create").click()
}
}
idea {
// Wait for the default "Main.java" tab to load
// Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus.
// So we need to wait for that to occur, and then focus on "continue_tutorial.java.ft"
waitFor(ofSeconds(20)) {
findAll<ComponentFixture>(
byXpath("//div[@accessiblename='Main.java' and @class='EditorTabLabel']")
).isNotEmpty()
}
// TODO: Need a good way to ensure this is the first test ran in the entire suite
// step("Verify Continue tutorial file is loaded") {
// find<ComponentFixture>(byXpath("//div[@visible_text='continue_tutorial.java']"))
// }
step("Manually open the webview") {
// Manually open the webview
find<ComponentFixture>(byXpath("//div[@text='Continue']"), ofSeconds((10))).click()
waitFor(ofSeconds(10)) {
browser().isShowing
}
}
step("Verify the onboarding card is present") {
waitFor(ofSeconds(30)) {
try {
browser().findElement("//*[@data-testid='onboarding-card']").html.isNotEmpty()
} catch (e: Exception) {
false
}
}
}
}
}
}

View file

@ -1,94 +0,0 @@
package com.github.continuedev.continueintellijextension.e2e
import com.automation.remarks.junit5.Video
import com.github.continuedev.continueintellijextension.pages.dialog
import com.github.continuedev.continueintellijextension.pages.idea
import com.github.continuedev.continueintellijextension.pages.welcomeFrame
import com.github.continuedev.continueintellijextension.utils.RemoteRobotExtension
import com.github.continuedev.continueintellijextension.utils.StepsLogger
import com.github.continuedev.continueintellijextension.utils.getMetaKey
import com.intellij.remoterobot.RemoteRobot
import com.intellij.remoterobot.fixtures.ComponentFixture
import com.intellij.remoterobot.fixtures.JCefBrowserFixture
import com.intellij.remoterobot.search.locators.Locator
import com.intellij.remoterobot.search.locators.byXpath
import com.intellij.remoterobot.steps.CommonSteps
import com.intellij.remoterobot.utils.keyboard
import com.intellij.remoterobot.utils.waitFor
import com.intellij.remoterobot.utils.waitForIgnoringError
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import java.awt.event.KeyEvent.*
import java.time.Duration.ofMinutes
import java.time.Duration.ofSeconds
@ExtendWith(RemoteRobotExtension::class)
class TutorialTest {
init {
StepsLogger.init()
}
@BeforeEach
fun waitForIde(remoteRobot: RemoteRobot) {
waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") }
}
@AfterEach
fun closeProject(remoteRobot: RemoteRobot) = CommonSteps(remoteRobot).closeProject()
@Test
@Video
fun completeTutorial(remoteRobot: RemoteRobot) = with(remoteRobot) {
welcomeFrame {
createNewProjectLink.click()
dialog("New Project") {
findText("Java").click()
checkBox("Add sample code").select()
button("Create").click()
}
}
// Wait for the default "Main.java" tab to load
// Our "continue_tutorial.java" tab loads first, but then "Main.java" takes focus.
// So we need to wait for that to occur, and then focus on "continue_tutorial.java"
waitFor(ofSeconds(20)) {
findAll<ComponentFixture>(
byXpath("//div[@accessiblename='Main.java' and @class='EditorTabLabel']")
).isNotEmpty()
}
val tutorialEditorTabLocator: Locator =
byXpath("//div[@accessiblename='continue_tutorial.java' and @class='EditorTabLabel']")
val tutorialEditorTab: ComponentFixture =
remoteRobot.find(ComponentFixture::class.java, tutorialEditorTabLocator)
tutorialEditorTab.click()
// Manually open the webview
find<ComponentFixture>(byXpath("//div[@text='Continue']")).click()
// Arbitrary sleep while we wait for the webview to load
Thread.sleep(10000)
val textToInsert = "Hello world!"
idea {
with(textEditor()) {
editor.insertTextAtLine(0, 0, textToInsert)
editor.selectText(textToInsert)
keyboard {
hotKey(getMetaKey(), VK_J)
}
}
}
// TODO: locator needs to be OS aware
// https://github.com/JetBrains/intellij-ui-test-robot/blob/139a05eb99e9a49f13605626b81ad9864be23c96/remote-fixtures/src/main/kotlin/com/intellij/remoterobot/fixtures/CommonContainerFixture.kt#L203
val jcefBrowser = find<JCefBrowserFixture>(JCefBrowserFixture.macLocator)
assert(jcefBrowser.getDom().isNotEmpty()) { "JCEF browser not found or empty" }
val codeSnippetText = jcefBrowser.findElementByContainsText(textToInsert)
assert(codeSnippetText.html.isNotEmpty()) { "Failed to find code snippet in webview" }
}
}

View file

@ -0,0 +1,43 @@
{
"ui": {
"displayRawMarkdown": false
},
"models": [
{
"title": "TEST LLM",
"provider": "test",
"model": "this field is not used"
},
{
"title": "Mock",
"provider": "mock",
"model": "this field is not used"
}
],
"analytics": {
"provider": "continue-proxy"
},
"tabAutocompleteModel": {
"title": "TEST LLM",
"provider": "test",
"model": "this field is not used"
},
"tabAutocompleteOptions": {
"useCache": false
},
"contextProviders": [
{
"name": "docs"
},
{
"name": "diff"
},
{
"name": "url"
},
{
"name": "folder"
}
],
"docs": []
}

View file

@ -1,4 +1,4 @@
package com.github.continuedev.continueintellijextension.pages
package com.github.continuedev.continueintellijextension.fixtures
/*
* Source: https://github.com/JetBrains/intellij-ui-test-robot/blob/139a05eb99e9a49f13605626b81ad9864be23c96/ui-test-example/src/test/kotlin/org/intellij/examples/simple/plugin/pages/DialogFixture.kt

View file

@ -1,4 +1,4 @@
package com.github.continuedev.continueintellijextension.pages
package com.github.continuedev.continueintellijextension.fixtures
/*
* Source: https://github.com/JetBrains/intellij-ui-test-robot/blob/139a05eb99e9a49f13605626b81ad9864be23c96/ui-test-example/src/test/kotlin/org/intellij/examples/simple/plugin/pages/IdeaFrame.kt

View file

@ -1,4 +1,4 @@
package com.github.continuedev.continueintellijextension.pages
package com.github.continuedev.continueintellijextension.fixtures
/*
* Source: https://github.com/JetBrains/intellij-ui-test-robot/blob/139a05eb99e9a49f13605626b81ad9864be23c96/ui-test-example/src/test/kotlin/org/intellij/examples/simple/plugin/pages/WelcomeFrame.kt

View file

@ -5,6 +5,6 @@
},
"extends": ["../../.eslintrc.shared.json"],
"rules": {
"@typescript-eslint/naming-convention": "warn"
"@typescript-eslint/naming-convention": "off"
}
}

Some files were not shown because too many files have changed in this diff Show more