🚧 progress, organizing, about to remove webviewCore protocol

This commit is contained in:
Nate Sesti 2024-04-30 21:48:48 -07:00
parent 298181a507
commit 2cb68a06d6
14 changed files with 514 additions and 651 deletions

View file

@ -2,18 +2,26 @@ import { v4 as uuidv4 } from "uuid";
import type { ContextItemId, IDE } from ".";
import { CompletionProvider } from "./autocomplete/completionProvider";
import { ConfigHandler } from "./config/handler";
import {
setupLocalMode,
setupOptimizedExistingUserMode,
setupOptimizedMode,
} from "./config/onboarding";
import { addModel, addOpenAIKey, deleteModel } from "./config/util";
import { indexDocs } from "./indexing/docs";
import TransformersJsEmbeddingsProvider from "./indexing/embeddings/TransformersJsEmbeddingsProvider";
import { CodebaseIndexer, PauseToken } from "./indexing/indexCodebase";
import { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import { logDevData } from "./util/devdata";
import { DevDataSqliteDb } from "./util/devdataSqlite";
import historyManager from "./util/history";
import type { IMessenger, Message } from "./util/messenger";
import { editConfigJson, getConfigJsonPath } from "./util/paths";
import { Telemetry } from "./util/posthog";
import { streamDiffLines } from "./util/verticalEdit";
export class Core {
// implements IMessenger<ToCoreProtocol, FromCoreProtocol>
configHandler: ConfigHandler;
codebaseIndexer: CodebaseIndexer;
completionProvider: CompletionProvider;
@ -115,13 +123,46 @@ export class Core {
// Edit config
on("config/addModel", (msg) => {
addModel(msg.data.model);
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
const lines = newConfigString.split("\n");
let startLine: number | undefined;
let endLine: number | undefined;
for (let i = 0; i < lines.length; i++) {
const 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"
);
}
});
on("config/addOpenAiKey", (msg) => {
addOpenAIKey(msg.data);
this.configHandler.reloadConfig();
});
on("config/deleteModel", (msg) => {
deleteModel(msg.data.title);
this.configHandler.reloadConfig();
});
on("config/reload", (msg) => {
this.configHandler.reloadConfig();
@ -139,43 +180,66 @@ export class Core {
new TransformersJsEmbeddingsProvider(),
)) {
}
this.ide.infoPopup(`🎉 Successfully indexed ${msg.data.title}`);
this.messenger.send("refreshSubmenuItems", undefined);
});
on("context/loadSubmenuItems", async (msg) => {
const config = await this.config();
const items = config.contextProviders
?.find((provider) => provider.description.title === msg.data.title)
?.loadSubmenuItems({ ide: this.ide });
return items || [];
const { title } = msg.data;
const config = await this.configHandler.loadConfig();
const provider = config.contextProviders?.find(
(p) => p.description.title === title,
);
if (!provider) {
throw new Error(
`Unknown provider ${title}. Existing providers: ${config.contextProviders
?.map((p) => p.description.title)
.join(", ")}`,
);
}
try {
const items = await provider.loadSubmenuItems({ ide });
return items;
} catch (e) {
this.ide.errorPopup(`Error loading submenu items from ${title}: ${e}`);
return [];
}
});
on("context/getContextItems", async (msg) => {
const { name, query, fullInput, selectedCode } = msg.data;
const config = await this.config();
const llm = await this.getSelectedModel();
const provider = config.contextProviders?.find(
(provider) => provider.description.title === msg.data.name,
(provider) => provider.description.title === name,
);
if (!provider) return [];
const id: ContextItemId = {
providerTitle: provider.description.title,
itemId: uuidv4(),
};
const items = await provider.getContextItems(msg.data.query, {
llm,
embeddingsProvider: config.embeddingsProvider,
fullInput: msg.data.fullInput,
ide,
selectedCode: msg.data.selectedCode,
reranker: config.reranker,
});
try {
const id: ContextItemId = {
providerTitle: provider.description.title,
itemId: uuidv4(),
};
const items = await provider.getContextItems(query, {
llm,
embeddingsProvider: config.embeddingsProvider,
fullInput,
ide,
selectedCode,
reranker: config.reranker,
});
Telemetry.capture("useContextProvider", {
name: provider.description.title,
});
Telemetry.capture("useContextProvider", {
name: provider.description.title,
});
return items.map((item) => ({
...item,
id,
}));
return items.map((item) => ({
...item,
id,
}));
} catch (e) {
this.ide.errorPopup(`Error getting context items from ${name}: ${e}`);
return [];
}
});
on("config/getBrowserSerialized", (msg) => {
@ -239,6 +303,15 @@ export class Core {
llmStreamComplete(this.configHandler, this.abortedMessageIds, msg),
);
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(
configHandler: ConfigHandler,
abortedMessageIds: Set<string>,
@ -338,5 +411,31 @@ export class Core {
on("streamDiffLines", (msg) =>
streamDiffLinesGenerator(this.configHandler, this.abortedMessageIds, msg),
);
on("completeOnboarding", (msg) => {
const mode = msg.data.mode;
Telemetry.capture("onboardingSelection", {
mode,
});
if (mode === "custom" || mode === "localExistingUser") {
return;
}
editConfigJson(
mode === "local"
? setupLocalMode
: mode === "optimized"
? setupOptimizedMode
: setupOptimizedExistingUserMode,
);
});
on("stats/getTokensPerDay", async (msg) => {
const rows = await DevDataSqliteDb.getTokensPerDay();
return rows;
});
on("stats/getTokensPerModel", async (msg) => {
const rows = await DevDataSqliteDb.getTokensPerModel();
return rows;
});
}
}

2
core/index.d.ts vendored
View file

@ -412,6 +412,8 @@ export interface IDE {
getStats(directory: string): Promise<{ [path: string]: number }>;
getTags(artifactId: string): Promise<IndexTag[]>;
getRepoName(dir: string): Promise<string | undefined>;
errorPopup(message: string): Promise<void>;
infoPopup(message: string): Promise<void>;
}
// Slash Commands

View file

@ -80,7 +80,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
completionOptions: LLMFullCompletionOptions;
title: string;
},
string,
Promise<string>,
];
"llm/streamComplete": [
{
@ -109,8 +109,14 @@ export type ToCoreFromIdeOrWebviewProtocol = {
},
ProtocolGeneratorType<DiffLine>,
];
"stats/getTokensPerDay": [undefined, { day: string; tokens: number }[]];
"stats/getTokensPerModel": [undefined, { model: string; tokens: number }[]];
"stats/getTokensPerDay": [
undefined,
Promise<{ day: string; tokens: number }[]>,
];
"stats/getTokensPerModel": [
undefined,
Promise<{ model: string; tokens: number }[]>,
];
"index/setPaused": [boolean, void];
"index/forceReIndex": [undefined, void];
completeOnboarding: [

View file

@ -56,10 +56,12 @@ export type ToIdeFromWebviewOrCoreProtocol = {
getTags: [string, IndexTag[]];
// end methods from IDE type
errorPopup: [{ message: string }, void];
getIdeSettings: [undefined, IdeSettings];
// Git
getBranch: [{ dir: string }, string];
getRepoName: [{ dir: string }, string | undefined];
errorPopup: [{ message: string }, void];
infoPopup: [{ message: string }, void];
};

View file

@ -58,7 +58,6 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
openSettings: [undefined, void];
viewHistory: [undefined, void];
newSession: [undefined, void];
refreshSubmenuItems: [undefined, void];
setTheme: [{ theme: any }, void];
setColors: [{ [key: string]: string }, void];
"jetbrains/editorInsetRefresh": [undefined, void];

View file

@ -2,4 +2,5 @@ export type ToWebviewFromIdeOrCoreProtocol = {
configUpdate: [undefined, void];
getDefaultModelTitle: [undefined, string];
indexProgress: [{ progress: number; desc: string }, void];
refreshSubmenuItems: [undefined, void];
};

View file

@ -12,6 +12,12 @@ import type {
import { getContinueGlobalPath } from "./paths";
class FileSystemIde implements IDE {
infoPopup(message: string): Promise<void> {
return Promise.resolve();
}
errorPopup(message: string): Promise<void> {
return Promise.resolve();
}
getRepoName(dir: string): Promise<string | undefined> {
return Promise.resolve(undefined);
}

View file

@ -17,6 +17,14 @@ export class MessageIde implements IDE {
) => Promise<ToIdeFromWebviewOrCoreProtocol[T][1]>,
) {}
infoPopup(message: string): Promise<void> {
return this.request("errorPopup", { message });
}
errorPopup(message: string): Promise<void> {
return this.request("errorPopup", { message });
}
getRepoName(dir: string): Promise<string | undefined> {
return this.request("getRepoName", { dir });
}

View file

@ -40,6 +40,7 @@ export interface IMessenger<
invoke<T extends keyof ToProtocol>(
messageType: T,
data: ToProtocol[T][0],
messageId?: string,
): ToProtocol[T][1];
}
@ -48,11 +49,18 @@ export class InProcessMessenger<
FromProtocol extends IProtocol,
> implements IMessenger<ToProtocol, FromProtocol>
{
protected typeListeners = new Map<
// Listeners for the entity that owns this messenger (right now, always Core)
protected myTypeListeners = new Map<
keyof ToProtocol,
((message: Message) => any)[]
(message: Message) => any
>();
protected idListeners = new Map<string, (message: Message) => any>();
// Listeners defined by the other side of the protocol (right now, always IDE)
protected externalTypeListeners = new Map<
keyof FromProtocol,
(message: Message) => any
>();
protected _onErrorHandlers: ((error: Error) => void)[] = [];
onError(handler: (error: Error) => void) {
@ -62,44 +70,17 @@ export class InProcessMessenger<
invoke<T extends keyof ToProtocol>(
messageType: T,
data: ToProtocol[T][0],
messageId?: string,
): ToProtocol[T][1] {
const listeners = this.typeListeners.get(messageType);
if (!listeners || !listeners.length) return;
const listener = this.myTypeListeners.get(messageType);
if (!listener) return;
const msg: Message = {
messageType: messageType as string,
data,
messageId: uuidv4(),
messageId: messageId ?? uuidv4(),
};
return listeners[0](msg);
}
// get reverseMessenger(): IMessenger<ToProtocol, FromProtocol> {
// return {
// onError: (handler: (error: Error) => void) => {},
// send: (messageType: string, message: any, messageId?: string) => {
// const messageId_ = messageId || uuidv4();
// this.handleMessage({
// messageType,
// messageId: messageId_,
// data: message,
// });
// return messageId_;
// },
// on: (
// messageType: keyof ToProtocol,
// handler: (message: Message) => any,
// ) => {
// // Need to keep track of stuff?
// },
// request: (messageType: keyof FromProtocol, data: any) => {
// return this.request(messageType, data);
// },
// };
// }
protected _send(message: Message) {
throw new Error("Not implemented");
return listener(msg);
}
send<T extends keyof FromProtocol>(
@ -113,62 +94,55 @@ export class InProcessMessenger<
data: message,
messageId,
};
this._send(message);
this.externalTypeListeners.get(messageType)?.(data);
return messageId;
}
protected handleMessage(msg: Message) {
if (msg.messageType === undefined || msg.messageId === undefined) {
throw new Error(`Invalid message sent: ${JSON.stringify(msg)}`);
}
// Call handler and respond with return value
const listeners = this.typeListeners.get(msg.messageType as any);
listeners?.forEach(async (handler) => {
try {
const response = await handler(msg);
if (response && typeof response[Symbol.asyncIterator] === "function") {
for await (const update of response) {
this.send(msg.messageType, update, msg.messageId);
}
this.send(msg.messageType, { done: true }, msg.messageId);
} else {
this.send(msg.messageType, response || {}, msg.messageId);
}
} catch (e: any) {
console.warn(`Error running handler for "${msg.messageType}": `, e);
this._onErrorHandlers.forEach((handler) => {
handler(e);
});
}
});
// Call handler which is waiting for the response, nothing to return
this.idListeners.get(msg.messageId)?.(msg);
}
on<T extends keyof ToProtocol>(
messageType: T,
handler: (message: Message<ToProtocol[T][0]>) => ToProtocol[T][1],
): void {
if (!this.typeListeners.has(messageType)) {
this.typeListeners.set(messageType, []);
}
this.typeListeners.get(messageType)?.push(handler);
this.myTypeListeners.set(messageType, handler);
}
request<T extends keyof FromProtocol>(
async request<T extends keyof FromProtocol>(
messageType: T,
data: FromProtocol[T][0],
): Promise<FromProtocol[T][1]> {
const messageId = uuidv4();
return new Promise((resolve) => {
const handler = (msg: Message) => {
resolve(msg.data);
this.idListeners.delete(messageId);
};
this.idListeners.set(messageId, handler);
this.send(messageType, data, messageId);
const listener = this.externalTypeListeners.get(messageType);
if (!listener) {
throw new Error(`No handler for message type "${String(messageType)}"`);
}
const response = await listener({
messageType: messageType as string,
data,
messageId,
});
return response;
}
externalOn<T extends keyof FromProtocol>(
messageType: T,
handler: (message: Message) => any,
) {
this.externalTypeListeners.set(messageType, handler);
}
externalRequest<T extends keyof ToProtocol>(
messageType: T,
data: ToProtocol[T][0],
): Promise<ToProtocol[T][1]> {
const messageId = uuidv4();
const listener = this.myTypeListeners.get(messageType);
if (!listener) {
throw new Error(`No handler for message type "${String(messageType)}"`);
}
const response = listener({
messageType: messageType as string,
data,
messageId,
});
return Promise.resolve(response);
}
}

View file

@ -55,11 +55,7 @@ export class ContinueGUIWebviewViewProvider
private readonly extensionContext: vscode.ExtensionContext,
private readonly verticalDiffManager: VerticalPerLineDiffManager,
) {
this.webviewProtocol = new VsCodeWebviewProtocol(
ide,
configHandler,
verticalDiffManager,
);
this.webviewProtocol = new VsCodeWebviewProtocol();
}
getSidebarContent(

View file

@ -0,0 +1,256 @@
import { FromCoreProtocol, ToCoreProtocol } from "core/protocol";
import { ToIdeFromWebviewOrCoreProtocol } from "core/protocol/ide";
import { ToIdeFromCoreProtocol } from "core/protocol/ideCore";
import { WEBVIEW_TO_CORE_PASS_THROUGH } from "core/protocol/passThrough";
import { InProcessMessenger, Message } from "core/util/messenger";
import { getConfigJsonPath } from "core/util/paths";
import * as fs from "node:fs";
import * as path from "node:path";
import * as vscode from "vscode";
import { VerticalPerLineDiffManager } from "../diff/verticalPerLine/manager";
import { VsCodeIde } from "../ideProtocol";
import { getExtensionUri } from "../util/vscode";
import {
ToCoreOrIdeFromWebviewProtocol,
VsCodeWebviewProtocol,
} from "../webviewProtocol";
/**
* A shared messenger class between Core and Webview
* so we don't have to rewrite some of the handlers
*/
export class VsCodeMessenger {
onWebview<T extends keyof ToCoreOrIdeFromWebviewProtocol>(
messageType: T,
handler: (
message: Message<ToCoreOrIdeFromWebviewProtocol[T][0]>,
) =>
| Promise<ToCoreOrIdeFromWebviewProtocol[T][1]>
| ToCoreOrIdeFromWebviewProtocol[T][1],
): void {
this.webviewProtocol.on(messageType, handler);
}
onCore<T extends keyof ToIdeFromCoreProtocol>(
messageType: T,
handler: (
message: Message<ToIdeFromCoreProtocol[T][0]>,
) => Promise<ToIdeFromCoreProtocol[T][1]> | ToIdeFromCoreProtocol[T][1],
): void {
this.inProcessMessenger.externalOn(messageType, handler);
}
onWebviewOrCore<T extends keyof ToIdeFromWebviewOrCoreProtocol>(
messageType: T,
handler: (
message: Message<ToIdeFromWebviewOrCoreProtocol[T][0]>,
) =>
| Promise<ToIdeFromWebviewOrCoreProtocol[T][1]>
| ToIdeFromWebviewOrCoreProtocol[T][1],
): void {
this.onWebview(messageType, handler);
this.onCore(messageType, handler);
}
constructor(
private readonly inProcessMessenger: InProcessMessenger<
ToCoreProtocol,
FromCoreProtocol
>,
private readonly webviewProtocol: VsCodeWebviewProtocol,
private readonly ide: VsCodeIde,
private readonly verticalDiffManager: VerticalPerLineDiffManager,
) {
/** WEBVIEW LISTENERS **/
this.onWebview("showFile", (msg) => {
this.ide.openFile(msg.data.filepath);
});
this.onWebview("openConfigJson", (msg) => {
this.ide.openFile(getConfigJsonPath());
});
this.onWebview("readRangeInFile", async (msg) => {
return await vscode.workspace
.openTextDocument(msg.data.filepath)
.then((document) => {
const start = new vscode.Position(0, 0);
const end = new vscode.Position(5, 0);
const range = new vscode.Range(start, end);
const contents = document.getText(range);
return contents;
});
});
this.onWebview("toggleDevTools", (msg) => {
vscode.commands.executeCommand("workbench.action.toggleDevTools");
vscode.commands.executeCommand("continue.viewLogs");
});
this.onWebview("reloadWindow", (msg) => {
vscode.commands.executeCommand("workbench.action.reloadWindow");
});
this.onWebview("focusEditor", (msg) => {
vscode.commands.executeCommand("workbench.action.focusActiveEditorGroup");
});
this.onWebview("toggleFullScreen", (msg) => {
vscode.commands.executeCommand("continue.toggleFullScreen");
});
// IDE
this.onWebview("getDiff", async (msg) => {
return await ide.getDiff();
});
this.onWebview("getTerminalContents", async (msg) => {
return await ide.getTerminalContents();
});
this.onWebview("getDebugLocals", async (msg) => {
return await ide.getDebugLocals(Number(msg.data.threadIndex));
});
this.onWebview("getAvailableThreads", async (msg) => {
return await ide.getAvailableThreads();
});
this.onWebview("getTopLevelCallStackSources", async (msg) => {
return await ide.getTopLevelCallStackSources(
msg.data.threadIndex,
msg.data.stackDepth,
);
});
this.onWebview("listWorkspaceContents", async (msg) => {
return await ide.listWorkspaceContents();
});
this.onWebview("getWorkspaceDirs", async (msg) => {
return await ide.getWorkspaceDirs();
});
this.onWebview("listFolders", async (msg) => {
return await ide.listFolders();
});
this.onWebview("writeFile", async (msg) => {
return await ide.writeFile(msg.data.path, msg.data.contents);
});
this.onWebview("showVirtualFile", async (msg) => {
return await ide.showVirtualFile(msg.data.name, msg.data.content);
});
this.onWebview("getContinueDir", async (msg) => {
return await ide.getContinueDir();
});
this.onWebview("openFile", async (msg) => {
return await ide.openFile(msg.data.path);
});
this.onWebview("runCommand", async (msg) => {
await ide.runCommand(msg.data.command);
});
this.onWebview("getSearchResults", async (msg) => {
return await ide.getSearchResults(msg.data.query);
});
this.onWebview("subprocess", async (msg) => {
return await ide.subprocess(msg.data.command);
});
// History
this.onWebview("saveFile", async (msg) => {
return await ide.saveFile(msg.data.filepath);
});
this.onWebview("readFile", async (msg) => {
return await ide.readFile(msg.data.filepath);
});
this.onWebview("showDiff", async (msg) => {
return await ide.showDiff(
msg.data.filepath,
msg.data.newContents,
msg.data.stepIndex,
);
});
this.onWebview("getProblems", async (msg) => {
return await ide.getProblems(msg.data.filepath);
});
this.onWebview("getBranch", async (msg) => {
const { dir } = msg.data;
return await ide.getBranch(dir);
});
this.onWebview("getOpenFiles", async (msg) => {
return await ide.getOpenFiles();
});
this.onWebview("getPinnedFiles", async (msg) => {
return await ide.getPinnedFiles();
});
this.onWebview("showLines", async (msg) => {
const { filepath, startLine, endLine } = msg.data;
return await ide.showLines(filepath, startLine, endLine);
});
// Other
this.onWebview("errorPopup", (msg) => {
vscode.window
.showErrorMessage(msg.data.message, "Show Logs")
.then((selection) => {
if (selection === "Show Logs") {
vscode.commands.executeCommand("workbench.action.toggleDevTools");
}
});
});
this.onWebview("applyToCurrentFile", async (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.`,
await this.webviewProtocol.request("getDefaultModelTitle", undefined),
);
});
this.onWebview("showTutorial", async (msg) => {
const tutorialPath = path.join(
getExtensionUri().fsPath,
"continue_tutorial.py",
);
// Ensure keyboard shortcuts match OS
if (process.platform !== "darwin") {
let tutorialContent = fs.readFileSync(tutorialPath, "utf8");
tutorialContent = tutorialContent
.replace("⌘", "^")
.replace("Cmd", "Ctrl");
fs.writeFileSync(tutorialPath, tutorialContent);
}
const doc = await vscode.workspace.openTextDocument(
vscode.Uri.file(tutorialPath),
);
await vscode.window.showTextDocument(doc);
});
this.onWebview("openUrl", (msg) => {
vscode.env.openExternal(vscode.Uri.parse(msg.data));
});
this.onWebview("insertAtCursor", async (msg) => {
const editor = vscode.window.activeTextEditor;
if (editor === undefined || !editor.selection) {
return;
}
editor.edit((editBuilder) => {
editBuilder.replace(
new vscode.Range(editor.selection.start, editor.selection.end),
msg.data.text,
);
});
});
/** PASS THROUGH **/
WEBVIEW_TO_CORE_PASS_THROUGH.forEach((messageType) => {
this.onWebview(messageType, async (msg) => {
return await this.inProcessMessenger.externalRequest(
messageType,
msg.data,
);
});
});
}
}

View file

@ -1,6 +1,7 @@
import { ConfigHandler } from "core/config/handler";
import { Core } from "core/core";
import { CodebaseIndexer, PauseToken } from "core/indexing/indexCodebase";
import { FromCoreProtocol, ToCoreProtocol } from "core/protocol";
import type { IdeSettings } from "core/protocol/ideWebview";
import { InProcessMessenger } from "core/util/messenger";
import { v4 as uuidv4 } from "uuid";
@ -18,6 +19,7 @@ import { setupRemoteConfigSync } from "../stubs/activation";
import { getUserToken } from "../stubs/auth";
import { TabAutocompleteModel } from "../util/loadAutocompleteModel";
import type { VsCodeWebviewProtocol } from "../webviewProtocol";
import { VsCodeMessenger } from "./VsCodeMessenger";
export class VsCodeExtension {
// Currently some of these are public so they can be used in testing (test/test-suites)
@ -142,7 +144,17 @@ export class VsCodeExtension {
userTokenPromise,
);
this.core = new Core(new InProcessMessenger(), this.ide);
const inProcessMessenger = new InProcessMessenger<
ToCoreProtocol,
FromCoreProtocol
>();
this.core = new Core(inProcessMessenger, this.ide);
const vscodeMessenger = new VsCodeMessenger(
inProcessMessenger,
this.webviewProtocol,
this.ide,
this.verticalDiffManager,
);
if (
!(

View file

@ -29,6 +29,14 @@ class VsCodeIde implements IDE {
this.ideUtils = new VsCodeIdeUtils();
}
async infoPopup(message: string): Promise<void> {
vscode.window.showInformationMessage(message);
}
async errorPopup(message: string): Promise<void> {
vscode.window.showErrorMessage(message);
}
async getRepoName(dir: string): Promise<string | undefined> {
const repo = await this.getRepo(vscode.Uri.file(dir));
const remotes = repo?.repository?.remotes;

View file

@ -1,56 +1,30 @@
import type { ContextItemId, IDE } from "core";
import type { ConfigHandler } from "core/config/handler";
import {
setupLocalMode,
setupOptimizedExistingUserMode,
setupOptimizedMode,
} from "core/config/onboarding";
import { addModel, addOpenAIKey, deleteModel } from "core/config/util";
import { indexDocs } from "core/indexing/docs";
import TransformersJsEmbeddingsProvider from "core/indexing/embeddings/TransformersJsEmbeddingsProvider";
import { ToCoreFromWebviewProtocol } from "core/protocol/coreWebview";
ToCoreFromWebviewProtocol,
ToWebviewFromCoreProtocol,
} from "core/protocol/coreWebview";
import {
ToIdeFromWebviewProtocol,
ToWebviewFromIdeProtocol,
} from "core/protocol/ideWebview";
import { WEBVIEW_TO_CORE_PASS_THROUGH } from "core/protocol/passThrough";
import { logDevData } from "core/util/devdata";
import { DevDataSqliteDb } from "core/util/devdataSqlite";
import historyManager from "core/util/history";
import { IMessenger, type Message } from "core/util/messenger";
import { editConfigJson, getConfigJsonPath } from "core/util/paths";
import { Telemetry } from "core/util/posthog";
import fs from "node:fs";
import path from "node:path";
import { v4 as uuidv4 } from "uuid";
import * as vscode from "vscode";
import type { VerticalPerLineDiffManager } from "./diff/verticalPerLine/manager";
import { getExtensionUri } from "./util/vscode";
async function showTutorial() {
const tutorialPath = path.join(
getExtensionUri().fsPath,
"continue_tutorial.py",
);
// Ensure keyboard shortcuts match OS
if (process.platform !== "darwin") {
let tutorialContent = fs.readFileSync(tutorialPath, "utf8");
tutorialContent = tutorialContent.replace("⌘", "^").replace("Cmd", "Ctrl");
fs.writeFileSync(tutorialPath, tutorialContent);
}
const doc = await vscode.workspace.openTextDocument(
vscode.Uri.file(tutorialPath),
);
await vscode.window.showTextDocument(doc);
}
type ToProtocol = ToIdeFromWebviewProtocol;
type FromProtocol = ToWebviewFromIdeProtocol;
export type ToCoreOrIdeFromWebviewProtocol = ToCoreFromWebviewProtocol &
ToIdeFromWebviewProtocol;
type FullToWebviewFromIdeOrCoreProtocol = ToWebviewFromIdeProtocol &
ToWebviewFromCoreProtocol;
export class VsCodeWebviewProtocol
implements IMessenger<ToProtocol, FromProtocol>
implements
IMessenger<
ToCoreOrIdeFromWebviewProtocol,
FullToWebviewFromIdeOrCoreProtocol
>
{
listeners = new Map<keyof ToProtocol, ((message: Message) => any)[]>();
listeners = new Map<
keyof ToCoreOrIdeFromWebviewProtocol,
((message: Message) => any)[]
>();
send(messageType: string, data: any, messageId?: string): string {
const id = messageId ?? uuidv4();
@ -62,11 +36,13 @@ export class VsCodeWebviewProtocol
return id;
}
on<T extends keyof ToProtocol>(
on<T extends keyof ToCoreOrIdeFromWebviewProtocol>(
messageType: T,
handler: (
message: Message<ToProtocol[T][0]>,
) => Promise<ToProtocol[T][1]> | ToProtocol[T][1],
message: Message<ToCoreOrIdeFromWebviewProtocol[T][0]>,
) =>
| Promise<ToCoreOrIdeFromWebviewProtocol[T][1]>
| ToCoreOrIdeFromWebviewProtocol[T][1],
): void {
if (!this.listeners.has(messageType)) {
this.listeners.set(messageType, []);
@ -81,18 +57,6 @@ export class VsCodeWebviewProtocol
return this._webview;
}
handleWebviewToCoreMessage<T extends keyof ToCoreFromWebviewProtocol>(
messageType: T,
data: ToCoreFromWebviewProtocol[T][0],
messageId: string,
) {
// Pass through to core
const response = "TODO";
// Send response back to webview
this.send(messageType, response, messageId);
}
set webview(webView: vscode.Webview) {
this._webview = webView;
this._webviewListener?.dispose();
@ -102,15 +66,6 @@ export class VsCodeWebviewProtocol
throw new Error(`Invalid webview protocol msg: ${JSON.stringify(msg)}`);
}
if (WEBVIEW_TO_CORE_PASS_THROUGH.includes(msg.messageType)) {
this.handleWebviewToCoreMessage(
msg.messageType,
msg.data,
msg.messageId,
);
return;
}
const respond = (message: any) =>
this.send(msg.messageType, message, msg.messageId);
@ -169,473 +124,12 @@ export class VsCodeWebviewProtocol
});
}
constructor(
private readonly ide: IDE,
private readonly configHandler: ConfigHandler,
private readonly verticalDiffManager: VerticalPerLineDiffManager,
) {
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) => {
const start = new vscode.Position(0, 0);
const end = new vscode.Position(5, 0);
const range = new vscode.Range(start, end);
const 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("getDebugLocals", async (msg) => {
return await ide.getDebugLocals(Number(msg.data.threadIndex));
});
this.on("getAvailableThreads", async (msg) => {
return await ide.getAvailableThreads();
});
this.on("getTopLevelCallStackSources", async (msg) => {
return await ide.getTopLevelCallStackSources(
msg.data.threadIndex,
msg.data.stackDepth,
);
});
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
const lines = newConfigString.split("\n");
let startLine: number | undefined;
let endLine: number | undefined;
for (let i = 0; i < lines.length; i++) {
const 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}`);
}
Telemetry.capture("useSlashCommand", {
name: 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,
reranker: config.reranker,
fullInput,
ide,
selectedCode,
});
Telemetry.capture("useContextProvider", {
name: provider.description.title,
});
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", async (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.`,
await this.request("getDefaultModelTitle", undefined),
);
});
this.on("showTutorial", (msg) => {
showTutorial();
});
this.on("completeOnboarding", (msg) => {
const mode = msg.data.mode;
Telemetry.capture("onboardingSelection", {
mode,
});
if (mode === "custom" || mode === "localExistingUser") {
return;
}
editConfigJson(
mode === "local"
? setupLocalMode
: mode === "optimized"
? setupOptimizedMode
: setupOptimizedExistingUserMode,
);
});
this.on("openUrl", (msg) => {
vscode.env.openExternal(vscode.Uri.parse(msg.data));
});
this.on("stats/getTokensPerDay", async (msg) => {
const rows = await DevDataSqliteDb.getTokensPerDay();
return rows;
});
this.on("stats/getTokensPerModel", async (msg) => {
const rows = await DevDataSqliteDb.getTokensPerModel();
return rows;
});
this.on("insertAtCursor", async (msg) => {
const editor = vscode.window.activeTextEditor;
if (editor === undefined || !editor.selection) {
return;
}
editor.edit((editBuilder) => {
editBuilder.replace(
new vscode.Range(editor.selection.start, editor.selection.end),
msg.data.text,
);
});
});
}
invoke<T extends keyof ToProtocol>(
constructor() {}
invoke<T extends keyof ToCoreOrIdeFromWebviewProtocol>(
messageType: T,
data: ToProtocol[T][0],
): ToProtocol[T][1] {
data: ToCoreOrIdeFromWebviewProtocol[T][0],
messageId?: string,
): ToCoreOrIdeFromWebviewProtocol[T][1] {
throw new Error("Method not implemented.");
}
@ -643,10 +137,10 @@ export class VsCodeWebviewProtocol
throw new Error("Method not implemented.");
}
public request<T extends keyof FromProtocol>(
public request<T extends keyof FullToWebviewFromIdeOrCoreProtocol>(
messageType: T,
data: FromProtocol[T][0],
): Promise<FromProtocol[T][1]> {
data: FullToWebviewFromIdeOrCoreProtocol[T][0],
): Promise<FullToWebviewFromIdeOrCoreProtocol[T][1]> {
const messageId = uuidv4();
return new Promise((resolve) => {
if (!this.webview) {
@ -656,7 +150,7 @@ export class VsCodeWebviewProtocol
this.send(messageType, data, messageId);
const disposable = this.webview.onDidReceiveMessage(
(msg: Message<FromProtocol[T][1]>) => {
(msg: Message<FullToWebviewFromIdeOrCoreProtocol[T][1]>) => {
if (msg.messageId === messageId) {
resolve(msg.data);
disposable?.dispose();