Merge branch 'preview' into nate/refactor-core

This commit is contained in:
Nate Sesti 2024-05-18 17:27:21 -07:00
commit 696a955aee
82 changed files with 53811 additions and 24278 deletions

4
.vscode/tasks.json vendored
View file

@ -110,8 +110,8 @@
{
"label": "install-all-dependencies",
"type": "shell",
"windows": { "command": "./install-dependencies.ps1" },
"command": "./install-dependencies.sh",
"windows": { "command": "./scripts/install-dependencies.ps1" },
"command": "./scripts/install-dependencies.sh",
"problemMatcher": [] // Empty so users are not prompted to select progress reporting
},
//

View file

@ -58,15 +58,14 @@ Continue is continuously improving, but a feature isn't complete until it is ref
#### Pre-requisites
- You should have Node.js version 20.11.0 (LTS) or higher installed. You can get it on [nodejs.org](https://nodejs.org/en/download) or, if you are using NVM (Node Version Manager), you can set the correct version of Node.js for this project by running the following command in the root of the project:
- Continue uses `pnpm` to manage node_modules. You can install `pnpm` globally with `npm install -g pnpm`, or another method described in [their docs](https://pnpm.io/installation#using-npm).
#### VS Code
You should have Node.js version 20.11.0 (LTS) or higher installed. You can get it on [nodejs.org](https://nodejs.org/en/download) or, if you are using NVM (Node Version Manager), you can set the correct version of Node.js for this project by running the following command in the root of the project:
```bash
nvm use
```
#### VS Code
1. Clone and open in VS Code the Continue repo `https://github.com/continuedev/continue`
2. Open the VS Code command pallet (`cmd/ctrl+shift+p`) and select `Tasks: Run Task` and then select `install-all-dependencies`
@ -80,7 +79,7 @@ nvm use
1. The new VS Code window with the extension is referred to as the _Host VS Code_
2. The window you started debugging from is referred to as the _Main VS Code_
4. To package the extension, run `pnpm package` in the `extensions/vscode` directory. This will generate `extensions/vscode/build/continue-patch.vsix`, which you can install by right-clicking and selecting "Install Extension VSIX".
4. To package the extension, run `npm package` in the `extensions/vscode` directory. This will generate `extensions/vscode/build/continue-patch.vsix`, which you can install by right-clicking and selecting "Install Extension VSIX".
> Note: Breakpoints can be used in both the `core` and `extensions/vscode` folders while debugging, but are not currently supported inside of `gui` code. Hot-reloading is enabled with Vite, so if you make any changes to the `gui`, they should be automatically reflected without rebuilding. Similarly, any changes to `core` or `extensions/vscode` will be automatically included by just reloading the _Host VS Code_ window with cmd/ctrl+shift+p "Reload Window".
@ -89,7 +88,7 @@ nvm use
Pre-requisite: You should use the Intellij IDE, which can be downloaded [here](https://www.jetbrains.com/idea/download). Either Ultimate or Community (free) will work. Continue is built with JDK version 19.
1. Clone the repository
2. Run `install-dependencies.sh` or `install-dependencies.ps1` on Windows
2. Run `scripts/install-dependencies.sh` or `scripts/install-dependencies.ps1` on Windows
3. Run `cd extensions/vscode && node scripts/prepackage.js` (this will copy over the built React application to the proper JetBrains directory)
4. Select the "Run Plugin" Gradle configuration and click the "Run" or "Debug" button
5. To package the extension, choose the "Build Plugin" Gradle configuration

View file

@ -1,7 +1,18 @@
const esbuild = require("esbuild");
const { execSync } = require("child_process");
const fs = require("fs");
const path = require("path");
const ncp = require("ncp").ncp;
const { rimrafSync } = require("rimraf");
function execCmdSync(cmd) {
try {
execSync(cmd);
} catch (err) {
console.error(`Error executing command '${cmd}': `, err.output.toString());
process.exit(1);
}
}
const esbuildOutputFile = "out/index.js";
const platforms = ["darwin", "linux", "win32"];
@ -9,6 +20,10 @@ const architectures = ["x64", "arm64"];
let targets = platforms.flatMap((platform) =>
architectures.map((arch) => `${platform}-${arch}`),
);
const assetBackups = [
"node_modules/win-ca/lib/crypt32-ia32.node.bak",
"node_modules/win-ca/lib/crypt32-x64.node.bak"
];
let esbuildOnly = false;
for (let i = 2; i < process.argv.length; i++) {
@ -28,9 +43,64 @@ const targetToLanceDb = {
"win32-x64": "@lancedb/vectordb-win32-x64-msvc",
};
async function installNodeModuleInTempDirAndCopyToCurrent(package, toCopy) {
console.log(`Copying ${package} to ${toCopy}`);
// This is a way to install only one package without npm trying to install all the dependencies
// Create a temporary directory for installing the package
const adjustedName = toCopy.replace(/^@/, "").replace("/", "-");
const tempDir = path.join(
__dirname,
"tmp",
`continue-node_modules-${adjustedName}`,
);
const currentDir = process.cwd();
// Remove the dir we will be copying to
rimrafSync(`node_modules/${toCopy}`);
// Ensure the temporary directory exists
fs.mkdirSync(tempDir, { recursive: true });
try {
// Move to the temporary directory
process.chdir(tempDir);
// Initialize a new package.json and install the package
execCmdSync(`npm init -y && npm i -f ${package} --no-save`);
console.log(
`Contents of: ${package}`,
fs.readdirSync(path.join(tempDir, "node_modules", toCopy)),
);
// Copy the installed package back to the current directory
await new Promise((resolve, reject) => {
ncp(
path.join(tempDir, "node_modules", toCopy),
path.join(currentDir, "node_modules", toCopy),
{ dereference: true },
(error) => {
if (error) {
console.error(`[error] Error copying ${package} package`, error);
reject(error);
} else {
resolve();
}
},
);
});
} finally {
// Clean up the temporary directory
rimrafSync(tempDir);
// Return to the original directory
process.chdir(currentDir);
}
}
(async () => {
// console.log("[info] Building with ncc...");
// execSync(`npx ncc build src/index.ts -o out`);
// execCmdSync(`npx ncc build src/index.ts -o out`);
// Copy node_modules for pre-built binaries
const DYNAMIC_IMPORTS = [
@ -80,10 +150,20 @@ const targetToLanceDb = {
for (const target of targets) {
if (targetToLanceDb[target]) {
console.log(`[info] Downloading ${target}...`);
execSync(`npm install -f ${targetToLanceDb[target]} --no-save`);
await installNodeModuleInTempDirAndCopyToCurrent(
targetToLanceDb[target],
"@lancedb",
);
}
}
console.log("[info] Cleaning up artifacts from previous builds...");
// delete asset backups generated by previous pkg invocations, if present
for (const assetPath of assetBackups) {
fs.rmSync(assetPath, {force: true});
}
console.log("[info] Building with esbuild...");
// Bundles the extension into one file
await esbuild.build({
@ -120,7 +200,7 @@ const targetToLanceDb = {
const targetDir = `bin/${target}`;
fs.mkdirSync(targetDir, { recursive: true });
console.log(`[info] Building ${target}...`);
execSync(
execCmdSync(
`npx pkg --no-bytecode --public-packages "*" --public pkgJson/${target} --out-path ${targetDir}`,
);
@ -128,8 +208,8 @@ const targetToLanceDb = {
const downloadUrl = `https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v6-${
target === "win32-arm64" ? "win32-ia32" : target
}.tar.gz`;
execSync(`curl -L -o ${targetDir}/build.tar.gz ${downloadUrl}`);
execSync(`cd ${targetDir} && tar -xvzf build.tar.gz`);
execCmdSync(`curl -L -o ${targetDir}/build.tar.gz ${downloadUrl}`);
execCmdSync(`cd ${targetDir} && tar -xvzf build.tar.gz`);
fs.copyFileSync(
`${targetDir}/build/Release/node_sqlite3.node`,
`${targetDir}/node_sqlite3.node`,
@ -143,10 +223,10 @@ const targetToLanceDb = {
// Download and unzip prebuilt esbuild binary for the target
console.log(`[info] Downloading esbuild for ${target}...`);
// Version is pinned to 0.19.11 in package.json to make sure that they match
execSync(
execCmdSync(
`curl -o ${targetDir}/esbuild.tgz https://registry.npmjs.org/@esbuild/${target}/-/${target}-0.19.11.tgz`,
);
execSync(`tar -xzvf ${targetDir}/esbuild.tgz -C ${targetDir}`);
execCmdSync(`tar -xzvf ${targetDir}/esbuild.tgz -C ${targetDir}`);
if (target.startsWith("win32")) {
fs.cpSync(`${targetDir}/package/esbuild.exe`, `${targetDir}/esbuild.exe`);
} else {
@ -158,7 +238,7 @@ const targetToLanceDb = {
recursive: true,
});
}
// execSync(
// execCmdSync(
// `npx pkg out/index.js --target node18-darwin-arm64 --no-bytecode --public-packages "*" --public -o bin/pkg`
// );
console.log("[info] Done!");

11932
binary/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -35,6 +35,7 @@
"@vercel/ncc": "^0.38.1",
"esbuild": "0.19.11",
"pkg": "^5.8.1",
"rimraf": "^5.0.7",
"typescript": "^5.3.3"
},
"dependencies": {
@ -48,7 +49,7 @@
"posthog-node": "^3.6.3",
"system-ca": "^1.0.2",
"uuid": "^9.0.1",
"vectordb": "^0.4.10",
"vectordb": "^0.4.20",
"win-ca": "^3.5.1"
}
}

5758
binary/pnpm-lock.yaml generated

File diff suppressed because it is too large Load diff

View file

@ -12,6 +12,30 @@ ollama run starcoder:3b
Once it has been downloaded, you should begin to see completions in VS Code.
## Setting up with LM Studio
You can also set up tab-autocomplete with a local LM Studio instance by following these steps:
1. Download the latest version of LM Studio from [here](https://lmstudio.ai/)
2. Download a model (e.g. search for `second-state/StarCoder2-3B-GGUF` and choose one of the options there)
3. Go to the server section (button is on the left), select your model from the dropdown at the top, and click "Start Server"
4. Go to the "My Models" section (button is on the left), find your selected model, and copy the name the path (example: `second-state/StarCoder2-3B-GGUF/starcoder2-3b-Q8_0.gguf`); this will be used as the "model" attribute in Continue
5. Go to Continue and modify the configurations for a [custom model](#setting-up-a-custom-model)
6. Set the "provider" to `lmstudio` and the "model" to the path copied earlier
Example:
```json title=~/.continue/config.json
{
"tabAutocompleteModel": {
"title": "Starcoder2 3b",
"model": "second-state/StarCoder2-3B-GGUF/starcoder2-3b-Q8_0.gguf",
"provider": "lmstudio",
},
...
}
```
## Setting up a custom model
All of the configuration options available for chat models are available to use for tab-autocomplete. For example, if you wanted to use a remote vLLM instance you would edit your `config.json` like this (note that it is not inside the models array), filling in the correct model name and vLLM endpoint:

View file

@ -30,7 +30,9 @@ export async function* noFirstCharNewline(stream: AsyncGenerator<string>) {
for await (const char of stream) {
if (first) {
first = false;
if (char === "\n") {return;}
if (char === "\n") {
return;
}
}
yield char;
}
@ -48,9 +50,9 @@ export async function* stopOnUnmatchedClosingBracket(
): AsyncGenerator<string> {
const stack: string[] = [];
for (let i = 0; i < suffix.length; i++) {
if (suffix[i] === " ") {continue;}
if (suffix[i] === " ") continue;
const openBracket = BRACKETS_REVERSE[suffix[i]];
if (!openBracket) {break;}
if (!openBracket) break;
stack.unshift(openBracket);
}

View file

@ -1,32 +1,36 @@
import { ContextProviderWithParams, SerializedContinueConfig } from "../index.js";
import {
ContextProviderWithParams,
SerializedContinueConfig,
} from "../index.js";
export const defaultConfig: SerializedContinueConfig = {
models: [
{
title: "GPT-4-Turbo (Free Trial)",
provider: "free-trial",
model: "gpt-4-turbo",
systemMessage:
"You are an expert software developer. You give helpful and concise responses.",
},
{
title: "Llama3 70b (Free Trial)",
provider: "free-trial",
model: "llama3-70b",
systemMessage:
"You are an expert software developer. You give helpful and concise responses. Whenever you write a code block you include the language after the opening ticks.",
},
{
title: "GPT-4o (Free Trial)",
provider: "free-trial",
model: "gpt-4o",
systemMessage:
"You are an expert software developer. You give helpful and concise responses.",
},
{
title: "Claude 3 Sonnet (Free Trial)",
provider: "free-trial",
model: "claude-3-sonnet-20240229",
},
{
title: "GPT-3.5-Turbo (Free Trial)",
provider: "free-trial",
model: "gpt-3.5-turbo",
},
{
title: "Gemini Pro (Free Trial)",
provider: "free-trial",
model: "gemini-pro",
},
{
title: "Mixtral (Free Trial)",
provider: "free-trial",
model: "mistral-8x7b",
},
],
customCommands: [
{
@ -46,29 +50,30 @@ export const defaultConfig: SerializedContinueConfig = {
export const defaultConfigJetBrains: SerializedContinueConfig = {
models: [
{
title: "Claude 3 Sonnet (Free Trial)",
title: "GPT-4-Turbo (Free Trial)",
provider: "free-trial",
model: "claude-3-sonnet-20240229",
model: "gpt-4-turbo",
systemMessage:
"You are an expert software developer. You give helpful and concise responses.",
},
{
title: "Llama3 70b (Free Trial)",
provider: "free-trial",
model: "llama3-70b",
systemMessage:
"You are an expert software developer. You give helpful and concise responses. Whenever you write a code block you include the language after the opening ticks.",
},
{
title: "GPT-4o (Free Trial)",
provider: "free-trial",
model: "gpt-4o",
systemMessage:
"You are an expert software developer. You give helpful and concise responses.",
},
{
title: "GPT-3.5-Turbo (Free Trial)",
title: "Claude 3 Sonnet (Free Trial)",
provider: "free-trial",
model: "gpt-3.5-turbo",
},
{
title: "Gemini Pro (Free Trial)",
provider: "free-trial",
model: "gemini-pro",
},
{
title: "Mixtral (Free Trial)",
provider: "free-trial",
model: "mistral-8x7b",
model: "claude-3-sonnet-20240229",
},
],
customCommands: [

View file

@ -66,7 +66,7 @@ export class ConfigHandler {
const uniqueId = await this.ide.getUniqueId();
this.savedConfig = await loadFullConfigNode(
this.ide.readFile.bind(this.ide),
this.ide,
workspaceConfigs,
await this.ideSettingsPromise,
ideInfo.ideType,

View file

@ -19,6 +19,7 @@ import {
CustomLLM,
EmbeddingsProviderDescription,
IContextProvider,
IDE,
IdeType,
ModelDescription,
Reranker,
@ -49,6 +50,7 @@ import {
defaultSlashCommandsJetBrains,
defaultSlashCommandsVscode,
} from "./default.js";
import { getPromptFiles, slashCommandFromPromptFile } from "./promptFile.js";
const { execSync } = require("child_process");
function resolveSerializedConfig(filepath: string): SerializedContinueConfig {
@ -130,9 +132,10 @@ function loadSerializedConfig(
return config;
}
function serializedToIntermediateConfig(
async function serializedToIntermediateConfig(
initial: SerializedContinueConfig,
): Config {
ide: IDE,
): Promise<Config> {
const slashCommands: SlashCommand[] = [];
for (const command of initial.slashCommands || []) {
const newCommand = slashCommandFromDescription(command);
@ -144,6 +147,20 @@ function serializedToIntermediateConfig(
slashCommands.push(slashFromCustomCommand(command));
}
const workspaceDirs = await ide.getWorkspaceDirs();
const promptFiles = (
await Promise.all(
workspaceDirs.map((dir) =>
getPromptFiles(ide, path.join(dir, ".prompts")),
),
)
)
.flat()
.filter(({ path }) => path.endsWith(".prompt"));
for (const file of promptFiles) {
slashCommands.push(slashCommandFromPromptFile(file.path, file.content));
}
const config: Config = {
...initial,
slashCommands,
@ -168,7 +185,7 @@ function isContextProviderWithParams(
/** Only difference between intermediate and final configs is the `models` array */
async function intermediateToFinalConfig(
config: Config,
readFile: (filepath: string) => Promise<string>,
ide: IDE,
ideSettings: IdeSettings,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
@ -179,7 +196,7 @@ async function intermediateToFinalConfig(
if (isModelDescription(desc)) {
const llm = await llmFromDescription(
desc,
readFile,
ide.readFile.bind(ide),
uniqueId,
ideSettings,
writeLog,
@ -201,7 +218,7 @@ async function intermediateToFinalConfig(
model: modelName,
title: `${llm.title} - ${modelName}`,
},
readFile,
ide.readFile.bind(ide),
uniqueId,
ideSettings,
writeLog,
@ -261,7 +278,7 @@ async function intermediateToFinalConfig(
if (isModelDescription(config.tabAutocompleteModel)) {
autocompleteLlm = await llmFromDescription(
config.tabAutocompleteModel,
readFile,
ide.readFile.bind(ide),
uniqueId,
ideSettings,
writeLog,
@ -450,7 +467,7 @@ async function buildConfigTs() {
}
async function loadFullConfigNode(
readFile: (filepath: string) => Promise<string>,
ide: IDE,
workspaceConfigs: ContinueRcJson[],
ideSettings: IdeSettings,
ideType: IdeType,
@ -458,7 +475,7 @@ async function loadFullConfigNode(
writeLog: (log: string) => Promise<void>,
): Promise<ContinueConfig> {
let serialized = loadSerializedConfig(workspaceConfigs, ideSettings, ideType);
let intermediate = serializedToIntermediateConfig(serialized);
let intermediate = await serializedToIntermediateConfig(serialized, ide);
const configJsContents = await buildConfigTs();
if (configJsContents) {
@ -495,7 +512,7 @@ async function loadFullConfigNode(
const finalConfig = await intermediateToFinalConfig(
intermediate,
readFile,
ide,
ideSettings,
uniqueId,
writeLog,

View file

@ -7,29 +7,30 @@ export function setupOptimizedMode(
...config,
models: [
{
title: "Claude 3 Sonnet (Free Trial)",
title: "GPT-4-Turbo (Free Trial)",
provider: "free-trial",
model: "claude-3-sonnet-20240229",
model: "gpt-4-turbo",
systemMessage:
"You are an expert software developer. You give helpful and concise responses.",
},
{
title: "Llama3 70b (Free Trial)",
provider: "free-trial",
model: "llama3-70b",
systemMessage:
"You are an expert software developer. You give helpful and concise responses. Whenever you write a code block you include the language after the opening ticks.",
},
{
title: "GPT-4o (Free Trial)",
provider: "free-trial",
model: "gpt-4o",
systemMessage:
"You are an expert software developer. You give helpful and concise responses.",
},
{
title: "GPT-3.5-Turbo (Free Trial)",
title: "Claude 3 Sonnet (Free Trial)",
provider: "free-trial",
model: "gpt-3.5-turbo",
},
{
title: "Gemini Pro (Free Trial)",
provider: "free-trial",
model: "gemini-pro",
},
{
title: "Mixtral (Free Trial)",
provider: "free-trial",
model: "mistral-8x7b",
model: "claude-3-sonnet-20240229",
},
],
tabAutocompleteModel: {
@ -93,3 +94,24 @@ export function setupLocalMode(
reranker: undefined,
};
}
export function setupLocalAfterFreeTrial(
config: SerializedContinueConfig,
): SerializedContinueConfig {
return {
...config,
models: [
{
title: "Llama 3",
provider: "ollama",
model: "llama3",
},
{
title: "Ollama",
provider: "ollama",
model: "AUTODETECT",
},
...config.models.filter((model) => model.provider !== "free-trial"),
],
};
}

103
core/config/promptFile.ts Normal file
View file

@ -0,0 +1,103 @@
import * as YAML from "yaml";
import { IDE, SlashCommand } from "..";
import { stripImages } from "../llm/countTokens";
import { renderTemplatedString } from "../llm/llms";
import { getBasename } from "../util";
export async function getPromptFiles(
ide: IDE,
dir: string,
): Promise<{ path: string; content: string }[]> {
const paths = await ide.listWorkspaceContents(dir);
const results = paths.map(async (path) => {
const content = await ide.readFile(path);
return { path, content };
});
return Promise.all(results);
}
export function slashCommandFromPromptFile(
path: string,
content: string,
): SlashCommand {
let [preambleRaw, prompt] = content.split("\n---\n");
if (prompt === undefined) {
prompt = preambleRaw;
preambleRaw = "";
}
const preamble = YAML.parse(preambleRaw) ?? {};
const name = preamble.name ?? getBasename(path).split(".prompt")[0];
const description = preamble.description ?? name;
let systemMessage: string | undefined = undefined;
if (prompt.includes("<system>")) {
systemMessage = prompt.split("<system>")[1].split("</system>")[0].trim();
prompt = prompt.split("</system>")[1].trim();
}
return {
name,
description,
run: async function* ({ input, llm, history, ide }) {
// Remove slash command prefix from input
let userInput = input;
if (userInput.startsWith(`/${name}`)) {
userInput = userInput
.slice(name.length + 1, userInput.length)
.trimStart();
}
// Render prompt template
const diff = await ide.getDiff();
const promptUserInput = await renderTemplatedString(
prompt,
ide.readFile.bind(ide),
{ input: userInput, diff },
);
const messages = [...history];
// Find the last chat message with this slash command and replace it with the user input
for (let i = messages.length - 1; i >= 0; i--) {
const { role, content } = messages[i];
if (role !== "user") {
continue;
}
if (
Array.isArray(content) &&
content.some((part) => part.text?.startsWith(`/${name}`))
) {
messages[i] = {
...messages[i],
content: content.map((part) => {
return part.text?.startsWith(`/${name}`)
? { ...part, text: promptUserInput }
: part;
}),
};
break;
} else if (
typeof content === "string" &&
content.startsWith(`/${name}`)
) {
messages[i] = { ...messages[i], content: promptUserInput };
break;
}
}
// System message
if (systemMessage) {
if (messages[0]?.role === "system") {
messages[0].content = systemMessage;
} else {
messages.unshift({ role: "system", content: systemMessage });
}
}
for await (const chunk of llm.streamChat(messages)) {
yield stripImages(chunk.content);
}
},
};
}

View file

@ -437,10 +437,6 @@ declare global {
description: string;
params?: { [key: string]: any };
run: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>;
// If true, this command will be run in NodeJs and have access to the filesystem and other Node-only APIs
// You must make sure to dynamically import any Node-only dependencies in your command so that it doesn't break in the browser
runInNodeJs?: boolean;
}
// Config

View file

@ -32,13 +32,18 @@ export function addModel(model: ModelDescription) {
export function addOpenAIKey(key: string) {
editConfigJson((config) => {
config.models = config.models.map((m: ModelDescription) => {
if (m.provider === "free-trial") {
m.apiKey = key;
m.provider = "openai";
}
return m;
});
config.models = config.models
.filter(
(model) =>
model.provider !== "free-trial" || model.model.startsWith("gpt"),
)
.map((m: ModelDescription) => {
if (m.provider === "free-trial") {
m.apiKey = key;
m.provider = "openai";
}
return m;
});
return config;
});
}

View file

@ -1,10 +1,10 @@
import { BaseContextProvider } from "../index.js";
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
} from "../../index.js";
import { getBasename } from "../../util/index.js";
import { BaseContextProvider } from "../index.js";
class CurrentFileContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {

View file

@ -126,9 +126,9 @@ export async function retrieveContextItemsFromEmbeddings(
);
results.sort(
(a, b) => scores[results.indexOf(b)] - scores[results.indexOf(a)],
(a, b) => scores[results.indexOf(a)] - scores[results.indexOf(b)],
);
results = results.slice(0, nFinal);
results = results.slice(-nFinal);
}
if (results.length === 0) {

7
core/index.d.ts vendored
View file

@ -37,7 +37,7 @@ export interface Chunk extends ChunkWithoutID {
export interface IndexingProgressUpdate {
progress: number;
desc: string;
status: "starting" | "indexing" | "done" | "failed" | "paused";
status: "starting" | "indexing" | "done" | "failed" | "paused" | "disabled";
}
export type PromptTemplate =
@ -452,10 +452,6 @@ export interface SlashCommand {
description: string;
params?: { [key: string]: any };
run: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>;
// If true, this command will be run in NodeJs and have access to the filesystem and other Node-only APIs
// You must make sure to dynamically import any Node-only dependencies in your command so that it doesn't break in the browser
runInNodeJs?: boolean;
}
// Config
@ -715,6 +711,7 @@ export interface TabAutocompleteOptions {
export interface ContinueUIConfig {
codeBlockToolbarPosition?: "top" | "bottom";
fontSize?: number;
}
interface ContextMenuConfig {

View file

@ -53,12 +53,28 @@ export class CodebaseIndexer {
abortSignal: AbortSignal,
): AsyncGenerator<IndexingProgressUpdate> {
if (workspaceDirs.length === 0) {
yield {
progress: 0,
desc: "Nothing to index",
status: "disabled",
};
return;
}
const config = await this.configHandler.loadConfig();
if (config.disableIndexing) {
yield {
progress: 0,
desc: "Indexing is disabled in the config.json",
status: "disabled",
};
return;
} else {
yield {
progress: 0,
desc: "Starting indexing",
status: "starting",
};
}
const indexesToBuild = await this.getIndexesToBuild();
@ -111,12 +127,20 @@ export class CodebaseIndexer {
yield {
progress: 1,
desc: "Indexing cancelled",
status: "failed",
status: "disabled",
};
return;
}
while (this.pauseToken.paused) {
await new Promise((resolve) => setTimeout(resolve, 100));
if (this.pauseToken.paused) {
yield {
progress: completedDirs / workspaceDirs.length,
desc: "Paused",
status: "paused",
};
while (this.pauseToken.paused) {
await new Promise((resolve) => setTimeout(resolve, 100));
}
}
yield {

View file

@ -7,20 +7,22 @@ const DEFAULT_ARGS = {
temperature: DEFAULT_TEMPERATURE,
};
const GPT_4_CTX_LEN = 4096;
const CONTEXT_LENGTH_FOR_MODEL: { [name: string]: number } = {
"gpt-3.5-turbo": 4096,
"gpt-3.5-turbo-0613": 4096,
"gpt-3.5-turbo-16k": 16_384,
"gpt-4": 8192,
"gpt-35-turbo-16k": 16_384,
"gpt-35-turbo-0613": 4096,
"gpt-35-turbo": 4096,
"gpt-4-32k": 32_768,
"gpt-4-turbo-preview": 128_000,
"gpt-4o": 128_000,
"gpt-4-vision": 128_000,
"gpt-4-0125-preview": 128_000,
"gpt-4-1106-preview": 128_000,
"gpt-4": GPT_4_CTX_LEN,
"gpt-4-32k": GPT_4_CTX_LEN,
"gpt-4-turbo-preview": GPT_4_CTX_LEN,
"gpt-4o": GPT_4_CTX_LEN,
"gpt-4-vision": GPT_4_CTX_LEN,
"gpt-4-0125-preview": GPT_4_CTX_LEN,
"gpt-4-1106-preview": GPT_4_CTX_LEN,
};
const TOKEN_BUFFER_FOR_SAFETY = 350;
@ -35,6 +37,5 @@ export {
DEFAULT_MAX_TOKENS,
MAX_CHUNK_SIZE,
PROXY_URL,
TOKEN_BUFFER_FOR_SAFETY
TOKEN_BUFFER_FOR_SAFETY,
};

View file

@ -58,8 +58,9 @@ function countTokens(
? countImageTokens(part)
: encoding.encode(part.text ?? "", "all", []).length;
}, 0);
} else {
return encoding.encode(content ?? "", "all", []).length;
}
return encoding.encode(content, "all", []).length;
}
function flattenMessages(msgs: ChatMessage[]): ChatMessage[] {

View file

@ -217,14 +217,25 @@ ${settings}
${prompt}`;
}
private _logTokensGenerated(model: string, completion: string) {
const tokens = this.countTokens(completion);
private _logTokensGenerated(
model: string,
prompt: string,
completion: string,
) {
let promptTokens = this.countTokens(prompt);
let generatedTokens = this.countTokens(completion);
Telemetry.capture("tokens_generated", {
model: model,
provider: this.providerName,
tokens: tokens,
promptTokens: promptTokens,
generatedTokens: generatedTokens,
});
DevDataSqliteDb.logTokensGenerated(model, this.providerName, tokens);
DevDataSqliteDb.logTokensGenerated(
model,
this.providerName,
promptTokens,
generatedTokens,
);
}
fetch(url: RequestInfo | URL, init?: RequestInit): Promise<Response> {
@ -335,7 +346,7 @@ ${prompt}`;
yield chunk;
}
this._logTokensGenerated(completionOptions.model, completion);
this._logTokensGenerated(completionOptions.model, prompt, completion);
if (log && this.writeLog) {
await this.writeLog(`Completion:\n\n${completion}\n\n`);
@ -370,7 +381,7 @@ ${prompt}`;
const completion = await this._complete(prompt, completionOptions);
this._logTokensGenerated(completionOptions.model, completion);
this._logTokensGenerated(completionOptions.model, prompt, completion);
if (log && this.writeLog) {
await this.writeLog(`Completion:\n\n${completion}\n\n`);
}
@ -432,7 +443,7 @@ ${prompt}`;
throw error;
}
this._logTokensGenerated(completionOptions.model, completion);
this._logTokensGenerated(completionOptions.model, prompt, completion);
if (log && this.writeLog) {
await this.writeLog(`Completion:\n\n${completion}\n\n`);
}

View file

@ -93,8 +93,10 @@ class FreeTrial extends BaseLLM {
async listModels(): Promise<string[]> {
return [
"llama3-70b",
"gpt-3.5-turbo",
"gpt-4o",
"gpt-4-turbo",
"gemini-1.5-pro-latest",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",

View file

@ -142,14 +142,13 @@ export async function llmFromDescription(
};
if (desc.provider === "continue-proxy") {
options = {
...options,
apiBase: new URL(
options.apiKey = ideSettings.userToken;
if (ideSettings.remoteConfigServerUrl) {
options.apiBase = new URL(
"/proxy/v1",
ideSettings.remoteConfigServerUrl,
).toString(),
apiKey: ideSettings.userToken,
};
).toString();
}
}
return new cls(options);

View file

@ -1,8 +1,11 @@
import { ModelProvider } from "../../..";
import { LLMOptions, ModelProvider } from "../../..";
import OpenAI from "../OpenAI";
class ContinueProxy extends OpenAI {
static providerName: ModelProvider = "continue-proxy";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "http://localhost:3000/proxy/v1",
};
}
export default ContinueProxy;

10626
core/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -18,7 +18,7 @@
"@types/jquery": "^3.5.29",
"@types/mustache": "^4.2.5",
"@types/uuid": "^9.0.7",
"esbuild": "^0.19.11",
"esbuild": "0.17.19",
"eslint": "^8",
"eslint-plugin-import": "^2.29.1",
"eslint-plugin-require-extensions": "^0.1.3",
@ -65,8 +65,9 @@
"sqlite3": "^5.1.7",
"tree-sitter-wasms": "^0.1.11",
"uuid": "^9.0.1",
"vectordb": "^0.4.12",
"web-tree-sitter": "^0.21.0"
"vectordb": "^0.4.20",
"web-tree-sitter": "^0.21.0",
"yaml": "^2.4.2"
},
"puppeteer": {
"chromium_revision": "119.0.6045.105"

7835
core/pnpm-lock.yaml generated

File diff suppressed because it is too large Load diff

View file

@ -12,41 +12,54 @@ export class DevDataSqliteDb {
model TEXT NOT NULL,
provider TEXT NOT NULL,
tokens_generated INTEGER NOT NULL,
tokens_prompt INTEGER NOT NULL DEFAULT 0,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)`,
);
// Add tokens_prompt column if it doesn't exist
const columnCheckResult = await db.all(
`PRAGMA table_info(tokens_generated);`,
);
const columnExists = columnCheckResult.some(
(col: any) => col.name === "tokens_prompt",
);
if (!columnExists) {
await db.exec(
`ALTER TABLE tokens_generated ADD COLUMN tokens_prompt INTEGER NOT NULL DEFAULT 0;`,
);
}
}
public static async logTokensGenerated(
model: string,
provider: string,
tokens: number,
promptTokens: number,
generatedTokens: number,
) {
const db = await DevDataSqliteDb.get();
await db?.run(
"INSERT INTO tokens_generated (model, provider, tokens_generated) VALUES (?, ?, ?)",
[model, provider, tokens],
`INSERT INTO tokens_generated (model, provider, tokens_prompt, tokens_generated) VALUES (?, ?, ?, ?)`,
[model, provider, promptTokens, generatedTokens],
);
}
public static async getTokensPerDay() {
const db = await DevDataSqliteDb.get();
// Return a sum of tokens_generated column aggregated by day
const result = await db?.all(
`SELECT date(timestamp) as day, sum(tokens_generated) as tokens
// Return a sum of tokens_generated and tokens_prompt columns aggregated by day
`SELECT date(timestamp) as day, sum(tokens_prompt) as promptTokens, sum(tokens_generated) as generatedTokens
FROM tokens_generated
GROUP BY date(timestamp)`,
// WHERE model = ? AND provider = ?
// [model, provider],
);
return result ?? [];
}
public static async getTokensPerModel() {
const db = await DevDataSqliteDb.get();
// Return a sum of tokens_generated column aggregated by model
const result = await db?.all(
`SELECT model, sum(tokens_generated) as tokens
// Return a sum of tokens_generated and tokens_prompt columns aggregated by model
`SELECT model, sum(tokens_prompt) as promptTokens, sum(tokens_generated) as generatedTokens
FROM tokens_generated
GROUP BY model`,
);

View file

@ -2,19 +2,19 @@ export function removeQuotesAndEscapes(output: string): string {
output = output.trim();
// Replace smart quotes
output = output.replace("“", "\"");
output = output.replace("”", "\"");
output = output.replace("“", '"');
output = output.replace("”", '"');
output = output.replace("‘", "'");
output = output.replace("’", "'");
// Remove escapes
output = output.replace("\\\"", "\"");
output = output.replace('\\"', '"');
output = output.replace("\\'", "'");
output = output.replace("\\n", "\n");
output = output.replace("\\t", "\t");
output = output.replace("\\\\", "\\");
while (
(output.startsWith("\"") && output.endsWith("\"")) ||
(output.startsWith('"') && output.endsWith('"')) ||
(output.startsWith("'") && output.endsWith("'"))
) {
output = output.slice(1, -1);
@ -158,7 +158,9 @@ export function getMarkdownLanguageTagForFile(filepath: string): string {
}
export function copyOf(obj: any): any {
if (obj === null || obj === undefined) {return obj;}
if (obj === null || obj === undefined) {
return obj;
}
return JSON.parse(JSON.stringify(obj));
}

View file

@ -8,7 +8,13 @@ import {
} from "../autocomplete/lineStream.js";
import { streamDiff } from "../diff/streamDiff.js";
import { streamLines } from "../diff/util.js";
import { ChatMessage, DiffLine, ILLM } from "../index.js";
import {
ChatMessage,
DiffLine,
ILLM,
LLMFullCompletionOptions,
ModelProvider,
} from "../index.js";
import { gptEditPrompt } from "../llm/templates/edit.js";
import { Telemetry } from "./posthog.js";
@ -46,6 +52,10 @@ function modelIsInept(model: string): boolean {
return !(model.includes("gpt") || model.includes("claude"));
}
function isGpt4Trial(model: string, provider: ModelProvider): boolean {
return provider === "free-trial" && model.startsWith("gpt-4");
}
export async function* streamDiffLines(
prefix: string,
highlighted: string,
@ -82,6 +92,10 @@ export async function* streamDiffLines(
);
const inept = modelIsInept(llm.model);
const options: LLMFullCompletionOptions = {};
if (isGpt4Trial(llm.model, llm.providerName)) {
options.maxTokens = 2048;
}
const completion =
typeof prompt === "string"
? llm.streamComplete(prompt, { raw: true })

View file

@ -1,6 +1,6 @@
# AnthropicLLM
# Anthropic
To setup Anthropic, add the following to your `config.json` file:
To setup Anthropic, obtain an API key from [here](https://www.anthropic.com/api) and add the following to your `config.json` file:
```json title="~/.continue/config.json"
{
@ -8,13 +8,11 @@ To setup Anthropic, add the following to your `config.json` file:
{
"title": "Anthropic",
"provider": "anthropic",
"model": "claude-2",
"model": "claude-3-opus-20240229",
"apiKey": "YOUR_API_KEY"
}
]
}
```
Claude 2 is not yet publicly released. You can request early access [here](https://www.anthropic.com/earlyaccess).
[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Anthropic.ts)

View file

@ -1,24 +1,72 @@
# FreeTrial
# Free Trial
With the `FreeTrial` provider, new users can try out Continue with GPT-4 using a proxy server that securely makes calls to OpenAI using our API key. Continue should just work the first time you install the extension in VS Code.
The `"free-trial"` provider lets new users try out Continue with GPT-4, Llama3, Claude 3, and other models using a proxy server that securely makes API calls to these services. Continue should just work the first time you install the extension.
Once you are using Continue regularly though, you will need to add an OpenAI API key that has access to GPT-4 by following these steps:
While the Continue extension is always free to use, we cannot support infinite free LLM usage for all of our users. You will eventually need to either:
1. Copy your API key from https://platform.openai.com/account/api-keys
2. Open `~/.continue/config.json`. You can do this by using the '/config' command in Continue
3. Change the LLM to look like this:
1. Select an open-source model to use for free locally, or
2. Add your own API key for OpenAI, Anthropic, or another LLM provider
## Options
### 🦙 Ollama (free, local)
Ollama is a local service that makes it easy to run language models on your laptop.
1. Download Ollama from https://ollama.ai
2. Open `~/.continue/config.json`. You can do this by clicking the gear icon in the bottom right corner of the Continue sidebar
3. Add the following to your `config.json`:
```json title="~/.continue/config.json"
{
"models": [
{
"title": "GPT-4",
"provider": "openai",
"model": "gpt-4",
"title": "Llama3 8b",
"provider": "ollama",
"model": "llama3:8b"
}
]
}
```
### ⚡️ Groq (extremely fast)
Groq provides lightning fast inference for open-source LLMs like Llama3, up to twice as fast as through other providers.
1. Obtain an API key from https://console.groq.com
2. Add the following to your `config.json`:
```json title="~/.continue/config.json"
{
"models": [
{
"title": "Llama3 70b",
"provider": "groq",
"model": "llama3-70b",
"apiKey": "YOUR_API_KEY"
}
]
}
```
[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/FreeTrial.ts)
### ✨ OpenAI (highly capable)
1. Copy your API key from https://platform.openai.com/account/api-keys
2. Add the following to your `config.json`:
```json title="~/.continue/config.json"
{
"models": [
{
"title": "GPT-4-Turbo",
"provider": "openai",
"model": "gpt-4-turbo",
"apiKey": "YOUR_API_KEY"
}
]
}
```
### ⏩ Other options
The above were only a few examples, but Continue can be used with any LLM or provider. You can find [a full list of providers here](../../setup/select-provider.md).

View file

@ -1,6 +1,6 @@
# Ollama
[Ollama](https://ollama.ai/) is an application for Mac and Linux that makes it easy to locally run open-source models, including Llama-2. Download the app from the website, and it will walk you through setup in a couple of minutes. You can also read more in their [README](https://github.com/jmorganca/ollama). Continue can then be configured to use the `Ollama` LLM class:
[Ollama](https://ollama.ai/) is an application for Mac, Windows, and Linux that makes it easy to locally run open-source models, including Llama3. Download the app from the website, and it will walk you through setup in a couple of minutes. You can also read more in their [README](https://github.com/ollama/ollama). Continue can then be configured to use the `"ollama"` provider:
```json title="~/.continue/config.json"
{
@ -8,9 +8,7 @@
{
"title": "Ollama",
"provider": "ollama",
"model": "llama2-7b",
"completionOptions": {},
"apiBase": "http://localhost:11434"
"model": "llama3:8b"
}
]
}
@ -38,7 +36,7 @@ If you need to send custom headers for authentication, you may use the `requestO
{
"title": "Ollama",
"provider": "ollama",
"model": "llama2-7b",
"model": "llama3:8b",
"requestOptions": {
"headers": {
"Authorization": "Bearer xxx"

View file

@ -6,19 +6,19 @@ keywords: [configure, llm, provider]
# Configuration
## Change the default LLM
## Setting up chat models
In `config.json`, you'll find the `models` property, a list of the models that you have saved to use with Continue:
```json
"models": [
{
"title": "Smart Model",
"title": "GPT-4",
"provider": "free-trial",
"model": "gpt-4"
},
{
"title": "Fast Model",
"title": "GPT-3.5-Turbo",
"provider": "free-trial",
"model": "gpt-3.5-turbo"
}
@ -167,7 +167,10 @@ export function modifyConfig(config: Config): Config {
title: "My Custom LLM",
model: "mistral-7b",
},
streamCompletion: async function* (prompt: string, options: CompletionOptions) {
streamCompletion: async function* (
prompt: string,
options: CompletionOptions,
) {
// Make the API call here
// Then yield each part of the completion as it is streamed

View file

@ -8,16 +8,16 @@ keywords: [telemetry, anonymous, usage info, opt out]
## Overview
Continue collects and reports **anonymous** usage information. This data is essential to understanding how we should improve the product. You can opt out of it at any time. We use [Posthog](https://posthog.com/), an open source platform for product analytics, to collect and store the data. You can review the code [here](https://github.com/continuedev/continue/blob/main/gui/src/hooks/CustomPostHogProvider.tsx).
Continue collects and reports **anonymous** usage information. This data is essential to understanding how we should improve the product. You can opt out of it at any time. We use [Posthog](https://posthog.com/), an open source platform for product analytics, to collect and store the data. You can review the code [here](https://github.com/continuedev/continue/blob/main/gui/src/hooks/CustomPostHogProvider.tsx), or review our official policy [here](https://continue.dev/privacy).
## What we track
We track
- whether you accept or reject suggestions (not the code itself)
- the name of slash commands that are run
- whether you accept or reject suggestions (never including the code or the prompt)
- the name of the model and slash command used
- the number of tokens generated
- the name of your OS and IDE
- the name of the default model you configured
All data is anonymous and cleaned of PII before being sent to PostHog.

View file

@ -14,12 +14,22 @@ To solve many problems, the first step is reading the logs to find the relevant
### VS Code
#### Console logs
1. `cmd+shift+p` (MacOS) / `ctrl+shift+p` (Windows)
2. Search for and then select "Developer: Toggle Developer Tools"
3. This will open the [Chrome DevTools window](https://developer.chrome.com/docs/devtools/)
4. Select the `Console` tab
5. Read the console logs
#### LLM prompt logs
If you're getting a response from the LLM that doesn't seem to make sense, you can
1. Open the "Output" panel (right next to the terminal)
2. In the dropdown, select "Continue - LLM Prompts/Completions
3. View the exact prompts that were sent to the LLM and the completions recieved
### JetBrains
Open `~/.continue/core.log`. The most recent logs are found at the bottom of the file.
@ -55,9 +65,11 @@ If you are using VS Code and require requests to be made through a proxy, you ar
Continue can be used in [code-server](https://coder.com/), but if you are running across an error in the logs that includes "This is likely because the editor is not running in a secure context", please see [their documentation on securely exposing code-server](https://coder.com/docs/code-server/latest/guide#expose-code-server).
## Download a Newer Version
## Download the latest pre-release
If you are using an older version of the Continue extension, particularly one which depends on the separate Python server, we would recommend downloading the latest version of the extension, as we are constantly making bug fixes and are likely to have solved any major issues.
We are constantly making fixes and improvements to Continue, but the latest changes remain in a "pre-release" version for roughly a week so that we can test their stability. If you are experiencing issues, you can try the pre-release by going to the Continue extension page in VS Code and selecting "Switch to Pre-Release" as shown below.
![Pre-Release](../static/img/prerelease.png)
## Download an Older Version

View file

@ -28,6 +28,30 @@ ollama run starcoder2:3b
Once it has been downloaded, you should begin to see completions in VS Code.
## Setting up with LM Studio
You can also set up tab-autocomplete with a local LM Studio instance by following these steps:
1. Download the latest version of LM Studio from [here](https://lmstudio.ai/)
2. Download a model (e.g. search for `second-state/StarCoder2-3B-GGUF` and choose one of the options there)
3. Go to the server section (button is on the left), select your model from the dropdown at the top, and click "Start Server"
4. Go to the "My Models" section (button is on the left), find your selected model, and copy the name the path (example: `second-state/StarCoder2-3B-GGUF/starcoder2-3b-Q8_0.gguf`); this will be used as the "model" attribute in Continue
5. Go to Continue and modify the configurations for a [custom model](#setting-up-a-custom-model)
6. Set the "provider" to `lmstudio` and the "model" to the path copied earlier
Example:
```json title=~/.continue/config.json
{
"tabAutocompleteModel": {
"title": "Starcoder2 3b",
"model": "second-state/StarCoder2-3B-GGUF/starcoder2-3b-Q8_0.gguf",
"provider": "lmstudio",
},
...
}
```
## Setting up a custom model
All of the configuration options available for chat models are available to use for tab-autocomplete. For example, if you wanted to use a remote Ollama instance you would edit your `config.json` like this (note that it is not inside the models array):

View file

@ -1,57 +0,0 @@
import React from "react";
interface ClassPropertyRefProps {
name: string;
details: string;
required: boolean;
default: string;
}
const PYTHON_TYPES = {
string: "str",
integer: "int",
};
export default function ClassPropertyRef(props: ClassPropertyRefProps) {
const details = JSON.parse(props.details);
return (
<>
<div>
<h4 style={{ display: "inline-block", marginRight: "10px" }}>
{props.name}
</h4>
{props.required && (
<span
style={{
color: "red",
fontSize: "11px",
marginRight: "4px",
borderRadius: "4px",
border: "1px solid red",
padding: "1px 2px",
}}
>
REQUIRED
</span>
)}
<span>
{details.type && `(${PYTHON_TYPES[details.type] || details.type})`}
</span>
{props.default && (
<span>
{" "}
={" "}
<code>
{details.type === "string" && '"'}
{props.default}
{details.type === "string" && '"'}
</code>
</span>
)}
</div>
<p>{details.description}</p>
</>
);
}

BIN
docs/static/img/prerelease.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 124 KiB

View file

@ -438,12 +438,12 @@
"properties": {
"model": {
"enum": [
"gpt-4-turbo",
"gpt-4o",
"llama3-70b",
"gpt-3.5-turbo",
"gpt-4",
"phind-codellama-34b",
"gemini-pro",
"gpt-4-vision-preview",
"codellama-70b",
"mistral-8x7b",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
@ -1963,6 +1963,9 @@
"enum": ["top", "bottom"],
"default": "top",
"description": "Whether to show the copy and apply code buttons at the top or bottom of code blocks in the sidebar."
},
"fontSize": {
"type": "number"
}
}
},

View file

@ -438,12 +438,12 @@
"properties": {
"model": {
"enum": [
"gpt-4-turbo",
"gpt-4o",
"llama3-70b",
"gpt-3.5-turbo",
"gpt-4",
"phind-codellama-34b",
"gemini-pro",
"gpt-4-vision-preview",
"codellama-70b",
"mistral-8x7b",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
@ -1963,6 +1963,9 @@
"enum": ["top", "bottom"],
"default": "top",
"description": "Whether to show the copy and apply code buttons at the top or bottom of code blocks in the sidebar."
},
"fontSize": {
"type": "number"
}
}
},

View file

@ -1,9 +1,3 @@
{
"customCommands": [
{
"name": "hello",
"prompt": "{{{ input }}}\n\nWrite a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.",
"description": "This is an example custom command. Use /config to edit it and create more"
}
]
"customCommands": []
}

View file

@ -0,0 +1,28 @@
temperature: 0.0
---
{{{ diff }}}
Give me feedback on the above changes. For each file, you should output a markdown section including the following:
- If you found any problems, an h3 like "❌ <filename>"
- If you didn't find any problems, an h3 like "✅ <filename>"
- If you found any problems, add below a bullet point description of what you found, including a minimal code snippet explaining how to fix it
- If you didn't find any problems, you don't need to add anything else
Here is an example. The example is surrounded in backticks, but your response should not be:
```
### ✅ <Filename1>
### ❌ <Filename2>
<Description>
```
You should look primarily for the following types of issues, and only mention other problems if they are highly pressing.
- console.logs that have been left after debugging
- repeated code
- algorithmic errors that could fail under edge cases
- something that could be refactored
Make sure to review ALL files that were changed, do not skip any.

View file

@ -0,0 +1,17 @@
temperature: 0.5
maxTokens: 4096
---
<system>
You are an expert programmer
</system>
{{{ input }}}
Write unit tests for the above selected code, following each of these instructions:
- Use `jest`
- Properly set up and tear down
- Include important edge cases
- The tests should be complete and sophisticated
- Give the tests just as chat output, don't edit any file
- Don't explain how to set up `jest`
- Write a single code block, making sure to label with the language being used (e.g. "```typscript")

View file

@ -438,12 +438,12 @@
"properties": {
"model": {
"enum": [
"gpt-4-turbo",
"gpt-4o",
"llama3-70b",
"gpt-3.5-turbo",
"gpt-4",
"phind-codellama-34b",
"gemini-pro",
"gpt-4-vision-preview",
"codellama-70b",
"mistral-8x7b",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
@ -1963,6 +1963,9 @@
"enum": ["top", "bottom"],
"default": "top",
"description": "Whether to show the copy and apply code buttons at the top or bottom of code blocks in the sidebar."
},
"fontSize": {
"type": "number"
}
}
},

View file

@ -474,12 +474,12 @@
"properties": {
"model": {
"enum": [
"gpt-4-turbo",
"gpt-4o",
"llama3-70b",
"gpt-3.5-turbo",
"gpt-4",
"phind-codellama-34b",
"gemini-pro",
"gpt-4-vision-preview",
"codellama-70b",
"mistral-8x7b",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
@ -2202,6 +2202,9 @@
],
"default": "top",
"description": "Whether to show the copy and apply code buttons at the top or bottom of code blocks in the sidebar."
},
"fontSize": {
"type": "number"
}
}
},

View file

@ -1,12 +0,0 @@
import { factorial, repeat } from "./factorial";
function fib(n) {
if (n <= 1) return n;
return fib(n - 2) + fib(n - 1);
}
let d = repeat(5, "a");
console.log(d);
let e = factorial(3);
console.log(e);

View file

@ -1,8 +0,0 @@
export function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
export function repeat(n: number, a: string) {
return a.repeat(n);
}

14851
extensions/vscode/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -1,7 +1,7 @@
{
"name": "continue",
"icon": "media/icon.png",
"version": "0.9.93",
"version": "0.9.94",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -116,7 +116,7 @@
{
"command": "continue.quickEdit",
"category": "Continue",
"title": "Quick Edit",
"title": "Generate Code",
"group": "Continue"
},
{
@ -501,7 +501,7 @@
"@typescript-eslint/parser": "^5.45.0",
"@vscode/vsce": "^2.22.0",
"cargo-cp-artifact": "^0.1",
"esbuild": "^0.17.19",
"esbuild": "0.17.19",
"eslint": "^8.28.0",
"glob": "^8.0.3",
"json-schema-to-typescript": "^12.0.0",

File diff suppressed because it is too large Load diff

View file

@ -16,6 +16,9 @@ function execCmdSync(cmd) {
// Clear folders that will be packaged to ensure clean slate
rimrafSync(path.join(__dirname, "..", "bin"));
rimrafSync(path.join(__dirname, "..", "out"));
fs.mkdirSync(path.join(__dirname, "..", "out", "node_modules"), {
recursive: true,
});
// Get the target to package for
let target = undefined;
@ -102,16 +105,17 @@ const exe = os === "win32" ? ".exe" : "";
}
// Install node_modules //
// execCmdSync("pnpm install");
// console.log("[info] pnpm install in extensions/vscode completed");
execCmdSync("npm install");
console.log("[info] npm install in extensions/vscode completed");
console.log("Contents of node_modules: ", fs.readdirSync("./node_modules"));
process.chdir("../../gui");
// execCmdSync("pnpm install");
// console.log("[info] pnpm install in gui completed");
execCmdSync("npm install");
console.log("[info] npm install in gui completed");
if (ghAction()) {
execCmdSync("pnpm run build");
execCmdSync("npm run build");
}
// Copy over the dist folder to the Intellij extension //
@ -316,7 +320,9 @@ const exe = os === "win32" ? ".exe" : "";
console.log(`Copying ${package} to ${toCopy}`);
// This is a way to install only one package without npm trying to install all the dependencies
// Create a temporary directory for installing the package
const tempDir = `/tmp/continue-node_modules-${package}-${toCopy}`;
const adjustedName = toCopy.replace(/^@/, "").replace("/", "-");
const tempDir = `/tmp/continue-node_modules-${adjustedName}`;
const currentDir = process.cwd();
// Remove the dir we will be copying to
@ -411,7 +417,11 @@ const exe = os === "win32" ? ".exe" : "";
fs.unlinkSync("node_modules/@esbuild/esbuild.zip");
} else {
// Download esbuild from npm in tmp and copy over
await installNodeModuleInTempDirAndCopyToCurrent("esbuild", "@esbuild");
console.log("npm installing esbuild binary");
await installNodeModuleInTempDirAndCopyToCurrent(
"esbuild@0.17.19",
"@esbuild",
);
}
await new Promise((resolve, reject) => {

View file

@ -1,9 +1,9 @@
import * as vscode from "vscode";
import { getMetaKeyLabel } from "../util/util";
import { getMetaKeyName } from "../util/util";
const inlineTipDecoration = vscode.window.createTextEditorDecorationType({
after: {
contentText: `Add to chat (${getMetaKeyLabel()} L) | Edit highlighted code (${getMetaKeyLabel()} I).`,
contentText: `Add to chat (${getMetaKeyName()}+L) | Edit highlighted code (${getMetaKeyName()}+I).`,
color: "#888",
margin: "0 0 0 6em",
fontWeight: "bold",
@ -50,7 +50,7 @@ function handleSelectionChange(e: vscode.TextEditorSelectionChangeEvent) {
const emptyFileTooltipDecoration = vscode.window.createTextEditorDecorationType(
{
after: {
contentText: `Use ${getMetaKeyLabel()} I to generate code`,
contentText: `Use ${getMetaKeyName()}+I to generate code`,
color: "#888",
margin: "2em 0 0 0",
fontStyle: "italic",

View file

@ -9,7 +9,7 @@ import {
} from "./decorations";
import type { VerticalDiffCodeLens } from "./manager";
export class VerticalPerLineDiffHandler {
export class VerticalPerLineDiffHandler implements vscode.Disposable {
private editor: vscode.TextEditor;
private startLine: number;
private endLine: number;
@ -56,7 +56,7 @@ export class VerticalPerLineDiffHandler {
this.editor,
);
vscode.window.onDidChangeActiveTextEditor((editor) => {
const disposable = vscode.window.onDidChangeActiveTextEditor((editor) => {
// When we switch away and back to this editor, need to re-draw decorations
if (editor?.document.uri.fsPath === this.filepath) {
this.editor = editor;
@ -69,6 +69,7 @@ export class VerticalPerLineDiffHandler {
this.queueDiffLine(undefined);
}
});
this.disposables.push(disposable);
}
private get filepath() {
@ -243,6 +244,13 @@ export class VerticalPerLineDiffHandler {
this.cancelled = true;
this.refreshCodeLens();
this.dispose();
}
disposables: vscode.Disposable[] = [];
dispose() {
this.disposables.forEach((disposable) => disposable.dispose());
}
get isCancelled() {

View file

@ -173,7 +173,10 @@ export class VsCodeExtension {
// Listen for file changes in the workspace
const filepath = event.uri.fsPath;
if (filepath.endsWith(".continuerc.json")) {
if (
filepath.endsWith(".continuerc.json") ||
filepath.endsWith(".prompt")
) {
this.configHandler.reloadConfig();
this.tabAutocompleteModel.clearLlm();
} else if (

View file

@ -300,9 +300,13 @@ export class VsCodeIdeUtils {
// First, check whether it's a notebook document
// Need to iterate over the cells to get full contents
const notebook = vscode.workspace.notebookDocuments.find(
(doc) => doc.uri.toString() === uri.toString(),
);
const notebook =
vscode.workspace.notebookDocuments.find(
(doc) => doc.uri.toString() === uri.toString(),
) ??
(uri.fsPath.endsWith("ipynb")
? await vscode.workspace.openNotebookDocument(uri)
: undefined);
if (notebook) {
return notebook
.getCells()
@ -331,7 +335,8 @@ export class VsCodeIdeUtils {
const truncatedBytes = bytes.slice(0, VsCodeIdeUtils.MAX_BYTES);
const contents = new TextDecoder().decode(truncatedBytes);
return contents;
} catch {
} catch (e) {
console.warn("Error reading file", e);
return "";
}
}
@ -588,7 +593,17 @@ export class VsCodeIdeUtils {
}
repos.push(repo.state.HEAD?.name);
diffs.push(await repo.diff());
// Staged changes
// const a = await repo.diffIndexWithHEAD();
const staged = await repo.diff(true);
// Un-staged changes
// const b = await repo.diffWithHEAD();
const unstaged = await repo.diff(false);
// All changes
// const e = await repo.diffWith("HEAD");
// Only staged
// const f = await repo.diffIndexWith("HEAD");
diffs.push(`${staged}\n${unstaged}`);
}
const fullDiff = diffs.join("\n\n");

View file

@ -100,6 +100,19 @@ export function getMetaKeyLabel() {
}
}
export function getMetaKeyName() {
const platform = getPlatform();
switch (platform) {
case "mac":
return "Cmd";
case "linux":
case "windows":
return "Ctrl";
default:
return "Ctrl";
}
}
export function getExtensionVersion(): string {
const extension = vscode.extensions.getExtension("continue.continue");
return extension?.packageJSON.version || "0.1.0";

View file

@ -130,19 +130,45 @@ export class VsCodeWebviewProtocol
}
}
vscode.window
.showErrorMessage(message, "Show Logs", "Troubleshooting")
.then((selection) => {
if (selection === "Show Logs") {
vscode.commands.executeCommand(
"workbench.action.toggleDevTools",
);
} else if (selection === "Troubleshooting") {
vscode.env.openExternal(
vscode.Uri.parse("https://docs.continue.dev/troubleshooting"),
);
}
});
if (message.includes("https://proxy-server")) {
message = message.split("\n").slice(1).join("\n").trim();
try {
message = JSON.parse(message).message;
} catch {}
if (message.includes("exceeded")) {
message +=
" To keep using Continue, you can set up a local model or use your own API key.";
} else {
message +=
" To avoid rate limiting, you can set up a local model or use your own API key.";
}
vscode.window
.showInformationMessage(message, "Add API Key", "Use Local Model")
.then((selection) => {
if (selection === "Add API Key") {
this.request("addApiKey", undefined);
} else if (selection === "Use Local Model") {
this.request("setupLocalModel", undefined);
}
});
} else {
vscode.window
.showErrorMessage(message, "Show Logs", "Troubleshooting")
.then((selection) => {
if (selection === "Show Logs") {
vscode.commands.executeCommand(
"workbench.action.toggleDevTools",
);
} else if (selection === "Troubleshooting") {
vscode.env.openExternal(
vscode.Uri.parse(
"https://docs.continue.dev/troubleshooting",
),
);
}
});
}
}
}
});

15324
gui/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

1
gui/pnpm-lock.yaml generated
View file

@ -4517,6 +4517,7 @@ snapshots:
uuid: 9.0.1
vectordb: 0.4.20(@apache-arrow/ts@14.0.2)(apache-arrow@14.0.2)
web-tree-sitter: 0.21.0
yaml: 2.4.2
transitivePeerDependencies:
- '@apache-arrow/ts'
- apache-arrow

View file

@ -169,6 +169,25 @@ const Layout = () => {
setIndexingState(data);
});
useWebviewListener(
"addApiKey",
async () => {
navigate("/modelconfig/openai");
},
[navigate],
);
useWebviewListener(
"setupLocalModel",
async () => {
postToIde("completeOnboarding", {
mode: "localAfterFreeTrial",
});
navigate("/localOnboarding");
},
[navigate],
);
useEffect(() => {
const onboardingComplete = getLocalStorage("onboardingComplete");
if (
@ -185,9 +204,9 @@ const Layout = () => {
}, [location]);
const [indexingState, setIndexingState] = useState<IndexingProgressUpdate>({
desc: "Starting indexing",
desc: "Indexing disabled",
progress: 0.0,
status: "starting",
status: "disabled",
});
return (
@ -221,10 +240,10 @@ const Layout = () => {
{indexingState.status !== "indexing" && // Would take up too much space together with indexing progress
defaultModel?.provider === "free-trial" &&
(location.pathname === "/settings" ||
parseInt(localStorage.getItem("ftc") || "0") >= 50) && (
parseInt(localStorage.getItem("ftc") || "0") >= 10) && (
<ProgressBar
completed={parseInt(localStorage.getItem("ftc") || "0")}
total={150}
total={100}
/>
)}
@ -270,7 +289,10 @@ const Layout = () => {
{bottomMessage}
</BottomMessageDiv>
</div>
<div className="text-sm" id="tooltip-portal-div" />
<div
style={{ fontSize: `${getFontSize() - 4}px` }}
id="tooltip-portal-div"
/>
</LayoutTopDiv>
);
};

View file

@ -24,18 +24,16 @@ function FTCDialog() {
<div className="p-4">
<h3>Free Trial Limit Reached</h3>
<p>
You've reached the free trial limit of 250 free inputs with Continue's
OpenAI API key. To keep using Continue, you can either use your own API
key, or use a local LLM. To read more about the options, see our{" "}
You've reached the free trial limit of 100 free inputs. To keep using
Continue, you can either use your own API key, or use a local LLM. To
read more about the options, see our{" "}
<a
href="https://docs.continue.dev/customization/models"
target="_blank"
>
documentation
</a>
. If you're just looking for fastest way to keep going, type '/config'
to open your Continue config file and paste your API key into the
OpenAIFreeTrial object.
.
</p>
<Input

View file

@ -1,110 +0,0 @@
import { TrashIcon } from "@heroicons/react/24/outline";
import { useDispatch, useSelector } from "react-redux";
import styled from "styled-components";
import {
Button,
defaultBorderRadius,
vscBackground,
vscForeground,
vscInputBackground,
} from "..";
import {
setDialogMessage,
setShowDialog,
} from "../../redux/slices/uiStateSlice";
import { RootState } from "../../redux/store";
import HeaderButtonWithText from "../HeaderButtonWithText";
const MiniPillSpan = styled.span`
padding: 3px;
padding-left: 6px;
padding-right: 6px;
border-radius: ${defaultBorderRadius};
color: ${vscForeground};
background-color: #fff3;
overflow: hidden;
font-size: 12px;
display: flex;
align-items: center;
text-align: center;
justify-content: center;
`;
const ContextGroupSelectDiv = styled.div`
display: flex;
align-items: center;
gap: 8px;
padding: 8px;
border-radius: ${defaultBorderRadius};
background-color: ${vscInputBackground};
color: ${vscForeground};
margin-top: 8px;
cursor: pointer;
&:hover {
background-color: ${vscBackground};
color: ${vscForeground};
}
`;
function SelectContextGroupDialog() {
const dispatch = useDispatch();
const savedContextGroups = useSelector(
(state: RootState) => state.serverState.savedContextGroups
);
return (
<div className="p-4">
<h2>Saved Context Groups</h2>
{savedContextGroups && Object.keys(savedContextGroups).length > 0 ? (
<div className="overflow-scroll">
{Object.keys(savedContextGroups).map((key: string) => {
const contextGroup = savedContextGroups[key];
return (
<ContextGroupSelectDiv
onClick={() => {
dispatch(setDialogMessage(undefined));
dispatch(setShowDialog(false));
// TODO
// client?.selectContextGroup(key);
}}
>
<b>{key}: </b>
{contextGroup.map((contextItem) => {
return (
<MiniPillSpan>{contextItem.description.name}</MiniPillSpan>
);
})}
<HeaderButtonWithText
text="Delete"
onClick={(e) => {
e.stopPropagation();
// TODO
// client?.deleteContextGroup(key);
}}
>
<TrashIcon width="1.4em" height="1.4em" />
</HeaderButtonWithText>
</ContextGroupSelectDiv>
);
})}
</div>
) : (
<div>No saved context groups</div>
)}
<Button
className="ml-auto"
onClick={() => {
dispatch(setDialogMessage(undefined));
dispatch(setShowDialog(false));
}}
>
Cancel
</Button>
</div>
);
}
export default SelectContextGroupDialog;

View file

@ -0,0 +1,85 @@
import React from "react";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import styled from "styled-components";
import { Button, Input } from "..";
import { setDefaultModel } from "../../redux/slices/stateSlice";
import { setShowDialog } from "../../redux/slices/uiStateSlice";
import { ideRequest, postToIde } from "../../util/ide";
const GridDiv = styled.div`
display: grid;
grid-template-columns: 1fr 1fr;
grid-gap: 8px;
align-items: center;
`;
function SetupLocalOrKeyDialog() {
const navigate = useNavigate();
const [apiKey, setApiKey] = React.useState("");
const dispatch = useDispatch();
return (
<div className="p-4">
<h3>Set up your own model</h3>
<p>
To keep using Continue after your free inputs, you can either use your
own API key, or use a local LLM. To read more about the options, see our{" "}
<a
className="cursor-pointer"
onClick={() =>
ideRequest(
"openUrl",
"https://docs.continue.dev/reference/Model%20Providers/freetrial",
)
}
>
documentation
</a>
.
</p>
<Input
type="text"
placeholder="Enter your OpenAI API key"
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
/>
<Button
className="w-full"
disabled={!apiKey}
onClick={() => {
postToIde("config/addOpenAiKey", apiKey);
dispatch(setShowDialog(false));
dispatch(setDefaultModel({ title: "GPT-4" }));
}}
>
Use my OpenAI API key
</Button>
<div className="text-center">— OR —</div>
<GridDiv>
<Button
onClick={() => {
dispatch(setShowDialog(false));
postToIde("completeOnboarding", {
mode: "localAfterFreeTrial",
});
navigate("/localOnboarding");
}}
>
Use local model
</Button>
<Button
onClick={() => {
dispatch(setShowDialog(false));
navigate("/models");
}}
>
View all options
</Button>
</GridDiv>
</div>
);
}
export default SetupLocalOrKeyDialog;

View file

@ -159,7 +159,7 @@ export const CustomScrollbarDiv = styled.div`
`;
const TooltipStyles = {
fontSize: "12px",
fontSize: `${getFontSize() - 2}px`,
backgroundColor: vscInputBackground,
boxShadow: `0px 0px 2px 1px ${vscBadgeBackground}`,
color: vscForeground,
@ -303,18 +303,6 @@ export const MainContainerWithBorder = styled.div<{ borderWidth?: string }>`
background-color: white;
`;
export const MainTextInput = styled.textarea`
padding: 8px;
font-size: 16px;
border-radius: ${defaultBorderRadius};
border: 1px solid #ccc;
margin: 8px 8px;
background-color: ${vscBackground};
color: ${vscForeground};
outline: 1px solid orange;
resize: none;
`;
export const appear = keyframes`
from {
opacity: 0;

View file

@ -4,6 +4,7 @@ import ReactDOM from "react-dom";
import styled from "styled-components";
import { StyledTooltip, lightGray, vscForeground } from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { getFontSize } from "../../util";
const DIAMETER = 6;
const CircleDiv = styled.div<{ color: string }>`
@ -41,7 +42,7 @@ const GridDiv = styled.div`
const P = styled.p`
margin: 0;
margin-top: 2px;
font-size: 11.5px;
font-size: ${getFontSize() - 2.5}px;
color: ${lightGray};
text-align: center;
white-space: nowrap;
@ -63,12 +64,13 @@ const IndexingProgressBar = ({ indexingState }: ProgressBarProps) => {
const tooltipPortalDiv = document.getElementById("tooltip-portal-div");
const [expanded, setExpanded] = useState(true);
const [paused, setPaused] = useState<boolean | undefined>(undefined);
const [hovered, setHovered] = useState(false);
useEffect(() => {
ideMessenger.post("index/setPaused", !expanded);
}, [expanded]);
if (paused === undefined) return;
ideMessenger.post("index/setPaused", paused);
}, [paused]);
return (
<div
@ -78,7 +80,7 @@ const IndexingProgressBar = ({ indexingState }: ProgressBarProps) => {
indexingState.progress < 1 &&
indexingState.progress >= 0
) {
setExpanded((prev) => !prev);
setPaused((prev) => !prev);
} else {
ideMessenger.post("index/forceReIndex", undefined);
}
@ -126,12 +128,49 @@ const IndexingProgressBar = ({ indexingState }: ProgressBarProps) => {
tooltipPortalDiv,
)}
</>
) : expanded ? ( //progress bar
) : indexingState.status === "disabled" ? ( //gray disabled dot
<>
<CircleDiv
data-tooltip-id="progress_dot"
color={lightGray}
></CircleDiv>
{tooltipPortalDiv &&
ReactDOM.createPortal(
<StyledTooltip id="progress_dot" place="top">
{indexingState.desc}
</StyledTooltip>,
tooltipPortalDiv,
)}
</>
) : indexingState.status === "paused" ||
(paused && indexingState.status === "indexing") ? (
//yellow 'paused' dot
<>
<CircleDiv
data-tooltip-id="progress_dot"
color="#bb0"
onClick={(e) => {
ideMessenger.post("index/setPaused", false);
}}
></CircleDiv>
{tooltipPortalDiv &&
ReactDOM.createPortal(
<StyledTooltip id="progress_dot" place="top">
Click to unpause indexing (
{Math.trunc(indexingState.progress * 100)}%)
</StyledTooltip>,
tooltipPortalDiv,
)}
</>
) : indexingState.status === "indexing" ? ( //progress bar
<>
<GridDiv
data-tooltip-id="usage_progress_bar"
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
onClick={(e) => {
ideMessenger.post("index/setPaused", true);
}}
>
<ProgressBarWrapper>
<ProgressBarFill completed={fillPercentage} />
@ -150,20 +189,7 @@ const IndexingProgressBar = ({ indexingState }: ProgressBarProps) => {
tooltipPortalDiv,
)}
</>
) : (
//yellow 'paused' dot
<>
<CircleDiv data-tooltip-id="progress_dot" color="#bb0"></CircleDiv>
{tooltipPortalDiv &&
ReactDOM.createPortal(
<StyledTooltip id="progress_dot" place="top">
Click to unpause indexing (
{Math.trunc(indexingState.progress * 100)}%)
</StyledTooltip>,
tooltipPortalDiv,
)}
</>
)}
) : null}
</div>
);
};

View file

@ -1,5 +1,13 @@
import ReactDOM from "react-dom";
import { useDispatch } from "react-redux";
import styled from "styled-components";
import { StyledTooltip, lightGray, vscForeground } from "..";
import {
setDialogMessage,
setShowDialog,
} from "../../redux/slices/uiStateSlice";
import { getFontSize } from "../../util";
import SetupLocalOrKeyDialog from "../dialogs/SetupLocalOrKey";
const ProgressBarWrapper = styled.div`
width: 100px;
@ -22,12 +30,13 @@ const GridDiv = styled.div`
grid-template-rows: 1fr auto;
align-items: center;
justify-items: center;
cursor: pointer;
`;
const P = styled.p`
margin: 0;
margin-top: 2px;
font-size: 11.5px;
font-size: ${getFontSize() - 2.5}px;
color: ${lightGray};
text-align: center;
white-space: nowrap;
@ -41,37 +50,46 @@ interface ProgressBarProps {
}
const ProgressBar = ({ completed, total }: ProgressBarProps) => {
const dispatch = useDispatch();
const fillPercentage = Math.min(100, Math.max(0, (completed / total) * 100));
const tooltipPortalDiv = document.getElementById("tooltip-portal-div");
return (
<>
<a
href="https://docs.continue.dev/reference/Model%20Providers/freetrial"
className="no-underline ml-2"
<GridDiv
data-tooltip-id="usage_progress_bar"
onClick={() => {
dispatch(setShowDialog(true));
dispatch(setDialogMessage(<SetupLocalOrKeyDialog />));
}}
>
<GridDiv data-tooltip-id="usage_progress_bar">
<ProgressBarWrapper>
<ProgressBarFill
completed={fillPercentage}
color={
completed / total > 0.75
? completed / total > 0.95
? "#f00"
: "#fc0"
: undefined
}
/>
</ProgressBarWrapper>
<P>
Free Uses: {completed} / {total}
</P>
</GridDiv>
</a>
<StyledTooltip id="usage_progress_bar" place="bottom">
{
"Continue allows you to use our OpenAI API key for up to 250 inputs. After this, you can either use your own API key, or use a local LLM. Click the progress bar to go to the docs and learn more."
}
</StyledTooltip>
<ProgressBarWrapper>
<ProgressBarFill
completed={fillPercentage}
color={
completed / total > 0.75
? completed / total > 0.9
? "#f00"
: "#fc0"
: undefined
}
/>
</ProgressBarWrapper>
<P>
Free Uses: {completed} / {total}
</P>
</GridDiv>
{tooltipPortalDiv &&
ReactDOM.createPortal(
<StyledTooltip id="usage_progress_bar" place="top">
{
"Click to use your own API key or local LLM (required after 100 inputs)"
}
</StyledTooltip>,
tooltipPortalDiv,
)}
</>
);
};

View file

@ -10,6 +10,7 @@ import {
vscForeground,
} from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { getFontSize } from "../../util";
import FileIcon from "../FileIcon";
const ContextItemDiv = styled.div`
@ -79,7 +80,7 @@ const ContextItemsPeek = (props: ContextItemsPeekProps) => {
display: "flex",
justifyContent: "left",
alignItems: "center",
fontSize: "11px",
fontSize: `${getFontSize() - 3}px`,
}}
onClick={() => setOpen((prev) => !prev)}
>

View file

@ -1,6 +1,7 @@
import { PlayIcon, StopIcon } from "@heroicons/react/24/outline";
import styled from "styled-components";
import { Button } from "..";
import { getFontSize } from "../../util";
const StyledButton = styled(Button)<{
color?: string | null;
@ -46,7 +47,7 @@ function ContinueButton(props: {
<StyledButton
showStop={props.showStop}
hidden={props.hidden}
style={{ fontSize: "10px" }}
style={{ fontSize: `${getFontSize() - 4}px` }}
className="m-auto"
onClick={props.disabled ? undefined : props.onClick}
isDisabled={props.disabled}

View file

@ -17,6 +17,7 @@ import { selectUseActiveFile } from "../../redux/selectors";
import { defaultModelSelector } from "../../redux/selectors/modelSelectors";
import {
getAltKeyLabel,
getFontSize,
getMetaKeyLabel,
isJetBrains,
isMetaEquivalentKeyPressed,
@ -35,7 +36,7 @@ const StyledDiv = styled.div<{ hidden?: boolean }>`
align-items: center;
z-index: 50;
font-size: 10px;
font-size: ${getFontSize() - 4}px;
cursor: text;

View file

@ -4,10 +4,10 @@ import {
AtSymbolIcon,
BeakerIcon,
BookOpenIcon,
ChevronDoubleRightIcon,
CodeBracketIcon,
Cog6ToothIcon,
CommandLineIcon,
CubeIcon,
ExclamationCircleIcon,
ExclamationTriangleIcon,
FolderIcon,
@ -82,8 +82,8 @@ function DropdownIcon(props: { className?: string; item: ComboBoxItem }) {
props.item.type === "contextProvider"
? props.item.id
: props.item.type === "slashCommand"
? props.item.id
: props.item.type;
? props.item.id
: props.item.type;
const Icon = ICONS_FOR_DROPDOWN[provider];
const iconClass = `${props.className} flex-shrink-0`;
@ -91,11 +91,7 @@ function DropdownIcon(props: { className?: string; item: ComboBoxItem }) {
return props.item.type === "contextProvider" ? (
<AtSymbolIcon className={iconClass} height="1.2em" width="1.2em" />
) : (
<ChevronDoubleRightIcon
className={iconClass}
height="1.2em"
width="1.2em"
/>
<CubeIcon className={iconClass} height="1.2em" width="1.2em" />
);
}
return <Icon className={iconClass} height="1.2em" width="1.2em" />;

View file

@ -38,7 +38,11 @@ import {
setEditingContextItemAtIndex,
} from "../../redux/slices/stateSlice";
import { RootState } from "../../redux/store";
import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util";
import {
getFontSize,
isJetBrains,
isMetaEquivalentKeyPressed,
} from "../../util";
import CodeBlockExtension from "./CodeBlockExtension";
import { SlashCommand } from "./CommandsExtension";
import InputToolbar from "./InputToolbar";
@ -62,7 +66,7 @@ const InputBoxDiv = styled.div`
z-index: 1;
border: 0.5px solid ${vscInputBorder};
outline: none;
font-size: 14px;
font-size: ${getFontSize()}px;
&:focus {
outline: none;
@ -380,7 +384,7 @@ function TipTapEditor(props: TipTapEditorProps) {
editorProps: {
attributes: {
class: "outline-none -mt-1 overflow-hidden",
style: "font-size: 14px;",
style: `font-size: ${getFontSize()}px;`,
},
},
content: props.editorState || mainEditorContent || "",
@ -422,7 +426,7 @@ function TipTapEditor(props: TipTapEditorProps) {
},
});
const shortcutTimeoutRef = useRef<NodeJS.Timeout | undefined>(undefined);
const editorFocusedRef = useUpdatingRef(editor?.isFocused, [editor]);
useEffect(() => {
if (isJetBrains()) {
@ -431,35 +435,18 @@ function TipTapEditor(props: TipTapEditorProps) {
}
const handleKeyDown = async (event: KeyboardEvent) => {
if (!editor) return;
const shouldSkip = () => {
const skip = shortcutTimeoutRef.current !== undefined;
if (!skip) {
shortcutTimeoutRef.current = setTimeout(async () => {
shortcutTimeoutRef.current = undefined;
}, 100);
}
return skip;
};
if (!editor || !editorFocusedRef.current) return;
if (event.metaKey && event.key === "x") {
if (!shouldSkip()) {
document.execCommand("cut");
}
document.execCommand("cut");
event.stopPropagation();
event.preventDefault();
} else if (event.metaKey && event.key === "v") {
if (!shouldSkip()) {
document.execCommand("paste");
}
document.execCommand("paste");
event.stopPropagation();
event.preventDefault();
} else if (event.metaKey && event.key === "c") {
if (!shouldSkip()) {
document.execCommand("copy");
}
document.execCommand("copy");
event.stopPropagation();
event.preventDefault();
}
@ -470,7 +457,7 @@ function TipTapEditor(props: TipTapEditorProps) {
return () => {
document.removeEventListener("keydown", handleKeyDown);
};
}, [editor, shortcutTimeoutRef]);
}, [editor, editorFocusedRef]);
useEffect(() => {
if (mainEditorContent && editor) {

View file

@ -48,7 +48,7 @@ const StyledMarkdown = styled.div<{
word-wrap: break-word;
border-radius: ${defaultBorderRadius};
background-color: ${vscEditorBackground};
font-size: 12px;
font-size: ${getFontSize() - 2}px;
font-family: var(--vscode-editor-font-family);
}

View file

@ -10,7 +10,9 @@ import {
setInactive,
} from "../redux/slices/stateSlice";
import { RootState } from "../redux/store";
import { isJetBrains } from "../util";
import { setLocalStorage } from "../util/localStorage";
import useChatHandler from "./useChatHandler";
import { useWebviewListener } from "./useWebviewListener";
@ -26,6 +28,12 @@ function useSetup(dispatch: Dispatch<any>) {
);
dispatch(setConfig(config));
setConfigLoaded(true);
// Perform any actions needed with the config
if (config.ui?.fontSize) {
setLocalStorage("fontSize", config.ui.fontSize);
document.body.style.fontSize = `${config.ui.fontSize}px`;
}
};
// Load config from the IDE

View file

@ -49,6 +49,7 @@ import {
} from "../redux/slices/uiStateSlice";
import { RootState } from "../redux/store";
import {
getFontSize,
getMetaKeyLabel,
isJetBrains,
isMetaEquivalentKeyPressed,
@ -73,7 +74,7 @@ const StopButton = styled.div`
margin-right: auto;
margin-left: auto;
font-size: 12px;
font-size: ${getFontSize() - 2}px;
border: 0.5px solid ${lightGray};
border-radius: ${defaultBorderRadius};
@ -109,7 +110,7 @@ const NewSessionButton = styled.div`
margin-left: 8px;
margin-top: 4px;
font-size: 12px;
font-size: ${getFontSize() - 2}px;
border-radius: ${defaultBorderRadius};
padding: 2px 6px;
@ -245,7 +246,7 @@ function GUI(props: GUIProps) {
if (u) {
setLocalStorage("ftc", u + 1);
if (u >= 150) {
if (u >= 100) {
dispatch(setShowDialog(true));
dispatch(setDialogMessage(<FTCDialog />));
posthog?.capture("ftc_reached");

View file

@ -38,7 +38,12 @@ function Stats() {
const navigate = useNavigate();
const ideMessenger = useContext(IdeMessengerContext);
const [days, setDays] = useState<{ day: string; tokens: number }[]>([]);
const [days, setDays] = useState<
{ day: string; promptTokens: number; generatedTokens: number }[]
>([]);
const [models, setModels] = useState<
{ model: string; promptTokens: number; generatedTokens: number }[]
>([]);
useEffect(() => {
ideMessenger.request("stats/getTokensPerDay", undefined).then((days) => {
@ -46,8 +51,6 @@ function Stats() {
});
}, []);
const [models, setModels] = useState<{ model: string; tokens: number }[]>([]);
useEffect(() => {
ideMessenger
.request("stats/getTokensPerModel", undefined)
@ -78,8 +81,12 @@ function Stats() {
<h2 className="ml-2">Tokens per Day</h2>
<CopyButton
text={generateTable(
([["Day", "Tokens"]] as any).concat(
days.map((day) => [day.day, day.tokens]),
([["Day", "Generated Tokens", "Prompt Tokens"]] as any).concat(
days.map((day) => [
day.day,
day.generatedTokens,
day.promptTokens,
]),
),
)}
/>
@ -88,14 +95,16 @@ function Stats() {
<thead>
<Tr>
<Th>Day</Th>
<Th>Tokens</Th>
<Th>Generated Tokens</Th>
<Th>Prompt Tokens</Th>
</Tr>
</thead>
<tbody>
{days.map((day) => (
<Tr key={day.day} className="">
<Td>{day.day}</Td>
<Td>{day.tokens}</Td>
<Td>{day.generatedTokens}</Td>
<Td>{day.promptTokens}</Td>
</Tr>
))}
</tbody>
@ -105,8 +114,12 @@ function Stats() {
<h2 className="ml-2">Tokens per Model</h2>
<CopyButton
text={generateTable(
([["Model", "Tokens"]] as any).concat(
models.map((model) => [model.model, model.tokens]),
([["Model", "Generated Tokens", "Prompt Tokens"]] as any).concat(
models.map((model) => [
model.model,
model.generatedTokens,
model.promptTokens,
]),
),
)}
/>
@ -115,14 +128,16 @@ function Stats() {
<thead>
<Tr>
<Th>Model</Th>
<Th>Tokens</Th>
<Th>Generated Tokens</Th>
<Th>Prompt Tokens</Th>
</Tr>
</thead>
<tbody>
{models.map((model) => (
<Tr key={model.model} className="">
<Td>{model.model}</Td>
<Td>{model.tokens}</Td>
<Td>{model.generatedTokens}</Td>
<Td>{model.promptTokens}</Td>
</Tr>
))}
</tbody>

View file

@ -11,6 +11,7 @@ type LocalStorageTypes = {
inputHistory: JSONContent[];
extensionVersion: string;
indexingState: IndexingProgressUpdate;
fontSize: number;
};
export function getLocalStorage<T extends keyof LocalStorageTypes>(

View file

@ -546,7 +546,7 @@ const gpt4turbo: ModelPackage = {
contextLength: 128_000,
title: "GPT-4 Turbo",
},
providerOptions: ["openai"],
providerOptions: ["openai", "freetrial"],
icon: "openai.png",
};
@ -558,6 +558,8 @@ const gpt4o: ModelPackage = {
model: "gpt-4o",
contextLength: 128_000,
title: "GPT-4o",
systemMessage:
"You are an expert software developer. You give helpful and concise responses.",
},
providerOptions: ["openai", "freetrial"],
icon: "openai.png",
@ -1037,6 +1039,7 @@ After it's up and running, you can start using Continue.`,
{ ...claude3Haiku, title: "Claude 3 Haiku (trial)" },
{ ...gemini15Pro, title: "Gemini 1.5 Pro (trial)" },
{ ...gpt4o, title: "GPT-4o (trial)" },
{ ...gpt4turbo, title: "GPT-4-Turbo (trial)" },
{ ...gpt35turbo, title: "GPT-3.5-Turbo (trial)" },
{
...AUTODETECT,

View file

@ -50,15 +50,15 @@ if (($null -eq $cargo) -or ($null -eq $node)) {
Write-Host "`nInstalling Core extension dependencies..." -ForegroundColor White
Push-Location core
pnpm install
pnpm link --global
npm install
npm link
Pop-Location
Write-Output "`nInstalling GUI extension dependencies..." -ForegroundColor White
Push-Location gui
pnpm install
pnpm link --global @continuedev/core
pnpm run build
npm install
npm link @continuedev/core
npm run build
Pop-Location
# VSCode Extension (will also package GUI)
@ -66,10 +66,10 @@ Write-Output "`nInstalling VSCode extension dependencies..." -ForegroundColor Wh
Push-Location extensions/vscode
# This does way too many things inline but is the common denominator between many of the scripts
pnpm install
pnpm link --global @continuedev/core
npm install
npm link @continuedev/core
pnpm run package
npm run package
Pop-Location
@ -77,8 +77,8 @@ Pop-Location
Write-Output "`nInstalling binary dependencies..." -ForegroundColor White
Push-Location binary
pnpm install
pnpm run build
npm install
npm run build
Pop-Location

View file

@ -6,28 +6,28 @@
set -e
echo "Installing Core extension dependencies..."
pushd core
pnpm install
pnpm link --global
npm install
npm link
popd
echo "Installing GUI extension dependencies..."
pushd gui
pnpm install
pnpm link --global @continuedev/core
pnpm run build
npm install
npm link @continuedev/core
npm run build
popd
# VSCode Extension (will also package GUI)
echo "Installing VSCode extension dependencies..."
pushd extensions/vscode
# This does way too many things inline but is the common denominator between many of the scripts
pnpm install
pnpm link --global @continuedev/core
pnpm run package
npm install
npm link @continuedev/core
npm run package
popd
echo "Installing binary dependencies..."
pushd binary
pnpm install
pnpm run build
npm install
npm run build

30
scripts/uninstall.js Normal file
View file

@ -0,0 +1,30 @@
const fs = require("fs");
const directories = [
// gui
"./gui/node_modules",
"./gui/out",
"./gui/dist",
// core
"./core/node_modules",
"./core/dist",
// extensions/vscode
"./extensions/vscode/node_modules",
"./extensions/vscode/bin",
"./extensions/vscode/build",
"./extensions/vscode/out",
// binary
"./binary/node_modules",
"./binary/bin",
"./binary/dist",
"./binary/out",
];
directories.forEach((dir) => {
if (fs.existsSync(dir)) {
fs.rmdirSync(dir, { recursive: true });
console.log(`Removed ${dir}`);
} else {
console.log(`${dir} not found`);
}
});