continue-custom/extension/src/debugPanel.ts
Bishwendu Kundu 0752c15c1a
Initial intelliJ plugin changes to support webview (#457)
* Initial intelliJ plugin changes to support webview

* connect webview websockets

* Starting work on downloading server binary from S3

* fix color theme in intellij

* refactor name to continuedev

* correctly set important variables for onLoad

* highlighted code now working

* keyboard shortcuts (Actions)

* fix: 🐛 hf_tgi fix, proxy support for ggml

* fix: 🐛 remove unecessary logging

* Sync the changes

* Clean up code

* updating how continue works

* ci: 🏷 Update PyPI version [skip ci]

* docs: 📝 docs for customizing chat / edit templates

* docs: 📝 headless mode docs (start)

* docs: 📝 updated setup docs

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* fix: 🐛 compatibility with python 3.8

* feat: ✨ verify_ssl option for all LLMs

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* fix: 🐛 verify_ssl and ssl_context mutual exclusivity

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* feat: 🩹 ca_bundle_path for maybeproxyopenai

* fix: 🐛 a few minor fixes

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* fix: 🐛 custom escaping instead of URI for diff paths

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* fix: 🐛 fix huggingface tgi

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* docs: 📝 small docs update on how continue works

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* Clarifying `logs` instructions in troubleshooting.md (#476)

* fix: 🐛 fixes to templating messages

* fix: some typos (#478)

* fix: 🐛 fix for lmstudio defaults

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* Implement design patterns for better extensibility

* Fix: Ensure read operations in ContinuePluginSelectionListener are run within the correct context using runReadAction.

* feat: ✨ implement most other ideProtocolClient methods

* wait until server is running to connect

* remove unnecessary imports, update version

* reformat code and optimize the imports

* fix: 🐛 fix serialization bug

* fix: 🐛 attempt to fix error from jetbrains marketplace

* a few updates

* fix: 🐛 bringing jetbrains up to par

* feat: ✨ highlighted code updates in intellij

* fix: 🚑 fix freezing issue

* fix: 🐛 fix icons, bump version

* feat: ✨ /edit support, other fixes

* quick input, keyboard shortcuts

* fix: 🐛 fix /edit and keyboard shortcuts and lagging on scroll

* feat: 💄 welcome panel

* chore: 🔖 update version

* ide endpoint for websockets

* fix: 🚑 fix freezing problem

* quick input

* fix: 🐛 small jetbrains fixes

* fix: 💄 nicer dropdown that can "drop up"

* fix: 🐛 fix font size for dropdown

* fix: 💄 fix textarea for quickinput

* Preview (#541)

* Strong typing (#533)

* refactor: ♻️ get rid of continuedev.src.continuedev structure

* refactor: ♻️ switching back to server folder

* feat: ✨ make config.py imports shorter

* feat: 🔖 publish as pre-release vscode extension

* refactor: ♻️ refactor and add more completion params to ui

* build: 🏗️ download from preview S3

* fix: 🐛 fix paths

* fix: 💚 package:pre-release

* ci: 💚 more time for tests

* fix: 💚 fix build scripts

* fix: 🐛 fix import in run.py

* fix: 🔖 update version to try again

* ci: 💚 Update package.json version [skip ci]

* refactor: 🔥 don't check for old extensions version

* fix: 🐛 small bug fixes

* fix: 🐛 fix config.py import paths

* ci: 💚 Update package.json version [skip ci]

* ci: 💚 platform-specific builds test #1

* feat: 💚 ship with binary

* fix: 💚 fix copy statement to include.exe for windows

* fix: 💚 cd extension before packaging

* chore: 🔊 count tokens generated

* fix: 💚 remove npm_config_arch

* fix: 💚 publish as pre-release!

* chore: 🔖 update version

* perf: 💚 hardcode distro paths

* fix: 🐛 fix yaml syntax error

* chore: 🔖 update version

* fix: 💚 update permissions and version

* feat: 🐛 kill old server if needed

* feat: 💄 update marketplace icon for pre-release

* ci: 💚 Update package.json version [skip ci]

* feat: ✨ auto-reload for config.py

* feat: 🔧 update default config.py imports

* feat: ✨ codelens in config.py

* feat: ✨ select model param count from UI

* ci: 💚 Update package.json version [skip ci]

* feat: ✨ more model options, ollama error handling

* perf: ⚡ don't show server loading immediately

* fix: 🐛 fixing small UI details

* ci: 💚 Update package.json version [skip ci]

* feat: 🚀 headers param on LLM class

* fix: 🐛 fix headers for openai.;y

* feat: ✨ highlight code on cmd+shift+L

* ci: 💚 Update package.json version [skip ci]

* feat: 💄 sticky top bar in gui.tsx

* fix: 🔊 websocket logging and horizontal scrollbar

* ci: 💚 Update package.json version [skip ci]

* feat: ✨ allow AzureOpenAI Service through GGML

* ci: 💚 Update package.json version [skip ci]

* fix: 🐛 fix automigration

* ci: 💚 Update package.json version [skip ci]

* ci: 💚 upload binaries in ci, download apple silicon

* chore: 🔥 remove notes

* fix: 💚 use curl to download binary

* fix: 💚 set permissions on apple silicon binary

* fix: 💚 testing

* fix: 💚 cleanup file

* fix: 💚 fix preview.yaml

* fix: 💚 only upload once per binary

* fix: 💚 install rosetta

* ci: 💚 download binary after tests

* ci: 💚 Update package.json version [skip ci]

* ci: 💚 prepare ci for merge to main

---------

Co-authored-by: GitHub Action <action@github.com>

* fix: 📝 fix deployent readme

* fix: 🐛 do read operation in readAction

* chore: 🔖 update version

* 🐛 small jetbrains fixes

* ⚡️ exponential backoff jetbrains

* 🐛 fix history loading bug

* 💄 many small ui fixes

* 🐛 fixes freezing problem (actually)

* 🥅 catch errors, other stuff

* 🐛 many jetbrains fixes

* 💄 when no context items found, say in dropdown

* 🎉 VS Code tutorial

* ✨ jetbrains tutorial file

* ⚡️ exponential backoff for ide websockets

* 🎉 unused work on intellij editor inlay

* ✨ server loading progress messages

* ✨ additional progress update

* 💄 fix /edit flickering, keyboard interactions

---------

Co-authored-by: Nate Sesti <sestinj@gmail.com>
Co-authored-by: Ty Dunn <ty@tydunn.com>
Co-authored-by: GitHub Action <action@github.com>
Co-authored-by: Aaron Mihalik <amihalik@users.noreply.github.com>
Co-authored-by: LangLangBart <92653266+LangLangBart@users.noreply.github.com>
Co-authored-by: Nate Sesti <33237525+sestinj@users.noreply.github.com>
2023-10-16 23:14:00 -07:00

336 lines
9.3 KiB
TypeScript

import * as vscode from "vscode";
import { getContinueServerUrl } from "./bridge";
import {
getExtensionUri,
getNonce,
getUniqueId,
openEditorAndRevealRange,
} from "./util/vscode";
import { RangeInFile } from "../schema/RangeInFile";
import { setFocusedOnContinueInput } from "./commands";
const WebSocket = require("ws");
let websocketConnections: { [url: string]: WebsocketConnection | undefined } =
{};
class WebsocketConnection {
private _ws: WebSocket;
private _onMessage: (message: string) => void;
private _onOpen: () => void;
private _onClose: () => void;
private _onError: (e: any) => void;
constructor(
url: string,
onMessage: (message: string) => void,
onOpen: () => void,
onClose: () => void,
onError: (e: any) => void
) {
this._ws = new WebSocket(url);
this._onMessage = onMessage;
this._onOpen = onOpen;
this._onClose = onClose;
this._onError = onError;
this._ws.addEventListener("message", (event) => {
this._onMessage(event.data);
});
this._ws.addEventListener("close", () => {
this._onClose();
});
this._ws.addEventListener("open", () => {
this._onOpen();
});
this._ws.addEventListener("error", (e: any) => {
this._onError(e);
});
}
public send(message: string) {
if (typeof message !== "string") {
message = JSON.stringify(message);
}
if (this._ws.readyState === WebSocket.OPEN) {
this._ws.send(message);
} else {
this._ws.addEventListener("open", () => {
this._ws.send(message);
});
}
}
public close() {
this._ws.close();
}
}
export let debugPanelWebview: vscode.Webview | undefined;
export function setupDebugPanel(
panel: vscode.WebviewPanel | vscode.WebviewView,
sessionIdPromise: Promise<string>
): string {
debugPanelWebview = panel.webview;
panel.onDidDispose(() => {
debugPanelWebview = undefined;
});
let extensionUri = getExtensionUri();
let scriptUri: string;
let styleMainUri: string;
let vscMediaUrl: string = debugPanelWebview
.asWebviewUri(vscode.Uri.joinPath(extensionUri, "react-app/dist"))
.toString();
const isProduction = true; // context?.extensionMode === vscode.ExtensionMode.Development;
if (isProduction) {
scriptUri = debugPanelWebview
.asWebviewUri(
vscode.Uri.joinPath(extensionUri, "react-app/dist/assets/index.js")
)
.toString();
styleMainUri = debugPanelWebview
.asWebviewUri(
vscode.Uri.joinPath(extensionUri, "react-app/dist/assets/index.css")
)
.toString();
} else {
scriptUri = "http://localhost:5173/src/main.tsx";
styleMainUri = "http://localhost:5173/src/main.css";
}
panel.webview.options = {
enableScripts: true,
localResourceRoots: [vscode.Uri.joinPath(extensionUri, "react-app/dist")],
enableCommandUris: true,
};
const nonce = getNonce();
vscode.window.onDidChangeTextEditorSelection((e) => {
if (e.selections[0].isEmpty) {
return;
}
const rangeInFile: RangeInFile = {
range: e.selections[0] as any,
filepath: e.textEditor.document.fileName,
};
const filesystem = {
[rangeInFile.filepath]: e.textEditor.document.getText(),
};
panel.webview.postMessage({
type: "highlightedCode",
rangeInFile,
filesystem,
});
panel.webview.postMessage({
type: "workspacePath",
value: vscode.workspace.workspaceFolders?.[0].uri.fsPath,
});
});
async function connectWebsocket(url: string) {
return new Promise((resolve, reject) => {
const onMessage = (message: any) => {
panel.webview.postMessage({
type: "websocketForwardingMessage",
url,
data: message,
});
};
const onOpen = () => {
panel.webview.postMessage({
type: "websocketForwardingOpen",
url,
});
resolve(null);
};
const onClose = () => {
websocketConnections[url] = undefined;
panel.webview.postMessage({
type: "websocketForwardingClose",
url,
});
};
const onError = (e: any) => {
panel.webview.postMessage({
type: "websocketForwardingError",
url,
error: e,
});
};
try {
const connection = new WebsocketConnection(
url,
onMessage,
onOpen,
onClose,
onError
);
websocketConnections[url] = connection;
resolve(null);
} catch (e) {
console.log("Caught it!: ", e);
reject(e);
}
});
}
panel.webview.onDidReceiveMessage(async (data) => {
switch (data.type) {
case "onLoad": {
const sessionId = await sessionIdPromise;
panel.webview.postMessage({
type: "onLoad",
vscMachineId: getUniqueId(),
apiUrl: getContinueServerUrl(),
workspacePaths: vscode.workspace.workspaceFolders?.map(
(folder) => folder.uri.fsPath
),
sessionId,
vscMediaUrl,
dataSwitchOn: vscode.workspace
.getConfiguration("continue")
.get<boolean>("dataSwitch"),
});
break;
}
case "websocketForwardingOpen": {
let url = data.url;
if (typeof websocketConnections[url] === "undefined") {
await connectWebsocket(url);
} else {
console.log(
"Websocket connection requested by GUI already open at",
url
);
panel.webview.postMessage({
type: "websocketForwardingOpen",
url,
});
}
break;
}
case "websocketForwardingClose": {
let url = data.url;
let connection = websocketConnections[url];
if (typeof connection !== "undefined") {
connection.close();
websocketConnections[url] = undefined;
}
break;
}
case "websocketForwardingMessage": {
let url = data.url;
let connection = websocketConnections[url];
if (typeof connection === "undefined") {
await connectWebsocket(url);
}
connection = websocketConnections[url];
if (typeof connection === "undefined") {
throw new Error("Failed to connect websocket in VS Code Extension");
}
connection.send(data.message);
break;
}
case "openFile": {
openEditorAndRevealRange(data.path, undefined, vscode.ViewColumn.One);
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": {
setFocusedOnContinueInput(false);
vscode.commands.executeCommand(
"workbench.action.focusActiveEditorGroup"
);
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();
}
});
});
}
);
break;
}
}
});
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>const vscode = acquireVsCodeApi();</script>
<link href="${styleMainUri}" rel="stylesheet">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Lexend:wght@300&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap" rel="stylesheet">
<title>Continue</title>
</head>
<body>
<div id="root"></div>
<script type="module" nonce="${nonce}" src="${scriptUri}"></script>
<script>localStorage.setItem("ide", "vscode")</script>
</body>
</html>`;
}
export class ContinueGUIWebviewViewProvider
implements vscode.WebviewViewProvider
{
public static readonly viewType = "continue.continueGUIView";
private readonly sessionIdPromise: Promise<string>;
constructor(sessionIdPromise: Promise<string>) {
this.sessionIdPromise = sessionIdPromise;
}
resolveWebviewView(
webviewView: vscode.WebviewView,
_context: vscode.WebviewViewResolveContext,
_token: vscode.CancellationToken
): void | Thenable<void> {
webviewView.webview.html = setupDebugPanel(
webviewView,
this.sessionIdPromise
);
}
}