🚧 initial removal of server for jetbrains

This commit is contained in:
Nate Sesti 2023-12-17 23:47:16 -05:00
parent 258f6471c2
commit e8513c4a49
11 changed files with 278 additions and 619 deletions

View file

@ -1,6 +1,5 @@
// import "vscode-webview";
import { v4 as uuidv4 } from "uuid";
interface vscode {
postMessage(message: any): vscode;
}

View file

@ -1,6 +1,7 @@
package com.github.continuedev.continueintellijextension.actions
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.google.gson.Gson
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
@ -129,7 +130,7 @@ class QuickTextEntryAction : AnAction() {
}
continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
continuePluginService.dispatchCustomEvent("message", mutableMapOf("type" to "focusContinueInput"))
continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "focusContinueInput")))
}
}
@ -178,7 +179,7 @@ class FocusContinueInputWithEditAction : AnAction() {
val continuePluginService = pluginServiceFromActionEvent(e) ?: return
continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
continuePluginService.dispatchCustomEvent("message", mutableMapOf("type" to "focusContinueInputWithEdit"))
continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "focusContinueInputWithEdit")))
continuePluginService.ideProtocolClient?.sendHighlightedCode()
}
@ -201,7 +202,7 @@ class FocusContinueInputAction : AnAction() {
val continuePluginService = pluginServiceFromActionEvent(e) ?: return
continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
continuePluginService.dispatchCustomEvent("message", mutableMapOf("type" to "focusContinueInput"))
continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "focusContinueInput")))
continuePluginService.ideProtocolClient?.sendHighlightedCode()
}
@ -224,7 +225,7 @@ class NewContinueSessionAction : AnAction() {
val continuePluginService = pluginServiceFromActionEvent(e) ?: return
continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
continuePluginService.dispatchCustomEvent("message", mutableMapOf("type" to "focusContinueInputWithNewSession"))
continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "focusContinueInputWithNewSession")))
}
}
@ -238,6 +239,6 @@ class ViewHistoryAction : AnAction() {
val continuePluginService = pluginServiceFromActionEvent(e) ?: return
continuePluginService.dispatchCustomEvent("message", mutableMapOf("type" to "viewHistory"))
continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "viewHistory")))
}
}

View file

@ -1,24 +1,16 @@
package com.github.continuedev.continueintellijextension.activities
import com.github.continuedev.continueintellijextension.constants.CONTINUE_PYTHON_SERVER_URL
import com.github.continuedev.continueintellijextension.constants.CONTINUE_SERVER_WEBSOCKET_PORT
import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath
import com.github.continuedev.continueintellijextension.`continue`.DefaultTextSelectionStrategy
import com.github.continuedev.continueintellijextension.`continue`.IdeProtocolClient
import com.github.continuedev.continueintellijextension.`continue`.getMachineUniqueID
import com.github.continuedev.continueintellijextension.listeners.ContinuePluginSelectionListener
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.google.gson.Gson
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.CustomShortcutSet
import com.intellij.openapi.actionSystem.KeyboardShortcut
import com.intellij.openapi.actionSystem.Shortcut
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.keymap.KeymapManager
import com.intellij.openapi.project.DumbAware
@ -28,10 +20,7 @@ import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.util.io.StreamUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.ui.jcef.executeJavaScriptAsync
import kotlinx.coroutines.*
import okhttp3.OkHttpClient
import okhttp3.Request
import java.awt.Dimension
import java.awt.Font
import java.awt.GridLayout
@ -39,381 +28,9 @@ import java.io.*
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.attribute.PosixFilePermission
import javax.swing.*
fun getContinueGlobalPath(): String {
val continuePath = Paths.get(System.getProperty("user.home"), ".continue")
if (Files.notExists(continuePath)) {
Files.createDirectories(continuePath)
}
return continuePath.toString()
}
fun serverPath(): String {
val sPath = Paths.get(getContinueGlobalPath(), "server").toString()
val directory = File(sPath)
if (!directory.exists()) {
directory.mkdir()
}
return sPath
}
fun serverVersionPath(): String {
return Paths.get(serverPath(), "server_version.txt").toString()
}
fun serverBinaryPath(): String {
val exeFile = if (System.getProperty("os.name").toLowerCase()
.contains("win")
) "continue_server.exe" else "continue_server"
return Paths.get(serverPath(), "exe", exeFile).toString()
}
fun downloadFromS3(
bucket: String,
filename: String,
destination: String,
region: String,
useBackupUrl: Boolean = false
) {
val client = OkHttpClient()
val url = if (useBackupUrl)
"https://s3.continue.dev/$filename"
else
"https://$bucket.s3.$region.amazonaws.com/$filename"
val request = Request.Builder()
.url(url)
.build()
// Create the necessary folders
val directory = File(destination).parentFile
if (!directory.exists()) {
directory.mkdirs()
}
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) {
Files.deleteIfExists(Paths.get(destination))
throw IOException("No body returned when downloading from S3 bucket")
}
val fos = FileOutputStream(File(destination))
val body = response.body!!.byteStream()
fos.use {
body.copyTo(it)
}
}
}
// Set permissions on the binary
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")
}
}
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)
}
fun getProcessId(port: Int): String? {
val os = System.getProperty("os.name").toLowerCase()
val command = when {
os.contains("win") -> listOf(
"cmd.exe",
"/c",
"netstat -ano | findstr :$port"
)
os.contains("nix") || os.contains("mac") || os.contains("nux") -> listOf(
"/bin/sh",
"-c",
"lsof -t -i tcp:$port"
)
else -> throw UnsupportedOperationException("Unsupported operating system: $os")
}
val process = ProcessBuilder(command).start()
val reader = BufferedReader(InputStreamReader(process.inputStream))
return reader.readLine()?.trim()
}
fun killProcess(pid: String) {
val os = System.getProperty("os.name").toLowerCase()
val command = when {
os.contains("win") -> listOf("taskkill", "/F", "/PID", pid)
else -> listOf(
"kill",
"-9",
pid
)
}
try {
val process = ProcessBuilder(command).start()
process.waitFor()
} catch (e: IOException) {
e.printStackTrace()
}
}
fun checkServerRunning(): Boolean {
val processId = getProcessId(CONTINUE_SERVER_WEBSOCKET_PORT)
return processId != null
}
fun getExtensionVersion(): String {
val pluginId =
PluginId.getId("com.github.continuedev.continueintellijextension")
val pluginDescriptor = PluginManagerCore.getPlugin(pluginId)
return pluginDescriptor?.version ?: ""
}
fun checkOrKillRunningServer(project: Project): Boolean {
val continuePluginService = ServiceManager.getService(
project,
ContinuePluginService::class.java
)
val serverRunning: Boolean = checkServerRunning()
var shouldKillAndReplace = true
val serverVersionPath = serverVersionPath()
if (File(serverVersionPath).exists()) {
val serverVersion = File(serverVersionPath).readText()
if (serverVersion == getExtensionVersion() && serverRunning) {
println("Continue server of correct version already running")
shouldKillAndReplace = false
}
}
if (shouldKillAndReplace) {
continuePluginService.dispatchCustomEvent("serverStatus", mutableMapOf(
"type" to "serverStatus",
"message" to "Stopping Outdated Server"
))
println("Killing server from old version of Continue")
val pid = getProcessId(CONTINUE_SERVER_WEBSOCKET_PORT)
pid?.let { killProcess(it) }
if (File(serverVersionPath).exists()) {
File(serverVersionPath).delete()
}
val serverBinary = serverBinaryPath()
if (File(serverBinary).exists()) {
File(serverBinary).delete()
}
}
return serverRunning && !shouldKillAndReplace
}
fun runBinary(path: String) {
try {
if (System.getProperty("os.name").toLowerCase().contains("win")) {
// Windows approach
val script = """
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "$path", 0
Set WshShell = Nothing
""".trimIndent()
val scriptPath = Paths.get("startProcess.vbs")
Files.writeString(scriptPath, script)
val processBuilder = ProcessBuilder("cmd", "/c", "start", "cscript", scriptPath.toString())
processBuilder.start()
} else {
// Unix-like approach
val processBuilder = ProcessBuilder("sh", "-c", "nohup $path > /dev/null 2>&1 &")
processBuilder.start()
}
} catch (e: IOException) {
e.printStackTrace()
}
}
suspend fun startBinaryWithRetry(path: String) {
var attempts = 0
while (attempts < 5) {
try {
// Your suspend function call here
runBinary(path)
break // If the function call is successful, break the loop
} catch (e: Exception) {
attempts++
delay(500)
if (attempts == 5) throw e // If this was the last attempt, rethrow the exception
}
}
}
fun getContinueServerUrl(): String {
val settings =
ServiceManager.getService(ContinueExtensionSettings::class.java)
return settings.continueState.serverUrl
}
suspend fun startContinuePythonServer(project: Project) {
println("server starting")
val continuePluginService = ServiceManager.getService(
project,
ContinuePluginService::class.java
)
val settings =
ServiceManager.getService(ContinueExtensionSettings::class.java)
val serverUrl = getContinueServerUrl()
if ((serverUrl != CONTINUE_PYTHON_SERVER_URL && serverUrl != "http://127.0.0.1:65432") || settings.continueState.manuallyRunningServer) {
continuePluginService.dispatchCustomEvent("serverStatus", mutableMapOf(
"type" to "serverStatus",
"message" to "Connecting to Continue Server"
))
println("Continue server being run manually, skipping start")
return
}
if (checkOrKillRunningServer(project)) {
continuePluginService.dispatchCustomEvent("serverStatus", mutableMapOf(
"type" to "serverStatus",
"message" to "Connecting to Continue Server"
))
println("Continue server already running")
return
}
// Determine from OS details which file to download
val filename = when {
System.getProperty("os.name")
.toLowerCase().contains("win") -> "windows/continue_server.exe"
System.getProperty("os.name").startsWith("Mac", ignoreCase = true) ->
if (System.getProperty("os.arch") == "arm64") "apple-silicon/continue_server" else "mac/continue_server"
else -> "linux/continue_server"
}
val destination = serverBinaryPath()
// Check whether the binary needs to be downloaded
var shouldDownload = true
if (File(destination).exists()) {
if (File(serverVersionPath()).exists()) {
val serverVersion = File(serverVersionPath()).readText()
if (serverVersion == getExtensionVersion()) {
println("Continue server already downloaded")
shouldDownload = false
} else {
println("Old version of the server downloaded, removing")
File(destination).delete()
}
} else {
println("Old version of the server downloaded, removing")
File(destination).delete()
}
}
if (shouldDownload) {
continuePluginService.dispatchCustomEvent("serverStatus", mutableMapOf(
"type" to "serverStatus",
"message" to "Downloading Continue server binary"
))
println("Downloading Continue Server Binary")
// Download the binary from S3
try {
downloadFromS3(
"continue-server-binaries",
filename,
destination,
"us-west-1",
false
)
} catch (e: Exception) {
continuePluginService.dispatchCustomEvent("serverStatus", mutableMapOf(
"type" to "serverStatus",
"message" to "First download failed, attempting backup"
))
try {
downloadFromS3(
"continue-server-binaries",
filename,
destination,
"us-west-1",
true
)
} catch (e: Exception) {
continuePluginService.dispatchCustomEvent("serverStatus", mutableMapOf(
"type" to "serverStatus",
"message" to "Failed to download Continue server binary: ${e.message}"
))
throw e
}
}
// Set permissions on the binary
setPermissions(destination)
}
// Validate that the binary exists
if (!File(destination).exists()) {
continuePluginService.dispatchCustomEvent("serverStatus", mutableMapOf(
"type" to "serverStatus",
"message" to "Failed to download Continue server binary"
))
throw Error("Failed to download Continue server binary")
}
// Spawn server process
continuePluginService.dispatchCustomEvent("serverStatus", mutableMapOf(
"type" to "serverStatus",
"message" to "Launching Continue Server"
))
println("Starting Continue server binary")
startBinaryWithRetry(destination)
// Write the server version to server_version.txt
File(serverVersionPath()).writeText(getExtensionVersion())
// Wait for the server process to start
println("Waiting for Continue server to start...")
var i = 1
while (getProcessId(CONTINUE_SERVER_WEBSOCKET_PORT) == null) {
delay(1000)
continuePluginService.dispatchCustomEvent("serverStatus", mutableMapOf(
"type" to "serverStatus",
"message" to "Launching Continue Server" + ".".repeat(i % 4)
))
i++
}
println("Continue server started")
}
class WelcomeDialogWrapper(val project: Project) : DialogWrapper(true) {
private var panel: JPanel? = null
private var paragraph: JTextArea? = null
@ -538,13 +155,11 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
}
GlobalScope.async(Dispatchers.IO) {
startContinuePythonServer(project)
val ideProtocolClient = IdeProtocolClient(
continuePluginService,
defaultStrategy,
coroutineScope,
project.basePath ?: "/",
project.basePath,
project
)

View file

@ -1,4 +1,98 @@
package com.github.continuedev.continueintellijextension.constants
const val CONTINUE_PYTHON_SERVER_URL = "http://localhost:65432"
const val CONTINUE_SERVER_WEBSOCKET_PORT = 65432
import java.nio.file.Files
import java.nio.file.Paths
const val DEFAULT_CONFIG = """
{
models: [
{
title: "GPT-4",
provider: "openai-free-trial",
model: "gpt-4",
},
{
title: "GPT-3.5-Turbo",
provider: "openai-free-trial",
model: "gpt-3.5-turbo",
},
],
modelRoles: {
default: "GPT-4",
summarize: "GPT-3.5-Turbo",
},
slashCommands: [
{
name: "edit",
description: "Edit highlighted code",
step: "EditHighlightedCodeStep",
},
{
name: "comment",
description: "Write comments for the highlighted code",
step: "CommentCodeStep",
},
{
name: "share",
description: "Download and share this session",
step: "ShareSessionStep",
},
{
name: "cmd",
description: "Generate a shell command",
step: "GenerateShellCommandStep",
},
],
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: "diff", params: {} },
{
name: "open",
params: {},
},
{ name: "terminal", params: {} },
],
}
"""
const val DEFAULT_CONFIG_JS = """
function modifyConfig(config) {
return config;
}
export {
modifyConfig
};
"""
fun getContinueGlobalPath(): String {
val continuePath = Paths.get(System.getProperty("user.home"), ".continue")
if (Files.notExists(continuePath)) {
Files.createDirectories(continuePath)
}
return continuePath.toString()
}
fun getConfigJsonPath(): String {
val path = Paths.get(getContinueGlobalPath(), "config.json")
if (Files.notExists(path)) {
Files.createFile(path)
Files.writeString(path, DEFAULT_CONFIG);
}
return path.toString()
}
fun getConfigJsPath(): String {
val path = Paths.get(getContinueGlobalPath(), "config.js")
if (Files.notExists(path)) {
Files.createFile(path)
Files.writeString(path, DEFAULT_CONFIG_JS);
}
return path.toString()
}

View file

@ -1,7 +1,9 @@
package com.github.continuedev.continueintellijextension.`continue`
import com.github.continuedev.continueintellijextension.*
import com.github.continuedev.continueintellijextension.activities.getContinueServerUrl
import com.github.continuedev.continueintellijextension.constants.getConfigJsPath
import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath
import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
@ -16,7 +18,6 @@ import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.util.Computable
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
@ -24,19 +25,14 @@ import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.wm.WindowManager
import com.intellij.testFramework.LightVirtualFile
import com.intellij.ui.awt.RelativePoint
import io.socket.client.Ack
import io.socket.client.IO
import io.socket.client.Socket
import io.socket.emitter.Emitter;
import kotlinx.coroutines.*
import okhttp3.*
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.net.NetworkInterface
import java.net.URI
import java.net.URLEncoder
import java.nio.charset.Charset
import java.nio.file.Files
import java.nio.file.Paths
import java.util.*
@ -45,23 +41,15 @@ fun uuid(): String {
}
data class WebSocketMessage<T>(val message_type: String, val message_id: String, val data: T)
data class WorkspaceDirectory(val workspaceDirectory: String)
data class UniqueId(val uniqueId: String)
data class ReadFile(val contents: String)
data class VisibleFiles(val visibleFiles: List<String>)
data class IdeMessage<T>(val type: String, val messageId: String, val message: T)
data class Position(val line: Int, val character: Int)
data class Range(val start: Position, val end: Position)
data class RangeInFile(val filepath: String, val range: Range)
data class GetTerminalContents(val contents: String)
data class ListDirectoryContents(val contents: List<String>)
data class RangeInFileWithContents(val filepath: String, val range: Range, val contents: String)
data class HighlightedCodeUpdate(val highlightedCode: List<RangeInFileWithContents>, val edit: Boolean)
data class HighlightedCode(val highlightedCode: List<RangeInFile>)
data class AcceptRejectDiff(val accepted: Boolean, val stepIndex: Int)
data class DeleteAtIndex(val index: Int)
data class MainUserInput(val input: String)
data class IdeInfo(val name: String, val version: String?, val remoteName: String?)
fun getMachineUniqueID(): String {
val sb = StringBuilder()
@ -92,62 +80,51 @@ class IdeProtocolClient (
private val continuePluginService: ContinuePluginService,
private val textSelectionStrategy: TextSelectionStrategy,
private val coroutineScope: CoroutineScope,
private val workspacePath: String,
private val workspacePath: String?,
private val project: Project
): DumbAware {
private var webSocket: WebSocket? = null
private var socket: Socket? = null
val diffManager = DiffManager(project)
init {
initWebSocket()
initIdeProtocol()
}
private fun serializeMessage(data: Map<String, Any>): String {
val gson = Gson()
return gson.toJson(data)
}
private fun send(messageType: String, messageId: String, data: Any) {
val wsMessage = WebSocketMessage(
private fun send(messageType: String, data: Any?, messageId: String? = null) {
val id = messageId ?: uuid()
val message = IdeMessage(
messageType,
messageId,
id,
data
)
socket?.send("message", Gson().toJson(wsMessage))
val json = Gson().toJson(message)
continuePluginService.dispatchCustomEvent(json)
}
private fun handleWebsocketMessage(text: String, respond: (String, String, Any) -> Unit) {
fun handleWebsocketMessage(text: String) {
coroutineScope.launch(Dispatchers.IO) {
val parsedMessage: Map<String, Any> = Gson().fromJson(
text,
object : TypeToken<Map<String, Any>>() {}.type
)
val messageType = parsedMessage["message_type"] as? String
val messageId = parsedMessage["message_id"] as? String
if (messageId == null) {
println("Received message without messageId: $text")
val messageType = parsedMessage["type"] as? String
if (messageType == null) {
println("Recieved message without type: $text")
return@launch
}
val data = parsedMessage["data"] as Map<*, *>
// fun respond(t: String, a: String, b: Any) {
//
// }
fun respond(responseData: Any?) {
if (data["messageId"] == null) {
println("Recieved message without messageId: $text")
return
}
send(messageType, responseData, data["messageId"] as String);
}
try {
when (messageType) {
"workspaceDirectory" -> {
respond("workspaceDirectory", messageId, WorkspaceDirectory(workspaceDirectory()))
}
"uniqueId" -> respond(
"uniqueId",
messageId,
UniqueId(uniqueId())
mapOf("uniqueId" to uniqueId())
)
"ide" -> {
@ -157,15 +134,15 @@ class IdeProtocolClient (
val sshClient = System.getenv("SSH_CLIENT")
val sshTty = System.getenv("SSH_TTY")
var remoteName: String? = null
var remoteName: String = "local"
if (sshClient != null || sshTty != null) {
remoteName = "ssh"
}
respond(
"ide",
messageId,
IdeInfo(ideName, ideVersion, remoteName)
)
respond(mapOf(
"name" to ideName,
"version" to ideVersion,
"remoteName" to remoteName
))
}
"showDiff" -> {
@ -177,37 +154,35 @@ class IdeProtocolClient (
}
"readFile" -> {
val msg =
ReadFile(readFile(data["filepath"] as String))
val msg = readFile(data["filepath"] as String)
respond(
"readFile",
messageId,
msg
mapOf("contents" to msg)
)
}
"listDirectoryContents" -> {
respond(
"listDirectoryContents",
messageId,
ListDirectoryContents(listDirectoryContents())
mapOf("contents" to listDirectoryContents())
)
}
"listWorkspaceContents" -> {
respond(listDirectoryContents())
}
"getWorkspaceDirs" -> {
respond(workspaceDirectories())
}
"getTerminalContents" -> {
respond(
"getTerminalContents",
messageId,
GetTerminalContents("Terminal cannot be accessed in JetBrains IDE")
mapOf("contents" to "Terminal cannot be accessed in JetBrains IDE")
)
}
"visibleFiles" -> {
val msg = VisibleFiles(visibleFiles())
respond(
"visibleFiles",
messageId,
msg
mapOf("visibleFiles" to visibleFiles())
)
}
@ -242,13 +217,50 @@ class IdeProtocolClient (
val rif = RangeInFile(rifWithContents.filepath, rifWithContents.range)
rifs += rif
}
respond(
"highlightedCode",
messageId,
HighlightedCode(rifs)
)
respond(mapOf("highlightedCode" to rifs))
}
// NEW //
"getDiff" -> {
respond("");
}
"getSerializedConfig" -> {
val configPath = getConfigJsonPath()
val config = File(configPath).readText()
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()
val configJsContents = File(configJsPath).readText()
val configJsDataUrl = "data:text/javascript;base64,${Base64.getEncoder().encodeToString(configJsContents.toByteArray())}"
respond(configJsDataUrl)
}
"writeFile" -> {
val msg = data["message"] as Map<String, String>;
val file = File(msg["path"])
file.writeText(msg["contents"] as String)
respond(null);
}
"getContinueDir" -> {
respond(getContinueGlobalPath())
}
"openFile" -> {
setFileOpen((data["message"] as Map<String, Any>)["path"] as String)
respond(null)
}
"runCommand" -> {
respond(null)
// Running commands not yet supported in JetBrains
}
"errorPopup" -> {
showMessage(data["message"] as String)
}
else -> {
println("Unknown messageType: $messageType")
}
@ -259,7 +271,7 @@ class IdeProtocolClient (
}
}
private fun initWebSocket() {
private fun initIdeProtocol() {
val applicationInfo = ApplicationInfo.getInstance()
val ideName: String = applicationInfo.fullApplicationName
val ideVersion = applicationInfo.fullVersion
@ -277,76 +289,21 @@ class IdeProtocolClient (
)
val windowInfo = mapOf(
"window_id" to continuePluginService.windowId,
"workspace_directory" to workspaceDirectory(),
"unique_id" to uniqueId(),
"ide_info" to IDEInfo(
name = ideName,
version = ideVersion,
remote_name = remoteName ?: ""
),
"server_url" to getContinueServerUrl()
"window_id" to continuePluginService.windowId,
"unique_id" to uniqueId(),
"ide_info" to IDEInfo(
name = ideName,
version = ideVersion,
remote_name = remoteName ?: ""
),
)
val requestUrl = "${getContinueServerUrl()}/?window_info=${
URLEncoder.encode(
Gson().toJson(windowInfo), "UTF-8"
)}"
val uri: URI = URI.create(requestUrl)
val options: IO.Options = IO.Options.builder()
.setPath("/ide/socket.io")
.setTransports(arrayOf("websocket", "polling", "flashsocket"))
.build()
val socket: Socket = IO.socket(uri, options)
socket.on(Socket.EVENT_CONNECT) {
println("Connected to Continue IDE websocket")
}
socket.on(Socket.EVENT_DISCONNECT) {
println("Disconnected from Continue IDE websocket")
}
socket.on(Socket.EVENT_CONNECT_ERROR, { args ->
println("Error connecting to Continue IDE websocket")
println(args[0].toString())
})
socket.on("message") { args ->
val data = args[0].toString()
if (args.size == 1) {
println("Received message without ack: $data")
return@on
}
val ack = args[args.size - 1] as Ack
fun respond(messageType: String, messageId: String, data: Any) {
val wsMessage = WebSocketMessage(
messageType,
messageId,
data
)
ack.call(Gson().toJson(wsMessage))
}
handleWebsocketMessage(data, ::respond)
// ack.call()
}
socket.connect()
this.socket = socket
}
private fun sendMessage(messageType: String, message: Map<String, Any>) {
val sendData = mapOf("message_type" to messageType, "data" to message)
val jsonMessage = serializeMessage(sendData)
webSocket?.send(jsonMessage)
}
private fun workspaceDirectory(): String {
return this.workspacePath
private fun workspaceDirectories(): Array<String> {
if (this.workspacePath != null) {
return arrayOf(this.workspacePath)
}
return arrayOf<String>();
}
fun uniqueId(): String {
@ -397,6 +354,10 @@ class IdeProtocolClient (
}
}
fun readRangeInFile(rangeInFile: RangeInFile): String {
return "TODO"
}
private fun getHighlightedCode(): RangeInFileWithContents? {
val result = ApplicationManager.getApplication().runReadAction<RangeInFileWithContents?> {
@ -439,28 +400,28 @@ class IdeProtocolClient (
// edit
// ))
continuePluginService.dispatchCustomEvent("highlightedCode",
mapOf(
continuePluginService.dispatchCustomEvent(
Gson().toJson(mapOf(
"type" to "highlightedCode",
"rangeInFileWithContents" to rif,
"edit" to edit
))
)))
}
fun sendMainUserInput(input: String) {
continuePluginService.dispatchCustomEvent("userInput",
mapOf(
val data = mapOf(
"type" to "userInput",
"input" to input,
))
)
continuePluginService.dispatchCustomEvent(Gson().toJson(data))
}
fun sendAcceptRejectDiff(accepted: Boolean, stepIndex: Int) {
send("acceptRejectDiff", uuid(), AcceptRejectDiff(accepted, stepIndex))
send("acceptRejectDiff", AcceptRejectDiff(accepted, stepIndex), uuid())
}
fun deleteAtIndex(index: Int) {
send("deleteAtIndex", uuid(), DeleteAtIndex(index))
send("deleteAtIndex", DeleteAtIndex(index), uuid())
}
private val DEFAULT_IGNORE_DIRS = listOf(
@ -491,20 +452,25 @@ class IdeProtocolClient (
private fun listDirectoryContents(): List<String> {
val workspacePath = File(workspaceDirectory())
val workspaceDir = VirtualFileManager.getInstance().findFileByUrl("file://$workspacePath")
val dirs = workspaceDirectories()
val contents = ArrayList<String>()
if (workspaceDir != null) {
VfsUtil.iterateChildrenRecursively(workspaceDir, null) { virtualFile: VirtualFile ->
if (!virtualFile.isDirectory) {
val filePath = virtualFile.path
if (!shouldIgnoreDirectory(filePath)) {
contents.add(filePath)
for (dir in dirs) {
val workspacePath = File(dir)
val workspaceDir = VirtualFileManager.getInstance().findFileByUrl("file://$workspacePath")
if (workspaceDir != null) {
VfsUtil.iterateChildrenRecursively(workspaceDir, null) { virtualFile: VirtualFile ->
if (!virtualFile.isDirectory) {
val filePath = virtualFile.path
if (!shouldIgnoreDirectory(filePath)) {
contents.add(filePath)
}
}
true
}
true
}
}

View file

@ -1,6 +0,0 @@
package com.github.continuedev.continueintellijextension.`continue`
interface WebSocketEventListener {
fun onMessageReceived(message: String)
fun onErrorOccurred(error: Throwable)
}

View file

@ -6,10 +6,8 @@ import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.options.Configurable
import com.intellij.openapi.project.DumbAware
import kotlinx.serialization.Serializable
import java.awt.GridBagConstraints
import java.awt.GridBagLayout
import javax.annotation.Nullable
import javax.swing.JCheckBox
import javax.swing.JComponent
import javax.swing.JLabel
@ -18,9 +16,6 @@ import javax.swing.JTextField
class ContinueSettingsComponent: DumbAware {
val panel: JPanel = JPanel(GridBagLayout())
private val myTextField: JTextField = JTextField()
private val myCheckBox: JCheckBox =
JCheckBox("Manually Running Continue Server")
init {
val constraints = GridBagConstraints()
@ -31,16 +26,6 @@ class ContinueSettingsComponent: DumbAware {
constraints.gridx = 0
constraints.gridy = GridBagConstraints.RELATIVE
val serverURLLabel = JLabel("Server URL")
panel.add(serverURLLabel, constraints)
panel.add(myTextField, constraints)
val runningServerLabel = JLabel("Manually Running Server")
panel.add(runningServerLabel, constraints)
panel.add(myCheckBox, constraints)
// Add a "filler" component that takes up all remaining vertical space
constraints.weighty = 1.0
val filler = JPanel()
@ -48,17 +33,6 @@ class ContinueSettingsComponent: DumbAware {
}
var serverUrl: String?
get() = myTextField.text
set(newText) {
myTextField.text = newText
}
var manuallyRunningServer: Boolean
get() = myCheckBox.isSelected
set(value) {
myCheckBox.isSelected = value
}
}
@State(
@ -68,8 +42,6 @@ class ContinueSettingsComponent: DumbAware {
open class ContinueExtensionSettings : PersistentStateComponent<ContinueExtensionSettings.ContinueState> {
class ContinueState {
var serverUrl: String = "http://localhost:65432"
var manuallyRunningServer: Boolean = false
var shownWelcomeDialog: Boolean = false
}
@ -99,24 +71,17 @@ class ContinueExtensionConfigurable : Configurable {
override fun isModified(): Boolean {
val settings = ServiceManager.getService(ContinueExtensionSettings::class.java)
return mySettingsComponent!!.serverUrl != settings.continueState.serverUrl || mySettingsComponent!!.manuallyRunningServer != settings.continueState.manuallyRunningServer
return false;
}
override fun apply() {
val settings =
ServiceManager.getService(ContinueExtensionSettings::class.java)
settings.continueState.serverUrl =
mySettingsComponent?.serverUrl ?: "http://localhost:65432"
settings.continueState.manuallyRunningServer =
mySettingsComponent!!.manuallyRunningServer
}
override fun reset() {
val settings =
ServiceManager.getService(ContinueExtensionSettings::class.java)
mySettingsComponent!!.serverUrl = settings.continueState.serverUrl
mySettingsComponent!!.manuallyRunningServer =
settings.continueState.manuallyRunningServer
}
override fun disposeUIResources() {

View file

@ -34,12 +34,9 @@ class ContinuePluginService(project: Project) : Disposable, DumbAware {
}
fun dispatchCustomEvent(
type: String,
data: Map<String, Any>
data: String
) {
val gson = Gson()
val jsonData = gson.toJson(data)
val jsCode = buildJavaScript(type, jsonData)
val jsCode = buildJavaScript(data)
try {
continuePluginWindow?.webView?.executeJavaScriptAsync(jsCode)
@ -48,7 +45,7 @@ class ContinuePluginService(project: Project) : Disposable, DumbAware {
}
}
private fun buildJavaScript(type: String, jsonData: String): String {
private fun buildJavaScript(jsonData: String): String {
return """window.postMessage($jsonData, "*");"""
}

View file

@ -1,6 +1,6 @@
package com.github.continuedev.continueintellijextension.toolWindow
import com.github.continuedev.continueintellijextension.activities.getContinueServerUrl
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
@ -10,9 +10,7 @@ import com.github.continuedev.continueintellijextension.services.ContinuePluginS
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionToolbar
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.editor.colors.EditorColorsManager
@ -28,7 +26,6 @@ import kotlinx.coroutines.launch
import org.cef.CefApp
import org.cef.browser.CefBrowser
import org.cef.handler.CefLoadHandlerAdapter
import java.awt.BorderLayout
import javax.swing.*
import kotlin.math.max
import kotlin.math.min
@ -86,6 +83,9 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
val json: JsonObject = parser.parse(msg).asJsonObject
val type = json.get("type").asString
val data = json.get("data").asJsonObject
val ide = continuePluginService.ideProtocolClient;
when (type) {
"onLoad" -> {
GlobalScope.launch {
@ -122,7 +122,6 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
val jsonData = mutableMapOf(
"type" to "onLoad",
"windowId" to continuePluginService.windowId,
"serverUrl" to getContinueServerUrl(),
"workspacePaths" to continuePluginService.worksapcePaths,
"vscMachineId" to getMachineUniqueID(),
"vscMediaUrl" to "http://continue",
@ -133,7 +132,30 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
}
"showLines" -> {
continuePluginService.ideProtocolClient?.highlightCode(RangeInFile(
ide?.highlightCode(RangeInFile(
data.get("filepath").asString,
Range(Position(
data.get("start").asInt,
0
), Position(
data.get("end").asInt,
0
)),
),"#00ff0022")
}
"showVirtualFile" -> {
ide?.showVirtualFile(data.get("name").asString, data.get("content").asString)
}
"showFile" -> {
ide?.setFileOpen(data.get("filepath").asString)
}
"reloadWindow" -> {}
"openConfigJson" -> {
ide?.setFileOpen(getConfigJsonPath())
}
"readRangeInFile" -> {
ide?.readRangeInFile(RangeInFile(
data.get("filepath").asString,
Range(Position(
data.get("start").asInt,
@ -142,16 +164,16 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
data.get("end").asInt + 1,
0
)),
))
}
"focusEditor" -> {}
),"#00ff0022")
// IDE //
else -> {
if (msg != null) {
ide?.handleWebsocketMessage(msg)
}
}
"showVirtualFile" -> {
continuePluginService.ideProtocolClient?.showVirtualFile(data.get("name").asString, data.get("content").asString)
}
"showFile" -> {
continuePluginService.ideProtocolClient?.setFileOpen(data.get("filepath").asString)
}
"reloadWindow" -> {}
}

View file

@ -276,7 +276,7 @@ export function getSidebarContent(
respond(await ide.listWorkspaceContents());
break;
}
case "getWorkspaceDir": {
case "getWorkspaceDirs": {
respond(await ide.getWorkspaceDirs());
break;
}

View file

@ -81,3 +81,9 @@ export function deleteModel(title: any) {
export function addOpenAIKey(key: string) {
postToIde("addOpenAIKey", { key });
}
export function appendText(text: string) {
const div = document.createElement("div");
div.innerText = text;
document.body.appendChild(div);
}