🚧 communication between core and jetbrains

This commit is contained in:
Nate Sesti 2024-02-15 19:56:40 -08:00
parent 6113e802d5
commit 5bb270fa97
15 changed files with 264 additions and 22 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

@ -18,7 +18,11 @@ export class ConfigHandler {
private readonly ide: IDE;
constructor(ide: IDE) {
this.ide = ide;
this.loadConfig();
try {
this.loadConfig();
} catch (e) {
console.error("Failed to load config: ", e);
}
}
reloadConfig() {

View file

@ -183,3 +183,7 @@ export function getTabAutocompleteCacheSqlitePath(): string {
export function getDocsSqlitePath(): string {
return path.join(getIndexFolderPath(), "docs.sqlite");
}
export function getCoreLogsPath(): string {
return path.join(getContinueGlobalPath(), "core.log");
}

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

@ -1,6 +1,7 @@
package com.github.continuedev.continueintellijextension.activities
import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath
import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger
import com.github.continuedev.continueintellijextension.`continue`.startProxyServer
import com.github.continuedev.continueintellijextension.`continue`.DefaultTextSelectionStrategy
import com.github.continuedev.continueintellijextension.`continue`.IdeProtocolClient
@ -30,7 +31,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
@ -156,17 +159,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 +196,18 @@ 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 continueCorePath = Paths.get(pluginPath.toString(), "core", "pkg").toString()
val coreMessenger = CoreMessenger(continueCorePath, ideProtocolClient);
}
}
}

View file

@ -0,0 +1,139 @@
package com.github.continuedev.continueintellijextension.`continue`
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.io.*
import com.google.gson.Gson
import com.intellij.openapi.components.ServiceManager
import java.io.*
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 + "\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, onResponse: (String) -> Unit) {
val messageId = uuid();
val message = gson.toJson(mapOf(
"messageId" to messageId,
"messageType" to messageType,
"data" to data
))
responseListeners[messageId] = onResponse
write(message)
}
private fun handleResponse(json: String) {
val responseMap = gson.fromJson(json, Map::class.java)
val messageId = responseMap["messageId"].toString()
val messageType = responseMap["messageType"].toString()
val responseData = gson.toJson(responseMap["data"])
// IDE listeners
if (ideMessageTypes.contains(responseMap["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(responseData)
responseListeners.remove(messageId)
}
}
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"
)
init {
// 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))
var sentPing = false
Thread {
try {
while (true) {
if (!sentPing) {
sentPing = true
request("ping", "ping") { response ->
println("Response!: $response")
}
}
val line = reader.readLine()
println("Core: $line")
if (line != null && line.isNotEmpty()) {
handleResponse(line)
}
}
} 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

@ -3,6 +3,14 @@ const { execSync } = require("child_process");
const esbuildOutputFile = "out/index.js";
let esbuildOnly = false;
for (let i = 2; i < process.argv.length; i++) {
if (process.argv[i] === "--esbuild-only") {
esbuildOnly = true;
break; // Exit the loop once the flag is found
}
}
(async () => {
// console.log("[info] Building with ncc...");
// execSync(`npx ncc build src/index.ts -o out`);
@ -28,6 +36,10 @@ const esbuildOutputFile = "out/index.js";
define: { "import.meta.url": "importMetaUrl" },
});
if (esbuildOnly) {
return;
}
console.log("[info] Building binary with pkg...");
execSync("npx pkg .");
console.log("[info] Done!");

11
pkg/package-lock.json generated
View file

@ -11,6 +11,7 @@
"dependencies": {
"commander": "^12.0.0",
"core": "file:../core",
"follow-redirects": "^1.15.5",
"uuid": "^9.0.1",
"vectordb": "^0.4.10"
},
@ -18,6 +19,7 @@
"pkg": "out/index.js"
},
"devDependencies": {
"@types/follow-redirects": "^1.14.4",
"@types/uuid": "^9.0.8",
"@vercel/ncc": "^0.38.1",
"esbuild": "^0.19.11",
@ -689,6 +691,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/node": {
"version": "20.3.0",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.3.0.tgz",

View file

@ -23,11 +23,13 @@
"test": "echo \"Error: no test specified\" && exit 1",
"build": "node build.js",
"build:old": "ncc build src/index.ts -o out && pkg .",
"build:dev": "tsc"
"build:dev": "tsc",
"esbuild": "node build.js --esbuild-only"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@types/follow-redirects": "^1.14.4",
"@types/uuid": "^9.0.8",
"@vercel/ncc": "^0.38.1",
"esbuild": "^0.19.11",
@ -37,6 +39,7 @@
"dependencies": {
"commander": "^12.0.0",
"core": "file:../core",
"follow-redirects": "^1.15.5",
"uuid": "^9.0.1",
"vectordb": "^0.4.10"
}

View file

@ -3,6 +3,6 @@ import { IpcMessenger } from "./messenger";
export class IpcIde extends MessageIde {
constructor(messenger: IpcMessenger) {
super(messenger.request);
super(messenger.request.bind(messenger));
}
}

View file

@ -39,6 +39,18 @@ export class Core {
this.selectedModelTitle = msg.data;
});
// Special
on("abort", (msg) => {
// TODO
});
on("ping", (msg) => {
if (msg.data !== "ping") {
throw new Error("ping message incorrect");
}
return "pong";
});
// History
on("history/list", (msg) => {
return historyManager.list();

View file

@ -1,5 +1,7 @@
import { v4 as uuidv4 } from "uuid";
import { getCoreLogsPath } from "core/util/paths";
import * as fs from "fs";
import { Message } from "../../core/util/messenger";
import { Protocol } from "./protocol";
@ -8,30 +10,37 @@ export class IpcMessenger {
idListeners = new Map<string, (message: Message) => any>();
constructor() {
console.log = console.error;
const logger = (message: any, ...optionalParams: any[]) => {
const logFilePath = getCoreLogsPath();
const logMessage = `${message} ${optionalParams.join(" ")}\n`;
fs.appendFileSync(logFilePath, logMessage);
};
console.log = logger;
console.error = logger;
console.warn = logger;
console.log("[info] Starting Continue core...");
process.stdin.on("data", (data) => {
const d = data.toString();
console.log("Receieved data: ", data);
try {
const d = data.toString();
const msg: Message = JSON.parse(d);
if (
msg.data !== undefined ||
msg.messageType !== undefined ||
msg.messageId !== undefined
) {
if (msg.messageType === undefined || msg.messageId === undefined) {
throw new Error("Invalid message sent: " + JSON.stringify(msg));
}
// Call handler and respond with return value
this.typeListeners.get(msg.messageType)?.forEach(async (handler) => {
const response = await handler(msg);
this.send(msg.messageType, response, msg.messageId);
});
this.typeListeners
.get(msg.messageType as any)
?.forEach(async (handler) => {
const response = await handler(msg);
this.send(msg.messageType, response, msg.messageId);
});
// Call handler which is waiting for the response, nothing to return
this.idListeners.get(msg.messageId)?.(msg);
} catch (e) {
console.error("Invalid JSON:", d);
console.error("Invalid JSON:", data);
return;
}
});
@ -45,7 +54,8 @@ export class IpcMessenger {
messageId,
};
// process.send?.(data);
process.stdout?.write(JSON.stringify(data));
process.stdout?.write(JSON.stringify(data) + "\n");
console.log("Sent: ", JSON.stringify(data));
return messageId;
}

View file

@ -13,6 +13,7 @@ export type Protocol = {
// New
"update/modelChange": [string, void];
// Special
ping: [string, string];
abort: [undefined, void];
// History