diff --git a/extensions/intellij/CONTRIBUTING.md b/extensions/intellij/CONTRIBUTING.md index c8b040424..5ea6929f2 100644 --- a/extensions/intellij/CONTRIBUTING.md +++ b/extensions/intellij/CONTRIBUTING.md @@ -1,6 +1,7 @@ # Contributing to Continue (JetBrains extension) -This file is for contribution guidelines specific to the JetBrains extension. See the root [`CONTRIBUTING.md`](../../CONTRIBUTING.md) for general contribution guidelines. +This file is for contribution guidelines specific to the JetBrains extension. See the root [ +`CONTRIBUTING.md`](../../CONTRIBUTING.md) for general contribution guidelines. ## Table of Contents @@ -13,11 +14,10 @@ This file is for contribution guidelines specific to the JetBrains extension. Se - [Misc](#misc) - [Development Workflow](#development-workflow) - [Running the extension](#running-the-extension) - - [Available Gradle tasks](#available-gradle-tasks) -- [Debugging](#debugging) - [Reloading changes](#reloading-changes) - [Setting breakpoints](#setting-breakpoints) -- [Packaging](#packaging) + - [Available Gradle tasks](#available-gradle-tasks) + - [Packaging](#packaging) ## Architecture Overview @@ -57,13 +57,31 @@ This project requires Node.js version 20.11.0 (LTS) or higher. You have two opti ## Development Workflow +Because the `gui` and `core` are written in TypeScript, our development workflow is built around the assumption that you have VS Code installed. + ### Running the extension -- Select the "Run Continue" Gradle configuration in the top-right corner of the IDE -- Click the "Run" or "Debug" button - - The first time running this will install the IDE version specified by the `platformVersion` property in [`./run/Run Continue.run.xml`](./.run/Run%20Continue.run.xml). This will take a moment as the installation size can be close to 1GB. +- Open the project in VS Code and star the `Core binary` task +- Switch back to Intellij and select the "Run Continue" configuration in the top-right corner of the IDE +- Click the "Debug" button + - The first time running this will install the IDE version specified by the `platformVersion` property in [`./run/Run Extension.run.xml`](./.run/Run%20Extension.run.xml). This will take a moment as the installation size can be close to 1GB. -![run-extension-screenshot](../../media/run-intellij-extension.png) +![run-extension-screenshot](../../media/run-intellij-extension.png)\ + +This should open a new instance on IntelliJ with the extension installed and connected via TCP to the server started through the `Core binary` task. + +### Reloading changes + +- `extensions/intellij`: Attempt to reload changed classes by selecting `Run | Debugging Actions | Reload Changed Classes` + - This will often fail on new imports, schema changes etc. In that case, you need to stop and restart the extension +- `gui`: Changes will be reloaded automatically +- `core`: Run `npm run build` from the `binary` directory and restart the `Core binary` task in VS Code + +### Setting breakpoints + +- `extensions/intellij`: Breakpoints can be set in Intellij +- `gui`: You'll need to set explicit `debugger` statements in the source code, or through the browser dev tools +- `core`: Breakpoints can be set in VS Code ### Available Gradle tasks @@ -83,30 +101,10 @@ runIde - Runs the IDE instance with the developed plugin installed. verifyPluginConfiguration - Checks if Java and Kotlin compilers configuration meet IntelliJ SDK requirements ``` -## Debugging - -### Reloading changes - -- `extensions/intellij`: Attempt to reload changed classes by selecting - `Run | Debugging Actions | Reload Changed Classes` - - This will often fail on new imports, schema changes etc. In that case, you need to stop and restart the extension -- `gui`: Run `npm run build` from the `gui` directory -- `core`: Run `npm run build` from the `binary` directory - -### Setting breakpoints - -- `extensions/intellij`: Run the extension in debug mode -- `gui`: You'll need to set explicit `debugger` statements in the source code, or through the browser dev tools -- `core`: To set breakpoints in `core`, we need to start `binary` in a debug configuration - - Select the "Run Continue (TCP)" task in the top right corner - - Open the project in a VS Code window (we recommend this for a preconfigured Typescript debugging experience) - - Select the "Core Binary" task from the Run and Debug panel - - You can now set breakpoints in `core`. Note that if you make changes, you'll need to restart the "Core Binary" - task and reload changes classes in Intellij. - -## Packaging +### Packaging - Unix: `./gradlew build` - Windows: `./gradlew.bat build` -This will generate a .zip file in `./build/distributions` with the version defined in [`./gradle.properties`](./gradle.properties) +This will generate a .zip file in `./build/distributions` with the version defined in [ +`./gradle.properties`](./gradle.properties) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt index b47818158..3934029b1 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt @@ -1,19 +1,19 @@ package com.github.continuedev.continueintellijextension.`continue` +import com.github.continuedev.continueintellijextension.constants.MessageTypes import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.github.continuedev.continueintellijextension.services.TelemetryService -import com.github.continuedev.continueintellijextension.constants.MessageTypes import com.google.gson.Gson import com.intellij.openapi.components.service import com.intellij.openapi.project.Project -import kotlinx.coroutines.* import java.io.* import java.net.Socket import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Paths import java.nio.file.attribute.PosixFilePermission +import kotlinx.coroutines.* class CoreMessenger( private val project: Project, @@ -22,235 +22,218 @@ class CoreMessenger( private val ideProtocolClient: IdeProtocolClient, coroutineScope: CoroutineScope ) { - private var writer: Writer? = null - private var reader: BufferedReader? = null - private var process: Process? = null - private val gson = Gson() - private val responseListeners = mutableMapOf Unit>() - private val useTcp: Boolean = System.getenv("USE_TCP")?.toBoolean() ?: false + private var writer: Writer? = null + private var reader: BufferedReader? = null + private var process: Process? = null + private val gson = Gson() + private val responseListeners = mutableMapOf Unit>() + private val useTcp: Boolean = System.getenv("USE_TCP")?.toBoolean() ?: false - private fun write(message: String) { - try { - writer?.write(message + "\r\n") - writer?.flush() - } catch (e: Exception) { - println("Error writing to Continue core: $e") - } + private fun write(message: String) { + try { + writer?.write(message + "\r\n") + writer?.flush() + } catch (e: Exception) { + println("Error writing to Continue core: $e") } + } - fun request(messageType: String, data: Any?, messageId: String?, onResponse: (Any?) -> Unit) { - val id = messageId ?: uuid() - val message = gson.toJson( - mapOf( - "messageId" to id, - "messageType" to messageType, - "data" to data - ) - ) - responseListeners[id] = onResponse + fun request(messageType: String, data: Any?, messageId: String?, onResponse: (Any?) -> Unit) { + val id = messageId ?: uuid() + val message = + gson.toJson(mapOf("messageId" to id, "messageType" to messageType, "data" to data)) + responseListeners[id] = onResponse + write(message) + } + + private fun handleMessage(json: String) { + val responseMap = gson.fromJson(json, Map::class.java) + val messageId = responseMap["messageId"].toString() + val messageType = responseMap["messageType"].toString() + val data = responseMap["data"] + + // IDE listeners + if (MessageTypes.ideMessageTypes.contains(messageType)) { + ideProtocolClient.handleMessage(json) { data -> + val message = + gson.toJson( + mapOf("messageId" to messageId, "messageType" to messageType, "data" to data)) write(message) + } } - private fun handleMessage(json: String) { - val responseMap = gson.fromJson(json, Map::class.java) - val messageId = responseMap["messageId"].toString() - val messageType = responseMap["messageType"].toString() - val data = responseMap["data"] - - // IDE listeners - if (MessageTypes.ideMessageTypes.contains(messageType)) { - ideProtocolClient.handleMessage(json) { data -> - val message = gson.toJson( - mapOf( - "messageId" to messageId, - "messageType" to messageType, - "data" to data - ) - ) - write(message) - }; - } - - // Forward to webview - if (MessageTypes.PASS_THROUGH_TO_WEBVIEW.contains(messageType)) { - // TODO: Currently we aren't set up to receive a response back from the webview - // Can circumvent for getDefaultsModelTitle here for now - if (messageType == "getDefaultModelTitle") { - val continueSettingsService = service() - val defaultModelTitle = continueSettingsService.continueState.lastSelectedInlineEditModel; - val message = gson.toJson( - mapOf( - "messageId" to messageId, - "messageType" to messageType, - "data" to defaultModelTitle - ) - ) - write(message) - } - val continuePluginService = project.service() - continuePluginService.sendToWebview(messageType, responseMap["data"], messageType) - } - - // Responses for messageId - responseListeners[messageId]?.let { listener -> - listener(data) - if (MessageTypes.generatorTypes.contains(messageType)) { - val done = (data as Map)["done"] - if (done == true) { - responseListeners.remove(messageId) - } else { - } - } else { - responseListeners.remove(messageId) - } - - } + // Forward to webview + if (MessageTypes.PASS_THROUGH_TO_WEBVIEW.contains(messageType)) { + // TODO: Currently we aren't set up to receive a response back from the webview + // Can circumvent for getDefaultsModelTitle here for now + if (messageType == "getDefaultModelTitle") { + val continueSettingsService = service() + val defaultModelTitle = continueSettingsService.continueState.lastSelectedInlineEditModel + val message = + gson.toJson( + mapOf( + "messageId" to messageId, + "messageType" to messageType, + "data" to defaultModelTitle)) + write(message) + } + val continuePluginService = project.service() + continuePluginService.sendToWebview(messageType, responseMap["data"], messageType) } - private fun setPermissions(destination: String) { - val osName = System.getProperty("os.name").toLowerCase() - if (osName.contains("mac") || osName.contains("darwin")) { - ProcessBuilder( - "xattr", - "-dr", - "com.apple.quarantine", - destination - ).start() - setFilePermissions(destination, "rwxr-xr-x") - } else if (osName.contains("nix") || osName.contains("nux") || osName.contains("mac")) { - setFilePermissions(destination, "rwxr-xr-x") - } + // Responses for messageId + responseListeners[messageId]?.let { listener -> + listener(data) + if (MessageTypes.generatorTypes.contains(messageType)) { + val done = (data as Map)["done"] + if (done == true) { + responseListeners.remove(messageId) + } else {} + } else { + responseListeners.remove(messageId) + } } + } - private fun setFilePermissions(path: String, posixPermissions: String) { - val perms = HashSet() - 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) + private fun setPermissions(destination: String) { + val osName = System.getProperty("os.name").toLowerCase() + if (osName.contains("mac") || osName.contains("darwin")) { + ProcessBuilder("xattr", "-dr", "com.apple.quarantine", destination).start() + setFilePermissions(destination, "rwxr-xr-x") + } else if (osName.contains("nix") || osName.contains("nux") || osName.contains("mac")) { + setFilePermissions(destination, "rwxr-xr-x") } + } - private val exitCallbacks: MutableList<() -> Unit> = mutableListOf() - fun onDidExit(callback: () -> Unit) { - exitCallbacks.add(callback) - } + private fun setFilePermissions(path: String, posixPermissions: String) { + val perms = HashSet() + if (posixPermissions.contains("r")) perms.add(PosixFilePermission.OWNER_READ) + if (posixPermissions.contains("w")) perms.add(PosixFilePermission.OWNER_WRITE) + if (posixPermissions.contains("x")) perms.add(PosixFilePermission.OWNER_EXECUTE) + Files.setPosixFilePermissions(Paths.get(path), perms) + } - init { - if (useTcp) { - try { - val socket = Socket("127.0.0.1", 3000) - val writer = PrintWriter(socket.getOutputStream(), true) - this.writer = writer - val reader = BufferedReader(InputStreamReader(socket.getInputStream())) - this.reader = reader + private val exitCallbacks: MutableList<() -> Unit> = mutableListOf() - Thread { + fun onDidExit(callback: () -> Unit) { + exitCallbacks.add(callback) + } + + init { + if (useTcp) { + try { + val socket = Socket("127.0.0.1", 3000) + val writer = PrintWriter(socket.getOutputStream(), true) + this.writer = writer + val reader = BufferedReader(InputStreamReader(socket.getInputStream())) + this.reader = reader + + Thread { + try { + while (true) { + val line = reader.readLine() + if (line != null && line.isNotEmpty()) { try { - while (true) { - val line = reader.readLine() - if (line != null && line.isNotEmpty()) { - try { - handleMessage(line) - } catch (e: Exception) { - println("Error handling message: $line") - println(e) - } - } else { - Thread.sleep(100) - } - } - } catch (e: IOException) { - e.printStackTrace() - } finally { - try { - reader.close() - writer.close() - } catch (e: IOException) { - e.printStackTrace() - } - } - }.start() - } catch (e: Exception) { - println("An error occurred: ${e.message}") - } - } else { - // Set proper permissions - coroutineScope.launch(Dispatchers.IO) { - setPermissions(continueCorePath) - setPermissions(esbuildPath) - } - - // Start the subprocess - val processBuilder = ProcessBuilder(continueCorePath) - .directory(File(continueCorePath).parentFile) - process = processBuilder.start() - - val outputStream = process!!.outputStream - val inputStream = process!!.inputStream - - writer = OutputStreamWriter(outputStream, StandardCharsets.UTF_8) - reader = BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8)) - - process!!.onExit().thenRun { - exitCallbacks.forEach { it() } - var err = process?.errorStream?.bufferedReader()?.readText()?.trim() - if (err != null) { - // There are often "⚡️Done in Xms" messages, and we want everything after the last one - val delimiter = "⚡ Done in" - val doneIndex = err.lastIndexOf(delimiter) - if (doneIndex != -1) { - err = err.substring(doneIndex + delimiter.length) + handleMessage(line) + } catch (e: Exception) { + println("Error handling message: $line") + println(e) } + } else { + Thread.sleep(100) + } } - - println("Core process exited with output: $err") - CoroutineScope(Dispatchers.Main).launch { - ideProtocolClient.showToast("error", "Core process exited with output: $err") - } - - // Log the cause of the failure - val telemetryService = service() - telemetryService.capture( - "jetbrains_core_exit", mapOf( - "error" to err - ) - ) - - // Clean up all resources - writer?.close() - reader?.close() - process?.destroy() - } - - coroutineScope.launch(Dispatchers.IO) { + } catch (e: IOException) { + e.printStackTrace() + } finally { try { - while (true) { - val line = reader?.readLine() - if (line != null && line.isNotEmpty()) { - try { - handleMessage(line) - } catch (e: Exception) { - println("Error handling message: $line") - println(e) - } - } else { - delay(100) - } - } + reader.close() + writer.close() } catch (e: IOException) { - e.printStackTrace() - } finally { - try { - reader?.close() - writer?.close() - outputStream.close() - inputStream.close() - process?.destroy() - } catch (e: IOException) { - e.printStackTrace() - } + e.printStackTrace() } + } } + .start() + } catch (e: Exception) { + println("TCP Connection Error: Unable to connect to 127.0.0.1:3000") + println("Reason: ${e.message}") + e.printStackTrace() + } + } else { + // Set proper permissions + coroutineScope.launch(Dispatchers.IO) { + setPermissions(continueCorePath) + setPermissions(esbuildPath) + } + + // Start the subprocess + val processBuilder = + ProcessBuilder(continueCorePath).directory(File(continueCorePath).parentFile) + process = processBuilder.start() + + val outputStream = process!!.outputStream + val inputStream = process!!.inputStream + + writer = OutputStreamWriter(outputStream, StandardCharsets.UTF_8) + reader = BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8)) + + process!!.onExit().thenRun { + exitCallbacks.forEach { it() } + var err = process?.errorStream?.bufferedReader()?.readText()?.trim() + if (err != null) { + // There are often "⚡️Done in Xms" messages, and we want everything after the last one + val delimiter = "⚡ Done in" + val doneIndex = err.lastIndexOf(delimiter) + if (doneIndex != -1) { + err = err.substring(doneIndex + delimiter.length) + } } + + println("Core process exited with output: $err") + CoroutineScope(Dispatchers.Main).launch { + ideProtocolClient.showToast("error", "Core process exited with output: $err") + } + + // Log the cause of the failure + val telemetryService = service() + telemetryService.capture("jetbrains_core_exit", mapOf("error" to err)) + + // Clean up all resources + writer?.close() + reader?.close() + process?.destroy() + } + + coroutineScope.launch(Dispatchers.IO) { + try { + while (true) { + val line = reader?.readLine() + if (line != null && line.isNotEmpty()) { + try { + handleMessage(line) + } catch (e: Exception) { + println("Error handling message: $line") + println(e) + } + } else { + delay(100) + } + } + } catch (e: IOException) { + e.printStackTrace() + } finally { + try { + reader?.close() + writer?.close() + outputStream.close() + inputStream.close() + process?.destroy() + } catch (e: IOException) { + e.printStackTrace() + } + } + } } + } } diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 64dd51f97..c12ade5b7 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -559,7 +559,6 @@ function TipTapEditor(props: TipTapEditorProps) { ); if (isJetBrains()) { - // debugger; if (code === "KeyJ") { setIgnoreHighlightedCode(true); setTimeout(() => { @@ -567,49 +566,51 @@ function TipTapEditor(props: TipTapEditorProps) { }, 100); } - handleMetaKeyPressJetBrains(e, text, editor.commands.setContent); - return; - } + if (isMetaEquivalentKeyPressed(e)) { + handleMetaKeyPressJetBrains(e, text, editor.commands.setContent); + } + } else { + if (code === "KeyL") { + debugger; + setIgnoreHighlightedCode(true); + setTimeout(() => { + setIgnoreHighlightedCode(false); + }, 100); + return; + } - if (code === "KeyL") { - setIgnoreHighlightedCode(true); - setTimeout(() => { - setIgnoreHighlightedCode(false); - }, 100); - return; - } - - switch (key) { - case "x": - if (isWebEnv) { - await navigator.clipboard.writeText(text); - editor.commands.deleteSelection(); - } else { - document.execCommand("cut"); - } - break; - case "c": - if (isWebEnv) { - await navigator.clipboard.writeText(text); - } else { - document.execCommand("copy"); - } - break; - case "v": - if (isWebEnv) { - const clipboardText = await navigator.clipboard.readText(); - editor.commands.insertContent(clipboardText); - } else { - document.execCommand("paste"); - } - break; + switch (key) { + case "x": + if (isWebEnv) { + await navigator.clipboard.writeText(text); + editor.commands.deleteSelection(); + } else { + document.execCommand("cut"); + } + break; + case "c": + if (isWebEnv) { + await navigator.clipboard.writeText(text); + } else { + document.execCommand("copy"); + } + break; + case "v": + if (isWebEnv) { + const clipboardText = await navigator.clipboard.readText(); + editor.commands.insertContent(clipboardText); + } else { + document.execCommand("paste"); + } + break; + } } } else if (e.key === "Escape") { ideMessenger.post("focusEditor", undefined); } }; - const handleKeyUp = (event: React.KeyboardEvent) => { + const handleKeyUp = () => { setActiveKey(null); }; diff --git a/gui/src/util/handleMetaKeyPressJetBrains.ts b/gui/src/util/handleMetaKeyPressJetBrains.ts index 7184f5e84..70740262c 100644 --- a/gui/src/util/handleMetaKeyPressJetBrains.ts +++ b/gui/src/util/handleMetaKeyPressJetBrains.ts @@ -12,8 +12,12 @@ export const handleMetaKeyPressJetBrains = ( handleMetaBackspace(e, text, setText, selectionStart, selectionEnd); } - if (getPlatform() === "mac" && ["ArrowLeft", "ArrowRight"].includes(e.key)) { - handleMacArrowKeys(e, text, selectionStart, selectionEnd); + if (getPlatform() === "mac") { + if (e.key === "ArrowLeft") { + handleMacArrowLeftKey(e); + } else if (e.key === "ArrowRight") { + handleMacArrowRightKey(e); + } } }; @@ -40,81 +44,34 @@ const handleMetaBackspace = ( target.setSelectionRange(newStart, newStart); }; -// const handleMacArrowKeys = ( -// e: KeyboardEvent, -// text: string, -// start: number, -// end: number, -// ) => { -// debugger; -// const target = e.target as HTMLDivElement; -// const selection = window.getSelection(); -// const range = document.createRange(); - -// let newStart = start, -// newEnd = end; - -// if (e.key === "ArrowLeft") { -// newStart = text.lastIndexOf("\n", start - 1) + 1; -// newEnd = e.shiftKey ? end : newStart; -// } else if (e.key === "ArrowRight") { -// const nextNewline = text.indexOf("\n", end); -// newEnd = nextNewline === -1 ? text.length : nextNewline; -// newStart = e.shiftKey ? start : newEnd; -// } - -// range.setStart(target.firstChild!, newStart); -// range.setEnd(target.firstChild!, newEnd); - -// selection?.removeAllRanges(); -// selection?.addRange(range); -// }; - -const handleMacArrowKeys = ( - e: KeyboardEvent, - text: string, - start: number, - end: number, -) => { +const handleMacArrowLeftKey = (e: KeyboardEvent) => { const target = e.target as HTMLDivElement; - const paragraph = target.firstChild as HTMLParagraphElement; const selection = window.getSelection(); + const range = document.createRange(); - if (!selection) return; - - let newPosition: number; - - if (e.key === "ArrowLeft") { - newPosition = 0; // Beginning of the paragraph - } else if (e.key === "ArrowRight") { - newPosition = paragraph.textContent?.length - 1 || 0; // End of the paragraph - - const range = document.createRange(); //Create a range (a range is a like the selection but invisible) - range.selectNodeContents(target); //Select the entire contents of the element with the range - range.collapse(false); //collapse the range to the end point. false means collapse to end rather than the start - selection.removeAllRanges(); //remove any selections already made - selection.addRange(range); //make the range you have just created the visible selection - return; + if (e.shiftKey) { + selection.modify("extend", "backward", "character"); } else { - return; + range.setStart(target.firstChild, 0); + range.setEnd(target.firstChild, 0); + + selection.removeAllRanges(); + selection.addRange(range); } +}; + +const handleMacArrowRightKey = (e: KeyboardEvent) => { + const selection = window.getSelection(); + const range = document.createRange(); + const target = e.target as HTMLDivElement; if (e.shiftKey) { - // If Shift key is pressed, extend the selection - if (selection.anchorNode === paragraph) { - range.setStart(paragraph, selection.anchorOffset); - } else { - range.setStart(paragraph, 0); - } - range.setEnd(paragraph, newPosition); + selection.modify("extend", "forward", "character"); } else { - // If Shift key is not pressed, just move the cursor - range.setStart(paragraph, newPosition); - range.collapse(true); + range.selectNodeContents(target); + range.collapse(false); + selection.removeAllRanges(); + selection.addRange(range); } - - // Apply the new selection - selection.removeAllRanges(); - selection.addRange(range); }; diff --git a/media/run-continue-intellij.png b/media/run-continue-intellij.png new file mode 100644 index 000000000..75d0a04f3 Binary files /dev/null and b/media/run-continue-intellij.png differ diff --git a/media/run-intellij-extension.png b/media/run-intellij-extension.png deleted file mode 100644 index 4c2a5a479..000000000 Binary files a/media/run-intellij-extension.png and /dev/null differ