truetrue
diff --git a/extensions/intellij/CONTRIBUTING.md b/extensions/intellij/CONTRIBUTING.md
index 9757bc430..fc1fdaa24 100644
--- a/extensions/intellij/CONTRIBUTING.md
+++ b/extensions/intellij/CONTRIBUTING.md
@@ -101,6 +101,32 @@ allow for changes to your `config.json` and other files during development, with
When using the `Run Continue` task, we automatically tail both prompt logs and IDE logs.
+#### Viewing more IDE logs
+
+You can selectively increase the log granularity (e.g., debug-level logs) as follows:
+
+- Navigate to `Help | Diagnostic Tools | Debug Log Settings...`
+- Add a line in the format: `com.intellij.diagnostic:debug`
+
+You can find more information about this feature in [official docs](https://youtrack.jetbrains.com/articles/SUPPORT-A-43/How-to-enable-debug-logging-in-IntelliJ-IDEA).
+
+### Developing `build.plugin.kts`
+
+If in doubt, check out the
+official [IntelliJ Platform Plugin Template](https://github.com/JetBrains/intellij-platform-plugin-template).
+These templates are the most up-to-date examples of how to correctly customize the plugin build scripts.
+
+Also, check out
+the [useful recipes](https://plugins.jetbrains.com/docs/intellij/tools-intellij-platform-gradle-plugin-recipes.html)
+for common problems.
+
+### Adding new extensions in `plugin.xml`
+
+There's a tool called [JetBrains Platform Explorer](https://plugins.jetbrains.com/intellij-platform-explorer) that
+aggregates plugin metadata and allows you to filter by specific
+extension points. If you're having trouble implementing a feature that's not officially documented,
+you can learn from other open source plugins.
+
### Reloading changes
- `extensions/intellij`: Attempt to reload changed classes by selecting
diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts
index 8dc8ce738..8692b35f4 100644
--- a/extensions/intellij/build.gradle.kts
+++ b/extensions/intellij/build.gradle.kts
@@ -1,77 +1,75 @@
import org.jetbrains.changelog.markdownToHTML
-
-fun properties(key: String) = providers.gradleProperty(key)
+import org.jetbrains.intellij.platform.gradle.TestFrameworkType
+import org.jetbrains.intellij.platform.gradle.tasks.PrepareSandboxTask
fun environment(key: String) = providers.environmentVariable(key)
-fun Sync.prepareSandbox() {
- from("../../binary/bin") { into("${intellij.pluginName.get()}/core/") }
-}
-
val remoteRobotVersion = "0.11.23"
+val platformType: String by project
+val platformVersion: String by project
+val pluginGroup: String by project
+val pluginVersion: String by project
+val pluginSinceBuild: String by project
+val pluginRepositoryUrl: String by project
val isEap get() = environment("RELEASE_CHANNEL").orNull == "eap"
-val pluginVersion = properties("pluginVersion").get()
plugins {
- id("java")
- kotlin("jvm") version "1.9.0"
- id("org.jetbrains.intellij") version "1.15.0"
+ kotlin("jvm") version "1.8.0"
+ id("org.jetbrains.intellij.platform") version "2.6.0"
id("org.jetbrains.changelog") version "2.1.2"
id("org.jetbrains.qodana") version "0.1.13"
id("org.jetbrains.kotlinx.kover") version "0.7.3"
- kotlin("plugin.serialization") version "1.8.0"
id("io.sentry.jvm.gradle") version "5.8.0"
}
-group = properties("pluginGroup").get()
+group = pluginGroup
version = if (isEap) "$pluginVersion-eap" else pluginVersion
repositories {
mavenCentral()
- maven { url = uri("https://packages.jetbrains.team/maven/p/ij/intellij-dependencies") }
+ intellijPlatform {
+ defaultRepositories()
+ }
}
dependencies {
- implementation("org.jetbrains.kotlin:kotlin-stdlib:1.4.32")
- implementation("com.posthog.java:posthog:1.+")
- implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0")
+ intellijPlatform {
+ create(platformType, platformVersion)
+ plugins(listOf("org.jetbrains.plugins.terminal:223.8214.6"))
+ testFramework(TestFrameworkType.Platform)
+ }
+ implementation("com.posthog.java:posthog:1.2.0")
+
testImplementation("com.intellij.remoterobot:remote-robot:$remoteRobotVersion")
testImplementation("com.intellij.remoterobot:remote-fixtures:$remoteRobotVersion")
testImplementation("io.mockk:mockk:1.14.2")
- testImplementation("org.junit.jupiter:junit-jupiter-api:5.10.0")
- testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.9.2")
testImplementation("com.squareup.okhttp3:logging-interceptor:4.12.0")
testImplementation("com.automation-remarks:video-recorder-junit5:2.0")
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3")
- testImplementation(kotlin("test"))
+ testRuntimeOnly("org.junit.vintage:junit-vintage-engine:5.10.0") // required to run both JUnit 5 and JUnit 3
}
-// Set the JVM language level used to build the project. Use Java 11 for 2020.3+, and Java 17 for
-// 2022.2+.
kotlin { jvmToolchain(17) }
-// Configure Gradle IntelliJ Plugin - read more:
-// https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html
-intellij {
- pluginName = properties("pluginName")
- version = properties("platformVersion")
- type = properties("platformType")
-
- // Plugin Dependencies. Uses `platformPlugins` property from the gradle.properties file.
- plugins =
- properties("platformPlugins").map {
- it.split(',').map(String::trim).filter(String::isNotEmpty)
+intellijPlatform {
+ pluginConfiguration {
+ ideaVersion {
+ sinceBuild = pluginSinceBuild
}
+ }
+ pluginVerification {
+ ides {
+ ide("IC", "2025.1.4")
+ ide("IC", "2022.3.3")
+ }
+ }
}
-// Configure Gradle Changelog Plugin - read more:
-// https://github.com/JetBrains/gradle-changelog-plugin
changelog {
groups.empty()
- repositoryUrl = properties("pluginRepositoryUrl")
+ repositoryUrl = pluginRepositoryUrl
}
-// Configure Gradle Qodana Plugin - read more: https://github.com/JetBrains/gradle-qodana-plugin
qodana {
cachePath = provider { file(".qodana").canonicalPath }
reportPath = provider { file("build/reports/inspections").canonicalPath }
@@ -79,75 +77,52 @@ qodana {
showReport = environment("QODANA_SHOW_REPORT").map { it.toBoolean() }.getOrElse(false)
}
-// Configure Gradle Kover Plugin - read more: https://github.com/Kotlin/kotlinx-kover#configuration
koverReport { defaults { xml { onCheck = true } } }
+intellijPlatformTesting {
+ runIde {
+ register("runIdeForUiTests") {
+ task {
+ environment(
+ "CONTINUE_GLOBAL_DIR",
+ "${rootProject.projectDir}/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue"
+ )
+ jvmArgumentProviders += CommandLineArgumentProvider {
+ listOf(
+ "-Drobot-server.port=8082",
+ "-Dide.mac.message.dialogs.as.sheets=false",
+ "-Djb.privacy.policy.text=",
+ "-Djb.consents.confirmation.enabled=false",
+ "-Dide.mac.file.chooser.native=false",
+ "-DjbScreenMenuBar.enabled=false",
+ "-Dapple.laf.useScreenMenuBar=false",
+ "-Didea.trust.all.projects=true",
+ "-Dide.show.tips.on.startup.default.value=false",
+ "-Dide.browser.jcef.jsQueryPoolSize=10000",
+ "-Dide.browser.jcef.contextMenu.devTools.enabled=true"
+ )
+ }
+ }
+ plugins {
+ robotServerPlugin()
+ }
+ }
+ }
+}
+
tasks {
- downloadRobotServerPlugin {
- version = remoteRobotVersion
- }
-
- prepareSandbox {
- prepareSandbox()
- }
-
- prepareTestingSandbox {
- prepareSandbox()
- }
-
- prepareUiTestingSandbox {
- prepareSandbox()
- }
-
- wrapper {
- gradleVersion = properties("gradleVersion").get()
+ withType {
+ from("../../binary/bin") {
+ into(pluginName.map { "$it/core" })
+ }
}
patchPluginXml {
- sinceBuild = properties("pluginSinceBuild")
- untilBuild = properties("pluginUntilBuild")
- pluginDescription =
- providers.fileContents(layout.projectDirectory.file("README.md")).asText.map {
- val start = ""
- val end = ""
-
- with(it.lines()) {
- if (!containsAll(listOf(start, end))) {
- throw GradleException(
- "Plugin description section not found in README.md:\n$start ... $end"
- )
- }
- subList(indexOf(start) + 1, indexOf(end)).joinToString("\n").let(::markdownToHTML)
- }
- }
- }
-
- // Configure UI tests plugin
- // Read more: https://github.com/JetBrains/intellij-ui-test-robot
- runIdeForUiTests {
- environment(
- "CONTINUE_GLOBAL_DIR",
- "${rootProject.projectDir}/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue"
- )
- systemProperty("robot-server.port", "8082")
- systemProperty("ide.mac.message.dialogs.as.sheets", "false")
- systemProperty("jb.privacy.policy.text", "")
- systemProperty("jb.consents.confirmation.enabled", "false")
- systemProperty("ide.mac.file.chooser.native", "false")
- systemProperty("jbScreenMenuBar.enabled", "false")
- systemProperty("apple.laf.useScreenMenuBar", "false")
- systemProperty("idea.trust.all.projects", "true")
- systemProperty("ide.show.tips.on.startup.default.value", "false")
- systemProperty("ide.browser.jcef.jsQueryPoolSize", "10000")
- systemProperty("ide.browser.jcef.contextMenu.devTools.enabled", "true")
-
- // This is to ensure we load the GUI with OSR enabled. We have logic that
- // renders with OSR disabled below a particular IDE version.
- // See ContinueExtensionSettingsService.kt for more info.
- // Currently commented out however since test fail in CI with this version
-// intellij {
-// version = "2024.1"
-// }
+ pluginDescription = providers.fileContents(layout.projectDirectory.file("README.md")).asText.get()
+ .substringAfter("")
+ .substringBefore("")
+ .let(::markdownToHTML)
+ check(pluginDescription.get().isNotEmpty()) { "Plugin description section not found in README.md" }
}
signPlugin {
@@ -164,8 +139,10 @@ tasks {
}
runIde {
- val dir = "${rootProject.projectDir.parentFile.parentFile.absolutePath}/manual-testing-sandbox"
- args = listOf(dir, "$dir/test.kt")
+ val openProject = "$projectDir/../../manual-testing-sandbox"
+ argumentProviders += CommandLineArgumentProvider {
+ listOf(openProject, "$openProject/test.kt")
+ }
}
test {
diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties
index a1c5d01c1..69bb623a6 100644
--- a/extensions/intellij/gradle.properties
+++ b/extensions/intellij/gradle.properties
@@ -1,26 +1,9 @@
-# IntelliJ Platform Artifacts Repositories -> https://plugins.jetbrains.com/docs/intellij/intellij-artifacts.html
pluginGroup=com.github.continuedev.continueintellijextension
-pluginName=continue-intellij-extension
pluginRepositoryUrl=https://github.com/continuedev/continue
-# SemVer format -> https://semver.org
-pluginVersion=1.0.30
-# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
+pluginVersion=1.0.33
pluginSinceBuild=223
-# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension
platformType=IC
platformVersion=2022.3.3
-# org.gradle.java.home=/opt/homebrew/opt/openjdk@17
-#platformVersion = LATEST-EAP-SNAPSHOT
-# Plugin Dependencies -> https://plugins.jetbrains.com/docs/intellij/plugin-dependencies.html
-# Example: platformPlugins = com.intellij.java, com.jetbrains.php:203.4449.22
-platformPlugins=org.jetbrains.plugins.terminal
-# Gradle Releases -> https://github.com/gradle/gradle/releases
-gradleVersion=8.3
-# Opt-out flag for bundling Kotlin standard library -> https://jb.gg/intellij-platform-kotlin-stdlib
kotlin.stdlib.default.dependency=false
-# Enable Gradle Configuration Cache -> https://docs.gradle.org/current/userguide/configuration_cache.html
org.gradle.configuration-cache=true
-# Enable Gradle Build Cache -> https://docs.gradle.org/current/userguide/build_cache.html
org.gradle.caching=true
-# Enable Gradle Kotlin DSL Lazy Property Assignment -> https://docs.gradle.org/current/userguide/kotlin_dsl.html#kotdsl:assignment
-systemProp.org.gradle.unsafe.kotlin.assignment=true
diff --git a/extensions/intellij/gradle/wrapper/gradle-wrapper.jar b/extensions/intellij/gradle/wrapper/gradle-wrapper.jar
index 7f93135c4..d64cd4917 100644
Binary files a/extensions/intellij/gradle/wrapper/gradle-wrapper.jar and b/extensions/intellij/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/extensions/intellij/gradle/wrapper/gradle-wrapper.properties b/extensions/intellij/gradle/wrapper/gradle-wrapper.properties
index ab1b658ea..d4081da47 100644
--- a/extensions/intellij/gradle/wrapper/gradle-wrapper.properties
+++ b/extensions/intellij/gradle/wrapper/gradle-wrapper.properties
@@ -1,8 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-bin.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
-#org.gradle.java.home=/opt/homebrew/opt/openjdk@17
\ No newline at end of file
diff --git a/extensions/intellij/gradlew b/extensions/intellij/gradlew
index 0adc8e1a5..1aa94a426 100755
--- a/extensions/intellij/gradlew
+++ b/extensions/intellij/gradlew
@@ -145,7 +145,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
- # shellcheck disable=SC3045
+ # shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
@@ -153,7 +153,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
- # shellcheck disable=SC3045
+ # shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
@@ -202,11 +202,11 @@ fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
-# Collect all arguments for the java command;
-# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
-# shell script including quotes and variable substitutions, so put them in
-# double quotes to make sure that they get re-expanded; and
-# * put everything else in single quotes, so that it's not re-expanded.
+# Collect all arguments for the java command:
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
+# and any embedded shellness will be escaped.
+# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
+# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt
index c6df8eddd..b9eec734c 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt
@@ -10,7 +10,7 @@ import com.intellij.openapi.fileEditor.FileEditorManager
class RestartContinueProcess : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val pluginService = getContinuePluginService(e.project) ?: return
- pluginService.coreMessengerManager?.restart()
+ pluginService.coreMessengerManager?.coreMessenger?.restart()
}
}
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt
index 4538b8771..e52a69711 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt
@@ -112,8 +112,10 @@ class ContinueAuthService {
val jsonBody = gson.toJson(mapOf("refreshToken" to refreshToken))
val url = getControlPlaneUrl() + "/auth/refresh"
val response = HttpRequests.post(url, HttpRequests.JSON_CONTENT_TYPE)
- .connect { connection -> connection.write(jsonBody.toByteArray()) }
- .toString()
+ .connect {
+ connection -> connection.write(jsonBody.toByteArray())
+ connection.readString()
+ }
return gson.fromJson(response, RefreshTokenResponse::class.java)
}
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt
index 28b648d4a..856215be2 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt
@@ -29,6 +29,9 @@ class ApplyToFileHandler(
private val diffStreamService: DiffStreamService
) {
+ // Store the original file content before applying changes
+ private val originalFileContent: String? = editorUtils?.getDocumentText()
+
suspend fun handleApplyToFile() {
// Notify webview that we're starting to stream
notifyStreamStarted()
@@ -111,6 +114,7 @@ class ApplyToFileHandler(
numDiffs = numDiffs,
filepath = params.filepath,
fileContent = params.text,
+ originalFileContent = originalFileContent,
toolCallId = params.toolCallId.toString()
)
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 1c0ab242a..1e8e78208 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
@@ -17,11 +17,11 @@ class CoreMessenger(
private val project: Project,
private val ideProtocolClient: IdeProtocolClient,
val coroutineScope: CoroutineScope,
- private val onExit: () -> Unit
+ private val onUnexpectedExit: () -> Unit
) {
private val gson = Gson()
private val responseListeners = mutableMapOf Unit>()
- private val process = startContinueProcess()
+ private var process = startContinueProcess()
private val log = Logger.getInstance(CoreMessenger::class.java)
fun request(messageType: String, data: Any?, messageId: String?, onResponse: (Any?) -> Unit) {
@@ -36,7 +36,7 @@ class CoreMessenger(
val process = if (isTcp)
ContinueSocketProcess()
else
- ContinueBinaryProcess(onExit)
+ ContinueBinaryProcess(onUnexpectedExit)
return ContinueProcessHandler(coroutineScope, process, ::handleMessage)
}
@@ -81,7 +81,15 @@ class CoreMessenger(
null
}
- fun killSubProcess() {
+ fun restart() {
+ log.warn("Restarting Continue process")
+ responseListeners.clear()
+ process.close()
+ process = startContinueProcess()
+ }
+
+ fun close() {
+ log.warn("Closing Continue process")
process.close()
}
}
\ No newline at end of file
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt
index 3dbf9c2d5..71b367e20 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt
@@ -9,37 +9,34 @@ import com.intellij.openapi.project.Project
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
+import kotlin.time.Duration.Companion.seconds
class CoreMessengerManager(
- private val project: Project,
- private val ideProtocolClient: IdeProtocolClient,
+ project: Project,
+ ideProtocolClient: IdeProtocolClient,
private val coroutineScope: CoroutineScope
) {
- var coreMessenger: CoreMessenger = createCoreMessenger()
- private var lastBackoffInterval = 0.5
+ val coreMessenger = CoreMessenger(project, ideProtocolClient, coroutineScope, ::onUnexpectedExit)
+ private var backoffIntervalSeconds = 1
private val log = Logger.getInstance(CoreMessengerManager::class.java)
init {
setupAnonymousTelemetry()
}
- fun restart() {
+ private fun onUnexpectedExit() {
coroutineScope.launch {
try {
- coreMessenger.killSubProcess()
- lastBackoffInterval *= 2
- log.warn("Continue process exited, retrying in $lastBackoffInterval seconds")
- delay((lastBackoffInterval * 1000).toLong())
- coreMessenger = createCoreMessenger()
+ delay(backoffIntervalSeconds.seconds)
+ backoffIntervalSeconds *= 2
+ log.warn("Continue process terminated externally, retrying in $backoffIntervalSeconds seconds")
+ coreMessenger.restart()
} catch (e: Exception) {
service().capture("jetbrains_core_start_error", mapOf("error" to e))
}
}
}
- private fun createCoreMessenger() =
- CoreMessenger(project, ideProtocolClient, coroutineScope, ::restart)
-
private fun setupAnonymousTelemetry() {
coreMessenger.request("config/getSerializedProfileInfo", null, null) { response ->
val allowAnonymousTelemetry =
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt
index 2f1889fb4..8bdb7f964 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt
@@ -3,6 +3,7 @@ package com.github.continuedev.continueintellijextension.`continue`
import com.github.continuedev.continueintellijextension.*
import com.github.continuedev.continueintellijextension.constants.ContinueConstants
import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath
+import com.github.continuedev.continueintellijextension.`continue`.file.FileUtils
import com.github.continuedev.continueintellijextension.error.ContinueErrorService
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
@@ -38,9 +39,7 @@ import java.awt.Toolkit
import java.awt.datatransfer.DataFlavor
import java.io.BufferedReader
import java.io.File
-import java.io.FileInputStream
import java.io.InputStreamReader
-import java.nio.charset.Charset
class IntelliJIDE(
private val project: Project,
@@ -49,7 +48,7 @@ class IntelliJIDE(
) : IDE {
private val gitService = GitService(project, continuePluginService)
-
+ private val fileUtils = FileUtils()
private val ripgrep: String = getRipgrepPath()
init {
@@ -204,16 +203,11 @@ class IntelliJIDE(
return configs as List
}
- override suspend fun fileExists(filepath: String): Boolean {
- val file = UriUtils.uriToFile(filepath)
- return file.exists()
- }
+ override suspend fun fileExists(filepath: String): Boolean =
+ fileUtils.fileExists(filepath)
- override suspend fun writeFile(path: String, contents: String) {
- val file = UriUtils.uriToFile(path)
- file.parentFile?.mkdirs()
- file.writeText(contents)
- }
+ override suspend fun writeFile(path: String, contents: String) =
+ fileUtils.writeFile(path, contents)
override suspend fun showVirtualFile(title: String, contents: String) {
val virtualFile = LightVirtualFile(title, contents)
@@ -321,38 +315,8 @@ class IntelliJIDE(
}
}
- override suspend fun readFile(filepath: String): String {
- return try {
- val content = ApplicationManager.getApplication().runReadAction {
- val virtualFile = LocalFileSystem.getInstance().findFileByPath(UriUtils.parseUri(filepath).path)
- if (virtualFile != null && FileDocumentManager.getInstance().isFileModified(virtualFile)) {
- return@runReadAction FileDocumentManager.getInstance().getDocument(virtualFile)?.text
- }
- return@runReadAction null
- }
-
- if (content != null) {
- content
- } else {
- val file = UriUtils.uriToFile(filepath)
- if (!file.exists() || file.isDirectory) return ""
- withContext(Dispatchers.IO) {
- FileInputStream(file).use { fis ->
- val sizeToRead = minOf(100000, file.length()).toInt()
- val buffer = ByteArray(sizeToRead)
- val bytesRead = fis.read(buffer, 0, sizeToRead)
- if (bytesRead <= 0) return@use ""
- String(buffer, 0, bytesRead, Charset.forName("UTF-8"))
- // `\r` takes up unnecessary tokens
- .lineSequence().joinToString("\n")
- }
- }
- }
- } catch (e: Exception) {
- e.printStackTrace()
- ""
- }
- }
+ override suspend fun readFile(filepath: String): String =
+ fileUtils.readFile(filepath)
override suspend fun readRangeInFile(filepath: String, range: Range): String {
val fullContents = readFile(filepath)
@@ -661,13 +625,8 @@ class IntelliJIDE(
}
}
- override suspend fun listDir(dir: String): List> {
- val files = UriUtils.uriToFile(dir).listFiles()?.map {
- listOf(it.name, if (it.isDirectory) FileType.DIRECTORY.value else FileType.FILE.value)
- } ?: emptyList()
-
- return files
- }
+ override suspend fun listDir(dir: String): List> =
+ fileUtils.listDir(dir)
override suspend fun getFileStats(files: List): Map {
return files.associateWith { file ->
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/file/FileUtils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/file/FileUtils.kt
new file mode 100644
index 000000000..bfd60dfe2
--- /dev/null
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/file/FileUtils.kt
@@ -0,0 +1,69 @@
+package com.github.continuedev.continueintellijextension.`continue`.file
+
+import com.github.continuedev.continueintellijextension.FileType
+import com.github.continuedev.continueintellijextension.`continue`.UriUtils
+import com.intellij.openapi.application.ApplicationManager
+import com.intellij.openapi.fileEditor.FileDocumentManager
+import com.intellij.openapi.vfs.LocalFileSystem
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import java.io.FileInputStream
+import java.nio.charset.Charset
+
+class FileUtils {
+ // todo: use VFS (it's moved from IntellijIde)
+
+ fun fileExists(uri: String): Boolean {
+ val file = UriUtils.uriToFile(uri)
+ return file.exists()
+ }
+
+ fun writeFile(uri: String, contents: String) {
+ val file = UriUtils.uriToFile(uri)
+ file.parentFile?.mkdirs()
+ file.writeText(contents)
+ }
+
+ fun listDir(dir: String): List> {
+ val files = UriUtils.uriToFile(dir).listFiles()?.map {
+ listOf(it.name, if (it.isDirectory) FileType.DIRECTORY.value else FileType.FILE.value)
+ } ?: emptyList()
+
+ return files
+ }
+
+ fun readFile(uri: String): String {
+ return try {
+ val content = ApplicationManager.getApplication().runReadAction {
+ val virtualFile = LocalFileSystem.getInstance().findFileByPath(UriUtils.parseUri(uri).path)
+ if (virtualFile != null && FileDocumentManager.getInstance().isFileModified(virtualFile)) {
+ return@runReadAction FileDocumentManager.getInstance().getDocument(virtualFile)?.text
+ }
+ return@runReadAction null
+ }
+
+ if (content != null) {
+ content
+ } else {
+ val file = UriUtils.uriToFile(uri)
+ if (!file.exists() || file.isDirectory) return ""
+ FileInputStream(file).use { fis ->
+ val sizeToRead = minOf(100000, file.length()).toInt()
+ val buffer = ByteArray(sizeToRead)
+ val bytesRead = fis.read(buffer, 0, sizeToRead)
+ if (bytesRead <= 0) return@use ""
+ val content = String(buffer, 0, bytesRead, Charset.forName("UTF-8"))
+ // Remove `\r` characters but preserve trailing newlines to prevent line count discrepancies
+ val contentWithoutCR = content.replace("\r\n", "\n").replace("\r", "\n")
+ contentWithoutCR
+ }
+ }
+ } catch (e: Exception) {
+ e.printStackTrace()
+ ""
+ }
+
+ }
+
+
+}
\ No newline at end of file
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueBinaryProcess.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueBinaryProcess.kt
index eb45cc4da..6ef0c335b 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueBinaryProcess.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueBinaryProcess.kt
@@ -1,5 +1,7 @@
package com.github.continuedev.continueintellijextension.`continue`.process
+import com.github.continuedev.continueintellijextension.proxy.ProxySettings
+import com.github.continuedev.continueintellijextension.error.ContinueErrorService
import com.github.continuedev.continueintellijextension.services.TelemetryService
import com.github.continuedev.continueintellijextension.utils.OS
import com.github.continuedev.continueintellijextension.utils.getContinueBinaryPath
@@ -14,7 +16,9 @@ import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.attribute.PosixFilePermission
-class ContinueBinaryProcess(private val onExit: () -> Unit) : ContinueProcess {
+class ContinueBinaryProcess(
+ private val onUnexpectedExit: () -> Unit
+) : ContinueProcess {
private val process = startBinaryProcess()
override val input: InputStream = process.inputStream
@@ -28,11 +32,16 @@ class ContinueBinaryProcess(private val onExit: () -> Unit) : ContinueProcess {
runBlocking(Dispatchers.IO) {
setPermissions()
}
- return ProcessBuilder(path).directory(File(path).parentFile)
- .start()
- .apply { onExit().thenRun(onExit).thenRun { reportErrorTelemetry() } }
- }
+ val builder = ProcessBuilder(path)
+ val proxySettings = ProxySettings.getSettings()
+ if (proxySettings.enabled)
+ builder.environment() += "HTTP_PROXY" to proxySettings.proxy
+ return builder
+ .directory(File(path).parentFile)
+ .start()
+ .apply { onExit().thenRun(onUnexpectedExit).thenRun(::reportErrorTelemetry) }
+ }
private fun reportErrorTelemetry() {
var err = process.errorStream?.bufferedReader()?.readText()?.trim()
@@ -44,11 +53,8 @@ class ContinueBinaryProcess(private val onExit: () -> Unit) : ContinueProcess {
err = err.substring(doneIndex + delimiter.length)
}
}
-
- println("Core process exited with output: $err")
-
- val telemetryService = service()
- telemetryService.capture("jetbrains_core_exit", mapOf("error" to err))
+ service().reportMessage("Core process exited with output: $err")
+ service().capture("jetbrains_core_exit", mapOf("error" to err))
}
private companion object {
@@ -67,6 +73,7 @@ class ContinueBinaryProcess(private val onExit: () -> Unit) : ContinueProcess {
elevatePermissions()
}
+ // todo: consider setting permissions ahead-of-time during build/packaging, not at runtime
private fun elevatePermissions() {
val path = getContinueBinaryPath()
val permissions = setOf(
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcessHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcessHandler.kt
index 68ec83bf6..8e918b2c3 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcessHandler.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcessHandler.kt
@@ -2,6 +2,7 @@ package com.github.continuedev.continueintellijextension.`continue`.process
import com.github.continuedev.continueintellijextension.error.ContinueErrorService
import com.intellij.openapi.components.service
+import com.intellij.openapi.diagnostic.Logger
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import java.io.BufferedReader
@@ -19,6 +20,7 @@ class ContinueProcessHandler(
private val pendingWrites = Channel(Channel.UNLIMITED)
private val writer = OutputStreamWriter(process.output)
private val reader = BufferedReader(InputStreamReader(process.input))
+ private val log = Logger.getInstance(ContinueProcessHandler::class.java)
init {
scope.launch(Dispatchers.IO) {
@@ -27,6 +29,7 @@ class ContinueProcessHandler(
val line = reader.readLine()
if (line != null && line.isNotEmpty()) {
try {
+ log.debug("Handle: $line")
handleMessage(line)
} catch (e: Exception) {
service().report(e, "Error handling message: $line")
@@ -40,6 +43,7 @@ class ContinueProcessHandler(
}
scope.launch(Dispatchers.IO) {
for (message in pendingWrites) {
+ log.debug("Write: $message")
writer.write(message)
writer.write("\r\n")
writer.flush()
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt
index 21f920ef9..35e23d8a2 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorService.kt
@@ -6,6 +6,7 @@ import com.intellij.openapi.components.Service
import com.intellij.openapi.diagnostic.Attachment
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.PluginId
+import com.intellij.openapi.util.SystemInfo
import com.intellij.ui.jcef.JBCefApp
import io.sentry.Hint
import io.sentry.Sentry
@@ -26,6 +27,8 @@ class ContinueErrorService {
config.setTag("ide_version", ApplicationInfo.getInstance().build.asString())
config.setTag("jcef_supported", JBCefApp.isSupported().toString())
config.setTag("plugin_version", PluginManagerCore.getPlugin(PluginId.getId(PLUGIN_ID))?.version)
+ config.setTag("system", SystemInfo.OS_NAME)
+ config.setTag("system_version", SystemInfo.OS_VERSION)
}
}
@@ -39,7 +42,14 @@ class ContinueErrorService {
sentryEvent.message = Message().apply { this.message = message }
val hint = Hint.withAttachments(attachments?.map { SentryAttachment(it.bytes, it.path) })
Sentry.captureEvent(sentryEvent, hint)
- log.warn("Problem sent to Sentry: $message", throwable)
+ log.warn("Exception sent to Sentry: $message", throwable)
+ }
+
+ fun reportMessage(
+ message: String,
+ ) {
+ Sentry.captureMessage(message)
+ log.warn("Message sent to Sentry: $message")
}
private companion object {
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/proxy/ProxyPoolingActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/proxy/ProxyPoolingActivity.kt
new file mode 100644
index 000000000..0d88d0bdd
--- /dev/null
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/proxy/ProxyPoolingActivity.kt
@@ -0,0 +1,36 @@
+package com.github.continuedev.continueintellijextension.proxy
+
+import com.github.continuedev.continueintellijextension.services.ContinuePluginService
+import com.intellij.openapi.components.service
+import com.intellij.openapi.diagnostic.Logger
+import com.intellij.openapi.project.Project
+import com.intellij.openapi.startup.StartupActivity
+import kotlinx.coroutines.*
+import kotlin.time.Duration.Companion.seconds
+
+class ProxyPoolingActivity : StartupActivity {
+ private val scope = CoroutineScope(Dispatchers.Default)
+ private var lastSettings = ProxySettings.getSettings()
+ private val log = Logger.getInstance(ProxyPoolingActivity::class.java)
+
+ override fun runActivity(project: Project) {
+ scope.launch {
+ while (isActive) {
+ val newSettings = ProxySettings.getSettings()
+ if (newSettings != lastSettings) {
+ onSettingsChanged(project)
+ lastSettings = newSettings
+ }
+ delay(2.seconds)
+ }
+ }
+ }
+
+ private fun onSettingsChanged(project: Project) {
+ log.warn("Proxy settings changed, restarting")
+ project.service().coreMessengerManager?.coreMessenger?.restart()
+ }
+}
+
+
+
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/proxy/ProxySettings.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/proxy/ProxySettings.kt
new file mode 100644
index 000000000..70c66637c
--- /dev/null
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/proxy/ProxySettings.kt
@@ -0,0 +1,20 @@
+package com.github.continuedev.continueintellijextension.proxy
+
+import com.intellij.util.net.HttpConfigurable
+
+data class ProxySettings(
+ val enabled: Boolean,
+ val proxy: String,
+) {
+
+ companion object {
+ fun getSettings(): ProxySettings {
+ val settings = HttpConfigurable.getInstance()
+ return ProxySettings(
+ enabled = settings.USE_HTTP_PROXY,
+ proxy = "${settings.PROXY_HOST}:${settings.PROXY_PORT}"
+ )
+ }
+ }
+
+}
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt
index 6ebb8f41f..102981715 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt
@@ -33,7 +33,7 @@ class ContinuePluginService : Disposable, DumbAware {
coroutineScope.cancel()
coreMessenger?.coroutineScope?.let {
it.cancel()
- coreMessenger?.killSubProcess()
+ coreMessenger?.close()
}
}
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt
index 4afa1cb45..256dba81e 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt
@@ -2,62 +2,69 @@ package com.github.continuedev.continueintellijextension.toolWindow
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.intellij.openapi.actionSystem.ActionManager
-import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.components.service
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowFactory
import com.intellij.ui.content.ContentFactory
+import com.intellij.ui.dsl.builder.AlignX
+import com.intellij.ui.dsl.builder.panel
+import com.intellij.ui.jcef.JBCefApp
+import com.intellij.util.ui.JBUI.Borders.empty
import javax.swing.JComponent
+import javax.swing.JPanel
const val JS_QUERY_POOL_SIZE = "200"
class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
- override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
- val continueToolWindow = ContinuePluginWindow(project)
- val content =
- ContentFactory.getInstance().createContent(continueToolWindow.content, null, false)
- toolWindow.contentManager.addContent(content)
- val titleActions = mutableListOf()
- createTitleActions(titleActions)
-
- // Add MaximizeToolWindow action
- val action = ActionManager.getInstance().getAction("MaximizeToolWindow")
- if (action != null) {
- titleActions.add(action)
+ override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
+ val inner = if (JBCefApp.isSupported())
+ ContinuePluginWindow(project).content
+ else
+ createNotSupportedPanel()
+ val content = ContentFactory.getInstance().createContent(inner, null, false)
+ toolWindow.contentManager.addContent(content)
+ toolWindow.setTitleActions(
+ listOf(
+ ActionManager.getInstance().getAction("ContinueSidebarActionsGroup"),
+ ActionManager.getInstance().getAction("MaximizeToolWindow")
+ )
+ )
}
- toolWindow.setTitleActions(titleActions)
- }
+ override fun shouldBeAvailable(project: Project) = true
- private fun createTitleActions(titleActions: MutableList) {
- val action = ActionManager.getInstance().getAction("ContinueSidebarActionsGroup")
- if (action != null) {
- titleActions.add(action)
- }
- }
-
- override fun shouldBeAvailable(project: Project) = true
-
- class ContinuePluginWindow(project: Project) {
- private val defaultGUIUrl = "http://continue/index.html"
-
- init {
- System.setProperty("ide.browser.jcef.jsQueryPoolSize", JS_QUERY_POOL_SIZE)
- System.setProperty("ide.browser.jcef.contextMenu.devTools.enabled", "true")
- System.setProperty("ide.browser.jcef.out-of-process.enabled", "false")
+ private fun createNotSupportedPanel(): JPanel {
+ val html = ContinuePluginToolWindowFactory::class.java.classLoader
+ .getResourceAsStream("jcef_error.html")
+ .bufferedReader()
+ .readText()
+ return panel {
+ row {
+ text(html)
+ }
+ }.withBorder(empty(10))
}
- val browser: ContinueBrowser by lazy {
- val url = System.getenv("GUI_URL")?.toString() ?: defaultGUIUrl
+ class ContinuePluginWindow(project: Project) {
+ private val defaultGUIUrl = "http://continue/index.html"
- val browser = ContinueBrowser(project, url)
- project.service().continuePluginWindow = this
- browser
+ init {
+ System.setProperty("ide.browser.jcef.jsQueryPoolSize", JS_QUERY_POOL_SIZE)
+ System.setProperty("ide.browser.jcef.contextMenu.devTools.enabled", "true")
+ System.setProperty("ide.browser.jcef.out-of-process.enabled", "false")
+ }
+
+ val browser: ContinueBrowser by lazy {
+ val url = System.getenv("GUI_URL") ?: defaultGUIUrl
+
+ val browser = ContinueBrowser(project, url)
+ project.service().continuePluginWindow = this
+ browser
+ }
+
+ val content: JComponent
+ get() = browser.browser.component
}
-
- val content: JComponent
- get() = browser.browser.component
- }
}
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt
index 133c80e63..32c7802ad 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt
@@ -290,6 +290,7 @@ data class ApplyState(
val numDiffs: Int? = null,
val filepath: String? = null,
val fileContent: String? = null,
+ val originalFileContent: String? = null,
val toolCallId: String? = null
)
diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml
index 15a0dd864..0191d8f60 100644
--- a/extensions/intellij/src/main/resources/META-INF/plugin.xml
+++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml
@@ -14,9 +14,6 @@
com.intellij.modules.json
-
-
-
@@ -40,6 +37,7 @@
+
+
+
+
Continue Chat is Unable to Load
+
+
Continue Chat requires a JRE that supports the Java Chromium Embedded Framework (JCEF) to render our webview. You can
+ still use Autocomplete and Edit.
+
How to Fix It?
+
You can manually switch to a JRE that supports JCEF:
+
+
In the main menu, go to Help | Find Action or press
+ Ctrl + Shift + A.
+
+
Find and select the Choose Boot Java Runtime for the IDE action.
+
Select the runtime that comes with JCEF support and click OK.
+
Restart with the new runtime.
+
+
Runtimes that support JCEF are usually called JetBrains Runtime and have the -jcef suffix,
+ for example 21.0.3+13-509.11-jcef.
+
+You can find more information in the JetBrains documentation.
+
\ No newline at end of file
diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ApplyToFileHandlerTest.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ApplyToFileHandlerTest.kt
index 4e12e270e..0a018a18f 100644
--- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ApplyToFileHandlerTest.kt
+++ b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ApplyToFileHandlerTest.kt
@@ -12,13 +12,12 @@ import com.github.continuedev.continueintellijextension.services.ContinuePluginS
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import io.mockk.*
+import junit.framework.TestCase
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
-import org.junit.jupiter.api.BeforeEach
-import org.junit.jupiter.api.Test
@ExperimentalCoroutinesApi
-class ApplyToFileHandlerTest {
+class ApplyToFileHandlerTest : TestCase() {
// Mock all dependencies
private val mockProject = mockk(relaxed = true)
private val mockContinuePluginService = mockk(relaxed = true)
@@ -39,8 +38,7 @@ class ApplyToFileHandlerTest {
"tool-call-123"
)
- @BeforeEach
- fun setUp() {
+ override fun setUp() {
// Common setup
every { mockEditorUtils.editor } returns mockEditor
every { mockContinuePluginService.coreMessenger } returns mockCoreMessenger
@@ -56,8 +54,7 @@ class ApplyToFileHandlerTest {
)
}
- @Test
- fun `should insert text directly when document is empty`() = runTest {
+ fun `test should insert text directly when document is empty`() = runTest {
// Given
every { mockEditorUtils.isDocumentEmpty() } returns true
diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/CheckFimTest.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/CheckFimTest.kt
index b23bcf7ec..da819ad67 100644
--- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/CheckFimTest.kt
+++ b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/CheckFimTest.kt
@@ -1,48 +1,39 @@
package com.github.continuedev.continueintellijextension.unit
import com.github.continuedev.continueintellijextension.FimResult
-import com.github.continuedev.continueintellijextension.`continue`.UriUtils
import com.github.continuedev.continueintellijextension.utils.checkFim
-import org.junit.jupiter.api.Disabled
-import org.junit.jupiter.api.Test
-import java.io.File
-import kotlin.test.assertEquals
+import junit.framework.TestCase
-class CheckFimTest {
- @Test
- fun testFim() {
+class CheckFimTest : TestCase() {
+ fun `test FIM`() {
val oldEditRange = "hello world"
val newEditRange = "hello this world"
val cursorPosition = Pair(0, 6)
assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.FimEdit("this "))
}
- @Test
- fun testMultilineFim() {
+ fun `test multiline FIM`() {
val oldEditRange = "hello {\n world\n}"
val newEditRange = "hello {\n print()\n world\n}"
val cursorPosition = Pair(1, 2)
assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.FimEdit("print()\n "))
}
- @Test
- fun testNotFim() {
+ fun `test not FIM`() {
val oldEditRange = "hello world"
val newEditRange = "hello this world"
val cursorPosition = Pair(0, 8)
assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.NotFimEdit)
}
- @Test
- fun testMultilineNotFim() {
+ fun `test multiline not FIM`() {
val oldEditRange = "hello {\n world\n}"
val newEditRange = "hello {\n world\n}\nprint()"
val cursorPosition = Pair(1, 2)
assertEquals(checkFim(oldEditRange, newEditRange, cursorPosition), FimResult.NotFimEdit)
}
- @Test
- fun testFimEdge() {
+ fun `test FIM edge`() {
val oldEditRange = ""
val newEditRange = ""
val cursorPosition = Pair(0, 0)
diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/FileUtilsTest.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/FileUtilsTest.kt
new file mode 100644
index 000000000..3ec25afba
--- /dev/null
+++ b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/FileUtilsTest.kt
@@ -0,0 +1,77 @@
+package com.github.continuedev.continueintellijextension.unit
+
+import com.github.continuedev.continueintellijextension.FileType
+import com.github.continuedev.continueintellijextension.`continue`.file.FileUtils
+import com.intellij.testFramework.UsefulTestCase
+import com.intellij.testFramework.fixtures.CodeInsightTestFixture
+import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory
+
+class FileUtilsTest : UsefulTestCase() {
+ val fileUtils = FileUtils()
+ val myFixture = setupRealFilesFixture()
+ val tmpFixture get() = myFixture.tempDirFixture
+ val tmpDir get() = myFixture.tempDirPath
+
+ override fun setUp() =
+ myFixture.setUp()
+
+ override fun tearDown() =
+ myFixture.tearDown()
+
+ fun `test fileExists`() {
+ val file = tmpFixture.createFile("test.txt", "")
+ val uri = "file://${file.path}"
+ assertTrue(fileUtils.fileExists(uri))
+ }
+
+ fun `test fileExists inside directory`() {
+ val file = tmpFixture.createFile("dir/dir2/file.txt", "")
+ val uri = "file://${file.path}"
+ assertTrue(fileUtils.fileExists(uri))
+ }
+
+ fun `test fileExists fails when file doesn't exists`() {
+ val uri = "file:///tmp/aaaa.txt"
+ assertFalse(fileUtils.fileExists(uri))
+ }
+
+ fun `test readFile`() {
+ val uri = "file://$tmpDir/bbbb.txt"
+ tmpFixture.createFile("bbbb.txt", "contents")
+ val text = fileUtils.readFile(uri)
+ assertEquals("contents", text)
+ }
+
+ fun `test listDir`() {
+ tmpFixture.createFile("a.txt", "a")
+ tmpFixture.createFile("b.txt", "b")
+ tmpFixture.createFile("c.txt", "c")
+ tmpFixture.createFile("dir/invisibleA.txt", "d")
+ tmpFixture.createFile("dir/invisibleB.txt", "e")
+
+ val result = fileUtils.listDir("file://$tmpDir")
+
+ assertTrue(result.any { it[0] == "a.txt" && it[1] == FileType.FILE.value })
+ assertTrue(result.any { it[0] == "b.txt" && it[1] == FileType.FILE.value })
+ assertTrue(result.any { it[0] == "c.txt" && it[1] == FileType.FILE.value })
+ assertTrue(result.any { it[0] == "dir" && it[1] == FileType.DIRECTORY.value })
+ assertTrue(result.any { it[0] == "dir" && it[1] == FileType.DIRECTORY.value })
+ assertFalse(result.any { it[0] == "invisibleA.txt" })
+ assertFalse(result.any { it[0] == "invisibleB.txt" })
+ assertEquals(4, result.size)
+ }
+
+ private companion object {
+
+ // note: with this, files will actually exist inside /tmp/unitTest/ dir, otherwise it's virtual
+ fun setupRealFilesFixture(): CodeInsightTestFixture {
+ val factory = IdeaTestFixtureFactory.getFixtureFactory()
+ return factory.createCodeInsightFixture(
+ factory.createLightFixtureBuilder("my_continue_project").fixture,
+ factory.createTempDirTestFixture()
+ )
+ }
+
+ }
+
+}
\ No newline at end of file
diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/UriUtilsTest.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/UriUtilsTest.kt
index 9b4690d79..170446f61 100644
--- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/UriUtilsTest.kt
+++ b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/UriUtilsTest.kt
@@ -1,64 +1,48 @@
package com.github.continuedev.continueintellijextension.unit
import com.github.continuedev.continueintellijextension.`continue`.UriUtils
-import org.junit.jupiter.api.Disabled
-import org.junit.jupiter.api.Test
+import junit.framework.TestCase
import java.io.File
-import kotlin.test.assertEquals
-class UriUtilsTest {
- @Test
- fun testUriToFile() {
+class UriUtilsTest : TestCase() {
+ fun `test URI to File`() {
val uri = "file:///path/to/file"
val file = UriUtils.uriToFile(uri)
assertEquals(File("/path/to/file"), file)
}
- @Disabled("Not working")
- @Test
- fun testUriToFileWithWindowsPath() {
- val uri = "file:///C:/path/to/file"
- val file = UriUtils.uriToFile(uri)
- assertEquals(File("C:/path/to/file"), file)
- }
+ // fixme it's not working
+ // fun `test Windows path`() {
+ // val uri = "file:///C:/path/to/file"
+ // val file = UriUtils.uriToFile(uri)
+ // assertEquals(File("C:/path/to/file"), file)
+ // }
- @Test
- fun shouldHandleAuthorityComponent() {
- val uri = "file://C:/path/to/file"
- val file = UriUtils.uriToFile(uri)
- assertEquals(File("/C:/path/to/file"), file)
- }
-
- @Test
- fun testUriToFileWithSpaces() {
+ fun `test spaces`() {
val uri = "file:///path/to/file%20with%20spaces"
val file = UriUtils.uriToFile(uri)
assertEquals(File("/path/to/file with spaces"), file)
}
- @Test
- fun testUriToFileWithSpecialCharacters() {
+ fun `test special characters`() {
val uri = "file:///path/to/file%23with%25special%26chars"
val file = UriUtils.uriToFile(uri)
assertEquals(File("/path/to/file#with%special&chars"), file)
}
- @Test
- fun testUriToFileWithQueryParams() {
+ fun `test query params`() {
val uri = "file:///path/to/file?param=value"
val file = UriUtils.uriToFile(uri)
assertEquals(File("/path/to/file"), file)
}
- @Test
- fun testUriToFileWithWSLPath() {
+ fun `test WSL path`() {
val uri = "file:///wsl$/Ubuntu/home/user/file.txt"
val file = UriUtils.uriToFile(uri)
assertEquals(File("/wsl$/Ubuntu/home/user/file.txt"), file)
}
- @Test
- fun testUriToFileWithWSLLocalhostPath() {
+ fun `test WSL localhost path`() {
val uri = "file:///wsl.localhost/Ubuntu/home/user/file.txt"
val file = UriUtils.uriToFile(uri)
assertEquals(File("/wsl.localhost/Ubuntu/home/user/file.txt"), file)
diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json
index a6a86e3b4..0f419444a 100644
--- a/extensions/vscode/package-lock.json
+++ b/extensions/vscode/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "continue",
- "version": "1.1.66",
+ "version": "1.1.68",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
- "version": "1.1.66",
+ "version": "1.1.68",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",
diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json
index a813e7b95..a3ca3a6b7 100644
--- a/extensions/vscode/package.json
+++ b/extensions/vscode/package.json
@@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
- "version": "1.1.66",
+ "version": "1.1.69",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
diff --git a/extensions/vscode/scripts/download-copy-sqlite-esbuild.js b/extensions/vscode/scripts/download-copy-sqlite-esbuild.js
index ea6f8ebd9..b595c3bdf 100644
--- a/extensions/vscode/scripts/download-copy-sqlite-esbuild.js
+++ b/extensions/vscode/scripts/download-copy-sqlite-esbuild.js
@@ -1,83 +1,40 @@
const { fork } = require("child_process");
const fs = require("fs");
-const https = require("https");
const path = require("path");
+const { ProxyAgent } = require("undici");
const { rimrafSync } = require("rimraf");
const { execCmdSync } = require("../../../scripts/util");
/**
- * download a file using nodejs http
+ * download a file using fetch API
* @param {string} url
* @param {string} outputPath
- * @param {number} maxRedirects
*/
-async function downloadFile(url, outputPath, maxRedirects = 5) {
- return new Promise((resolve, reject) => {
- const downloadWithRedirects = (currentUrl, redirectCount = 0) => {
- if (redirectCount > maxRedirects) {
- return reject(new Error(`Too many redirects (${maxRedirects})`));
- }
+async function downloadFile(url, outputPath) {
+ // Use proxy if set in environment variables
+ const proxy = process.env.https_proxy || process.env.HTTPS_PROXY;
+ const agent = proxy ? new ProxyAgent(proxy) : undefined;
- const request = https.get(currentUrl, (response) => {
- if (
- response.statusCode >= 300 &&
- response.statusCode < 400 &&
- response.headers.location
- ) {
- return downloadWithRedirects(
- response.headers.location,
- redirectCount + 1,
- );
- }
-
- if (response.statusCode !== 200) {
- return reject(
- new Error(`HTTP ${response.statusCode}: ${response.statusMessage}`),
- );
- }
-
- const outputDir = path.dirname(outputPath);
- if (!fs.existsSync(outputDir)) {
- fs.mkdirSync(outputDir, { recursive: true });
- }
-
- const writeStream = fs.createWriteStream(outputPath);
-
- const totalSize = parseInt(response.headers["content-length"], 10);
- let downloadedSize = 0;
-
- response.on("data", (chunk) => {
- downloadedSize += chunk.length;
- if (totalSize) {
- const percent = ((downloadedSize / totalSize) * 100).toFixed(1);
- process.stdout.write(
- `\rDownloading: ${percent}% (${downloadedSize}/${totalSize} bytes)`,
- );
- }
- });
-
- response.pipe(writeStream);
-
- writeStream.on("finish", () => {
- console.log(`\nDownload completed: ${outputPath}`);
- resolve(outputPath);
- });
-
- writeStream.on("error", reject);
- response.on("error", reject);
- });
-
- request.on("error", reject);
- request.setTimeout(30000, () => {
- request.destroy();
- reject(new Error("Request timeout"));
- });
- };
-
- downloadWithRedirects(url);
+ const response = await fetch(url, {
+ redirect: "follow", // Automatically follow redirects
+ dispatcher: agent,
});
+
+ if (!response.ok) {
+ throw new Error(`Failed to download file, status code: ${response.status}`);
+ }
+
+ // Create output directory if it doesn't exist
+ const outputDir = path.dirname(outputPath);
+ if (!fs.existsSync(outputDir)) {
+ fs.mkdirSync(outputDir, { recursive: true });
+ }
+
+ // Get the response as an array buffer and write it to the file
+ const buffer = await response.arrayBuffer();
+ fs.writeFileSync(outputPath, Buffer.from(buffer));
}
/**
diff --git a/extensions/vscode/src/activation/NextEditWindowManager.ts b/extensions/vscode/src/activation/NextEditWindowManager.ts
index 58d03239d..89c3c1d57 100644
--- a/extensions/vscode/src/activation/NextEditWindowManager.ts
+++ b/extensions/vscode/src/activation/NextEditWindowManager.ts
@@ -6,10 +6,6 @@ import * as vscode from "vscode";
import { DiffChar, DiffLine } from "core";
import { CodeRenderer } from "core/codeRenderer/CodeRenderer";
import { myersCharDiff } from "core/diff/myers";
-import {
- NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
- NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
-} from "core/nextEdit/constants";
import { getOffsetPositionAtLastNewLine } from "core/nextEdit/diff/diff";
import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService";
import { getThemeString } from "../util/getTheme";
@@ -117,6 +113,9 @@ export class NextEditWindowManager {
// Track for logging purposes.
private loggingService: NextEditLoggingService;
private mostRecentCompletionId: string | null = null;
+ // Helps us skip redundant calculations. No need for cleanup because this always gets reassigned with new values at showNextEditWindow, and we don't reuse windows.
+ private editableRegionStartLine: number = 0;
+ private editableRegionEndLine: number = 0;
// Disposables
private disposables: vscode.Disposable[] = [];
@@ -261,6 +260,7 @@ export class NextEditWindowManager {
editor: vscode.TextEditor,
currCursorPos: vscode.Position,
editableRegionStartLine: number,
+ editableRegionEndLine: number,
oldEditRangeSlice: string,
newEditRangeSlice: string,
diffLines: DiffLine[],
@@ -272,11 +272,15 @@ export class NextEditWindowManager {
// Clear any existing decorations first (very important to prevent overlapping).
await this.hideAllNextEditWindows();
+ this.editableRegionStartLine = editableRegionStartLine;
+ this.editableRegionEndLine = editableRegionEndLine;
+
// Store the current tooltip text for accepting later.
this.currentTooltipText = newEditRangeSlice;
// How far away is the current line from the start of the editable region?
- const lineOffsetAtCursorPos = currCursorPos.line - editableRegionStartLine;
+ const lineOffsetAtCursorPos =
+ currCursorPos.line - this.editableRegionStartLine;
// How long is the line at the current cursor position?
const lineContentAtCursorPos =
@@ -291,7 +295,7 @@ export class NextEditWindowManager {
// Calculate the actual line number in the editor by adding the startPos offset
// to the line number from the diff calculation.
this.finalCursorPos = new vscode.Position(
- editableRegionStartLine + offset.line,
+ this.editableRegionStartLine + offset.line,
offset.character,
);
@@ -301,13 +305,13 @@ export class NextEditWindowManager {
currCursorPos,
oldEditRangeSlice,
newEditRangeSlice,
- editableRegionStartLine,
+ this.editableRegionStartLine,
diffLines,
);
const diffChars = myersCharDiff(oldEditRangeSlice, newEditRangeSlice);
- this.renderDeletes(editor, editableRegionStartLine, diffChars);
+ this.renderDeletions(editor, diffChars);
// Reserve tab and esc to either accept or reject the displayed next edit contents.
await NextEditWindowManager.reserveTabAndEsc();
@@ -317,6 +321,8 @@ export class NextEditWindowManager {
* Hide all tooltips in all editors.
*/
public async hideAllNextEditWindows() {
+ await NextEditWindowManager.freeTabAndEsc();
+
if (this.currentDecoration) {
vscode.window.visibleTextEditors.forEach((editor) => {
editor.setDecorations(this.currentDecoration!, []);
@@ -339,12 +345,10 @@ export class NextEditWindowManager {
// Clear the current tooltip text.
this.currentTooltipText = null;
}
-
- await NextEditWindowManager.freeTabAndEsc();
}
public async hideAllNextEditWindowsAndResetCompletionId() {
- this.hideAllNextEditWindows();
+ await this.hideAllNextEditWindows();
// Log with accept = false.
await vscode.commands.executeCommand(
@@ -352,6 +356,7 @@ export class NextEditWindowManager {
this.mostRecentCompletionId,
this.loggingService,
);
+
this.mostRecentCompletionId = null;
}
@@ -369,6 +374,10 @@ export class NextEditWindowManager {
const position = editor.selection.active;
let success = false;
+
+ // Hide windows first for a snappier feel.
+ await this.hideAllNextEditWindows();
+
if (this.textApplier) {
success = await this.textApplier.applyText(
editor,
@@ -377,20 +386,15 @@ export class NextEditWindowManager {
this.finalCursorPos,
);
} else {
- // Define the editable region.
- const editableRegionStartLine = Math.max(
- 0,
- position.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
- );
- const editableRegionEndLine = Math.min(
- editor.document.lineCount - 1,
- position.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
- );
- const startPos = new vscode.Position(editableRegionStartLine, 0);
- const endPosChar = editor.document.lineAt(editableRegionEndLine).text
+ // Define the range to replace.
+ const startPos = new vscode.Position(this.editableRegionStartLine, 0);
+ const endPosChar = editor.document.lineAt(this.editableRegionEndLine).text
.length;
- const endPos = new vscode.Position(editableRegionEndLine, endPosChar);
+ const endPos = new vscode.Position(
+ this.editableRegionEndLine,
+ endPosChar,
+ );
const editRange = new vscode.Range(startPos, endPos);
success = await editor.edit((editBuilder) => {
@@ -405,23 +409,19 @@ export class NextEditWindowManager {
.update("editor.inlineSuggest.enabled", false, true);
}
- if (success) {
+ if (success && this.finalCursorPos) {
// Move cursor to the final position if available.
- if (this.finalCursorPos) {
- editor.selection = new vscode.Selection(
- this.finalCursorPos,
- this.finalCursorPos,
- );
-
- // Reenable inline suggestions after we move the cursor.
- await vscode.workspace
- .getConfiguration()
- .update("editor.inlineSuggest.enabled", true, true);
-
- await this.hideAllNextEditWindows();
- }
+ editor.selection = new vscode.Selection(
+ this.finalCursorPos,
+ this.finalCursorPos,
+ );
}
+ // Reenable inline suggestions.
+ await vscode.workspace
+ .getConfiguration()
+ .update("editor.inlineSuggest.enabled", true, true);
+
// Log with accept = true.
await vscode.commands.executeCommand(
"continue.logNextEditOutcomeAccept",
@@ -454,7 +454,7 @@ export class NextEditWindowManager {
*/
private setupListeners() {
// Theme change listener.
- vscode.workspace.onDidChangeConfiguration((e) => {
+ vscode.workspace.onDidChangeConfiguration(async (e) => {
if (
e.affectsConfiguration("workbench.colorTheme") ||
e.affectsConfiguration("editor.fontSize") ||
@@ -467,7 +467,7 @@ export class NextEditWindowManager {
e.affectsConfiguration("workbench.preferredHighContrastLightColorTheme")
) {
this.theme = getThemeString();
- this.codeRenderer.setTheme(this.theme);
+ await this.codeRenderer.setTheme(this.theme);
console.log(
"Theme updated:",
this.theme ? "Theme exists" : "Theme is undefined",
@@ -479,9 +479,9 @@ export class NextEditWindowManager {
});
// Listen for active color theme changes.
- vscode.window.onDidChangeActiveColorTheme(() => {
+ vscode.window.onDidChangeActiveColorTheme(async () => {
this.theme = getThemeString();
- this.codeRenderer.setTheme(this.theme);
+ await this.codeRenderer.setTheme(this.theme);
console.log(
"Active theme changed:",
this.theme ? "Theme exists" : "Theme is undefined",
@@ -495,10 +495,11 @@ export class NextEditWindowManager {
this.activeEditor &&
!vscode.window.visibleTextEditors.includes(this.activeEditor)
) {
- if (this.mostRecentCompletionId)
+ if (this.mostRecentCompletionId) {
this.loggingService.cancelRejectionTimeout(
this.mostRecentCompletionId,
);
+ }
await this.hideAllNextEditWindows();
}
});
@@ -508,10 +509,11 @@ export class NextEditWindowManager {
// If the selection changed in our active editor, hide the tooltip.
if (this.activeEditor && e.textEditor === this.activeEditor) {
// If the cursor moved because of something other than accepting next edit, stop logging it.
- if (!this.accepted && this.mostRecentCompletionId)
+ if (!this.accepted && this.mostRecentCompletionId) {
this.loggingService.cancelRejectionTimeout(
this.mostRecentCompletionId,
);
+ }
await this.hideAllNextEditWindows();
}
});
@@ -747,7 +749,6 @@ export class NextEditWindowManager {
}
// Store the decoration and editor.
- await this.hideAllNextEditWindows();
this.currentDecoration = decoration; // TODO: This might be redundant.
this.disposables.push(decoration);
this.activeEditor = editor;
@@ -786,13 +787,7 @@ export class NextEditWindowManager {
);
}
- private renderDeletes(
- editor: vscode.TextEditor,
- editableRegionStartLine: number,
- // oldEditRangeSlice: string,
- // newEditRangeSlice: string,
- oldDiffChars: DiffChar[],
- ) {
+ private renderDeletions(editor: vscode.TextEditor, oldDiffChars: DiffChar[]) {
const charsToDelete: vscode.DecorationOptions[] = [];
// const diffChars = myersCharDiff(oldEditRangeSlice, newEditRangeSlice);
@@ -803,11 +798,11 @@ export class NextEditWindowManager {
charsToDelete.push({
range: new vscode.Range(
new vscode.Position(
- editableRegionStartLine + diff.oldLineIndex!,
+ this.editableRegionStartLine + diff.oldLineIndex!,
diff.oldCharIndexInLine!,
),
new vscode.Position(
- editableRegionStartLine + diff.oldLineIndex!,
+ this.editableRegionStartLine + diff.oldLineIndex!,
diff.oldCharIndexInLine! + diff.char.length,
),
),
diff --git a/extensions/vscode/src/apply/ApplyManager.ts b/extensions/vscode/src/apply/ApplyManager.ts
index 1ac84c368..c12d6323a 100644
--- a/extensions/vscode/src/apply/ApplyManager.ts
+++ b/extensions/vscode/src/apply/ApplyManager.ts
@@ -29,13 +29,6 @@ export class ApplyManager {
toolCallId,
isSearchAndReplace,
}: ApplyToFilePayload) {
- await this.webviewProtocol.request("updateApplyState", {
- streamId,
- status: "streaming",
- fileContent: text,
- toolCallId,
- });
-
if (filepath) {
await this.ensureFileOpen(filepath);
}
@@ -46,6 +39,17 @@ export class ApplyManager {
return;
}
+ // Capture the original file content before applying changes
+ const originalFileContent = activeTextEditor.document.getText();
+
+ await this.webviewProtocol.request("updateApplyState", {
+ streamId,
+ status: "streaming",
+ fileContent: text,
+ originalFileContent,
+ toolCallId,
+ });
+
const hasExistingDocument = !!activeTextEditor.document.getText().trim();
if (hasExistingDocument) {
diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts
index 88131a3e8..39b82c1a0 100644
--- a/extensions/vscode/src/autocomplete/completionProvider.ts
+++ b/extensions/vscode/src/autocomplete/completionProvider.ts
@@ -420,6 +420,7 @@ export class ContinueCompletionProvider
editor,
currCursorPos,
editableRegionStartLine,
+ editableRegionEndLine,
oldEditRangeSlice,
newEditRangeSlice,
diffLines,
diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts
index 339f9e84b..869e5962d 100644
--- a/extensions/vscode/src/diff/vertical/handler.ts
+++ b/extensions/vscode/src/diff/vertical/handler.ts
@@ -315,11 +315,12 @@ export class VerticalDiffHandler implements vscode.Disposable {
// newline separated, because myersDiff() would consider
// ["A"] => "A" and ["A", ""] => "A\n" to be the same single line.
// "A\n" and "A\n\n" are unambiguous.
- const oldFileContent =
- diffLines
- .filter((line) => line.type === "same" || line.type === "old")
- .map((line) => line.line)
- .join("\n") + "\n";
+ const oldContentWithoutTrailingNewline = diffLines
+ .filter((line) => line.type === "same" || line.type === "old")
+ .map((line) => line.line)
+ .join("\n");
+
+ const oldFileContent = oldContentWithoutTrailingNewline + "\n";
const newFileContent =
diffLines
@@ -329,9 +330,16 @@ export class VerticalDiffHandler implements vscode.Disposable {
const myersDiffs = myersDiff(oldFileContent, newFileContent);
- const replaceContent = myersDiffs
- .map((diff) => (diff.type === "old" ? "" : diff.line))
- .join("\n");
+ // Preserve the trailing newline behavior by checking the original document content
+ const originalDocumentContent = this.editor.document.getText(this.range);
+ const originalContentEndsWithNewline =
+ originalDocumentContent.endsWith("\n");
+
+ // Add trailing newline only if the original file had one to prevent line count discrepancies
+ const replaceContent =
+ myersDiffs
+ .map((diff) => (diff.type === "old" ? "" : diff.line))
+ .join("\n") + (originalContentEndsWithNewline ? "\n" : "");
// Then, we insert our diff lines
await this.editor.edit((editBuilder) => {
diff --git a/extensions/vscode/src/extension/EditOutcomeTracker.ts b/extensions/vscode/src/extension/EditOutcomeTracker.ts
index c69dbac72..69ac452fa 100644
--- a/extensions/vscode/src/extension/EditOutcomeTracker.ts
+++ b/extensions/vscode/src/extension/EditOutcomeTracker.ts
@@ -65,6 +65,7 @@ class EditOutcomeTracker {
newCodeLines: pendingEdit.newCodeLines,
lineChange: pendingEdit.lineChange,
accepted,
+ filepath: pendingEdit.filepath,
},
});
diff --git a/gui/src/components/StyledMarkdownPreview/index.tsx b/gui/src/components/StyledMarkdownPreview/index.tsx
index aed35e735..5b1249cd8 100644
--- a/gui/src/components/StyledMarkdownPreview/index.tsx
+++ b/gui/src/components/StyledMarkdownPreview/index.tsx
@@ -113,6 +113,10 @@ const StyledMarkdown = styled.div<{
line-height: 1.5;
}
+ * {
+ word-break: break-word;
+ }
+
> *:last-child {
margin-bottom: 0;
}
diff --git a/gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.test.ts b/gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.test.ts
deleted file mode 100644
index 51649c251..000000000
--- a/gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.test.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import { headerIsMarkdown } from "./headerIsMarkdown";
-
-describe("headerIsMarkdown", () => {
- // Test exact match with common Markdown identifiers
- it("should identify exact matches with common Markdown identifiers", () => {
- expect(headerIsMarkdown("md")).toBe(true);
- expect(headerIsMarkdown("markdown")).toBe(true);
- expect(headerIsMarkdown("gfm")).toBe(true);
- expect(headerIsMarkdown("github-markdown")).toBe(true);
- });
-
- // Test identifiers preceded by a space
- it("should identify identifiers preceded by a space", () => {
- expect(headerIsMarkdown("lang md")).toBe(true);
- expect(headerIsMarkdown("something markdown")).toBe(true);
- expect(headerIsMarkdown("language gfm")).toBe(true);
- expect(headerIsMarkdown("spec github-markdown")).toBe(true);
- });
-
- // Test file extensions
- it("should identify file names with markdown extensions", () => {
- expect(headerIsMarkdown("example.md")).toBe(true);
- expect(headerIsMarkdown("document.markdown")).toBe(true);
- expect(headerIsMarkdown("readme.gfm")).toBe(true);
- });
-
- // Test more complex cases with extensions
- it("should identify file names with markdown extensions followed by other text", () => {
- expect(headerIsMarkdown("example.md additional text")).toBe(true);
- expect(headerIsMarkdown("document.markdown with some description")).toBe(
- true,
- );
- expect(headerIsMarkdown("readme.gfm v2.0")).toBe(true);
- });
-
- // Test non-markdown cases
- it("should not identify non-markdown headers", () => {
- expect(headerIsMarkdown("javascript")).toBe(false);
- expect(headerIsMarkdown("typescript")).toBe(false);
- expect(headerIsMarkdown("plain")).toBe(false);
- expect(headerIsMarkdown("python")).toBe(false);
- });
-
- // Test edge cases
- it("should handle edge cases correctly", () => {
- expect(headerIsMarkdown("")).toBe(false);
- expect(headerIsMarkdown("mdx")).toBe(false); // Similar but not exactly "md"
- expect(headerIsMarkdown("readme md")).toBe(true);
- expect(headerIsMarkdown("md.js")).toBe(false); // "md" is not the extension
- });
-
- // Test case sensitivity
- it("should respect case sensitivity", () => {
- expect(headerIsMarkdown("MD")).toBe(false);
- expect(headerIsMarkdown("MARKDOWN")).toBe(false);
- expect(headerIsMarkdown("example.MD")).toBe(false);
- expect(headerIsMarkdown("lang MD")).toBe(false);
- });
-
- // Test with special characters and spacing
- it("should handle special characters and spacing correctly", () => {
- expect(headerIsMarkdown(" md")).toBe(true); // Space before "md"
- expect(headerIsMarkdown("md ")).toBe(true); // Space after "md"
- expect(headerIsMarkdown("hello-md")).toBe(false); // "md" with hyphen prefix
- expect(headerIsMarkdown("markdown:")).toBe(false); // "markdown" with suffix
- });
-});
diff --git a/gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.ts b/gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.ts
deleted file mode 100644
index cfdba2fde..000000000
--- a/gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-/**
- * Determines if a given header string represents Markdown content.
- *
- * The function checks various patterns to identify Markdown headers:
- * - Exact match with common Markdown identifiers (md, markdown, gfm, github-markdown)
- * - Contains these identifiers preceded by a space
- * - First word has a file extension of md, markdown, or gfm
- *
- * @param header - The string to check for Markdown indicators
- * @returns True if the header represents Markdown content, false otherwise
- */
-export function headerIsMarkdown(header: string): boolean {
- return (
- header === "md" ||
- header === "markdown" ||
- header === "gfm" ||
- header === "github-markdown" ||
- header.includes(" md") ||
- header.includes(" markdown") ||
- header.includes(" gfm") ||
- header.includes(" github-markdown") ||
- header.split(" ")[0]?.split(".").pop() === "md" ||
- header.split(" ")[0]?.split(".").pop() === "markdown" ||
- header.split(" ")[0]?.split(".").pop() === "gfm"
- );
-}
diff --git a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.test.ts b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.test.ts
index af94f118d..4e347a9e2 100644
--- a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.test.ts
+++ b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.test.ts
@@ -6,6 +6,14 @@ describe("patchNestedMarkdown", () => {
expect(patchNestedMarkdown(source)).toBe(source);
});
+ it("should handle nested blocks without a type", () => {
+ const source =
+ "```markdown README.md\n# Project Structure\n\n```\n.\n├── AdvancedPage.tsx\n├── Calculator.java\n├── Dockerfile\n├── calculator_test/\n│ ├── Calculator.java\n│ └── Main.java\n├── data.json\n├── example.ipynb\n├── logs/\n├── nested-folder/\n│ ├── helloNested.py\n│ ├── package.json\n│ └── rules.md\n├── program.cs\n├── query.sql\n├── react-calculator/\n├── readme.md\n├── requirements.txt\n├── test.css\n├── test.html\n├── test.js\n├── test.kt\n├── test.php\n├── test.py\n├── test.rb\n├── test.rs\n├── test.sh\n└── test.ts\n```\n```";
+ const expected =
+ "~~~markdown README.md\n# Project Structure\n\n```\n.\n├── AdvancedPage.tsx\n├── Calculator.java\n├── Dockerfile\n├── calculator_test/\n│ ├── Calculator.java\n│ └── Main.java\n├── data.json\n├── example.ipynb\n├── logs/\n├── nested-folder/\n│ ├── helloNested.py\n│ ├── package.json\n│ └── rules.md\n├── program.cs\n├── query.sql\n├── react-calculator/\n├── readme.md\n├── requirements.txt\n├── test.css\n├── test.html\n├── test.js\n├── test.kt\n├── test.php\n├── test.py\n├── test.rb\n├── test.rs\n├── test.sh\n└── test.ts\n```\n~~~";
+ expect(patchNestedMarkdown(source)).toBe(expected);
+ });
+
it("should replace backticks with tildes for markdown codeblocks", () => {
const source = "```markdown\n# Header\nSome text\n```";
const expected = "~~~markdown\n# Header\nSome text\n~~~";
diff --git a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts
index 9be5bfbb2..380c1a18a 100644
--- a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts
+++ b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts
@@ -7,7 +7,10 @@
Note, this was benchmarked at sub-millisecond
*/
-import { headerIsMarkdown } from "./headerIsMarkdown";
+import {
+ headerIsMarkdown,
+ MarkdownBlockStateTracker,
+} from "../../../../../core/utils/markdownUtils";
export const patchNestedMarkdown = (source: string): string => {
// Early return if no markdown codeblock pattern is found (including GitHub variants)
@@ -16,21 +19,29 @@ export const patchNestedMarkdown = (source: string): string => {
let nestCount = 0;
const lines = source.split("\n");
- const trimmedLines = lines.map((l) => l.trim());
+
+ // Use optimized state tracker for efficient bare backtick analysis
+ const stateTracker = new MarkdownBlockStateTracker(lines);
+ const trimmedLines = stateTracker.getTrimmedLines();
for (let i = 0; i < trimmedLines.length; i++) {
const line = trimmedLines[i];
if (nestCount > 0) {
// Inside a markdown block
- if (line.match(/^`+$/)) {
- // Ending a block with just backticks (```)
- nestCount--;
- if (nestCount === 0) {
- lines[i] = "~~~"; // End of markdown block
+ if (stateTracker.isBareBacktickLine(i)) {
+ // Found bare backticks - use optimized lookup for remaining count
+ const remainingBareBackticks =
+ stateTracker.getRemainingBareBackticksAfter(i);
+
+ // If this is the last bare backticks, it closes the markdown block
+ if (remainingBareBackticks === 0) {
+ nestCount = 0;
+ lines[i] = "~~~"; // Convert final closing delimiter to tildes
}
+ // Otherwise, keep as backticks (inner nested block delimiter)
} else if (line.startsWith("```")) {
- // Going into a nested codeblock
+ // Going into a nested codeblock (with language identifier)
nestCount++;
}
} else {
diff --git a/gui/src/components/gui/Alert.tsx b/gui/src/components/gui/Alert.tsx
index a2739757f..f7eb5b845 100644
--- a/gui/src/components/gui/Alert.tsx
+++ b/gui/src/components/gui/Alert.tsx
@@ -3,7 +3,7 @@ import {
ExclamationCircleIcon,
ExclamationTriangleIcon,
InformationCircleIcon,
-} from "@heroicons/react/24/solid";
+} from "@heroicons/react/16/solid";
import { ReactNode } from "react";
import { vscBackground } from "..";
diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx
index f97c7d101..ff596c7e7 100644
--- a/gui/src/components/mainInput/InputToolbar.tsx
+++ b/gui/src/components/mainInput/InputToolbar.tsx
@@ -1,8 +1,9 @@
import {
AtSymbolIcon,
- LightBulbIcon,
+ LightBulbIcon as LightBulbIconOutline,
PhotoIcon,
} from "@heroicons/react/24/outline";
+import { LightBulbIcon as LightBulbIconSolid } from "@heroicons/react/24/solid";
import { InputModifiers } from "core";
import { modelSupportsImages } from "core/llm/autodetect";
import { useContext, useRef } from "react";
@@ -13,7 +14,6 @@ import { selectSelectedChatModel } from "../../redux/slices/configSlice";
import { setHasReasoningEnabled } from "../../redux/slices/sessionSlice";
import { exitEdit } from "../../redux/thunks/edit";
import { getAltKeyLabel, isMetaEquivalentKeyPressed } from "../../util";
-import { cn } from "../../util/cn";
import { ToolTip } from "../gui/Tooltip";
import ModelSelect from "../modelSelection/ModelSelect";
import { ModeSelect } from "../ModeSelect";
@@ -139,19 +139,23 @@ function InputToolbar(props: InputToolbarProps) {
)}
- {defaultModel?.provider === "anthropic" && (
+ {defaultModel?.underlyingProviderName === "anthropic" && (
dispatch(setHasReasoningEnabled(!hasReasoningEnabled))
}
>
-
+ {hasReasoningEnabled ? (
+
+ ) : (
+
+ )}
{hasReasoningEnabled
diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/GeneratingIndicator.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/GeneratingIndicator.tsx
index e6d38d85a..0f95a4e40 100644
--- a/gui/src/components/mainInput/Lump/LumpToolbar/GeneratingIndicator.tsx
+++ b/gui/src/components/mainInput/Lump/LumpToolbar/GeneratingIndicator.tsx
@@ -8,8 +8,8 @@ export function GeneratingIndicator({
testId?: string;
}) {
return (
-
- {text}
+
+ {text}
);
diff --git a/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPoliciesSection.tsx b/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPoliciesSection.tsx
index 8adfa75d2..5aee1466f 100644
--- a/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPoliciesSection.tsx
+++ b/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPoliciesSection.tsx
@@ -1,4 +1,4 @@
-import { Tool } from "core";
+import { MessageModes, Tool } from "core";
import { useMemo } from "react";
import { useAppDispatch, useAppSelector } from "../../../../../redux/hooks";
import { toggleToolGroupSetting } from "../../../../../redux/slices/uiSlice";
@@ -43,20 +43,28 @@ export const ToolPoliciesSection = () => {
const allToolsOff = mode === "chat";
- const message =
- mode === "chat"
- ? "All tools disabled (Chat)"
- : mode === "plan"
- ? "Read-only/MCP tools available (Plan)"
- : "All tools available (Agent)";
+ const getMessage = (mode: MessageModes) => {
+ switch (mode) {
+ case "chat":
+ return "All tools disabled in Chat, switch to Plan or Agent mode to use tools";
+ case "plan":
+ return "Read-only/MCP tools available in Plan mode";
+ default:
+ return "";
+ }
+ };
+
+ const message = getMessage(mode);
return (
<>
-