Merge branch 'nate/merge-preview-to-atwood-p2' into preview

This commit is contained in:
Nate Sesti 2024-02-23 21:08:08 -05:00
commit 7d80820d73
130 changed files with 9318 additions and 3293 deletions

12
.vscode/launch.json vendored
View file

@ -5,6 +5,18 @@
"version": "0.2.0",
"compounds": [],
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Core Binary",
"skipFiles": ["<node_internals>/**"],
"program": "${workspaceFolder}/pkg/out/index.js",
"preLaunchTask": "pkg:esbuild",
"outFiles": ["${workspaceFolder}/pkg/out/**/*.js"],
"sourceMaps": true,
"smartStep": true,
"internalConsoleOptions": "openOnSessionStart"
},
{
"type": "node",
"request": "launch",

12
.vscode/tasks.json vendored
View file

@ -136,6 +136,18 @@
}
}
]
},
//
// esbuild for the core binary
{
"label": "pkg:esbuild",
"type": "shell",
"command": "npm",
"args": ["run", "esbuild"],
"problemMatcher": [],
"options": {
"cwd": "pkg"
}
}
]
}

View file

@ -111,7 +111,8 @@ export async function constructAutocompletePrompt(
line: number,
character: number
) => Promise<AutocompleteSnippet | undefined>,
options: TabAutocompleteOptions
options: TabAutocompleteOptions,
modelName: string
): Promise<{
prefix: string;
suffix: string;
@ -167,17 +168,17 @@ export async function constructAutocompletePrompt(
.join("\n");
const maxPrefixTokens =
options.maxPromptTokens * options.prefixPercentage -
countTokens(formattedSnippets, "gpt-4");
let prefix = pruneLinesFromTop(fullPrefix, maxPrefixTokens);
countTokens(formattedSnippets, modelName);
let prefix = pruneLinesFromTop(fullPrefix, maxPrefixTokens, modelName);
if (formattedSnippets.length > 0) {
prefix = formattedSnippets + "\n" + prefix;
}
const maxSuffixTokens = Math.min(
options.maxPromptTokens - countTokens(prefix, "gpt-4"),
options.maxPromptTokens - countTokens(prefix, modelName),
options.maxSuffixPercentage * options.maxPromptTokens
);
let suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens);
let suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens, modelName);
return { prefix, suffix, useFim: true, completeMultiline };
}

View file

@ -6,7 +6,6 @@ import EditSlashCommand from "./edit";
import HttpSlashCommand from "./http";
import ShareSlashCommand from "./share";
import StackOverflowSlashCommand from "./stackOverflow";
import VerticalEditSlashCommand from "./verticalEdit";
export default [
DraftIssueCommand,
@ -17,5 +16,4 @@ export default [
CommentSlashCommand,
HttpSlashCommand,
CommitMessageCommand,
VerticalEditSlashCommand,
];

View file

@ -1,12 +1,17 @@
import { SerializedContinueConfig } from "..";
const defaultConfig: SerializedContinueConfig = {
export const defaultConfig: SerializedContinueConfig = {
models: [
{
title: "GPT-4 Vision (Free Trial)",
provider: "free-trial",
model: "gpt-4-vision-preview",
},
{
title: "GPT-3.5-Turbo (Free Trial)",
provider: "free-trial",
model: "gpt-3.5-turbo",
},
{
title: "Gemini Pro (Free Trial)",
provider: "free-trial",
@ -29,7 +34,7 @@ const defaultConfig: SerializedContinueConfig = {
},
{
name: "share",
description: "Download and share this session",
description: "Export this session as markdown",
},
{
name: "cmd",
@ -56,4 +61,55 @@ const defaultConfig: SerializedContinueConfig = {
],
};
export default defaultConfig;
export const defaultConfigJetBrains: SerializedContinueConfig = {
models: [
{
title: "GPT-4 Vision (Free Trial)",
provider: "free-trial",
model: "gpt-4-vision-preview",
},
{
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: "Codellama 70b (Free Trial)",
provider: "free-trial",
model: "codellama-70b",
},
],
slashCommands: [
{
name: "edit",
description: "Edit selected code",
},
{
name: "comment",
description: "Write comments for the selected code",
},
{
name: "share",
description: "Export this session as markdown",
},
],
customCommands: [
{
name: "test",
prompt:
"Write 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: "Write unit tests for highlighted code",
},
],
contextProviders: [
{
name: "open",
params: {},
},
],
};

196
core/config/handler.ts Normal file
View file

@ -0,0 +1,196 @@
import { http, https } from "follow-redirects";
import * as fs from "fs";
import { HttpProxyAgent } from "http-proxy-agent";
import { HttpsProxyAgent } from "https-proxy-agent";
import fetch from "node-fetch";
import { ContinueConfig, ContinueRcJson, IDE, ILLM } from "..";
import { Telemetry } from "../util/posthog";
import {
BrowserSerializedContinueConfig,
finalToBrowserConfig,
loadFullConfigNode,
} from "./load";
const tls = require("tls");
export class ConfigHandler {
private savedConfig: ContinueConfig | undefined;
private savedBrowserConfig?: BrowserSerializedContinueConfig;
private readonly ide: IDE;
constructor(ide: IDE) {
this.ide = ide;
try {
this.loadConfig();
} catch (e) {
console.error("Failed to load config: ", e);
}
}
reloadConfig() {
this.savedConfig = undefined;
this.savedBrowserConfig = undefined;
this.loadConfig();
}
async getSerializedConfig(): Promise<BrowserSerializedContinueConfig> {
if (!this.savedBrowserConfig) {
this.savedConfig = await this.loadConfig();
this.savedBrowserConfig = finalToBrowserConfig(this.savedConfig);
}
return this.savedBrowserConfig;
}
async loadConfig(): Promise<ContinueConfig> {
try {
if (this.savedConfig) {
return this.savedConfig;
}
let workspaceConfigs: ContinueRcJson[] = [];
try {
workspaceConfigs = await this.ide.getWorkspaceConfigs();
} catch (e) {
console.warn("Failed to load workspace configs");
}
const ideInfo = await this.ide.getIdeInfo();
this.savedConfig = await loadFullConfigNode(
this.ide.readFile,
workspaceConfigs,
ideInfo.ideType
);
this.savedConfig.allowAnonymousTelemetry =
this.savedConfig.allowAnonymousTelemetry &&
(await this.ide.isTelemetryEnabled());
// Setup telemetry only after (and if) we know it is enabled
await Telemetry.setup(
this.savedConfig.allowAnonymousTelemetry ?? true,
await this.ide.getUniqueId()
);
return this.savedConfig;
} catch (e: any) {
console.error("Failed to loadConfig: ", e.message);
throw new Error("Failed to loadConfig: " + e.message);
}
}
setupLlm(llm: ILLM): ILLM {
const TIMEOUT = 7200; // 7200 seconds = 2 hours
// Since we know this is happening in Node.js, we can add requestOptions through a custom agent
const ca = [...tls.rootCertificates];
const customCerts =
typeof llm.requestOptions?.caBundlePath === "string"
? [llm.requestOptions?.caBundlePath]
: llm.requestOptions?.caBundlePath;
if (customCerts) {
ca.push(
...customCerts.map((customCert) => fs.readFileSync(customCert, "utf8"))
);
}
let timeout = (llm.requestOptions?.timeout || TIMEOUT) * 1000; // measured in ms
const agentOptions = {
ca,
rejectUnauthorized: llm.requestOptions?.verifySsl,
timeout,
sessionTimeout: timeout,
keepAlive: true,
keepAliveMsecs: timeout,
};
const proxy = llm.requestOptions?.proxy;
llm._fetch = async (input, init) => {
// Create agent
const protocol = new URL(input).protocol === "https:" ? https : http;
const agent = proxy
? new URL(input).protocol === "https:"
? new HttpsProxyAgent(proxy, agentOptions)
: new HttpProxyAgent(proxy, agentOptions)
: new protocol.Agent(agentOptions);
const headers: { [key: string]: string } =
llm!.requestOptions?.headers || {};
for (const [key, value] of Object.entries(init?.headers || {})) {
headers[key] = value as string;
}
// Replace localhost with 127.0.0.1
input = new URL(input);
if (input.hostname === "localhost") {
input.hostname = "127.0.0.1";
}
let updatedBody: string | undefined = undefined;
try {
if (
llm.requestOptions?.extraBodyProperties &&
typeof init.body === "string"
) {
const parsedBody = JSON.parse(init.body);
updatedBody = JSON.stringify({
...parsedBody,
...llm.requestOptions.extraBodyProperties,
});
}
} catch (e) {
console.log("Unable to parse HTTP request body: ", e);
}
const resp = await fetch(input, {
...init,
body: updatedBody ?? init.body,
headers,
agent,
});
if (!resp.ok) {
let text = await resp.text();
if (resp.status === 404 && !resp.url.includes("/v1")) {
if (text.includes("try pulling it first")) {
const model = JSON.parse(text).error.split(" ")[1].slice(1, -1);
text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`;
} else if (text.includes("/api/chat")) {
text =
"The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue.";
} else {
text =
"This may mean that you forgot to add '/v1' to the end of your 'apiBase' in config.json.";
}
}
throw new Error(
`HTTP ${resp.status} ${resp.statusText} from ${resp.url}\n\n${text}`
);
}
return resp;
};
llm.writeLog = async (log: string) => {
// const outputChannel = vscode.window.createOutputChannel(
// "Continue - LLM Prompt/Completion"
// );
// outputChannel.appendLine(
// "=========================================================================="
// );
// outputChannel.appendLine(
// "=========================================================================="
// );
// outputChannel.append(log);
};
return llm;
}
async llmFromTitle(title?: string): Promise<ILLM> {
const config = await this.loadConfig();
const model =
config.models.find((m) => m.title === title) || config.models[0];
if (!model) {
throw new Error("No model found");
}
return this.setupLlm(model);
}
}

View file

@ -1,4 +1,5 @@
import * as fs from "fs";
import path from "path";
import {
BrowserSerializedContinueConfig,
Config,
@ -9,11 +10,11 @@ import {
CustomLLM,
EmbeddingsProviderDescription,
IContextProvider,
IdeType,
ModelDescription,
SerializedContinueConfig,
SlashCommand,
} from "..";
import {
slashCommandFromDescription,
slashFromCustomCommand,
@ -36,6 +37,7 @@ import {
getContinueDotEnv,
migrate,
} from "../util/paths";
const { execSync } = require("child_process");
function resolveSerializedConfig(filepath: string): SerializedContinueConfig {
let content = fs.readFileSync(filepath, "utf8");
@ -59,9 +61,10 @@ function resolveSerializedConfig(filepath: string): SerializedContinueConfig {
function loadSerializedConfig(
workspaceConfigs: ContinueRcJson[],
remoteConfigServerUrl: URL | undefined
remoteConfigServerUrl: URL | undefined,
ideType: IdeType
): SerializedContinueConfig {
const configPath = getConfigJsonPath();
const configPath = getConfigJsonPath(ideType);
let config = resolveSerializedConfig(configPath);
if (config.allowAnonymousTelemetry === undefined) {
config.allowAnonymousTelemetry = true;
@ -320,53 +323,101 @@ function finalToBrowserConfig(
};
}
async function buildConfigTs(browser: boolean) {
function getTarget() {
const os =
{
aix: "linux",
darwin: "darwin",
freebsd: "linux",
linux: "linux",
openbsd: "linux",
sunos: "linux",
win32: "win32",
}[process.platform as string] ?? "linux";
const arch = {
arm: "arm64",
arm64: "arm64",
ia32: "x64",
loong64: "arm64",
mips: "arm64",
mipsel: "arm64",
ppc: "x64",
ppc64: "x64",
riscv64: "arm64",
s390: "x64",
s390x: "x64",
x64: "x64",
}[process.arch];
return `${os}-${arch}`;
}
function escapeSpacesInPath(p: string): string {
return p.replace(/ /g, "\\ ");
}
async function buildConfigTs() {
if (!fs.existsSync(getConfigTsPath())) {
return undefined;
}
try {
// Dynamic import esbuild so potentially disastrous errors can be caught
const esbuild = require("esbuild");
if (process.env.IS_BINARY === "true") {
execSync(
escapeSpacesInPath(path.dirname(process.execPath)) +
`/esbuild${
getTarget().startsWith("win32") ? ".exe" : ""
} ${escapeSpacesInPath(
getConfigTsPath()
)} --bundle --outfile=${escapeSpacesInPath(
getConfigJsPath()
)} --platform=node --format=cjs --sourcemap --external:fetch --external:fs --external:path --external:os --external:child_process`
);
} else {
// Dynamic import esbuild so potentially disastrous errors can be caught
const esbuild = require("esbuild");
await esbuild.build({
entryPoints: [getConfigTsPath()],
bundle: true,
platform: browser ? "browser" : "node",
format: browser ? "esm" : "cjs",
outfile: getConfigJsPath(!browser),
external: ["fetch", "fs", "path", "os", "child_process"],
sourcemap: true,
});
await esbuild.build({
entryPoints: [getConfigTsPath()],
bundle: true,
platform: "node",
format: "cjs",
outfile: getConfigJsPath(),
external: ["fetch", "fs", "path", "os", "child_process"],
sourcemap: true,
});
}
} catch (e) {
throw new Error(
console.log(
"Build error. Please check your ~/.continue/config.ts file: " + e
);
return undefined;
}
if (!fs.existsSync(getConfigJsPath(!browser))) {
if (!fs.existsSync(getConfigJsPath())) {
return undefined;
}
return fs.readFileSync(getConfigJsPath(!browser), "utf8");
return fs.readFileSync(getConfigJsPath(), "utf8");
}
async function loadFullConfigNode(
readFile: (filepath: string) => Promise<string>,
workspaceConfigs: ContinueRcJson[],
remoteConfigServerUrl: URL | undefined
remoteConfigServerUrl: URL | undefined,
ideType: IdeType
): Promise<ContinueConfig> {
let serialized = loadSerializedConfig(
workspaceConfigs,
remoteConfigServerUrl
remoteConfigServerUrl,
ideType
);
let intermediate = serializedToIntermediateConfig(serialized);
const configJsContents = await buildConfigTs(false);
const configJsContents = await buildConfigTs();
if (configJsContents) {
try {
// Try config.ts first
const configJsPath = getConfigJsPath(true);
const configJsPath = getConfigJsPath();
const module = await require(configJsPath);
delete require.cache[require.resolve(configJsPath)];
if (!module.modifyConfig) {

View file

@ -15,7 +15,11 @@ declare global {
};
colorThemeName?: string;
workspacePaths?: string[];
postIntellijMessage?: (type: string, data: any) => void;
postIntellijMessage?: (
messageType: string,
data: any,
messageIde: string
) => void;
}
}
@ -313,13 +317,24 @@ declare global {
message: string;
}
export type IdeType = "vscode" | "jetbrains";
export interface IdeInfo {
ideType: IdeType;
name: string;
version: string;
remoteName: string;
}
export interface IDE {
getSerializedConfig(): Promise<BrowserSerializedContinueConfig>;
getIdeInfo(): Promise<IdeInfo>;
getDiff(): Promise<string>;
isTelemetryEnabled(): Promise<boolean>;
getUniqueId(): Promise<string>;
getTerminalContents(): Promise<string>;
listWorkspaceContents(directory?: string): Promise<string[]>;
listFolders(): Promise<string[]>;
getWorkspaceDirs(): Promise<string[]>;
getWorkspaceConfigs(): Promise<ContinueRcJson[]>;
writeFile(path: string, contents: string): Promise<void>;
showVirtualFile(title: string, contents: string): Promise<void>;
getContinueDir(): Promise<string>;
@ -327,6 +342,7 @@ declare global {
runCommand(command: string): Promise<void>;
saveFile(filepath: string): Promise<void>;
readFile(filepath: string): Promise<string>;
readRangeInFile(filepath: string, range: Range): Promise<string>;
showLines(
filepath: string,
startLine: number,
@ -337,34 +353,13 @@ declare global {
newContents: string,
stepIndex: number
): Promise<void>;
verticalDiffUpdate(
filepath: string,
startLine: number,
endLine: number,
diffLine: DiffLine
): Promise<void>;
getOpenFiles(): Promise<string[]>;
getPinnedFiles(): Promise<string[]>;
getSearchResults(query: string): Promise<string>;
subprocess(command: string): Promise<[string, string]>;
getProblems(filepath?: string | undefined): Promise<Problem[]>;
getBranch(dir: string): Promise<string>;
// Embeddings
/**
* Returns list of [tag, filepath, hash of contents] that need to be embedded
*/
getFilesToEmbed(providerId: string): Promise<[string, string, string][]>;
sendEmbeddingForChunk(
chunk: Chunk,
embedding: number[],
tags: string[]
): void;
retrieveChunks(
text: string,
n: number,
directory: string | undefined
): Promise<Chunk[]>;
getStats(directory: string): Promise<{ [path: string]: number }>;
}
// Slash Commands
@ -377,6 +372,8 @@ declare global {
input: string;
params?: { [key: string]: any } | undefined;
contextItems: ContextItemWithId[];
selectedCode: RangeInFile[];
config: ContinueConfig;
}
export interface SlashCommand {

38
core/config/util.ts Normal file
View file

@ -0,0 +1,38 @@
import { readFileSync, writeFileSync } from "fs";
import { ModelDescription } from "..";
import { editConfigJson, getConfigJsonPath } from "../util/paths";
export function addModel(model: ModelDescription) {
const config = readFileSync(getConfigJsonPath(), "utf8");
const configJson = JSON.parse(config);
configJson.models.push(model);
const newConfigString = JSON.stringify(
configJson,
(key, value) => {
return value === null ? undefined : value;
},
2
);
writeFileSync(getConfigJsonPath(), newConfigString);
return newConfigString;
}
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;
});
return config;
});
}
export function deleteModel(title: string) {
editConfigJson((config) => {
config.models = config.models.filter((m: any) => m.title !== title);
return config;
});
}

View file

@ -1,5 +1,6 @@
import { Chunk, ContextItem, ContextProviderExtras, ILLM } from "..";
import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearch";
import { LanceDbIndex } from "../indexing/LanceDbIndex";
import { ChunkCodebaseIndex } from "../indexing/chunk/ChunkCodebaseIndex";
import { IndexTag } from "../indexing/types";
import { llmCanGenerateInParallel } from "../llm/autodetect";
@ -147,7 +148,11 @@ export async function retrieveContextItemsFromEmbeddings(
console.warn("Error retrieving from FTS:", e);
}
let vecResults = await extras.ide.retrieveChunks(
const lanceDbIndex = new LanceDbIndex(extras.embeddingsProvider, (path) =>
extras.ide.readFile(path)
);
let vecResults = await lanceDbIndex.retrieve(
tags,
extras.fullInput,
nRetrieve,
filterDirectory

View file

@ -1,131 +0,0 @@
import { Chunk, DiffLine, Problem } from "..";
import { BrowserSerializedContinueConfig } from "../config/load";
import { IDE } from "../index";
import { ideRequest } from "./messaging";
async function r(messageType: string, options: any = {}) {
return await ideRequest(messageType, options);
}
export class ExtensionIde implements IDE {
async getSerializedConfig(): Promise<BrowserSerializedContinueConfig> {
return await r("getSerializedConfig");
}
async getDiff() {
return await r("getDiff");
}
async getTerminalContents() {
return await r("getTerminalContents");
}
async listWorkspaceContents(directory?: string): Promise<string[]> {
return await r("listWorkspaceContents");
}
async getWorkspaceDirs(): Promise<string[]> {
return await r("getWorkspaceDirs");
}
async showLines(
filepath: string,
startLine: number,
endLine: number
): Promise<void> {
return await r("showLines", { filepath, startLine, endLine });
}
async listFolders(): Promise<string[]> {
return await r("listFolders");
}
_continueDir: string | null = null;
async getContinueDir(): Promise<string> {
if (this._continueDir) {
return this._continueDir;
}
const dir = await r("getContinueDir");
this._continueDir = dir;
return dir;
}
async writeFile(path: string, contents: string): Promise<void> {
await r("writeFile", { path, contents });
}
async showVirtualFile(title: string, contents: string): Promise<void> {
await r("showVirtualFile", { name: title, content: contents });
}
async openFile(path: string): Promise<void> {
await r("openFile", { path });
}
async runCommand(command: string): Promise<void> {
await r("runCommand", { command });
}
async saveFile(filepath: string): Promise<void> {
await r("saveFile", { filepath });
}
async readFile(filepath: string): Promise<string> {
return await r("readFile", { filepath });
}
async showDiff(
filepath: string,
newContents: string,
stepIndex: number
): Promise<void> {
await r("showDiff", { filepath, newContents, stepIndex });
}
async verticalDiffUpdate(
filepath: string,
startLine: number,
endLine: number,
diffLine: DiffLine
) {
await r("diffLine", { filepath, startLine, endLine, diffLine });
}
getOpenFiles(): Promise<string[]> {
return r("getOpenFiles");
}
getPinnedFiles(): Promise<string[]> {
return r("getPinnedFiles");
}
getSearchResults(query: string): Promise<string> {
return r("getSearchResults", { query });
}
getProblems(filepath?: string | undefined): Promise<Problem[]> {
return r("getProblems", { filepath });
}
subprocess(command: string): Promise<[string, string]> {
return r("subprocess", { command });
}
getFilesToEmbed(providerId: string): Promise<[string, string, string][]> {
return r("getFilesToEmbed", { providerId });
}
sendEmbeddingForChunk(chunk: Chunk, embedding: number[], tags: string[]) {
return r("sendChunkForFile", { chunk, embedding, tags });
}
async getBranch(dir: string): Promise<string> {
return r("getBranch", { dir });
}
retrieveChunks(
text: string,
n: number,
directory: string | undefined
): Promise<Chunk[]> {
return r("retrieveChunks", { text, n, directory });
}
}

View file

@ -1,142 +0,0 @@
// import "vscode-webview";
import { v4 as uuidv4 } from "uuid";
import { ChatMessage, LLMFullCompletionOptions, LLMReturnValue } from "..";
interface vscode {
postMessage(message: any): vscode;
}
declare const vscode: any;
function _postToIde(type: string, data: any) {
if (typeof vscode === "undefined") {
if (localStorage.getItem("ide") === "jetbrains") {
if (window.postIntellijMessage === undefined) {
console.log(
"Unable to send message: postIntellijMessage is undefined. ",
type,
data
);
throw new Error("postIntellijMessage is undefined");
}
window.postIntellijMessage?.(type, data);
return;
} else {
console.log("Unable to send message: vscode is undefined. ", type, data);
return;
}
}
vscode.postMessage({
type,
...data,
});
}
export function postToIde(type: string, data: any, attempt: number = 0) {
try {
_postToIde(type, data);
} catch (error) {
if (attempt < 5) {
console.log(`Attempt ${attempt} failed. Retrying...`);
setTimeout(
() => postToIde(type, data, attempt + 1),
Math.pow(2, attempt) * 1000
);
} else {
console.error("Max attempts reached. Message could not be sent.", error);
}
}
}
export async function ideRequest(type: string, message: any): Promise<any> {
// message, messageId, and type are passed back and forth
const messageId = uuidv4();
return new Promise((resolve) => {
const handler = (event: any) => {
if (event.data.messageId === messageId) {
window.removeEventListener("message", handler);
resolve(event.data.message);
}
};
window.addEventListener("message", handler);
postToIde(type, { message, messageId });
});
}
export async function* ideStreamRequest(
type: string,
message: any,
cancelToken?: AbortSignal
): AsyncGenerator<any, any> {
const messageId = uuidv4();
postToIde(type, { message, messageId });
let buffer = "";
let index = 0;
let done = false;
let returnVal = undefined;
const handler = (event: any) => {
if (event.data.messageId === messageId) {
if (event.data.message.done) {
window.removeEventListener("message", handler);
done = true;
returnVal = event.data.message.data;
} else {
buffer += event.data.message.content || "";
}
}
};
window.addEventListener("message", handler);
cancelToken?.addEventListener("abort", () => {
postToIde("abort", { messageId });
});
while (!done) {
if (buffer.length > index) {
const chunk = buffer.slice(index);
index = buffer.length;
yield chunk;
} else {
yield undefined;
}
await new Promise((resolve) => setTimeout(resolve, 50));
}
if (buffer.length > index) {
const chunk = buffer.slice(index);
index = buffer.length;
yield chunk;
}
return returnVal;
}
export async function* llmStreamChat(
modelTitle: string,
cancelToken: AbortSignal | undefined,
messages: ChatMessage[],
options: LLMFullCompletionOptions = {}
): AsyncGenerator<ChatMessage, LLMReturnValue> {
const gen = ideStreamRequest(
"llmStreamChat",
{
messages,
title: modelTitle,
completionOptions: options,
},
cancelToken
);
let next = await gen.next();
while (!next.done) {
if (next.value) {
yield { role: "user", content: next.value };
}
next = await gen.next();
}
return { prompt: next.value?.prompt, completion: next.value?.completion };
}

45
core/index.d.ts vendored
View file

@ -13,7 +13,11 @@ declare global {
};
colorThemeName?: string;
workspacePaths?: string[];
postIntellijMessage?: (type: string, data: any) => void;
postIntellijMessage?: (
messageType: string,
data: any,
messageIde: string
) => void;
}
}
@ -311,13 +315,24 @@ export class Problem {
message: string;
}
export type IdeType = "vscode" | "jetbrains";
export interface IdeInfo {
ideType: IdeType;
name: string;
version: string;
remoteName: string;
}
export interface IDE {
getSerializedConfig(): Promise<BrowserSerializedContinueConfig>;
getIdeInfo(): Promise<IdeInfo>;
getDiff(): Promise<string>;
isTelemetryEnabled(): Promise<boolean>;
getUniqueId(): Promise<string>;
getTerminalContents(): Promise<string>;
listWorkspaceContents(directory?: string): Promise<string[]>;
listFolders(): Promise<string[]>;
getWorkspaceDirs(): Promise<string[]>;
getWorkspaceConfigs(): Promise<ContinueRcJson[]>;
writeFile(path: string, contents: string): Promise<void>;
showVirtualFile(title: string, contents: string): Promise<void>;
getContinueDir(): Promise<string>;
@ -325,6 +340,7 @@ export interface IDE {
runCommand(command: string): Promise<void>;
saveFile(filepath: string): Promise<void>;
readFile(filepath: string): Promise<string>;
readRangeInFile(filepath: string, range: Range): Promise<string>;
showLines(
filepath: string,
startLine: number,
@ -335,34 +351,13 @@ export interface IDE {
newContents: string,
stepIndex: number
): Promise<void>;
verticalDiffUpdate(
filepath: string,
startLine: number,
endLine: number,
diffLine: DiffLine
): Promise<void>;
getOpenFiles(): Promise<string[]>;
getPinnedFiles(): Promise<string[]>;
getSearchResults(query: string): Promise<string>;
subprocess(command: string): Promise<[string, string]>;
getProblems(filepath?: string | undefined): Promise<Problem[]>;
getBranch(dir: string): Promise<string>;
// Embeddings
/**
* Returns list of [tag, filepath, hash of contents] that need to be embedded
*/
getFilesToEmbed(providerId: string): Promise<[string, string, string][]>;
sendEmbeddingForChunk(
chunk: Chunk,
embedding: number[],
tags: string[]
): void;
retrieveChunks(
text: string,
n: number,
directory: string | undefined
): Promise<Chunk[]>;
getStats(directory: string): Promise<{ [path: string]: number }>;
}
// Slash Commands
@ -375,6 +370,8 @@ export interface ContinueSDK {
input: string;
params?: { [key: string]: any } | undefined;
contextItems: ContextItemWithId[];
selectedCode: RangeInFile[];
config: ContinueConfig;
}
export interface SlashCommand {

View file

@ -11,7 +11,7 @@ export function* basicChunker(
let currLine = 0;
for (const line of contents.split("\n")) {
const lineTokens = countTokens(line, "gpt-4");
const lineTokens = countTokens(line);
if (chunkTokens + lineTokens > maxChunkSize - 5) {
yield { content: chunkContent, startLine, endLine: currLine - 1 };
chunkContent = "";

View file

@ -43,11 +43,11 @@ export async function* chunkDocument(
contents,
maxChunkSize
)) {
if (countTokens(chunkWithoutId.content, "gpt-4") > MAX_CHUNK_SIZE) {
if (countTokens(chunkWithoutId.content) > MAX_CHUNK_SIZE) {
console.warn(
`Chunk with more than ${maxChunkSize} tokens constructed: `,
filepath,
countTokens(chunkWithoutId.content, "gpt-4")
countTokens(chunkWithoutId.content)
);
continue;
}

View file

@ -59,10 +59,7 @@ function collapseChildren(
}
code = code.slice(node.startIndex);
let removedChild = false;
while (
countTokens(code, "gpt-4") > maxChunkSize &&
collapsedChildren.length > 0
) {
while (countTokens(code) > maxChunkSize && collapsedChildren.length > 0) {
removedChild = true;
// Remove children starting at the end - TODO: Add multiple chunks so no children are missing
const childCode = collapsedChildren.pop()!;
@ -169,7 +166,7 @@ function* getSmartCollapsedChunks(
// Keep entire text if not over size
if (
(root || node.type in collapsedNodeConstructors) &&
countTokens(node.text, "gpt-4") < maxChunkSize
countTokens(node.text) < maxChunkSize
) {
yield {
content: node.text,

View file

@ -57,7 +57,7 @@ export async function* markdownChunker(
maxChunkSize: number,
hLevel: number
): AsyncGenerator<ChunkWithoutID> {
if (countTokens(content, "gpt-4") <= maxChunkSize) {
if (countTokens(content) <= maxChunkSize) {
const header = findHeader(content.split("\n"));
yield {
content,
@ -122,8 +122,7 @@ export async function* markdownChunker(
for (const section of sections) {
for await (const chunk of markdownChunker(
section.content,
maxChunkSize -
(section.header ? countTokens(section.header, "gpt-4") : 0),
maxChunkSize - (section.header ? countTokens(section.header) : 0),
hLevel + 1
)) {
yield {

View file

@ -1,37 +1,12 @@
import {
PipelineType,
env,
pipeline,
} from "../../vendor/node_modules/@xenova/transformers";
import { Worker } from "worker_threads";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider";
env.allowLocalModels = true;
env.allowRemoteModels = false;
if (typeof window === "undefined") {
// The embeddings provider should just never be called in the browser
env.localModelPath = `${__dirname}/../models`;
}
class EmbeddingsPipeline {
static task: PipelineType = "feature-extraction";
static model = "all-MiniLM-L6-v2";
static instance: any | null = null;
static async getInstance() {
if (this.instance === null) {
this.instance = await pipeline(this.task, this.model);
}
return this.instance;
}
}
class TransformersJsEmbeddingsProvider extends BaseEmbeddingsProvider {
static MaxGroupSize: number = 4;
static ModelName: string = "all-MiniLM-L2-v6";
constructor() {
super({ model: "all-MiniLM-L2-v6" });
super({ model: TransformersJsEmbeddingsProvider.ModelName });
}
get id(): string {
@ -39,33 +14,27 @@ class TransformersJsEmbeddingsProvider extends BaseEmbeddingsProvider {
}
async embed(chunks: string[]) {
let extractor = await EmbeddingsPipeline.getInstance();
return new Promise((resolve, reject) => {
const worker = new Worker("./TransformersJsWorkerThread.js");
if (!extractor) {
throw new Error("TransformerJS embeddings pipeline is not initialized");
}
worker.postMessage(chunks);
if (chunks.length === 0) {
return [];
}
let outputs = [];
for (
let i = 0;
i < chunks.length;
i += TransformersJsEmbeddingsProvider.MaxGroupSize
) {
let chunkGroup = chunks.slice(
i,
i + TransformersJsEmbeddingsProvider.MaxGroupSize
);
let output = await extractor(chunkGroup, {
pooling: "mean",
normalize: true,
worker.on("message", (result) => {
if (result.error) {
reject(new Error(result.error));
} else {
resolve(result);
}
});
outputs.push(...output.tolist());
}
return outputs;
worker.on("error", reject);
worker.on("exit", (code) => {
if (code !== 0) {
reject(new Error(`Worker stopped with exit code ${code}`));
}
});
}) as any;
}
}

View file

@ -0,0 +1,58 @@
import {
env,
pipeline,
} from "../../vendor/node_modules/@xenova/transformers/types/transformers";
import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider";
const { parentPort } = require("worker_threads");
env.allowLocalModels = true;
env.allowRemoteModels = false;
if (typeof window === "undefined") {
// The embeddings provider should just never be called in the browser
env.localModelPath = `${__dirname}/../models`;
}
class EmbeddingsPipeline {
static task = "feature-extraction";
static model = TransformersJsEmbeddingsProvider.ModelName;
static instance = null;
static async getInstance() {
if (this.instance === null) {
this.instance = await pipeline(this.task, this.model);
}
return this.instance;
}
}
parentPort.on("message", async (chunks) => {
try {
const extractor = await EmbeddingsPipeline.getInstance();
if (!extractor) {
throw new Error("TransformerJS embeddings pipeline is not initialized");
}
let outputs = [];
for (
let i = 0;
i < chunks.length;
i += TransformersJsEmbeddingsProvider.MaxGroupSize
) {
let chunkGroup = chunks.slice(
i,
i + TransformersJsEmbeddingsProvider.MaxGroupSize
);
let output = await extractor(chunkGroup, {
pooling: "mean",
normalize: true,
});
outputs.push(...output.tolist());
}
parentPort.postMessage(outputs);
} catch (error) {
parentPort.postMessage({ error: error.message });
}
});

View file

@ -0,0 +1,94 @@
import { IDE, IndexingProgressUpdate } from "..";
import { ConfigHandler } from "../config/handler";
import { FullTextSearchCodebaseIndex } from "./FullTextSearch";
import { LanceDbIndex } from "./LanceDbIndex";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex";
import { getComputeDeleteAddRemove } from "./refreshIndex";
import { CodebaseIndex, IndexTag } from "./types";
export class CodebaseIndexer {
configHandler: ConfigHandler;
ide: IDE;
constructor(configHandler: ConfigHandler, ide: IDE) {
this.configHandler = configHandler;
this.ide = ide;
}
private async getIndexesToBuild(): Promise<CodebaseIndex[]> {
const config = await this.configHandler.loadConfig();
const indexes = [
new ChunkCodebaseIndex(this.ide.readFile.bind(this.ide)), // Chunking must come first
new LanceDbIndex(
config.embeddingsProvider,
this.ide.readFile.bind(this.ide)
),
new FullTextSearchCodebaseIndex(),
];
return indexes;
}
async *refresh(
workspaceDirs: string[]
): AsyncGenerator<IndexingProgressUpdate> {
const config = await this.configHandler.loadConfig();
if (config.disableIndexing) {
return;
}
const indexesToBuild = await this.getIndexesToBuild();
let completedDirs = 0;
for (let directory of workspaceDirs) {
const stats = await this.ide.getStats(directory);
const branch = await this.ide.getBranch(directory);
let completedIndexes = 0;
try {
for (let codebaseIndex of indexesToBuild) {
const tag: IndexTag = {
directory,
branch,
artifactId: codebaseIndex.artifactId,
};
const [results, markComplete] = await getComputeDeleteAddRemove(
tag,
{ ...stats },
(filepath) => this.ide.readFile(filepath)
);
for await (let { progress, desc } of codebaseIndex.update(
tag,
results,
markComplete
)) {
yield {
progress:
(completedDirs +
(completedIndexes + progress) / indexesToBuild.length) /
workspaceDirs.length,
desc,
};
}
completedIndexes++;
yield {
progress:
(completedDirs + completedIndexes / indexesToBuild.length) /
workspaceDirs.length,
desc: "Completed indexing " + codebaseIndex.artifactId,
};
}
} catch (e) {
console.warn("Error refreshing index: ", e);
}
completedDirs++;
yield {
progress: completedDirs / workspaceDirs.length,
desc: "Indexing Complete",
};
}
}
}

View file

@ -1,16 +1,29 @@
import { encodingForModel as _encodingForModel, Tiktoken } from "js-tiktoken";
import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken";
// @ts-expect-error
import llamaTokenizer from "llama-tokenizer-js";
import { ChatMessage, MessageContent, MessagePart } from "..";
import { autodetectTemplateType } from "./autodetect";
import { TOKEN_BUFFER_FOR_SAFETY } from "./constants";
let encoding: Tiktoken | null = null;
interface Encoding {
encode: Tiktoken["encode"];
decode: Tiktoken["decode"];
}
function encodingForModel(modelName: string): Tiktoken {
if (encoding) {
return encoding;
let gptEncoding: Encoding | null = null;
function encodingForModel(modelName: string): Encoding {
const modelType = autodetectTemplateType(modelName);
if (!modelType || modelType === "none") {
if (!gptEncoding) {
gptEncoding = _encodingForModel("gpt-4");
}
return gptEncoding;
}
encoding = _encodingForModel("gpt-4");
return encoding;
return llamaTokenizer;
}
function countImageTokens(content: MessagePart): number {
@ -21,7 +34,11 @@ function countImageTokens(content: MessagePart): number {
}
}
function countTokens(content: MessageContent, modelName: string): number {
function countTokens(
content: MessageContent,
// defaults to llama2 because the tokenizer tends to produce more tokens
modelName: string = "llama2"
): number {
const encoding = encodingForModel(modelName);
if (Array.isArray(content)) {
return content.reduce((acc, part) => {
@ -72,21 +89,29 @@ function countChatMessageTokens(
return countTokens(chatMessage.content, modelName) + TOKENS_PER_MESSAGE;
}
function pruneLinesFromTop(prompt: string, maxTokens: number): string {
let totalTokens = countTokens(prompt, "gpt-4");
function pruneLinesFromTop(
prompt: string,
maxTokens: number,
modelName: string
): string {
let totalTokens = countTokens(prompt, modelName);
const lines = prompt.split("\n");
while (totalTokens > maxTokens && lines.length > 0) {
totalTokens -= countTokens(lines.shift()!, "gpt-4");
totalTokens -= countTokens(lines.shift()!, modelName);
}
return lines.join("\n");
}
function pruneLinesFromBottom(prompt: string, maxTokens: number): string {
let totalTokens = countTokens(prompt, "gpt-4");
function pruneLinesFromBottom(
prompt: string,
maxTokens: number,
modelName: string
): string {
let totalTokens = countTokens(prompt, modelName);
const lines = prompt.split("\n");
while (totalTokens > maxTokens && lines.length > 0) {
totalTokens -= countTokens(lines.pop()!, "gpt-4");
totalTokens -= countTokens(lines.pop()!, modelName);
}
return lines.join("\n");

View file

@ -25,40 +25,44 @@ class Ollama extends BaseLLM {
method: "POST",
headers: {},
body: JSON.stringify({ name: this._getModel() }),
}).then(async (response) => {
if (response.status !== 200) {
console.warn(
"Error calling Ollama /api/show endpoint: ",
await response.text()
);
return;
}
const body = await response.json();
if (body.parameters) {
const params = [];
for (let line of body.parameters.split("\n")) {
let parts = line.split(" ");
if (parts.length < 2) {
continue;
}
let key = parts[0];
let value = parts[parts.length - 1];
switch (key) {
case "num_ctx":
this.contextLength = parseInt(value);
break;
case "stop":
if (!this.completionOptions.stop) {
this.completionOptions.stop = [];
}
this.completionOptions.stop.push(value);
break;
default:
break;
})
.then(async (response) => {
if (response.status !== 200) {
console.warn(
"Error calling Ollama /api/show endpoint: ",
await response.text()
);
return;
}
const body = await response.json();
if (body.parameters) {
const params = [];
for (let line of body.parameters.split("\n")) {
let parts = line.split(" ");
if (parts.length < 2) {
continue;
}
let key = parts[0];
let value = parts[parts.length - 1];
switch (key) {
case "num_ctx":
this.contextLength = parseInt(value);
break;
case "stop":
if (!this.completionOptions.stop) {
this.completionOptions.stop = [];
}
this.completionOptions.stop.push(value);
break;
default:
break;
}
}
}
}
});
})
.catch((e) => {
console.warn(`Error calling Ollama /api/show endpoint: ${e}`);
});
}
private _getModel() {

243
core/package-lock.json generated
View file

@ -15,9 +15,13 @@
"adf-to-md": "^1.1.0",
"axios": "^1.6.7",
"cheerio": "^1.0.0-rc.12",
"commander": "^12.0.0",
"dotenv": "^16.3.1",
"fastest-levenshtein": "^1.0.16",
"follow-redirects": "^1.15.5",
"handlebars": "^4.7.8",
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"js-tiktoken": "^1.0.8",
"llm-code-highlighter": "^0.0.13",
"node-fetch": "^3.3.2",
@ -35,6 +39,7 @@
"web-tree-sitter": "^0.20.8"
},
"devDependencies": {
"@types/follow-redirects": "^1.14.4",
"@types/handlebars": "^4.1.0",
"@types/jest": "^29.5.11",
"@types/jquery": "^3.5.29",
@ -2046,6 +2051,15 @@
"resolved": "https://registry.npmjs.org/@types/command-line-usage/-/command-line-usage-5.0.2.tgz",
"integrity": "sha512-n7RlEEJ+4x4TS7ZQddTmNSxP+zziEG0TNsMfiRIxcIVXt71ENJ9ojeXmGO3wPoTdn7pJcU2xc3CJYMktNT6DPg=="
},
"node_modules/@types/follow-redirects": {
"version": "1.14.4",
"resolved": "https://registry.npmjs.org/@types/follow-redirects/-/follow-redirects-1.14.4.tgz",
"integrity": "sha512-GWXfsD0Jc1RWiFmMuMFCpXMzi9L7oPDVwxUnZdg89kDNnqsRfUKXEtUYtA98A6lig1WXH/CYY/fvPW9HuN5fTA==",
"dev": true,
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/graceful-fs": {
"version": "4.1.9",
"resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.9.tgz",
@ -2251,15 +2265,14 @@
}
},
"node_modules/agent-base": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
"integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",
"optional": true,
"version": "7.1.0",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.0.tgz",
"integrity": "sha512-o/zjMZRhJxny7OyEF+Op8X+efiELC7k7yOjMzgfzVqOzXqkBkWI79YoTdOtsuWd5BWhAGAuOY/Xa6xpiaWXiNg==",
"dependencies": {
"debug": "4"
"debug": "^4.3.4"
},
"engines": {
"node": ">= 6.0.0"
"node": ">= 14"
}
},
"node_modules/agentkeepalive": {
@ -2401,6 +2414,20 @@
"node": "^12.13.0 || ^14.15.0 || >=16.0.0"
}
},
"node_modules/are-we-there-yet/node_modules/readable-stream": {
"version": "3.6.2",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
"optional": true,
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
"util-deprecate": "^1.0.1"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/argparse": {
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz",
@ -2740,6 +2767,42 @@
"readable-stream": "^3.4.0"
}
},
"node_modules/bl/node_modules/buffer": {
"version": "5.7.1",
"resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
"integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"dependencies": {
"base64-js": "^1.3.1",
"ieee754": "^1.1.13"
}
},
"node_modules/bl/node_modules/readable-stream": {
"version": "3.6.2",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
"util-deprecate": "^1.0.1"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/boolbase": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz",
@ -2820,9 +2883,9 @@
}
},
"node_modules/buffer": {
"version": "5.7.1",
"resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
"integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
"integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
"funding": [
{
"type": "github",
@ -2837,9 +2900,10 @@
"url": "https://feross.org/support"
}
],
"optional": true,
"dependencies": {
"base64-js": "^1.3.1",
"ieee754": "^1.1.13"
"ieee754": "^1.2.1"
}
},
"node_modules/buffer-from": {
@ -3201,6 +3265,14 @@
"node": ">=12.17"
}
},
"node_modules/commander": {
"version": "12.0.0",
"resolved": "https://registry.npmjs.org/commander/-/commander-12.0.0.tgz",
"integrity": "sha512-MwVNWlYjDTtOjX5PiD7o5pK0UrFU/OYgcJfjjK4RaHZETNtjJqrZa9Y9ds88+A+f+d5lv+561eZ+yCKoS3gbAA==",
"engines": {
"node": ">=18"
}
},
"node_modules/concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
@ -4928,30 +5000,27 @@
"optional": true
},
"node_modules/http-proxy-agent": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-4.0.1.tgz",
"integrity": "sha512-k0zdNgqWTGA6aeIRVpvfVob4fL52dTfaehylg0Y4UvSySvOq/Y+BOyPrgpUrA7HylqvU8vIZGsRuXmspskV0Tg==",
"optional": true,
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.1.tgz",
"integrity": "sha512-My1KCEPs6A0hb4qCVzYp8iEvA8j8YqcvXLZZH8C9OFuTYpYjHE7N2dtG3mRl1HMD4+VGXpF3XcDVcxGBT7yDZQ==",
"dependencies": {
"@tootallnate/once": "1",
"agent-base": "6",
"debug": "4"
"agent-base": "^7.1.0",
"debug": "^4.3.4"
},
"engines": {
"node": ">= 6"
"node": ">= 14"
}
},
"node_modules/https-proxy-agent": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",
"integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==",
"optional": true,
"version": "7.0.3",
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.3.tgz",
"integrity": "sha512-kCnwztfX0KZJSLOBrcL0emLeFako55NWMovvyPP2AjsghNk9RB1yjSI+jVumPHYZsNXegNoqupSW9IY3afSH8w==",
"dependencies": {
"agent-base": "6",
"agent-base": "^7.0.2",
"debug": "4"
},
"engines": {
"node": ">= 6"
"node": ">= 14"
}
},
"node_modules/human-signals": {
@ -6212,6 +6281,11 @@
"integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==",
"dev": true
},
"node_modules/llama-tokenizer-js": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/llama-tokenizer-js/-/llama-tokenizer-js-1.1.3.tgz",
"integrity": "sha512-+BUgsLCXVQJkjiD/t7PdESLn+yXJIRX/BJfwzVVYfKZ9aN3gsP9xoadBZxKnCxGz2Slby+S7x41gUr2TKNaS4Q=="
},
"node_modules/llm-code-highlighter": {
"version": "0.0.13",
"resolved": "https://registry.npmjs.org/llm-code-highlighter/-/llm-code-highlighter-0.0.13.tgz",
@ -6358,6 +6432,45 @@
"node": ">= 10"
}
},
"node_modules/make-fetch-happen/node_modules/agent-base": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
"integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",
"optional": true,
"dependencies": {
"debug": "4"
},
"engines": {
"node": ">= 6.0.0"
}
},
"node_modules/make-fetch-happen/node_modules/http-proxy-agent": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-4.0.1.tgz",
"integrity": "sha512-k0zdNgqWTGA6aeIRVpvfVob4fL52dTfaehylg0Y4UvSySvOq/Y+BOyPrgpUrA7HylqvU8vIZGsRuXmspskV0Tg==",
"optional": true,
"dependencies": {
"@tootallnate/once": "1",
"agent-base": "6",
"debug": "4"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/make-fetch-happen/node_modules/https-proxy-agent": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",
"integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==",
"optional": true,
"dependencies": {
"agent-base": "6",
"debug": "4"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/make-fetch-happen/node_modules/lru-cache": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
@ -7339,6 +7452,19 @@
"resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz",
"integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg=="
},
"node_modules/prebuild-install/node_modules/readable-stream": {
"version": "3.6.2",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
"util-deprecate": "^1.0.1"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/prebuild-install/node_modules/tar-fs": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz",
@ -7559,16 +7685,19 @@
"dev": true
},
"node_modules/readable-stream": {
"version": "3.6.2",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
"version": "4.5.2",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.5.2.tgz",
"integrity": "sha512-yjavECdqeZ3GLXNgRXgeQEdz9fvDDkNKyHnbHRFtOr7/LcfgBcmct7t/ET+HaCTqfh06OzoAxrkN/IfjJBVe+g==",
"optional": true,
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
"util-deprecate": "^1.0.1"
"abort-controller": "^3.0.0",
"buffer": "^6.0.3",
"events": "^3.3.0",
"process": "^0.11.10",
"string_decoder": "^1.3.0"
},
"engines": {
"node": ">= 6"
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
}
},
"node_modules/regexp.prototype.flags": {
@ -7610,46 +7739,6 @@
"readable-stream": ">=4.0.0"
}
},
"node_modules/replicate/node_modules/buffer": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
"integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"optional": true,
"dependencies": {
"base64-js": "^1.3.1",
"ieee754": "^1.2.1"
}
},
"node_modules/replicate/node_modules/readable-stream": {
"version": "4.5.2",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.5.2.tgz",
"integrity": "sha512-yjavECdqeZ3GLXNgRXgeQEdz9fvDDkNKyHnbHRFtOr7/LcfgBcmct7t/ET+HaCTqfh06OzoAxrkN/IfjJBVe+g==",
"optional": true,
"dependencies": {
"abort-controller": "^3.0.0",
"buffer": "^6.0.3",
"events": "^3.3.0",
"process": "^0.11.10",
"string_decoder": "^1.3.0"
},
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
}
},
"node_modules/require-directory": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
@ -8097,6 +8186,18 @@
"node": ">= 10"
}
},
"node_modules/socks-proxy-agent/node_modules/agent-base": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
"integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",
"optional": true,
"dependencies": {
"debug": "4"
},
"engines": {
"node": ">= 6.0.0"
}
},
"node_modules/source-map": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",

View file

@ -8,6 +8,7 @@
"author": "Nate Sesti and Ty Dunn",
"license": "Apache-2.0",
"devDependencies": {
"@types/follow-redirects": "^1.14.4",
"@types/handlebars": "^4.1.0",
"@types/jest": "^29.5.11",
"@types/jquery": "^3.5.29",
@ -24,11 +25,16 @@
"adf-to-md": "^1.1.0",
"axios": "^1.6.7",
"cheerio": "^1.0.0-rc.12",
"commander": "^12.0.0",
"dotenv": "^16.3.1",
"fastest-levenshtein": "^1.0.16",
"follow-redirects": "^1.15.5",
"handlebars": "^4.7.8",
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"js-tiktoken": "^1.0.8",
"llm-code-highlighter": "^0.0.13",
"llama-tokenizer-js": "^1.1.3",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",
"ollama": "^0.4.6",

98
core/protocol.ts Normal file
View file

@ -0,0 +1,98 @@
import {
BrowserSerializedContinueConfig,
ChatMessage,
ContextItemWithId,
ContextSubmenuItem,
LLMFullCompletionOptions,
MessageContent,
PersistedSessionInfo,
RangeInFile,
SerializedContinueConfig,
SessionInfo,
} from ".";
export type ProtocolGeneratorType<T> = AsyncGenerator<{
done?: boolean;
content: T;
}>;
export type Protocol = {
// New
"update/modelChange": [string, void];
// Special
ping: [string, string];
abort: [undefined, void];
// History
"history/list": [undefined, SessionInfo[]];
"history/delete": [{ id: string }, void];
"history/load": [{ id: string }, PersistedSessionInfo];
"history/save": [PersistedSessionInfo, void];
"devdata/log": [{ tableName: string; data: any }, void];
"config/addOpenAiKey": [string, void];
"config/addModel": [
{ model: SerializedContinueConfig["models"][number] },
void,
];
"config/getBrowserSerialized": [
undefined,
Promise<BrowserSerializedContinueConfig>,
];
"config/deleteModel": [{ title: string }, void];
"config/reload": [undefined, Promise<BrowserSerializedContinueConfig>];
"context/getContextItems": [
{
name: string;
query: string;
fullInput: string;
selectedCode: RangeInFile[];
},
Promise<ContextItemWithId[]>,
];
"context/loadSubmenuItems": [
{ title: string },
Promise<ContextSubmenuItem[]>,
];
"context/addDocs": [{ title: string; url: string }, void];
"autocomplete/complete": [
{ filepath: string; line: number; column: number },
string[],
];
"command/run": [
{
input: string;
history: ChatMessage[];
modelTitle: string;
slashCommandName: string;
contextItems: ContextItemWithId[];
params: any;
historyIndex: number;
selectedCode: RangeInFile[];
},
ProtocolGeneratorType<string>,
];
"llm/complete": [
{
prompt: string;
completionOptions: LLMFullCompletionOptions;
title: string;
},
string,
];
"llm/streamComplete": [
{
prompt: string;
completionOptions: LLMFullCompletionOptions;
title: string;
},
ProtocolGeneratorType<string>,
];
"llm/streamChat": [
{
messages: ChatMessage[];
completionOptions: LLMFullCompletionOptions;
title: string;
},
ProtocolGeneratorType<MessageContent>,
];
};

View file

@ -2,10 +2,10 @@ import * as dotenv from "dotenv";
import { ContinueSDK } from "..";
import EditSlashCommand, { getPromptParts } from "../commands/slash/edit";
import { contextItemToRangeInFileWithContents } from "../commands/util";
import FileSystemIde from "../ide/filesystem";
import FreeTrial from "../llm/llms/FreeTrial";
import Ollama from "../llm/llms/Ollama";
import { dedentAndGetCommonWhitespace } from "../util";
import FileSystemIde from "../util/filesystem";
jest.setTimeout(100_000);
@ -62,6 +62,8 @@ describe("/edit slash command", () => {
history: [],
input: "implement this function",
contextItems: [TEST_CONTEXT_ITEM],
selectedCode: [],
config: {} as any,
};
let total = "";

View file

@ -18,5 +18,5 @@
"noEmitOnError": false,
"types": ["jest", "node"]
},
"include": ["./**/*.ts"]
"include": ["./**/*.ts", "indexing/embeddings/TransformersJsWorkerThread.js"]
}

8
core/util/devdata.ts Normal file
View file

@ -0,0 +1,8 @@
import { writeFileSync } from "fs";
import { getDevDataFilePath } from "./paths";
export function logDevData(tableName: string, data: any) {
const filepath: string = getDevDataFilePath(tableName);
const jsonLine = JSON.stringify(data);
writeFileSync(filepath, `${jsonLine}\n`, { flag: "a" });
}

View file

@ -1,12 +1,30 @@
import * as fs from "fs";
import { DiffLine, IDE, Problem } from "..";
import { BrowserSerializedContinueConfig } from "../config/load";
import { Chunk } from "../index";
import { getContinueGlobalPath } from "../util/paths";
import { ContinueRcJson, IDE, IdeInfo, Problem, Range } from "..";
import { getContinueGlobalPath } from "./paths";
class FileSystemIde implements IDE {
async getSerializedConfig(): Promise<BrowserSerializedContinueConfig> {
throw new Error("Not implemented");
getIdeInfo(): Promise<IdeInfo> {
return Promise.resolve({
ideType: "vscode",
name: "na",
version: "0.1",
remoteName: "na",
});
}
readRangeInFile(filepath: string, range: Range): Promise<string> {
return Promise.resolve("");
}
getStats(directory: string): Promise<{ [path: string]: number }> {
return Promise.resolve({});
}
isTelemetryEnabled(): Promise<boolean> {
return Promise.resolve(false);
}
getUniqueId(): Promise<string> {
return Promise.resolve("NOT_UNIQUE");
}
getWorkspaceConfigs(): Promise<ContinueRcJson[]> {
return Promise.resolve([]);
}
getDiff(): Promise<string> {
@ -92,15 +110,6 @@ class FileSystemIde implements IDE {
return Promise.resolve("");
}
async verticalDiffUpdate(
filepath: string,
startLine: number,
endLine: number,
diffLine: DiffLine
) {
return Promise.resolve();
}
getOpenFiles(): Promise<string[]> {
return Promise.resolve([]);
}
@ -120,20 +129,6 @@ class FileSystemIde implements IDE {
async subprocess(command: string): Promise<[string, string]> {
return ["", ""];
}
getFilesToEmbed(providerId: string): Promise<[string, string, string][]> {
return Promise.resolve([]);
}
sendEmbeddingForChunk(chunk: Chunk, embedding: number[], tags: string[]) {}
retrieveChunks(
text: string,
n: number,
directory: string | undefined
): Promise<Chunk[]> {
return Promise.resolve([]);
}
}
export default FileSystemIde;

View file

@ -1,9 +1,9 @@
import { PersistedSessionInfo, SessionInfo } from "core";
import { getSessionFilePath, getSessionsListPath } from "core/util/paths";
import * as fs from "fs";
import { PersistedSessionInfo, SessionInfo } from "..";
import { getSessionFilePath, getSessionsListPath } from "./paths";
class HistoryManager {
list(): PersistedSessionInfo[] {
list(): SessionInfo[] {
const filepath = getSessionsListPath();
if (!fs.existsSync(filepath)) {
return [];

121
core/util/messageIde.ts Normal file
View file

@ -0,0 +1,121 @@
import { ContinueRcJson, IDE, IdeInfo, Problem, Range } from "..";
export class MessageIde implements IDE {
constructor(
private readonly request: (messageType: string, data: any) => Promise<any>
) {}
getIdeInfo(): Promise<IdeInfo> {
return this.request("getIdeInfo", undefined);
}
readRangeInFile(filepath: string, range: Range): Promise<string> {
return this.request("readRangeInFile", { filepath, range });
}
getStats(directory: string): Promise<{ [path: string]: number }> {
throw new Error("Method not implemented.");
}
isTelemetryEnabled(): Promise<boolean> {
return this.request("isTelemetryEnabled", undefined);
}
getUniqueId(): Promise<string> {
return this.request("getUniqueId", undefined);
}
getWorkspaceConfigs(): Promise<ContinueRcJson[]> {
return this.request("getWorkspaceConfigs", undefined);
}
async getDiff() {
return await this.request("getDiff", undefined);
}
async getTerminalContents() {
return await this.request("getTerminalContents", undefined);
}
async listWorkspaceContents(directory?: string): Promise<string[]> {
return await this.request("listWorkspaceContents", undefined);
}
async getWorkspaceDirs(): Promise<string[]> {
return await this.request("getWorkspaceDirs", undefined);
}
async showLines(
filepath: string,
startLine: number,
endLine: number
): Promise<void> {
return await this.request("showLines", { filepath, startLine, endLine });
}
async listFolders(): Promise<string[]> {
return await this.request("listFolders", undefined);
}
_continueDir: string | null = null;
async getContinueDir(): Promise<string> {
if (this._continueDir) {
return this._continueDir;
}
const dir = await this.request("getContinueDir", undefined);
this._continueDir = dir;
return dir;
}
async writeFile(path: string, contents: string): Promise<void> {
await this.request("writeFile", { path, contents });
}
async showVirtualFile(title: string, contents: string): Promise<void> {
await this.request("showVirtualFile", { name: title, content: contents });
}
async openFile(path: string): Promise<void> {
await this.request("openFile", { path });
}
async runCommand(command: string): Promise<void> {
await this.request("runCommand", { command });
}
async saveFile(filepath: string): Promise<void> {
await this.request("saveFile", { filepath });
}
async readFile(filepath: string): Promise<string> {
return await this.request("readFile", { filepath });
}
async showDiff(
filepath: string,
newContents: string,
stepIndex: number
): Promise<void> {
await this.request("showDiff", { filepath, newContents, stepIndex });
}
getOpenFiles(): Promise<string[]> {
return this.request("getOpenFiles", undefined);
}
getPinnedFiles(): Promise<string[]> {
return this.request("getPinnedFiles", undefined);
}
getSearchResults(query: string): Promise<string> {
return this.request("getSearchResults", { query });
}
getProblems(filepath?: string | undefined): Promise<Problem[]> {
return this.request("getProblems", { filepath });
}
subprocess(command: string): Promise<[string, string]> {
return this.request("subprocess", { command });
}
async getBranch(dir: string): Promise<string> {
return this.request("getBranch", { dir });
}
}

5
core/util/messenger.ts Normal file
View file

@ -0,0 +1,5 @@
export interface Message<T = any> {
messageType: string;
messageId: string;
data: T;
}

View file

@ -2,8 +2,8 @@ import dotenv from "dotenv";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { SerializedContinueConfig } from "..";
import defaultConfig from "../config/default";
import { IdeType, SerializedContinueConfig } from "..";
import { defaultConfig, defaultConfigJetBrains } from "../config/default";
import Types from "../config/types";
export function getContinueGlobalPath(): string {
@ -43,10 +43,14 @@ export function getSessionsListPath(): string {
return filepath;
}
export function getConfigJsonPath(): string {
export function getConfigJsonPath(ideType: IdeType = "vscode"): string {
const p = path.join(getContinueGlobalPath(), "config.json");
if (!fs.existsSync(p)) {
fs.writeFileSync(p, JSON.stringify(defaultConfig, null, 2));
if (ideType === "jetbrains") {
fs.writeFileSync(p, JSON.stringify(defaultConfigJetBrains, null, 2));
} else {
fs.writeFileSync(p, JSON.stringify(defaultConfig, null, 2));
}
}
return p;
}
@ -87,13 +91,9 @@ export function getConfigTsPath(): string {
return p;
}
export function getConfigJsPath(node: boolean): string {
export function getConfigJsPath(): string {
// Do not create automatically
return path.join(
getContinueGlobalPath(),
"out",
`config${node ? ".node" : ""}.js`
);
return path.join(getContinueGlobalPath(), "out", "config.js");
}
export function getTsConfigPath(): string {
@ -220,3 +220,7 @@ export function getContinueDotEnv(): { [key: string]: string } {
return {};
}
}
export function getCoreLogsPath(): string {
return path.join(getContinueGlobalPath(), "core.log");
}

View file

@ -19,14 +19,18 @@ export class Telemetry {
if (!allow) {
Telemetry.client = undefined;
} else {
if (!Telemetry.client) {
const { PostHog } = await import("posthog-node");
Telemetry.client = new PostHog(
"phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs",
{
host: "https://app.posthog.com",
}
);
try {
if (!Telemetry.client) {
const { PostHog } = await import("posthog-node");
Telemetry.client = new PostHog(
"phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs",
{
host: "https://app.posthog.com",
}
);
}
} catch (e) {
console.error(`Failed to setup telemetry: ${e}`);
}
}
}

View file

@ -1,24 +1,16 @@
import { ContextItemWithId, DiffLine, ILLM, SlashCommand } from "../..";
import { DiffLine, ILLM } from "..";
import {
filterCodeBlockLines,
filterEnglishLinesAtEnd,
filterEnglishLinesAtStart,
filterLeadingAndTrailingNewLineInsertion,
fixCodeLlamaFirstLineIndentation,
} from "../../autocomplete/lineStream";
import { streamDiff } from "../../diff/streamDiff";
import { streamLines } from "../../diff/util";
import { stripImages } from "../../llm/countTokens";
import { gptEditPrompt } from "../../llm/templates/edit";
import {
dedentAndGetCommonWhitespace,
getMarkdownLanguageTagForFile,
renderPromptTemplate,
} from "../../util";
import {
RangeInFileWithContents,
contextItemToRangeInFileWithContents,
} from "../util";
} from "../autocomplete/lineStream";
import { streamDiff } from "../diff/streamDiff";
import { streamLines } from "../diff/util";
import { stripImages } from "../llm/countTokens";
import { gptEditPrompt } from "../llm/templates/edit";
import { dedentAndGetCommonWhitespace, renderPromptTemplate } from "../util";
function constructPrompt(
codeToEdit: string,
@ -87,38 +79,3 @@ export async function* streamDiffLines(
yield diffLine;
}
}
const VerticalEditSlashCommand: SlashCommand = {
name: "verticalEdit",
description: "Edit selected code with vertical diff",
run: async function* ({ ide, llm, input, contextItems }) {
const contextItemToEdit = contextItems.find(
(item: ContextItemWithId) =>
item.editing && item.id.providerTitle === "code"
);
if (!contextItemToEdit) {
yield "Highlight the code that you want to edit first";
return;
}
const rif: RangeInFileWithContents =
contextItemToRangeInFileWithContents(contextItemToEdit);
const startLine = rif.range.start.line;
const endLine = rif.range.end.line;
const filepath = rif.filepath;
const diffLineGenerator = streamDiffLines(
rif.contents,
llm,
input,
getMarkdownLanguageTagForFile(rif.filepath)
);
for await (const diffLine of diffLineGenerator) {
await ide.verticalDiffUpdate(filepath, startLine, endLine, diffLine);
}
},
};
export default VerticalEditSlashCommand;

2
core/vendor/package-lock.json generated vendored
View file

@ -7,7 +7,7 @@
"": {
"name": "vendor",
"version": "1.0.0",
"license": "ISC",
"license": "Apache-2.0",
"dependencies": {
"@xenova/transformers": "^2.14.0"
}

View file

@ -7,7 +7,7 @@
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"license": "Apache-2.0",
"dependencies": {
"@xenova/transformers": "^2.14.0"
}

101
core/web/webviewProtocol.ts Normal file
View file

@ -0,0 +1,101 @@
import {
ContextItemWithId,
ContinueRcJson,
DiffLine,
Problem,
Range,
} from "..";
import { RangeInFileWithContents } from "../commands/util";
import { Protocol } from "../protocol";
export type IdeProtocol = {
listWorkspaceContents: [undefined, string[]];
getWorkspaceDirs: [undefined, string[]];
listFolders: [undefined, string[]];
writeFile: [{ path: string; contents: string }, void];
showVirtualFile: [{ name: string; content: string }, void];
getContinueDir: [undefined, string];
openFile: [{ path: string }, void];
runCommand: [{ command: string }, void];
getSearchResults: [{ query: string }, string];
subprocess: [{ command: string }, [string, string]];
saveFile: [{ filepath: string }, void];
readFile: [{ filepath: string }, string];
showDiff: [
{ filepath: string; newContents: string; stepIndex: number },
void,
];
diffLine: [
{
diffLine: DiffLine;
filepath: string;
startLine: number;
endLine: number;
},
void,
];
getProblems: [{ filepath: string }, Problem[]];
getBranch: [{ dir: string }, string];
getOpenFiles: [undefined, string[]];
getPinnedFiles: [undefined, string[]];
showLines: [{ filepath: string; startLine: number; endLine: number }, void];
readRangeInFile: [{ filepath: string; range: Range }, string];
getDiff: [undefined, string];
getWorkspaceConfigs: [undefined, ContinueRcJson[]];
getTerminalContents: [undefined, string];
isTelemetryEnabled: [undefined, boolean];
getUniqueId: [undefined, string];
};
export type WebviewProtocol = Protocol &
IdeProtocol & {
onLoad: [
undefined,
{
windowId: string;
serverUrl: string;
workspacePaths: string[];
vscMachineId: string;
vscMediaUrl: string;
},
];
errorPopup: [{ message: string }, void];
applyToCurrentFile: [{ text: string }, void];
showTutorial: [undefined, void];
showFile: [{ filepath: string }, void];
openConfigJson: [undefined, void];
toggleDevTools: [undefined, void];
reloadWindow: [undefined, void];
focusEditor: [undefined, void];
toggleFullScreen: [undefined, void];
};
export type ReverseWebviewProtocol = {
setInactive: [undefined, void];
configUpdate: [undefined, void];
submitMessage: [{ message: any }, void]; // any -> JSONContent from TipTap
addContextItem: [
{
historyIndex: number;
item: ContextItemWithId;
},
void,
];
getDefaultModelTitle: [undefined, string];
newSessionWithPrompt: [{ prompt: string }, void];
userInput: [{ input: string }, void];
focusContinueInput: [undefined, void];
focusContinueInputWithoutClear: [undefined, void];
focusContinueInputWithNewSession: [undefined, void];
highlightedCode: [{ rangeInFileWithContents: RangeInFileWithContents }, void];
addModel: [undefined, void];
openSettings: [undefined, void];
viewHistory: [undefined, void];
indexProgress: [{ progress: number; desc: string }, void];
newSession: [undefined, void];
refreshSubmenuItems: [undefined, void];
setTheme: [{ theme: any }, void];
setColors: [{ [key: string]: string }, void];
};

View file

@ -899,6 +899,13 @@
resolved "https://registry.npmjs.org/@types/command-line-usage/-/command-line-usage-5.0.2.tgz"
integrity sha512-n7RlEEJ+4x4TS7ZQddTmNSxP+zziEG0TNsMfiRIxcIVXt71ENJ9ojeXmGO3wPoTdn7pJcU2xc3CJYMktNT6DPg==
"@types/follow-redirects@^1.14.4":
version "1.14.4"
resolved "https://registry.npmjs.org/@types/follow-redirects/-/follow-redirects-1.14.4.tgz"
integrity sha512-GWXfsD0Jc1RWiFmMuMFCpXMzi9L7oPDVwxUnZdg89kDNnqsRfUKXEtUYtA98A6lig1WXH/CYY/fvPW9HuN5fTA==
dependencies:
"@types/node" "*"
"@types/graceful-fs@^4.1.3":
version "4.1.9"
resolved "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.9.tgz"
@ -1685,6 +1692,11 @@ command-line-usage@^7.0.0, command-line-usage@7.0.1:
table-layout "^3.0.0"
typical "^7.1.1"
commander@^12.0.0:
version "12.0.0"
resolved "https://registry.npmjs.org/commander/-/commander-12.0.0.tgz"
integrity sha512-MwVNWlYjDTtOjX5PiD7o5pK0UrFU/OYgcJfjjK4RaHZETNtjJqrZa9Y9ds88+A+f+d5lv+561eZ+yCKoS3gbAA==
concat-map@0.0.1:
version "0.0.1"
resolved "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz"
@ -2758,6 +2770,14 @@ http-proxy-agent@^4.0.1:
agent-base "6"
debug "4"
http-proxy-agent@^7.0.1:
version "7.0.1"
resolved "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.1.tgz"
integrity sha512-My1KCEPs6A0hb4qCVzYp8iEvA8j8YqcvXLZZH8C9OFuTYpYjHE7N2dtG3mRl1HMD4+VGXpF3XcDVcxGBT7yDZQ==
dependencies:
agent-base "^7.1.0"
debug "^4.3.4"
https-proxy-agent@^5.0.0:
version "5.0.1"
resolved "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz"
@ -2766,6 +2786,14 @@ https-proxy-agent@^5.0.0:
agent-base "6"
debug "4"
https-proxy-agent@^7.0.3:
version "7.0.3"
resolved "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.3.tgz"
integrity sha512-kCnwztfX0KZJSLOBrcL0emLeFako55NWMovvyPP2AjsghNk9RB1yjSI+jVumPHYZsNXegNoqupSW9IY3afSH8w==
dependencies:
agent-base "^7.0.2"
debug "4"
human-signals@^2.1.0:
version "2.1.0"
resolved "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz"
@ -4320,7 +4348,25 @@ react-is@^18.0.0:
resolved "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz"
integrity sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==
readable-stream@^3.1.1, readable-stream@^3.4.0, readable-stream@^3.6.0:
readable-stream@^3.1.1:
version "3.6.2"
resolved "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz"
integrity sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==
dependencies:
inherits "^2.0.3"
string_decoder "^1.1.1"
util-deprecate "^1.0.1"
readable-stream@^3.4.0:
version "3.6.2"
resolved "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz"
integrity sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==
dependencies:
inherits "^2.0.3"
string_decoder "^1.1.1"
util-deprecate "^1.0.1"
readable-stream@^3.6.0:
version "3.6.2"
resolved "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz"
integrity sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==

View file

@ -1 +1,2 @@
src/main/resources/webview
src/main/resources/webview
src/main/resources/bin

View file

@ -79,6 +79,12 @@ koverReport {
}
tasks {
prepareSandbox {
from("../../pkg/bin") {
into("${intellij.pluginName.get()}/core/")
}
}
wrapper {
gradleVersion = properties("gradleVersion").get()
}

View file

@ -4,7 +4,7 @@ pluginGroup = com.github.continuedev.continueintellijextension
pluginName = continue-intellij-extension
pluginRepositoryUrl = https://github.com/continuedev/continue
# SemVer format -> https://semver.org
pluginVersion = 0.0.27
pluginVersion = 0.0.33
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
pluginSinceBuild = 223

View file

@ -4,13 +4,11 @@ import com.github.continuedev.continueintellijextension.services.ContinuePluginS
import com.google.gson.Gson
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.wm.ToolWindowManager
import java.awt.Dimension
import java.awt.GridLayout
import javax.swing.*
import javax.swing.event.DocumentEvent
import javax.swing.event.DocumentListener
@ -130,7 +128,7 @@ class QuickTextEntryAction : AnAction() {
}
continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "focusContinueInput")))
continuePluginService.sendToWebview("focusContinueInput", null)
}
}
@ -179,7 +177,7 @@ class FocusContinueInputWithoutClearAction : AnAction() {
val continuePluginService = pluginServiceFromActionEvent(e) ?: return
continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "focusContinueInputWithoutClear")))
continuePluginService.sendToWebview("focusContinueInputWithoutClear", null)
continuePluginService.ideProtocolClient?.sendHighlightedCode()
}
@ -202,7 +200,7 @@ class FocusContinueInputAction : AnAction() {
val continuePluginService = pluginServiceFromActionEvent(e) ?: return
continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "focusContinueInput")))
continuePluginService.sendToWebview("focusContinueInput", null)
continuePluginService.ideProtocolClient?.sendHighlightedCode()
}
@ -225,7 +223,7 @@ class NewContinueSessionAction : AnAction() {
val continuePluginService = pluginServiceFromActionEvent(e) ?: return
continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "focusContinueInputWithNewSession")))
continuePluginService.sendToWebview("focusContinueInputWithNewSession", null)
}
}
@ -239,6 +237,6 @@ class ViewHistoryAction : AnAction() {
val continuePluginService = pluginServiceFromActionEvent(e) ?: return
continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "viewHistory")))
continuePluginService.sendToWebview("viewHistory", null)
}
}

View file

@ -1,9 +1,7 @@
package com.github.continuedev.continueintellijextension.activities
import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath
import com.github.continuedev.continueintellijextension.`continue`.startProxyServer
import com.github.continuedev.continueintellijextension.`continue`.DefaultTextSelectionStrategy
import com.github.continuedev.continueintellijextension.`continue`.IdeProtocolClient
import com.github.continuedev.continueintellijextension.`continue`.*
import com.github.continuedev.continueintellijextension.listeners.ContinuePluginSelectionListener
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
@ -30,7 +28,9 @@ import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Paths
import javax.swing.*
import com.intellij.openapi.application.PathManager;
import com.intellij.ide.plugins.PluginManager
import com.intellij.openapi.extensions.PluginId
class WelcomeDialogWrapper(val project: Project) : DialogWrapper(true) {
private var panel: JPanel? = null
@ -78,6 +78,28 @@ class WelcomeDialogWrapper(val project: Project) : DialogWrapper(true) {
}
}
fun showTutorial(project: Project) {
ContinuePluginStartupActivity::class.java.getClassLoader().getResourceAsStream("continue_tutorial.py").use { `is` ->
if (`is` == null) {
throw IOException("Resource not found: continue_tutorial.py")
}
var content = StreamUtil.readText(`is`, StandardCharsets.UTF_8)
if (!System.getProperty("os.name").toLowerCase().contains("mac")) {
content = content.replace("⌘", "⌃")
}
val filepath = Paths.get(getContinueGlobalPath(), "continue_tutorial.py").toString()
File(filepath).writeText(content)
val virtualFile = LocalFileSystem.getInstance().findFileByPath(filepath)
ApplicationManager.getApplication().invokeLater {
if (virtualFile != null) {
FileEditorManager.getInstance(project).openFile(virtualFile, true)
}
}
}
}
class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
private val coroutineScope = CoroutineScope(Dispatchers.IO)
@ -121,6 +143,8 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
ContinuePluginService::class.java
)
val theme = GetTheme().getTheme()
val defaultStrategy = DefaultTextSelectionStrategy()
coroutineScope.launch {
@ -129,24 +153,7 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
if (!settings.continueState.shownWelcomeDialog) {
settings.continueState.shownWelcomeDialog = true
// Open continue_tutorial.py
ContinuePluginStartupActivity::class.java.getClassLoader().getResourceAsStream("continue_tutorial.py").use { `is` ->
if (`is` == null) {
throw IOException("Resource not found: continue_tutorial.py")
}
var content = StreamUtil.readText(`is`, StandardCharsets.UTF_8)
if (!System.getProperty("os.name").toLowerCase().contains("mac")) {
content = content.replace("⌘", "⌃")
}
val filepath = Paths.get(getContinueGlobalPath(), "continue_tutorial.py").toString()
File(filepath).writeText(content)
val virtualFile = LocalFileSystem.getInstance().findFileByPath(filepath)
if (virtualFile != null) {
ApplicationManager.getApplication().invokeLater {
FileEditorManager.getInstance(project).openFile(virtualFile, true)
}
}
}
showTutorial(project)
// Show the welcome dialog
// withContext(Dispatchers.Main) {
@ -156,17 +163,17 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
// settings.continueState.shownWelcomeDialog = true
}
GlobalScope.async(Dispatchers.IO) {
val ideProtocolClient = IdeProtocolClient(
val ideProtocolClient = IdeProtocolClient(
continuePluginService,
defaultStrategy,
coroutineScope,
project.basePath,
project
)
)
continuePluginService.ideProtocolClient = ideProtocolClient
continuePluginService.ideProtocolClient = ideProtocolClient
GlobalScope.async(Dispatchers.IO) {
val listener =
ContinuePluginSelectionListener(
ideProtocolClient,
@ -193,6 +200,34 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
}
}
GlobalScope.async(Dispatchers.IO) {
val myPluginId = "com.github.continuedev.continueintellijextension"
val pluginDescriptor = PluginManager.getPlugin(PluginId.getId(myPluginId))
if (pluginDescriptor == null) {
throw Exception("Plugin not found")
}
val pluginPath = pluginDescriptor.pluginPath
val osName = System.getProperty("os.name").toLowerCase()
val os = when {
osName.contains("mac") || osName.contains("darwin") -> "darwin"
osName.contains("win") -> "win32"
osName.contains("nix") || osName.contains("nux") || osName.contains("aix") -> "linux"
else -> "linux"
}
val osArch = System.getProperty("os.arch").toLowerCase()
val arch = when {
osArch.contains("aarch64") || (osArch.contains("arm") && osArch.contains("64")) -> "arm64"
osArch.contains("amd64") || osArch.contains("x86_64") -> "x64"
else -> "x64"
}
val target = "$os-$arch"
val continueCorePath = Paths.get(pluginPath.toString(), "core", target, "pkg").toString()
val coreMessenger = CoreMessenger(continueCorePath, ideProtocolClient);
continuePluginService.coreMessenger = coreMessenger
}
}
}

View file

@ -0,0 +1,48 @@
package com.github.continuedev.continueintellijextension.`continue`
import com.github.continuedev.continueintellijextension.activities.ContinuePluginStartupActivity
import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.StreamUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.jetbrains.jsonSchema.extension.JsonSchemaFileProvider
import com.jetbrains.jsonSchema.extension.JsonSchemaProviderFactory
import com.jetbrains.jsonSchema.extension.SchemaType
import java.io.File
import java.io.IOException
import java.nio.charset.StandardCharsets
import java.nio.file.Paths
class ConfigJsonSchemaProviderFactory : JsonSchemaProviderFactory {
override fun getProviders(project: Project): MutableList<JsonSchemaFileProvider> {
return mutableListOf(ConfigJsonSchemaFileProvider())
}
}
class ConfigJsonSchemaFileProvider : JsonSchemaFileProvider {
override fun isAvailable(file: VirtualFile): Boolean {
return file.name == "config.json"
}
override fun getName(): String {
return "config.json"
}
override fun getSchemaFile(): VirtualFile? {
ContinuePluginStartupActivity::class.java.getClassLoader().getResourceAsStream("config_schema.json").use { `is` ->
if (`is` == null) {
throw IOException("Resource not found: config_schema.json")
}
val content = StreamUtil.readText(`is`, StandardCharsets.UTF_8)
val filepath = Paths.get(getContinueGlobalPath(), "config_schema.json").toString()
File(filepath).writeText(content)
return LocalFileSystem.getInstance().findFileByPath(filepath)
}
}
override fun getSchemaType(): SchemaType {
return SchemaType.embeddedSchema
}
}

View file

@ -0,0 +1,179 @@
package com.github.continuedev.continueintellijextension.`continue`
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.io.*
import com.google.gson.Gson
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.attribute.PosixFilePermission
class CoreMessenger(continueCorePath: String, ideProtocolClient: IdeProtocolClient) {
private val writer: OutputStreamWriter
private val reader: BufferedReader
private val process: Process
private val gson = Gson()
private val responseListeners = mutableMapOf<String, (String) -> Unit>()
private val ideProtocolClient = ideProtocolClient
private fun write(message: String) {
writer.write(message + "\r\n")
writer.flush()
}
private fun close() {
writer.close()
reader.close()
val exitCode = process.waitFor()
println("Subprocess exited with code: $exitCode")
}
fun request(messageType: String, data: Any?, messageId: String?, onResponse: (String) -> Unit) {
val id = messageId ?: uuid()
val message = gson.toJson(mapOf(
"messageId" to id,
"messageType" to messageType,
"data" to data
))
responseListeners[id] = onResponse
write(message)
}
private fun handleMessage(json: String) {
val responseMap = gson.fromJson(json, Map::class.java)
val messageId = responseMap["messageId"].toString()
val messageType = responseMap["messageType"].toString()
val data = gson.toJson(responseMap["data"])
// IDE listeners
if (ideMessageTypes.contains(messageType)) {
ideProtocolClient.handleMessage(json) { data ->
val message = gson.toJson(mapOf(
"messageId" to messageId,
"messageType" to messageType,
"data" to data
))
write(message)
};
}
// Responses for messageId
responseListeners[messageId]?.let { listener ->
listener(data)
if (generatorTypes.contains(messageType)) {
val parsedData = gson.fromJson(data, Map::class.java)
val done = parsedData["done"] as Boolean?
if (done == true) {
responseListeners.remove(messageId)
} else {}
} else {
responseListeners.remove(messageId)
}
}
}
private val generatorTypes = listOf(
"llm/streamComplete",
"llm/streamChat",
"command/run"
)
private val ideMessageTypes = listOf(
"readRangeInFile",
"isTelemetryEnabled",
"getUniqueId",
"getWorkspaceConfigs",
"getDiff",
"getTerminalContents",
"listWorkspaceContents",
"getWorkspaceDirs",
"showLines",
"listFolders",
"getContinueDir",
"writeFile",
"showVirtualFile",
"openFile",
"runCommand",
"saveFile",
"readFile",
"showDiff",
"getOpenFiles",
"getPinnedFiles",
"getSearchResults",
"getProblems",
"subprocess",
"getBranch",
"getIdeInfo"
)
private fun setPermissions(destination: String) {
val osName = System.getProperty("os.name").toLowerCase()
if (osName.contains("mac") || osName.contains("darwin")) {
ProcessBuilder(
"xattr",
"-dr",
"com.apple.quarantine",
destination
).start()
setFilePermissions(destination, "rwxr-xr-x")
} else if (osName.contains("nix") || osName.contains("nux") || osName.contains("mac")) {
setFilePermissions(destination, "rwxr-xr-x")
}
}
private fun setFilePermissions(path: String, posixPermissions: String) {
val perms = HashSet<PosixFilePermission>()
if (posixPermissions.contains("r")) perms.add(PosixFilePermission.OWNER_READ)
if (posixPermissions.contains("w")) perms.add(PosixFilePermission.OWNER_WRITE)
if (posixPermissions.contains("x")) perms.add(PosixFilePermission.OWNER_EXECUTE)
Files.setPosixFilePermissions(Paths.get(path), perms)
}
init {
// Set proper permissions
setPermissions(continueCorePath)
// Start the subprocess
val processBuilder = ProcessBuilder(continueCorePath)
process = processBuilder.start()
val outputStream = process.outputStream
val inputStream = process.inputStream
writer = OutputStreamWriter(outputStream)
reader = BufferedReader(InputStreamReader(inputStream))
process.onExit().thenRun {
val err = process.errorStream.bufferedReader().readText()
ideProtocolClient.showMessage("Core process exited with output: $err")
}
Thread {
try {
while (true) {
val line = reader.readLine()
if (line != null && line.isNotEmpty()) {
handleMessage(line)
} else {
Thread.sleep(100)
}
}
} catch (e: IOException) {
e.printStackTrace()
} finally {
try {
reader.close()
writer.close()
outputStream.close()
inputStream.close()
process.destroy()
} catch (e: IOException) {
e.printStackTrace()
}
}
}.start()
}
}

View file

@ -0,0 +1,58 @@
package com.github.continuedev.continueintellijextension.`continue`
import com.intellij.codeInsight.template.impl.TemplateColors
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors
import com.intellij.openapi.editor.colors.EditorColors
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.EditorColorsScheme
import com.intellij.openapi.editor.colors.TextAttributesKey
import kotlin.math.max
import kotlin.math.min
class GetTheme {
fun getTheme(): Map<String, String> {
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
val defaultForeground = globalScheme.defaultForeground
val highlight = globalScheme.getColor(EditorColors.MODIFIED_TAB_ICON_COLOR) ?: defaultForeground
val defaultBackgroundHex = String.format("#%02x%02x%02x", defaultBackground.red, defaultBackground.green, defaultBackground.blue)
val defaultForegroundHex = String.format("#%02x%02x%02x", defaultForeground.red, defaultForeground.green, defaultForeground.blue)
val highlightHex = String.format("#%02x%02x%02x", highlight.red, highlight.green, highlight.blue)
val grayscale = (defaultBackground.red * 0.3 + defaultBackground.green * 0.59 + defaultBackground.blue * 0.11).toInt()
val adjustedRed: Int
val adjustedGreen: Int
val adjustedBlue: Int
val tint: Int = 20
if (grayscale > 128) { // if closer to white
adjustedRed = max(0, defaultBackground.red - tint)
adjustedGreen = max(0, defaultBackground.green - tint)
adjustedBlue = max(0, defaultBackground.blue - tint)
} else { // if closer to black
adjustedRed = min(255, defaultBackground.red + tint)
adjustedGreen = min(255, defaultBackground.green + tint)
adjustedBlue = min(255, defaultBackground.blue + tint)
}
val secondaryDarkHex = String.format("#%02x%02x%02x", adjustedRed, adjustedGreen, adjustedBlue)
return mapOf(
"--vscode-editor-foreground" to defaultForegroundHex,
"--vscode-sideBar-background" to defaultBackgroundHex,
"--vscode-input-background" to secondaryDarkHex,
"--vscode-editor-background" to defaultBackgroundHex,
"--vscode-button-background" to defaultBackgroundHex,
"--vscode-list-activeSelectionBackground" to defaultBackgroundHex,
"--vscode-focusBorder" to highlightHex,
"--vscode-quickInputList-focusForeground" to defaultForegroundHex,
"--vscode-quickInput-background" to secondaryDarkHex,
"--vscode-input-border" to "#80808080",
"--vscode-badge-background" to highlightHex,
"--vscode-badge-foreground" to defaultForegroundHex,
"--vscode-sideBar-border" to "#80808080"
)
}
}

View file

@ -1,28 +1,19 @@
package com.github.continuedev.continueintellijextension.`continue`
import com.github.continuedev.continueintellijextension.*
import com.github.continuedev.continueintellijextension.constants.*
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.JsonObject
import com.google.gson.reflect.TypeToken
import com.intellij.execution.ExecutionManager
import com.intellij.execution.process.ProcessAdapter
import com.intellij.execution.process.ProcessEvent
import com.intellij.execution.ui.RunContentDescriptor
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.editor.SelectionModel
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManagerListener
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.ui.popup.JBPopupFactory
@ -32,15 +23,10 @@ import com.intellij.openapi.wm.WindowManager
import com.intellij.testFramework.LightVirtualFile
import com.intellij.ui.awt.RelativePoint
import kotlinx.coroutines.*
import net.minidev.json.JSONObject
import org.jetbrains.annotations.NotNull
import java.io.*
import java.net.NetworkInterface
import java.nio.charset.Charset
import java.nio.file.Files
import java.nio.file.Paths
import java.util.*
import kotlin.coroutines.ContinuationInterceptor
fun uuid(): String {
@ -103,7 +89,7 @@ class AsyncFileSaveListener : AsyncFileListener {
}
override fun prepareChange(events: MutableList<out VFileEvent>): AsyncFileListener.ChangeApplier? {
for (event in events) {
if (event.path.endsWith(".continue/config.json") || event.path.endsWith(".continue/config.ts") || event.path.endsWith(".continue\\config.json") || event.path.endsWith(".continue\\config.ts")) {
if (event.path.endsWith(".continue/config.json") || event.path.endsWith(".continue/config.ts") || event.path.endsWith(".continue\\config.json") || event.path.endsWith(".continue\\config.ts") || event.path.endsWith(".continuerc.json")) {
return object : AsyncFileListener.ChangeApplier {
override fun afterVfsChange() {
val config = readConfigJson()
@ -137,35 +123,21 @@ class IdeProtocolClient (
private fun send(messageType: String, data: Any?, messageId: String? = null) {
val id = messageId ?: uuid()
val message = IdeMessage(
messageType,
id,
data
)
val json = Gson().toJson(message)
continuePluginService.dispatchCustomEvent(json)
continuePluginService.sendToWebview(messageType, data, id)
}
fun handleWebsocketMessage(text: String) {
fun handleMessage(text: String, respond: (Any?) -> Unit) {
coroutineScope.launch(Dispatchers.IO) {
val parsedMessage: Map<String, Any> = Gson().fromJson(
text,
object : TypeToken<Map<String, Any>>() {}.type
)
val messageType = parsedMessage["type"] as? String
val messageType = parsedMessage["messageType"] as? String
if (messageType == null) {
println("Recieved message without type: $text")
return@launch
}
val data = parsedMessage["data"] as Map<*, *>
fun respond(responseData: Any?) {
if (data["messageId"] == null) {
println("Recieved message without messageId: $text")
return
}
send(messageType, responseData ?: emptyMap<String, String>(), data["messageId"] as String);
}
val data = parsedMessage["data"]
val historyManager = HistoryManager()
@ -175,7 +147,7 @@ class IdeProtocolClient (
mapOf("uniqueId" to uniqueId())
)
"ide" -> {
"getIdeInfo" -> {
val applicationInfo = ApplicationInfo.getInstance()
val ideName: String = applicationInfo.fullApplicationName
val ideVersion = applicationInfo.fullVersion
@ -187,14 +159,19 @@ class IdeProtocolClient (
remoteName = "ssh"
}
respond(mapOf(
"ideType" to "jetbrains",
"name" to ideName,
"version" to ideVersion,
"remoteName" to remoteName
))
}
"getUniqueId" -> {
respond(uniqueId())
}
"showDiff" -> {
val data = data["message"] as Map<String, Any>
val data = data as Map<String, Any>
diffManager.showDiff(
data["filepath"] as String,
data["newContents"] as String,
@ -204,10 +181,31 @@ class IdeProtocolClient (
}
"readFile" -> {
val msg = readFile((data["message"] as Map<String, String>)["filepath"] as String)
val msg = readFile((data as Map<String, String>)["filepath"] as String)
respond(msg)
}
"isTelemetryEnabled" -> {
respond(true)
}
"readRangeInFile" -> {
val fullContents = readFile((data as Map<String, String>)["filepath"] as String)
val range = data["range"] as Map<String, Any>
val start = range["start"] as Map<String, Any>
val end = range["end"] as Map<String, Any>
val startLine = start["line"] as Int
val startCharacter = start["character"] as Int
val endLine = end["line"] as Int
val endCharacter = end["character"] as Int
val firstLine = fullContents.split("\n")[startLine].slice(startCharacter until fullContents.split("\n")[startLine].length)
val lastLine = fullContents.split("\n")[endLine].slice(0 until endCharacter)
val between = fullContents.split("\n").slice(startLine + 1 until endLine).joinToString("\n")
respond(firstLine + "\n" + between + "\n" + lastLine)
}
"listWorkspaceContents" -> {
respond(listDirectoryContents(null))
}
@ -216,6 +214,10 @@ class IdeProtocolClient (
respond(workspaceDirectories())
}
"getWorkspaceConfigs" -> {
respond(emptyList<String>())
}
"getTerminalContents" -> {
respond(
mapOf("contents" to "Terminal cannot be accessed in JetBrains IDE")
@ -229,10 +231,11 @@ class IdeProtocolClient (
}
"saveFile" -> {
saveFile((data["message"] as Map<String, String>)["filepath"] ?: throw Exception("No filepath provided"))
saveFile((data as Map<String, String>)["filepath"] ?: throw Exception("No filepath provided"))
respond(null)
}
"showVirtualFile" -> {
val data = data as Map<String, Any>
showVirtualFile(
data["name"] as String,
data["contents"] as String
@ -242,10 +245,11 @@ class IdeProtocolClient (
"connected" -> {}
"showMessage" -> {
showMessage(data["message"] as String)
showMessage(data as String)
respond(null)
}
"setFileOpen" -> {
val data = data as Map<String, Any>
setFileOpen(
data["filepath"] as String,
data["open"] as Boolean
@ -253,8 +257,27 @@ class IdeProtocolClient (
respond(null)
}
"showLines" -> {
val data = data as Map<String, Any>
val filepath = data["filepath"] as String
val startLine = data["startLine"] as Int
val endLine = data["endLine"] as Int
highlightCode(
RangeInFile(
filepath,
Range(
Position(startLine, 0),
Position(endLine, 0)
)
),
data["color"] as String
)
respond(null)
}
"highlightCode" -> {
val gson = Gson()
val data = data as Map<String, Any>
val json = gson.toJson(data["rangeInFile"])
val type = object : TypeToken<RangeInFile>() {}.type
val rangeInFile =
@ -265,16 +288,6 @@ class IdeProtocolClient (
"setSuggestionsLocked" -> {}
"getSessionId" -> {}
"highlightedCode" -> {
val rifWithContents = getHighlightedCode()
val rifs: MutableList<RangeInFile> = mutableListOf()
if (rifWithContents != null) {
val rif = RangeInFile(rifWithContents.filepath, rifWithContents.range)
rifs += rif
}
respond(mapOf("highlightedCode" to rifs))
}
// NEW //
"getDiff" -> {
@ -295,29 +308,6 @@ class IdeProtocolClient (
respond(output.toString());
}
"getSerializedConfig" -> {
val configPath = getConfigJsonPath()
var config = File(configPath).readText()
migrate("camelCaseConfig") {
if (config.contains("_")) {
config = config
.replace(Regex("(_\\w)")) { it.value[1].uppercase() }
.replace("openai-aiohttp", "openai")
// Rewrite to config.json
File(configPath).writeText(config)
}
}
migrate("renameFreeTrialProvider") {
config = config.replace("openai-free-trial", "free-trial");
File(configPath).writeText(config)
}
val mapType = object : TypeToken<Map<String, Any>>() {}.type
val parsed: Map<String, Any> = Gson().fromJson(config, mapType)
respond(parsed)
}
"getConfigJsUrl" -> {
// Calculate a data URL for the config.js file
val configJsPath = getConfigJsPath()
@ -326,7 +316,7 @@ class IdeProtocolClient (
respond(configJsDataUrl)
}
"writeFile" -> {
val msg = data["message"] as Map<String, String>;
val msg = data as Map<String, String>;
val file = File(msg["path"])
file.writeText(msg["contents"] as String)
respond(null);
@ -335,7 +325,7 @@ class IdeProtocolClient (
respond(getContinueGlobalPath())
}
"openFile" -> {
setFileOpen((data["message"] as Map<String, Any>)["path"] as String)
setFileOpen((data as Map<String, Any>)["path"] as String)
respond(null)
}
"runCommand" -> {
@ -343,7 +333,14 @@ class IdeProtocolClient (
// Running commands not yet supported in JetBrains
}
"errorPopup" -> {
showMessage(data["message"] as String)
val data = data as Map<String, Any>
val message = data["message"] as String
showMessage(message)
respond(null)
}
"listFolders" -> {
respond(null)
}
// History
@ -351,15 +348,15 @@ class IdeProtocolClient (
respond(historyManager.list());
}
"saveSession" -> {
historyManager.save(data["message"] as PersistedSessionInfo);
historyManager.save(data as PersistedSessionInfo);
respond(null);
}
"deleteSession" -> {
historyManager.delete(data["message"] as String);
historyManager.delete(data as String);
respond(null);
}
"loadSession" -> {
val session = historyManager.load(data["message"] as String)
val session = historyManager.load(data as String)
respond(session)
}
"getSearchResults" -> {
@ -371,7 +368,12 @@ class IdeProtocolClient (
val openFiles = visibleFiles()
respond(openFiles)
}
"getPinnedFiles" -> {
val openFiles = visibleFiles()
respond(openFiles)
}
"logDevData" -> {
val data = data as Map<String, Any>
val filename = data["tableName"] as String
val jsonLine = data["data"]
val filepath = getDevDataFilepath(filename)
@ -379,6 +381,7 @@ class IdeProtocolClient (
File(filepath).appendText(contents)
}
"addModel" -> {
val data = data as Map<String, Any>
val model = data["model"] as Map<String, Any>
val updatedConfig = editConfigJson {
val models = it["models"] as MutableList<Map<String, Any>>
@ -392,7 +395,7 @@ class IdeProtocolClient (
"deleteModel" -> {
val configJson = editConfigJson { config ->
var models: MutableList<Map<String, Any>> = config["models"] as MutableList<Map<String, Any>>
val data = data as Map<String, Any>
val model = data["title"] as String
models = models.filter { it["title"] != model }.toMutableList()
config["models"] = models
@ -402,6 +405,7 @@ class IdeProtocolClient (
}
"addOpenAIKey" -> {
val updatedConfig = editConfigJson { config ->
val data = data as Map<String, Any>
val key = data["key"] as String
var models = config["models"] as MutableList<MutableMap<String, Any>>
models = models.map {
@ -432,12 +436,8 @@ class IdeProtocolClient (
}
fun configUpdate(config: Map<String, Any>) {
val data = mapOf(
"type" to "configUpdate",
"config" to config
)
val json = Gson().toJson(data)
continuePluginService.dispatchCustomEvent(json)
continuePluginService.coreMessenger?.request("config/reload", null, null) { _ -> }
continuePluginService.sendToWebview("configUpdate", config)
}
private fun editConfigJson(callback: (config: MutableMap<String, Any>) -> Map<String, Any>): Map<String, Any> {
@ -581,20 +581,17 @@ class IdeProtocolClient (
// edit
// ))
continuePluginService.dispatchCustomEvent(
Gson().toJson(mapOf(
"type" to "highlightedCode",
continuePluginService.sendToWebview(
"highlightedCode",
mapOf(
"rangeInFileWithContents" to rif,
"edit" to edit
)))
)
)
}
fun sendMainUserInput(input: String) {
val data = mapOf(
"type" to "userInput",
"input" to input,
)
continuePluginService.dispatchCustomEvent(Gson().toJson(data))
continuePluginService.sendToWebview("userInput", mapOf("input" to input))
}
fun sendAcceptRejectDiff(accepted: Boolean, stepIndex: Int) {
@ -712,7 +709,7 @@ class IdeProtocolClient (
return fileEditorManager.openFiles.toList().map { it.path }
}
private fun showMessage(msg: String) {
fun showMessage(msg: String) {
val statusBar = WindowManager.getInstance().getStatusBar(project)
JBPopupFactory.getInstance()

View file

@ -35,7 +35,7 @@ class CustomResourceHandler : CefResourceHandler, DumbAware {
): Boolean {
val url = cefRequest.url
return if (url != null) {
val pathToResource = url.replace("http://continue", "webview/")
val pathToResource = url.replace("http://continue", "webview/").replace("http://localhost:5173", "webview/")
val newUrl = javaClass.classLoader.getResource(pathToResource)
state = OpenedConnection(newUrl?.openConnection())
currentUrl = url

View file

@ -1,6 +1,8 @@
package com.github.continuedev.continueintellijextension.services
import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger
import com.github.continuedev.continueintellijextension.`continue`.IdeProtocolClient
import com.github.continuedev.continueintellijextension.`continue`.uuid
import com.github.continuedev.continueintellijextension.toolWindow.ContinuePluginToolWindowFactory
import com.google.gson.Gson
import com.intellij.openapi.Disposable
@ -20,7 +22,8 @@ class ContinuePluginService(project: Project) : Disposable, DumbAware {
var continuePluginWindow: ContinuePluginToolWindowFactory.ContinuePluginWindow? = null
var ideProtocolClient: IdeProtocolClient? = null
var workspacePaths: Array<String>? = null
var coreMessenger: CoreMessenger? = null
var worksapcePaths: Array<String>? = null
var windowId: String = UUID.randomUUID().toString()
override fun dispose() {
@ -33,10 +36,19 @@ class ContinuePluginService(project: Project) : Disposable, DumbAware {
}
}
fun dispatchCustomEvent(
data: String
fun sendToWebview(
messageType: String,
data: Any?,
messageId: String = uuid()
) {
val jsCode = buildJavaScript(data)
val jsonData = Gson().toJson(
mapOf(
"messageId" to messageId,
"messageType" to messageType,
"data" to data
)
)
val jsCode = buildJavaScript(jsonData)
try {
continuePluginWindow?.webView?.executeJavaScriptAsync(jsCode)

View file

@ -1,10 +1,8 @@
package com.github.continuedev.continueintellijextension.toolWindow
import com.github.continuedev.continueintellijextension.activities.showTutorial
import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath
import com.github.continuedev.continueintellijextension.`continue`.Position
import com.github.continuedev.continueintellijextension.`continue`.Range
import com.github.continuedev.continueintellijextension.`continue`.RangeInFile
import com.github.continuedev.continueintellijextension.`continue`.getMachineUniqueID
import com.github.continuedev.continueintellijextension.`continue`.*
import com.github.continuedev.continueintellijextension.factories.CustomSchemeHandlerFactory
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.google.gson.Gson
@ -55,12 +53,34 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
class ContinuePluginWindow(toolWindow: ToolWindow, project: Project) {
val PASS_THROUGH_TO_CORE = listOf(
"abort",
"getContinueDir",
"history/list",
"history/save",
"history/delete",
"history/load",
"devdata/log",
"config/addModel",
"config/deleteModel",
"config/addOpenAIKey",
"llm/streamComplete",
"llm/streamChat",
"llm/complete",
"command/run",
"context/loadSubmenuItems",
"context/getContextItems",
"context/addDocs",
"config/getBrowserSerialized",
)
init {
System.setProperty("ide.browser.jcef.jsQueryPoolSize", JS_QUERY_POOL_SIZE)
System.setProperty("ide.browser.jcef.osr.enabled", "false")
}
val webView: JBCefBrowser by lazy {
val browser = JBCefBrowser()
val browser = JBCefBrowser.createBuilder().setOffScreenRendering(false).build()
browser.jbCefClient.setProperty(
JBCefClient.Properties.JS_QUERY_POOL_SIZE,
JS_QUERY_POOL_SIZE
@ -68,6 +88,8 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
registerAppSchemeHandler()
browser.loadURL("http://continue/index.html")
// browser.loadHTML("<html><body><input type='text'/></body></html>")
// browser.loadURL("http://localhost:5173/index.html")
Disposer.register(project, browser)
val continuePluginService = ServiceManager.getService(
@ -81,58 +103,46 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
myJSQueryOpenInBrowser.addHandler { msg: String? ->
val parser = JsonParser()
val json: JsonObject = parser.parse(msg).asJsonObject
val type = json.get("type").asString
val data = json.get("data").asJsonObject
val messageType = json.get("messageType").asString
val data = json.get("data")
val messageId = json.get("messageId")?.asString
val ide = continuePluginService.ideProtocolClient;
when (type) {
val respond = fun(data: Any?) {
val jsonData = mutableMapOf(
"messageId" to messageId,
"data" to data,
"messageType" to messageType
)
val jsonString = Gson().toJson(jsonData)
continuePluginService.sendToWebview(messageType, data, messageId ?: uuid())
}
if (PASS_THROUGH_TO_CORE.contains(messageType)) {
continuePluginService.coreMessenger?.request(messageType, data, messageId, respond)
return@addHandler null
}
when (messageType) {
"onLoad" -> {
GlobalScope.launch {
// Set the colors to match Intellij theme
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
val defaultForeground = globalScheme.defaultForeground
val defaultBackgroundHex = String.format("#%02x%02x%02x", defaultBackground.red, defaultBackground.green, defaultBackground.blue)
val defaultForegroundHex = String.format("#%02x%02x%02x", defaultForeground.red, defaultForeground.green, defaultForeground.blue)
val grayscale = (defaultBackground.red * 0.3 + defaultBackground.green * 0.59 + defaultBackground.blue * 0.11).toInt()
val adjustedRed: Int
val adjustedGreen: Int
val adjustedBlue: Int
val tint: Int = 20
if (grayscale > 128) { // if closer to white
adjustedRed = max(0, defaultBackground.red - tint)
adjustedGreen = max(0, defaultBackground.green - tint)
adjustedBlue = max(0, defaultBackground.blue - tint)
} else { // if closer to black
adjustedRed = min(255, defaultBackground.red + tint)
adjustedGreen = min(255, defaultBackground.green + tint)
adjustedBlue = min(255, defaultBackground.blue + tint)
}
val secondaryDarkHex = String.format("#%02x%02x%02x", adjustedRed, adjustedGreen, adjustedBlue)
browser.executeJavaScriptAsync("document.body.style.setProperty(\"--vscode-editor-foreground\", \"$defaultForegroundHex\");")
browser.executeJavaScriptAsync("document.body.style.setProperty(\"--vscode-sideBar-background\", \"$defaultBackgroundHex\");")
browser.executeJavaScriptAsync("document.body.style.setProperty(\"--vscode-input-background\", \"$secondaryDarkHex\");")
browser.executeJavaScriptAsync("document.body.style.setProperty(\"--vscode-editor-background\", \"$defaultBackgroundHex\");")
val colors = GetTheme().getTheme();
continuePluginService.sendToWebview("setColors", colors)
val jsonData = mutableMapOf(
"type" to "onLoad",
"windowId" to continuePluginService.windowId,
"workspacePaths" to continuePluginService.workspacePaths,
"vscMachineId" to getMachineUniqueID(),
"vscMediaUrl" to "http://continue",
)
val jsonString = Gson().toJson(jsonData)
browser.executeJavaScriptAsync("""window.postMessage($jsonString, "*");""")
respond(jsonData)
}
}
"showLines" -> {
val data = data.asJsonObject
ide?.highlightCode(RangeInFile(
data.get("filepath").asString,
Range(Position(
@ -145,10 +155,15 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
),"#00ff0022")
}
"showTutorial" -> {
showTutorial(project)
}
"showVirtualFile" -> {
val data = data.asJsonObject
ide?.showVirtualFile(data.get("name").asString, data.get("content").asString)
}
"showFile" -> {
val data = data.asJsonObject
ide?.setFileOpen(data.get("filepath").asString)
}
"reloadWindow" -> {}
@ -156,6 +171,7 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
ide?.setFileOpen(getConfigJsonPath())
}
"readRangeInFile" -> {
val data = data.asJsonObject
ide?.readRangeInFile(RangeInFile(
data.get("filepath").asString,
Range(Position(
@ -172,7 +188,7 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
// IDE //
else -> {
if (msg != null) {
ide?.handleWebsocketMessage(msg)
ide?.handleMessage(msg, respond)
}
}
}
@ -201,8 +217,8 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
fun executeJavaScript(browser: CefBrowser?, myJSQueryOpenInBrowser: JBCefJSQuery) {
// Execute JavaScript - you might want to handle potential exceptions here
val script = """window.postIntellijMessage = function(type, data) {
const msg = JSON.stringify({type, data});
val script = """window.postIntellijMessage = function(messageType, data, messageId) {
const msg = JSON.stringify({messageType, data, messageId});
${myJSQueryOpenInBrowser.inject("msg")}
}""".trimIndent()

View file

@ -6,6 +6,10 @@
<depends>com.intellij.modules.platform</depends>
<idea-version since-build="223.0"/>
<extensions defaultExtensionNs="JavaScript.JsonSchema">
<ProviderFactory implementation="com.github.continuedev.continueintellijextension.continue.ConfigJsonSchemaProviderFactory"/>
</extensions>
<extensions defaultExtensionNs="com.intellij">
<toolWindow id="Continue" anchor="right" icon="/tool-window-icon.png"
factoryClass="com.github.continuedev.continueintellijextension.toolWindow.ContinuePluginToolWindowFactory"/>

File diff suppressed because it is too large Load diff

View file

@ -19,7 +19,7 @@ You can either
- follow along by clicking the gray CodeLens buttons above the lines, in order, starting with "Begin Section"
"""
# region —————————————————————————— Part 1: Ask a question about code [⌘ M] ——————————————————————————
# region —————————————————————————— Part 1: Ask a question about code [⌘ L] ——————————————————————————
"""Step 1: Highlight the function below"""
@ -34,14 +34,14 @@ def mysterious_function(x):
return x
"""Step 2: Use the keyboard shortcut [⌘ M] to
"""Step 2: Use the keyboard shortcut [⌘ L] to
select the code and toggle the Continue input box"""
"""Step 3: Ask a question and press Enter"""
# endregion
# region ————————————————————————————————— Part 2: Edit code [⌘ ⇧ L] —————————————————————————————————
# region ————————————————————————————————— Part 2: Edit code [⌘ I] —————————————————————————————————
"""Step 1: Highlight this code"""
@ -60,7 +60,7 @@ def mysterious_function(x):
return x
"""Step 2: Use the keyboard shortcut [⌘ ⇧ L] to edit"""
"""Step 2: Use the keyboard shortcut [⌘ I] to edit"""
"""Step 3: Type "<your edit request>" and press Enter"""

View file

@ -8,11 +8,11 @@ Continue is currently in the left sidebar, but we recommend moving it to the rig
## 🔑 Most important shortcuts
<kbd>Cmd/Ctrl</kbd> + <kbd>M</kbd> = Select code
<kbd>Cmd/Ctrl</kbd> + <kbd>L</kbd> = Select code
<kbd>Cmd/Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>M</kbd> = Select code for follow-up
<kbd>Cmd/Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>L</kbd> = Select code for follow-up
<kbd>Cmd/Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>L</kbd> = Quick edit
<kbd>Cmd/Ctrl</kbd> + <kbd>I</kbd> = Quick edit
<kbd>Cmd/Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>R</kbd> = Automatically debug terminal

View file

@ -91,9 +91,13 @@
"adf-to-md": "^1.1.0",
"axios": "^1.6.7",
"cheerio": "^1.0.0-rc.12",
"commander": "^12.0.0",
"dotenv": "^16.3.1",
"fastest-levenshtein": "^1.0.16",
"follow-redirects": "^1.15.5",
"handlebars": "^4.7.8",
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"js-tiktoken": "^1.0.8",
"llm-code-highlighter": "^0.0.13",
"node-fetch": "^3.3.2",
@ -111,6 +115,7 @@
"web-tree-sitter": "^0.20.8"
},
"devDependencies": {
"@types/follow-redirects": "^1.14.4",
"@types/handlebars": "^4.1.0",
"@types/jest": "^29.5.11",
"@types/jquery": "^3.5.29",

View file

@ -195,13 +195,13 @@
"keybindings": [
{
"command": "continue.focusContinueInput",
"mac": "cmd+m",
"key": "ctrl+m"
"mac": "cmd+l",
"key": "ctrl+l"
},
{
"command": "continue.focusContinueInputWithoutClear",
"mac": "cmd+shift+m",
"key": "ctrl+shift+m"
"mac": "cmd+shift+l",
"key": "ctrl+shift+l"
},
{
"command": "continue.acceptDiff",
@ -221,8 +221,8 @@
},
{
"command": "continue.quickEdit",
"mac": "cmd+shift+l",
"key": "ctrl+shift+l"
"mac": "cmd+i",
"key": "ctrl+i"
},
{
"command": "continue.toggleAuxiliaryBar",

View file

@ -13,11 +13,22 @@ if (args[2] === "--target") {
(async () => {
console.log("[info] Packaging extension for target ", target);
// Copy config_schema.json to config.json in docs
// Copy config_schema.json to config.json in docs and intellij
fs.copyFileSync(
"config_schema.json",
path.join("..", "..", "docs", "static", "schemas", "config.json")
);
fs.copyFileSync(
"config_schema.json",
path.join(
"..",
"intellij",
"src",
"main",
"resources",
"config_schema.json"
)
);
// Modify and copy for .continuerc.json
const schema = JSON.parse(fs.readFileSync("config_schema.json", "utf8"));
schema.definitions.SerializedContinueConfig.properties.mergeBehavior = {
@ -77,11 +88,19 @@ if (args[2] === "--target") {
});
});
// Put back index.html
if (fs.existsSync(indexHtmlPath)) {
fs.rmSync(indexHtmlPath, {});
}
fs.copyFileSync("tmp_index.html", indexHtmlPath);
fs.unlinkSync("tmp_index.html");
// Copy over other misc. files
fs.copyFileSync(
"../extensions/vscode/gui/onigasm.wasm",
path.join(intellijExtensionWebviewPath, "onigasm.wasm")
);
console.log("[info] Copied gui build to Intellij extension");
// Then copy over the dist folder to the VSCode extension //

View file

@ -2,27 +2,14 @@ import { getTsConfigPath, migrate } from "core/util/paths";
import { Telemetry } from "core/util/posthog";
import * as fs from "fs";
import path from "path";
import { v4 } from "uuid";
import * as vscode from "vscode";
import { registerAllCommands } from "../commands";
import IdeProtocolClient from "../continueIdeClient";
import { ContinueGUIWebviewViewProvider } from "../debugPanel";
import { VsCodeExtension } from "../extension/vscodeExtension";
import registerQuickFixProvider from "../lang-server/codeActions";
import { registerAllCodeLensProviders } from "../lang-server/codeLens";
import {
ContinueCompletionProvider,
setupStatusBar,
} from "../lang-server/completionProvider";
import { vsCodeIndexCodebase } from "../util/indexCodebase";
import { RemoteConfigSync } from "../util/remoteConfig";
import { getExtensionVersion } from "../util/util";
import { getExtensionUri } from "../util/vscode";
import { setupInlineTips } from "./inlineTips";
export let extensionContext: vscode.ExtensionContext | undefined = undefined;
export let ideProtocolClient: IdeProtocolClient;
export let windowId: string = v4();
export async function showTutorial() {
const tutorialPath = path.join(
getExtensionUri().fsPath,
@ -48,7 +35,9 @@ async function openTutorialFirstTime(context: vscode.ExtensionContext) {
}
}
function showRefactorMigrationMessage() {
function showRefactorMigrationMessage(
extensionContext: vscode.ExtensionContext
) {
// Only if the vscode setting continue.manuallyRunningSserver is true
const manuallyRunningServer =
vscode.workspace
@ -82,45 +71,13 @@ export async function activateExtension(context: vscode.ExtensionContext) {
// Add necessary files
getTsConfigPath();
extensionContext = context;
// Register commands and providers
registerAllCodeLensProviders(context);
registerAllCommands(context);
registerQuickFixProvider();
await openTutorialFirstTime(context);
setupInlineTips(context);
showRefactorMigrationMessage();
const config = vscode.workspace.getConfiguration("continue");
const enabled = config.get<boolean>("enableTabAutocomplete");
showRefactorMigrationMessage(context);
// Register inline completion provider (odd versions are pre-release)
if (parseInt(context.extension.packageJSON.version.split(".")[1]) % 2 !== 0) {
setupStatusBar(enabled);
context.subscriptions.push(
vscode.languages.registerInlineCompletionItemProvider(
[{ pattern: "**" }],
new ContinueCompletionProvider()
)
);
}
ideProtocolClient = new IdeProtocolClient(context);
// Register Continue GUI as sidebar webview, and beginning a new session
const provider = new ContinueGUIWebviewViewProvider();
context.subscriptions.push(
vscode.window.registerWebviewViewProvider(
"continue.continueGUIView",
provider,
{
webviewOptions: { retainContextWhenHidden: true },
}
)
);
vsCodeIndexCodebase(ideProtocolClient.getWorkspaceDirectories());
const vscodeExtension = new VsCodeExtension(context);
migrate("showWelcome", () => {
vscode.commands.executeCommand(
@ -131,25 +88,6 @@ export async function activateExtension(context: vscode.ExtensionContext) {
);
});
// (async () => {
// const defaultDocsPages = [
// ["Socket.IO", "https://python-socketio.readthedocs.io/en/stable"],
// // ["Flask", "https://flask.palletsprojects.com/en/2.0.x/"],
// ];
// const config = await configHandler.loadConfig(new VsCodeIde());
// defaultDocsPages.forEach(async ([title, url]) => {
// for await (const update of indexDocs(
// title,
// new URL(url),
// config.embeddingsProvider
// )) {
// console.log(update.progress, update.desc);
// }
// });
// })();
// Load Continue configuration
if (!context.globalState.get("hasBeenInstalled")) {
context.globalState.update("hasBeenInstalled", true);

View file

@ -3,7 +3,7 @@ import { getMetaKeyLabel } from "../util/util";
const inlineTipDecoration = vscode.window.createTextEditorDecorationType({
after: {
contentText: `${getMetaKeyLabel()} M to select code, ${getMetaKeyLabel()} ⇧ L to edit`,
contentText: `${getMetaKeyLabel()} L to select code, ${getMetaKeyLabel()} I to edit`,
color: "#888",
margin: "0 0 0 6em",
fontWeight: "bold",
@ -31,7 +31,7 @@ function handleSelectionChange(e: vscode.TextEditorSelectionChangeEvent) {
const line = Math.max(0, selection.start.line - 1);
const hoverMarkdown = new vscode.MarkdownString(
`Use ${getMetaKeyLabel()} M to select code, or ${getMetaKeyLabel()} ⇧ L to edit highlighted code. Click [here](command:continue.hideInlineTip) if you don't want to see these inline suggestions.`
`Use ${getMetaKeyLabel()} L to select code, or ${getMetaKeyLabel()} I to edit highlighted code. Click [here](command:continue.hideInlineTip) if you don't want to see these inline suggestions.`
);
hoverMarkdown.isTrusted = true;
hoverMarkdown.supportHtml = true;
@ -49,7 +49,7 @@ function handleSelectionChange(e: vscode.TextEditorSelectionChangeEvent) {
const emptyFileTooltipDecoration = vscode.window.createTextEditorDecorationType(
{
after: {
contentText: `Use ${getMetaKeyLabel()} ⇧ L to generate code`,
contentText: `Use ${getMetaKeyLabel()} I to generate code`,
color: "#888",
margin: "2em 0 0 0",
fontStyle: "italic",

View file

@ -3,19 +3,19 @@ import * as os from "os";
import * as path from "path";
import * as vscode from "vscode";
import { extensionContext, ideProtocolClient } from "./activation/activate";
import { debugPanelWebview, getSidebarContent } from "./debugPanel";
import { acceptDiffCommand, rejectDiffCommand } from "./diff/horizontal";
import {
editorToVerticalDiffCodeLens,
streamEdit,
verticalPerLineDiffManager,
} from "./diff/verticalPerLine/manager";
import { VsCodeIde } from "./ideProtocol";
import { IDE } from "core";
import { ConfigHandler } from "core/config/handler";
import { logDevData } from "core/util/devdata";
import { ContinueGUIWebviewViewProvider } from "./debugPanel";
import { DiffManager } from "./diff/horizontal";
import { VerticalPerLineDiffManager } from "./diff/verticalPerLine/manager";
import { AutocompleteOutcome } from "./lang-server/completionProvider";
import { configHandler, llmFromTitle } from "./loadConfig";
import { VsCodeWebviewProtocol } from "./webviewProtocol";
function addHighlightedCodeToContext(edit: boolean) {
function addHighlightedCodeToContext(
edit: boolean,
webviewProtocol: VsCodeWebviewProtocol | undefined
) {
const editor = vscode.window.activeTextEditor;
if (editor) {
const selection = editor.selection;
@ -37,22 +37,28 @@ function addHighlightedCodeToContext(edit: boolean) {
},
};
debugPanelWebview?.postMessage({
type: "highlightedCode",
webviewProtocol?.request("highlightedCode", {
rangeInFileWithContents,
edit,
});
}
}
async function addEntireFileToContext(filepath: vscode.Uri, edit: boolean) {
async function addEntireFileToContext(
filepath: vscode.Uri,
edit: boolean,
webviewProtocol: VsCodeWebviewProtocol | undefined
) {
// If a directory, add all files in the directory
const stat = await vscode.workspace.fs.stat(filepath);
if (stat.type === vscode.FileType.Directory) {
const files = await vscode.workspace.fs.readDirectory(filepath);
for (const [filename, type] of files) {
if (type === vscode.FileType.File) {
addEntireFileToContext(vscode.Uri.joinPath(filepath, filename), edit);
addEntireFileToContext(
vscode.Uri.joinPath(filepath, filename),
edit,
webviewProtocol
);
}
}
return;
@ -75,79 +81,70 @@ async function addEntireFileToContext(filepath: vscode.Uri, edit: boolean) {
},
};
debugPanelWebview?.postMessage({
type: "highlightedCode",
webviewProtocol?.request("highlightedCode", {
rangeInFileWithContents,
edit,
});
}
function acceptRejectVerticalDiffBlock(
accept: boolean,
filepath?: string,
index?: number
) {
if (!filepath) {
const activeEditor = vscode.window.activeTextEditor;
if (!activeEditor) {
return;
}
filepath = activeEditor.document.uri.fsPath;
}
if (typeof index === "undefined") {
index = 0;
}
let blocks = editorToVerticalDiffCodeLens.get(filepath);
const block = blocks?.[index];
if (!blocks || !block) {
return;
}
const handler = verticalPerLineDiffManager.getHandlerForFile(filepath);
if (!handler) {
return;
}
// CodeLens object removed from editorToVerticalDiffCodeLens here
handler.acceptRejectBlock(accept, block.start, block.numGreen, block.numRed);
}
// Copy everything over from extension.ts
const commandsMap: { [command: string]: (...args: any) => any } = {
"continue.acceptDiff": acceptDiffCommand,
"continue.rejectDiff": rejectDiffCommand,
const commandsMap: (
ide: IDE,
extensionContext: vscode.ExtensionContext,
sidebar: ContinueGUIWebviewViewProvider,
configHandler: ConfigHandler,
diffManager: DiffManager,
verticalDiffManager: VerticalPerLineDiffManager
) => { [command: string]: (...args: any) => any } = (
ide,
extensionContext,
sidebar,
configHandler,
diffManager,
verticalDiffManager
) => ({
"continue.acceptDiff": async (newFilepath?: string | vscode.Uri) => {
if (newFilepath instanceof vscode.Uri) {
newFilepath = newFilepath.fsPath;
}
verticalDiffManager.clearForFilepath(newFilepath, true);
await diffManager.acceptDiff(newFilepath);
},
"continue.rejectDiff": async (newFilepath?: string | vscode.Uri) => {
if (newFilepath instanceof vscode.Uri) {
newFilepath = newFilepath.fsPath;
}
verticalDiffManager.clearForFilepath(newFilepath, false);
await diffManager.rejectDiff(newFilepath);
},
"continue.acceptVerticalDiffBlock": (filepath?: string, index?: number) => {
acceptRejectVerticalDiffBlock(true, filepath, index);
verticalDiffManager.acceptRejectVerticalDiffBlock(true, filepath, index);
},
"continue.rejectVerticalDiffBlock": (filepath?: string, index?: number) => {
acceptRejectVerticalDiffBlock(false, filepath, index);
verticalDiffManager.acceptRejectVerticalDiffBlock(false, filepath, index);
},
"continue.quickFix": async (message: string, code: string, edit: boolean) => {
debugPanelWebview?.postMessage({
type: "newSessionWithPrompt",
sidebar.webviewProtocol?.request("newSessionWithPrompt", {
prompt: `${
edit ? "/edit " : ""
}${code}\n\nHow do I fix this problem in the above code?: ${message}`,
});
if (!edit) {
vscode.commands.executeCommand("continue.continueGUIView.focus");
}
},
"continue.focusContinueInput": async () => {
vscode.commands.executeCommand("continue.continueGUIView.focus");
debugPanelWebview?.postMessage({
type: "focusContinueInput",
});
addHighlightedCodeToContext(false);
sidebar.webviewProtocol?.request("focusContinueInput", undefined);
addHighlightedCodeToContext(false, sidebar.webviewProtocol);
},
"continue.focusContinueInputWithoutClear": async () => {
vscode.commands.executeCommand("continue.continueGUIView.focus");
debugPanelWebview?.postMessage({
type: "focusContinueInputWithoutClear",
});
addHighlightedCodeToContext(true);
sidebar.webviewProtocol?.request(
"focusContinueInputWithoutClear",
undefined
);
addHighlightedCodeToContext(true, sidebar.webviewProtocol);
},
"continue.toggleAuxiliaryBar": () => {
vscode.commands.executeCommand("workbench.action.toggleAuxiliaryBar");
@ -167,7 +164,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
}
if (text.length > 0) {
await streamEdit(text);
await verticalDiffManager.streamEdit(text);
} else {
// Pick context first
const quickPickItems: Promise<vscode.QuickPickItem[]> = configHandler
@ -201,7 +198,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
title: "Continue Quick Edit",
});
if (text) {
const llm = await llmFromTitle();
const llm = await configHandler.llmFromTitle();
const config = await configHandler.loadConfig();
const context = (
await Promise.all(
@ -216,7 +213,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
return provider.getContextItems("", {
embeddingsProvider: config.embeddingsProvider,
ide: new VsCodeIde(),
ide,
llm,
fullInput: text || "",
selectedCode: [],
@ -230,24 +227,24 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
"\n\n---\n\n" +
text;
await streamEdit(text);
await verticalDiffManager.streamEdit(text);
}
}
},
"continue.writeCommentsForCode": async () => {
await streamEdit("Write comments for this code");
await verticalDiffManager.streamEdit("Write comments for this code");
},
"continue.writeDocstringForCode": async () => {
await streamEdit("Write a docstring for this code");
await verticalDiffManager.streamEdit("Write a docstring for this code");
},
"continue.fixCode": async () => {
await streamEdit("Fix this code");
await verticalDiffManager.streamEdit("Fix this code");
},
"continue.optimizeCode": async () => {
await streamEdit("Optimize this code");
await verticalDiffManager.streamEdit("Optimize this code");
},
"continue.fixGrammar": async () => {
await streamEdit(
await verticalDiffManager.streamEdit(
"If there are any grammar or spelling mistakes in this writing, fix them"
);
},
@ -264,10 +261,9 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
await vscode.window.showTextDocument(uri);
},
"continue.debugTerminal": async () => {
const terminalContents = await ideProtocolClient.getTerminalContents(1);
const terminalContents = await ide.getTerminalContents();
vscode.commands.executeCommand("continue.continueGUIView.focus");
debugPanelWebview?.postMessage({
type: "userInput",
sidebar.webviewProtocol?.request("userInput", {
input: `I got the following error, can you please help explain how to fix it?\n\n${terminalContents}`,
});
},
@ -280,21 +276,17 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
// Commands without keyboard shortcuts
"continue.addModel": () => {
vscode.commands.executeCommand("continue.continueGUIView.focus");
debugPanelWebview?.postMessage({
type: "addModel",
});
sidebar.webviewProtocol?.request("addModel", undefined);
},
"continue.openSettingsUI": () => {
vscode.commands.executeCommand("continue.continueGUIView.focus");
debugPanelWebview?.postMessage({
type: "openSettings",
});
sidebar.webviewProtocol?.request("openSettings", undefined);
},
"continue.sendMainUserInput": (text: string) => {
ideProtocolClient.sendMainUserInput(text);
sidebar.sendMainUserInput(text);
},
"continue.shareSession": () => {
ideProtocolClient.sendMainUserInput("/share");
sidebar.sendMainUserInput("/share");
},
"continue.selectRange": (startLine: number, endLine: number) => {
if (!vscode.window.activeTextEditor) {
@ -319,17 +311,13 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
});
},
"continue.sendToTerminal": (text: string) => {
ideProtocolClient.runCommand(text);
ide.runCommand(text);
},
"continue.newSession": () => {
debugPanelWebview?.postMessage({
type: "newSession",
});
sidebar.webviewProtocol?.request("newSession", undefined);
},
"continue.viewHistory": () => {
debugPanelWebview?.postMessage({
type: "viewHistory",
});
sidebar.webviewProtocol?.request("viewHistory", undefined);
},
"continue.toggleFullScreen": () => {
// Check if full screen is already open by checking open tabs
@ -364,7 +352,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
return;
}
// Close the sidebars
// Close the sidebar.webviews
// vscode.commands.executeCommand("workbench.action.closeSidebar");
vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar");
// vscode.commands.executeCommand("workbench.action.toggleZenMode");
@ -373,9 +361,12 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
"Continue",
vscode.ViewColumn.One
);
panel.webview.html = getSidebarContent(
panel.webview.html = sidebar.getSidebarContent(
extensionContext,
panel,
ide,
configHandler,
verticalDiffManager,
undefined,
undefined,
true
@ -388,7 +379,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
vscode.commands.executeCommand("continue.continueGUIView.focus");
for (const uri of uris) {
addEntireFileToContext(uri, false);
addEntireFileToContext(uri, false, sidebar.webviewProtocol);
}
},
"continue.updateAllReferences": (filepath: vscode.Uri) => {
@ -398,7 +389,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
return;
}
const position = editor.selection.active;
ideProtocolClient.sendMainUserInput(
sidebar.sendMainUserInput(
`/references ${filepath.fsPath} ${position.line} ${position.character}`
);
},
@ -408,7 +399,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
) => {
clearTimeout(logRejectionTimeout);
outcome.accepted = true;
ideProtocolClient.logDevData("autocomplete", outcome);
logDevData("autocomplete", outcome);
},
"continue.toggleTabAutocompleteEnabled": () => {
const config = vscode.workspace.getConfiguration("continue");
@ -419,10 +410,27 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
vscode.ConfigurationTarget.Global
);
},
};
});
export function registerAllCommands(context: vscode.ExtensionContext) {
for (const [command, callback] of Object.entries(commandsMap)) {
export function registerAllCommands(
context: vscode.ExtensionContext,
ide: IDE,
extensionContext: vscode.ExtensionContext,
sidebar: ContinueGUIWebviewViewProvider,
configHandler: ConfigHandler,
diffManager: DiffManager,
verticalDiffManager: VerticalPerLineDiffManager
) {
for (const [command, callback] of Object.entries(
commandsMap(
ide,
extensionContext,
sidebar,
configHandler,
diffManager,
verticalDiffManager
)
)) {
context.subscriptions.push(
vscode.commands.registerCommand(command, callback)
);

View file

@ -1,707 +1,118 @@
import { ContextItemId, DiffLine, FileEdit, ModelDescription } from "core";
import { indexDocs } from "core/indexing/docs";
import TransformersJsEmbeddingsProvider from "core/indexing/embeddings/TransformersJsEmbeddingsProvider";
import { editConfigJson, getConfigJsonPath } from "core/util/paths";
import { readFileSync, writeFileSync } from "fs";
import { v4 as uuidv4 } from "uuid";
import { FileEdit, IDE } from "core";
import { ConfigHandler } from "core/config/handler";
import * as vscode from "vscode";
import {
extensionContext,
ideProtocolClient,
showTutorial,
windowId,
} from "./activation/activate";
import { streamEdit } from "./diff/verticalPerLine/manager";
import historyManager from "./history";
import { VsCodeIde } from "./ideProtocol";
import { configHandler, llmFromTitle } from "./loadConfig";
import { VerticalPerLineDiffManager } from "./diff/verticalPerLine/manager";
import { getTheme } from "./util/getTheme";
import { getExtensionUri, getNonce, getUniqueId } from "./util/vscode";
import { VsCodeWebviewProtocol } from "./webviewProtocol";
export let debugPanelWebview: vscode.Webview | undefined;
export class ContinueGUIWebviewViewProvider
implements vscode.WebviewViewProvider
{
public static readonly viewType = "continue.continueGUIView";
public webviewProtocol: VsCodeWebviewProtocol;
export async function webviewRequest(
messageType: string,
data: any = {}
): Promise<any> {
return new Promise((resolve, reject) => {
if (!debugPanelWebview) {
resolve(undefined);
resolveWebviewView(
webviewView: vscode.WebviewView,
_context: vscode.WebviewViewResolveContext,
_token: vscode.CancellationToken
): void | Thenable<void> {
this._webview = webviewView.webview;
webviewView.webview.html = this.getSidebarContent(
this.extensionContext,
webviewView,
this.ide,
this.configHandler,
this.verticalDiffManager
);
}
private _webview?: vscode.Webview;
get webview() {
return this._webview;
}
sendMainUserInput(input: string) {
this.webview?.postMessage({
type: "userInput",
input,
});
}
constructor(
private readonly configHandler: ConfigHandler,
private readonly ide: IDE,
private readonly windowId: string,
private readonly extensionContext: vscode.ExtensionContext,
private readonly verticalDiffManager: VerticalPerLineDiffManager
) {
this.webviewProtocol = new VsCodeWebviewProtocol(
ide,
configHandler,
verticalDiffManager
);
}
getSidebarContent(
context: vscode.ExtensionContext | undefined,
panel: vscode.WebviewPanel | vscode.WebviewView,
ide: IDE,
configHandler: ConfigHandler,
verticalDiffManager: VerticalPerLineDiffManager,
page: string | undefined = undefined,
edits: FileEdit[] | undefined = undefined,
isFullScreen: boolean = false
): string {
let extensionUri = getExtensionUri();
let scriptUri: string;
let styleMainUri: string;
let vscMediaUrl: string = panel.webview
.asWebviewUri(vscode.Uri.joinPath(extensionUri, "gui"))
.toString();
const inDevelopmentMode =
context?.extensionMode === vscode.ExtensionMode.Development;
if (!inDevelopmentMode) {
scriptUri = panel.webview
.asWebviewUri(vscode.Uri.joinPath(extensionUri, "gui/assets/index.js"))
.toString();
styleMainUri = panel.webview
.asWebviewUri(vscode.Uri.joinPath(extensionUri, "gui/assets/index.css"))
.toString();
} else {
scriptUri = "http://localhost:5173/src/main.tsx";
styleMainUri = "http://localhost:5173/src/index.css";
}
const listener = debugPanelWebview?.onDidReceiveMessage((data) => {
if (data.type === messageType) {
resolve(data);
listener?.dispose();
}
});
debugPanelWebview?.postMessage({ type: messageType, data });
setTimeout(() => {
reject("Error communciating with Continue side panel: timed out");
listener?.dispose();
}, 500);
});
}
const abortedMessageIds: Set<string> = new Set();
export function getSidebarContent(
context: vscode.ExtensionContext | undefined,
panel: vscode.WebviewPanel | vscode.WebviewView,
page: string | undefined = undefined,
edits: FileEdit[] | undefined = undefined,
isFullScreen: boolean = false
): string {
if (!isFullScreen) {
debugPanelWebview = panel.webview;
panel.onDidDispose(() => {
debugPanelWebview = undefined;
});
}
let extensionUri = getExtensionUri();
let scriptUri: string;
let styleMainUri: string;
let vscMediaUrl: string = panel.webview
.asWebviewUri(vscode.Uri.joinPath(extensionUri, "gui"))
.toString();
const inDevelopmentMode =
context?.extensionMode === vscode.ExtensionMode.Development;
if (!inDevelopmentMode) {
scriptUri = panel.webview
.asWebviewUri(vscode.Uri.joinPath(extensionUri, "gui/assets/index.js"))
.toString();
styleMainUri = panel.webview
.asWebviewUri(vscode.Uri.joinPath(extensionUri, "gui/assets/index.css"))
.toString();
} else {
scriptUri = "http://localhost:5173/src/main.tsx";
styleMainUri = "http://localhost:5173/src/index.css";
}
panel.webview.options = {
enableScripts: true,
localResourceRoots: [
vscode.Uri.joinPath(extensionUri, "gui"),
vscode.Uri.joinPath(extensionUri, "assets"),
],
enableCommandUris: true,
portMapping: [
{
webviewPort: 65433,
extensionHostPort: 65433,
},
],
};
const nonce = getNonce();
panel.webview.onDidReceiveMessage(async (data) => {
const ide = new VsCodeIde();
const respond = (message: any) => {
panel.webview.postMessage({
type: data.type,
messageId: data.messageId,
message: message,
});
panel.webview.options = {
enableScripts: true,
localResourceRoots: [
vscode.Uri.joinPath(extensionUri, "gui"),
vscode.Uri.joinPath(extensionUri, "assets"),
],
enableCommandUris: true,
portMapping: [
{
webviewPort: 65433,
extensionHostPort: 65433,
},
],
};
try {
switch (data.type) {
case "abort": {
abortedMessageIds.add(data.messageId);
break;
}
case "showFile": {
ideProtocolClient.openFile(data.filepath);
break;
}
case "openConfigJson": {
ideProtocolClient.openFile(getConfigJsonPath());
break;
}
case "readRangeInFile": {
vscode.workspace.openTextDocument(data.filepath).then((document) => {
let start = new vscode.Position(0, 0);
let end = new vscode.Position(5, 0);
let range = new vscode.Range(start, end);
let contents = document.getText(range);
panel.webview.postMessage({
type: "readRangeInFile",
messageId: data.messageId,
contents,
});
});
break;
}
case "toggleDevTools": {
vscode.commands.executeCommand("workbench.action.toggleDevTools");
vscode.commands.executeCommand("continue.viewLogs");
break;
}
case "reloadWindow": {
vscode.commands.executeCommand("workbench.action.reloadWindow");
break;
}
case "focusEditor": {
vscode.commands.executeCommand(
"workbench.action.focusActiveEditorGroup"
);
break;
}
case "toggleFullScreen": {
vscode.commands.executeCommand("continue.toggleFullScreen");
break;
}
case "withProgress": {
// This message allows withProgress to be used in the webview
if (data.done) {
// Will be caught in the listener created below
break;
}
let title = data.title;
vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title,
cancellable: false,
},
async () => {
return new Promise<void>((resolve, reject) => {
let listener = panel.webview.onDidReceiveMessage(
async (data) => {
if (
data.type === "withProgress" &&
data.done &&
data.title === title
) {
listener.dispose();
resolve();
}
}
);
});
}
);
const nonce = getNonce();
break;
}
// IDE
case "getDiff": {
respond(await ide.getDiff());
break;
}
case "getSerializedConfig": {
respond(await ide.getSerializedConfig());
break;
}
case "getTerminalContents": {
respond(await ide.getTerminalContents());
break;
}
case "listWorkspaceContents": {
respond(await ide.listWorkspaceContents());
break;
}
case "getWorkspaceDirs": {
respond(await ide.getWorkspaceDirs());
break;
}
case "listFolders": {
respond(await ide.listFolders());
break;
}
case "writeFile": {
respond(
await ide.writeFile(data.message.path, data.message.contents)
);
break;
}
case "showVirtualFile": {
respond(
await ide.showVirtualFile(data.message.name, data.message.content)
);
break;
}
case "getContinueDir": {
respond(await ide.getContinueDir());
break;
}
case "openFile": {
respond(await ide.openFile(data.message.path));
break;
}
case "runCommand": {
respond(await ide.runCommand(data.message.command));
break;
}
case "getSearchResults": {
respond(await ide.getSearchResults(data.message.query));
break;
}
case "subprocess": {
respond(await ide.subprocess(data.message.command));
break;
}
case "getFilesToEmbed": {
let filesToEmbed = await ide.getFilesToEmbed(data.message.providerId);
respond(filesToEmbed);
break;
}
case "sendChunkForFile": {
respond(
await ide.sendEmbeddingForChunk(
data.message.chunk,
data.message.embedding,
data.message.tags
)
);
break;
}
case "retrieveChunks": {
respond(
await ide.retrieveChunks(
data.message.text,
data.message.n,
data.message.directory
)
);
break;
}
// History
case "history": {
respond(historyManager.list());
break;
}
case "saveSession": {
historyManager.save(data.message);
respond({});
break;
}
case "deleteSession": {
historyManager.delete(data.message);
respond({});
break;
}
case "loadSession": {
respond(historyManager.load(data.message));
break;
}
case "saveFile": {
respond(await ide.saveFile(data.message.filepath));
break;
}
case "readFile": {
respond(await ide.readFile(data.message.filepath));
break;
}
case "showDiff": {
respond(
await ide.showDiff(
data.message.filepath,
data.message.newContents,
data.message.stepIndex
)
);
break;
}
case "diffLine": {
const {
diffLine,
filepath,
startLine,
endLine,
}: {
diffLine: DiffLine;
filepath: string;
startLine: number;
endLine: number;
} = data.message;
respond(
await ide.verticalDiffUpdate(filepath, startLine, endLine, diffLine)
);
break;
}
case "getProblems": {
respond(await ide.getProblems(data.message.filepath));
break;
}
case "getBranch": {
const { dir } = data.message;
respond(await ide.getBranch(dir));
break;
}
case "getOpenFiles": {
respond(await ide.getOpenFiles());
break;
}
case "getPinnedFiles": {
respond(await ide.getPinnedFiles());
break;
}
case "showLines": {
const { filepath, startLine, endLine } = data.message;
respond(await ide.showLines(filepath, startLine, endLine));
break;
}
// Other
case "errorPopup": {
vscode.window
.showErrorMessage(data.message, "Show Logs")
.then((selection) => {
if (selection === "Show Logs") {
vscode.commands.executeCommand(
"workbench.action.toggleDevTools"
);
}
});
break;
}
case "logDevData": {
ideProtocolClient.logDevData(data.tableName, data.data);
break;
}
case "addModel": {
const model = data.model;
const config = readFileSync(getConfigJsonPath(), "utf8");
const configJson = JSON.parse(config);
configJson.models.push(model);
const newConfigString = JSON.stringify(
configJson,
(key, value) => {
return value === null ? undefined : value;
},
2
);
writeFileSync(getConfigJsonPath(), newConfigString);
configHandler.reloadConfig();
ideProtocolClient.openFile(getConfigJsonPath());
// Find the range where it was added and highlight
let lines = newConfigString.split("\n");
let startLine;
let endLine;
for (let i = 0; i < lines.length; i++) {
let line = lines[i];
if (!startLine) {
if (line.trim() === `"title": "${data.model.title}",`) {
startLine = i - 1;
}
} else {
if (line.startsWith(" }")) {
endLine = i;
break;
}
}
}
if (startLine && endLine) {
ideProtocolClient.highlightCode(
{
filepath: getConfigJsonPath(),
range: {
start: { character: 0, line: startLine },
end: { character: 0, line: endLine },
},
},
"#fff1"
);
}
vscode.window.showInformationMessage(
"🎉 Your model has been successfully added to config.json. You can use this file to further edit its configuration."
);
break;
}
case "deleteModel": {
const configJson = editConfigJson((config) => {
config.models = config.models.filter(
(m: any) => m.title !== data.title
);
return config;
});
configHandler.reloadConfig();
break;
}
case "addOpenAIKey": {
const configJson = editConfigJson((config) => {
config.models = config.models.map((m: ModelDescription) => {
if (m.provider === "free-trial") {
m.apiKey = data.key;
m.provider = "openai";
}
return m;
});
return config;
});
configHandler.reloadConfig();
break;
}
case "llmStreamComplete": {
const model = await llmFromTitle(data.message.title);
const gen = model.streamComplete(
data.message.prompt,
data.message.completionOptions
);
let next = await gen.next();
while (!next.done) {
if (abortedMessageIds.has(data.messageId)) {
abortedMessageIds.delete(data.messageId);
next = await gen.return({ completion: "", prompt: "" });
break;
}
respond({ content: next.value });
next = await gen.next();
}
respond({ done: true, data: next.value });
break;
}
case "llmStreamChat": {
const model = await llmFromTitle(data.message.title);
const gen = model.streamChat(
data.message.messages,
data.message.completionOptions
);
let next = await gen.next();
while (!next.done) {
if (abortedMessageIds.has(data.messageId)) {
abortedMessageIds.delete(data.messageId);
next = await gen.return({ completion: "", prompt: "" });
break;
}
respond({ content: next.value.content });
next = await gen.next();
}
respond({ done: true, data: next.value });
break;
}
case "llmComplete": {
const model = await llmFromTitle(data.message.title);
const completion = await model.complete(
data.message.prompt,
data.message.completionOptions
);
respond({ content: completion });
break;
}
case "runNodeJsSlashCommand": {
const {
input,
history,
modelTitle,
slashCommandName,
contextItems,
params,
historyIndex,
} = data.message;
const config = await configHandler.loadConfig();
const llm = await llmFromTitle(modelTitle);
const slashCommand = config.slashCommands?.find(
(sc) => sc.name === slashCommandName
);
if (!slashCommand) {
throw new Error(`Unknown slash command ${slashCommandName}`);
}
for await (const update of slashCommand.run({
input,
history,
llm,
contextItems,
params,
ide,
addContextItem: (item) => {
debugPanelWebview?.postMessage({
type: "addContextItem",
message: { item, historyIndex },
});
},
})) {
if (abortedMessageIds.has(data.messageId)) {
abortedMessageIds.delete(data.messageId);
break;
}
respond({ content: update });
}
respond({ done: true });
break;
}
case "loadSubmenuItems": {
const { title } = data.message;
const config = await configHandler.loadConfig();
const provider = config.contextProviders?.find(
(p) => p.description.title === title
);
if (!provider) {
vscode.window.showErrorMessage(
`Unknown provider ${title}. Existing providers: ${config.contextProviders
?.map((p) => p.description.title)
.join(", ")}`
);
respond({ items: [] });
break;
}
try {
const items = await provider.loadSubmenuItems({ ide });
respond({ items });
} catch (e) {
vscode.window.showErrorMessage(
`Error loading submenu items from ${title}: ${e}`
);
respond({ items: [] });
}
break;
}
case "getContextItems": {
const { name, query, fullInput, selectedCode } = data.message;
const config = await configHandler.loadConfig();
const llm = await llmFromTitle();
const provider = config.contextProviders?.find(
(p) => p.description.title === name
);
if (!provider) {
vscode.window.showErrorMessage(
`Unknown provider ${name}. Existing providers: ${config.contextProviders
?.map((p) => p.description.title)
.join(", ")}`
);
respond({ items: [] });
break;
}
try {
const id: ContextItemId = {
providerTitle: provider.description.title,
itemId: uuidv4(),
};
const items = await provider.getContextItems(query, {
llm,
embeddingsProvider: config.embeddingsProvider,
fullInput,
ide,
selectedCode,
});
respond({ items: items.map((item) => ({ ...item, id })) });
} catch (e) {
vscode.window.showErrorMessage(
`Error getting context items from ${name}: ${e}`
);
respond({ items: [] });
}
break;
}
case "addDocs": {
const { url, title } = data;
const embeddingsProvider = new TransformersJsEmbeddingsProvider();
vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: `Indexing ${title}`,
cancellable: false,
},
async (progress) => {
for await (const update of indexDocs(
title,
new URL(url),
embeddingsProvider
)) {
progress.report({
increment: update.progress,
message: update.desc,
});
}
vscode.window.showInformationMessage(
`🎉 Successfully indexed ${title}`
);
debugPanelWebview?.postMessage({
type: "refreshSubmenuItems",
});
}
);
break;
}
case "applyToCurrentFile": {
// Select the entire current file
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showErrorMessage(
"No active editor to apply edits to"
);
break;
}
const document = editor.document;
if (document.getText().trim() === "") {
editor.edit((editBuilder) => {
editBuilder.insert(document.positionAt(0), data.text);
});
return;
}
const start = new vscode.Position(0, 0);
const end = new vscode.Position(
document.lineCount - 1,
document.lineAt(document.lineCount - 1).text.length
);
editor.selection = new vscode.Selection(start, end);
streamEdit(
`The following code was suggested as an edit:\n\`\`\`\n${data.text}\n\`\`\`\nPlease apply it to the previous code.`
);
break;
}
case "showTutorial": {
showTutorial();
break;
}
}
} catch (e: any) {
let message = `Continue error: ${e.message}`;
if (e.cause) {
if (e.cause.name === "ConnectTimeoutError") {
message = `Connection timed out. If you expect it to take a long time to connect, you can increase the timeout in config.json by setting "requestOptions": { "timeout": 10000 }. You can find the full config reference here: https://continue.dev/docs/reference/config`;
} else if (e.cause.code === "ECONNREFUSED") {
message = `Connection was refused. This likely means that there is no server running at the specified URL. If you are running your own server you may need to set the "apiBase" parameter in config.json. For example, you can set up an OpenAI-compatible server like here: https://continue.dev/docs/reference/Model%20Providers/openai#openai-compatible-servers--apis`;
} else {
message = `The request failed with "${e.cause.name}": ${e.cause.message}. If you're having trouble setting up Continue, please see the troubleshooting guide for help.`;
}
const currentTheme = getTheme();
vscode.workspace.onDidChangeConfiguration((e) => {
if (e.affectsConfiguration("workbench.colorTheme")) {
// Send new theme to GUI to update embedded Monaco themes
this.webviewProtocol?.request("setTheme", { theme: getTheme() });
}
});
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://continue.dev/docs/troubleshooting")
);
}
});
respond({ done: true, data: {} });
}
});
this.webviewProtocol.webview = panel.webview;
const currentTheme = getTheme();
vscode.workspace.onDidChangeConfiguration((e) => {
if (e.affectsConfiguration("workbench.colorTheme")) {
// Send new theme to GUI to update embedded Monaco themes
debugPanelWebview?.postMessage({ type: "setTheme", theme: getTheme() });
}
});
return `<!DOCTYPE html>
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
@ -729,7 +140,7 @@ export function getSidebarContent(
<script type="module" nonce="${nonce}" src="${scriptUri}"></script>
<script>localStorage.setItem("ide", "vscode")</script>
<script>window.windowId = "${windowId}"</script>
<script>window.windowId = "${this.windowId}"</script>
<script>window.vscMachineId = "${getUniqueId()}"</script>
<script>window.vscMediaUrl = "${vscMediaUrl}"</script>
<script>window.ide = "vscode"</script>
@ -750,18 +161,5 @@ export function getSidebarContent(
${page ? `<script>window.location.pathname = "${page}"</script>` : ""}
</body>
</html>`;
}
export class ContinueGUIWebviewViewProvider
implements vscode.WebviewViewProvider
{
public static readonly viewType = "continue.continueGUIView";
resolveWebviewView(
webviewView: vscode.WebviewView,
_context: vscode.WebviewViewResolveContext,
_token: vscode.CancellationToken
): void | Thenable<void> {
webviewView.webview.html = getSidebarContent(extensionContext, webviewView);
}
}

View file

@ -3,11 +3,9 @@ import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import * as vscode from "vscode";
import { extensionContext } from "../activation/activate";
import { debugPanelWebview } from "../debugPanel";
import { getMetaKeyLabel, getPlatform } from "../util/util";
import { uriFromFilePath } from "../util/vscode";
import { verticalPerLineDiffManager } from "./verticalPerLine/manager";
import { VsCodeWebviewProtocol } from "../webviewProtocol";
interface DiffInfo {
originalFilepath: string;
@ -32,7 +30,7 @@ export const DIFF_DIRECTORY = path
.join(os.homedir(), ".continue", "diffs")
.replace(/^C:/, "c:");
class DiffManager {
export class DiffManager {
// Create a temporary file in the global .continue directory which displays the updated version
// Doing this because virtual files are read-only
private diffs: Map<string, DiffInfo> = new Map();
@ -50,7 +48,9 @@ class DiffManager {
}
}
constructor() {
webviewProtocol: VsCodeWebviewProtocol | undefined;
constructor(private readonly extensionContext: vscode.ExtensionContext) {
this.setupDirectory();
// Listen for file closes, and if it's a diff file, clean up
@ -115,7 +115,7 @@ class DiffManager {
.update("codeLens", true, vscode.ConfigurationTarget.Global);
if (
extensionContext?.globalState.get<boolean>(
this.extensionContext.globalState.get<boolean>(
"continue.showDiffInfoMessage"
) !== false
) {
@ -128,7 +128,7 @@ class DiffManager {
.then((selection) => {
if (selection === "Don't show again") {
// Get the global state
extensionContext?.globalState.update(
this.extensionContext.globalState.update(
"continue.showDiffInfoMessage",
false
);
@ -289,7 +289,7 @@ class DiffManager {
}
// Stop the step at step_index in case it is still streaming
debugPanelWebview?.postMessage({ type: "setInactive" });
this.webviewProtocol?.request("setInactive", undefined);
vscode.workspace.textDocuments
.find((doc) => doc.uri.fsPath === newFilepath)
@ -302,8 +302,6 @@ class DiffManager {
}
}
export const diffManager = new DiffManager();
async function recordAcceptReject(accepted: boolean, diffInfo: DiffInfo) {
const devDataDir = devDataPath();
const suggestionsPath = path.join(devDataDir, "suggestions.json");
@ -333,19 +331,3 @@ async function recordAcceptReject(accepted: boolean, diffInfo: DiffInfo) {
JSON.stringify(suggestions, null, 4)
);
}
export async function acceptDiffCommand(newFilepath?: string | vscode.Uri) {
if (newFilepath instanceof vscode.Uri) {
newFilepath = newFilepath.fsPath;
}
verticalPerLineDiffManager.clearForFilepath(newFilepath, true);
await diffManager.acceptDiff(newFilepath);
}
export async function rejectDiffCommand(newFilepath?: string | vscode.Uri) {
if (newFilepath instanceof vscode.Uri) {
newFilepath = newFilepath.fsPath;
}
verticalPerLineDiffManager.clearForFilepath(newFilepath, false);
await diffManager.rejectDiff(newFilepath);
}

View file

@ -7,10 +7,7 @@ import {
indexDecorationType,
redDecorationType,
} from "./decorations";
import {
editorToVerticalDiffCodeLens,
verticalPerLineDiffManager,
} from "./manager";
import { VerticalDiffCodeLens } from "./manager";
export class VerticalPerLineDiffHandler {
private editor: vscode.TextEditor;
@ -33,6 +30,14 @@ export class VerticalPerLineDiffHandler {
startLine: number,
endLine: number,
editor: vscode.TextEditor,
private readonly editorToVerticalDiffCodeLens: Map<
string,
VerticalDiffCodeLens[]
>,
private readonly clearForFilepath: (
filepath: string | undefined,
accept: boolean
) => void,
input?: string
) {
this.currentLineIndex = startLine;
@ -71,13 +76,13 @@ export class VerticalPerLineDiffHandler {
}
if (this.deletionBuffer.length || this.insertedInCurrentBlock > 0) {
const blocks = editorToVerticalDiffCodeLens.get(this.filepath) || [];
const blocks = this.editorToVerticalDiffCodeLens.get(this.filepath) || [];
blocks.push({
start: this.currentLineIndex - this.insertedInCurrentBlock,
numRed: this.deletionBuffer.length,
numGreen: this.insertedInCurrentBlock,
});
editorToVerticalDiffCodeLens.set(this.filepath, blocks);
this.editorToVerticalDiffCodeLens.set(this.filepath, blocks);
}
if (this.deletionBuffer.length === 0) {
@ -188,7 +193,7 @@ export class VerticalPerLineDiffHandler {
this.greenDecorationManager.clear();
this.clearIndexLineDecorations();
editorToVerticalDiffCodeLens.delete(this.filepath);
this.editorToVerticalDiffCodeLens.delete(this.filepath);
this.editor.edit((editBuilder) => {
for (const range of rangesToDelete) {
@ -251,7 +256,7 @@ export class VerticalPerLineDiffHandler {
// }
// });
} catch (e) {
verticalPerLineDiffManager.clearForFilepath(this.filepath, false);
this.clearForFilepath(this.filepath, false);
throw e;
}
}
@ -288,7 +293,7 @@ export class VerticalPerLineDiffHandler {
// Shift the codelens objects
const blocks =
editorToVerticalDiffCodeLens
this.editorToVerticalDiffCodeLens
.get(this.filepath)
?.filter((x) => x.start !== startLine)
.map((x) => {
@ -297,6 +302,6 @@ export class VerticalPerLineDiffHandler {
}
return x;
}) || [];
editorToVerticalDiffCodeLens.set(this.filepath, blocks);
this.editorToVerticalDiffCodeLens.set(this.filepath, blocks);
}
}

View file

@ -1,13 +1,23 @@
import { streamDiffLines } from "core/commands/slash/verticalEdit";
import { ConfigHandler } from "core/config/handler";
import { getMarkdownLanguageTagForFile } from "core/util";
import { streamDiffLines } from "core/util/verticalEdit";
import * as vscode from "vscode";
import { llmFromTitle } from "../../loadConfig";
import { VerticalPerLineDiffHandler } from "./handler";
class VerticalPerLineDiffManager {
export interface VerticalDiffCodeLens {
start: number;
numRed: number;
numGreen: number;
}
export class VerticalPerLineDiffManager {
private filepathToEditorMap: Map<string, VerticalPerLineDiffHandler> =
new Map();
editorToVerticalDiffCodeLens: Map<string, VerticalDiffCodeLens[]> = new Map();
constructor(private readonly configHandler: ConfigHandler) {}
createVerticalPerLineDiffHandler(
filepath: string,
startLine: number,
@ -24,6 +34,8 @@ class VerticalPerLineDiffManager {
startLine,
endLine,
editor,
this.editorToVerticalDiffCodeLens,
this.clearForFilepath,
input
);
this.filepathToEditorMap.set(filepath, handler);
@ -46,7 +58,9 @@ class VerticalPerLineDiffManager {
const handler = new VerticalPerLineDiffHandler(
startLine,
endLine,
editor
editor,
this.editorToVerticalDiffCodeLens,
this.clearForFilepath
);
this.filepathToEditorMap.set(filepath, handler);
return handler;
@ -75,78 +89,113 @@ class VerticalPerLineDiffManager {
this.filepathToEditorMap.delete(filepath);
}
}
}
export const verticalPerLineDiffManager = new VerticalPerLineDiffManager();
acceptRejectVerticalDiffBlock(
accept: boolean,
filepath?: string,
index?: number
) {
if (!filepath) {
const activeEditor = vscode.window.activeTextEditor;
if (!activeEditor) {
return;
}
filepath = activeEditor.document.uri.fsPath;
}
export async function streamEdit(input: string) {
const editor = vscode.window.activeTextEditor;
if (!editor) {
return;
if (typeof index === "undefined") {
index = 0;
}
let blocks = this.editorToVerticalDiffCodeLens.get(filepath);
const block = blocks?.[index];
if (!blocks || !block) {
return;
}
const handler = this.getHandlerForFile(filepath);
if (!handler) {
return;
}
// CodeLens object removed from editorToVerticalDiffCodeLens here
handler.acceptRejectBlock(
accept,
block.start,
block.numGreen,
block.numRed
);
}
const filepath = editor.document.uri.fsPath;
const startLine = editor.selection.start.line;
const endLine = editor.selection.end.line;
async streamEdit(input: string) {
const editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
const existingHandler =
verticalPerLineDiffManager.getHandlerForFile(filepath);
existingHandler?.clear(false);
await new Promise((resolve) => {
setTimeout(resolve, 200);
});
const diffHandler =
verticalPerLineDiffManager.createVerticalPerLineDiffHandler(
const filepath = editor.document.uri.fsPath;
const startLine = editor.selection.start.line;
const endLine = editor.selection.end.line;
const existingHandler = this.getHandlerForFile(filepath);
existingHandler?.clear(false);
await new Promise((resolve) => {
setTimeout(resolve, 200);
});
const diffHandler = this.createVerticalPerLineDiffHandler(
filepath,
existingHandler?.range.start.line ?? startLine,
existingHandler?.range.end.line ?? endLine,
input
);
if (!diffHandler) {
return;
}
if (!diffHandler) {
return;
}
const selectedRange =
existingHandler?.range ??
new vscode.Range(
editor.selection.start.with(undefined, 0),
editor.selection.end.with(undefined, Number.MAX_SAFE_INTEGER)
const selectedRange =
existingHandler?.range ??
new vscode.Range(
editor.selection.start.with(undefined, 0),
editor.selection.end.with(undefined, Number.MAX_SAFE_INTEGER)
);
const rangeContent = editor.document.getText(selectedRange);
const llm = await this.configHandler.llmFromTitle();
// Unselect the range
editor.selection = new vscode.Selection(
editor.selection.active,
editor.selection.active
);
const rangeContent = editor.document.getText(selectedRange);
const llm = await llmFromTitle();
// Unselect the range
editor.selection = new vscode.Selection(
editor.selection.active,
editor.selection.active
);
vscode.commands.executeCommand(
"setContext",
"continue.streamingDiff",
true
);
vscode.commands.executeCommand("setContext", "continue.streamingDiff", true);
if (existingHandler?.input) {
if (existingHandler.input.startsWith("Original request: ")) {
existingHandler.input = existingHandler.input.substring(
"Original request: ".length
if (existingHandler?.input) {
if (existingHandler.input.startsWith("Original request: ")) {
existingHandler.input = existingHandler.input.substring(
"Original request: ".length
);
}
input = `Original request: ${existingHandler.input}\nUpdated request: ${input}`;
}
try {
await diffHandler.run(
streamDiffLines(
rangeContent,
llm,
input,
getMarkdownLanguageTagForFile(filepath)
)
);
} finally {
vscode.commands.executeCommand(
"setContext",
"continue.streamingDiff",
false
);
}
input = `Original request: ${existingHandler.input}\nUpdated request: ${input}`;
}
await diffHandler.run(
streamDiffLines(
rangeContent,
llm,
input,
getMarkdownLanguageTagForFile(filepath)
)
);
}
export interface VerticalDiffCodeLens {
start: number;
numRed: number;
numGreen: number;
}
export const editorToVerticalDiffCodeLens: Map<string, VerticalDiffCodeLens[]> =
new Map();

View file

@ -0,0 +1,182 @@
import { ConfigHandler } from "core/config/handler";
import { CodebaseIndexer } from "core/indexing/indexCodebase";
import { v4 as uuidv4 } from "uuid";
import * as vscode from "vscode";
import { registerAllCommands } from "../commands";
import { ContinueGUIWebviewViewProvider } from "../debugPanel";
import { DiffManager } from "../diff/horizontal";
import { VerticalPerLineDiffManager } from "../diff/verticalPerLine/manager";
import { VsCodeIde } from "../ideProtocol";
import { registerAllCodeLensProviders } from "../lang-server/codeLens";
import {
ContinueCompletionProvider,
setupStatusBar,
} from "../lang-server/completionProvider";
import { TabAutocompleteModel } from "../util/loadAutocompleteModel";
import { VsCodeWebviewProtocol } from "../webviewProtocol";
export class VsCodeExtension {
private configHandler: ConfigHandler;
private extensionContext: vscode.ExtensionContext;
private ide: VsCodeIde;
private tabAutocompleteModel: TabAutocompleteModel;
private sidebar: ContinueGUIWebviewViewProvider;
private windowId: string;
private indexer: CodebaseIndexer;
private diffManager: DiffManager;
private verticalDiffManager: VerticalPerLineDiffManager;
private webviewProtocol: VsCodeWebviewProtocol;
constructor(context: vscode.ExtensionContext) {
this.diffManager = new DiffManager(context);
this.ide = new VsCodeIde(this.diffManager);
this.configHandler = new ConfigHandler(this.ide);
this.configHandler.reloadConfig();
this.verticalDiffManager = new VerticalPerLineDiffManager(
this.configHandler
);
this.extensionContext = context;
this.tabAutocompleteModel = new TabAutocompleteModel(this.configHandler);
this.windowId = uuidv4();
this.sidebar = new ContinueGUIWebviewViewProvider(
this.configHandler,
this.ide,
this.windowId,
this.extensionContext,
this.verticalDiffManager
);
// Sidebar
context.subscriptions.push(
vscode.window.registerWebviewViewProvider(
"continue.continueGUIView",
this.sidebar,
{
webviewOptions: { retainContextWhenHidden: true },
}
)
);
this.webviewProtocol = this.sidebar.webviewProtocol;
this.diffManager.webviewProtocol = this.webviewProtocol;
this.indexer = new CodebaseIndexer(this.configHandler, this.ide);
// CodeLens
registerAllCodeLensProviders(
context,
this.diffManager,
this.verticalDiffManager.editorToVerticalDiffCodeLens
);
// Tab autocomplete
const config = vscode.workspace.getConfiguration("continue");
const enabled = config.get<boolean>("enableTabAutocomplete");
// Register inline completion provider (odd versions are pre-release)
if (
parseInt(context.extension.packageJSON.version.split(".")[1]) % 2 !==
0
) {
setupStatusBar(enabled);
context.subscriptions.push(
vscode.languages.registerInlineCompletionItemProvider(
[{ pattern: "**" }],
new ContinueCompletionProvider(
this.configHandler,
this.ide,
this.tabAutocompleteModel
)
)
);
}
// Commands
registerAllCommands(
context,
this.ide,
context,
this.sidebar,
this.configHandler,
this.diffManager,
this.verticalDiffManager
);
// Indexing
this.ide.getWorkspaceDirs().then((dirs) => this.refreshCodebaseIndex(dirs));
// Listen for file saving
vscode.workspace.onDidSaveTextDocument((event) => {
const filepath = event.uri.fsPath;
if (
filepath.endsWith(".continue/config.json") ||
filepath.endsWith(".continue\\config.json") ||
filepath.endsWith(".continue/config.ts") ||
filepath.endsWith(".continue\\config.ts") ||
filepath.endsWith(".continuerc.json")
) {
this.configHandler.reloadConfig();
this.tabAutocompleteModel.clearLlm();
} else if (
filepath.endsWith(".continueignore") ||
filepath.endsWith(".gitignore")
) {
// Update embeddings! (TODO)
}
});
// Refresh index when branch is changed
this.ide.getWorkspaceDirs().then((dirs) =>
dirs.forEach(async (dir) => {
const repo = await this.ide.getRepo(vscode.Uri.file(dir));
if (repo) {
repo.state.onDidChange(() => {
// args passed to this callback are always undefined, so keep track of previous branch
const currentBranch = repo?.state?.HEAD?.name;
if (currentBranch) {
if (this.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir]) {
if (
currentBranch !== this.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir]
) {
// Trigger refresh of index only in this directory
this.refreshCodebaseIndex([dir]);
}
}
this.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir] = currentBranch;
}
});
}
})
);
// Register a content provider for the readonly virtual documents
const documentContentProvider = new (class
implements vscode.TextDocumentContentProvider
{
// emitter and its event
onDidChangeEmitter = new vscode.EventEmitter<vscode.Uri>();
onDidChange = this.onDidChangeEmitter.event;
provideTextDocumentContent(uri: vscode.Uri): string {
return uri.query;
}
})();
context.subscriptions.push(
vscode.workspace.registerTextDocumentContentProvider(
VsCodeExtension.continueVirtualDocumentScheme,
documentContentProvider
)
);
}
static continueVirtualDocumentScheme = "continue";
private PREVIOUS_BRANCH_FOR_WORKSPACE_DIR: { [dir: string]: string } = {};
private async refreshCodebaseIndex(dirs: string[]) {
for await (const update of this.indexer.refresh(dirs)) {
this.webviewProtocol.request("indexProgress", update);
}
}
}

View file

@ -2,48 +2,105 @@ import { exec } from "child_process";
import { getContinueGlobalPath } from "core/util/paths";
import * as path from "path";
import * as vscode from "vscode";
import { ideProtocolClient } from "./activation/activate";
import * as child_process from "child_process";
import { Chunk, DiffLine, IDE, Problem } from "core";
import {
BrowserSerializedContinueConfig,
finalToBrowserConfig,
} from "core/config/load";
import { LanceDbIndex } from "core/indexing/LanceDbIndex";
import { IndexTag } from "core/indexing/types";
import { verticalPerLineDiffManager } from "./diff/verticalPerLine/manager";
import { configHandler } from "./loadConfig";
import { ContinueRcJson, IDE, IdeInfo, Problem, Range } from "core";
import { DiffManager } from "./diff/horizontal";
import { VsCodeIdeUtils } from "./util/ideUtils";
import { traverseDirectory } from "./util/traverseDirectory";
import { getExtensionUri, openEditorAndRevealRange } from "./util/vscode";
class VsCodeIde implements IDE {
async getSerializedConfig(): Promise<BrowserSerializedContinueConfig> {
const config = await configHandler.loadConfig();
return finalToBrowserConfig(config);
ideUtils: VsCodeIdeUtils;
constructor(private readonly diffManager: DiffManager) {
this.ideUtils = new VsCodeIdeUtils();
}
getIdeInfo(): Promise<IdeInfo> {
return Promise.resolve({
ideType: "vscode",
name: vscode.env.appName,
version: vscode.version,
remoteName: vscode.env.remoteName || "local",
});
}
readRangeInFile(filepath: string, range: Range): Promise<string> {
return this.ideUtils.readRangeInFile(
filepath,
new vscode.Range(
new vscode.Position(range.start.line, range.start.character),
new vscode.Position(range.end.line, range.end.character)
)
);
}
async getStats(directory: string): Promise<{ [path: string]: number }> {
const files = await this.listWorkspaceContents(directory);
const pathToLastModified: { [path: string]: number } = {};
await Promise.all(
files.map(async (file) => {
let stat = await vscode.workspace.fs.stat(vscode.Uri.file(file));
pathToLastModified[file] = stat.mtime;
})
);
return pathToLastModified;
}
async getRepo(dir: vscode.Uri): Promise<any> {
return this.ideUtils.getRepo(dir);
}
async isTelemetryEnabled(): Promise<boolean> {
return (
(await vscode.workspace
.getConfiguration("continue")
.get("telemetryEnabled")) ?? true
);
}
getUniqueId(): Promise<string> {
return Promise.resolve(vscode.env.machineId);
}
async getDiff(): Promise<string> {
return await ideProtocolClient.getDiff();
return await this.ideUtils.getDiff();
}
async getTerminalContents(): Promise<string> {
return await ideProtocolClient.getTerminalContents(1);
return await this.ideUtils.getTerminalContents(1);
}
async listWorkspaceContents(directory?: string): Promise<string[]> {
if (directory) {
return await ideProtocolClient.getDirectoryContents(directory, true);
return await this.ideUtils.getDirectoryContents(directory, true);
} else {
const contents = await Promise.all(
ideProtocolClient
this.ideUtils
.getWorkspaceDirectories()
.map((dir) => ideProtocolClient.getDirectoryContents(dir, true))
.map((dir) => this.ideUtils.getDirectoryContents(dir, true))
);
return contents.flat();
}
}
async getWorkspaceConfigs() {
const workspaceDirs =
vscode.workspace.workspaceFolders?.map((folder) => folder.uri) || [];
const configs: ContinueRcJson[] = [];
for (const workspaceDir of workspaceDirs) {
const files = await vscode.workspace.fs.readDirectory(workspaceDir);
for (const [filename, type] of files) {
if (type === vscode.FileType.File && filename === ".continuerc.json") {
const contents = await this.ideUtils.readFile(
vscode.Uri.joinPath(workspaceDir, filename).fsPath
);
configs.push(JSON.parse(contents));
}
}
}
return configs;
}
async listFolders(): Promise<string[]> {
const allDirs: string[] = [];
@ -63,7 +120,7 @@ class VsCodeIde implements IDE {
}
async getWorkspaceDirs(): Promise<string[]> {
return ideProtocolClient.getWorkspaceDirectories();
return this.ideUtils.getWorkspaceDirectories();
}
async getContinueDir(): Promise<string> {
@ -78,11 +135,11 @@ class VsCodeIde implements IDE {
}
async showVirtualFile(title: string, contents: string): Promise<void> {
ideProtocolClient.showVirtualFile(title, contents);
this.ideUtils.showVirtualFile(title, contents);
}
async openFile(path: string): Promise<void> {
ideProtocolClient.openFile(path);
this.ideUtils.openFile(path);
}
async showLines(
@ -95,53 +152,44 @@ class VsCodeIde implements IDE {
new vscode.Position(endLine, 0)
);
openEditorAndRevealRange(filepath, range).then(() => {
ideProtocolClient.highlightCode(
{
filepath,
range,
},
"#fff1"
);
// TODO: Highlight lines
// this.ideUtils.highlightCode(
// {
// filepath,
// range,
// },
// "#fff1"
// );
});
}
async runCommand(command: string): Promise<void> {
await ideProtocolClient.runCommand(command);
if (vscode.window.terminals.length) {
vscode.window.terminals[0].show();
vscode.window.terminals[0].sendText(command, false);
} else {
const terminal = vscode.window.createTerminal();
terminal.show();
terminal.sendText(command, false);
}
}
async saveFile(filepath: string): Promise<void> {
await ideProtocolClient.saveFile(filepath);
await this.ideUtils.saveFile(filepath);
}
async readFile(filepath: string): Promise<string> {
return await ideProtocolClient.readFile(filepath);
return await this.ideUtils.readFile(filepath);
}
async showDiff(
filepath: string,
newContents: string,
stepIndex: number
): Promise<void> {
await ideProtocolClient.showDiff(filepath, newContents, stepIndex);
}
async verticalDiffUpdate(
filepath: string,
startLine: number,
endLine: number,
diffLine: DiffLine
) {
const diffHandler =
verticalPerLineDiffManager.getOrCreateVerticalPerLineDiffHandler(
filepath,
startLine,
endLine
);
if (diffHandler) {
await diffHandler.handleDiffLine(diffLine);
}
await this.diffManager.writeDiff(filepath, newContents, stepIndex);
}
async getOpenFiles(): Promise<string[]> {
return await ideProtocolClient.getOpenFiles();
return await this.ideUtils.getOpenFiles();
}
async getPinnedFiles(): Promise<string[]> {
@ -227,48 +275,7 @@ class VsCodeIde implements IDE {
}
async getBranch(dir: string): Promise<string> {
return ideProtocolClient.getBranch(vscode.Uri.file(dir));
}
async getFilesToEmbed(
providerId: string
): Promise<[string, string, string][]> {
return [];
}
async sendEmbeddingForChunk(
chunk: Chunk,
embedding: number[],
tags: string[]
) {}
async retrieveChunks(
text: string,
n: number,
directory: string | undefined
): Promise<Chunk[]> {
const embeddingsProvider = (await configHandler.loadConfig())
.embeddingsProvider;
if (!embeddingsProvider) {
return [];
}
const lanceDbIndex = new LanceDbIndex(embeddingsProvider, (path) =>
ideProtocolClient.readFile(path)
);
const tags = await Promise.all(
(await this.getWorkspaceDirs()).map(async (dir) => {
let branch = await ideProtocolClient.getBranch(vscode.Uri.file(dir));
let tag: IndexTag = {
directory: dir,
branch,
artifactId: lanceDbIndex.artifactId,
};
return tag;
})
);
let chunks = await lanceDbIndex.retrieve(tags, text, n, directory);
return chunks as any[];
return this.ideUtils.getBranch(vscode.Uri.file(dir));
}
}

View file

@ -0,0 +1,31 @@
import { IDE } from "core";
import { AutocompleteSnippet } from "core/autocomplete/constructPrompt";
import * as vscode from "vscode";
export class AutocompletePromptBuilder {
constructor(private readonly ide: IDE) {}
async getDefinition(
uri: string,
line: number,
character: number
): Promise<AutocompleteSnippet | undefined> {
const definitions = (await vscode.commands.executeCommand(
"vscode.executeDefinitionProvider",
vscode.Uri.parse(uri),
new vscode.Position(line, character)
)) as any;
if (definitions[0]?.targetRange) {
return {
filepath: uri,
content: await this.ide.readRangeInFile(
definitions[0].targetUri.fsPath,
definitions[0].targetRange
),
};
}
return undefined;
}
}

View file

@ -1,19 +1,26 @@
import * as os from "os";
import * as path from "path";
import * as vscode from "vscode";
import { DIFF_DIRECTORY, diffManager } from "../diff/horizontal";
import { editorToVerticalDiffCodeLens } from "../diff/verticalPerLine/manager";
import { DIFF_DIRECTORY, DiffManager } from "../diff/horizontal";
import { VerticalDiffCodeLens } from "../diff/verticalPerLine/manager";
import { editorSuggestionsLocked, editorToSuggestions } from "../suggestions";
import { getMetaKeyLabel } from "../util/util";
import { getExtensionUri } from "../util/vscode";
class VerticalPerLineCodeLensProvider implements vscode.CodeLensProvider {
constructor(
private readonly editorToVerticalDiffCodeLens: Map<
string,
VerticalDiffCodeLens[]
>
) {}
public provideCodeLenses(
document: vscode.TextDocument,
_: vscode.CancellationToken
): vscode.CodeLens[] | Thenable<vscode.CodeLens[]> {
const filepath = document.uri.fsPath;
const blocks = editorToVerticalDiffCodeLens.get(filepath);
const blocks = this.editorToVerticalDiffCodeLens.get(filepath);
if (!blocks) {
return [];
}
@ -28,12 +35,12 @@ class VerticalPerLineCodeLensProvider implements vscode.CodeLensProvider {
);
codeLenses.push(
new vscode.CodeLens(range, {
title: "Accept ✅",
title: "Accept",
command: "continue.acceptVerticalDiffBlock",
arguments: [filepath, i],
}),
new vscode.CodeLens(range, {
title: "Reject ❌",
title: "Reject",
command: "continue.rejectVerticalDiffBlock",
arguments: [filepath, i],
})
@ -41,7 +48,7 @@ class VerticalPerLineCodeLensProvider implements vscode.CodeLensProvider {
if (codeLenses.length === 2) {
codeLenses.push(
new vscode.CodeLens(range, {
title: `(${getMetaKeyLabel()}⇧↩/${getMetaKeyLabel()}⇧⌫ to accept/reject all, ${getMetaKeyLabel()}⇧L to retry)`,
title: `(${getMetaKeyLabel()}⇧↩/${getMetaKeyLabel()}⇧⌫ to accept/reject all, ${getMetaKeyLabel()}I to retry)`,
command: "",
})
);
@ -71,12 +78,12 @@ class SuggestionsCodeLensProvider implements vscode.CodeLensProvider {
);
codeLenses.push(
new vscode.CodeLens(range, {
title: "Accept ✅",
title: "Accept",
command: "continue.acceptSuggestion",
arguments: [suggestion],
}),
new vscode.CodeLens(range, {
title: "Reject ❌",
title: "Reject",
command: "continue.rejectSuggestion",
arguments: [suggestion],
})
@ -96,6 +103,12 @@ class SuggestionsCodeLensProvider implements vscode.CodeLensProvider {
}
class DiffViewerCodeLensProvider implements vscode.CodeLensProvider {
diffManager: DiffManager;
constructor(diffManager: DiffManager) {
this.diffManager = diffManager;
}
public provideCodeLenses(
document: vscode.TextDocument,
_: vscode.CancellationToken
@ -103,7 +116,7 @@ class DiffViewerCodeLensProvider implements vscode.CodeLensProvider {
if (path.dirname(document.uri.fsPath) === DIFF_DIRECTORY) {
const codeLenses: vscode.CodeLens[] = [];
let range = new vscode.Range(0, 0, 1, 0);
const diffInfo = diffManager.diffAtNewFilepath(document.uri.fsPath);
const diffInfo = this.diffManager.diffAtNewFilepath(document.uri.fsPath);
if (diffInfo) {
range = diffInfo.range;
}
@ -334,7 +347,11 @@ let suggestionsCodeLensDisposable: vscode.Disposable | undefined = undefined;
let configPyCodeLensDisposable: vscode.Disposable | undefined = undefined;
let tutorialCodeLensDisposable: vscode.Disposable | undefined = undefined;
export function registerAllCodeLensProviders(context: vscode.ExtensionContext) {
export function registerAllCodeLensProviders(
context: vscode.ExtensionContext,
diffManager: DiffManager,
editorToVerticalDiffCodeLens: Map<string, VerticalDiffCodeLens[]>
) {
if (verticalPerLineCodeLensProvider) {
verticalPerLineCodeLensProvider.dispose();
}
@ -353,7 +370,7 @@ export function registerAllCodeLensProviders(context: vscode.ExtensionContext) {
verticalPerLineCodeLensProvider = vscode.languages.registerCodeLensProvider(
"*",
new VerticalPerLineCodeLensProvider()
new VerticalPerLineCodeLensProvider(editorToVerticalDiffCodeLens)
);
suggestionsCodeLensDisposable = vscode.languages.registerCodeLensProvider(
"*",
@ -361,7 +378,7 @@ export function registerAllCodeLensProviders(context: vscode.ExtensionContext) {
);
diffsCodeLensDisposable = vscode.languages.registerCodeLensProvider(
"*",
new DiffViewerCodeLensProvider()
new DiffViewerCodeLensProvider(diffManager)
);
configPyCodeLensDisposable = vscode.languages.registerCodeLensProvider(
"*",

View file

@ -1,8 +1,7 @@
import { TabAutocompleteOptions } from "core";
import { IDE, TabAutocompleteOptions } from "core";
import { AutocompleteLruCache } from "core/autocomplete/cache";
import { onlyWhitespaceAfterEndOfLine } from "core/autocomplete/charStream";
import {
AutocompleteSnippet,
constructAutocompletePrompt,
languageForFilepath,
} from "core/autocomplete/constructPrompt";
@ -12,13 +11,15 @@ import {
} from "core/autocomplete/lineStream";
import { DEFAULT_AUTOCOMPLETE_OPTS } from "core/autocomplete/parameters";
import { getTemplateForModel } from "core/autocomplete/templates";
import { ConfigHandler } from "core/config/handler";
import { streamLines } from "core/diff/util";
import OpenAI from "core/llm/llms/OpenAI";
import { logDevData } from "core/util/devdata";
import Handlebars from "handlebars";
import { v4 as uuidv4 } from "uuid";
import * as vscode from "vscode";
import { ideProtocolClient } from "../activation/activate";
import { TabAutocompleteModel, configHandler } from "../loadConfig";
import { TabAutocompleteModel } from "../util/loadAutocompleteModel";
import { AutocompletePromptBuilder } from "./autocompletePromptBuilder";
const statusBarItemText = (enabled: boolean | undefined) =>
enabled ? "$(check) Continue" : "$(circle-slash) Continue";
@ -70,30 +71,6 @@ export function setupStatusBar(
});
}
async function getDefinition(
uri: string,
line: number,
character: number
): Promise<AutocompleteSnippet | undefined> {
const definitions = (await vscode.commands.executeCommand(
"vscode.executeDefinitionProvider",
vscode.Uri.parse(uri),
new vscode.Position(line, character)
)) as any;
if (definitions[0]?.targetRange) {
return {
filepath: uri,
content: await ideProtocolClient.readRangeInFile(
definitions[0].targetUri.fsPath,
definitions[0].targetRange
),
};
}
return undefined;
}
export interface AutocompleteOutcome {
accepted?: boolean;
time: number;
@ -234,158 +211,6 @@ class GeneratorReuseManager {
}
}
async function getTabCompletion(
document: vscode.TextDocument,
pos: vscode.Position,
token: vscode.CancellationToken,
options: TabAutocompleteOptions
): Promise<AutocompleteOutcome | undefined> {
const startTime = Date.now();
// Filter
const lang = languageForFilepath(document.fileName);
const line = document.lineAt(pos).text;
for (const endOfLine of lang.endOfLine) {
if (line.endsWith(endOfLine) && pos.character >= endOfLine.length) {
return undefined;
}
}
try {
// Model
const llm = await TabAutocompleteModel.get();
if (llm instanceof OpenAI) {
llm.useLegacyCompletionsEndpoint = true;
}
if (!llm) return;
// Prompt
const fullPrefix = document.getText(
new vscode.Range(new vscode.Position(0, 0), pos)
);
const fullSuffix = document.getText(
new vscode.Range(
pos,
new vscode.Position(document.lineCount, Number.MAX_SAFE_INTEGER)
)
);
const lineBelowCursor = document.lineAt(
Math.min(pos.line + 1, document.lineCount - 1)
).text;
const clipboardText = await vscode.env.clipboard.readText();
const { prefix, suffix, completeMultiline } =
await constructAutocompletePrompt(
document.uri.toString(),
fullPrefix,
fullSuffix,
clipboardText,
lang,
getDefinition,
options
);
const { template, completionOptions } = options.template
? { template: options.template, completionOptions: {} }
: getTemplateForModel(llm.model);
const compiledTemplate = Handlebars.compile(template);
const prompt = compiledTemplate({ prefix, suffix });
// Completion
let completion = "";
const cache = await autocompleteCache;
const cachedCompletion = await cache.get(prompt);
let cacheHit = false;
if (cachedCompletion) {
// Cache
cacheHit = true;
completion = cachedCompletion;
} else {
setupStatusBar(true, true);
// Try to reuse pending requests if what the user typed matches start of completion
let stop = [
...(completionOptions?.stop || []),
"\n\n",
"```",
...lang.stopWords,
];
if (options.disableMultiLineCompletions || !completeMultiline) {
stop.unshift("\n");
}
let generator = GeneratorReuseManager.getGenerator(prefix, () =>
llm.streamComplete(prompt, {
...completionOptions,
temperature: 0,
raw: true,
stop,
})
);
// LLM
let cancelled = false;
const generatorWithCancellation = async function* () {
for await (const update of generator) {
if (token.isCancellationRequested) {
stopStatusBarLoading();
cancelled = true;
return undefined;
}
yield update;
}
};
const gen2 = onlyWhitespaceAfterEndOfLine(
generatorWithCancellation(),
lang.endOfLine
);
const lineGenerator = streamWithNewLines(streamLines(gen2));
const finalGenerator = stopAtSimilarLine(lineGenerator, lineBelowCursor);
for await (const update of finalGenerator) {
completion += update;
}
if (cancelled) {
return undefined;
}
// Don't return empty
if (completion.trim().length <= 0) {
return undefined;
}
// Post-processing
completion = completion.trimEnd();
}
const time = Date.now() - startTime;
return {
time,
completion,
prompt,
modelProvider: llm.providerName,
modelName: llm.model,
completionOptions,
cacheHit,
};
} catch (e: any) {
console.warn("Error generating autocompletion: ", e);
if (!ContinueCompletionProvider.errorsShown.has(e.message)) {
ContinueCompletionProvider.errorsShown.add(e.message);
vscode.window.showErrorMessage(e.message, "Documentation").then((val) => {
if (val === "Documentation") {
vscode.env.openExternal(
vscode.Uri.parse(
"https://continue.dev/docs/walkthroughs/tab-autocomplete"
)
);
}
});
}
return undefined;
}
}
export class ContinueCompletionProvider
implements vscode.InlineCompletionItemProvider
{
@ -395,6 +220,174 @@ export class ContinueCompletionProvider
public static errorsShown: Set<string> = new Set();
private readonly promptBuilder: AutocompletePromptBuilder;
constructor(
private readonly configHandler: ConfigHandler,
private readonly ide: IDE,
private readonly tabAutocompleteModel: TabAutocompleteModel
) {
this.promptBuilder = new AutocompletePromptBuilder(ide);
}
async getTabCompletion(
document: vscode.TextDocument,
pos: vscode.Position,
token: vscode.CancellationToken,
options: TabAutocompleteOptions
): Promise<AutocompleteOutcome | undefined> {
const startTime = Date.now();
// Filter
const lang = languageForFilepath(document.fileName);
const line = document.lineAt(pos).text;
for (const endOfLine of lang.endOfLine) {
if (line.endsWith(endOfLine) && pos.character >= endOfLine.length) {
return undefined;
}
}
try {
// Model
const llm = await this.tabAutocompleteModel.get();
if (llm instanceof OpenAI) {
llm.useLegacyCompletionsEndpoint = true;
}
if (!llm) return;
// Prompt
const fullPrefix = document.getText(
new vscode.Range(new vscode.Position(0, 0), pos)
);
const fullSuffix = document.getText(
new vscode.Range(
pos,
new vscode.Position(document.lineCount, Number.MAX_SAFE_INTEGER)
)
);
const lineBelowCursor = document.lineAt(
Math.min(pos.line + 1, document.lineCount - 1)
).text;
const clipboardText = await vscode.env.clipboard.readText();
const { prefix, suffix, completeMultiline } =
await constructAutocompletePrompt(
document.uri.toString(),
fullPrefix,
fullSuffix,
clipboardText,
lang,
this.promptBuilder.getDefinition.bind(this.promptBuilder),
options,
llm.model
);
const { template, completionOptions } = options.template
? { template: options.template, completionOptions: {} }
: getTemplateForModel(llm.model);
const compiledTemplate = Handlebars.compile(template);
const prompt = compiledTemplate({ prefix, suffix });
// Completion
let completion = "";
const cache = await autocompleteCache;
const cachedCompletion = await cache.get(prompt);
let cacheHit = false;
if (cachedCompletion) {
// Cache
cacheHit = true;
completion = cachedCompletion;
} else {
setupStatusBar(true, true);
// Try to reuse pending requests if what the user typed matches start of completion
let stop = [
...(completionOptions?.stop || []),
"\n\n",
"```",
...lang.stopWords,
];
if (options.disableMultiLineCompletions || !completeMultiline) {
stop.unshift("\n");
}
let generator = GeneratorReuseManager.getGenerator(prefix, () =>
llm.streamComplete(prompt, {
...completionOptions,
temperature: 0,
raw: true,
stop,
})
);
// LLM
let cancelled = false;
const generatorWithCancellation = async function* () {
for await (const update of generator) {
if (token.isCancellationRequested) {
stopStatusBarLoading();
cancelled = true;
return undefined;
}
yield update;
}
};
const gen2 = onlyWhitespaceAfterEndOfLine(
generatorWithCancellation(),
lang.endOfLine
);
const lineGenerator = streamWithNewLines(streamLines(gen2));
const finalGenerator = stopAtSimilarLine(
lineGenerator,
lineBelowCursor
);
for await (const update of finalGenerator) {
completion += update;
}
if (cancelled) {
return undefined;
}
// Don't return empty
if (completion.trim().length <= 0) {
return undefined;
}
// Post-processing
completion = completion.trimEnd();
}
const time = Date.now() - startTime;
return {
time,
completion,
prompt,
modelProvider: llm.providerName,
modelName: llm.model,
completionOptions,
cacheHit,
};
} catch (e: any) {
console.warn("Error generating autocompletion: ", e);
if (!ContinueCompletionProvider.errorsShown.has(e.message)) {
ContinueCompletionProvider.errorsShown.add(e.message);
vscode.window
.showErrorMessage(e.message, "Documentation")
.then((val) => {
if (val === "Documentation") {
vscode.env.openExternal(
vscode.Uri.parse(
"https://continue.dev/docs/walkthroughs/tab-autocomplete"
)
);
}
});
}
return undefined;
}
}
public async provideInlineCompletionItems(
document: vscode.TextDocument,
position: vscode.Position,
@ -406,7 +399,7 @@ export class ContinueCompletionProvider
const uuid = uuidv4();
ContinueCompletionProvider.lastUUID = uuid;
const config = await configHandler.loadConfig();
const config = await this.configHandler.loadConfig();
const options = {
...config.tabAutocompleteOptions,
...DEFAULT_AUTOCOMPLETE_OPTS,
@ -438,7 +431,7 @@ export class ContinueCompletionProvider
}
try {
const outcome = await getTabCompletion(
const outcome = await this.getTabCompletion(
document,
position,
token,
@ -460,7 +453,7 @@ export class ContinueCompletionProvider
const logRejectionTimeout = setTimeout(() => {
// Wait 10 seconds, then assume it wasn't accepted
outcome.accepted = false;
ideProtocolClient.logDevData("autocomplete", outcome);
logDevData("autocomplete", outcome);
}, 10_000);
return [

View file

@ -1,323 +0,0 @@
import { ContinueConfig, ContinueRcJson, ILLM } from "core";
import defaultConfig from "core/config/default";
import {
finalToBrowserConfig,
intermediateToFinalConfig,
loadFullConfigNode,
serializedToIntermediateConfig,
} from "core/config/load";
import Ollama from "core/llm/llms/Ollama";
import { getConfigJsonPath } from "core/util/paths";
import { Telemetry } from "core/util/posthog";
import { http, https } from "follow-redirects";
import * as fs from "fs";
import { HttpProxyAgent } from "http-proxy-agent";
import { HttpsProxyAgent } from "https-proxy-agent";
import fetch from "node-fetch";
import * as vscode from "vscode";
import { ideProtocolClient } from "./activation/activate";
import { debugPanelWebview, webviewRequest } from "./debugPanel";
import { getUniqueId } from "./util/vscode";
const tls = require("tls");
const outputChannel = vscode.window.createOutputChannel(
"Continue - LLM Prompt/Completion"
);
class VsCodeConfigHandler {
savedConfig: ContinueConfig | undefined;
reloadConfig() {
this.savedConfig = undefined;
this.loadConfig();
}
private async _getWorkspaceConfigs() {
const workspaceDirs =
vscode.workspace.workspaceFolders?.map((folder) => folder.uri) || [];
const configs: ContinueRcJson[] = [];
for (const workspaceDir of workspaceDirs) {
const files = await vscode.workspace.fs.readDirectory(workspaceDir);
for (const [filename, type] of files) {
if (type === vscode.FileType.File && filename === ".continuerc.json") {
const contents = await ideProtocolClient.readFile(
vscode.Uri.joinPath(workspaceDir, filename).fsPath
);
configs.push(JSON.parse(contents));
}
}
}
return configs;
}
async loadConfig(): Promise<ContinueConfig> {
try {
if (this.savedConfig) {
return this.savedConfig;
}
let workspaceConfigs: ContinueRcJson[] = [];
try {
workspaceConfigs = await this._getWorkspaceConfigs();
} catch (e) {
console.warn("Failed to load workspace configs");
}
const remoteConfigServerUrl = vscode.workspace
.getConfiguration("continue")
.get<string | undefined>("remoteConfigServerUrl", undefined);
this.savedConfig = await loadFullConfigNode(
ideProtocolClient.readFile,
workspaceConfigs,
remoteConfigServerUrl ? new URL(remoteConfigServerUrl) : undefined
);
this.savedConfig.allowAnonymousTelemetry =
this.savedConfig.allowAnonymousTelemetry &&
vscode.workspace.getConfiguration("continue").get("telemetryEnabled");
// Update the sidebar panel
const browserConfig = finalToBrowserConfig(this.savedConfig);
debugPanelWebview?.postMessage({ type: "configUpdate", browserConfig });
// Setup telemetry only after (and if) we know it is enabled
await Telemetry.setup(
this.savedConfig.allowAnonymousTelemetry ?? true,
getUniqueId()
);
return this.savedConfig;
} catch (e) {
vscode.window
.showErrorMessage(
"Error loading config.json. Please check your config.json file: " + e,
"Open config.json"
)
.then((selection) => {
if (selection === "Open config.json") {
vscode.workspace
.openTextDocument(getConfigJsonPath())
.then((doc) => {
vscode.window.showTextDocument(doc);
});
}
});
return intermediateToFinalConfig(
serializedToIntermediateConfig(defaultConfig),
ideProtocolClient.readFile
);
}
}
}
export const configHandler = new VsCodeConfigHandler();
const TIMEOUT = 7200; // 7200 seconds = 2 hours
function setupLlm(llm: ILLM): ILLM {
// Since we know this is happening in Node.js, we can add requestOptions through a custom agent
const ca = [...tls.rootCertificates];
const customCerts =
typeof llm.requestOptions?.caBundlePath === "string"
? [llm.requestOptions?.caBundlePath]
: llm.requestOptions?.caBundlePath;
if (customCerts) {
ca.push(
...customCerts.map((customCert) => fs.readFileSync(customCert, "utf8"))
);
}
let timeout = (llm.requestOptions?.timeout || TIMEOUT) * 1000; // measured in ms
const agentOptions = {
ca,
rejectUnauthorized: llm.requestOptions?.verifySsl,
timeout,
sessionTimeout: timeout,
keepAlive: true,
keepAliveMsecs: timeout,
};
const proxy = llm.requestOptions?.proxy;
llm._fetch = async (input, init) => {
// Create agent
const protocol = new URL(input).protocol === "https:" ? https : http;
const agent = proxy
? new URL(input).protocol === "https:"
? new HttpsProxyAgent(proxy, agentOptions)
: new HttpProxyAgent(proxy, agentOptions)
: new protocol.Agent(agentOptions);
const headers: { [key: string]: string } =
llm!.requestOptions?.headers || {};
for (const [key, value] of Object.entries(init?.headers || {})) {
headers[key] = value as string;
}
let updatedBody: string | undefined = undefined;
try {
if (
llm.requestOptions?.extraBodyProperties &&
typeof init.body === "string"
) {
const parsedBody = JSON.parse(init.body);
updatedBody = JSON.stringify({
...parsedBody,
...llm.requestOptions.extraBodyProperties,
});
}
} catch (e) {
console.log("Unable to parse HTTP request body: ", e);
}
const resp = await fetch(input, {
...init,
body: updatedBody ?? init.body,
headers,
agent,
});
if (!resp.ok) {
let text = await resp.text();
if (resp.status === 404 && !resp.url.includes("/v1")) {
if (text.includes("try pulling it first")) {
const model = JSON.parse(text).error.split(" ")[1].slice(1, -1);
text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`;
} else if (text.includes("/api/chat")) {
text =
"The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue.";
} else {
text =
"This may mean that you forgot to add '/v1' to the end of your 'apiBase' in config.json.";
}
}
throw new Error(
`HTTP ${resp.status} ${resp.statusText} from ${resp.url}\n\n${text}`
);
}
return resp;
};
llm.writeLog = async (log: string) => {
outputChannel.appendLine(
"=========================================================================="
);
outputChannel.appendLine(
"=========================================================================="
);
outputChannel.append(log);
};
return llm;
}
export async function llmFromTitle(title?: string): Promise<ILLM> {
let config = await configHandler.loadConfig();
if (title === undefined) {
const resp = await webviewRequest("getDefaultModelTitle");
if (resp?.defaultModelTitle) {
title = resp.defaultModelTitle;
}
}
let llm = title
? config.models.find((llm) => llm.title === title)
: config.models[0];
if (!llm) {
// Try to reload config
configHandler.reloadConfig();
config = await configHandler.loadConfig();
llm = config.models.find((llm) => llm.title === title);
if (!llm) {
throw new Error(`Unknown model ${title}`);
}
}
return setupLlm(llm);
}
export class TabAutocompleteModel {
private static _llm: ILLM | undefined;
private static defaultTag: string = "deepseek-coder:1.3b-base";
private static shownOllamaWarning: boolean = false;
private static shownDeepseekWarning: boolean = false;
static clearLlm() {
TabAutocompleteModel._llm = undefined;
}
static async getDefaultTabAutocompleteModel() {
const llm = new Ollama({
model: TabAutocompleteModel.defaultTag,
});
// Check that deepseek is already downloaded
try {
const models = await llm.listModels();
if (!models.includes(TabAutocompleteModel.defaultTag)) {
// Raise warning and explain how to download
if (!TabAutocompleteModel.shownDeepseekWarning) {
vscode.window
.showWarningMessage(
`Your local Ollama instance doesn't yet have DeepSeek Coder. To download this model, run \`ollama run deepseek-coder:1.3b-base\` (recommended). If you'd like to use a custom model for tab autocomplete, learn more in the docs`,
"Documentation",
"Copy Command"
)
.then((value) => {
if (value === "Documentation") {
vscode.env.openExternal(
vscode.Uri.parse(
"https://continue.dev/docs/walkthroughs/tab-autocomplete"
)
);
} else if (value === "Copy Command") {
vscode.env.clipboard.writeText(
"ollama run deepseek-coder:1.3b-base"
);
}
});
TabAutocompleteModel.shownDeepseekWarning = true;
}
return undefined;
}
} catch (e) {
if (!TabAutocompleteModel.shownOllamaWarning) {
vscode.window
.showWarningMessage(
"Continue failed to connect to Ollama, which is used by default for tab-autocomplete. If you haven't downloaded it yet, you can do so at https://ollama.ai (recommended). If you'd like to use a custom model for tab autocomplete, learn more in the docs",
"Documentation"
)
.then((value) => {
if (value === "Documentation") {
vscode.env.openExternal(
vscode.Uri.parse(
"https://continue.dev/docs/walkthroughs/tab-autocomplete"
)
);
}
});
TabAutocompleteModel.shownOllamaWarning = true;
}
return undefined;
}
return llm;
}
static async get() {
if (!TabAutocompleteModel._llm) {
const config = await configHandler.loadConfig();
if (config.tabAutocompleteModel) {
TabAutocompleteModel._llm = setupLlm(config.tabAutocompleteModel);
} else {
TabAutocompleteModel._llm =
await TabAutocompleteModel.getDefaultTabAutocompleteModel();
}
}
return TabAutocompleteModel._llm;
}
}

View file

@ -1,8 +1,5 @@
import * as vscode from "vscode";
import { openEditorAndRevealRange } from "./util/vscode";
import { translate } from "./util/vscode";
import { registerAllCodeLensProviders } from "./lang-server/codeLens";
import { extensionContext, ideProtocolClient } from "./activation/activate";
import { openEditorAndRevealRange, translate } from "./util/vscode";
export interface SuggestionRanges {
oldRange: vscode.Range;
@ -125,9 +122,9 @@ export function rerenderDecorations(editorUri: string) {
vscode.TextEditorRevealType.Default
);
if (extensionContext) {
registerAllCodeLensProviders(extensionContext);
}
// if (extensionContext) {
// registerAllCodeLensProviders(extensionContext);
// }
}
export function suggestionDownCommand() {

View file

@ -1,104 +1,24 @@
import { FileEdit, RangeInFile } from "core";
import { getDevDataFilePath } from "core/util/paths";
import { writeFileSync } from "fs";
import * as path from "path";
import path from "path";
import * as vscode from "vscode";
import { extensionContext } from "./activation/activate";
import { debugPanelWebview, getSidebarContent } from "./debugPanel";
import { diffManager } from "./diff/horizontal";
import { TabAutocompleteModel, configHandler } from "./loadConfig";
import { VsCodeExtension } from "../extension/vscodeExtension";
import {
SuggestionRanges,
acceptSuggestionCommand,
editorSuggestionsLocked,
rejectSuggestionCommand,
showSuggestion as showSuggestionInEditor,
} from "./suggestions";
import { vsCodeIndexCodebase } from "./util/indexCodebase";
import { defaultIgnoreFile, traverseDirectory } from "./util/traverseDirectory";
} from "../suggestions";
import { defaultIgnoreFile, traverseDirectory } from "./traverseDirectory";
import {
getUniqueId,
openEditorAndRevealRange,
uriFromFilePath,
} from "./util/vscode";
} from "./vscode";
const util = require("util");
const exec = util.promisify(require("child_process").exec);
const continueVirtualDocumentScheme = "continue";
class IdeProtocolClient {
private static PREVIOUS_BRANCH_FOR_WORKSPACE_DIR: { [dir: string]: string } =
{};
constructor(context: vscode.ExtensionContext) {
// Listen for file saving
vscode.workspace.onDidSaveTextDocument((event) => {
const filepath = event.uri.fsPath;
if (
filepath.endsWith(".continue/config.json") ||
filepath.endsWith(".continue\\config.json") ||
filepath.endsWith(".continue/config.ts") ||
filepath.endsWith(".continue\\config.ts") ||
filepath.endsWith(".continuerc.json")
) {
configHandler.reloadConfig();
TabAutocompleteModel.clearLlm();
} else if (
filepath.endsWith(".continueignore") ||
filepath.endsWith(".gitignore")
) {
debugPanelWebview?.postMessage({
type: "updateEmbeddings",
});
}
});
// Refresh index when branch is changed
this.getWorkspaceDirectories().forEach(async (dir) => {
const repo = await this.getRepo(vscode.Uri.file(dir));
if (repo) {
repo.state.onDidChange(() => {
// args passed to this callback are always undefined, so keep track of previous branch
const currentBranch = repo?.state?.HEAD?.name;
if (currentBranch) {
if (IdeProtocolClient.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir]) {
if (
currentBranch !==
IdeProtocolClient.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir]
) {
// Trigger refresh of index only in this directory
vsCodeIndexCodebase([dir]);
}
}
IdeProtocolClient.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir] =
currentBranch;
}
});
}
});
// Register a content provider for the readonly virtual documents
const documentContentProvider = new (class
implements vscode.TextDocumentContentProvider
{
// emitter and its event
onDidChangeEmitter = new vscode.EventEmitter<vscode.Uri>();
onDidChange = this.onDidChangeEmitter.event;
provideTextDocumentContent(uri: vscode.Uri): string {
return uri.query;
}
})();
context.subscriptions.push(
vscode.workspace.registerTextDocumentContentProvider(
continueVirtualDocumentScheme,
documentContentProvider
)
);
}
const asyncExec = util.promisify(require("child_process").exec);
export class VsCodeIdeUtils {
visibleMessages: Set<string> = new Set();
async gotoDefinition(
@ -207,10 +127,6 @@ class IdeProtocolClient {
);
}
async showDiff(filepath: string, replacement: string, step_index: number) {
await diffManager.writeDiff(filepath, replacement, step_index);
}
showMultiFileEdit(edits: FileEdit[]) {
vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar");
const panel = vscode.window.createWebviewPanel(
@ -218,12 +134,13 @@ class IdeProtocolClient {
"Continue",
vscode.ViewColumn.One
);
panel.webview.html = getSidebarContent(
extensionContext,
panel,
"/monaco",
edits
);
// panel.webview.html = this.sidebar.getSidebarContent(
// extensionContext,
// panel,
// this.ide,
// "/monaco",
// edits
// );
}
openFile(filepath: string, range?: vscode.Range) {
@ -244,9 +161,9 @@ class IdeProtocolClient {
vscode.workspace
.openTextDocument(
vscode.Uri.parse(
`${continueVirtualDocumentScheme}:${encodeURIComponent(
name
)}?${encodeURIComponent(contents)}`
`${
VsCodeExtension.continueVirtualDocumentScheme
}:${encodeURIComponent(name)}?${encodeURIComponent(contents)}`
)
)
.then((doc) => {
@ -480,7 +397,7 @@ class IdeProtocolClient {
let repo = await this.getRepo(forDirectory);
if (repo?.state?.HEAD?.name === undefined) {
try {
const { stdout } = await exec("git rev-parse --abbrev-ref HEAD", {
const { stdout } = await asyncExec("git rev-parse --abbrev-ref HEAD", {
cwd: forDirectory.fsPath,
});
return stdout?.trim() || "NONE";
@ -533,30 +450,4 @@ class IdeProtocolClient {
});
return rangeInFiles;
}
async runCommand(command: string) {
if (vscode.window.terminals.length) {
vscode.window.terminals[0].show();
vscode.window.terminals[0].sendText(command, false);
} else {
const terminal = vscode.window.createTerminal();
terminal.show();
terminal.sendText(command, false);
}
}
sendMainUserInput(input: string) {
debugPanelWebview?.postMessage({
type: "userInput",
input,
});
}
logDevData(tableName: string, data: any) {
const filepath: string = getDevDataFilePath(tableName);
const jsonLine = JSON.stringify(data);
writeFileSync(filepath, `${jsonLine}\n`, { flag: "a" });
}
}
export default IdeProtocolClient;

View file

@ -1,100 +0,0 @@
import { FullTextSearchCodebaseIndex } from "core/indexing/FullTextSearch";
import { LanceDbIndex } from "core/indexing/LanceDbIndex";
import { ChunkCodebaseIndex } from "core/indexing/chunk/ChunkCodebaseIndex";
import { getComputeDeleteAddRemove } from "core/indexing/refreshIndex";
import { CodebaseIndex, IndexTag, LastModifiedMap } from "core/indexing/types";
import * as vscode from "vscode";
import { ideProtocolClient } from "../activation/activate";
import { debugPanelWebview } from "../debugPanel";
import { VsCodeIde } from "../ideProtocol";
import { configHandler } from "../loadConfig";
const vscodeGetStats = async (
directory: string | undefined
): Promise<LastModifiedMap> => {
const files = await new VsCodeIde().listWorkspaceContents(directory);
const pathToLastModified: { [path: string]: number } = {};
await Promise.all(
files.map(async (file) => {
let stat = await vscode.workspace.fs.stat(vscode.Uri.file(file));
pathToLastModified[file] = stat.mtime;
})
);
return pathToLastModified;
};
async function getIndexesToBuild(): Promise<CodebaseIndex[]> {
const ide = new VsCodeIde();
const config = await configHandler.loadConfig();
const indexes = [
new ChunkCodebaseIndex(ide.readFile), // Chunking must come first
new LanceDbIndex(config.embeddingsProvider, ide.readFile),
new FullTextSearchCodebaseIndex(),
];
return indexes;
}
export async function vsCodeIndexCodebase(workspaceDirs: string[]) {
const update = (progress: number, desc: string) => {
debugPanelWebview?.postMessage({ type: "indexProgress", progress, desc });
};
const config = await configHandler.loadConfig();
if (config.disableIndexing) {
return;
}
const indexesToBuild = await getIndexesToBuild();
let completedDirs = 0;
for (let directory of workspaceDirs) {
const stats = await vscodeGetStats(directory);
const branch = await ideProtocolClient.getBranch(
vscode.Uri.file(directory)
);
let completedIndexes = 0;
try {
for (let codebaseIndex of indexesToBuild) {
const tag: IndexTag = {
directory,
branch,
artifactId: codebaseIndex.artifactId,
};
const [results, markComplete] = await getComputeDeleteAddRemove(
tag,
{ ...stats },
(filepath) => ideProtocolClient.readFile(filepath)
);
for await (let { progress, desc } of codebaseIndex.update(
tag,
results,
markComplete
)) {
update(
(completedDirs +
(completedIndexes + progress) / indexesToBuild.length) /
workspaceDirs.length,
desc
);
}
completedIndexes++;
update(
(completedDirs + completedIndexes / indexesToBuild.length) /
workspaceDirs.length,
"Completed indexing " + codebaseIndex.artifactId
);
}
} catch (e) {
console.warn("Error refreshing index: ", e);
}
completedDirs++;
update(completedDirs / workspaceDirs.length, "Indexing Complete");
}
}

View file

@ -0,0 +1,90 @@
import { ILLM } from "core";
import { ConfigHandler } from "core/config/handler";
import Ollama from "core/llm/llms/Ollama";
import * as vscode from "vscode";
export class TabAutocompleteModel {
private _llm: ILLM | undefined;
private defaultTag: string = "starcoder:3b";
private defaultTagName: string = "Starcoder 3b";
private shownOllamaWarning: boolean = false;
private shownDeepseekWarning: boolean = false;
private configHandler: ConfigHandler;
constructor(configHandler: ConfigHandler) {
this.configHandler = configHandler;
}
clearLlm() {
this._llm = undefined;
}
async getDefaultTabAutocompleteModel() {
const llm = new Ollama({
model: this.defaultTag,
});
try {
const models = await llm.listModels();
if (!models.includes(this.defaultTag)) {
if (!this.shownDeepseekWarning) {
vscode.window
.showWarningMessage(
`Your local Ollama instance doesn't yet have ${this.defaultTagName}. To download this model, run \`ollama run ${this.defaultTag}\` (recommended). If you'd like to use a custom model for tab autocomplete, learn more in the docs`,
"Documentation",
"Copy Command"
)
.then((value) => {
if (value === "Documentation") {
vscode.env.openExternal(
vscode.Uri.parse(
"https://continue.dev/docs/walkthroughs/tab-autocomplete"
)
);
} else if (value === "Copy Command") {
vscode.env.clipboard.writeText(`ollama run ${this.defaultTag}`);
}
});
this.shownDeepseekWarning = true;
}
return undefined;
}
} catch (e) {
if (!this.shownOllamaWarning) {
vscode.window
.showWarningMessage(
"Continue failed to connect to Ollama, which is used by default for tab-autocomplete. If you haven't downloaded it yet, you can do so at https://ollama.ai (recommended). If you'd like to use a custom model for tab autocomplete, learn more in the docs",
"Documentation"
)
.then((value) => {
if (value === "Documentation") {
vscode.env.openExternal(
vscode.Uri.parse(
"https://continue.dev/docs/walkthroughs/tab-autocomplete"
)
);
}
});
this.shownOllamaWarning = true;
}
return undefined;
}
return llm;
}
async get() {
if (!this._llm) {
const config = await this.configHandler.loadConfig();
if (config.tabAutocompleteModel) {
this._llm = this.configHandler.setupLlm(config.tabAutocompleteModel);
} else {
this._llm = await this.getDefaultTabAutocompleteModel();
}
}
return this._llm;
}
}

View file

@ -0,0 +1,534 @@
import { ContextItemId, IDE } from "core";
import { ConfigHandler } from "core/config/handler";
import { addModel, addOpenAIKey, deleteModel } from "core/config/util";
import { indexDocs } from "core/indexing/docs";
import TransformersJsEmbeddingsProvider from "core/indexing/embeddings/TransformersJsEmbeddingsProvider";
import { logDevData } from "core/util/devdata";
import historyManager from "core/util/history";
import { Message } from "core/util/messenger";
import { getConfigJsonPath } from "core/util/paths";
import {
ReverseWebviewProtocol,
WebviewProtocol,
} from "core/web/webviewProtocol";
import { v4 as uuidv4 } from "uuid";
import * as vscode from "vscode";
import { showTutorial } from "./activation/activate";
import { VerticalPerLineDiffManager } from "./diff/verticalPerLine/manager";
export class VsCodeWebviewProtocol {
listeners = new Map<keyof WebviewProtocol, ((message: Message) => any)[]>();
abortedMessageIds: Set<string> = new Set();
private send(messageType: string, data: any, messageId?: string): string {
const id = messageId || uuidv4();
this.webview?.postMessage({
messageType,
data,
messageId: id,
});
return id;
}
private on<T extends keyof WebviewProtocol>(
messageType: T,
handler: (
message: Message<WebviewProtocol[T][0]>
) => Promise<WebviewProtocol[T][1]> | WebviewProtocol[T][1]
): void {
if (!this.listeners.has(messageType)) {
this.listeners.set(messageType, []);
}
this.listeners.get(messageType)?.push(handler);
}
_webview?: vscode.Webview;
_webviewListener?: vscode.Disposable;
get webview(): vscode.Webview | undefined {
return this._webview;
}
set webview(webView: vscode.Webview) {
this._webview = webView;
this._webviewListener?.dispose();
this._webviewListener = this._webview.onDidReceiveMessage(async (msg) => {
if (!msg.messageType || !msg.messageId) {
throw new Error("Invalid webview protocol msg: " + JSON.stringify(msg));
}
const respond = (message: any) =>
this.send(msg.messageType, message, msg.messageId);
const handlers = this.listeners.get(msg.messageType) || [];
for (const handler of handlers) {
try {
const response = await handler(msg);
if (
response &&
typeof response[Symbol.asyncIterator] === "function"
) {
for await (const update of response) {
respond(update);
}
respond({ done: true });
} else {
respond(response || {});
}
} catch (e: any) {
console.error(
"Error handling webview message: " +
JSON.stringify({ msg }, null, 2)
);
let message = `Continue error: ${e.message}`;
if (e.cause) {
if (e.cause.name === "ConnectTimeoutError") {
message = `Connection timed out. If you expect it to take a long time to connect, you can increase the timeout in config.json by setting "requestOptions": { "timeout": 10000 }. You can find the full config reference here: https://continue.dev/docs/reference/config`;
} else if (e.cause.code === "ECONNREFUSED") {
message = `Connection was refused. This likely means that there is no server running at the specified URL. If you are running your own server you may need to set the "apiBase" parameter in config.json. For example, you can set up an OpenAI-compatible server like here: https://continue.dev/docs/reference/Model%20Providers/openai#openai-compatible-servers--apis`;
} else {
message = `The request failed with "${e.cause.name}": ${e.cause.message}. If you're having trouble setting up Continue, please see the troubleshooting guide for help.`;
}
}
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://continue.dev/docs/troubleshooting")
);
}
});
}
}
});
}
constructor(
private readonly ide: IDE,
private readonly configHandler: ConfigHandler,
private readonly verticalDiffManager: VerticalPerLineDiffManager
) {
this.on("abort", (msg) => {
this.abortedMessageIds.add(msg.messageId);
});
this.on("showFile", (msg) => {
this.ide.openFile(msg.data.filepath);
});
this.on("openConfigJson", (msg) => {
this.ide.openFile(getConfigJsonPath());
});
this.on("readRangeInFile", async (msg) => {
return await vscode.workspace
.openTextDocument(msg.data.filepath)
.then((document) => {
let start = new vscode.Position(0, 0);
let end = new vscode.Position(5, 0);
let range = new vscode.Range(start, end);
let contents = document.getText(range);
return contents;
});
});
this.on("toggleDevTools", (msg) => {
vscode.commands.executeCommand("workbench.action.toggleDevTools");
vscode.commands.executeCommand("continue.viewLogs");
});
this.on("reloadWindow", (msg) => {
vscode.commands.executeCommand("workbench.action.reloadWindow");
});
this.on("focusEditor", (msg) => {
vscode.commands.executeCommand("workbench.action.focusActiveEditorGroup");
});
this.on("toggleFullScreen", (msg) => {
vscode.commands.executeCommand("continue.toggleFullScreen");
});
// IDE
this.on("getDiff", async (msg) => {
return await ide.getDiff();
});
this.on("config/getBrowserSerialized", async (msg) => {
return await configHandler.getSerializedConfig();
});
this.on("getTerminalContents", async (msg) => {
return await ide.getTerminalContents();
});
this.on("listWorkspaceContents", async (msg) => {
return await ide.listWorkspaceContents();
});
this.on("getWorkspaceDirs", async (msg) => {
return await ide.getWorkspaceDirs();
});
this.on("listFolders", async (msg) => {
return await ide.listFolders();
});
this.on("writeFile", async (msg) => {
return await ide.writeFile(msg.data.path, msg.data.contents);
});
this.on("showVirtualFile", async (msg) => {
return await ide.showVirtualFile(msg.data.name, msg.data.content);
});
this.on("getContinueDir", async (msg) => {
return await ide.getContinueDir();
});
this.on("openFile", async (msg) => {
return await ide.openFile(msg.data.path);
});
this.on("runCommand", async (msg) => {
await ide.runCommand(msg.data.command);
});
this.on("getSearchResults", async (msg) => {
return await ide.getSearchResults(msg.data.query);
});
this.on("subprocess", async (msg) => {
return await ide.subprocess(msg.data.command);
});
// History
this.on("history/list", (msg) => {
return historyManager.list();
});
this.on("history/save", (msg) => {
historyManager.save(msg.data);
});
this.on("history/delete", (msg) => {
historyManager.delete(msg.data.id);
});
this.on("history/load", (msg) => {
return historyManager.load(msg.data.id);
});
this.on("saveFile", async (msg) => {
return await ide.saveFile(msg.data.filepath);
});
this.on("readFile", async (msg) => {
return await ide.readFile(msg.data.filepath);
});
this.on("showDiff", async (msg) => {
return await ide.showDiff(
msg.data.filepath,
msg.data.newContents,
msg.data.stepIndex
);
});
this.on("getProblems", async (msg) => {
return await ide.getProblems(msg.data.filepath);
});
this.on("getBranch", async (msg) => {
const { dir } = msg.data;
return await ide.getBranch(dir);
});
this.on("getOpenFiles", async (msg) => {
return await ide.getOpenFiles();
});
this.on("getPinnedFiles", async (msg) => {
return await ide.getPinnedFiles();
});
this.on("showLines", async (msg) => {
const { filepath, startLine, endLine } = msg.data;
return await ide.showLines(filepath, startLine, endLine);
});
// Other
this.on("errorPopup", (msg) => {
vscode.window
.showErrorMessage(msg.data.message, "Show Logs")
.then((selection) => {
if (selection === "Show Logs") {
vscode.commands.executeCommand("workbench.action.toggleDevTools");
}
});
});
this.on("devdata/log", (msg) => {
logDevData(msg.data.tableName, msg.data.data);
});
this.on("config/addModel", (msg) => {
const model = msg.data.model;
const newConfigString = addModel(model);
this.configHandler.reloadConfig();
this.ide.openFile(getConfigJsonPath());
// Find the range where it was added and highlight
let lines = newConfigString.split("\n");
let startLine;
let endLine;
for (let i = 0; i < lines.length; i++) {
let line = lines[i];
if (!startLine) {
if (line.trim() === `"title": "${model.title}",`) {
startLine = i - 1;
}
} else {
if (line.startsWith(" }")) {
endLine = i;
break;
}
}
}
if (startLine && endLine) {
this.ide.showLines(
getConfigJsonPath(),
startLine,
endLine
// "#fff1"
);
}
vscode.window.showInformationMessage(
"🎉 Your model has been successfully added to config.json. You can use this file to further edit its configuration."
);
});
this.on("config/deleteModel", (msg) => {
deleteModel(msg.data.title);
this.configHandler.reloadConfig();
});
this.on("config/addOpenAiKey", async (msg) => {
addOpenAIKey(msg.data);
this.configHandler.reloadConfig();
});
async function* llmStreamComplete(
protocol: VsCodeWebviewProtocol,
msg: Message<WebviewProtocol["llm/streamComplete"][0]>
) {
const model = await protocol.configHandler.llmFromTitle(msg.data.title);
const gen = model.streamComplete(
msg.data.prompt,
msg.data.completionOptions
);
let next = await gen.next();
while (!next.done) {
if (protocol.abortedMessageIds.has(msg.messageId)) {
protocol.abortedMessageIds.delete(msg.messageId);
next = await gen.return({ completion: "", prompt: "" });
break;
}
yield { content: next.value };
next = await gen.next();
}
return { done: true, content: next.value };
}
this.on("llm/streamComplete", (msg) => llmStreamComplete(this, msg));
async function* llmStreamChat(
protocol: VsCodeWebviewProtocol,
msg: Message<WebviewProtocol["llm/streamChat"][0]>
) {
const model = await protocol.configHandler.llmFromTitle(msg.data.title);
const gen = model.streamChat(
msg.data.messages,
msg.data.completionOptions
);
let next = await gen.next();
while (!next.done) {
if (protocol.abortedMessageIds.has(msg.messageId)) {
protocol.abortedMessageIds.delete(msg.messageId);
next = await gen.return({ completion: "", prompt: "" });
break;
}
yield { content: next.value.content };
next = await gen.next();
}
return { done: true, content: next.value };
}
this.on("llm/streamChat", (msg) => llmStreamChat(this, msg));
this.on("llm/complete", async (msg) => {
const model = await this.configHandler.llmFromTitle(msg.data.title);
const completion = await model.complete(
msg.data.prompt,
msg.data.completionOptions
);
return completion;
});
async function* runNodeJsSlashCommand(
protocol: VsCodeWebviewProtocol,
msg: Message<WebviewProtocol["command/run"][0]>
) {
const {
input,
history,
modelTitle,
slashCommandName,
contextItems,
params,
historyIndex,
selectedCode,
} = msg.data;
const config = await protocol.configHandler.loadConfig();
const llm = await protocol.configHandler.llmFromTitle(modelTitle);
const slashCommand = config.slashCommands?.find(
(sc) => sc.name === slashCommandName
);
if (!slashCommand) {
throw new Error(`Unknown slash command ${slashCommandName}`);
}
for await (const content of slashCommand.run({
input,
history,
llm,
contextItems,
params,
ide,
addContextItem: (item) => {
protocol.request("addContextItem", {
item,
historyIndex,
});
},
selectedCode,
config,
})) {
if (content) {
yield { content };
}
}
yield { done: true, content: "" };
}
this.on("command/run", (msg) => runNodeJsSlashCommand(this, msg));
this.on("context/loadSubmenuItems", async (msg) => {
const { title } = msg.data;
const config = await this.configHandler.loadConfig();
const provider = config.contextProviders?.find(
(p) => p.description.title === title
);
if (!provider) {
vscode.window.showErrorMessage(
`Unknown provider ${title}. Existing providers: ${config.contextProviders
?.map((p) => p.description.title)
.join(", ")}`
);
return [];
}
try {
const items = await provider.loadSubmenuItems({ ide });
return items;
} catch (e) {
vscode.window.showErrorMessage(
`Error loading submenu items from ${title}: ${e}`
);
return [];
}
});
this.on("context/getContextItems", async (msg) => {
const { name, query, fullInput, selectedCode } = msg.data;
const config = await this.configHandler.loadConfig();
const llm = await this.configHandler.llmFromTitle();
const provider = config.contextProviders?.find(
(p) => p.description.title === name
);
if (!provider) {
vscode.window.showErrorMessage(
`Unknown provider ${name}. Existing providers: ${config.contextProviders
?.map((p) => p.description.title)
.join(", ")}`
);
return [];
}
try {
const id: ContextItemId = {
providerTitle: provider.description.title,
itemId: uuidv4(),
};
const items = await provider.getContextItems(query, {
llm,
embeddingsProvider: config.embeddingsProvider,
fullInput,
ide,
selectedCode,
});
return items.map((item) => ({ ...item, id }));
} catch (e) {
vscode.window.showErrorMessage(
`Error getting context items from ${name}: ${e}`
);
return [];
}
});
this.on("context/addDocs", (msg) => {
const { url, title } = msg.data;
const embeddingsProvider = new TransformersJsEmbeddingsProvider();
vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: `Indexing ${title}`,
cancellable: false,
},
async (progress) => {
for await (const update of indexDocs(
title,
new URL(url),
embeddingsProvider
)) {
progress.report({
increment: update.progress,
message: update.desc,
});
}
vscode.window.showInformationMessage(
`🎉 Successfully indexed ${title}`
);
this.request("refreshSubmenuItems", undefined);
}
);
});
this.on("applyToCurrentFile", (msg) => {
// Select the entire current file
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showErrorMessage("No active editor to apply edits to");
return;
}
const document = editor.document;
const start = new vscode.Position(0, 0);
const end = new vscode.Position(
document.lineCount - 1,
document.lineAt(document.lineCount - 1).text.length
);
editor.selection = new vscode.Selection(start, end);
this.verticalDiffManager.streamEdit(
`The following code was suggested as an edit:\n\`\`\`\n${msg.data.text}\n\`\`\`\nPlease apply it to the previous code.`
);
});
this.on("showTutorial", (msg) => {
showTutorial();
});
}
public request<T extends keyof ReverseWebviewProtocol>(
messageType: T,
data: ReverseWebviewProtocol[T][0]
): Promise<ReverseWebviewProtocol[T][1]> {
const messageId = uuidv4();
return new Promise((resolve) => {
if (!this.webview) {
resolve(undefined);
return;
}
this.send(messageType, data, messageId);
const disposable = this.webview.onDidReceiveMessage((msg) => {
resolve(msg);
disposable?.dispose();
});
});
}
}

View file

@ -2323,9 +2323,13 @@ core-util-is@1.0.2:
adf-to-md "^1.1.0"
axios "^1.6.7"
cheerio "^1.0.0-rc.12"
commander "^12.0.0"
dotenv "^16.3.1"
fastest-levenshtein "^1.0.16"
follow-redirects "^1.15.5"
handlebars "^4.7.8"
http-proxy-agent "^7.0.1"
https-proxy-agent "^7.0.3"
js-tiktoken "^1.0.8"
llm-code-highlighter "^0.0.13"
node-fetch "^3.3.2"

477
gui/package-lock.json generated
View file

@ -79,9 +79,13 @@
"adf-to-md": "^1.1.0",
"axios": "^1.6.7",
"cheerio": "^1.0.0-rc.12",
"commander": "^12.0.0",
"dotenv": "^16.3.1",
"fastest-levenshtein": "^1.0.16",
"follow-redirects": "^1.15.5",
"handlebars": "^4.7.8",
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"js-tiktoken": "^1.0.8",
"llm-code-highlighter": "^0.0.13",
"node-fetch": "^3.3.2",
@ -99,6 +103,7 @@
"web-tree-sitter": "^0.20.8"
},
"devDependencies": {
"@types/follow-redirects": "^1.14.4",
"@types/handlebars": "^4.1.0",
"@types/jest": "^29.5.11",
"@types/jquery": "^3.5.29",
@ -836,12 +841,12 @@
}
},
"node_modules/@floating-ui/dom": {
"version": "1.6.1",
"resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.6.1.tgz",
"integrity": "sha512-iA8qE43/H5iGozC3W0YSnVSW42Vh522yyM1gj+BqRwVsTNOyr231PsXDaV04yT39PsO0QL2QpbI/M0ZaLUQgRQ==",
"version": "1.6.3",
"resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.6.3.tgz",
"integrity": "sha512-RnDthu3mzPlQ31Ss/BTwQ1zjzIhr3lk1gZB1OC56h/1vEtaXkESrOqL5fQVMfXpwGtRwX+YsZBdyHtJMQnkArw==",
"dependencies": {
"@floating-ui/core": "^1.6.0",
"@floating-ui/utils": "^0.2.1"
"@floating-ui/core": "^1.0.0",
"@floating-ui/utils": "^0.2.0"
}
},
"node_modules/@floating-ui/utils": {
@ -904,9 +909,9 @@
}
},
"node_modules/@jridgewell/resolve-uri": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz",
"integrity": "sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA==",
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
"integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
"engines": {
"node": ">=6.0.0"
}
@ -1113,13 +1118,13 @@
"integrity": "sha512-+9jVqKhRSpsc591z5vX+X5Yyw+he/HCB4iQ/RYxw35CEPaY1gnsNE43nf9n9AaYjAQrTiI/mOwKUKdUs9vf7Xg=="
},
"node_modules/@swc/core": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/@swc/core/-/core-1.4.0.tgz",
"integrity": "sha512-wc5DMI5BJftnK0Fyx9SNJKkA0+BZSJQx8430yutWmsILkHMBD3Yd9GhlMaxasab9RhgKqZp7Ht30hUYO5ZDvQg==",
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@swc/core/-/core-1.4.1.tgz",
"integrity": "sha512-3y+Y8js+e7BbM16iND+6Rcs3jdiL28q3iVtYsCviYSSpP2uUVKkp5sJnCY4pg8AaVvyN7CGQHO7gLEZQ5ByozQ==",
"dev": true,
"hasInstallScript": true,
"dependencies": {
"@swc/counter": "^0.1.1",
"@swc/counter": "^0.1.2",
"@swc/types": "^0.1.5"
},
"engines": {
@ -1130,16 +1135,16 @@
"url": "https://opencollective.com/swc"
},
"optionalDependencies": {
"@swc/core-darwin-arm64": "1.4.0",
"@swc/core-darwin-x64": "1.4.0",
"@swc/core-linux-arm-gnueabihf": "1.4.0",
"@swc/core-linux-arm64-gnu": "1.4.0",
"@swc/core-linux-arm64-musl": "1.4.0",
"@swc/core-linux-x64-gnu": "1.4.0",
"@swc/core-linux-x64-musl": "1.4.0",
"@swc/core-win32-arm64-msvc": "1.4.0",
"@swc/core-win32-ia32-msvc": "1.4.0",
"@swc/core-win32-x64-msvc": "1.4.0"
"@swc/core-darwin-arm64": "1.4.1",
"@swc/core-darwin-x64": "1.4.1",
"@swc/core-linux-arm-gnueabihf": "1.4.1",
"@swc/core-linux-arm64-gnu": "1.4.1",
"@swc/core-linux-arm64-musl": "1.4.1",
"@swc/core-linux-x64-gnu": "1.4.1",
"@swc/core-linux-x64-musl": "1.4.1",
"@swc/core-win32-arm64-msvc": "1.4.1",
"@swc/core-win32-ia32-msvc": "1.4.1",
"@swc/core-win32-x64-msvc": "1.4.1"
},
"peerDependencies": {
"@swc/helpers": "^0.5.0"
@ -1151,9 +1156,9 @@
}
},
"node_modules/@swc/core-darwin-arm64": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/@swc/core-darwin-arm64/-/core-darwin-arm64-1.4.0.tgz",
"integrity": "sha512-UTJ/Vz+s7Pagef6HmufWt6Rs0aUu+EJF4Pzuwvr7JQQ5b1DZeAAUeUtkUTFx/PvCbM8Xfw4XdKBUZfrIKCfW8A==",
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@swc/core-darwin-arm64/-/core-darwin-arm64-1.4.1.tgz",
"integrity": "sha512-ePyfx0348UbR4DOAW24TedeJbafnzha8liXFGuQ4bdXtEVXhLfPngprrxKrAddCuv42F9aTxydlF6+adD3FBhA==",
"cpu": [
"arm64"
],
@ -1167,9 +1172,9 @@
}
},
"node_modules/@swc/core-darwin-x64": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/@swc/core-darwin-x64/-/core-darwin-x64-1.4.0.tgz",
"integrity": "sha512-f8v58u2GsGak8EtZFN9guXqE0Ep10Suny6xriaW2d8FGqESPyNrnBzli3aqkSeQk5gGqu2zJ7WiiKp3XoUOidA==",
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@swc/core-darwin-x64/-/core-darwin-x64-1.4.1.tgz",
"integrity": "sha512-eLf4JSe6VkCMdDowjM8XNC5rO+BrgfbluEzAVtKR8L2HacNYukieumN7EzpYCi0uF1BYwu1ku6tLyG2r0VcGxA==",
"cpu": [
"x64"
],
@ -1183,9 +1188,9 @@
}
},
"node_modules/@swc/core-linux-arm-gnueabihf": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/@swc/core-linux-arm-gnueabihf/-/core-linux-arm-gnueabihf-1.4.0.tgz",
"integrity": "sha512-q2KAkBzmPcTnRij/Y1fgHCKAGevUX/H4uUESrw1J5gmUg9Qip6onKV80lTumA1/aooGJ18LOsB31qdbwmZk9OA==",
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@swc/core-linux-arm-gnueabihf/-/core-linux-arm-gnueabihf-1.4.1.tgz",
"integrity": "sha512-K8VtTLWMw+rkN/jDC9o/Q9SMmzdiHwYo2CfgkwVT29NsGccwmNhCQx6XoYiPKyKGIFKt4tdQnJHKUFzxUqQVtQ==",
"cpu": [
"arm"
],
@ -1199,9 +1204,9 @@
}
},
"node_modules/@swc/core-linux-arm64-gnu": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/@swc/core-linux-arm64-gnu/-/core-linux-arm64-gnu-1.4.0.tgz",
"integrity": "sha512-SknGu96W0mzHtLHWm+62fk5+Omp9fMPFO7AWyGFmz2tr8EgRRXtTSrBUnWhAbgcalnhen48GsvtMdxf1KNputg==",
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@swc/core-linux-arm64-gnu/-/core-linux-arm64-gnu-1.4.1.tgz",
"integrity": "sha512-0e8p4g0Bfkt8lkiWgcdiENH3RzkcqKtpRXIVNGOmVc0OBkvc2tpm2WTx/eoCnes2HpTT4CTtR3Zljj4knQ4Fvw==",
"cpu": [
"arm64"
],
@ -1215,9 +1220,9 @@
}
},
"node_modules/@swc/core-linux-arm64-musl": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/@swc/core-linux-arm64-musl/-/core-linux-arm64-musl-1.4.0.tgz",
"integrity": "sha512-/k3TDvpBRMDNskHooNN1KqwUhcwkfBlIYxRTnJvsfT2C7My4pffR+4KXmt0IKynlTTbCdlU/4jgX4801FSuliw==",
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@swc/core-linux-arm64-musl/-/core-linux-arm64-musl-1.4.1.tgz",
"integrity": "sha512-b/vWGQo2n7lZVUnSQ7NBq3Qrj85GrAPPiRbpqaIGwOytiFSk8VULFihbEUwDe0rXgY4LDm8z8wkgADZcLnmdUA==",
"cpu": [
"arm64"
],
@ -1231,9 +1236,9 @@
}
},
"node_modules/@swc/core-linux-x64-gnu": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/@swc/core-linux-x64-gnu/-/core-linux-x64-gnu-1.4.0.tgz",
"integrity": "sha512-GYsTMvNt5+WTVlwwQzOOWsPMw6P/F41u5PGHWmfev8Nd4QJ1h3rWPySKk4mV42IJwH9MgQCVSl3ygwNqwl6kFg==",
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@swc/core-linux-x64-gnu/-/core-linux-x64-gnu-1.4.1.tgz",
"integrity": "sha512-AFMQlvkKEdNi1Vk2GFTxxJzbICttBsOQaXa98kFTeWTnFFIyiIj2w7Sk8XRTEJ/AjF8ia8JPKb1zddBWr9+bEQ==",
"cpu": [
"x64"
],
@ -1247,9 +1252,9 @@
}
},
"node_modules/@swc/core-linux-x64-musl": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/@swc/core-linux-x64-musl/-/core-linux-x64-musl-1.4.0.tgz",
"integrity": "sha512-jGVPdM/VwF7kK/uYRW5N6FwzKf/FnDjGIR3RPvQokjYJy7Auk+3Oj21C0Jev7sIT9RYnO/TrFEoEozKeD/z2Qw==",
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@swc/core-linux-x64-musl/-/core-linux-x64-musl-1.4.1.tgz",
"integrity": "sha512-QX2MxIECX1gfvUVZY+jk528/oFkS9MAl76e3ZRvG2KC/aKlCQL0KSzcTSm13mOxkDKS30EaGRDRQWNukGpMeRg==",
"cpu": [
"x64"
],
@ -1263,9 +1268,9 @@
}
},
"node_modules/@swc/core-win32-arm64-msvc": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/@swc/core-win32-arm64-msvc/-/core-win32-arm64-msvc-1.4.0.tgz",
"integrity": "sha512-biHYm1AronEKlt47O/H8sSOBM2BKXMmWT+ApvlxUw50m1RGNnVnE0bgY7tylFuuSiWyXsQPJbmUV708JqORXVg==",
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@swc/core-win32-arm64-msvc/-/core-win32-arm64-msvc-1.4.1.tgz",
"integrity": "sha512-OklkJYXXI/tntD2zaY8i3iZldpyDw5q+NAP3k9OlQ7wXXf37djRsHLV0NW4+ZNHBjE9xp2RsXJ0jlOJhfgGoFA==",
"cpu": [
"arm64"
],
@ -1279,9 +1284,9 @@
}
},
"node_modules/@swc/core-win32-ia32-msvc": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/@swc/core-win32-ia32-msvc/-/core-win32-ia32-msvc-1.4.0.tgz",
"integrity": "sha512-TL5L2tFQb19kJwv6+elToGBj74QXCn9j+hZfwQatvZEJRA5rDK16eH6oAE751dGUArhnWlW3Vj65hViPvTuycw==",
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@swc/core-win32-ia32-msvc/-/core-win32-ia32-msvc-1.4.1.tgz",
"integrity": "sha512-MBuc3/QfKX9FnLOU7iGN+6yHRTQaPQ9WskiC8s8JFiKQ+7I2p25tay2RplR9dIEEGgVAu6L7auv96LbNTh+FaA==",
"cpu": [
"ia32"
],
@ -1295,9 +1300,9 @@
}
},
"node_modules/@swc/core-win32-x64-msvc": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/@swc/core-win32-x64-msvc/-/core-win32-x64-msvc-1.4.0.tgz",
"integrity": "sha512-e2xVezU7XZ2Stzn4i7TOQe2Kn84oYdG0M3A7XI7oTdcpsKCcKwgiMoroiAhqCv+iN20KNqhnWwJiUiTj/qN5AA==",
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@swc/core-win32-x64-msvc/-/core-win32-x64-msvc-1.4.1.tgz",
"integrity": "sha512-lu4h4wFBb/bOK6N2MuZwg7TrEpwYXgpQf5R7ObNSXL65BwZ9BG8XRzD+dLJmALu8l5N08rP/TrpoKRoGT4WSxw==",
"cpu": [
"x64"
],
@ -1805,9 +1810,9 @@
"integrity": "sha512-nG96G3Wp6acyAgJqGasjODb+acrI7KltPiRxzHPXnP3NgI28bpQDRv53olbqGXbfcgF5aiiHmO3xpwEpS5Ld9g=="
},
"node_modules/@types/node": {
"version": "20.11.16",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.16.tgz",
"integrity": "sha512-gKb0enTmRCzXSSUJDq6/sPcqrfCv2mkkG6Jt/clpn5eiCbKTY+SgZUxo+p8ZKMof5dCp9vHQUAB7wOUTod22wQ==",
"version": "20.11.17",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.17.tgz",
"integrity": "sha512-QmgQZGWu1Yw9TDyAP9ZzpFJKynYNeOvwMJmaxABfieQoVoiVOS6MN1WSpqpRcbeA5+RW82kraAVxCCJg+780Qw==",
"dev": true,
"dependencies": {
"undici-types": "~5.26.4"
@ -2066,6 +2071,15 @@
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
"dev": true
},
"node_modules/bcp-47-match": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/bcp-47-match/-/bcp-47-match-1.0.3.tgz",
"integrity": "sha512-LggQ4YTdjWQSKELZF5JwchnBa1u0pIQSZf5lSdOHEdbVP55h0qICA/FUp3+W99q0xqxYa1ZQizTUH87gecII5w==",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/binary-extensions": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz",
@ -2102,9 +2116,9 @@
}
},
"node_modules/browserslist": {
"version": "4.22.3",
"resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.22.3.tgz",
"integrity": "sha512-UAp55yfwNv0klWNapjs/ktHoguxuQNGnOzxYmfnXIS+8AsRDZkSDxg7R1AX3GKzn078SBI5dzwzj/Yx0Or0e3A==",
"version": "4.23.0",
"resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.23.0.tgz",
"integrity": "sha512-QW8HiM1shhT2GuzkvklfjcKDiWFXHOeFCIA/huJPwHsslwcydgk7X+z2zXpEijP98UCY7HbubZt5J2Zgvf0CaQ==",
"funding": [
{
"type": "opencollective",
@ -2120,8 +2134,8 @@
}
],
"dependencies": {
"caniuse-lite": "^1.0.30001580",
"electron-to-chromium": "^1.4.648",
"caniuse-lite": "^1.0.30001587",
"electron-to-chromium": "^1.4.668",
"node-releases": "^2.0.14",
"update-browserslist-db": "^1.0.13"
},
@ -2150,9 +2164,9 @@
}
},
"node_modules/caniuse-lite": {
"version": "1.0.30001585",
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001585.tgz",
"integrity": "sha512-yr2BWR1yLXQ8fMpdS/4ZZXpseBgE7o4g41x3a6AJOqZuOi+iE/WdJYAuZ6Y95i4Ohd2Y+9MzIWRR+uGABH4s3Q==",
"version": "1.0.30001587",
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001587.tgz",
"integrity": "sha512-HMFNotUmLXn71BQxg8cijvqxnIAofforZOwGsxyXJ0qugTdspUF4sPSJ2vhgprHCB996tIDzEq1ubumPDV8ULA==",
"funding": [
{
"type": "opencollective",
@ -2375,6 +2389,11 @@
"node": ">=4"
}
},
"node_modules/css-selector-parser": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/css-selector-parser/-/css-selector-parser-1.4.1.tgz",
"integrity": "sha512-HYPSb7y/Z7BNDCOrakL4raGO2zltZkbeXyAd6Tg9obzix6QhzxCotdBl6VT0Dv4vZfJGVz3WL/xaEI9Ly3ul0g=="
},
"node_modules/css-to-react-native": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/css-to-react-native/-/css-to-react-native-3.2.0.tgz",
@ -2478,6 +2497,18 @@
"integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==",
"dev": true
},
"node_modules/direction": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/direction/-/direction-1.0.4.tgz",
"integrity": "sha512-GYqKi1aH7PJXxdhTeZBFrg8vUBeKXi+cNprXsC1kpJcbcVnV9wBsrOu1cQEdG0WeQwlfHiy3XvnKfIrJ2R0NzQ==",
"bin": {
"direction": "cli.js"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/dlv": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz",
@ -2516,9 +2547,9 @@
"dev": true
},
"node_modules/electron-to-chromium": {
"version": "1.4.661",
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.661.tgz",
"integrity": "sha512-AFg4wDHSOk5F+zA8aR+SVIOabu7m0e7BiJnigCvPXzIGy731XENw/lmNxTySpVFtkFEy+eyt4oHhh5FF3NjQNw=="
"version": "1.4.669",
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.669.tgz",
"integrity": "sha512-E2SmpffFPrZhBSgf8ibqanRS2mpuk3FIRDzLDwt7WFpfgJMKDHJs0hmacyP0PS1cWsq0dVkwIIzlscNaterkPg=="
},
"node_modules/emoji-regex": {
"version": "9.2.2",
@ -2850,9 +2881,9 @@
}
},
"node_modules/hasown": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.0.tgz",
"integrity": "sha512-vUptKVTpIJhcczKBbgnS+RtcuYMB8+oNzPK2/Hp3hanz8JmpATdmmgLgSaadVREkDm+e2giHwY3ZRkyjSIDDFA==",
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.1.tgz",
"integrity": "sha512-1/th4MHjnwncwXsIW6QMzlvYL9kG5e/CpVvLRZe4XPa8TOUNbCELqmvhDmnkNsAjwaG4+I8gJJL0JBvTTLO9qA==",
"dev": true,
"dependencies": {
"function-bind": "^1.1.2"
@ -3066,6 +3097,15 @@
"url": "https://opencollective.com/unified"
}
},
"node_modules/hast-util-has-property": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/hast-util-has-property/-/hast-util-has-property-1.0.4.tgz",
"integrity": "sha512-ghHup2voGfgFoHMGnaLHOjbYFACKrRh9KFttdCzMCbFoBMJXiNi2+XTrPP8+q6cDJM/RSqlCfVWrjp1H201rZg==",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/unified"
}
},
"node_modules/hast-util-is-element": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/hast-util-is-element/-/hast-util-is-element-3.0.0.tgz",
@ -3087,6 +3127,129 @@
"url": "https://opencollective.com/unified"
}
},
"node_modules/hast-util-select": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/hast-util-select/-/hast-util-select-4.0.2.tgz",
"integrity": "sha512-8EEG2//bN5rrzboPWD2HdS3ugLijNioS1pqOTIolXNf67xxShYw4SQEmVXd3imiBG+U2bC2nVTySr/iRAA7Cjg==",
"dependencies": {
"bcp-47-match": "^1.0.0",
"comma-separated-tokens": "^1.0.0",
"css-selector-parser": "^1.0.0",
"direction": "^1.0.0",
"hast-util-has-property": "^1.0.0",
"hast-util-is-element": "^1.0.0",
"hast-util-to-string": "^1.0.0",
"hast-util-whitespace": "^1.0.0",
"not": "^0.1.0",
"nth-check": "^2.0.0",
"property-information": "^5.0.0",
"space-separated-tokens": "^1.0.0",
"unist-util-visit": "^2.0.0",
"zwitch": "^1.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/unified"
}
},
"node_modules/hast-util-select/node_modules/@types/unist": {
"version": "2.0.10",
"resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.10.tgz",
"integrity": "sha512-IfYcSBWE3hLpBg8+X2SEa8LVkJdJEkT2Ese2aaLs3ptGdVtABxndrMaxuFlQ1qdFf9Q5rDvDpxI3WwgvKFAsQA=="
},
"node_modules/hast-util-select/node_modules/comma-separated-tokens": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-1.0.8.tgz",
"integrity": "sha512-GHuDRO12Sypu2cV70d1dkA2EUmXHgntrzbpvOB+Qy+49ypNfGgFQIC2fhhXbnyrJRynDCAARsT7Ou0M6hirpfw==",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/hast-util-select/node_modules/hast-util-is-element": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/hast-util-is-element/-/hast-util-is-element-1.1.0.tgz",
"integrity": "sha512-oUmNua0bFbdrD/ELDSSEadRVtWZOf3iF6Lbv81naqsIV99RnSCieTbWuWCY8BAeEfKJTKl0gRdokv+dELutHGQ==",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/unified"
}
},
"node_modules/hast-util-select/node_modules/hast-util-whitespace": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-1.0.4.tgz",
"integrity": "sha512-I5GTdSfhYfAPNztx2xJRQpG8cuDSNt599/7YUn7Gx/WxNMsG+a835k97TDkFgk123cwjfwINaZknkKkphx/f2A==",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/unified"
}
},
"node_modules/hast-util-select/node_modules/property-information": {
"version": "5.6.0",
"resolved": "https://registry.npmjs.org/property-information/-/property-information-5.6.0.tgz",
"integrity": "sha512-YUHSPk+A30YPv+0Qf8i9Mbfe/C0hdPXk1s1jPVToV8pk8BQtpw10ct89Eo7OWkutrwqvT0eicAxlOg3dOAu8JA==",
"dependencies": {
"xtend": "^4.0.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/hast-util-select/node_modules/space-separated-tokens": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-1.1.5.tgz",
"integrity": "sha512-q/JSVd1Lptzhf5bkYm4ob4iWPjx0KiRe3sRFBNrVqbJkFaBm5vbbowy1mymoPNLRa52+oadOhJ+K49wsSeSjTA==",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/hast-util-select/node_modules/unist-util-is": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-4.1.0.tgz",
"integrity": "sha512-ZOQSsnce92GrxSqlnEEseX0gi7GH9zTJZ0p9dtu87WRb/37mMPO2Ilx1s/t9vBHrFhbgweUwb+t7cIn5dxPhZg==",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/unified"
}
},
"node_modules/hast-util-select/node_modules/unist-util-visit": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-2.0.3.tgz",
"integrity": "sha512-iJ4/RczbJMkD0712mGktuGpm/U4By4FfDonL7N/9tATGIF4imikjOuagyMY53tnZq3NP6BcmlrHhEKAfGWjh7Q==",
"dependencies": {
"@types/unist": "^2.0.0",
"unist-util-is": "^4.0.0",
"unist-util-visit-parents": "^3.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/unified"
}
},
"node_modules/hast-util-select/node_modules/unist-util-visit-parents": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-3.1.1.tgz",
"integrity": "sha512-1KROIZWo6bcMrZEwiH2UrXDyalAa0uqzWCxCJj6lPOvTve2WkfgCytoDTPaMnodXh1WrXOq0haVYHj99ynJlsg==",
"dependencies": {
"@types/unist": "^2.0.0",
"unist-util-is": "^4.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/unified"
}
},
"node_modules/hast-util-select/node_modules/zwitch": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/zwitch/-/zwitch-1.0.5.tgz",
"integrity": "sha512-V50KMwwzqJV0NpZIZFwfOD5/lyny3WlSzRiXgA0G7VUnRlqttta1L6UQIHzd6EuBY/cHGfwTIck7w1yH6Q5zUw==",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/hast-util-to-jsx-runtime": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.0.tgz",
@ -3113,6 +3276,15 @@
"url": "https://opencollective.com/unified"
}
},
"node_modules/hast-util-to-string": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/hast-util-to-string/-/hast-util-to-string-1.0.4.tgz",
"integrity": "sha512-eK0MxRX47AV2eZ+Lyr18DCpQgodvaS3fAQO2+b9Two9F5HEoRPhiUMNzoXArMJfZi2yieFzUBMRl3HNJ3Jus3w==",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/unified"
}
},
"node_modules/hast-util-to-text": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/hast-util-to-text/-/hast-util-to-text-4.0.0.tgz",
@ -3698,9 +3870,9 @@
}
},
"node_modules/mdast-util-mdx-jsx": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.0.0.tgz",
"integrity": "sha512-XZuPPzQNBPAlaqsTTgRrcJnyFbSOBovSadFgbFu8SnuNgm+6Bdx1K+IWoitsmj6Lq6MNtI+ytOqwN70n//NaBA==",
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.1.0.tgz",
"integrity": "sha512-A8AJHlR7/wPQ3+Jre1+1rq040fX9A4Q1jG8JxmSNp/PLPHg80A6475wxTp3KzHpApFH6yWxFotHrJQA3dXP6/w==",
"dependencies": {
"@types/estree-jsx": "^1.0.0",
"@types/hast": "^3.0.0",
@ -4319,9 +4491,9 @@
"integrity": "sha512-ihFnidEeU8iXzcVHy74dhkxh/dn8Dc08ERl0xwoMMGqp4+LvRSCgicb+zGqWthVokQKvCSxITlh3P08OzdTYCQ=="
},
"node_modules/monaco-editor": {
"version": "0.45.0",
"resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.45.0.tgz",
"integrity": "sha512-mjv1G1ZzfEE3k9HZN0dQ2olMdwIfaeAAjFiwNprLfYNRSz7ctv9XuCT7gPtBGrMUeV1/iZzYKj17Khu1hxoHOA==",
"version": "0.46.0",
"resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.46.0.tgz",
"integrity": "sha512-ADwtLIIww+9FKybWscd7OCfm9odsFYHImBRI1v9AviGce55QY8raT+9ihH8jX/E/e6QVSGM+pKj4jSUSRmALNQ==",
"peer": true
},
"node_modules/ms": {
@ -4658,12 +4830,15 @@
}
},
"node_modules/postcss-load-config/node_modules/lilconfig": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.0.0.tgz",
"integrity": "sha512-K2U4W2Ff5ibV7j7ydLr+zLAkIg5JJ4lPn1Ltsdt+Tz/IjQ8buJ55pZAxoP34lqIiwtF9iAvtLv3JGv7CAyAg+g==",
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.0.tgz",
"integrity": "sha512-p3cz0JV5vw/XeouBU3Ldnp+ZkBjE+n8ydJ4mcwBrOiXXPqNlrzGBqWs9X4MWF7f+iKUBu794Y8Hh8yawiJbCjw==",
"dev": true,
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/sponsors/antonk52"
}
},
"node_modules/postcss-nested": {
@ -4704,18 +4879,18 @@
"integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ=="
},
"node_modules/posthog-js": {
"version": "1.105.4",
"resolved": "https://registry.npmjs.org/posthog-js/-/posthog-js-1.105.4.tgz",
"integrity": "sha512-hazxQYi4nxSqktu0Hh1xCV+sJCpN8mp5E5Ei/cfEa2nsb13xQbzn81Lf3VIDA0xMU1mXxNRStntlY267eQVC/w==",
"version": "1.105.9",
"resolved": "https://registry.npmjs.org/posthog-js/-/posthog-js-1.105.9.tgz",
"integrity": "sha512-i9DnfyXDktugF5E9x0ejihQ8Xdh1kdVnVh7GdL7+PvFtULGMoN/b4pDmWBCwmH+ciubmqTCImVuNrZYy8+eTbw==",
"dependencies": {
"fflate": "^0.4.8",
"preact": "^10.19.3"
}
},
"node_modules/preact": {
"version": "10.19.3",
"resolved": "https://registry.npmjs.org/preact/-/preact-10.19.3.tgz",
"integrity": "sha512-nHHTeFVBTHRGxJXKkKu5hT8C/YWBkPso4/Gad6xuj5dbptt9iF9NZr9pHbPhBrnT2klheu7mHTxTZ/LjwJiEiQ==",
"version": "10.19.4",
"resolved": "https://registry.npmjs.org/preact/-/preact-10.19.4.tgz",
"integrity": "sha512-dwaX5jAh0Ga8uENBX1hSOujmKWgx9RtL80KaKUFLc6jb4vCEAc3EeZ0rnQO/FO4VgjfPMfoLFWnNG8bHuZ9VLw==",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/preact"
@ -5471,11 +5646,11 @@
}
},
"node_modules/react-tooltip": {
"version": "5.26.0",
"resolved": "https://registry.npmjs.org/react-tooltip/-/react-tooltip-5.26.0.tgz",
"integrity": "sha512-UBbwy3fo1KYDwRCOWwM6AEfQsk9shgVfNkXFqgwS33QHplzg7xao/7mX/6wd+lE6KSZzhUNTkB5TNk9SMaBV/A==",
"version": "5.26.2",
"resolved": "https://registry.npmjs.org/react-tooltip/-/react-tooltip-5.26.2.tgz",
"integrity": "sha512-C1qHiqWYn6l5c98kL/NKFyJSw5G11vUVJkgOPcKgn306c5iL5317LxMNn5Qg1GSSM7Qvtsd6KA5MvwfgxFF7Dg==",
"dependencies": {
"@floating-ui/dom": "^1.0.0",
"@floating-ui/dom": "^1.6.1",
"classnames": "^2.3.0"
},
"peerDependencies": {
@ -5738,123 +5913,6 @@
"resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.10.tgz",
"integrity": "sha512-IfYcSBWE3hLpBg8+X2SEa8LVkJdJEkT2Ese2aaLs3ptGdVtABxndrMaxuFlQ1qdFf9Q5rDvDpxI3WwgvKFAsQA=="
},
"node_modules/rehype-wrap-all/node_modules/bcp-47-match": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/bcp-47-match/-/bcp-47-match-1.0.3.tgz",
"integrity": "sha512-LggQ4YTdjWQSKELZF5JwchnBa1u0pIQSZf5lSdOHEdbVP55h0qICA/FUp3+W99q0xqxYa1ZQizTUH87gecII5w==",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/rehype-wrap-all/node_modules/comma-separated-tokens": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-1.0.8.tgz",
"integrity": "sha512-GHuDRO12Sypu2cV70d1dkA2EUmXHgntrzbpvOB+Qy+49ypNfGgFQIC2fhhXbnyrJRynDCAARsT7Ou0M6hirpfw==",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/rehype-wrap-all/node_modules/css-selector-parser": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/css-selector-parser/-/css-selector-parser-1.4.1.tgz",
"integrity": "sha512-HYPSb7y/Z7BNDCOrakL4raGO2zltZkbeXyAd6Tg9obzix6QhzxCotdBl6VT0Dv4vZfJGVz3WL/xaEI9Ly3ul0g=="
},
"node_modules/rehype-wrap-all/node_modules/direction": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/direction/-/direction-1.0.4.tgz",
"integrity": "sha512-GYqKi1aH7PJXxdhTeZBFrg8vUBeKXi+cNprXsC1kpJcbcVnV9wBsrOu1cQEdG0WeQwlfHiy3XvnKfIrJ2R0NzQ==",
"bin": {
"direction": "cli.js"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/rehype-wrap-all/node_modules/hast-util-has-property": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/hast-util-has-property/-/hast-util-has-property-1.0.4.tgz",
"integrity": "sha512-ghHup2voGfgFoHMGnaLHOjbYFACKrRh9KFttdCzMCbFoBMJXiNi2+XTrPP8+q6cDJM/RSqlCfVWrjp1H201rZg==",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/unified"
}
},
"node_modules/rehype-wrap-all/node_modules/hast-util-is-element": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/hast-util-is-element/-/hast-util-is-element-1.1.0.tgz",
"integrity": "sha512-oUmNua0bFbdrD/ELDSSEadRVtWZOf3iF6Lbv81naqsIV99RnSCieTbWuWCY8BAeEfKJTKl0gRdokv+dELutHGQ==",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/unified"
}
},
"node_modules/rehype-wrap-all/node_modules/hast-util-select": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/hast-util-select/-/hast-util-select-4.0.2.tgz",
"integrity": "sha512-8EEG2//bN5rrzboPWD2HdS3ugLijNioS1pqOTIolXNf67xxShYw4SQEmVXd3imiBG+U2bC2nVTySr/iRAA7Cjg==",
"dependencies": {
"bcp-47-match": "^1.0.0",
"comma-separated-tokens": "^1.0.0",
"css-selector-parser": "^1.0.0",
"direction": "^1.0.0",
"hast-util-has-property": "^1.0.0",
"hast-util-is-element": "^1.0.0",
"hast-util-to-string": "^1.0.0",
"hast-util-whitespace": "^1.0.0",
"not": "^0.1.0",
"nth-check": "^2.0.0",
"property-information": "^5.0.0",
"space-separated-tokens": "^1.0.0",
"unist-util-visit": "^2.0.0",
"zwitch": "^1.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/unified"
}
},
"node_modules/rehype-wrap-all/node_modules/hast-util-to-string": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/hast-util-to-string/-/hast-util-to-string-1.0.4.tgz",
"integrity": "sha512-eK0MxRX47AV2eZ+Lyr18DCpQgodvaS3fAQO2+b9Two9F5HEoRPhiUMNzoXArMJfZi2yieFzUBMRl3HNJ3Jus3w==",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/unified"
}
},
"node_modules/rehype-wrap-all/node_modules/hast-util-whitespace": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-1.0.4.tgz",
"integrity": "sha512-I5GTdSfhYfAPNztx2xJRQpG8cuDSNt599/7YUn7Gx/WxNMsG+a835k97TDkFgk123cwjfwINaZknkKkphx/f2A==",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/unified"
}
},
"node_modules/rehype-wrap-all/node_modules/property-information": {
"version": "5.6.0",
"resolved": "https://registry.npmjs.org/property-information/-/property-information-5.6.0.tgz",
"integrity": "sha512-YUHSPk+A30YPv+0Qf8i9Mbfe/C0hdPXk1s1jPVToV8pk8BQtpw10ct89Eo7OWkutrwqvT0eicAxlOg3dOAu8JA==",
"dependencies": {
"xtend": "^4.0.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/rehype-wrap-all/node_modules/space-separated-tokens": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-1.1.5.tgz",
"integrity": "sha512-q/JSVd1Lptzhf5bkYm4ob4iWPjx0KiRe3sRFBNrVqbJkFaBm5vbbowy1mymoPNLRa52+oadOhJ+K49wsSeSjTA==",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/rehype-wrap-all/node_modules/unist-util-is": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-4.1.0.tgz",
@ -5891,15 +5949,6 @@
"url": "https://opencollective.com/unified"
}
},
"node_modules/rehype-wrap-all/node_modules/zwitch": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/zwitch/-/zwitch-1.0.5.tgz",
"integrity": "sha512-V50KMwwzqJV0NpZIZFwfOD5/lyny3WlSzRiXgA0G7VUnRlqttta1L6UQIHzd6EuBY/cHGfwTIck7w1yH6Q5zUw==",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/remark-math": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/remark-math/-/remark-math-6.0.0.tgz",

View file

@ -2,7 +2,6 @@ import {
Cog6ToothIcon,
QuestionMarkCircleIcon,
} from "@heroicons/react/24/outline";
import { postToIde } from "core/ide/messaging";
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Outlet, useLocation, useNavigate } from "react-router-dom";
@ -13,6 +12,7 @@ import {
vscForeground,
vscInputBackground,
} from ".";
import { useWebviewListener } from "../hooks/useWebviewListener";
import { defaultModelSelector } from "../redux/selectors/modelSelectors";
import {
setBottomMessage,
@ -21,6 +21,7 @@ import {
} from "../redux/slices/uiStateSlice";
import { RootStore } from "../redux/store";
import { getFontSize, isMetaEquivalentKeyPressed } from "../util";
import { postToIde } from "../util/ide";
import HeaderButtonWithText from "./HeaderButtonWithText";
import TextDialog from "./dialogs";
import IndexingProgressBar from "./loaders/IndexingProgressBar";
@ -146,30 +147,35 @@ const Layout = () => {
};
}, [timeline]);
useEffect(() => {
const handler = (event: any) => {
if (event.data.type === "addModel") {
navigate("/models");
} else if (event.data.type === "openSettings") {
// navigate("/settings");
postToIde("openConfigJson", {});
} else if (event.data.type === "viewHistory") {
// Toggle the history page / main page
if (location.pathname === "/history") {
navigate("/");
} else {
navigate("/history");
}
} else if (event.data.type === "indexProgress") {
setIndexingProgress(event.data.progress);
setIndexingTask(event.data.desc);
useWebviewListener(
"addModel",
async () => {
navigate("/models");
},
[navigate]
);
useWebviewListener("openSettings", async () => {
postToIde("openConfigJson", undefined);
});
useWebviewListener(
"viewHistory",
async () => {
// Toggle the history page / main page
if (location.pathname === "/history") {
navigate("/");
} else {
navigate("/history");
}
};
window.addEventListener("message", handler);
return () => {
window.removeEventListener("message", handler);
};
}, [location, navigate]);
},
[location, navigate]
);
useWebviewListener("indexProgress", async (data) => {
setIndexingProgress(data.progress);
setIndexingTask(data.desc);
});
const [indexingProgress, setIndexingProgress] = useState(1);
const [indexingTask, setIndexingTask] = useState("Indexing Codebase");
@ -259,7 +265,7 @@ const Layout = () => {
<HeaderButtonWithText
onClick={() => {
// navigate("/settings");
postToIde("openConfigJson", {});
postToIde("openConfigJson", undefined);
}}
text="Config"
>

View file

@ -1,4 +1,3 @@
import { postToIde } from "core/ide/messaging";
import { usePostHog } from "posthog-js/react";
import React, { useContext, useLayoutEffect } from "react";
import { useDispatch } from "react-redux";
@ -6,6 +5,7 @@ import styled from "styled-components";
import { Button, Input } from "..";
import { SubmenuContextProvidersContext } from "../../App";
import { setShowDialog } from "../../redux/slices/uiStateSlice";
import { postToIde } from "../../util/ide";
const GridDiv = styled.div`
display: grid;
@ -58,7 +58,7 @@ function AddDocsDialog() {
disabled={!docsUrl || !urlValid}
className="ml-auto"
onClick={() => {
postToIde("addDocs", { url: docsUrl, title: docsTitle });
postToIde("context/addDocs", { url: docsUrl, title: docsTitle });
setDocsTitle("");
setDocsUrl("");
dispatch(setShowDialog(false));

View file

@ -5,7 +5,7 @@ import styled from "styled-components";
import { Button, Input } from "..";
import { setDefaultModel } from "../../redux/slices/stateSlice";
import { setShowDialog } from "../../redux/slices/uiStateSlice";
import { addOpenAIKey } from "../../util/ide";
import { postToIde } from "../../util/ide";
const GridDiv = styled.div`
display: grid;
@ -55,7 +55,7 @@ function FTCDialog() {
<Button
disabled={!apiKey}
onClick={() => {
addOpenAIKey(apiKey);
postToIde("config/addOpenAiKey", apiKey);
dispatch(setShowDialog(false));
dispatch(setDefaultModel("GPT-4"));
}}

View file

@ -55,19 +55,19 @@ function KeyboardShortcut(props: KeyboardShortcutProps) {
const vscodeShortcuts: KeyboardShortcutProps[] = [
{
mac: "⌘ M",
windows: "⌃ M",
description: "Ask about Highlighted Code",
mac: "⌘ L",
windows: "⌃ L",
description: "Select Code + New Session",
},
{
mac: "⌘ I",
windows: "⌃ I",
description: "Edit highlighted code",
},
{
mac: "⌘ ⇧ L",
windows: "⌃ ⇧ L",
description: "Edit highlighted code",
},
{
mac: "⌘ ⇧ M",
windows: "⌃ ⇧ M",
description: "Ask Follow-Up about Highlighted Code",
description: "Select Code",
},
{
mac: "⌘ ⇧ ⏎",
@ -92,12 +92,7 @@ const vscodeShortcuts: KeyboardShortcutProps[] = [
{
mac: "⌘ ⌫",
windows: "⌃ ⌫",
description: "Stop Active Step",
},
{
mac: "Tab",
windows: "Tab",
description: "Toggle between context items",
description: "Cancel response",
},
{
mac: "⌘ K ⌘ M",
@ -115,12 +110,12 @@ const jetbrainsShortcuts: KeyboardShortcutProps[] = [
{
mac: "⌘ J",
windows: "⌃ J",
description: "Ask about Highlighted Code",
description: "Select Code + New Session",
},
{
mac: "⌘ ⇧ J",
windows: "⌃ ⇧ J",
description: "Edit Highlighted Code",
description: "Select Code",
},
{
mac: "⌘ ⇧ ⏎",
@ -135,22 +130,17 @@ const jetbrainsShortcuts: KeyboardShortcutProps[] = [
{
mac: "⌥ ⇧ J",
windows: "⌥ ⇧ J",
description: "Quick Text Entry",
description: "Quick Input",
},
{
mac: "⌥ ⌘ J",
windows: "⌥ ⌃ J",
description: "Toggle Auxiliary Bar",
description: "Toggle Sidebar",
},
{
mac: "⌘ ⌫",
windows: "⌃ ⌫",
description: "Stop Active Step",
},
{
mac: "Tab",
windows: "Tab",
description: "Toggle between context items",
description: "Cancel respoonse",
},
{
mac: "⌘ '",

View file

@ -15,7 +15,7 @@ import {
} from "..";
import { RootStore } from "../../redux/store";
import { getFontSize } from "../../util";
import { logDevData } from "../../util/ide";
import { postToIde } from "../../util/ide";
import HeaderButtonWithText from "../HeaderButtonWithText";
import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview";
@ -70,7 +70,10 @@ function StepContainer(props: StepContainerProps) {
setFeedback(feedback);
if (props.item.promptLogs?.length) {
for (const [prompt, completion] of props.item.promptLogs) {
logDevData("chat", { prompt, completion, feedback });
postToIde("devdata/log", {
tableName: "chat",
data: { prompt, completion, feedback },
});
}
}
};

View file

@ -75,6 +75,26 @@ if (typeof document !== "undefined") {
}
}
export function parseHexColor(hexColor: string): {
r: number;
g: number;
b: number;
} {
if (hexColor.startsWith("#")) {
hexColor = hexColor.slice(1);
}
if (hexColor.length > 6) {
hexColor = hexColor.slice(0, 6);
}
const r = parseInt(hexColor.substring(0, 2), 16);
const g = parseInt(hexColor.substring(2, 4), 16);
const b = parseInt(hexColor.substring(4, 6), 16);
return { r, g, b };
}
export function parseColorForHex(colorVar: string): string {
const value = getComputedStyle(document.documentElement).getPropertyValue(
colorVar

View file

@ -1,7 +1,17 @@
import { useState } from "react";
import ReactDOM from "react-dom";
import styled from "styled-components";
import { StyledTooltip, lightGray, vscForeground } from "..";
const DIAMETER = 6;
const CircleDiv = styled.div`
background-color: #bb0;
box-shadow: 0px 0px 2px 1px #bb0;
width: ${DIAMETER}px;
height: ${DIAMETER}px;
border-radius: ${DIAMETER / 2}px;
`;
const ProgressBarWrapper = styled.div`
width: 100px;
height: 6px;
@ -52,22 +62,52 @@ const IndexingProgressBar = ({
const tooltipPortalDiv = document.getElementById("tooltip-portal-div");
const [expanded, setExpanded] = useState(true);
const [hovered, setHovered] = useState(false);
return (
<>
<GridDiv data-tooltip-id="usage_progress_bar">
<ProgressBarWrapper>
<ProgressBarFill completed={fillPercentage} />
</ProgressBarWrapper>
<P>Indexing ({Math.trunc((completed / total) * 100)}%)</P>
</GridDiv>
{tooltipPortalDiv &&
ReactDOM.createPortal(
<StyledTooltip id="usage_progress_bar" place="top">
{currentlyIndexing}
</StyledTooltip>,
tooltipPortalDiv
)}
</>
<div
onClick={() => setExpanded((prev) => !prev)}
className="cursor-pointer"
>
{expanded ? (
<>
<GridDiv
data-tooltip-id="usage_progress_bar"
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
>
<ProgressBarWrapper>
<ProgressBarFill completed={fillPercentage} />
</ProgressBarWrapper>
<P>
{hovered
? "Click to pause"
: `Indexing (${Math.trunc((completed / total) * 100)}%)`}
</P>
</GridDiv>
{tooltipPortalDiv &&
ReactDOM.createPortal(
<StyledTooltip id="usage_progress_bar" place="top">
{currentlyIndexing}
</StyledTooltip>,
tooltipPortalDiv
)}
</>
) : (
<>
<CircleDiv data-tooltip-id="progress_dot"></CircleDiv>
{tooltipPortalDiv &&
ReactDOM.createPortal(
<StyledTooltip id="progress_dot" place="top">
Click to unpause indexing (
{Math.trunc((completed / total) * 100)}%)
</StyledTooltip>,
tooltipPortalDiv
)}
</>
)}
</div>
);
};

View file

@ -21,7 +21,7 @@ const CodeBlockComponent = ({
(state: RootStore) => state.state.contextItems
);
return (
<NodeViewWrapper className="code-block-with-content" as="pre">
<NodeViewWrapper className="code-block-with-content" as="p">
<CodeSnippetPreview
borderColor={
item.id === contextItems[0]?.id

View file

@ -1,7 +1,6 @@
import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/outline";
import { ContextItemWithId } from "core";
import { contextItemToRangeInFileWithContents } from "core/commands/util";
import { ExtensionIde } from "core/ide";
import React from "react";
import styled from "styled-components";
import {
@ -10,6 +9,7 @@ import {
vscBackground,
vscForeground,
} from "..";
import { WebviewIde } from "../../util/webviewIde";
import FileIcon from "../FileIcon";
const ContextItemDiv = styled.div`
@ -49,16 +49,16 @@ const ContextItemsPeek = (props: ContextItemsPeekProps) => {
) {
if (contextItem.name.includes(" (") && contextItem.name.endsWith(")")) {
const rif = contextItemToRangeInFileWithContents(contextItem);
new ExtensionIde().showLines(
new WebviewIde().showLines(
rif.filepath,
rif.range.start.line,
rif.range.end.line
);
} else {
new ExtensionIde().openFile(contextItem.description);
new WebviewIde().openFile(contextItem.description);
}
} else {
new ExtensionIde().showVirtualFile(contextItem.name, contextItem.content);
new WebviewIde().showVirtualFile(contextItem.name, contextItem.content);
}
}

View file

@ -1,9 +1,10 @@
import { JSONContent } from "@tiptap/react";
import { ContextItemWithId } from "core";
import { useEffect, useState } from "react";
import { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import styled, { keyframes } from "styled-components";
import { defaultBorderRadius, vscBackground } from "..";
import { useWebviewListener } from "../../hooks/useWebviewListener";
import { selectSlashCommands } from "../../redux/selectors";
import { newSession, setMessageAtIndex } from "../../redux/slices/stateSlice";
import { RootStore } from "../../redux/store";
@ -70,24 +71,21 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
const [editorState, setEditorState] = useState(props.editorState);
useEffect(() => {
const listener = (e) => {
if (e.data.type === "newSessionWithPrompt" && props.isMainInput) {
useWebviewListener(
"newSessionWithPrompt",
async (data) => {
if (props.isMainInput) {
dispatch(newSession());
dispatch(
setMessageAtIndex({
message: { role: "user", content: e.data.prompt },
message: { role: "user", content: data.prompt },
index: 0,
})
);
}
};
window.addEventListener("message", listener);
return () => {
window.removeEventListener("message", listener);
};
}, []);
},
[props.isMainInput]
);
return (
<div

View file

@ -26,10 +26,11 @@ import {
import { SubmenuContextProvidersContext } from "../../App";
import useHistory from "../../hooks/useHistory";
import useUpdatingRef from "../../hooks/useUpdatingRef";
import { useWebviewListener } from "../../hooks/useWebviewListener";
import { setEditingContextItemAtIndex } from "../../redux/slices/stateSlice";
import { RootStore } from "../../redux/store";
import { isMetaEquivalentKeyPressed } from "../../util";
import { errorPopup, isJetBrains, postToIde } from "../../util/ide";
import { isJetBrains, postToIde } from "../../util/ide";
import CodeBlockExtension from "./CodeBlockExtension";
import { SlashCommand } from "./CommandsExtension";
import InputToolbar from "./InputToolbar";
@ -218,14 +219,15 @@ function TipTapEditor(props: TipTapEditorProps) {
};
});
} else {
errorPopup(
"Images need to be in jpg or png format and less than 10MB in size."
);
postToIde("errorPopup", {
message:
"Images need to be in jpg or png format and less than 10MB in size.",
});
}
return undefined;
}
const editor = useEditor({
const editor: Editor = useEditor({
extensions: [
Document,
History,
@ -233,7 +235,7 @@ function TipTapEditor(props: TipTapEditorProps) {
Placeholder.configure({
placeholder: () =>
historyLengthRef.current === 0
? "Ask a question, '/' for slash commands, '@' to add context"
? "Ask anything, '/' for slash commands, '@' to add context"
: "Ask a follow-up",
}),
Paragraph.extend({
@ -358,7 +360,7 @@ function TipTapEditor(props: TipTapEditorProps) {
setIgnoreHighlightedCode(false);
}, 100);
} else if (event.key === "Escape") {
postToIde("focusEditor", {});
postToIde("focusEditor", undefined);
}
};
@ -370,6 +372,109 @@ function TipTapEditor(props: TipTapEditorProps) {
}, []);
// IDE event listeners
useWebviewListener(
"userInput",
async (data) => {
if (!props.isMainInput) {
return;
}
editor?.commands.insertContent(data.input);
onEnterRef.current(editor.getJSON());
},
[editor, onEnterRef.current, props.isMainInput]
);
useWebviewListener(
"focusContinueInput",
async (data) => {
if (!props.isMainInput) {
return;
}
if (historyLength > 0) {
saveSession();
}
editor?.commands.focus("end");
},
[historyLength, saveSession, editor, props.isMainInput]
);
useWebviewListener(
"focusContinueInputWithoutClear",
async () => {
if (!props.isMainInput) {
return;
}
editor?.commands.focus("end");
},
[editor, props.isMainInput]
);
useWebviewListener(
"focusContinueInputWithNewSession",
async () => {
if (!props.isMainInput) {
return;
}
saveSession();
editor?.commands.focus("end");
},
[editor, props.isMainInput]
);
useWebviewListener(
"highlightedCode",
async (data) => {
if (!props.isMainInput || !editor) {
return;
}
if (!ignoreHighlightedCode) {
const rif: RangeInFile & { contents: string } =
data.rangeInFileWithContents;
const basename = getBasename(rif.filepath);
const item: ContextItemWithId = {
content: rif.contents,
name: `${basename} (${rif.range.start.line + 1}-${
rif.range.end.line + 1
})`,
description: rif.filepath,
id: {
providerTitle: "code",
itemId: rif.filepath,
},
};
let index = 0;
for (const el of editor.getJSON().content) {
if (el.type === "codeBlock") {
index += 2;
} else {
break;
}
}
editor
.chain()
.insertContentAt(index, {
type: "codeBlock",
attrs: {
item,
},
})
.run();
setTimeout(() => {
editor.commands.focus("end");
}, 100);
}
setIgnoreHighlightedCode(false);
},
[
editor,
props.isMainInput,
historyLength,
ignoreHighlightedCode,
props.isMainInput,
]
);
useEffect(() => {
if (!props.isMainInput) {
return;
@ -382,69 +487,6 @@ function TipTapEditor(props: TipTapEditorProps) {
// editor.commands.blur();
// }, 0);
}
const handler = async (event: any) => {
if (!editor) return;
if (event.data.type === "userInput") {
const input = event.data.input;
editor.commands.insertContent(input);
onEnterRef.current(editor.getJSON());
} else if (event.data.type === "focusContinueInput") {
if (historyLength > 0) {
saveSession();
}
editor.commands.focus("end");
} else if (event.data.type === "focusContinueInputWithoutClear") {
editor.commands.focus("end");
} else if (event.data.type === "focusContinueInputWithNewSession") {
saveSession();
editor.commands.focus("end");
} else if (event.data.type === "highlightedCode") {
if (!ignoreHighlightedCode) {
const rif: RangeInFile & { contents: string } =
event.data.rangeInFileWithContents;
const basename = getBasename(rif.filepath);
const item: ContextItemWithId = {
content: rif.contents,
name: `${basename} (${rif.range.start.line + 1}-${
rif.range.end.line + 1
})`,
description: rif.filepath,
id: {
providerTitle: "code",
itemId: rif.filepath,
},
};
let index = 0;
for (const el of editor.getJSON().content) {
if (el.type === "codeBlock") {
index += 2;
} else {
break;
}
}
editor
.chain()
.insertContentAt(index, {
type: "codeBlock",
attrs: {
item,
},
})
.run();
setTimeout(() => {
editor.commands.focus("end");
}, 100);
}
setIgnoreHighlightedCode(false);
}
};
window.addEventListener("message", handler);
return () => {
window.removeEventListener("message", handler);
};
}, [editor, props.isMainInput, historyLength, ignoreHighlightedCode]);
const [showDragOverMsg, setShowDragOverMsg] = useState(false);

View file

@ -5,10 +5,10 @@ import {
MessagePart,
RangeInFile,
} from "core";
import { ExtensionIde } from "core/ide";
import { ideRequest } from "core/ide/messaging";
import { stripImages } from "core/llm/countTokens";
import { getBasename } from "core/util";
import { ideRequest } from "../../util/ide";
import { WebviewIde } from "../../util/webviewIde";
interface MentionAttrs {
label: string;
@ -26,7 +26,7 @@ interface MentionAttrs {
async function resolveEditorContent(
editorState: JSONContent
): Promise<[ContextItemWithId[], MessageContent]> {
): Promise<[ContextItemWithId[], RangeInFile[], MessageContent]> {
let parts: MessagePart[] = [];
let contextItemAttrs: MentionAttrs[] = [];
const selectedCode: RangeInFile[] = [];
@ -87,7 +87,7 @@ async function resolveEditorContent(
let contextItemsText = "";
let contextItems: ContextItemWithId[] = [];
const ide = new ExtensionIde();
const ide = new WebviewIde();
for (const item of contextItemAttrs) {
if (item.itemType === "file") {
// This is a quick way to resolve @file references
@ -110,10 +110,7 @@ async function resolveEditorContent(
fullInput: stripImages(parts),
selectedCode,
};
const { items: resolvedItems } = await ideRequest(
"getContextItems",
data
);
const resolvedItems = await ideRequest("context/getContextItems", data);
contextItems.push(...resolvedItems);
for (const resolvedItem of resolvedItems) {
contextItemsText += resolvedItem.content + "\n\n";
@ -130,7 +127,7 @@ async function resolveEditorContent(
parts[lastTextIndex].text = `${slashCommand} ${parts[lastTextIndex].text}`;
}
return [contextItems, parts];
return [contextItems, selectedCode, parts];
}
function findLastIndex<T>(

View file

@ -3,10 +3,10 @@ import {
ClipboardIcon,
PlayIcon,
} from "@heroicons/react/24/outline";
import { postToIde } from "core/ide/messaging";
import { useState } from "react";
import styled from "styled-components";
import { vscEditorBackground } from "..";
import { postToIde } from "../../util/ide";
import HeaderButtonWithText from "../HeaderButtonWithText";
const TopDiv = styled.div`

View file

@ -5,13 +5,13 @@ import {
XMarkIcon,
} from "@heroicons/react/24/outline";
import { ContextItemWithId } from "core";
import { ExtensionIde } from "core/ide";
import { getMarkdownLanguageTagForFile } from "core/util";
import React from "react";
import styled from "styled-components";
import { defaultBorderRadius, lightGray, vscEditorBackground } from "..";
import { getFontSize } from "../../util";
import { postToIde } from "../../util/ide";
import { WebviewIde } from "../../util/webviewIde";
import FileIcon from "../FileIcon";
import HeaderButtonWithText from "../HeaderButtonWithText";
import StyledMarkdownPreview from "./StyledMarkdownPreview";
@ -90,7 +90,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
.split("(")[1]
.split(")")[0]
.split("-");
new ExtensionIde().showLines(
new WebviewIde().showLines(
props.item.description,
parseInt(lines[0]) - 1,
parseInt(lines[1]) - 1
@ -137,6 +137,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
</div>
</PreviewMarkdownHeader>
<div
contentEditable={false}
className="m-0"
ref={codeBlockRef}
style={{

View file

@ -22,7 +22,7 @@ import { defaultModelSelector } from "../../redux/selectors/modelSelectors";
import { setDefaultModel } from "../../redux/slices/stateSlice";
import { RootStore } from "../../redux/store";
import { getMetaKeyLabel, isMetaEquivalentKeyPressed } from "../../util";
import { deleteModel } from "../../util/ide";
import { postToIde } from "../../util/ide";
import HeaderButtonWithText from "../HeaderButtonWithText";
const GridDiv = styled.div`
@ -34,24 +34,6 @@ const GridDiv = styled.div`
overflow: hidden;
`;
const Select = styled.select`
border: none;
max-width: 50vw;
background-color: ${vscBackground};
color: ${vscForeground};
padding: 6px;
max-height: 35vh;
overflow: scroll;
cursor: pointer;
&:focus {
outline: none;
}
&:hover {
background-color: ${vscInputBackground};
}
`;
const StyledPlusIcon = styled(PlusIcon)`
background-color: ${vscBackground};
cursor: pointer;
@ -66,18 +48,6 @@ const StyledPlusIcon = styled(PlusIcon)`
border-left: 0.5px solid ${lightGray};
`;
const NewProviderDiv = styled.div`
cursor: pointer;
padding: 8px;
padding-left: 16px;
padding-right: 16px;
border-top: 0.5px solid ${lightGray};
&:hover {
background-color: ${vscInputBackground};
}
`;
const StyledListbox = styled(Listbox)`
background-color: ${vscBackground};
padding: 0;
@ -124,7 +94,7 @@ const StyledListboxOptions = styled(Listbox.Options)`
max-height: 80vh;
border-radius: ${defaultBorderRadius};
overflow: scroll;
overflow-y: scroll;
`;
const StyledListboxOption = styled(Listbox.Option)<{ selected: boolean }>`
@ -174,7 +144,7 @@ function ListBoxOption({
<HeaderButtonWithText
text="Delete"
onClick={(e) => {
deleteModel(option.title);
postToIde("config/deleteModel", { title: option.title });
e.stopPropagation();
e.preventDefault();
}}

View file

@ -7,9 +7,9 @@ import {
ChatMessage,
LLMReturnValue,
MessageContent,
RangeInFile,
SlashCommandDescription,
} from "core";
import { ideStreamRequest, llmStreamChat } from "core/ide/messaging";
import { constructMessages } from "core/llm/constructMessages";
import { stripImages } from "core/llm/countTokens";
import { usePostHog } from "posthog-js/react";
@ -26,7 +26,7 @@ import {
streamUpdate,
} from "../redux/slices/stateSlice";
import { RootStore } from "../redux/store";
import { errorPopup } from "../util/ide";
import { ideStreamRequest, llmStreamChat, postToIde } from "../util/ide";
function useChatHandler(dispatch: Dispatch) {
const posthog = usePostHog();
@ -98,14 +98,15 @@ function useChatHandler(dispatch: Dispatch) {
messages: ChatMessage[],
slashCommand: SlashCommandDescription,
input: string,
historyIndex: number
historyIndex: number,
selectedCode: RangeInFile[]
) {
const abortController = new AbortController();
const cancelToken = abortController.signal;
const modelTitle = defaultModel.title;
for await (const update of ideStreamRequest(
"runNodeJsSlashCommand",
"command/run",
{
input,
history: messages,
@ -114,6 +115,7 @@ function useChatHandler(dispatch: Dispatch) {
contextItems,
params: slashCommand.params,
historyIndex,
selectedCode,
},
cancelToken
)) {
@ -136,8 +138,9 @@ function useChatHandler(dispatch: Dispatch) {
}
// Resolve context providers and construct new history
const [contextItems, content] = await resolveEditorContent(editorState);
console.log(contextItems, content);
const [contextItems, selectedCode, content] =
await resolveEditorContent(editorState);
const message: ChatMessage = {
role: "user",
content,
@ -193,12 +196,15 @@ function useChatHandler(dispatch: Dispatch) {
messages,
slashCommand,
commandInput,
historyIndex
historyIndex,
selectedCode
);
}
} catch (e) {
console.log("Continue: error streaming response: ", e);
errorPopup(`Error streaming response: ${e.message}`);
postToIde("errorPopup", {
message: `Error streaming response: ${e.message}`,
});
} finally {
dispatch(setInactive());
}

View file

@ -1,12 +1,13 @@
import { Dispatch } from "@reduxjs/toolkit";
import { PersistedSessionInfo, SessionInfo } from "core";
import { ideRequest, llmStreamChat } from "core/ide/messaging";
import { llmCanGenerateInParallel } from "core/llm/autodetect";
import { stripImages } from "core/llm/countTokens";
import { useSelector } from "react-redux";
import { defaultModelSelector } from "../redux/selectors/modelSelectors";
import { newSession } from "../redux/slices/stateSlice";
import { RootStore } from "../redux/store";
import { ideRequest } from "../util/ide";
function truncateText(text: string, maxLength: number) {
if (text.length > maxLength) {
@ -23,7 +24,7 @@ function useHistory(dispatch: Dispatch) {
);
async function getHistory(): Promise<SessionInfo[]> {
return await ideRequest("history", {});
return await ideRequest("history/list", undefined);
}
async function saveSession() {
@ -46,24 +47,23 @@ function useHistory(dispatch: Dispatch) {
!disableSessionTitles &&
llmCanGenerateInParallel(defaultModel.provider, defaultModel.model)
) {
let fullContent = "";
for await (const { content } of llmStreamChat(
defaultModel.title,
undefined,
[
...stateCopy.history.map((item) => item.message),
{
role: "user",
content:
"Give a maximum 40 character title to describe this conversation so far. The title should help me recall the conversation if I look for it later. DO NOT PUT QUOTES AROUND THE TITLE",
},
],
{ maxTokens: 20 }
)) {
fullContent += content;
}
title = stripImages(fullContent);
// let fullContent = "";
// for await (const { content } of llmStreamChat(
// defaultModel.title,
// undefined,
// [
// ...stateCopy.history.map((item) => item.message),
// {
// role: "user",
// content:
// "Give a maximum 40 character title to describe this conversation so far. The title should help me recall the conversation if I look for it later. DO NOT PUT QUOTES AROUND THE TITLE",
// },
// ],
// { maxTokens: 20 }
// )) {
// fullContent += content;
// }
// title = stripImages(fullContent);
}
const sessionInfo: PersistedSessionInfo = {
@ -72,15 +72,15 @@ function useHistory(dispatch: Dispatch) {
sessionId: stateCopy.sessionId,
workspaceDirectory: window.workspacePaths?.[0] || "",
};
return await ideRequest("saveSession", sessionInfo);
return await ideRequest("history/save", sessionInfo);
}
async function deleteSession(sessionId: string) {
return await ideRequest("deleteSession", sessionId);
async function deleteSession(id: string) {
return await ideRequest("history/delete", { id });
}
async function loadSession(sessionId: string): Promise<PersistedSessionInfo> {
return await ideRequest("loadSession", sessionId);
async function loadSession(id: string): Promise<PersistedSessionInfo> {
return await ideRequest("history/load", { id });
}
return { getHistory, saveSession, deleteSession, loadSession };

View file

@ -1,7 +1,9 @@
import { useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { ReverseWebviewProtocol } from "core/web/webviewProtocol";
import { useLocation, useNavigate } from "react-router-dom";
import { v4 as uuidv4 } from "uuid";
import { useWebviewListener } from "./useWebviewListener";
const openGUITypes = [
const openGUITypes: (keyof ReverseWebviewProtocol)[] = [
"highlightedCode",
"newSessionWithPrompt",
"focusContinueInput",
@ -13,30 +15,36 @@ export const useNavigationListener = () => {
const navigate = useNavigate();
const location = useLocation();
useEffect(() => {
const listener = (e) => {
if(openGUITypes.includes(e.data.type)) {
for (const messageType of openGUITypes) {
useWebviewListener(
messageType,
async (data) => {
navigate("/");
setTimeout(() => {
window.postMessage(e.data, "*");
window.postMessage(
{
messageType,
data,
messageId: uuidv4(),
},
"*"
);
}, 200);
},
[navigate]
);
}
useWebviewListener(
"viewHistory",
async () => {
// Toggle the history page / main page
if (location.pathname === "/history") {
navigate("/");
} else {
navigate("/history");
}
if(e.data.type === "viewHistory") {
// Toggle the history page / main page
if (location.pathname === "/history") {
navigate("/");
} else {
navigate("/history");
}
}
};
window.addEventListener("message", listener);
return () => {
window.removeEventListener("message", listener);
};
}, [navigate]);
}
},
[location, navigate]
);
};

View file

@ -1,9 +1,5 @@
import { Dispatch } from "@reduxjs/toolkit";
import { useEffect } from "react";
import { setServerStatusMessage } from "../redux/slices/miscSlice";
import { isJetBrains, postToIde } from "../util/ide";
import { ExtensionIde } from "core/ide/index";
import { useSelector } from "react-redux";
import { VSC_THEME_COLOR_VARS } from "../components";
import { setVscMachineId } from "../redux/slices/configSlice";
@ -13,11 +9,14 @@ import {
setInactive,
} from "../redux/slices/stateSlice";
import { RootStore } from "../redux/store";
import { ideRequest, isJetBrains } from "../util/ide";
import useChatHandler from "./useChatHandler";
import { useWebviewListener } from "./useWebviewListener";
function useSetup(dispatch: Dispatch<any>) {
const loadConfig = async () => {
dispatch(setConfig(await new ExtensionIde().getSerializedConfig()));
const config = await ideRequest("config/getBrowserSerialized", undefined);
dispatch(setConfig(config));
};
// Load config from the IDE
@ -30,7 +29,15 @@ function useSetup(dispatch: Dispatch<any>) {
dispatch(setInactive());
// Tell JetBrains the webview is ready
postToIde("onLoad", {});
ideRequest("onLoad", undefined).then((msg) => {
(window as any).windowId = msg.windowId;
(window as any).serverUrl = msg.serverUrl;
(window as any).workspacePaths = msg.workspacePaths;
(window as any).vscMachineId = msg.vscMachineId;
(window as any).vscMediaUrl = msg.vscMediaUrl;
dispatch(setVscMachineId(msg.vscMachineId));
// dispatch(setVscMediaUrl(msg.vscMediaUrl));
});
}, []);
const { streamResponse } = useChatHandler(dispatch);
@ -40,47 +47,40 @@ function useSetup(dispatch: Dispatch<any>) {
);
// IDE event listeners
useEffect(() => {
const eventListener = (event: any) => {
switch (event.data.type) {
case "onLoad":
window.windowId = event.data.windowId;
window.serverUrl = event.data.serverUrl;
window.workspacePaths = event.data.workspacePaths;
window.vscMachineId = event.data.vscMachineId;
window.vscMediaUrl = event.data.vscMediaUrl;
dispatch(setVscMachineId(event.data.vscMachineId));
// dispatch(setVscMediaUrl(event.data.vscMediaUrl));
useWebviewListener("setInactive", async () => {
dispatch(setInactive());
});
break;
case "serverStatus":
dispatch(setServerStatusMessage(event.data.message));
break;
case "setInactive":
dispatch(setInactive());
break;
case "configUpdate":
loadConfig();
break;
case "submitMessage":
streamResponse(event.data.message);
break;
case "addContextItem":
dispatch(
addContextItemsAtIndex({
index: event.data.message.historyIndex,
contextItems: [event.data.message.item],
})
);
break;
case "getDefaultModelTitle":
postToIde("getDefaultModelTitle", { defaultModelTitle });
break;
}
};
window.addEventListener("message", eventListener);
return () => window.removeEventListener("message", eventListener);
}, [defaultModelTitle]);
useWebviewListener("setColors", async (colors) => {
Object.keys(colors).forEach((key) => {
document.body.style.setProperty(key, colors[key]);
});
});
useWebviewListener("configUpdate", async () => {
loadConfig();
});
useWebviewListener("submitMessage", async (data) => {
streamResponse(data.message);
});
useWebviewListener("addContextItem", async (data) => {
dispatch(
addContextItemsAtIndex({
index: data.historyIndex,
contextItems: [data.item],
})
);
});
useWebviewListener(
"getDefaultModelTitle",
async () => {
return defaultModelTitle;
},
[defaultModelTitle]
);
// Save theme colors to local storage for immediate loading in JetBrains
useEffect(() => {

View file

@ -1,11 +1,12 @@
import { ContextSubmenuItem } from "core";
import { ExtensionIde } from "core/ide";
import { ideRequest } from "core/ide/messaging";
import { getBasename, getLastNPathParts } from "core/util";
import MiniSearch, { SearchResult } from "minisearch";
import { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { selectContextProviderDescriptions } from "../redux/selectors";
import { ideRequest } from "../util/ide";
import { WebviewIde } from "../util/webviewIde";
import { useWebviewListener } from "./useWebviewListener";
const MINISEARCH_OPTIONS = {
prefix: true,
@ -29,7 +30,7 @@ function useSubmenuContextProviders() {
const [loaded, setLoaded] = useState(false);
async function getOpenFileItems() {
const openFiles = await new ExtensionIde().getOpenFiles();
const openFiles = await new WebviewIde().getOpenFiles();
return openFiles.map((file) => {
return {
id: file,
@ -40,18 +41,9 @@ function useSubmenuContextProviders() {
});
}
useEffect(() => {
const handler = (e) => {
if (e.data.type !== "refreshSubmenuItems") {
return;
}
setLoaded(false);
};
window.addEventListener("message", handler);
return () => {
window.removeEventListener("message", handler);
};
}, []);
useWebviewListener("refreshSubmenuItems", async (data) => {
setLoaded(true);
});
function addItem(providerTitle: string, item: ContextSubmenuItem) {
if (!minisearches[providerTitle]) {
@ -82,7 +74,7 @@ function useSubmenuContextProviders() {
fields: ["title"],
storeFields: ["id", "title", "description"],
});
const { items } = await ideRequest("loadSubmenuItems", {
const items = await ideRequest("context/loadSubmenuItems", {
title: description.title,
});
minisearch.addAll(items);

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