From d5294ae0c16f814ad2730784781cb448f2aa332f Mon Sep 17 00:00:00 2001 From: Jakub Blach Date: Mon, 4 Aug 2025 19:22:31 +0200 Subject: [PATCH 01/48] fix: update autocomplete to inline.completion.provider 2024.1 API --- extensions/intellij/build.gradle.kts | 7 +- extensions/intellij/gradle.properties | 3 - .../actions/ContinueActionPromote.kt | 20 +- .../autocomplete/AcceptAutocompleteAction.kt | 25 -- .../AutocompleteEditorListener.kt | 151 -------- .../AutocompleteLookupListener.kt | 48 --- .../autocomplete/AutocompleteService.kt | 323 ------------------ .../AutocompleteSpinnerWidgetFactory.kt | 109 ------ .../autocomplete/CancelAutocompleteAction.kt | 35 -- .../autocomplete/CompletionService.kt | 10 + .../autocomplete/ContinueCompletionService.kt | 54 +++ .../autocomplete/ContinueInlayRenderer.kt | 58 ---- .../ContinueInlineCompletionProvider.kt | 66 ++++ .../DisableTabAutocompleteAction.kt | 12 - .../EnableTabAutocompleteAction.kt | 12 - .../PartialAcceptAutocompleteAction.kt | 25 -- .../continue/ApplyToFileHandler.kt | 34 +- .../continue/ProfileInfoService.kt | 63 ++++ .../editor/InlineEditPanel.kt | 51 +-- .../nextEdit/AcceptNextEditAction.kt | 25 -- .../nextEdit/NextEditService.kt | 321 ----------------- .../nextEdit/NextEditWindowService.kt | 304 ----------------- .../src/main/resources/META-INF/plugin.xml | 41 +-- .../ContinueInlineCompletionProviderTest.kt | 116 +++++++ 24 files changed, 340 insertions(+), 1573 deletions(-) delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AcceptAutocompleteAction.kt delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteEditorListener.kt delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteLookupListener.kt delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteSpinnerWidgetFactory.kt delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/CancelAutocompleteAction.kt create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/CompletionService.kt create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCompletionService.kt delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlayRenderer.kt create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/DisableTabAutocompleteAction.kt delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/EnableTabAutocompleteAction.kt delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/PartialAcceptAutocompleteAction.kt create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ProfileInfoService.kt delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/AcceptNextEditAction.kt delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditService.kt delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowService.kt create mode 100644 extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinueInlineCompletionProviderTest.kt diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts index 8692b35f4..8b948203f 100644 --- a/extensions/intellij/build.gradle.kts +++ b/extensions/intellij/build.gradle.kts @@ -34,12 +34,13 @@ repositories { dependencies { intellijPlatform { - create(platformType, platformVersion) + create("IC", "2024.1") plugins(listOf("org.jetbrains.plugins.terminal:223.8214.6")) testFramework(TestFrameworkType.Platform) } implementation("com.posthog.java:posthog:1.2.0") + testImplementation("junit:junit:4.13.2") testImplementation("com.intellij.remoterobot:remote-robot:$remoteRobotVersion") testImplementation("com.intellij.remoterobot:remote-fixtures:$remoteRobotVersion") testImplementation("io.mockk:mockk:1.14.2") @@ -54,13 +55,13 @@ kotlin { jvmToolchain(17) } intellijPlatform { pluginConfiguration { ideaVersion { - sinceBuild = pluginSinceBuild + sinceBuild = "241" } } pluginVerification { ides { ide("IC", "2025.1.4") - ide("IC", "2022.3.3") + ide("IC", "2024.1") } } } diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 175993fa2..c058c9206 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -1,9 +1,6 @@ pluginGroup=com.github.continuedev.continueintellijextension pluginRepositoryUrl=https://github.com/continuedev/continue pluginVersion=1.0.34 -pluginSinceBuild=223 -platformType=IC -platformVersion=2022.3.3 kotlin.stdlib.default.dependency=false org.gradle.configuration-cache=true org.gradle.caching=true diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt index 747fefd03..c67148937 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt @@ -1,32 +1,14 @@ package com.github.continuedev.continueintellijextension.actions -import com.github.continuedev.continueintellijextension.autocomplete.AcceptAutocompleteAction -import com.github.continuedev.continueintellijextension.nextEdit.AcceptNextEditAction -import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings + import com.intellij.openapi.actionSystem.ActionPromoter import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.DataContext -import com.intellij.openapi.components.service import org.jetbrains.annotations.NotNull class ContinueActionPromote : ActionPromoter { override fun promote(@NotNull actions: List, @NotNull context: DataContext): List? { - // For autocomplete actions - if (actions.any { it is AcceptAutocompleteAction }) { - val settings = service() - if (settings.continueState.showIDECompletionSideBySide) { - return actions.filterIsInstance() - } - } - - if (actions.any { it is AcceptNextEditAction }) { - val settings = service() - if (settings.continueState.showIDECompletionSideBySide) { - return actions.filterIsInstance() - } - } - val rejectDiffActions = actions.filterIsInstance() if (rejectDiffActions.isNotEmpty()) { return rejectDiffActions diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AcceptAutocompleteAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AcceptAutocompleteAction.kt deleted file mode 100644 index 03b91e87c..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AcceptAutocompleteAction.kt +++ /dev/null @@ -1,25 +0,0 @@ -package com.github.continuedev.continueintellijextension.autocomplete - -import com.intellij.openapi.actionSystem.DataContext -import com.intellij.openapi.application.ApplicationManager -import com.intellij.openapi.components.service -import com.intellij.openapi.editor.Caret -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.editor.actionSystem.EditorAction -import com.intellij.openapi.editor.actionSystem.EditorActionHandler - -class AcceptAutocompleteAction : EditorAction(object : EditorActionHandler() { - override fun doExecute(editor: Editor, caret: Caret?, dataContext: DataContext?) { - ApplicationManager.getApplication().runWriteAction { - editor.project?.service()?.accept() - } - } - - override fun isEnabledForCaret(editor: Editor, caret: Caret, dataContext: DataContext?): Boolean { - val autocompleteService = editor.project?.service(); - val enabled = editor == autocompleteService?.pendingCompletion?.editor -// && caret.offset == autocompleteService.pendingCompletion?.offset - && autocompleteService.pendingCompletion?.text != null - return enabled - } -}) \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteEditorListener.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteEditorListener.kt deleted file mode 100644 index 9fca20413..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteEditorListener.kt +++ /dev/null @@ -1,151 +0,0 @@ -package com.github.continuedev.continueintellijextension.autocomplete - -import com.github.continuedev.continueintellijextension.nextEdit.NextEditService -import com.github.continuedev.continueintellijextension.services.ContinuePluginService -import com.github.continuedev.continueintellijextension.utils.castNestedOrNull -import com.intellij.openapi.application.invokeLater -import com.intellij.openapi.components.service -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.editor.EditorKind -import com.intellij.openapi.editor.event.* -import com.intellij.openapi.fileEditor.FileEditorManager -import com.intellij.openapi.fileEditor.FileEditorManagerEvent -import com.intellij.openapi.fileEditor.FileEditorManagerListener -import com.intellij.openapi.util.TextRange - -class AutocompleteCaretListener : CaretListener { - override fun caretPositionChanged(event: CaretEvent) { - if(event.editor.editorKind != EditorKind.MAIN_EDITOR) { - return - } - - val caret = event.caret ?: return - val offset = caret.offset - val editor = caret.editor - val autocompleteService = editor.project?.service() ?: return - - if (autocompleteService.lastChangeWasPartialAccept) { - autocompleteService.lastChangeWasPartialAccept = false - return - } - - val pending = autocompleteService.pendingCompletion; - if (pending != null && pending.editor == editor && pending.offset == offset) { - return - } - autocompleteService.clearCompletions(editor) - } -} - -class AutocompleteDocumentListener(private val editorManager: FileEditorManager, private val editor: Editor) : - DocumentListener { - override fun documentChanged(event: DocumentEvent) { - // Ignore empty changes or changes where content didn't actually change. - if (event.newFragment.isEmpty() && event.oldFragment.isEmpty()) { - return - } - - // Make sure this is an actual text modification event. - if (!event.isWholeTextReplaced && event.offset == 0 && event.oldLength == 0 && event.newLength == 0) { - return - } - - if (editor != editorManager.selectedTextEditor) { - return - } - - val service = editor.project?.service() ?: return - if (service.lastChangeWasPartialAccept) { - return - } - - val nextEditService = editor.project?.service() ?: return - - // Check if we're in a test environment based on some property or condition - val isAutocompleteTestEnvironment = System.getProperty("continue.autocomplete.test.environment") == "true" - val isNextEditTestEnvironment = System.getProperty("continue.nextEdit.test.environment") == "true" - - if (isAutocompleteTestEnvironment) { - invokeLater { - service.triggerCompletion(editor) - } - return - } else if (isNextEditTestEnvironment) { - invokeLater { - nextEditService.triggerNextEdit(editor) - } - return - } - - // Check settings to see if next edit is enabled, and then trigger either autocomplete or next exit. - val continuePluginService = editor.project?.service() - if (continuePluginService == null) { - return - } - - continuePluginService.coreMessenger?.request( - "config/getSerializedProfileInfo", - null, - null, - ({ response -> - val optInNextEditFeature = response.castNestedOrNull( - "content", - "result", - "config", - "experimental", - "optInNextEditFeature" - ) ?: false - - invokeLater { - if (optInNextEditFeature) { - nextEditService.triggerNextEdit(editor) - } else { - // Invoke later is important, otherwise the completion will be triggered before the document is updated - // causing the old caret offset to be used - // TODO: concurrency - service.triggerCompletion(editor) - } - } - }) - ) - } -} - -class AutocompleteEditorListener : EditorFactoryListener { - private val disposables = mutableMapOf Unit>() - override fun editorCreated(event: EditorFactoryEvent) { - val editor = event.editor - val project = editor.project ?: return - val editorManager = project.let { FileEditorManager.getInstance(it) } ?: return - val completionProvider = project.service() - - // Listen to changes to mouse position - val caretListener = AutocompleteCaretListener() - editor.caretModel.addCaretListener(caretListener) - - // Listen to changes to selection - val connection = editor.project?.messageBus?.connect() - connection?.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, object : FileEditorManagerListener { - override fun selectionChanged(event: FileEditorManagerEvent) { - completionProvider.clearCompletions(editor) - } - }) - - // Listen to changes to content - val documentListener = AutocompleteDocumentListener(editorManager, editor) - editor.document.addDocumentListener(documentListener) - - disposables[editor] = { - editor.caretModel.removeCaretListener(caretListener) - connection?.disconnect() - editor.document.removeDocumentListener(documentListener) - } - } - - override fun editorReleased(event: EditorFactoryEvent) { - val editor = event.editor - val disposable = disposables[editor] - disposable?.invoke() - disposables.remove(editor) - } -} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteLookupListener.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteLookupListener.kt deleted file mode 100644 index 2f2fa593b..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteLookupListener.kt +++ /dev/null @@ -1,48 +0,0 @@ -package com.github.continuedev.continueintellijextension.autocomplete - -import com.intellij.codeInsight.lookup.impl.LookupImpl -import com.intellij.codeInsight.lookup.Lookup -import com.intellij.codeInsight.lookup.LookupEvent -import com.intellij.codeInsight.lookup.LookupListener -import com.intellij.codeInsight.lookup.LookupManagerListener -import com.intellij.openapi.application.ApplicationManager -import com.intellij.openapi.components.Service -import com.intellij.openapi.components.service -import com.intellij.openapi.project.Project -import java.util.concurrent.atomic.AtomicBoolean - -@Service(Service.Level.PROJECT) -class AutocompleteLookupListener(project: Project) : LookupManagerListener { - private val isLookupShown = AtomicBoolean(true) - - fun isLookupEmpty(): Boolean { - return isLookupShown.get() - } - - init { - project.messageBus.connect().subscribe(LookupManagerListener.TOPIC, this) - } - - override fun activeLookupChanged(oldLookup: Lookup?, newLookup: Lookup?) { - val newEditor = newLookup?.editor ?: return - if (newLookup is LookupImpl) { - newLookup.addLookupListener( - object : LookupListener { - override fun lookupShown(event: LookupEvent) { - isLookupShown.set(false) - ApplicationManager.getApplication().invokeLater { - event.lookup.editor.project?.service()?.hideCompletions(newEditor) - } - } - - override fun lookupCanceled(event: LookupEvent) { - isLookupShown.set(true) - } - - override fun itemSelected(event: LookupEvent) { - isLookupShown.set(true) - } - }) - } - } -} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt deleted file mode 100644 index 4a84a202b..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt +++ /dev/null @@ -1,323 +0,0 @@ -package com.github.continuedev.continueintellijextension.autocomplete - -import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings -import com.github.continuedev.continueintellijextension.services.ContinuePluginService -import com.github.continuedev.continueintellijextension.utils.toUriOrNull -import com.github.continuedev.continueintellijextension.utils.uuid -import com.intellij.injected.editor.VirtualFileWindow -import com.intellij.openapi.application.* -import com.intellij.openapi.components.Service -import com.intellij.openapi.components.service -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.editor.InlayProperties -import com.intellij.openapi.editor.impl.EditorImpl -import com.intellij.openapi.fileEditor.FileDocumentManager -import com.intellij.openapi.project.Project -import com.intellij.openapi.util.TextRange -import com.intellij.openapi.wm.WindowManager -import com.intellij.psi.PsiDocumentManager -import com.intellij.psi.PsiElement - -data class PendingCompletion( - val editor: Editor, - var offset: Int, - val completionId: String, - var text: String? -) - - -fun PsiElement.isInjectedText(): Boolean { - val virtualFile = this.containingFile.virtualFile ?: return false - if (virtualFile is VirtualFileWindow) { - return true - } - return false -} - -fun Editor.addInlayElement( - lines: List, - offset: Int, - properties: InlayProperties -) { - if (this is EditorImpl) { - if (lines[0].isNotEmpty()) { - inlayModel.addInlineElement(offset, properties, ContinueInlayRenderer(listOf(lines[0]))) - } - if (lines.size > 1) { - inlayModel.addBlockElement(offset, properties, ContinueInlayRenderer(lines.drop(1))) - } - } -} - -@Service(Service.Level.PROJECT) -class AutocompleteService(private val project: Project) { - var pendingCompletion: PendingCompletion? = null - private val autocompleteLookupListener = project.service() - private val widget: AutocompleteSpinnerWidget? by lazy { - WindowManager.getInstance().getStatusBar(project) - ?.getWidget(AutocompleteSpinnerWidget.ID) as? AutocompleteSpinnerWidget - } - - // To avoid triggering another completion on partial acceptance, - // we need to keep track of whether the last change was a partial accept - var lastChangeWasPartialAccept = false - - fun triggerCompletion(editor: Editor) { - val settings = service() - if (!settings.continueState.enableTabAutocomplete) { - return - } - - if (pendingCompletion != null) { - clearCompletions(pendingCompletion!!.editor) - } - - // Set pending completion - val completionId = uuid() - val offset = editor.caretModel.primaryCaret.offset - pendingCompletion = PendingCompletion(editor, offset, completionId, null) - - // Request a completion from the core - val virtualFile = FileDocumentManager.getInstance().getFile(editor.document) - - val uri = virtualFile?.toUriOrNull() ?: return - - widget?.setLoading(true) - - val line = editor.caretModel.primaryCaret.logicalPosition.line - val column = editor.caretModel.primaryCaret.logicalPosition.column - val input = mapOf( - "completionId" to completionId, - "filepath" to uri, - "pos" to mapOf( - "line" to line, - "character" to column - ), - "clipboardText" to "", - "recentlyEditedRanges" to emptyList(), - "recentlyVisitedRanges" to emptyList(), - ) - - project.service().coreMessenger?.request( - "autocomplete/complete", - input, - null, - ({ response -> - if (pendingCompletion == null || pendingCompletion?.completionId == completionId) { - widget?.setLoading(false) - } - - val responseObject = response as Map<*, *> - val completions = responseObject["content"] as List<*> - - if (completions.isNotEmpty()) { - val completion = completions[0].toString() - val finalTextToInsert = deduplicateCompletion(editor, offset, completion) - - if (shouldRenderCompletion(finalTextToInsert, offset, line, editor)) { - renderCompletion(editor, offset, finalTextToInsert) - pendingCompletion = PendingCompletion(editor, offset, completionId, finalTextToInsert) - } - } - }) - ) - } - - private fun shouldRenderCompletion(completion: String, offset: Int, line: Int, editor: Editor): Boolean { - if (completion.isEmpty() || runReadAction { offset != editor.caretModel.offset }) { - return false - } - - if (completion.lines().size == 1) { - return true - } - - val endOffset = editor.document.getLineEndOffset(line) - - // Do not render if completion is multi-line and caret is in middle of line - return offset <= endOffset && editor.document.getText(TextRange(offset, endOffset)).isBlank() - } - - private fun deduplicateCompletion(editor: Editor, offset: Int, completion: String): String { - // Check if completion matches the first 10 characters after the cursor - return ApplicationManager.getApplication().runReadAction { - val document = editor.document - val caretOffset = editor.caretModel.offset - - // Don't care about it if it's at the end of the document - if (caretOffset == document.textLength) return@runReadAction completion - - val N = 10 - var textAfterCursor = if (caretOffset + N <= document.textLength) { - document.getText(TextRange(caretOffset, caretOffset + N)) - } else { - document.getText(TextRange(caretOffset, document.textLength)) - } - - // Avoid truncating the completion text when the text after the cursor is blank - if (textAfterCursor.isBlank()) return@runReadAction completion - - // Determine the index of a newline character within the text following the cursor. - val newlineIndex = textAfterCursor.indexOf("\r\n").takeIf { it >= 0 } ?: textAfterCursor.indexOf('\n') - // If a newline character is found and the current line is not empty, truncate the text at that point. - if (newlineIndex > 0) { - textAfterCursor = textAfterCursor.substring(0, newlineIndex) - } - - val indexOfTextAfterCursorInCompletion = completion.indexOf(textAfterCursor) - if (indexOfTextAfterCursorInCompletion > 0) { - return@runReadAction completion.slice(0..indexOfTextAfterCursorInCompletion - 1) - } else if (indexOfTextAfterCursorInCompletion == 0) { - return@runReadAction "" - } - - return@runReadAction completion - } - } - - private fun renderCompletion(editor: Editor, offset: Int, completion: String) { - if (completion.isEmpty()) { - return - } - if (isInjectedFile(editor)) return - // Skip rendering completions if the code completion dropdown is already visible and the IDE completion side-by-side setting is disabled - if (shouldSkipRender()) { - return - } - - invokeLater { - // Clear existing completions - hideCompletions(editor) - - val properties = InlayProperties() - properties.relatesToPrecedingText(true) - properties.disableSoftWrapping(true) - - val lines = completion.lines() - pendingCompletion = pendingCompletion?.copy(text = lines.joinToString("\n")) - editor.addInlayElement(lines, offset, properties) - -// val attributes = TextAttributes().apply { -// backgroundColor = JBColor.GREEN -// } -// val key = TextAttributesKey.createTextAttributesKey("CONTINUE_AUTOCOMPLETE") -// key.let { editor.colorsScheme.setAttributes(it, attributes) } -// editor.markupModel.addLineHighlighter(key, editor.caretModel.logicalPosition.line, HighlighterLayer.LAST) - } - } - - fun accept() { - val completion = pendingCompletion ?: return - val text = completion.text ?: return - val editor = completion.editor - val offset = completion.offset - editor.document.insertString(offset, text) - - editor.caretModel.moveToOffset(offset + text.length) - - project.service().coreMessenger?.request( - "autocomplete/accept", - hashMapOf("completionId" to completion.completionId), - null, - ({}) - ) - invokeLater { - clearCompletions(editor, completion) - } - } - - private fun shouldSkipRender(): Boolean { - val settings = service() - return !settings.continueState.showIDECompletionSideBySide && !autocompleteLookupListener.isLookupEmpty() - } - - private fun splitKeepingDelimiters(input: String, delimiterPattern: String = "\\s+"): List { - val initialSplit = input.split("(?<=$delimiterPattern)|(?=$delimiterPattern)".toRegex()) - .filter { it.isNotEmpty() } - - val result = mutableListOf() - var currentDelimiter = "" - - for (part in initialSplit) { - if (part.matches(delimiterPattern.toRegex())) { - currentDelimiter += part - } else { - if (currentDelimiter.isNotEmpty()) { - result.add(currentDelimiter) - currentDelimiter = "" - } - result.add(part) - } - } - - if (currentDelimiter.isNotEmpty()) { - result.add(currentDelimiter) - - } - - return result - } - - fun partialAccept() { - val completion = pendingCompletion ?: return - val text = completion.text ?: return - val editor = completion.editor - val offset = completion.offset - - lastChangeWasPartialAccept = true - - // Split the text into words, keeping delimiters - val words = splitKeepingDelimiters(text) - println(words) - val word = words[0] - editor.document.insertString(offset, word) - editor.caretModel.moveToOffset(offset + word.length) - - // Remove the completion and re-display it - hideCompletions(editor) - completion.text = text.substring(word.length) - completion.offset += word.length - renderCompletion(editor, completion.offset, completion.text!!) - } - - private fun cancelCompletion(completion: PendingCompletion) { - // Send cancellation message to core - widget?.setLoading(false) - project.service().coreMessenger?.request("autocomplete/cancel", null, null, ({})) - } - - fun clearCompletions(editor: Editor, completion: PendingCompletion? = pendingCompletion) { - if (isInjectedFile(editor)) return - - if (completion != null) { - cancelCompletion(completion) - if (completion.completionId == pendingCompletion?.completionId) pendingCompletion = null - } - disposeInlayRenderer(editor) - } - - private fun isInjectedFile(editor: Editor): Boolean { - return runReadAction { - PsiDocumentManager.getInstance(project).getPsiFile(editor.document)?.isInjectedText() ?: false - } - } - - fun hideCompletions(editor: Editor) { - if (isInjectedFile(editor)) return - - disposeInlayRenderer(editor) - } - - private fun disposeInlayRenderer(editor: Editor) { - editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength).forEach { - if (it.renderer is ContinueInlayRenderer) { - it.dispose() - } - } - editor.inlayModel.getBlockElementsInRange(0, editor.document.textLength).forEach { - if (it.renderer is ContinueInlayRenderer) { - it.dispose() - } - } - } -} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteSpinnerWidgetFactory.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteSpinnerWidgetFactory.kt deleted file mode 100644 index b19baf669..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteSpinnerWidgetFactory.kt +++ /dev/null @@ -1,109 +0,0 @@ -package com.github.continuedev.continueintellijextension.autocomplete - -import com.github.continuedev.continueintellijextension.Icons -import com.github.continuedev.continueintellijextension.activities.ContinuePluginDisposable -import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings -import com.intellij.openapi.Disposable -import com.intellij.openapi.components.service -import com.intellij.openapi.project.Project -import com.intellij.openapi.util.Disposer -import com.intellij.openapi.wm.StatusBar -import com.intellij.openapi.wm.StatusBarWidget -import com.intellij.openapi.util.IconLoader -import com.intellij.openapi.wm.StatusBarWidgetFactory -import com.intellij.openapi.wm.WindowManager -import com.intellij.openapi.wm.impl.status.EditorBasedWidget -import com.intellij.ui.AnimatedIcon -import com.intellij.util.Consumer -import java.awt.event.MouseEvent -import javax.swing.Icon -import javax.swing.JLabel - -class AutocompleteSpinnerWidget(project: Project) : EditorBasedWidget(project), StatusBarWidget.IconPresentation, - Disposable { - private val iconLabel = JLabel() - private var isLoading = false - - private val animatedIcon = AnimatedIcon.Default() - - init { - Disposer.register(project.service(), this) - updateIcon() - } - - fun show() { - println("Showing autocomplete spinner widget") - } - - override fun dispose() {} - - override fun ID(): String { - return ID - } - - override fun getTooltipText(): String { - val enabled = service().state.enableTabAutocomplete - return if (enabled) "Continue autocomplete enabled" else "Continue autocomplete disabled" - } - - override fun getClickConsumer(): Consumer? { - return null - } - - override fun getIcon(): Icon = if (isLoading) animatedIcon else - Icons.Continue - - fun setLoading(loading: Boolean) { - isLoading = loading - updateIcon() - } - - private fun updateIcon() { - iconLabel.icon = getIcon() - - - // Update the widget - val statusBar = WindowManager.getInstance().getStatusBar(project) - statusBar?.updateWidget(ID()) - } - - override fun install(statusBar: StatusBar) { - updateIcon() - } - - override fun getPresentation(): StatusBarWidget.WidgetPresentation { - return this - } - - companion object { - const val ID = "AutocompleteSpinnerWidget" - } -} - -class AutocompleteSpinnerWidgetFactory : StatusBarWidgetFactory { - fun create(project: Project): AutocompleteSpinnerWidget { - return AutocompleteSpinnerWidget(project) - } - - override fun getId(): String { - return AutocompleteSpinnerWidget.ID - } - - override fun getDisplayName(): String { - return "Continue Autocomplete" - } - - override fun isAvailable(p0: Project): Boolean { - return true - } - - override fun createWidget(project: Project): StatusBarWidget { - return create(project) - } - - override fun disposeWidget(p0: StatusBarWidget) { - Disposer.dispose(p0) - } - - override fun canBeEnabledOn(p0: StatusBar): Boolean = true -} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/CancelAutocompleteAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/CancelAutocompleteAction.kt deleted file mode 100644 index 8b5159d4d..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/CancelAutocompleteAction.kt +++ /dev/null @@ -1,35 +0,0 @@ -package com.github.continuedev.continueintellijextension.autocomplete - -import com.intellij.openapi.actionSystem.ActionUpdateThread -import com.intellij.openapi.actionSystem.AnAction -import com.intellij.openapi.actionSystem.AnActionEvent -import com.intellij.openapi.actionSystem.CommonDataKeys -import com.intellij.openapi.application.ApplicationManager -import com.intellij.openapi.components.service -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.project.Project - -class CancelAutocompleteAction : AnAction() { - override fun actionPerformed(e: AnActionEvent) { - if (isInvokedInEditor(e)) { - val editor = e.getRequiredData(CommonDataKeys.EDITOR) - ApplicationManager.getApplication().runWriteAction { - editor.project?.service()?.clearCompletions(editor) - } - } - } - - override fun update(e: AnActionEvent) { - e.presentation.isEnabledAndVisible = isInvokedInEditor(e) - } - - private fun isInvokedInEditor(e: AnActionEvent): Boolean { - val project: Project? = e.project - val editor: Editor? = e.getData(CommonDataKeys.EDITOR) - return project != null && editor != null && editor.contentComponent.hasFocus() - } - - override fun getActionUpdateThread(): ActionUpdateThread { - return ActionUpdateThread.BGT - } -} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/CompletionService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/CompletionService.kt new file mode 100644 index 000000000..ad06d95d5 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/CompletionService.kt @@ -0,0 +1,10 @@ +package com.github.continuedev.continueintellijextension.autocomplete + + +interface CompletionService { + + suspend fun getAutocomplete(uuid: String, url: String, line: Int, column: Int): String? + + fun acceptAutocomplete(uuid: String?) + +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCompletionService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCompletionService.kt new file mode 100644 index 000000000..453eadd01 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCompletionService.kt @@ -0,0 +1,54 @@ +package com.github.continuedev.continueintellijextension.autocomplete + +import com.github.continuedev.continueintellijextension.`continue`.ProfileInfoService +import com.github.continuedev.continueintellijextension.services.ContinuePluginService +import com.github.continuedev.continueintellijextension.utils.castNestedOrNull +import com.intellij.openapi.components.Service +import com.intellij.openapi.components.service +import com.intellij.openapi.project.Project +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.coroutines.withTimeoutOrNull +import kotlin.time.Duration.Companion.milliseconds + +@Service(Service.Level.PROJECT) +class ContinueCompletionService(private val project: Project) : CompletionService { + + override suspend fun getAutocomplete(uuid: String, url: String, line: Int, column: Int): String? { + val requestInput = getCompletionInput(uuid, url, line, column) + val modelTimeout = project.service().fetchModelTimeoutOrNull() + ?: return null + return withTimeoutOrNull(modelTimeout.milliseconds) { + suspendCancellableCoroutine { continuation -> + project.service().coreMessenger?.request( + "autocomplete/complete", + requestInput, + null + ) { + val content = it.castNestedOrNull>("content")?.firstOrNull() ?: "" + continuation.resumeWith(Result.success(content)) + } + } + } + } + + override fun acceptAutocomplete(uuid: String?) { + project.service().coreMessenger?.request( + "autocomplete/accept", + mapOf("completionId" to uuid), + null + ) {} + } + + private fun getCompletionInput(uuid: String, filepath: String, line: Int, character: Int): Map = mapOf( + "completionId" to uuid, + "filepath" to filepath, + "pos" to mapOf( + "line" to line, + "character" to character + ), + "clipboardText" to "", + "recentlyEditedRanges" to emptyList(), + "recentlyVisitedRanges" to emptyList(), + ) + +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlayRenderer.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlayRenderer.kt deleted file mode 100644 index bcf37fa20..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlayRenderer.kt +++ /dev/null @@ -1,58 +0,0 @@ -package com.github.continuedev.continueintellijextension.autocomplete - -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.editor.EditorCustomElementRenderer -import com.intellij.openapi.editor.Inlay -import com.intellij.openapi.editor.colors.EditorFontType -import com.intellij.openapi.editor.impl.EditorImpl -import com.intellij.openapi.editor.markup.TextAttributes -import com.intellij.ui.JBColor -import com.intellij.util.ui.UIUtil -import java.awt.Font -import java.awt.Graphics -import java.awt.Rectangle - -/** - * The `ContinueInlayRenderer` class is responsible for rendering custom inlay elements within an editor. - * It implements the [EditorCustomElementRenderer] interface to provide custom rendering logic for inlays. - * - * This renderer is designed to display a list of text lines (`lines`) within the editor, calculating the - * necessary width and height based on the content and rendering each line with appropriate font and color. - * - * @author lk - */ -class ContinueInlayRenderer(val lines: List) : EditorCustomElementRenderer { - override fun calcWidthInPixels(inlay: Inlay<*>): Int { - var maxLen = 0; - for (line in lines) { - val len = (inlay.editor as EditorImpl).getFontMetrics(Font.PLAIN).stringWidth(line) - if (len > maxLen) { - maxLen = len - } - } - return maxLen - } - - override fun calcHeightInPixels(inlay: Inlay<*>): Int { - return (inlay.editor as EditorImpl).lineHeight * lines.size - } - - private fun font(editor: Editor): Font { - val editorFont = editor.colorsScheme.getFont(EditorFontType.PLAIN) - return UIUtil.getFontWithFallbackIfNeeded(editorFont, lines.joinToString("\n")) - .deriveFont(editor.colorsScheme.editorFontSize) - } - - override fun paint(inlay: Inlay<*>, g: Graphics, targetRegion: Rectangle, textAttributes: TextAttributes) { - val editor = inlay.editor - g.color = JBColor.GRAY - g.font = font(editor) - var additionalYOffset = 0 - val ascent = editor.ascent - val lineHeight = editor.lineHeight - for (line in lines) { - g.drawString(line, targetRegion.x, targetRegion.y + ascent + additionalYOffset) - additionalYOffset += lineHeight - } - } -} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt new file mode 100644 index 000000000..bbcbc7992 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt @@ -0,0 +1,66 @@ +package com.github.continuedev.continueintellijextension.autocomplete + +import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings +import com.github.continuedev.continueintellijextension.utils.uuid +import com.intellij.codeInsight.inline.completion.DefaultInlineCompletionInsertHandler +import com.intellij.codeInsight.inline.completion.InlineCompletionEvent +import com.intellij.codeInsight.inline.completion.InlineCompletionInsertEnvironment +import com.intellij.codeInsight.inline.completion.InlineCompletionInsertHandler +import com.intellij.codeInsight.inline.completion.InlineCompletionProvider +import com.intellij.codeInsight.inline.completion.InlineCompletionProviderID +import com.intellij.codeInsight.inline.completion.InlineCompletionRequest +import com.intellij.codeInsight.inline.completion.elements.InlineCompletionElement +import com.intellij.codeInsight.inline.completion.elements.InlineCompletionGrayTextElement +import com.intellij.codeInsight.inline.completion.suggestion.InlineCompletionSuggestion +import com.intellij.codeInsight.inline.completion.suggestion.InlineCompletionVariant +import com.intellij.openapi.components.service +import com.intellij.openapi.project.Project +import kotlinx.coroutines.flow.flow + +class ContinueInlineCompletionProvider : InlineCompletionProvider { + override val id get() = InlineCompletionProviderID("Continue") + override val insertHandler: InlineCompletionInsertHandler = NotifyingHandler() + private var lastUuid: String? = null + private var lastProject: Project? = null + + override fun isEnabled(event: InlineCompletionEvent): Boolean = + ContinueExtensionSettings.instance.continueState.enableTabAutocomplete + + override suspend fun getSuggestion(request: InlineCompletionRequest): InlineCompletionSuggestion { + val editor = request.editor + val project = editor.project + ?: return InlineCompletionSuggestion.Empty + lastUuid = uuid() + lastProject = project + val variant = project.service().getAutocomplete( + lastUuid!!, + editor.virtualFile.url, + editor.caretModel.primaryCaret.logicalPosition.line, + editor.caretModel.primaryCaret.logicalPosition.column + ) + if (variant == null) + return InlineCompletionSuggestion.Empty + return object : InlineCompletionSuggestion { + override suspend fun getVariants(): List { + val completion = InlineCompletionVariant.build( + request.file.virtualFile, + flow { emit(InlineCompletionGrayTextElement(variant)) } + ) + return listOf(completion) + } + } + } + + // todo: we're hacking here with this handler + lastUuid and lastProject variables + // todo: because we simply want to get notified which completion is accepted (this sounds like a common problem!) + // todo: search for simpler solution / ask jetbrains why it's so complicated + private inner class NotifyingHandler() : InlineCompletionInsertHandler { + override fun afterInsertion( + environment: InlineCompletionInsertEnvironment, + elements: List + ) { + DefaultInlineCompletionInsertHandler.INSTANCE.afterInsertion(environment, elements) + lastProject?.service()?.acceptAutocomplete(lastUuid) + } + } +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/DisableTabAutocompleteAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/DisableTabAutocompleteAction.kt deleted file mode 100644 index d7e1f3b13..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/DisableTabAutocompleteAction.kt +++ /dev/null @@ -1,12 +0,0 @@ -package com.github.continuedev.continueintellijextension.autocomplete - -import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings -import com.intellij.openapi.actionSystem.AnAction -import com.intellij.openapi.actionSystem.AnActionEvent -import com.intellij.openapi.components.service -class DisableTabAutocompleteAction : AnAction() { - override fun actionPerformed(e: AnActionEvent) { - val continueSettingsService = service() - continueSettingsService.continueState.enableTabAutocomplete = true - } -} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/EnableTabAutocompleteAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/EnableTabAutocompleteAction.kt deleted file mode 100644 index b14aa2190..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/EnableTabAutocompleteAction.kt +++ /dev/null @@ -1,12 +0,0 @@ -package com.github.continuedev.continueintellijextension.autocomplete - -import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings -import com.intellij.openapi.actionSystem.AnAction -import com.intellij.openapi.actionSystem.AnActionEvent -import com.intellij.openapi.components.service -class EnableTabAutocompleteAction : AnAction() { - override fun actionPerformed(e: AnActionEvent) { - val continueSettingsService = service() - continueSettingsService.continueState.enableTabAutocomplete = true - } -} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/PartialAcceptAutocompleteAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/PartialAcceptAutocompleteAction.kt deleted file mode 100644 index 0af47bbc7..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/PartialAcceptAutocompleteAction.kt +++ /dev/null @@ -1,25 +0,0 @@ -package com.github.continuedev.continueintellijextension.autocomplete - -import com.intellij.openapi.actionSystem.DataContext -import com.intellij.openapi.application.ApplicationManager -import com.intellij.openapi.components.service -import com.intellij.openapi.editor.Caret -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.editor.actionSystem.EditorAction -import com.intellij.openapi.editor.actionSystem.EditorActionHandler - -class PartialAcceptAutocompleteAction : EditorAction(object : EditorActionHandler() { - override fun doExecute(editor: Editor, caret: Caret?, dataContext: DataContext?) { - ApplicationManager.getApplication().runWriteAction { - editor.project?.service()?.partialAccept() - } - } - - override fun isEnabledForCaret(editor: Editor, caret: Caret, dataContext: DataContext?): Boolean { - val autocompleteService = editor.project?.service(); - val enabled = editor == autocompleteService?.pendingCompletion?.editor - && caret.offset == autocompleteService.pendingCompletion?.offset - && autocompleteService.pendingCompletion?.text != null - return enabled - } -}) {} \ No newline at end of file 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 856215be2..158c61a50 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 @@ -9,13 +9,9 @@ import com.github.continuedev.continueintellijextension.editor.DiffStreamService import com.github.continuedev.continueintellijextension.editor.EditorUtils import com.github.continuedev.continueintellijextension.protocol.ApplyToFileParams import com.github.continuedev.continueintellijextension.services.ContinuePluginService -import com.github.continuedev.continueintellijextension.utils.castNestedOrNull import com.intellij.openapi.components.service import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project -import kotlinx.coroutines.suspendCancellableCoroutine -import kotlin.coroutines.resume -import kotlin.coroutines.resumeWithException /** * Handles applying text to a file with streaming diff preview @@ -122,33 +118,9 @@ class ApplyToFileHandler( } private suspend fun fetchApplyLLMConfig(): Any? { - return try { - suspendCancellableCoroutine { continuation -> - continuePluginService.coreMessenger?.request( - "config/getSerializedProfileInfo", null, null - ) { response -> - try { - val selectedModels = response.castNestedOrNull>( - "content", "result", "config", "selectedModelByRole" - ) - - // If "apply" role model is not found, try "chat" role - val applyCodeBlockModel = selectedModels?.get("apply") ?: selectedModels?.get("chat") - - if (applyCodeBlockModel != null) { - continuation.resume(applyCodeBlockModel) - } else { - // If neither "apply" nor "chat" models are available, return with exception - continuation.resumeWithException(IllegalStateException("No 'apply' or 'chat' model found in configuration.")) - } - } catch (e: Exception) { - continuation.resumeWithException(e) - } - } - } - } catch (_: Exception) { - null - } + val selectedModelByRole = project.service().fetchSelectedModelByRoleOrNull() + return selectedModelByRole?.get("apply") + ?: selectedModelByRole?.get("chat") } private fun setupAndStreamDiffs(editorUtils: EditorUtils, llm: Any) { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ProfileInfoService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ProfileInfoService.kt new file mode 100644 index 000000000..676563921 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ProfileInfoService.kt @@ -0,0 +1,63 @@ +package com.github.continuedev.continueintellijextension.`continue` + +import com.github.continuedev.continueintellijextension.services.ContinuePluginService +import com.github.continuedev.continueintellijextension.utils.castNestedOrNull +import com.intellij.openapi.components.Service +import com.intellij.openapi.components.service +import com.intellij.openapi.diagnostic.Logger +import com.intellij.openapi.project.Project +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.coroutines.withTimeoutOrNull +import kotlin.time.Duration.Companion.seconds + +@Service(Service.Level.PROJECT) +class ProfileInfoService(private val project: Project) { + private val log = Logger.getInstance(ProfileInfoService::class.java) + private var fallbackInfo: Any? = null // todo: add type + deserialize + + suspend fun fetchModelTimeoutOrNull() = + fetchOrNull().castNestedOrNull( + "content", + "result", + "config", + "tabAutocompleteOptions", + "modelTimeout" + ) + + suspend fun fetchSelectedModelByRoleOrNull(): Map? = + fetchOrNull().castNestedOrNull>( + "content", + "result", + "config", + "selectedModelByRole" + ) + + suspend fun fetchModelsByRoleOrNull() = + fetchOrNull().castNestedOrNull>( + "content", + "result", + "config", + "modelsByRole" + ) + + private suspend fun fetchOrNull(): Any? { + val actual = withTimeoutOrNull(1.seconds) { + suspendCancellableCoroutine { continuation -> + project.service().coreMessenger?.request( + "config/getSerializedProfileInfo", + null, + null + ) { response -> + continuation.resumeWith(Result.success(response)) + } + } + } + if (actual == null) { + log.warn("Fall back to previous settings due to timeout") + return fallbackInfo + } + fallbackInfo = actual + return actual + } + +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt index f5e8b81ee..e0dbcb0c2 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt @@ -2,8 +2,8 @@ package com.github.continuedev.continueintellijextension.editor import com.github.continuedev.continueintellijextension.Icons import com.github.continuedev.continueintellijextension.`continue`.GetTheme +import com.github.continuedev.continueintellijextension.`continue`.ProfileInfoService import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings -import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.github.continuedev.continueintellijextension.utils.castNestedOrNull import com.github.continuedev.continueintellijextension.utils.getMetaKeyLabel import com.github.continuedev.continueintellijextension.utils.getShiftKeyLabel @@ -14,12 +14,13 @@ import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.colors.EditorFontType import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.project.Project -import com.intellij.openapi.util.IconLoader import com.intellij.openapi.util.Ref import com.intellij.openapi.util.TextRange import com.intellij.ui.JBColor import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeoutOrNull import java.awt.* import java.awt.event.* import java.awt.geom.AffineTransform @@ -34,6 +35,7 @@ import kotlin.math.max import net.miginfocom.swing.MigLayout import org.jdesktop.swingx.JXPanel import org.jdesktop.swingx.JXTextArea +import kotlin.time.Duration.Companion.milliseconds const val MAIN_FONT_SIZE = 13 const val DOWN_ARROW = " ▾" @@ -43,37 +45,21 @@ const val MAX_MODEL_WAIT_TIME = 1500 * Fetches and combines available model titles from both "edit" and "chat" roles. * Edit models are prioritized and appear first in the returned list. * Handles duplicate models by only including them once (prioritizing edit role). - * - * @param continuePluginService The service used to fetch config information - * @return List of model titles with edit models first, duplicates removed - * @throws No exceptions, but will return empty list if request fails or times out after 1.5 seconds */ -fun getModelTitles(continuePluginService: ContinuePluginService): List { - val modelTitles = mutableListOf() - - continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response -> - val modelsByRole = - response.castNestedOrNull>("content", "result", "config", "modelsByRole") ?: return@request - - // Get edit models first - val editModels = modelsByRole.castNestedOrNull>("edit") - ?.mapNotNull { it.castNestedOrNull("title") } ?: emptyList() - - // Then get chat models - val chatModels = modelsByRole.castNestedOrNull>("chat") - ?.mapNotNull { it.castNestedOrNull("title") } ?: emptyList() - - // Add edit models first, then chat models (avoiding duplicates) - modelTitles.addAll(editModels) - modelTitles.addAll(chatModels.filter { it !in editModels }) +fun getModelTitles(project: Project): List { + // fixme: blocking code on EDT (however this is not a regression compared to the latest changes) + return runBlocking { + withTimeoutOrNull(MAX_MODEL_WAIT_TIME.milliseconds) { + val modelsByRole = project.service().fetchModelsByRoleOrNull() + val editModels = modelsByRole.castNestedOrNull>("edit") + ?.mapNotNull { it.castNestedOrNull("title") } + ?: emptyList() + val chatModels = modelsByRole.castNestedOrNull>("chat") + ?.mapNotNull { it.castNestedOrNull("title") } + ?: emptyList() + (editModels + chatModels).distinct() + } ?: emptyList() } - - val startTime = System.currentTimeMillis() - while (modelTitles.isEmpty() && System.currentTimeMillis() - startTime < MAX_MODEL_WAIT_TIME) { - Thread.sleep(20) - } - - return modelTitles } fun makeTextArea(): JTextArea { @@ -161,8 +147,7 @@ fun openInlineEdit(project: Project?, editor: Editor) { val manager = EditorComponentInlaysManager.from(editor, true) - val continuePluginService = project.service() - val modelTitles = getModelTitles(continuePluginService) + val modelTitles = getModelTitles(project) val highlightedRIF = editorUtils.getHighlightedRIF() ?: return val (startLineNumber, endLineNumber) = highlightedRIF.lines diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/AcceptNextEditAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/AcceptNextEditAction.kt deleted file mode 100644 index 88d43bdb8..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/AcceptNextEditAction.kt +++ /dev/null @@ -1,25 +0,0 @@ -package com.github.continuedev.continueintellijextension.nextEdit - -import com.intellij.openapi.actionSystem.DataContext -import com.intellij.openapi.application.ApplicationManager -import com.intellij.openapi.components.service -import com.intellij.openapi.editor.Caret -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.editor.actionSystem.EditorAction -import com.intellij.openapi.editor.actionSystem.EditorActionHandler - -class AcceptNextEditAction : EditorAction(object : EditorActionHandler() { - override fun doExecute(editor: Editor, caret: Caret?, dataContext: DataContext?) { - ApplicationManager.getApplication().runWriteAction { - editor.project?.service()?.accept() - } - } - - override fun isEnabledForCaret(editor: Editor, caret: Caret, dataContext: DataContext?): Boolean { - val nextEditService = editor.project?.service(); - val enabled = editor == nextEditService?.pendingCompletion?.editor -// && caret.offset == autocompleteService.pendingCompletion?.offset - && nextEditService.pendingCompletion?.text != null - return enabled - } -}) \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditService.kt deleted file mode 100644 index f9279b9b9..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditService.kt +++ /dev/null @@ -1,321 +0,0 @@ -package com.github.continuedev.continueintellijextension.nextEdit - -import com.github.continuedev.continueintellijextension.FimResult -import com.github.continuedev.continueintellijextension.autocomplete.AutocompleteLookupListener -import com.github.continuedev.continueintellijextension.autocomplete.AutocompleteSpinnerWidget -import com.github.continuedev.continueintellijextension.autocomplete.ContinueInlayRenderer -import com.github.continuedev.continueintellijextension.autocomplete.PendingCompletion -import com.github.continuedev.continueintellijextension.autocomplete.addInlayElement -import com.github.continuedev.continueintellijextension.autocomplete.isInjectedText -import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings -import com.github.continuedev.continueintellijextension.services.ContinuePluginService -import com.github.continuedev.continueintellijextension.utils.checkFim -import com.github.continuedev.continueintellijextension.utils.toUriOrNull -import com.github.continuedev.continueintellijextension.utils.uuid -import com.intellij.openapi.application.ApplicationManager -import com.intellij.openapi.application.WriteAction -import com.intellij.openapi.application.invokeLater -import com.intellij.openapi.application.runReadAction -import com.intellij.openapi.components.Service -import com.intellij.openapi.components.service -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.editor.InlayProperties -import com.intellij.openapi.fileEditor.FileDocumentManager -import com.intellij.openapi.project.Project -import com.intellij.openapi.util.TextRange -import com.intellij.openapi.wm.WindowManager -import com.intellij.psi.PsiDocumentManager - -@Service(Service.Level.PROJECT) -class NextEditService(private val project: Project) { - var pendingCompletion: PendingCompletion? = null - private val autocompleteLookupListener = project.service() - private val widget: AutocompleteSpinnerWidget? by lazy { - WindowManager.getInstance().getStatusBar(project) - ?.getWidget(AutocompleteSpinnerWidget.ID) as? AutocompleteSpinnerWidget - } - - // To avoid triggering another completion on partial acceptance, - // we need to keep track of whether the last change was a partial accept. - var lastChangeWasPartialAccept = false - - fun triggerNextEdit(editor: Editor) { - val settings = service() - if (!settings.continueState.enableTabAutocomplete) { - return - } - - if (pendingCompletion != null) { - clearCompletions(pendingCompletion!!.editor) - } - - // Set pending completion. - val completionId = uuid() - val offset = editor.caretModel.primaryCaret.offset - pendingCompletion = PendingCompletion(editor, offset, completionId, null) - - // Request a completion from the core. - val virtualFile = FileDocumentManager.getInstance().getFile(editor.document) - - val uri = virtualFile?.toUriOrNull() ?: return - - widget?.setLoading(true) - - val line = editor.caretModel.primaryCaret.logicalPosition.line - val column = editor.caretModel.primaryCaret.logicalPosition.column - val input = mapOf( - "completionId" to completionId, - "filepath" to uri, - "pos" to mapOf( - "line" to line, - "character" to column - ), - "clipboardText" to "", - "recentlyEditedRanges" to emptyList(), - "recentlyVisitedRanges" to emptyList(), - ) - - // TODO: Add message support for nextEdit/predict. - project.service().coreMessenger?.request( - "nextEdit/predict", - input, - null, - ({ response -> - if (pendingCompletion == null || pendingCompletion?.completionId == completionId) { - widget?.setLoading(false) - } - - val responseObject = response as Map<*, *> - val predictions = responseObject["content"] as List<*> - - if (predictions.isNotEmpty()) { - val prediction = predictions[0].toString() - val oldEditRange = predictions[1].toString() - // Check if the prediction is purely additive. - val result = checkFim( - oldEditRange, - prediction, - Pair(line, column) - ) - when (result) { - is FimResult.FimEdit -> { - // If so, render ghost text. - val finalTextToInsert = deduplicateCompletion(editor, offset, result.fimText) - if (shouldRenderCompletion(finalTextToInsert, offset, line, editor)) { - renderCompletion(editor, offset, finalTextToInsert) - pendingCompletion = PendingCompletion(editor, offset, completionId, finalTextToInsert) - } - } - is FimResult.NotFimEdit -> { - // Else, render a window. - if (shouldRenderCompletion(prediction, offset, line, editor)) { - val nextEditWindowService = NextEditWindowService.getInstance(project) - nextEditWindowService.showCodePreview(prediction, editor, completionId) - } - } - } - } - }) - ) - } - - private fun shouldRenderCompletion(completion: String, offset: Int, line: Int, editor: Editor): Boolean { - if (completion.isEmpty() || runReadAction { offset != editor.caretModel.offset }) { - return false - } - - if (completion.lines().size == 1) { - return true - } - - val endOffset = editor.document.getLineEndOffset(line) - - // Do not render if completion is multi-line and caret is in middle of line - return offset <= endOffset && editor.document.getText(TextRange(offset, endOffset)).isBlank() - } - - private fun deduplicateCompletion(editor: Editor, offset: Int, completion: String): String { - // Check if completion matches the first 10 characters after the cursor - return ApplicationManager.getApplication().runReadAction { - val document = editor.document - val caretOffset = editor.caretModel.offset - - // Don't care about it if it's at the end of the document - if (caretOffset == document.textLength) return@runReadAction completion - - val N = 10 - var textAfterCursor = if (caretOffset + N <= document.textLength) { - document.getText(TextRange(caretOffset, caretOffset + N)) - } else { - document.getText(TextRange(caretOffset, document.textLength)) - } - - // Avoid truncating the completion text when the text after the cursor is blank - if (textAfterCursor.isBlank()) return@runReadAction completion - - // Determine the index of a newline character within the text following the cursor. - val newlineIndex = textAfterCursor.indexOf("\r\n").takeIf { it >= 0 } ?: textAfterCursor.indexOf('\n') - // If a newline character is found and the current line is not empty, truncate the text at that point. - if (newlineIndex > 0) { - textAfterCursor = textAfterCursor.substring(0, newlineIndex) - } - - val indexOfTextAfterCursorInCompletion = completion.indexOf(textAfterCursor) - if (indexOfTextAfterCursorInCompletion > 0) { - return@runReadAction completion.slice(0..indexOfTextAfterCursorInCompletion - 1) - } else if (indexOfTextAfterCursorInCompletion == 0) { - return@runReadAction "" - } - - return@runReadAction completion - } - } - - private fun renderCompletion(editor: Editor, offset: Int, completion: String) { - if (completion.isEmpty()) { - return - } - if (isInjectedFile(editor)) return - // Skip rendering completions if the code completion dropdown is already visible and the IDE completion side-by-side setting is disabled - if (shouldSkipRender()) { - return - } - - ApplicationManager.getApplication().invokeLater { - WriteAction.run { - // Clear existing completions - hideCompletions(editor) - - val properties = InlayProperties() - properties.relatesToPrecedingText(true) - properties.disableSoftWrapping(true) - - val lines = completion.lines() - pendingCompletion = pendingCompletion?.copy(text = lines.joinToString("\n")) - editor.addInlayElement(lines, offset, properties) - -// val attributes = TextAttributes().apply { -// backgroundColor = JBColor.GREEN -// } -// val key = TextAttributesKey.createTextAttributesKey("CONTINUE_AUTOCOMPLETE") -// key.let { editor.colorsScheme.setAttributes(it, attributes) } -// editor.markupModel.addLineHighlighter(key, editor.caretModel.logicalPosition.line, HighlighterLayer.LAST) - } - } - } - - fun accept() { - val completion = pendingCompletion ?: return - val text = completion.text ?: return - val editor = completion.editor - val offset = completion.offset - editor.document.insertString(offset, text) - - editor.caretModel.moveToOffset(offset + text.length) - - project.service().coreMessenger?.request( - "nextEdit/accept", - hashMapOf("completionId" to completion.completionId), - null, - ({}) - ) - invokeLater { - clearCompletions(editor, completion) - } - } - - private fun shouldSkipRender(): Boolean { - val settings = service() - return !settings.continueState.showIDECompletionSideBySide && !autocompleteLookupListener.isLookupEmpty() - } - - private fun splitKeepingDelimiters(input: String, delimiterPattern: String = "\\s+"): List { - val initialSplit = input.split("(?<=$delimiterPattern)|(?=$delimiterPattern)".toRegex()) - .filter { it.isNotEmpty() } - - val result = mutableListOf() - var currentDelimiter = "" - - for (part in initialSplit) { - if (part.matches(delimiterPattern.toRegex())) { - currentDelimiter += part - } else { - if (currentDelimiter.isNotEmpty()) { - result.add(currentDelimiter) - currentDelimiter = "" - } - result.add(part) - } - } - - if (currentDelimiter.isNotEmpty()) { - result.add(currentDelimiter) - - } - - return result - } - - fun partialAccept() { - val completion = pendingCompletion ?: return - val text = completion.text ?: return - val editor = completion.editor - val offset = completion.offset - - lastChangeWasPartialAccept = true - - // Split the text into words, keeping delimiters - val words = splitKeepingDelimiters(text) - println(words) - val word = words[0] - editor.document.insertString(offset, word) - editor.caretModel.moveToOffset(offset + word.length) - - // Remove the completion and re-display it - hideCompletions(editor) - completion.text = text.substring(word.length) - completion.offset += word.length - renderCompletion(editor, completion.offset, completion.text!!) - } - - private fun rejectCompletion(completion: PendingCompletion) { - // Send rejection message to core - widget?.setLoading(false) - project.service().coreMessenger?.request("nextEdit/reject", null, null, ({})) - } - - fun clearCompletions(editor: Editor, completion: PendingCompletion? = pendingCompletion) { - if (isInjectedFile(editor)) return - - if (completion != null) { -// cancelCompletion(completion) - if (completion.completionId == pendingCompletion?.completionId) pendingCompletion = null - } - disposeInlayRenderer(editor) - } - - private fun isInjectedFile(editor: Editor): Boolean { - return runReadAction { - PsiDocumentManager.getInstance(project).getPsiFile(editor.document)?.isInjectedText() ?: false - } - } - - fun hideCompletions(editor: Editor) { - if (isInjectedFile(editor)) return - - disposeInlayRenderer(editor) - } - - private fun disposeInlayRenderer(editor: Editor) { - editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength).forEach { - if (it.renderer is ContinueInlayRenderer) { - it.dispose() - } - } - editor.inlayModel.getBlockElementsInRange(0, editor.document.textLength).forEach { - if (it.renderer is ContinueInlayRenderer) { - it.dispose() - } - } - } -} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowService.kt deleted file mode 100644 index 846db780e..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowService.kt +++ /dev/null @@ -1,304 +0,0 @@ -package com.github.continuedev.continueintellijextension.nextEdit - -import com.github.continuedev.continueintellijextension.services.ContinuePluginService -import com.intellij.openapi.actionSystem.AnAction -import com.intellij.openapi.actionSystem.AnActionEvent -import com.intellij.openapi.actionSystem.CustomShortcutSet -import com.intellij.openapi.command.WriteCommandAction -import com.intellij.openapi.components.Service -import com.intellij.openapi.components.service -import com.intellij.openapi.editor.Document -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.editor.EditorSettings -import com.intellij.openapi.editor.colors.EditorColorsManager -import com.intellij.openapi.editor.ex.EditorEx -import com.intellij.openapi.editor.ex.EditorSettingsExternalizable -import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory -import com.intellij.openapi.fileEditor.FileDocumentManager -import com.intellij.openapi.fileTypes.FileTypeManager -import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory -import com.intellij.openapi.project.Project -import com.intellij.openapi.ui.popup.JBPopupFactory -import com.intellij.openapi.ui.popup.JBPopupListener -import com.intellij.openapi.ui.popup.LightweightWindowEvent -import com.intellij.psi.PsiDocumentManager -import com.intellij.ui.EditorTextField -import com.intellij.ui.components.JBScrollPane -import java.awt.BorderLayout -import java.awt.Color -import java.awt.Dimension -import java.awt.FlowLayout -import java.awt.Point -import java.awt.event.ActionEvent -import java.awt.event.KeyAdapter -import java.awt.event.KeyEvent -import javax.swing.AbstractAction -import javax.swing.JButton -import javax.swing.JComponent -import javax.swing.JPanel -import javax.swing.JScrollPane -import javax.swing.KeyStroke - -@Service(Service.Level.PROJECT) -class NextEditWindowService(private val project: Project) { - /** - * Creates a Swing component that displays syntax-highlighted code. - * - * @param code The code to display - * @param language The language/file extension of the code (e.g. "java", "kotlin", "py") - * @param isEditable Whether the code should be editable (default: false) - * @return A JComponent that can be added to the UI - */ - fun createCodeViewer(code: String, language: String, document: Document, isEditable: Boolean = false): JComponent { - // Get file type based on extension. - // NOTE: This is actually IDE and tier-dependent. For example, TypeScript won't work on IntelliJ CE. - val fileType = FileTypeManager.getInstance().getFileTypeByExtension(language) - - // Create an EditorTextField with the specified code and file type. - val editorTextField = object : EditorTextField(code, project, fileType) { - override fun createEditor(): EditorEx { - val editor = super.createEditor() - - // Configure editor settings. - val settings: EditorSettings = editor.settings - settings.isLineNumbersShown = true - settings.isLineMarkerAreaShown = true - settings.isIndentGuidesShown = true - settings.isVirtualSpace = false - settings.isRightMarginShown = false - settings.additionalLinesCount = 0 - settings.isShowingSpecialChars = false - settings.isCaretRowShown = true - - // Set read-only if not editable. - editor.isViewer = !isEditable - - // Syntax highlighter. - // Get current editor color scheme. - val currentScheme = EditorColorsManager.getInstance().globalScheme - - // Apply syntax highlighting with current theme. - val virtualFile = FileDocumentManager.getInstance().getFile(document) - var syntaxHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(fileType, project, virtualFile) - - // If we couldn't get a syntax highlighter from the file, try to get one just from the file type. - if (syntaxHighlighter == null) { - syntaxHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(fileType, project, null) - } - - // If we have a highlighter, apply it. - if (syntaxHighlighter != null) { - editor.highlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter( - syntaxHighlighter, - currentScheme - ) - } else { - // Fallback to plain text highlighting if all attempts fail. - val plainTextFileType = FileTypeManager.getInstance().getFileTypeByExtension("txt") - editor.highlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter( - project, - plainTextFileType - ) - } - - // Apply the theme's background color. - editor.backgroundColor = currentScheme.defaultBackground - - return editor - } - - // Override to ensure multi-line support. - override fun getPreferredSize(): Dimension { - val lineCount = code.lines().size - // Adjust height based on line count (with some minimum). - val preferredSize = super.getPreferredSize() - val lineHeight = preferredSize.height / (if (lineCount > 0) lineCount else 1) - val newHeight = lineHeight * (if (lineCount > 0) lineCount else 1) + 10 // Add padding - return Dimension(preferredSize.width, newHeight) - } - } - - // Enable multi-line mode. - editorTextField.setOneLineMode(false) - - // Wrap in a scroll pane for larger code blocks. - val panel = JPanel(BorderLayout()) - panel.add(JBScrollPane(editorTextField), BorderLayout.CENTER) - - return panel - } - - /** - * Shows a popup dialog with the code preview. - */ - fun showCodePreview(code: String, parentEditor: Editor, completionId: String) { - // Use invokeAndWait or invokeLater to ensure we're on the EDT. - com.intellij.openapi.application.ApplicationManager.getApplication().invokeLater { - val codeViewer = createCodeViewer(code, getFileLanguage(parentEditor.document), parentEditor.document) - - // Create a button panel. - val buttonPanel = JPanel(FlowLayout(FlowLayout.RIGHT)) - val acceptButton = JButton("Accept (Tab)") - val dismissButton = JButton("Dismiss (Esc)") - buttonPanel.add(acceptButton) - buttonPanel.add(dismissButton) - - // Create a panel to hold the code viewer and buttons. - val panel = JPanel(BorderLayout()) - panel.add(codeViewer, BorderLayout.CENTER) - panel.add(buttonPanel, BorderLayout.SOUTH) - - - // Create the popup. - val popup = JBPopupFactory.getInstance() - .createComponentPopupBuilder(panel, codeViewer) - .setMovable(true) - .setResizable(true) - .setRequestFocus(true) - .setCancelOnClickOutside(true) - .setCancelOnOtherWindowOpen(true) - .setFocusable(true) - .addListener(object : JBPopupListener { - override fun onClosed(event: LightweightWindowEvent) { - if (!event.isOk) { - // This only triggers when dismissed, not when accepted. - println("Dismissing code preview popup") - project.service().coreMessenger?.request( - "nextEdit/reject", - hashMapOf("completionId" to completionId), - null, ({}) - ) - } - } - }) - .createPopup() - - // Helper function to accept the code and apply it to the editor. - fun acceptCode() { - val document = parentEditor.document - val caretModel = parentEditor.caretModel - val caretOffset = caretModel.offset - val caretPosition = document.getLineNumber(caretOffset) - - // Calculate start and end lines. - val totalLines = document.lineCount - val startLine = maxOf(0, caretPosition - 5) - val endLine = minOf(totalLines - 1, caretPosition + 5) - - // Get start and end offsets. - val startOffset = document.getLineStartOffset(startLine) - val endOffset = document.getLineEndOffset(endLine) - - // Write command to replace the text. - WriteCommandAction.runWriteCommandAction(project) { - document.replaceString(startOffset, endOffset, code) - } - - project.service().coreMessenger?.request( - "nextEdit/accept", - hashMapOf("completionId" to completionId), - null, ({}) - ) - } - - // Use ActionManager to handle Tab key globally during popup display. - val acceptAction = object : AnAction() { - override fun actionPerformed(e: AnActionEvent) { - acceptCode() - popup.closeOk(null) - } - } - - // Create a custom shortcut set for the Tab key. - val customShortcutSet = CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0)) - - - // Register action with shortcut. - acceptAction.registerCustomShortcutSet(customShortcutSet, panel) - - // Add button actions. - acceptButton.addActionListener { - acceptCode() - popup.closeOk(null) - } - - dismissButton.addActionListener { - popup.cancel() - } - - // Get the exact position of the cursor. - val visualPosition = parentEditor.caretModel.visualPosition - val cursorPoint = parentEditor.visualPositionToXY(visualPosition) - - // Convert to screen coordinates. - val editorComponent = parentEditor.component - val locationOnScreen = editorComponent.locationOnScreen - val screenPoint = Point( - locationOnScreen.x + cursorPoint.x, - locationOnScreen.y + cursorPoint.y - ) - - // Show the popup at the cursor position. - popup.showInScreenCoordinates(editorComponent, screenPoint) - - // Ensure proper focus for keyboard shortcuts. - codeViewer.requestFocusInWindow() - } - } - - // Move editorConfig to a proper instance property that gets actual editor settings. - private val editorConfig: EditorConfig by lazy { - val settings = EditorSettingsExternalizable.getInstance() - val editorFontSize = EditorColorsManager.getInstance().globalScheme.editorFontSize - val editorFontFamily = EditorColorsManager.getInstance().globalScheme.editorFontName - - EditorConfig( - fontSize = editorFontSize.toDouble(), - fontFamily = editorFontFamily - ) - } - - // Data class to hold editor configuration. - private data class EditorConfig( - val fontSize: Double = 14.0, - val fontFamily: String = "JetBrains Mono" - ) - - /** - * Convenience method to map common programming languages to their file extensions. - */ - fun mapLanguageToExtension(language: String): String { - return when (language.lowercase()) { - "javascript" -> "js" - "typescript" -> "ts" - "python" -> "py" - "java" -> "java" - "kotlin" -> "kt" - "c++" -> "cpp" - "c#" -> "cs" - "go" -> "go" - "rust" -> "rs" - "ruby" -> "rb" - "php" -> "php" - "swift" -> "swift" - "shell", "bash" -> "sh" - "html" -> "html" - "css" -> "css" - "json" -> "json" - "xml" -> "xml" - "yaml", "yml" -> "yaml" - "markdown", "md" -> "md" - // Add more mappings as needed - else -> language - } - } - - private fun getFileLanguage(document: Document): String { - val virtualFile = FileDocumentManager.getInstance().getFile(document) - return virtualFile?.extension?.lowercase() ?: "text" - } - - companion object { - fun getInstance(project: Project): NextEditWindowService = project.service() - } -} \ No newline at end of file diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index 0191d8f60..bcb524f1f 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -15,8 +15,6 @@ - - - + + + + - - - - - - - - - - - - - - - - - - - diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinueInlineCompletionProviderTest.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinueInlineCompletionProviderTest.kt new file mode 100644 index 000000000..331b9269f --- /dev/null +++ b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinueInlineCompletionProviderTest.kt @@ -0,0 +1,116 @@ +package com.github.continuedev.continueintellijextension.unit + +import com.github.continuedev.continueintellijextension.autocomplete.ContinueInlineCompletionProvider +import com.github.continuedev.continueintellijextension.autocomplete.CompletionService +import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings +import com.intellij.codeInsight.inline.completion.InlineCompletionHandler +import com.intellij.codeInsight.inline.completion.testInlineCompletion +import com.intellij.openapi.fileTypes.PlainTextFileType +import com.intellij.testFramework.fixtures.BasePlatformTestCase +import com.intellij.testFramework.replaceService +import org.junit.jupiter.api.Assertions.assertDoesNotThrow +import java.util.UUID + +@Suppress("UnstableApiUsage") +class ContinueInlineCompletionProviderTest : BasePlatformTestCase() { + + override fun runInDispatchThread() = + false + + override fun setUp() { + super.setUp() + InlineCompletionHandler.registerTestHandler(ContinueInlineCompletionProvider(), testRootDisposable) + } + + fun `test don't show when settings are disabled`() = myFixture.testInlineCompletion { + registerSuggestion("b") + init(PlainTextFileType.INSTANCE, "a") + ContinueExtensionSettings.instance.continueState.enableTabAutocomplete = false + callInlineCompletion() + delay() + assertNoLookup() + } + + + fun `test show completion on Ctrl + Space, then insert with Tab`() = myFixture.testInlineCompletion { + registerSuggestion("subtract(a: Int, b: Int) = a - b") + init( + PlainTextFileType.INSTANCE, + """ + class Calculator { + fun add(a: Int, b: Int) = a + b + fun + } + """.trimIndent() + ) + callInlineCompletion() + delay() + insertWithTab() + assertFileContent( + """ + class Calculator { + fun add(a: Int, b: Int) = a + b + fun subtract(a: Int, b: Int) = a - b + } + """.trimIndent() + ) + } + + fun `test inline completion that updates as the user types`() = myFixture.testInlineCompletion { + registerSuggestion("4567890'") + init(PlainTextFileType.INSTANCE, "digits = '123") + callInlineCompletion() + delay() + typeChar('4') + typeChar('5') + assertInlineRender("67890'") + typeChar('6') + insertWithTab() + assertFileContent("digits = '1234567890'") + } + + fun `test cycle between multiple completion variants`() { + // todo implement + } + + fun `test multiline`() = myFixture.testInlineCompletion { + registerSuggestion(": i32) -> i32 {\n a + b\n}") + init(PlainTextFileType.INSTANCE, "fn add(a: i32, b") + callInlineCompletion() + delay() + insertWithTab() + assertFileContent( + """ + fn add(a: i32, b: i32) -> i32 { + a + b + } + """.trimIndent() + ) + } + + fun `test accepting completion notifies the service with valid UUID`() = myFixture.testInlineCompletion { + var acceptedUuid: String? = null + registerSuggestion("test") { acceptedUuid = it } + init(PlainTextFileType.INSTANCE, "test ") + callInlineCompletion() + delay() + insertWithTab() + assertFileContent("test test") + assertDoesNotThrow { + UUID.fromString(acceptedUuid) + } + } + + private fun registerSuggestion(variant: String?, accept: (String?) -> Unit = {}) = + myFixture.project.replaceService( + CompletionService::class.java, + object : CompletionService { + override suspend fun getAutocomplete(uuid: String, url: String, line: Int, column: Int): String? = + variant + + override fun acceptAutocomplete(uuid: String?) = + accept(uuid) + }, + testRootDisposable + ) +} \ No newline at end of file From 29dc0e18401b25d745f14eae5ce0d254505ee223 Mon Sep 17 00:00:00 2001 From: Jakub Blach Date: Wed, 6 Aug 2025 01:45:26 +0200 Subject: [PATCH 02/48] fix: use older API from 2023.3 --- extensions/intellij/.run/Run Test IDE.run.xml | 46 +++++++++---------- extensions/intellij/build.gradle.kts | 30 ++++++------ extensions/intellij/gradle.properties | 2 +- .../autocomplete/ContinueCompletionService.kt | 3 +- .../ContinueInlineCompletionProvider.kt | 27 +++-------- .../ContinueInlineCompletionProviderTest.kt | 20 +++++--- 6 files changed, 60 insertions(+), 68 deletions(-) diff --git a/extensions/intellij/.run/Run Test IDE.run.xml b/extensions/intellij/.run/Run Test IDE.run.xml index 94ab5809f..686e26ef1 100644 --- a/extensions/intellij/.run/Run Test IDE.run.xml +++ b/extensions/intellij/.run/Run Test IDE.run.xml @@ -1,26 +1,24 @@ - - - - - - true - true - false - false - - - + + + + + + true + true + false + false + + \ No newline at end of file diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts index 8b948203f..bc3420959 100644 --- a/extensions/intellij/build.gradle.kts +++ b/extensions/intellij/build.gradle.kts @@ -5,16 +5,13 @@ import org.jetbrains.intellij.platform.gradle.tasks.PrepareSandboxTask fun environment(key: String) = providers.environmentVariable(key) 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" plugins { - kotlin("jvm") version "1.8.0" + kotlin("jvm") version "1.9.21" 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" @@ -34,7 +31,7 @@ repositories { dependencies { intellijPlatform { - create("IC", "2024.1") + create("IC", platformVersion) plugins(listOf("org.jetbrains.plugins.terminal:223.8214.6")) testFramework(TestFrameworkType.Platform) } @@ -50,27 +47,28 @@ dependencies { testRuntimeOnly("org.junit.vintage:junit-vintage-engine:5.10.0") // required to run both JUnit 5 and JUnit 3 } -kotlin { jvmToolchain(17) } +kotlin { + jvmToolchain(17) +} intellijPlatform { pluginConfiguration { ideaVersion { - sinceBuild = "241" + sinceBuild = "233" } } pluginVerification { ides { - ide("IC", "2025.1.4") + ide("IC", "2025.2") + ide("IC", "2025.1") + ide("IC", "2024.3") + ide("IC", "2024.2") ide("IC", "2024.1") + ide("IC", "2023.3") } } } -changelog { - groups.empty() - repositoryUrl = pluginRepositoryUrl -} - qodana { cachePath = provider { file(".qodana").canonicalPath } reportPath = provider { file("build/reports/inspections").canonicalPath } @@ -78,7 +76,11 @@ qodana { showReport = environment("QODANA_SHOW_REPORT").map { it.toBoolean() }.getOrElse(false) } -koverReport { defaults { xml { onCheck = true } } } +koverReport { + defaults { + xml { onCheck = true } + } +} intellijPlatformTesting { runIde { diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index c058c9206..20bc1310e 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -1,6 +1,6 @@ pluginGroup=com.github.continuedev.continueintellijextension -pluginRepositoryUrl=https://github.com/continuedev/continue pluginVersion=1.0.34 +platformVersion=2023.3 kotlin.stdlib.default.dependency=false org.gradle.configuration-cache=true org.gradle.caching=true diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCompletionService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCompletionService.kt index 453eadd01..4eae86f8d 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCompletionService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCompletionService.kt @@ -15,8 +15,7 @@ class ContinueCompletionService(private val project: Project) : CompletionServic override suspend fun getAutocomplete(uuid: String, url: String, line: Int, column: Int): String? { val requestInput = getCompletionInput(uuid, url, line, column) - val modelTimeout = project.service().fetchModelTimeoutOrNull() - ?: return null + val modelTimeout = project.service().fetchModelTimeoutOrNull() ?: 1000.0 return withTimeoutOrNull(modelTimeout.milliseconds) { suspendCancellableCoroutine { continuation -> project.service().coreMessenger?.request( diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt index bbcbc7992..c684c4bca 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt @@ -1,21 +1,14 @@ +@file:Suppress("UnstableApiUsage") + package com.github.continuedev.continueintellijextension.autocomplete import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.utils.uuid -import com.intellij.codeInsight.inline.completion.DefaultInlineCompletionInsertHandler -import com.intellij.codeInsight.inline.completion.InlineCompletionEvent -import com.intellij.codeInsight.inline.completion.InlineCompletionInsertEnvironment -import com.intellij.codeInsight.inline.completion.InlineCompletionInsertHandler -import com.intellij.codeInsight.inline.completion.InlineCompletionProvider -import com.intellij.codeInsight.inline.completion.InlineCompletionProviderID -import com.intellij.codeInsight.inline.completion.InlineCompletionRequest +import com.intellij.codeInsight.inline.completion.* import com.intellij.codeInsight.inline.completion.elements.InlineCompletionElement import com.intellij.codeInsight.inline.completion.elements.InlineCompletionGrayTextElement -import com.intellij.codeInsight.inline.completion.suggestion.InlineCompletionSuggestion -import com.intellij.codeInsight.inline.completion.suggestion.InlineCompletionVariant import com.intellij.openapi.components.service import com.intellij.openapi.project.Project -import kotlinx.coroutines.flow.flow class ContinueInlineCompletionProvider : InlineCompletionProvider { override val id get() = InlineCompletionProviderID("Continue") @@ -29,7 +22,7 @@ class ContinueInlineCompletionProvider : InlineCompletionProvider { override suspend fun getSuggestion(request: InlineCompletionRequest): InlineCompletionSuggestion { val editor = request.editor val project = editor.project - ?: return InlineCompletionSuggestion.Empty + ?: return InlineCompletionSuggestion.empty() lastUuid = uuid() lastProject = project val variant = project.service().getAutocomplete( @@ -39,15 +32,9 @@ class ContinueInlineCompletionProvider : InlineCompletionProvider { editor.caretModel.primaryCaret.logicalPosition.column ) if (variant == null) - return InlineCompletionSuggestion.Empty - return object : InlineCompletionSuggestion { - override suspend fun getVariants(): List { - val completion = InlineCompletionVariant.build( - request.file.virtualFile, - flow { emit(InlineCompletionGrayTextElement(variant)) } - ) - return listOf(completion) - } + return InlineCompletionSuggestion.empty() + return InlineCompletionSuggestion.withFlow { + emit(InlineCompletionGrayTextElement(variant)) } } diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinueInlineCompletionProviderTest.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinueInlineCompletionProviderTest.kt index 331b9269f..45c6249cd 100644 --- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinueInlineCompletionProviderTest.kt +++ b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinueInlineCompletionProviderTest.kt @@ -69,10 +69,6 @@ class ContinueInlineCompletionProviderTest : BasePlatformTestCase() { assertFileContent("digits = '1234567890'") } - fun `test cycle between multiple completion variants`() { - // todo implement - } - fun `test multiline`() = myFixture.testInlineCompletion { registerSuggestion(": i32) -> i32 {\n a + b\n}") init(PlainTextFileType.INSTANCE, "fn add(a: i32, b") @@ -89,18 +85,28 @@ class ContinueInlineCompletionProviderTest : BasePlatformTestCase() { } fun `test accepting completion notifies the service with valid UUID`() = myFixture.testInlineCompletion { - var acceptedUuid: String? = null - registerSuggestion("test") { acceptedUuid = it } + var uuid: String? = null + registerSuggestion("test") { uuid = it } init(PlainTextFileType.INSTANCE, "test ") callInlineCompletion() delay() insertWithTab() assertFileContent("test test") assertDoesNotThrow { - UUID.fromString(acceptedUuid) + UUID.fromString(uuid) } } + fun `test not accepting completions is not notifying service with UUID`() = myFixture.testInlineCompletion { + var uuid: String? = null + registerSuggestion("test") { uuid = it } + init(PlainTextFileType.INSTANCE, "test ") + callInlineCompletion() + delay() + assertInlineRender("test") + assertNull(uuid) + } + private fun registerSuggestion(variant: String?, accept: (String?) -> Unit = {}) = myFixture.project.replaceService( CompletionService::class.java, From f088de87db49cf5a1d35de6c4f32f65257776f39 Mon Sep 17 00:00:00 2001 From: Jakub Blach Date: Wed, 6 Aug 2025 01:49:43 +0200 Subject: [PATCH 03/48] fix: fix run config --- .../intellij/.run/Run Extension.run.xml | 3 +- extensions/intellij/.run/Run Test IDE.run.xml | 46 ++++++++++--------- 2 files changed, 25 insertions(+), 24 deletions(-) diff --git a/extensions/intellij/.run/Run Extension.run.xml b/extensions/intellij/.run/Run Extension.run.xml index 30a38f6c4..6a9bf8ff5 100644 --- a/extensions/intellij/.run/Run Extension.run.xml +++ b/extensions/intellij/.run/Run Extension.run.xml @@ -4,14 +4,13 @@ diff --git a/extensions/intellij/.run/Run Test IDE.run.xml b/extensions/intellij/.run/Run Test IDE.run.xml index 686e26ef1..94ab5809f 100644 --- a/extensions/intellij/.run/Run Test IDE.run.xml +++ b/extensions/intellij/.run/Run Test IDE.run.xml @@ -1,24 +1,26 @@ - - - - - - true - true - false - false - - + + + + + + true + true + false + false + + + \ No newline at end of file From 041108cca0b8fbe75ed6cdea9ea11d1c488fe744 Mon Sep 17 00:00:00 2001 From: Jakub Blach Date: Thu, 7 Aug 2025 19:06:13 +0200 Subject: [PATCH 04/48] fix: attempt to fix autocomplete e2e tests --- extensions/intellij/build.gradle.kts | 1 + 1 file changed, 1 insertion(+) diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts index bc3420959..a10ca6c70 100644 --- a/extensions/intellij/build.gradle.kts +++ b/extensions/intellij/build.gradle.kts @@ -36,6 +36,7 @@ dependencies { testFramework(TestFrameworkType.Platform) } implementation("com.posthog.java:posthog:1.2.0") + runtimeOnly("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.2") testImplementation("junit:junit:4.13.2") testImplementation("com.intellij.remoterobot:remote-robot:$remoteRobotVersion") From 05b2625adacca900db26f7e57db9f392ad187ece Mon Sep 17 00:00:00 2001 From: Jakub Blach Date: Thu, 7 Aug 2025 20:07:37 +0200 Subject: [PATCH 05/48] fix: attempt to fix runtime coroutine-related exceptions + fix e2e selector --- extensions/intellij/build.gradle.kts | 6 ++--- extensions/intellij/gradle.properties | 2 +- .../ContinueInlineCompletionProvider.kt | 27 ++++++++++++++----- .../e2e/Autocomplete.kt | 4 +-- 4 files changed, 24 insertions(+), 15 deletions(-) diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts index a10ca6c70..677d160d9 100644 --- a/extensions/intellij/build.gradle.kts +++ b/extensions/intellij/build.gradle.kts @@ -11,7 +11,7 @@ val pluginVersion: String by project val isEap get() = environment("RELEASE_CHANNEL").orNull == "eap" plugins { - kotlin("jvm") version "1.9.21" + kotlin("jvm") version "1.9.22" 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" @@ -36,7 +36,6 @@ dependencies { testFramework(TestFrameworkType.Platform) } implementation("com.posthog.java:posthog:1.2.0") - runtimeOnly("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.2") testImplementation("junit:junit:4.13.2") testImplementation("com.intellij.remoterobot:remote-robot:$remoteRobotVersion") @@ -55,7 +54,7 @@ kotlin { intellijPlatform { pluginConfiguration { ideaVersion { - sinceBuild = "233" + sinceBuild = "241" } } pluginVerification { @@ -65,7 +64,6 @@ intellijPlatform { ide("IC", "2024.3") ide("IC", "2024.2") ide("IC", "2024.1") - ide("IC", "2023.3") } } } diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 20bc1310e..272354fe4 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -1,6 +1,6 @@ pluginGroup=com.github.continuedev.continueintellijextension pluginVersion=1.0.34 -platformVersion=2023.3 +platformVersion=2024.1 kotlin.stdlib.default.dependency=false org.gradle.configuration-cache=true org.gradle.caching=true diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt index c684c4bca..bbcbc7992 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt @@ -1,14 +1,21 @@ -@file:Suppress("UnstableApiUsage") - package com.github.continuedev.continueintellijextension.autocomplete import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.utils.uuid -import com.intellij.codeInsight.inline.completion.* +import com.intellij.codeInsight.inline.completion.DefaultInlineCompletionInsertHandler +import com.intellij.codeInsight.inline.completion.InlineCompletionEvent +import com.intellij.codeInsight.inline.completion.InlineCompletionInsertEnvironment +import com.intellij.codeInsight.inline.completion.InlineCompletionInsertHandler +import com.intellij.codeInsight.inline.completion.InlineCompletionProvider +import com.intellij.codeInsight.inline.completion.InlineCompletionProviderID +import com.intellij.codeInsight.inline.completion.InlineCompletionRequest import com.intellij.codeInsight.inline.completion.elements.InlineCompletionElement import com.intellij.codeInsight.inline.completion.elements.InlineCompletionGrayTextElement +import com.intellij.codeInsight.inline.completion.suggestion.InlineCompletionSuggestion +import com.intellij.codeInsight.inline.completion.suggestion.InlineCompletionVariant import com.intellij.openapi.components.service import com.intellij.openapi.project.Project +import kotlinx.coroutines.flow.flow class ContinueInlineCompletionProvider : InlineCompletionProvider { override val id get() = InlineCompletionProviderID("Continue") @@ -22,7 +29,7 @@ class ContinueInlineCompletionProvider : InlineCompletionProvider { override suspend fun getSuggestion(request: InlineCompletionRequest): InlineCompletionSuggestion { val editor = request.editor val project = editor.project - ?: return InlineCompletionSuggestion.empty() + ?: return InlineCompletionSuggestion.Empty lastUuid = uuid() lastProject = project val variant = project.service().getAutocomplete( @@ -32,9 +39,15 @@ class ContinueInlineCompletionProvider : InlineCompletionProvider { editor.caretModel.primaryCaret.logicalPosition.column ) if (variant == null) - return InlineCompletionSuggestion.empty() - return InlineCompletionSuggestion.withFlow { - emit(InlineCompletionGrayTextElement(variant)) + return InlineCompletionSuggestion.Empty + return object : InlineCompletionSuggestion { + override suspend fun getVariants(): List { + val completion = InlineCompletionVariant.build( + request.file.virtualFile, + flow { emit(InlineCompletionGrayTextElement(variant)) } + ) + return listOf(completion) + } } } diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Autocomplete.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Autocomplete.kt index a8bdab796..44171e581 100644 --- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Autocomplete.kt +++ b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Autocomplete.kt @@ -28,13 +28,11 @@ class Autocomplete { @BeforeEach fun waitForIde(remoteRobot: RemoteRobot) { - System.setProperty("continue.autocomplete.test.environment", "true") waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") } } @AfterEach fun closeProject(remoteRobot: RemoteRobot) { - System.clearProperty("continue.autocomplete.test.environment") CommonSteps(remoteRobot).closeProject() } @@ -54,7 +52,7 @@ class Autocomplete { // Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus. waitFor(ofSeconds(20)) { findAll( - byXpath("//div[@accessiblename='Main.java' and @class='SingleHeightLabel']") + byXpath("//div[@visible_text='Main.java']") ).isNotEmpty() } From ceb01c45c3de61a9051c3b1fb4c4ef118789e482 Mon Sep 17 00:00:00 2001 From: Jakub Blach Date: Thu, 7 Aug 2025 20:44:50 +0200 Subject: [PATCH 06/48] fix: get extra debug info --- .github/actions/run-jetbrains-tests/action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/actions/run-jetbrains-tests/action.yml b/.github/actions/run-jetbrains-tests/action.yml index 6c2d431ff..51f3b8d55 100644 --- a/.github/actions/run-jetbrains-tests/action.yml +++ b/.github/actions/run-jetbrains-tests/action.yml @@ -107,7 +107,7 @@ runs: Xvfb -ac :99 -screen 0 1920x1080x24 & sleep 10 mkdir -p build/reports - ./gradlew runIdeForUiTests & + ./gradlew runIdeForUiTests --info --stacktrace & - name: Wait for JB connection uses: jtalk/url-health-check-action@v3 From 08c94db9540286b8d74b1c8fbbcc4772d02cab09 Mon Sep 17 00:00:00 2001 From: Jakub Blach Date: Thu, 7 Aug 2025 20:54:56 +0200 Subject: [PATCH 07/48] fix: test --- .github/actions/run-jetbrains-tests/action.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/actions/run-jetbrains-tests/action.yml b/.github/actions/run-jetbrains-tests/action.yml index 51f3b8d55..fa204761b 100644 --- a/.github/actions/run-jetbrains-tests/action.yml +++ b/.github/actions/run-jetbrains-tests/action.yml @@ -107,7 +107,7 @@ runs: Xvfb -ac :99 -screen 0 1920x1080x24 & sleep 10 mkdir -p build/reports - ./gradlew runIdeForUiTests --info --stacktrace & + ./gradlew runIdeForUiTests & - name: Wait for JB connection uses: jtalk/url-health-check-action@v3 @@ -121,7 +121,7 @@ runs: run: | cd extensions/intellij export DISPLAY=:99.0 - ./gradlew test + ./gradlew test --info --stacktrace - name: Move video if: ${{ failure() }} From e6b5335ae367e02be7dd7b5ce9324aac203299f4 Mon Sep 17 00:00:00 2001 From: Jakub Blach Date: Mon, 11 Aug 2025 15:20:58 +0200 Subject: [PATCH 08/48] fix: remove platformVersion from Run Extension to fix Kotlin version error --- extensions/intellij/.run/Run Extension.run.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/intellij/.run/Run Extension.run.xml b/extensions/intellij/.run/Run Extension.run.xml index 6a9bf8ff5..63b2835d6 100644 --- a/extensions/intellij/.run/Run Extension.run.xml +++ b/extensions/intellij/.run/Run Extension.run.xml @@ -10,7 +10,7 @@ From 81523665f3c13c34ec908d9b41935984acbaaa32 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 12 Aug 2025 20:40:02 -0700 Subject: [PATCH 09/48] feat: toggle between next edit and autocomplete --- .../ContinueInlineCompletionProvider.kt | 111 +++++++++++++++--- 1 file changed, 96 insertions(+), 15 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt index bbcbc7992..490ac8590 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt @@ -1,5 +1,10 @@ package com.github.continuedev.continueintellijextension.autocomplete +import com.github.continuedev.continueintellijextension.FimResult +import com.github.continuedev.continueintellijextension.Position +import com.github.continuedev.continueintellijextension.nextEdit.NextEditService +import com.github.continuedev.continueintellijextension.nextEdit.NextEditUtils +import com.github.continuedev.continueintellijextension.nextEdit.NextEditWindowManager import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.utils.uuid import com.intellij.codeInsight.inline.completion.DefaultInlineCompletionInsertHandler @@ -22,6 +27,7 @@ class ContinueInlineCompletionProvider : InlineCompletionProvider { override val insertHandler: InlineCompletionInsertHandler = NotifyingHandler() private var lastUuid: String? = null private var lastProject: Project? = null + private var isUsingNextEdit = false override fun isEnabled(event: InlineCompletionEvent): Boolean = ContinueExtensionSettings.instance.continueState.enableTabAutocomplete @@ -32,21 +38,91 @@ class ContinueInlineCompletionProvider : InlineCompletionProvider { ?: return InlineCompletionSuggestion.Empty lastUuid = uuid() lastProject = project - val variant = project.service().getAutocomplete( - lastUuid!!, - editor.virtualFile.url, - editor.caretModel.primaryCaret.logicalPosition.line, - editor.caretModel.primaryCaret.logicalPosition.column - ) - if (variant == null) - return InlineCompletionSuggestion.Empty - return object : InlineCompletionSuggestion { - override suspend fun getVariants(): List { - val completion = InlineCompletionVariant.build( - request.file.virtualFile, - flow { emit(InlineCompletionGrayTextElement(variant)) } + + // Check if Next Edit is supported + val isNextEditSupported = NextEditUtils.isNextEditSupported(project) + + if (isNextEditSupported) { + val currCursorPos = Pair( + editor.caretModel.primaryCaret.logicalPosition.line, + editor.caretModel.primaryCaret.logicalPosition.column + ) + // Use Next Edit - but don't return inline completion for it + val nextEditService = project.service() + val nextEditOutcome = nextEditService.getNextEditSuggestion( + lastUuid!!, + editor.virtualFile.url, + currCursorPos.first, + currCursorPos.second + ) + + if (nextEditOutcome != null) { + val editableRegionStartLine = nextEditOutcome.editableRegionStartLine + val editableRegionEndLine = nextEditOutcome.editableRegionEndLine + val oldEditRangeSlice = editor.document.text + .split("\n") + .drop(editableRegionStartLine) + .take(editableRegionEndLine - editableRegionStartLine + 1) + .joinToString("\n") + + // Check if it's a FIM (Fill-In-Middle) operation + val fimResult = NextEditUtils.checkFim( + oldEditRangeSlice, // Use the extracted slice instead of nextEditOutcome.oldCode + nextEditOutcome.completion, + currCursorPos ) - return listOf(completion) + + when (fimResult) { + is FimResult.FimEdit -> { + // Render as gray text inline completion + isUsingNextEdit = true + return object : InlineCompletionSuggestion { + override suspend fun getVariants(): List { + val completion = InlineCompletionVariant.build( + request.file.virtualFile, + flow { emit(InlineCompletionGrayTextElement(fimResult.fimText)) } + ) + return listOf(completion) + } + } + } + is FimResult.NotFimEdit -> { + // For non-FIM operations, show custom UI and return empty + val nextEditWindowManager = project.service() + isUsingNextEdit = true + nextEditWindowManager.showNextEditWindow( + editor, + Position(currCursorPos.first, currCursorPos.second), + editableRegionStartLine, + editableRegionEndLine, + oldEditRangeSlice, + nextEditOutcome.completion, + nextEditOutcome.diffLines, + ) + return InlineCompletionSuggestion.Empty + } + } + } + return InlineCompletionSuggestion.Empty + } else { + // Use traditional autocomplete + val variant = project.service().getAutocomplete( + lastUuid!!, + editor.virtualFile.url, + editor.caretModel.primaryCaret.logicalPosition.line, + editor.caretModel.primaryCaret.logicalPosition.column + ) + if (variant == null) + return InlineCompletionSuggestion.Empty + + return object : InlineCompletionSuggestion { + override suspend fun getVariants(): List { + val completion = InlineCompletionVariant.build( + request.file.virtualFile, + flow { emit(InlineCompletionGrayTextElement(variant)) } + ) + return listOf(completion) + } } } } @@ -60,7 +136,12 @@ class ContinueInlineCompletionProvider : InlineCompletionProvider { elements: List ) { DefaultInlineCompletionInsertHandler.INSTANCE.afterInsertion(environment, elements) - lastProject?.service()?.acceptAutocomplete(lastUuid) + + if (isUsingNextEdit) { + lastProject?.service()?.acceptEdit(lastUuid ?: "") + } else { + lastProject?.service()?.acceptAutocomplete(lastUuid) + } } } } \ No newline at end of file From c1ee00b312dbabf15d82e3eb5f833b7cfc5919e5 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 12 Aug 2025 20:40:37 -0700 Subject: [PATCH 10/48] refactor: move util to next edit utils --- .../nextEdit/NextEditUtils.kt | 117 ++++++++++++++++++ .../continueintellijextension/utils/Utils.kt | 67 ---------- 2 files changed, 117 insertions(+), 67 deletions(-) create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditUtils.kt diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditUtils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditUtils.kt new file mode 100644 index 000000000..f908a8846 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditUtils.kt @@ -0,0 +1,117 @@ +package com.github.continuedev.continueintellijextension.nextEdit + +import com.github.continuedev.continueintellijextension.FimResult +import com.github.continuedev.continueintellijextension.`continue`.ProfileInfoService +import com.github.continuedev.continueintellijextension.utils.castNestedOrNull +import com.intellij.openapi.components.service +import com.intellij.openapi.project.Project + +object NextEditUtils { + suspend fun isNextEditSupported(project: Project): Boolean { + return try { + val profileInfoService = project.service() + val selectedModelByRole = profileInfoService.fetchSelectedModelByRoleOrNull() + + // Use the existing utility function + val autocompleteModel = selectedModelByRole?.get("autocomplete").castNestedOrNull>() + + if (autocompleteModel != null) { + val modelName = autocompleteModel["model"] as? String ?: "" + val title = autocompleteModel["title"] as? String + val capabilities = autocompleteModel["capabilities"].castNestedOrNull>() + + isNextEditModel(modelName, title, capabilities) + } else { + false + } + } catch (e: Exception) { + println("Error checking Next Edit support: ${e.message}") + false + } + } + + private fun isNextEditModel( + model: String, + title: String?, + capabilities: Map? + ): Boolean { + // Check capabilities first + val hasNextEditCapability = capabilities?.get("nextEdit") as? Boolean ?: false + // Check model name and title against known Next Edit models + val supportedModels = listOf("mercury-coder-nextedit", "instinct") + val modelLower = model.lowercase() + val titleLower = title?.lowercase() + + return hasNextEditCapability || supportedModels.any { supportedModel -> + modelLower.contains(supportedModel) || + (titleLower?.contains(supportedModel) == true) + } + } + + /** + * Check if the diff is indeed a FIM (Fill-In-Middle). + * @param oldEditRange Original string content. + * @param newEditRange New string content. + * @param cursorPosition The position of the cursor in the old string. + * @return A Pair where the first value is a boolean indicating if the change is purely additive (FIM) + * and the second value is the FIM text content or null if not a FIM. + */ + fun checkFim( + oldEditRange: String, + newEditRange: String, + cursorPosition: Pair // line, character + ): FimResult { + // Find the common prefix + var prefixLength = 0 + while (prefixLength < oldEditRange.length && + prefixLength < newEditRange.length && + oldEditRange[prefixLength] == newEditRange[prefixLength]) { + prefixLength++ + } + + // Find the common suffix + var oldSuffixPos = oldEditRange.length - 1 + var newSuffixPos = newEditRange.length - 1 + + while (oldSuffixPos >= prefixLength && + newSuffixPos >= prefixLength && + oldEditRange[oldSuffixPos] == newEditRange[newSuffixPos]) { + oldSuffixPos-- + newSuffixPos-- + } + + // The old text is purely preserved if: + // 1. The prefix ends before or at the cursor. + // 2. The suffix starts after or at the cursor. + // 3. There's no gap between prefix and suffix in the old text. + + val suffixStartInOld = oldSuffixPos + 1 + val suffixStartInNew = newSuffixPos + 1 + + // Convert cursor position to an offset in the string. + // For simplicity, we need to calculate the cursor's position in the string. + // This requires knowledge of line endings in the oldEditRange. + val lines = oldEditRange.substring(0, prefixLength).split("\n") + val cursorOffset = if (lines.size > 1) { + lines.dropLast(1).sumOf { it.length + 1 } + cursorPosition.second + } else { + cursorPosition.second + } + + // Check if the cursor is positioned between the prefix and suffix. + val cursorBetweenPrefixAndSuffix = + prefixLength <= cursorOffset && cursorOffset <= suffixStartInOld + + // Check if the old text is completely preserved (no deletion). + val noTextDeleted = suffixStartInOld - prefixLength <= 0 + + val isFim = cursorBetweenPrefixAndSuffix && noTextDeleted + + return if (isFim) { + // Extract the content between prefix and suffix in the new string. + FimResult.FimEdit(newEditRange.substring(prefixLength, suffixStartInNew)) + } else { + FimResult.NotFimEdit + } + } +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Utils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Utils.kt index 888b59359..6126af546 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Utils.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Utils.kt @@ -118,71 +118,4 @@ fun getOsAndArchTarget(): String { } return "$osStr-$arch" -} - -/** - * Check if the diff is indeed a FIM (Fill-In-Middle). - * @param oldEditRange Original string content. - * @param newEditRange New string content. - * @param cursorPosition The position of the cursor in the old string. - * @return A Pair where the first value is a boolean indicating if the change is purely additive (FIM) - * and the second value is the FIM text content or null if not a FIM. - */ -fun checkFim( - oldEditRange: String, - newEditRange: String, - cursorPosition: Pair // line, character -): FimResult { - // Find the common prefix - var prefixLength = 0 - while (prefixLength < oldEditRange.length && - prefixLength < newEditRange.length && - oldEditRange[prefixLength] == newEditRange[prefixLength]) { - prefixLength++ - } - - // Find the common suffix - var oldSuffixPos = oldEditRange.length - 1 - var newSuffixPos = newEditRange.length - 1 - - while (oldSuffixPos >= prefixLength && - newSuffixPos >= prefixLength && - oldEditRange[oldSuffixPos] == newEditRange[newSuffixPos]) { - oldSuffixPos-- - newSuffixPos-- - } - - // The old text is purely preserved if: - // 1. The prefix ends before or at the cursor. - // 2. The suffix starts after or at the cursor. - // 3. There's no gap between prefix and suffix in the old text. - - val suffixStartInOld = oldSuffixPos + 1 - val suffixStartInNew = newSuffixPos + 1 - - // Convert cursor position to an offset in the string. - // For simplicity, we need to calculate the cursor's position in the string. - // This requires knowledge of line endings in the oldEditRange. - val lines = oldEditRange.substring(0, prefixLength).split("\n") - val cursorOffset = if (lines.size > 1) { - lines.dropLast(1).sumOf { it.length + 1 } + cursorPosition.second - } else { - cursorPosition.second - } - - // Check if the cursor is positioned between the prefix and suffix. - val cursorBetweenPrefixAndSuffix = - prefixLength <= cursorOffset && cursorOffset <= suffixStartInOld - - // Check if the old text is completely preserved (no deletion). - val noTextDeleted = suffixStartInOld - prefixLength <= 0 - - val isFim = cursorBetweenPrefixAndSuffix && noTextDeleted - - return if (isFim) { - // Extract the content between prefix and suffix in the new string. - FimResult.FimEdit(newEditRange.substring(prefixLength, suffixStartInNew)) - } else { - FimResult.NotFimEdit - } } \ No newline at end of file From ba21ae442c0f77dd185c472efa3519883b7f83db Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 12 Aug 2025 20:40:59 -0700 Subject: [PATCH 11/48] feat: add the core next edit service --- .../nextEdit/NextEditService.kt | 204 ++++++++++++++++++ 1 file changed, 204 insertions(+) create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditService.kt diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditService.kt new file mode 100644 index 000000000..a03ee47bb --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditService.kt @@ -0,0 +1,204 @@ +package com.github.continuedev.continueintellijextension.nextEdit + +import com.github.continuedev.continueintellijextension.Position +import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger +import com.github.continuedev.continueintellijextension.services.ContinuePluginService +import com.intellij.openapi.components.Service +import com.intellij.openapi.components.service +import com.intellij.openapi.editor.LogicalPosition +import com.intellij.openapi.project.Project +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.coroutines.withTimeoutOrNull +import kotlin.coroutines.resume +import kotlin.time.Duration.Companion.milliseconds + +interface NextEditService { + suspend fun getNextEditSuggestion( + completionId: String, + filepath: String, + line: Int, + character: Int, + withChain: Boolean = false, + usingFullFileDiff: Boolean = true + ): NextEditOutcome? + fun startChain() + fun deleteChain() + fun chainExists(): Boolean + fun getNextInChain(): NextEditItem? + fun markDisplayed(completionId: String, outcome: NextEditOutcome) + fun acceptEdit(completionId: String) + fun rejectEdit(completionId: String) +} + +@Service(Service.Level.PROJECT) +class ContinueNextEditService(private val project: Project) : NextEditService { + + private var currentChain: NextEditChain? = null + private val displayedCompletions = mutableMapOf() + + private val coreMessenger: CoreMessenger? + get() = project.service().coreMessenger + + override suspend fun getNextEditSuggestion( + completionId: String, + filepath: String, + line: Int, + character: Int, + withChain: Boolean, + usingFullFileDiff: Boolean + ): NextEditOutcome? { + val requestData = mapOf( + "input" to mapOf( + "completionId" to completionId, + "filepath" to filepath, + "pos" to mapOf("line" to line, "character" to character), + "recentlyEditedRanges" to emptyList(), + "recentlyVisitedRanges" to emptyList() + ), + "options" to mapOf( + "withChain" to withChain, + "usingFullFileDiff" to usingFullFileDiff + ) + ) + + return withTimeoutOrNull(5000.milliseconds) { + suspendCancellableCoroutine { continuation -> + coreMessenger?.request("nextEdit/predict", requestData, null) { response -> + val outcome = parseNextEditOutcome(response) + continuation.resume(outcome) + } + } + } + } + + override fun startChain() { + currentChain = NextEditChain() + coreMessenger?.request("nextEdit/startChain", emptyMap(), null) {} + } + + override fun deleteChain() { + currentChain = null + coreMessenger?.request("nextEdit/deleteChain", emptyMap(), null) {} + } + + override fun chainExists(): Boolean = currentChain != null + + override fun getNextInChain(): NextEditItem? { + return currentChain?.getNext() + } + + override fun markDisplayed(completionId: String, outcome: NextEditOutcome) { + displayedCompletions[completionId] = outcome + } + + override fun acceptEdit(completionId: String) { + coreMessenger?.request("nextEdit/accept", mapOf("completionId" to completionId), null) {} + displayedCompletions.remove(completionId) + } + + override fun rejectEdit(completionId: String) { + coreMessenger?.request("nextEdit/reject", mapOf("completionId" to completionId), null) {} + displayedCompletions.remove(completionId) + deleteChain() + } + + private fun parseNextEditOutcome(response: Any?): NextEditOutcome? { + return try { + val responseMap = response as? Map ?: return null + val contentMap = responseMap["content"] as? Map ?: return null + + // Extract position data + val cursorPos = contentMap["cursorPosition"] as? Map + val cursorPosition = if (cursorPos != null) { + Position( + line = (cursorPos["line"] as? Number)?.toInt() ?: 0, + character = (cursorPos["character"] as? Number)?.toInt() ?: 0 + ) + } else { + Position(0, 0) + } + + val finalCursorPos = contentMap["finalCursorPosition"] as? Map + val finalCursorPosition = if (finalCursorPos != null) { + Position( + line = (finalCursorPos["line"] as? Number)?.toInt() ?: 0, + character = (finalCursorPos["character"] as? Number)?.toInt() ?: 0 + ) + } else { + Position(0, 0) + } + + // Extract diffLines + val diffLinesRaw = contentMap["diffLines"] as? List> ?: emptyList() + val diffLines = diffLinesRaw.map { diffLineMap -> + DiffLine( + type = diffLineMap["type"] as? String ?: "same", + line = diffLineMap["line"] as? String ?: "" + ) + } + + // Construct NextEditOutcome from the map data + NextEditOutcome( + // TabAutocompleteOptions fields + disable = contentMap["disable"] as? Boolean ?: false, + maxPromptTokens = (contentMap["maxPromptTokens"] as? Number)?.toInt() ?: 2048, + debounceDelay = (contentMap["debounceDelay"] as? Number)?.toInt() ?: 150, + maxSuffixPercentage = (contentMap["maxSuffixPercentage"] as? Number)?.toInt() ?: 25, + prefixPercentage = (contentMap["prefixPercentage"] as? Number)?.toInt() ?: 85, + transform = contentMap["transform"] as? Boolean, + template = contentMap["template"] as? String, + multilineCompletions = contentMap["multilineCompletions"] as? String ?: "auto", + slidingWindowPrefixPercentage = (contentMap["slidingWindowPrefixPercentage"] as? Number)?.toInt() ?: 75, + slidingWindowSize = (contentMap["slidingWindowSize"] as? Number)?.toInt() ?: 500, + useCache = contentMap["useCache"] as? Boolean ?: true, + onlyMyCode = contentMap["onlyMyCode"] as? Boolean ?: true, + useRecentlyEdited = contentMap["useRecentlyEdited"] as? Boolean ?: true, + disableInFiles = contentMap["disableInFiles"] as? List, + useImports = contentMap["useImports"] as? Boolean, + showWhateverWeHaveAtXMs = (contentMap["showWhateverWeHaveAtXMs"] as? Number)?.toInt(), + + // Autocomplete fields + elapsed = (contentMap["elapsed"] as? Number)?.toLong() ?: 0L, + modelProvider = contentMap["modelProvider"] as? String ?: "", + modelName = contentMap["modelName"] as? String ?: "", + completionOptions = contentMap["completionOptions"] ?: emptyMap(), + completionId = contentMap["completionId"] as? String ?: "", + gitRepo = contentMap["gitRepo"] as? String, + uniqueId = contentMap["uniqueId"] as? String ?: "", + timestamp = (contentMap["timestamp"] as? Number)?.toLong() ?: System.currentTimeMillis(), + + // Next Edit specific fields + fileUri = contentMap["fileUri"] as? String ?: "", + workspaceDirUri = contentMap["workspaceDirUri"] as? String ?: "", + prompt = contentMap["prompt"] as? String ?: "", + userEdits = contentMap["userEdits"] as? String ?: "", + userExcerpts = contentMap["userExcerpts"] as? String ?: "", + originalEditableRange = contentMap["originalEditableRange"] as? String ?: "", + completion = contentMap["completion"] as? String ?: "", + cursorPosition = cursorPosition, + finalCursorPosition = finalCursorPosition, + accepted = contentMap["accepted"] as? Boolean, + editableRegionStartLine = (contentMap["editableRegionStartLine"] as? Number)?.toInt() ?: 0, + editableRegionEndLine = (contentMap["editableRegionEndLine"] as? Number)?.toInt() ?: 0, + diffLines = diffLines + ) + } catch (e: Exception) { + println("Error parsing Next Edit outcome: ${e.message}") + null + } + } +} + +data class NextEditChain( + private val items: MutableList = mutableListOf() +) { + fun getNext(): NextEditItem? = items.removeFirstOrNull() + fun add(item: NextEditItem) = items.add(item) + fun isEmpty(): Boolean = items.isEmpty() + fun size(): Int = items.size +} + +data class NextEditItem( + val outcome: NextEditOutcome, + val jumpLocation: LogicalPosition +) \ No newline at end of file From 7d1d48e8742c592181ac574e49b9bab1369199b3 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 12 Aug 2025 20:41:19 -0700 Subject: [PATCH 12/48] feat: add a rudimentary next edit window manager for intellij --- .../nextEdit/NextEditWindowManager.kt | 783 ++++++++++++++++++ 1 file changed, 783 insertions(+) create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt new file mode 100644 index 000000000..8b18486bf --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt @@ -0,0 +1,783 @@ +package com.github.continuedev.continueintellijextension.nextEdit + +import com.github.continuedev.continueintellijextension.Position +import com.github.continuedev.continueintellijextension.listeners.HandlerPriority +import com.github.continuedev.continueintellijextension.listeners.SelectionChangeManager +import com.github.continuedev.continueintellijextension.listeners.StateSnapshot +import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.command.WriteCommandAction +import com.intellij.openapi.components.Service +import com.intellij.openapi.editor.Editor +import com.intellij.openapi.editor.colors.EditorColorsManager +import com.intellij.openapi.editor.colors.EditorFontType +import com.intellij.openapi.editor.event.SelectionEvent +import com.intellij.openapi.editor.markup.EffectType +import com.intellij.openapi.editor.markup.HighlighterLayer +import com.intellij.openapi.editor.markup.HighlighterTargetArea +import com.intellij.openapi.editor.markup.RangeHighlighter +import com.intellij.openapi.editor.markup.TextAttributes +import com.intellij.openapi.project.Project +import com.intellij.openapi.ui.popup.JBPopup +import com.intellij.openapi.ui.popup.JBPopupFactory +import com.intellij.openapi.util.TextRange +import com.intellij.ui.JBColor +import com.intellij.ui.components.JBLabel +import com.intellij.ui.components.JBPanel +import com.intellij.util.ui.JBUI +import java.awt.BorderLayout +import java.awt.FlowLayout +import java.awt.event.ActionEvent +import java.awt.event.KeyEvent +import javax.swing.AbstractAction +import javax.swing.BoxLayout +import javax.swing.JComponent +import javax.swing.JLabel +import javax.swing.JScrollPane +import javax.swing.KeyStroke + +@Service(Service.Level.PROJECT) +class NextEditWindowManager(private val project: Project) { + private var currentPopup: JBPopup? = null + private var deletionHighlighters: List = emptyList() + private var isAccepted = false + private var currentCompletionId: String? = null + + suspend fun showNextEditWindow( + editor: Editor, + currCursorPos: Position, + editableRegionStartLine: Int, + editableRegionEndLine: Int, + oldCode: String, + newCode: String, + diffLines: List + ) { + println("DEBUG: showNextEditWindow called with:") + println(" currCursorPos: $currCursorPos") + println(" editableRegionStartLine: $editableRegionStartLine") + println(" editableRegionEndLine: $editableRegionEndLine") + println(" oldCode length: ${oldCode.length}") + println(" newCode length: ${newCode.length}") + println(" document total lines: ${editor.document.lineCount}") + println(" document writable: ${editor.document.isWritable}") + + // Clear existing decorations first + hideAllNextEditWindows() + + // Determine if this is a line deletion case + val isLineDelete = determineIfLineDelete( + editor, + editableRegionStartLine, + editableRegionEndLine, + oldCode, + newCode, + diffLines + ) + + println("DEBUG: isLineDelete: $isLineDelete") + + // Show the code popup with the new suggestion + showCodePopup(editor, newCode, diffLines) { action -> + when (action) { + PopupAction.ACCEPT -> acceptEdit( + editor, + newCode, + editableRegionStartLine, + editableRegionEndLine, + isLineDelete + ) + PopupAction.REJECT -> rejectEdit() + } + } + + // Render deletion strikethroughs in the editor + renderDeletionDecorations(editor, oldCode, newCode, editableRegionStartLine) + } + + private fun determineIfLineDelete( + editor: Editor, + editableRegionStartLine: Int, + editableRegionEndLine: Int, + oldCode: String, + newCode: String, + diffLines: List + ): Boolean { + // Check if new code is empty and we're dealing with a single line + if (newCode != "" || editableRegionStartLine != editableRegionEndLine) { + return false + } + + // Check if diffLines contains only deletions (no additions) + val onlyDeletions = diffLines.all { it.type == "old" || it.type == "same" } + val hasDeletedLine = diffLines.any { it.type == "old" } + + if (!onlyDeletions || !hasDeletedLine) { + return false + } + + // Fix: Use the correct method to get line text + val startOffset = editor.document.getLineStartOffset(editableRegionStartLine) + val endOffset = editor.document.getLineEndOffset(editableRegionStartLine) + val line = editor.document.getText(TextRange(startOffset, endOffset)) + val oldLine = oldCode.trim() + + return line.trim() == oldLine || line.trim().isEmpty() + } + + private fun showCodePopup( + editor: Editor, + code: String, + diffLines: List, + onAction: (PopupAction) -> Unit + ) { + val popupComponent = createNextEditPopupComponent(code, diffLines, onAction) + + val popup = JBPopupFactory.getInstance() + .createComponentPopupBuilder(popupComponent, popupComponent) // Set focus component + .setFocusable(true) + .setRequestFocus(true) + .setResizable(false) + .setMovable(false) + .setCancelOnClickOutside(false) + .setCancelOnWindowDeactivation(false) + .setCancelKeyEnabled(false) // Disable default Esc handling to use our custom one + .setCancelCallback { + onAction(PopupAction.REJECT) + true + } + .createPopup() + + currentPopup = popup + + // Show popup and ensure focus + ApplicationManager.getApplication().invokeLater { + try { + val caretPosition = editor.caretModel.primaryCaret.logicalPosition + val caretPoint = editor.logicalPositionToXY(caretPosition) + val editorComponent = editor.contentComponent + val screenPoint = java.awt.Point(caretPoint.x + 20, caretPoint.y + editor.lineHeight) + javax.swing.SwingUtilities.convertPointToScreen(screenPoint, editorComponent) + + popup.showInScreenCoordinates(editorComponent, screenPoint) + + // Force focus after popup is shown + ApplicationManager.getApplication().invokeLater { + popupComponent.requestFocusInWindow() + println("DEBUG: Popup shown and focus requested") + } + } catch (e: Exception) { + popup.showInBestPositionFor(editor) + ApplicationManager.getApplication().invokeLater { + popupComponent.requestFocusInWindow() + } + } + } + } + + private fun createNextEditPopupComponent( + code: String, + diffLines: List, + onAction: (PopupAction) -> Unit + ): JComponent { + val panel = JBPanel>().apply { + layout = BorderLayout() + border = JBUI.Borders.empty(8) + background = EditorColorsManager.getInstance().globalScheme.defaultBackground + } + + // Create syntax-highlighted code display + val codePanel = createCodeDisplayPanel(code, diffLines) + panel.add(codePanel, BorderLayout.CENTER) + + // Add keyboard shortcuts + addKeyboardShortcuts(panel, onAction) + + return panel + } + + private fun createCodeDisplayPanel(code: String, diffLines: List): JComponent { + val scheme = EditorColorsManager.getInstance().globalScheme + + // Use the editor's actual font settings + val editorFont = scheme.getFont(EditorFontType.PLAIN) + val fontSize = scheme.editorFontSize + val actualFont = editorFont.deriveFont(fontSize.toFloat()) + + // Get line spacing from editor settings + val lineSpacing = scheme.lineSpacing + val fontMetrics = java.awt.Toolkit.getDefaultToolkit().getFontMetrics(actualFont) + val baseLineHeight = fontMetrics.height + val actualLineHeight = (baseLineHeight * lineSpacing).toInt() + + val panel = JBPanel>().apply { + layout = BoxLayout(this, BoxLayout.Y_AXIS) + background = scheme.defaultBackground + border = JBUI.Borders.compound( + JBUI.Borders.customLine(JBColor.border()), + JBUI.Borders.empty(4) + ) + } + + var maxWidth = 0 + + // Filter out old lines and process only new and same lines from diffLines + val visibleDiffLines = diffLines.filter { it.type != "old" } + + // Create all labels first to measure them properly + val labels = mutableListOf() + + visibleDiffLines.forEach { diffLine -> + val displayText = diffLine.line.ifEmpty { " " } + + // Create HTML content for basic syntax highlighting + val htmlContent = createBasicHighlightedHtml(displayText, actualFont) + + val label = JBLabel(htmlContent).apply { + font = actualFont + isOpaque = true + + when (diffLine.type) { + "new" -> { + // Highlight new additions + background = JBColor(0x2D4A2D, 0x2D4A2D) // Darker green + foreground = scheme.defaultForeground + } + else -> { // "same" or any other type + // Regular unchanged lines + background = scheme.defaultBackground + foreground = scheme.defaultForeground + } + } + + // Match editor's text rendering + alignmentX = JComponent.LEFT_ALIGNMENT + } + + // Let the label calculate its own preferred size based on HTML content + val labelPreferredSize = label.preferredSize + maxWidth = maxOf(maxWidth, labelPreferredSize.width) + + // Set consistent height based on editor line height, but allow for HTML rendering + val adjustedLineHeight = maxOf(actualLineHeight, labelPreferredSize.height) + label.preferredSize = java.awt.Dimension(labelPreferredSize.width, adjustedLineHeight) + label.maximumSize = java.awt.Dimension(Int.MAX_VALUE, adjustedLineHeight) + + labels.add(label) + panel.add(label) + } + + // Calculate dimensions based on actual label measurements + val visibleLineCount = visibleDiffLines.size + val borderInsets = panel.border?.getBorderInsets(panel) ?: java.awt.Insets(0, 0, 0, 0) + + // Use the actual measured max width plus some padding + val contentWidth = maxWidth + borderInsets.left + borderInsets.right + 24 // More padding for HTML rendering + + // Calculate height based on actual label heights + val totalLabelHeight = labels.sumOf { it.preferredSize.height } + val contentHeight = totalLabelHeight + borderInsets.top + borderInsets.bottom + 16 + + // Set reasonable bounds for the popup with generous sizing +// val maxPopupWidth = 1200 // Increased to accommodate longer lines +// val maxPopupHeight = 800 // Increased to show more content +// val minPopupWidth = 500 // Increased minimum width +// val minPopupHeight = maxOf(actualLineHeight * 2, 100) // Minimum 2 lines + +// val finalWidth = minOf(maxPopupWidth, maxOf(minPopupWidth, contentWidth)) +// val finalHeight = minOf(maxPopupHeight, maxOf(minPopupHeight, contentHeight)) + val finalWidth = contentWidth + val finalHeight = contentHeight + + return JScrollPane(panel).apply { + border = null + preferredSize = java.awt.Dimension(finalWidth, finalHeight) + + // Only show scrollbars when actually needed + horizontalScrollBarPolicy = if (contentWidth > finalWidth) { + JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED + } else { + JScrollPane.HORIZONTAL_SCROLLBAR_NEVER + } + + verticalScrollBarPolicy = if (contentHeight > finalHeight) { + JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED + } else { + JScrollPane.VERTICAL_SCROLLBAR_NEVER + } + + // Use editor's background color + viewport.background = scheme.defaultBackground + background = scheme.defaultBackground + + // Smooth scrolling like in editor + viewport.scrollMode = javax.swing.JViewport.BACKINGSTORE_SCROLL_MODE + + // Match editor's scroll unit - use actual line height from labels + val averageLineHeight = if (labels.isNotEmpty()) { + labels.sumOf { it.preferredSize.height } / labels.size + } else { + actualLineHeight + } + verticalScrollBar.unitIncrement = averageLineHeight + horizontalScrollBar.unitIncrement = fontMetrics.charWidth(' ') * 4 + } + } + + private fun createBasicHighlightedHtml(text: String, font: java.awt.Font): String { + if (text.trim().isEmpty()) return "
 
" + + // Basic syntax highlighting patterns (you can extend this) + var highlightedText = text + .replace("&", "&") + .replace("<", "<") + .replace(">", ">") + .replace(" ", " ") // Preserve spaces + .replace("\t", "    ") // Convert tabs to spaces + + // Simple keyword highlighting (extend based on your needs) + val keywords = arrayOf( + "function", "const", "let", "var", "return", "if", "else", "for", "while", + "class", "public", "private", "static", "void", "int", "String", "boolean", + "def", "import", "from", "as", "try", "except", "finally", "with" + ) + + keywords.forEach { keyword -> + highlightedText = highlightedText.replace( + Regex("\\b$keyword\\b"), + "$keyword" + ) + } + + // String highlighting + highlightedText = highlightedText.replace( + Regex("\"([^\"]*)\"|'([^']*)'"), + "$0" + ) + + // Comment highlighting + highlightedText = highlightedText.replace( + Regex("//.*$", RegexOption.MULTILINE), + "$0" + ) + + // Use div instead of pre for better control over spacing + return "
$highlightedText
" + } + + private fun addKeyboardShortcuts(panel: JComponent, onAction: (PopupAction) -> Unit) { + println("DEBUG: Adding keyboard shortcuts to panel") + + // CRITICAL FIX: Disable focus traversal for Tab key + panel.setFocusTraversalKeysEnabled(false) + + val inputMap = panel.getInputMap(JComponent.WHEN_FOCUSED) + val actionMap = panel.actionMap + + // Add Tab key for accept + inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), "accept") + actionMap.put("accept", object : AbstractAction() { + override fun actionPerformed(e: ActionEvent?) { + println("DEBUG: Accept action triggered!") + onAction(PopupAction.ACCEPT) + } + }) + + // Add Esc key for reject + inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "reject") + actionMap.put("reject", object : AbstractAction() { + override fun actionPerformed(e: ActionEvent?) { + println("DEBUG: Reject action triggered!") + onAction(PopupAction.REJECT) + } + }) + + panel.isFocusable = true + + // Keep your existing debug listeners + panel.addFocusListener(object : java.awt.event.FocusListener { + override fun focusGained(e: java.awt.event.FocusEvent?) { + println("DEBUG: Panel gained focus") + } + override fun focusLost(e: java.awt.event.FocusEvent?) { + println("DEBUG: Panel lost focus") + } + }) + + panel.addKeyListener(object : java.awt.event.KeyListener { + override fun keyPressed(e: KeyEvent?) { + println("DEBUG: Key pressed: ${e?.keyCode} (Tab = ${KeyEvent.VK_TAB})") + } + override fun keyReleased(e: KeyEvent?) {} + override fun keyTyped(e: KeyEvent?) {} + }) + + panel.addHierarchyListener { e -> + if (e.changeFlags and java.awt.event.HierarchyEvent.SHOWING_CHANGED.toLong() != 0L) { + if (panel.isShowing) { + println("DEBUG: Panel is showing, requesting focus") + ApplicationManager.getApplication().invokeLater { + val focusResult = panel.requestFocusInWindow() + println("DEBUG: Focus request result: $focusResult") + } + } + } + } + } + + private fun renderDeletionDecorations( + editor: Editor, + oldCode: String, + newCode: String, + startLine: Int + ) { + // Clear any existing decorations first + clearAllDeletionDecorations() + + val diffChars = calculateCharDiff(oldCode, newCode) + + deletionHighlighters = diffChars.filter { it.type == "old" }.map { diff -> + val lineStartOffset = editor.document.getLineStartOffset(startLine + diff.oldLineIndex!!) + val startOffset = lineStartOffset + diff.oldCharIndexInLine!! + val endOffset = startOffset + diff.char.length + + editor.markupModel.addRangeHighlighter( + startOffset, + endOffset, + HighlighterLayer.SELECTION - 1, + TextAttributes().apply { + backgroundColor = JBColor.RED.brighter() + effectType = EffectType.STRIKEOUT + effectColor = JBColor.RED + }, + HighlighterTargetArea.EXACT_RANGE + ) + } + } + + private fun calculateCharDiff(oldCode: String, newCode: String): List { + // This is a simplified diff implementation + // For a production-ready solution, consider adding a proper diff library like java-diff-utils + + val result = mutableListOf() + + // Track indices as we process the diff + var oldIndex = 0 + var newIndex = 0 + var oldLineIndex = 0 + var newLineIndex = 0 + var oldCharIndexInLine = 0 + var newCharIndexInLine = 0 + + // Convert strings to character arrays for easier processing + val oldChars = oldCode.toCharArray() + val newChars = newCode.toCharArray() + + var i = 0 + var j = 0 + + // Simple longest common subsequence approach + while (i < oldChars.size || j < newChars.size) { + when { + i < oldChars.size && j < newChars.size && oldChars[i] == newChars[j] -> { + // Characters match - mark as "same" + val char = oldChars[i].toString() + + result.add(DiffChar( + type = "same", + char = char, + oldIndex = oldIndex, + newIndex = newIndex, + oldLineIndex = oldLineIndex, + newLineIndex = newLineIndex, + oldCharIndexInLine = oldCharIndexInLine, + newCharIndexInLine = newCharIndexInLine + )) + + // Update indices + oldIndex++ + newIndex++ + + if (char == "\n") { + oldLineIndex++ + newLineIndex++ + oldCharIndexInLine = 0 + newCharIndexInLine = 0 + } else { + oldCharIndexInLine++ + newCharIndexInLine++ + } + + i++ + j++ + } + + i < oldChars.size && (j >= newChars.size || shouldDeleteChar(oldChars, newChars, i, j)) -> { + // Character exists in old but not in new - mark as "old" + val char = oldChars[i].toString() + + result.add(DiffChar( + type = "old", + char = char, + oldIndex = oldIndex, + oldLineIndex = oldLineIndex, + oldCharIndexInLine = oldCharIndexInLine + )) + + // Update old indices only + oldIndex++ + if (char == "\n") { + oldLineIndex++ + oldCharIndexInLine = 0 + } else { + oldCharIndexInLine++ + } + + i++ + } + + j < newChars.size -> { + // Character exists in new but not in old - mark as "new" + val char = newChars[j].toString() + + result.add(DiffChar( + type = "new", + char = char, + newIndex = newIndex, + newLineIndex = newLineIndex, + newCharIndexInLine = newCharIndexInLine + )) + + // Update new indices only + newIndex++ + if (char == "\n") { + newLineIndex++ + newCharIndexInLine = 0 + } else { + newCharIndexInLine++ + } + + j++ + } + } + } + + return result + } + + // Helper function to determine if a character should be considered deleted + // This is a simplified heuristic - a proper diff algorithm would be more sophisticated + private fun shouldDeleteChar(oldChars: CharArray, newChars: CharArray, i: Int, j: Int): Boolean { + if (j >= newChars.size) return true + + // Look ahead a few characters to see if we can find a match + val lookAhead = minOf(5, oldChars.size - i, newChars.size - j) + for (k in 1..lookAhead) { + if (i + k < oldChars.size && oldChars[i] == newChars[j + k]) { + return false // Found a match ahead, so insert new chars first + } + if (j + k < newChars.size && oldChars[i + k] == newChars[j]) { + return true // Found a match ahead, so delete old char first + } + } + + return true // Default to deletion + } + + private fun acceptEdit( + editor: Editor, + newText: String, + startLine: Int, + endLine: Int, + isLineDelete: Boolean = false + ) { + println("DEBUG: acceptEdit called with:") + println(" newText: '$newText'") + println(" startLine: $startLine") + println(" endLine: $endLine") + println(" isLineDelete: $isLineDelete") + + isAccepted = true + hideAllNextEditWindows() + + try { + // Fix: Use the simpler WriteCommandAction.runWriteCommandAction + WriteCommandAction.runWriteCommandAction(project) { + println("DEBUG: Inside WriteCommandAction") + val document = editor.document + + // Validate line indices + val totalLines = document.lineCount + println("DEBUG: Total lines in document: $totalLines") + + if (startLine < 0 || startLine >= totalLines) { + println("ERROR: Invalid startLine $startLine (total lines: $totalLines)") + return@runWriteCommandAction + } + + if (endLine < 0 || endLine >= totalLines) { + println("ERROR: Invalid endLine $endLine (total lines: $totalLines)") + return@runWriteCommandAction + } + + if (isLineDelete) { + // Handle line deletion - include the newline character + val startOffset = document.getLineStartOffset(startLine) + var endOffset: Int + + // If this isn't the last line, extend to include the newline character + if (startLine < document.lineCount - 1) { + endOffset = document.getLineStartOffset(startLine + 1) + println("DEBUG: Line delete - including newline, endOffset: $endOffset") + } else { + // If it's the last line, just delete to end of line + endOffset = document.getLineEndOffset(startLine) + println("DEBUG: Line delete - last line, endOffset: $endOffset") + } + + println("DEBUG: Line deletion offsets:") + println(" startOffset: $startOffset") + println(" endOffset: $endOffset") + + val oldText = document.getText(TextRange(startOffset, endOffset)) + println("DEBUG: Deleting text: '$oldText'") + + // Delete the entire line including newline + document.deleteString(startOffset, endOffset) + println("DEBUG: Line deletion completed") + + } else { + // Handle normal text replacement + val startOffset = document.getLineStartOffset(startLine) + val endOffset = document.getLineEndOffset(endLine) + + println("DEBUG: Normal edit offsets:") + println(" startOffset: $startOffset") + println(" endOffset: $endOffset") + println(" document length: ${document.textLength}") + + if (startOffset < 0 || endOffset > document.textLength || startOffset > endOffset) { + println("ERROR: Invalid offsets - startOffset: $startOffset, endOffset: $endOffset, docLength: ${document.textLength}") + return@runWriteCommandAction + } + + // Show what we're replacing + val oldText = document.getText(TextRange(startOffset, endOffset)) + println("DEBUG: Replacing text:") + println(" Old: '$oldText'") + println(" New: '$newText'") + + // Perform the replacement + document.replaceString(startOffset, endOffset, newText) + println("DEBUG: Document replacement completed") + } + } + + println("DEBUG: WriteCommandAction completed successfully") + + } catch (e: Exception) { + println("ERROR: Exception in acceptEdit: ${e.message}") + e.printStackTrace() + } + + // Log acceptance (placeholder) + currentCompletionId?.let { + println("DEBUG: Would log acceptance for completion ID: $it") + // project.getService(NextEditService::class.java).acceptEdit(it) + } + + isAccepted = false + } + + private fun rejectEdit() { + hideAllNextEditWindows() + + // Log rejection and delete chain (placeholder) + currentCompletionId?.let { + // project.getService(NextEditService::class.java).rejectEdit(it) + } + } + + fun hideAllNextEditWindows() { + currentPopup?.let { popup -> + // Clear keyboard shortcuts before closing popup + val content = popup.content + if (content is JComponent) { + content.inputMap.clear() + content.actionMap.clear() + } + + popup.cancel() + currentPopup = null + } + + // Clear all deletion decorations without tracking editors + clearAllDeletionDecorations() + deletionHighlighters = emptyList() + } + + private fun clearAllDeletionDecorations() { + // Remove highlighters using their dispose method - they know which editor they belong to + deletionHighlighters.forEach { highlighter -> + try { + highlighter.dispose() + } catch (e: Exception) { + // Highlighter might already be disposed, ignore + } + } + } + + fun hasAccepted(): Boolean = isAccepted + + fun setAccepted(accepted: Boolean) { + isAccepted = accepted + } + + fun updateCurrentCompletionId(completionId: String) { + currentCompletionId = completionId + } + + fun cleanup() { + hideAllNextEditWindows() + currentCompletionId = null + } + + fun registerSelectionChangeHandler() { + val selectionManager = project.getService(SelectionChangeManager::class.java) + + selectionManager.registerListener( + "nextEditWindowManager", + { event, state -> + handleSelectionChange(event, state) + }, + HandlerPriority.HIGH + ) + } + + private suspend fun handleSelectionChange( + event: SelectionEvent, + state: StateSnapshot + ): Boolean { + // If window was just accepted, preserve the chain + if (state.nextEditWindowAccepted) { + println("Next edit window accepted, preserving chain") + return true + } + + return false + } +} + +enum class PopupAction { + ACCEPT, + REJECT +} + +data class DiffChar( + val type: String, // "old", "new", "same" + val char: String, + val oldIndex: Int? = null, // Character index assuming a flattened line string + val newIndex: Int? = null, + val oldLineIndex: Int? = null, // Line index + val newLineIndex: Int? = null, + val oldCharIndexInLine: Int? = null, // Character index within the line + val newCharIndexInLine: Int? = null +) \ No newline at end of file From 87a6bccbbe0b9d5041fee58dbe4acca65e4c42cc Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 12 Aug 2025 20:41:32 -0700 Subject: [PATCH 13/48] feat: add necessary types --- .../nextEdit/types.kt | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/types.kt diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/types.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/types.kt new file mode 100644 index 000000000..391fa0b73 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/types.kt @@ -0,0 +1,68 @@ +package com.github.continuedev.continueintellijextension.nextEdit + +import com.github.continuedev.continueintellijextension.Position + +//data class NextEditOutcome( +// val completion: String, +// val diffLines: List, +// val editableRegionStartLine: Int, +// val editableRegionEndLine: Int, +// val oldCode: String, +// val newCode: String +//) + +data class DiffLine( + val type: String, // "old", "new", "same" + val line: String +) + +data class NextEditOutcome( + // Fields from TabAutocompleteOptions + val disable: Boolean, + val maxPromptTokens: Int, + val debounceDelay: Int, + val maxSuffixPercentage: Int, + val prefixPercentage: Int, + val transform: Boolean?, + val template: String?, + val multilineCompletions: String, // "always" | "never" | "auto" + val slidingWindowPrefixPercentage: Int, + val slidingWindowSize: Int, + val useCache: Boolean, + val onlyMyCode: Boolean, + val useRecentlyEdited: Boolean, + val disableInFiles: List?, + val useImports: Boolean?, + val showWhateverWeHaveAtXMs: Int?, + + // Originally from Autocomplete (commented fields would be nullable if needed) + val elapsed: Long, + val modelProvider: String, + val modelName: String, + val completionOptions: Any, // Using Any since TypeScript uses 'any' + val completionId: String, + val gitRepo: String?, + val uniqueId: String, + val timestamp: Long, + + // New for Next Edit + val fileUri: String, + val workspaceDirUri: String, + val prompt: String, + val userEdits: String, + val userExcerpts: String, + val originalEditableRange: String, + val completion: String, + val cursorPosition: Position, + val finalCursorPosition: Position, + val accepted: Boolean?, + val editableRegionStartLine: Int, + val editableRegionEndLine: Int, + val diffLines: List +) + +enum class DiffLineType { + NEW, + OLD, + SAME +} \ No newline at end of file From 93cf740699c4b2769a5da05c67c4a816a8f9a2db Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 12 Aug 2025 20:41:54 -0700 Subject: [PATCH 14/48] feat: add next edit services --- extensions/intellij/src/main/resources/META-INF/plugin.xml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index bcb524f1f..6376821e9 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -25,6 +25,13 @@ + + + + Date: Tue, 12 Aug 2025 21:20:45 -0700 Subject: [PATCH 15/48] feat: add util for manually invoking inline completion' --- .../utils/InlineCompletionUtils.kt | 133 ++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/InlineCompletionUtils.kt diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/InlineCompletionUtils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/InlineCompletionUtils.kt new file mode 100644 index 000000000..cf64183fc --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/InlineCompletionUtils.kt @@ -0,0 +1,133 @@ +package com.github.continuedev.continueintellijextension.utils + +import com.intellij.openapi.actionSystem.ActionManager +import com.intellij.openapi.actionSystem.AnActionEvent +import com.intellij.openapi.actionSystem.CommonDataKeys +import com.intellij.openapi.actionSystem.impl.SimpleDataContext +import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.editor.Editor +import com.intellij.openapi.project.Project + +object InlineCompletionUtils { + /** + * Triggers inline completion for the given editor. + * This is equivalent to pressing Shift+Alt+Backslash or calling the "Generate Inline Completion" action. + * Always executes on the EDT to avoid threading issues. + * + * @param editor The editor to trigger completion for + * @param project The project context (optional, will be inferred from editor if null) + * @param callback Optional callback to receive the result (called on EDT) + */ + fun triggerInlineCompletion( + editor: Editor, + project: Project? = null, + callback: ((Boolean) -> Unit)? = null + ) { + val application = ApplicationManager.getApplication() + + if (application.isDispatchThread) { + // Already on EDT, execute directly + val result = performTrigger(editor, project) + callback?.invoke(result) + } else { + // Not on EDT, invoke later + application.invokeLater { + val result = performTrigger(editor, project) + callback?.invoke(result) + } + } + } + + /** + * Synchronous version that blocks until completion is triggered (use carefully). + * Only use this if you're already on the EDT or in a context where blocking is acceptable. + * + * @param editor The editor to trigger completion for + * @param project The project context (optional, will be inferred from editor if null) + * @return true if the action was found and executed, false otherwise + */ + fun triggerInlineCompletionSync(editor: Editor, project: Project? = null): Boolean { + val application = ApplicationManager.getApplication() + + return if (application.isDispatchThread) { + performTrigger(editor, project) + } else { + var result = false + application.invokeAndWait { + result = performTrigger(editor, project) + } + result + } + } + + /** + * Triggers inline completion with a delay. + * Useful for scenarios where you want to trigger completion after some processing. + * + * @param editor The editor to trigger completion for + * @param delayMs Delay in milliseconds before triggering + * @param project The project context (optional, will be inferred from editor if null) + * @param callback Optional callback to receive the result (called on EDT after trigger) + */ + fun triggerInlineCompletionDelayed( + editor: Editor, + delayMs: Long = 2000, + project: Project? = null, + callback: ((Boolean) -> Unit)? = null + ) { + ApplicationManager.getApplication().executeOnPooledThread { + Thread.sleep(delayMs) + triggerInlineCompletion(editor, project, callback) + } + } + + /** + * Internal method that performs the actual trigger logic. + * Must be called on the EDT. + */ + private fun performTrigger(editor: Editor, project: Project?): Boolean { + return try { + println("performTrigger called on EDT: ${ApplicationManager.getApplication().isDispatchThread}") + + val actionManager = ActionManager.getInstance() + val action = actionManager.getAction("CallInlineCompletionAction") + + if (action != null) { + println("Found CallInlineCompletionAction, checking if enabled...") + + val effectiveProject = project ?: editor.project + val dataContext = SimpleDataContext.builder() + .add(CommonDataKeys.EDITOR, editor) + .add(CommonDataKeys.PROJECT, effectiveProject) + .build() + + val event = AnActionEvent.createFromDataContext( + "ProgrammaticInlineCompletion", + null, + dataContext + ) + + // Check if action is enabled before performing it + action.update(event) + val isEnabled = event.presentation.isEnabled + println("Action enabled: $isEnabled") + + if (isEnabled) { + action.actionPerformed(event) + println("Action performed successfully") + true + } else { + println("Action is disabled, not performing") + false + } + } else { + println("CallInlineCompletionAction not found!") + false + } + } catch (e: Exception) { + println("Exception in performTrigger: ${e.message}") + e.printStackTrace() + false + } + } +} \ No newline at end of file From e66a19cfba078372ce0d7df28e6dd10e126e4059 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 13 Aug 2025 15:56:39 -0700 Subject: [PATCH 16/48] feat: handle three cases, refactor to helper methods in NextEditService --- .../ContinueInlineCompletionProvider.kt | 123 +++++++++--------- 1 file changed, 65 insertions(+), 58 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt index 490ac8590..103ade903 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt @@ -2,18 +2,13 @@ package com.github.continuedev.continueintellijextension.autocomplete import com.github.continuedev.continueintellijextension.FimResult import com.github.continuedev.continueintellijextension.Position +import com.github.continuedev.continueintellijextension.nextEdit.NextEditJumpManager import com.github.continuedev.continueintellijextension.nextEdit.NextEditService import com.github.continuedev.continueintellijextension.nextEdit.NextEditUtils import com.github.continuedev.continueintellijextension.nextEdit.NextEditWindowManager import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.utils.uuid -import com.intellij.codeInsight.inline.completion.DefaultInlineCompletionInsertHandler -import com.intellij.codeInsight.inline.completion.InlineCompletionEvent -import com.intellij.codeInsight.inline.completion.InlineCompletionInsertEnvironment -import com.intellij.codeInsight.inline.completion.InlineCompletionInsertHandler -import com.intellij.codeInsight.inline.completion.InlineCompletionProvider -import com.intellij.codeInsight.inline.completion.InlineCompletionProviderID -import com.intellij.codeInsight.inline.completion.InlineCompletionRequest +import com.intellij.codeInsight.inline.completion.* import com.intellij.codeInsight.inline.completion.elements.InlineCompletionElement import com.intellij.codeInsight.inline.completion.elements.InlineCompletionGrayTextElement import com.intellij.codeInsight.inline.completion.suggestion.InlineCompletionSuggestion @@ -43,67 +38,79 @@ class ContinueInlineCompletionProvider : InlineCompletionProvider { val isNextEditSupported = NextEditUtils.isNextEditSupported(project) if (isNextEditSupported) { + isUsingNextEdit = true + val nextEditService = project.service() + val nextEditJumpManager = project.service() + val currCursorPos = Pair( editor.caretModel.primaryCaret.logicalPosition.line, editor.caretModel.primaryCaret.logicalPosition.column ) - // Use Next Edit - but don't return inline completion for it - val nextEditService = project.service() - val nextEditOutcome = nextEditService.getNextEditSuggestion( - lastUuid!!, - editor.virtualFile.url, - currCursorPos.first, - currCursorPos.second + + val isJumping = nextEditJumpManager.isJumpInProgress() + val chainExists = nextEditService.chainExists() + val nextEditOutcome = when { + isJumping && chainExists -> nextEditService.handleCase2() // Case 2: Jumping (chain exists, jump was taken). + chainExists -> nextEditService.handleCase3( + editor, + currCursorPos + ) // Case 3: Accepting next edit outcome (chain exists, jump is not taken). + else -> nextEditService.handleCase1( + request, + editor, + currCursorPos, + lastUuid + ) // Case 1: Typing (chain does not exist). + } + + if (nextEditOutcome == null) { + return InlineCompletionSuggestion.Empty + } + + val editableRegionStartLine = nextEditOutcome.editableRegionStartLine + val editableRegionEndLine = nextEditOutcome.editableRegionEndLine + val oldEditRangeSlice = editor.document.text + .split("\n") + .drop(editableRegionStartLine) + .take(editableRegionEndLine - editableRegionStartLine + 1) + .joinToString("\n") + + // Check if it's a FIM (Fill-In-Middle) operation + val fimResult = NextEditUtils.checkFim( + oldEditRangeSlice, // Use the extracted slice instead of nextEditOutcome.oldCode + nextEditOutcome.completion, + currCursorPos ) - if (nextEditOutcome != null) { - val editableRegionStartLine = nextEditOutcome.editableRegionStartLine - val editableRegionEndLine = nextEditOutcome.editableRegionEndLine - val oldEditRangeSlice = editor.document.text - .split("\n") - .drop(editableRegionStartLine) - .take(editableRegionEndLine - editableRegionStartLine + 1) - .joinToString("\n") - - // Check if it's a FIM (Fill-In-Middle) operation - val fimResult = NextEditUtils.checkFim( - oldEditRangeSlice, // Use the extracted slice instead of nextEditOutcome.oldCode - nextEditOutcome.completion, - currCursorPos - ) - - when (fimResult) { - is FimResult.FimEdit -> { - // Render as gray text inline completion - isUsingNextEdit = true - return object : InlineCompletionSuggestion { - override suspend fun getVariants(): List { - val completion = InlineCompletionVariant.build( - request.file.virtualFile, - flow { emit(InlineCompletionGrayTextElement(fimResult.fimText)) } - ) - return listOf(completion) - } + when (fimResult) { + is FimResult.FimEdit -> { + // Render as gray text inline completion + return object : InlineCompletionSuggestion { + override suspend fun getVariants(): List { + val completion = InlineCompletionVariant.build( + request.file.virtualFile, + flow { emit(InlineCompletionGrayTextElement(fimResult.fimText)) } + ) + return listOf(completion) } } - is FimResult.NotFimEdit -> { - // For non-FIM operations, show custom UI and return empty - val nextEditWindowManager = project.service() - isUsingNextEdit = true - nextEditWindowManager.showNextEditWindow( - editor, - Position(currCursorPos.first, currCursorPos.second), - editableRegionStartLine, - editableRegionEndLine, - oldEditRangeSlice, - nextEditOutcome.completion, - nextEditOutcome.diffLines, - ) - return InlineCompletionSuggestion.Empty - } + } + + is FimResult.NotFimEdit -> { + // For non-FIM operations, show custom UI and return empty + val nextEditWindowManager = project.service() + nextEditWindowManager.showNextEditWindow( + editor, + Position(currCursorPos.first, currCursorPos.second), + editableRegionStartLine, + editableRegionEndLine, + oldEditRangeSlice, + nextEditOutcome.completion, + nextEditOutcome.diffLines, + ) + return InlineCompletionSuggestion.Empty } } - return InlineCompletionSuggestion.Empty } else { // Use traditional autocomplete val variant = project.service().getAutocomplete( From cf61261abc2b5edfdf233fe9e5c60223b93742cd Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 13 Aug 2025 15:57:09 -0700 Subject: [PATCH 17/48] feat: add helper methods to handle three cases, add more processing helpers --- .../nextEdit/NextEditService.kt | 214 ++++++++++++++++-- 1 file changed, 196 insertions(+), 18 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditService.kt index a03ee47bb..516ac3bd7 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditService.kt @@ -3,8 +3,10 @@ package com.github.continuedev.continueintellijextension.nextEdit import com.github.continuedev.continueintellijextension.Position import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger import com.github.continuedev.continueintellijextension.services.ContinuePluginService +import com.intellij.codeInsight.inline.completion.InlineCompletionRequest import com.intellij.openapi.components.Service import com.intellij.openapi.components.service +import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.LogicalPosition import com.intellij.openapi.project.Project import kotlinx.coroutines.suspendCancellableCoroutine @@ -21,10 +23,20 @@ interface NextEditService { withChain: Boolean = false, usingFullFileDiff: Boolean = true ): NextEditOutcome? + + suspend fun handleCase1( + request: InlineCompletionRequest, + editor: Editor, + currCursorPos: Pair, + lastUuid: String? + ): NextEditOutcome? + + suspend fun handleCase2(): NextEditOutcome? + suspend fun handleCase3(editor: Editor, currentCursorPos: Pair): NextEditOutcome? fun startChain() fun deleteChain() - fun chainExists(): Boolean - fun getNextInChain(): NextEditItem? + suspend fun chainExists(): Boolean + suspend fun getNextInChain(): ProcessedItem? fun markDisplayed(completionId: String, outcome: NextEditOutcome) fun acceptEdit(completionId: String) fun rejectEdit(completionId: String) @@ -32,13 +44,111 @@ interface NextEditService { @Service(Service.Level.PROJECT) class ContinueNextEditService(private val project: Project) : NextEditService { - - private var currentChain: NextEditChain? = null private val displayedCompletions = mutableMapOf() private val coreMessenger: CoreMessenger? get() = project.service().coreMessenger + // Case 1: Typing (chain does not exist). + override suspend fun handleCase1( + request: InlineCompletionRequest, + editor: Editor, + currCursorPos: Pair, + lastUuid: String? + ): NextEditOutcome? { + println("Case 1: Typing (chain does not exist)") + + // Start a new chain + startChain() + + val nextEditOutcome = this.getNextEditSuggestion( + lastUuid!!, + editor.virtualFile.url, + currCursorPos.first, + currCursorPos.second + ) + + // TODO: Check once and if null, invoke inline completion trigger once more + + return nextEditOutcome + } + + // Case 2: Jumping (chain exists, jump was taken). + override suspend fun handleCase2(): NextEditOutcome? { + println("Case 2: Jumping (chain exists, jump was taken)") + + val jumpManager = project.service() + + // Reset jump state + jumpManager.setJumpInProgress(false) + + // Use the saved completion from JumpManager instead of making new request + val savedCompletion = jumpManager.getSavedCompletionAfterJump() + if (savedCompletion != null) { + val (_, outcome) = savedCompletion + jumpManager.clearSavedCompletionAfterJump() + return outcome + } else { + // This technically should not happen according to the TypeScript comment + println("Error: No saved completion found after jump was taken") + return null + } + } + + // Case 3: Accepting next edit outcome (chain exists, jump is not taken). + override suspend fun handleCase3(editor: Editor, currentCursorPos: Pair): NextEditOutcome? { + println("Case 3: Accepting next edit outcome (chain exists, jump is not taken)") + + val jumpManager = project.service() + + // Try suggesting jump for each location in the chain + var isJumpSuggested = false + + while (chainExists() && !isJumpSuggested) { + val nextItemInChain = getNextInChain() + if (nextItemInChain == null) { + println("No more items in chain") + break + } + + val nextLocation = nextItemInChain.location + val outcome = nextItemInChain.outcome + + val currentPosition = LogicalPosition(currentCursorPos.first, currentCursorPos.second) + val nextPosition = LogicalPosition(nextLocation.range.start.line, nextLocation.range.start.character) + + isJumpSuggested = jumpManager.suggestJump( + editor, + currentPosition, + nextPosition, + outcome.completion + ) + + if (isJumpSuggested) { + // Store completion to be rendered after a jump + jumpManager.setCompletionAfterJump( + CompletionDataForAfterJump( + completionId = outcome.completionId, + outcome = outcome, + position = nextPosition + ) + ) + + // Don't display anything yet. + // This will be handled in Case 2. + return null + } + } + + if (!isJumpSuggested) { + println("No suitable jump location found after trying all positions") + deleteChain() + return null + } + + return null + } + override suspend fun getNextEditSuggestion( completionId: String, filepath: String, @@ -72,19 +182,32 @@ class ContinueNextEditService(private val project: Project) : NextEditService { } override fun startChain() { - currentChain = NextEditChain() + // Remove local chain creation coreMessenger?.request("nextEdit/startChain", emptyMap(), null) {} } override fun deleteChain() { - currentChain = null + // Remove local chain deletion coreMessenger?.request("nextEdit/deleteChain", emptyMap(), null) {} } - override fun chainExists(): Boolean = currentChain != null + override suspend fun chainExists(): Boolean { + return suspendCancellableCoroutine { continuation -> + coreMessenger?.request("nextEdit/isChainAlive", emptyMap(), null) { response -> + val exists = parseChainExistsResponse(response) + continuation.resume(exists) + } + } + } - override fun getNextInChain(): NextEditItem? { - return currentChain?.getNext() + override suspend fun getNextInChain(): ProcessedItem? { + return suspendCancellableCoroutine { continuation -> + coreMessenger?.request("nextEdit/queue/dequeueProcessed", emptyMap(), null) { response -> + val processedItem = parseProcessedItem(response) +// val nextEditItem = processedItem?.let { convertToNextEditItem(it) } + continuation.resume(processedItem) + } + } } override fun markDisplayed(completionId: String, outcome: NextEditOutcome) { @@ -107,6 +230,15 @@ class ContinueNextEditService(private val project: Project) : NextEditService { val responseMap = response as? Map ?: return null val contentMap = responseMap["content"] as? Map ?: return null + parseNextEditOutcomeFromMap(contentMap) + } catch (e: Exception) { + println("Error parsing Next Edit outcome: ${e.message}") + null + } + } + + private fun parseNextEditOutcomeFromMap(contentMap: Map): NextEditOutcome? { + return try { // Extract position data val cursorPos = contentMap["cursorPosition"] as? Map val cursorPosition = if (cursorPos != null) { @@ -183,20 +315,66 @@ class ContinueNextEditService(private val project: Project) : NextEditService { diffLines = diffLines ) } catch (e: Exception) { - println("Error parsing Next Edit outcome: ${e.message}") + println("Error parsing NextEditOutcome from map: ${e.message}") null } } + + private fun parseProcessedItem(response: Any?): ProcessedItem? { + return try { + val responseMap = response as? Map ?: return null + val content = responseMap["content"] as Map ?: return null + + // Parse location (RangeInFile) + val locationMap = content["location"] as? Map ?: return null + val filepath = locationMap["filepath"] as? String ?: return null + + val rangeMap = locationMap["range"] as? Map ?: return null + val startMap = rangeMap["start"] as? Map ?: return null + val endMap = rangeMap["end"] as? Map ?: return null + + val startPosition = Position( + line = (startMap["line"] as? Number)?.toInt() ?: 0, + character = (startMap["character"] as? Number)?.toInt() ?: 0 + ) + + val endPosition = Position( + line = (endMap["line"] as? Number)?.toInt() ?: 0, + character = (endMap["character"] as? Number)?.toInt() ?: 0 + ) + + val range = com.github.continuedev.continueintellijextension.Range(startPosition, endPosition) + val location = com.github.continuedev.continueintellijextension.RangeInFile(filepath, range) + + // Parse outcome (NextEditOutcome) - reuse existing logic from parseNextEditOutcome + val outcomeData = content["outcome"] as? Map ?: return null + val outcome = parseNextEditOutcomeFromMap(outcomeData) ?: return null + + ProcessedItem(location, outcome) + } catch (e: Exception) { + println("Error parsing ProcessedItem: ${e.message}") + null + } + } + + private fun parseChainExistsResponse(response: Any?): Boolean { + return try { + val responseMap = response as? Map ?: return false + val content = responseMap["content"] ?: return false + content as? Boolean ?: false + } catch (e: Exception) { + println("Error parsing chain exists response: ${e.message}") + false + } + } + + private fun convertToNextEditItem(processedItem: ProcessedItem): NextEditItem { + // Convert ProcessedItem from core to NextEditItem for JetBrains + // Implementation depends on ProcessedItem structure + TODO("Implement conversion from ProcessedItem to NextEditItem") + } } -data class NextEditChain( - private val items: MutableList = mutableListOf() -) { - fun getNext(): NextEditItem? = items.removeFirstOrNull() - fun add(item: NextEditItem) = items.add(item) - fun isEmpty(): Boolean = items.isEmpty() - fun size(): Int = items.size -} data class NextEditItem( val outcome: NextEditOutcome, From 42d882fe54986f7cb954e7f6916e258d653a1bab Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 13 Aug 2025 15:57:40 -0700 Subject: [PATCH 18/48] feat: change color to something more tolerable --- .../nextEdit/NextEditWindowManager.kt | 87 ++++++++++--------- 1 file changed, 47 insertions(+), 40 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt index 8b18486bf..7300cb0a3 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt @@ -4,6 +4,7 @@ import com.github.continuedev.continueintellijextension.Position import com.github.continuedev.continueintellijextension.listeners.HandlerPriority import com.github.continuedev.continueintellijextension.listeners.SelectionChangeManager import com.github.continuedev.continueintellijextension.listeners.StateSnapshot +import com.github.continuedev.continueintellijextension.utils.InlineCompletionUtils import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.components.Service @@ -11,11 +12,7 @@ import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.colors.EditorFontType import com.intellij.openapi.editor.event.SelectionEvent -import com.intellij.openapi.editor.markup.EffectType -import com.intellij.openapi.editor.markup.HighlighterLayer -import com.intellij.openapi.editor.markup.HighlighterTargetArea -import com.intellij.openapi.editor.markup.RangeHighlighter -import com.intellij.openapi.editor.markup.TextAttributes +import com.intellij.openapi.editor.markup.* import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopup import com.intellij.openapi.ui.popup.JBPopupFactory @@ -25,15 +22,9 @@ import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBPanel import com.intellij.util.ui.JBUI import java.awt.BorderLayout -import java.awt.FlowLayout import java.awt.event.ActionEvent import java.awt.event.KeyEvent -import javax.swing.AbstractAction -import javax.swing.BoxLayout -import javax.swing.JComponent -import javax.swing.JLabel -import javax.swing.JScrollPane -import javax.swing.KeyStroke +import javax.swing.* @Service(Service.Level.PROJECT) class NextEditWindowManager(private val project: Project) { @@ -85,6 +76,7 @@ class NextEditWindowManager(private val project: Project) { editableRegionEndLine, isLineDelete ) + PopupAction.REJECT -> rejectEdit() } } @@ -241,6 +233,7 @@ class NextEditWindowManager(private val project: Project) { background = JBColor(0x2D4A2D, 0x2D4A2D) // Darker green foreground = scheme.defaultForeground } + else -> { // "same" or any other type // Regular unchanged lines background = scheme.defaultBackground @@ -323,7 +316,9 @@ class NextEditWindowManager(private val project: Project) { } private fun createBasicHighlightedHtml(text: String, font: java.awt.Font): String { - if (text.trim().isEmpty()) return "
 
" + if (text.trim() + .isEmpty() + ) return "
 
" // Basic syntax highlighting patterns (you can extend this) var highlightedText = text @@ -397,6 +392,7 @@ class NextEditWindowManager(private val project: Project) { override fun focusGained(e: java.awt.event.FocusEvent?) { println("DEBUG: Panel gained focus") } + override fun focusLost(e: java.awt.event.FocusEvent?) { println("DEBUG: Panel lost focus") } @@ -406,6 +402,7 @@ class NextEditWindowManager(private val project: Project) { override fun keyPressed(e: KeyEvent?) { println("DEBUG: Key pressed: ${e?.keyCode} (Tab = ${KeyEvent.VK_TAB})") } + override fun keyReleased(e: KeyEvent?) {} override fun keyTyped(e: KeyEvent?) {} }) @@ -444,9 +441,10 @@ class NextEditWindowManager(private val project: Project) { endOffset, HighlighterLayer.SELECTION - 1, TextAttributes().apply { - backgroundColor = JBColor.RED.brighter() + backgroundColor = + JBColor.namedColor("Editor.DiffDeletedLines.background", JBColor(0xFFE6E6, 0x484A4A)) effectType = EffectType.STRIKEOUT - effectColor = JBColor.RED + effectColor = JBColor.namedColor("Editor.DiffDeletedLines.border", JBColor(0xD32F2F, 0xB71C1C)) }, HighlighterTargetArea.EXACT_RANGE ) @@ -481,16 +479,18 @@ class NextEditWindowManager(private val project: Project) { // Characters match - mark as "same" val char = oldChars[i].toString() - result.add(DiffChar( - type = "same", - char = char, - oldIndex = oldIndex, - newIndex = newIndex, - oldLineIndex = oldLineIndex, - newLineIndex = newLineIndex, - oldCharIndexInLine = oldCharIndexInLine, - newCharIndexInLine = newCharIndexInLine - )) + result.add( + DiffChar( + type = "same", + char = char, + oldIndex = oldIndex, + newIndex = newIndex, + oldLineIndex = oldLineIndex, + newLineIndex = newLineIndex, + oldCharIndexInLine = oldCharIndexInLine, + newCharIndexInLine = newCharIndexInLine + ) + ) // Update indices oldIndex++ @@ -514,13 +514,15 @@ class NextEditWindowManager(private val project: Project) { // Character exists in old but not in new - mark as "old" val char = oldChars[i].toString() - result.add(DiffChar( - type = "old", - char = char, - oldIndex = oldIndex, - oldLineIndex = oldLineIndex, - oldCharIndexInLine = oldCharIndexInLine - )) + result.add( + DiffChar( + type = "old", + char = char, + oldIndex = oldIndex, + oldLineIndex = oldLineIndex, + oldCharIndexInLine = oldCharIndexInLine + ) + ) // Update old indices only oldIndex++ @@ -538,13 +540,15 @@ class NextEditWindowManager(private val project: Project) { // Character exists in new but not in old - mark as "new" val char = newChars[j].toString() - result.add(DiffChar( - type = "new", - char = char, - newIndex = newIndex, - newLineIndex = newLineIndex, - newCharIndexInLine = newCharIndexInLine - )) + result.add( + DiffChar( + type = "new", + char = char, + newIndex = newIndex, + newLineIndex = newLineIndex, + newCharIndexInLine = newCharIndexInLine + ) + ) // Update new indices only newIndex++ @@ -672,7 +676,10 @@ class NextEditWindowManager(private val project: Project) { } println("DEBUG: WriteCommandAction completed successfully") - + InlineCompletionUtils.triggerInlineCompletion( + editor, + project + ) { success -> println("invocation: $success") } } catch (e: Exception) { println("ERROR: Exception in acceptEdit: ${e.message}") e.printStackTrace() From af6779c3ca49940e450bd62f02a42b2885172e7a Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 13 Aug 2025 15:57:52 -0700 Subject: [PATCH 19/48] feat: add more types --- .../continueintellijextension/nextEdit/types.kt | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/types.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/types.kt index 391fa0b73..98d304cae 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/types.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/types.kt @@ -1,6 +1,7 @@ package com.github.continuedev.continueintellijextension.nextEdit import com.github.continuedev.continueintellijextension.Position +import com.github.continuedev.continueintellijextension.RangeInFile //data class NextEditOutcome( // val completion: String, @@ -65,4 +66,9 @@ enum class DiffLineType { NEW, OLD, SAME -} \ No newline at end of file +} + +data class ProcessedItem( + val location: RangeInFile, + val outcome: NextEditOutcome +) \ No newline at end of file From f9c091aeddd9cf3e6239a3d91d0c4fc4d069d7e6 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 13 Aug 2025 15:58:07 -0700 Subject: [PATCH 20/48] feat: add jump manager to keep track of jumping in intellij --- .../nextEdit/NextEditJumpManager.kt | 440 ++++++++++++++++++ 1 file changed, 440 insertions(+) create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt new file mode 100644 index 000000000..5149961aa --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt @@ -0,0 +1,440 @@ +package com.github.continuedev.continueintellijextension.nextEdit + +import com.github.continuedev.continueintellijextension.listeners.HandlerPriority +import com.github.continuedev.continueintellijextension.listeners.SelectionChangeManager +import com.github.continuedev.continueintellijextension.listeners.StateSnapshot +import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.components.Service +import com.intellij.openapi.editor.Editor +import com.intellij.openapi.editor.LogicalPosition +import com.intellij.openapi.editor.ScrollType +import com.intellij.openapi.editor.event.SelectionEvent +import com.intellij.openapi.editor.markup.HighlighterLayer +import com.intellij.openapi.editor.markup.HighlighterTargetArea +import com.intellij.openapi.editor.markup.RangeHighlighter +import com.intellij.openapi.editor.markup.TextAttributes +import com.intellij.openapi.project.Project +import com.intellij.openapi.ui.popup.JBPopup +import com.intellij.openapi.ui.popup.JBPopupFactory +import com.intellij.openapi.util.TextRange +import com.intellij.ui.JBColor +import com.intellij.ui.components.JBLabel +import com.intellij.ui.components.JBPanel +import com.intellij.util.ui.JBUI +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import java.awt.BorderLayout +import java.awt.Point +import java.awt.event.ActionEvent +import java.awt.event.KeyEvent +import javax.swing.AbstractAction +import javax.swing.JComponent +import javax.swing.KeyStroke +import javax.swing.SwingUtilities + +data class CompletionDataForAfterJump( + val completionId: String, + val outcome: NextEditOutcome, + val position: LogicalPosition +) + +@Service(Service.Level.PROJECT) +class NextEditJumpManager(private val project: Project) { + + private val coroutineScope = CoroutineScope(Dispatchers.Main) + + // State management + private var jumpState = JumpState() + + // UI components + private var jumpPopup: JBPopup? = null + private var editorHighlighter: RangeHighlighter? = null + private var keyboardShortcutsPanel: JComponent? = null + + // Callbacks + private var triggerInlineSuggestCallback: (() -> Unit)? = null + private var deleteChainCallback: (() -> Unit)? = null + + private data class JumpState( + val inProgress: Boolean = false, + val justAccepted: Boolean = false, + val jumpPosition: LogicalPosition? = null, + val editor: Editor? = null, + val oldCursorPosition: LogicalPosition? = null, + val completionAfterJump: CompletionDataForAfterJump? = null + ) + + init { + registerSelectionChangeHandler() + } + + // Public API + fun isJumpInProgress(): Boolean = jumpState.inProgress + + fun setJumpInProgress(jumpInProgress: Boolean) { + jumpState = jumpState.copy(inProgress = jumpInProgress) + } + + fun wasJumpJustAccepted(): Boolean = jumpState.justAccepted + + fun setTriggerInlineSuggestCallback(callback: () -> Unit) { + triggerInlineSuggestCallback = callback + } + + fun setDeleteChainCallback(callback: () -> Unit) { + deleteChainCallback = callback + } + + fun setCompletionAfterJump(completionData: CompletionDataForAfterJump) { + jumpState = jumpState.copy(completionAfterJump = completionData) + } + + fun clearSavedCompletionAfterJump() { + jumpState = jumpState.copy(completionAfterJump = null) + } + + fun getSavedCompletionAfterJump(): CompletionDataForAfterJump? = jumpState.completionAfterJump + + // Main entry point + suspend fun suggestJump( + editor: Editor, + currentPosition: LogicalPosition, + nextJumpLocation: LogicalPosition, + completionContent: String? = null + ): Boolean { + // Skip if content is identical at jump location + if (completionContent != null && + isContentIdentical(editor, nextJumpLocation, completionContent) + ) { + println("Skipping jump as content is identical at jump location") + return false + } + + println("Suggesting jump from line ${currentPosition.line} to line ${nextJumpLocation.line}") + + // Update state + jumpState = jumpState.copy( + inProgress = true, + jumpPosition = nextJumpLocation, + editor = editor, + oldCursorPosition = currentPosition + ) + + // Show UI + showJumpDecoration(editor, nextJumpLocation) + + // Scroll to show jump location + editor.scrollingModel.scrollTo(nextJumpLocation, ScrollType.CENTER) + + return true + } + + // Private implementation + private fun showJumpDecoration(editor: Editor, position: LogicalPosition) { + clearJumpDecoration() + + // Add editor highlight + val markupModel = editor.markupModel + val lineStartOffset = editor.document.getLineStartOffset(position.line) + val lineEndOffset = editor.document.getLineEndOffset(position.line) + + editorHighlighter = markupModel.addRangeHighlighter( + lineStartOffset, + lineEndOffset, + HighlighterLayer.SELECTION - 1, + TextAttributes().apply { + backgroundColor = JBColor.namedColor("InfoPopup.background", JBColor(0xE6F3FF, 0x2D3142)) + }, + HighlighterTargetArea.LINES_IN_RANGE + ) + + // Show popup with keyboard shortcuts + showJumpPopup(editor, position) + } + + private fun showJumpPopup(editor: Editor, position: LogicalPosition) { + val popupComponent = createJumpPopupComponent() + + jumpPopup = JBPopupFactory.getInstance() + .createComponentPopupBuilder(popupComponent, popupComponent) // Set focus component + .setFocusable(true) + .setRequestFocus(true) + .setResizable(false) + .setMovable(false) + .setCancelOnClickOutside(false) + .setCancelOnWindowDeactivation(false) + .setCancelKeyEnabled(false) // Disable default Esc handling to use our custom one + .setCancelCallback { + rejectJump() + true + } + .createPopup() + + // Show popup and ensure focus + ApplicationManager.getApplication().invokeLater { + try { + val lineEndOffset = editor.document.getLineEndOffset(position.line) + val lineEndPoint = editor.offsetToXY(lineEndOffset) + val editorComponent = editor.contentComponent + val screenPoint = Point(lineEndPoint.x + 20, lineEndPoint.y) + SwingUtilities.convertPointToScreen(screenPoint, editorComponent) + + jumpPopup?.showInScreenCoordinates(editorComponent, screenPoint) + + // Force focus after popup is shown + ApplicationManager.getApplication().invokeLater { + popupComponent.requestFocusInWindow() + println("DEBUG: Jump popup shown and focus requested") + } + } catch (e: Exception) { + jumpPopup?.showInBestPositionFor(editor) + ApplicationManager.getApplication().invokeLater { + popupComponent.requestFocusInWindow() + } + } + } + } + + private fun createJumpPopupComponent(): JComponent { + val panel = JBPanel>().apply { + layout = BorderLayout() + border = JBUI.Borders.empty(4, 8) + background = JBColor.namedColor("InfoPopup.background", JBColor(0xE6F3FF, 0x2D3142)) + } + + // Create the message label + val message = "📍 Press Tab to jump, Esc to cancel" + val label = JBLabel(message).apply { + foreground = JBColor.foreground() + background = JBColor.namedColor("InfoPopup.background", JBColor(0xE6F3FF, 0x2D3142)) + isOpaque = true + } + + panel.add(label, BorderLayout.CENTER) + + // Add keyboard shortcuts to the panel + addKeyboardShortcuts(panel) + + // Store reference for cleanup + keyboardShortcutsPanel = panel + + return panel + } + + private fun addKeyboardShortcuts(panel: JComponent) { + println("DEBUG: Adding keyboard shortcuts to jump panel") + + // CRITICAL: Disable focus traversal for Tab key + panel.setFocusTraversalKeysEnabled(false) + + val inputMap = panel.getInputMap(JComponent.WHEN_FOCUSED) + val actionMap = panel.actionMap + + // Add Tab key for accept + inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), "acceptJump") + actionMap.put("acceptJump", object : AbstractAction() { + override fun actionPerformed(e: ActionEvent?) { + println("DEBUG: Accept jump action triggered!") + acceptJump() + } + }) + + // Add Esc key for reject + inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "rejectJump") + actionMap.put("rejectJump", object : AbstractAction() { + override fun actionPerformed(e: ActionEvent?) { + println("DEBUG: Reject jump action triggered!") + rejectJump() + } + }) + + panel.isFocusable = true + + // Debug listeners + panel.addFocusListener(object : java.awt.event.FocusListener { + override fun focusGained(e: java.awt.event.FocusEvent?) { + println("DEBUG: Jump panel gained focus") + } + + override fun focusLost(e: java.awt.event.FocusEvent?) { + println("DEBUG: Jump panel lost focus") + } + }) + + panel.addKeyListener(object : java.awt.event.KeyListener { + override fun keyPressed(e: KeyEvent?) { + println("DEBUG: Jump panel key pressed: ${e?.keyCode} (Tab = ${KeyEvent.VK_TAB}, Esc = ${KeyEvent.VK_ESCAPE})") + } + + override fun keyReleased(e: KeyEvent?) {} + override fun keyTyped(e: KeyEvent?) {} + }) + + panel.addHierarchyListener { e -> + if (e.changeFlags and java.awt.event.HierarchyEvent.SHOWING_CHANGED.toLong() != 0L) { + if (panel.isShowing) { + println("DEBUG: Jump panel is showing, requesting focus") + ApplicationManager.getApplication().invokeLater { + val focusResult = panel.requestFocusInWindow() + println("DEBUG: Jump panel focus request result: $focusResult") + } + } + } + } + } + + private fun acceptJump() { + val state = jumpState + if (!state.inProgress || state.jumpPosition == null || state.editor == null) { + println("DEBUG: Cannot accept jump - invalid state") + return + } + + println("Accepting jump to position: ${state.jumpPosition}") + + // Update state + jumpState = jumpState.copy(justAccepted = true) + + ApplicationManager.getApplication().invokeLater { + // Move cursor to jump position + state.editor.caretModel.moveToLogicalPosition(state.jumpPosition) + + // Clear decorations + clearJumpDecoration() + + // Reset accepted state after a brief moment + coroutineScope.launch { + kotlinx.coroutines.delay(100) + jumpState = jumpState.copy(justAccepted = false) + + // Trigger inline suggestion + triggerInlineSuggestCallback?.invoke() + } + } + } + + private fun rejectJump() { + if (!jumpState.inProgress) { + println("DEBUG: Cannot reject jump - not in progress") + return + } + + println("Rejecting jump - deleting chain") + + // Delete the chain + deleteChainCallback?.invoke() + + // Clear state + clearJumpState() + } + + private fun clearJumpDecoration() { + // Clear keyboard shortcuts first + keyboardShortcutsPanel?.let { panel -> + if (panel is JComponent) { + panel.inputMap?.clear() + panel.actionMap?.clear() + } + } + keyboardShortcutsPanel = null + + // Cancel popup + jumpPopup?.cancel() + jumpPopup = null + + // Remove editor highlighter + editorHighlighter?.let { highlighter -> + jumpState.editor?.markupModel?.removeHighlighter(highlighter) + editorHighlighter = null + } + } + + private fun clearJumpState() { + clearJumpDecoration() + jumpState = JumpState() + } + + private fun isContentIdentical( + editor: Editor, + jumpLocation: LogicalPosition, + completionContent: String + ): Boolean { + return try { + val completionLines = completionContent.split("\n") + val document = editor.document + val startLine = jumpLocation.line + val endLine = minOf(startLine + completionLines.size - 1, document.lineCount - 1) + + // Check if we have enough lines + if (endLine - startLine + 1 < completionLines.size) { + return false + } + + // Compare line by line + completionLines.indices.all { i -> + val documentLine = startLine + i + if (documentLine >= document.lineCount) return@all false + + val lineStartOffset = document.getLineStartOffset(documentLine) + val lineEndOffset = document.getLineEndOffset(documentLine) + val lineText = document.getText(TextRange(lineStartOffset, lineEndOffset)) + + lineText == completionLines[i] + } + } catch (error: Exception) { + println("Error checking content at jump location: $error") + false + } + } + + private fun registerSelectionChangeHandler() { + val selectionManager = project.getService(SelectionChangeManager::class.java) + + selectionManager.registerListener( + "nextEditJumpManager", + { event, state -> handleSelectionChange(event, state) }, + HandlerPriority.HIGH + ) + } + + private suspend fun handleSelectionChange( + event: SelectionEvent, + state: StateSnapshot + ): Boolean { + // Preserve chain during jump operations + when { + state.jumpInProgress -> { + println("Jump in progress, preserving chain") + + // Check if cursor moved away from expected position + val currentPos = event.editor.caretModel.logicalPosition + val oldPos = jumpState.oldCursorPosition + val jumpPos = jumpState.jumpPosition + + // If cursor moved but not to jump position, reject the jump + if (oldPos != null && jumpPos != null && + !currentPos.equals(oldPos) && !currentPos.equals(jumpPos) + ) { + println("DEBUG: Cursor moved unexpectedly, rejecting jump") + rejectJump() + } + + return true + } + + state.jumpJustAccepted -> { + println("Jump just accepted, preserving chain") + return true + } + + else -> return false + } + } + + fun cleanup() { + clearJumpState() + triggerInlineSuggestCallback = null + deleteChainCallback = null + } +} \ No newline at end of file From bfa9677feaab09d2a06118ee93e395f9b04b1c0d Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 13 Aug 2025 15:58:38 -0700 Subject: [PATCH 21/48] feat: add jump manager service to xml --- extensions/intellij/src/main/resources/META-INF/plugin.xml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index 6376821e9..74e74a1b4 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -32,6 +32,9 @@ + + Date: Wed, 13 Aug 2025 16:47:21 -0700 Subject: [PATCH 22/48] feat: invoke inline completion provider after a jump is taken --- .../nextEdit/NextEditJumpManager.kt | 55 ++++++++++++++----- 1 file changed, 40 insertions(+), 15 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt index 5149961aa..b9939affa 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt @@ -3,6 +3,7 @@ package com.github.continuedev.continueintellijextension.nextEdit import com.github.continuedev.continueintellijextension.listeners.HandlerPriority import com.github.continuedev.continueintellijextension.listeners.SelectionChangeManager import com.github.continuedev.continueintellijextension.listeners.StateSnapshot +import com.github.continuedev.continueintellijextension.utils.InlineCompletionUtils import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.Service import com.intellij.openapi.editor.Editor @@ -121,13 +122,32 @@ class NextEditJumpManager(private val project: Project) { oldCursorPosition = currentPosition ) - // Show UI - showJumpDecoration(editor, nextJumpLocation) + // Show UI - ensure this runs on EDT + return try { + var result = false + ApplicationManager.getApplication().invokeAndWait { + try { + showJumpDecoration(editor, nextJumpLocation) - // Scroll to show jump location - editor.scrollingModel.scrollTo(nextJumpLocation, ScrollType.CENTER) + // Scroll to show jump location + editor.scrollingModel.scrollTo(nextJumpLocation, ScrollType.CENTER) - return true + result = true + println("DEBUG: suggestJump completed successfully") + } catch (e: Exception) { + println("DEBUG: Error in suggestJump UI operations: $e") + // Reset state on error + jumpState = jumpState.copy(inProgress = false) + result = false + } + } + result + } catch (e: Exception) { + println("DEBUG: Error in suggestJump invokeAndWait: $e") + // Reset state on error + jumpState = jumpState.copy(inProgress = false) + false + } } // Private implementation @@ -154,7 +174,7 @@ class NextEditJumpManager(private val project: Project) { } private fun showJumpPopup(editor: Editor, position: LogicalPosition) { - val popupComponent = createJumpPopupComponent() + val popupComponent = createJumpPopupComponent(editor) jumpPopup = JBPopupFactory.getInstance() .createComponentPopupBuilder(popupComponent, popupComponent) // Set focus component @@ -166,7 +186,10 @@ class NextEditJumpManager(private val project: Project) { .setCancelOnWindowDeactivation(false) .setCancelKeyEnabled(false) // Disable default Esc handling to use our custom one .setCancelCallback { - rejectJump() + // Only reject jump if we're still in progress and not just accepted + if (jumpState.inProgress && !jumpState.justAccepted) { + rejectJump() + } true } .createPopup() @@ -196,7 +219,7 @@ class NextEditJumpManager(private val project: Project) { } } - private fun createJumpPopupComponent(): JComponent { + private fun createJumpPopupComponent(editor: Editor): JComponent { val panel = JBPanel>().apply { layout = BorderLayout() border = JBUI.Borders.empty(4, 8) @@ -214,7 +237,7 @@ class NextEditJumpManager(private val project: Project) { panel.add(label, BorderLayout.CENTER) // Add keyboard shortcuts to the panel - addKeyboardShortcuts(panel) + addKeyboardShortcuts(panel, editor) // Store reference for cleanup keyboardShortcutsPanel = panel @@ -222,7 +245,7 @@ class NextEditJumpManager(private val project: Project) { return panel } - private fun addKeyboardShortcuts(panel: JComponent) { + private fun addKeyboardShortcuts(panel: JComponent, editor: Editor) { println("DEBUG: Adding keyboard shortcuts to jump panel") // CRITICAL: Disable focus traversal for Tab key @@ -236,7 +259,7 @@ class NextEditJumpManager(private val project: Project) { actionMap.put("acceptJump", object : AbstractAction() { override fun actionPerformed(e: ActionEvent?) { println("DEBUG: Accept jump action triggered!") - acceptJump() + acceptJump(editor) } }) @@ -284,25 +307,27 @@ class NextEditJumpManager(private val project: Project) { } } - private fun acceptJump() { + private fun acceptJump(editor: Editor) { val state = jumpState if (!state.inProgress || state.jumpPosition == null || state.editor == null) { - println("DEBUG: Cannot accept jump - invalid state") + println("DEBUG: Cannot accept jump - invalid state: ${!state.inProgress} ${state.jumpPosition == null} ${state.editor == null}") return } println("Accepting jump to position: ${state.jumpPosition}") - // Update state + // Update state BEFORE clearing decorations to prevent cancel callback from triggering reject jumpState = jumpState.copy(justAccepted = true) ApplicationManager.getApplication().invokeLater { // Move cursor to jump position state.editor.caretModel.moveToLogicalPosition(state.jumpPosition) - // Clear decorations + // Clear decorations (this will cancel popup, but won't trigger reject due to state check) clearJumpDecoration() + InlineCompletionUtils.triggerInlineCompletion(editor, project) { success -> "success: $success" } + // Reset accepted state after a brief moment coroutineScope.launch { kotlinx.coroutines.delay(100) From 209de229c05624f5dd1d98394fdeff42b1fecd16 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 14 Aug 2025 19:15:50 -0700 Subject: [PATCH 23/48] feat: register an active handler to detect intentional cursor movements --- .../nextEdit/NextEditJumpManager.kt | 125 +++++++++++------- .../nextEdit/NextEditWindowManager.kt | 80 +++++++---- 2 files changed, 129 insertions(+), 76 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt index b9939affa..05e5b8a90 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt @@ -1,15 +1,12 @@ package com.github.continuedev.continueintellijextension.nextEdit -import com.github.continuedev.continueintellijextension.listeners.HandlerPriority -import com.github.continuedev.continueintellijextension.listeners.SelectionChangeManager -import com.github.continuedev.continueintellijextension.listeners.StateSnapshot +import com.github.continuedev.continueintellijextension.listeners.ActiveHandlerManager import com.github.continuedev.continueintellijextension.utils.InlineCompletionUtils import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.Service import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.LogicalPosition import com.intellij.openapi.editor.ScrollType -import com.intellij.openapi.editor.event.SelectionEvent import com.intellij.openapi.editor.markup.HighlighterLayer import com.intellij.openapi.editor.markup.HighlighterTargetArea import com.intellij.openapi.editor.markup.RangeHighlighter @@ -48,6 +45,9 @@ class NextEditJumpManager(private val project: Project) { // State management private var jumpState = JumpState() + // Handler management + private var jumpHandler: NextEditJumpHandler? = null + // UI components private var jumpPopup: JBPopup? = null private var editorHighlighter: RangeHighlighter? = null @@ -67,7 +67,7 @@ class NextEditJumpManager(private val project: Project) { ) init { - registerSelectionChangeHandler() +// registerSelectionChangeHandler() } // Public API @@ -97,6 +97,15 @@ class NextEditJumpManager(private val project: Project) { fun getSavedCompletionAfterJump(): CompletionDataForAfterJump? = jumpState.completionAfterJump + fun getJumpPosition(): LogicalPosition? = jumpState.jumpPosition + + fun getOriginalPosition(): LogicalPosition? = jumpState.oldCursorPosition + + fun abortJump() { + // Public method that delegates to the existing private rejectJump logic + rejectJump() + } + // Main entry point suspend fun suggestJump( editor: Editor, @@ -122,6 +131,11 @@ class NextEditJumpManager(private val project: Project) { oldCursorPosition = currentPosition ) + // Register active handler to track cursor movements during jump + jumpHandler = NextEditJumpHandler(project, this) + val activeHandlerManager = project.getService(ActiveHandlerManager::class.java) + activeHandlerManager.setActiveHandler(jumpHandler!!) + // Show UI - ensure this runs on EDT return try { var result = false @@ -333,6 +347,9 @@ class NextEditJumpManager(private val project: Project) { kotlinx.coroutines.delay(100) jumpState = jumpState.copy(justAccepted = false) + // Clear the active handler after jump is complete + clearActiveHandler() + // Trigger inline suggestion triggerInlineSuggestCallback?.invoke() } @@ -352,6 +369,9 @@ class NextEditJumpManager(private val project: Project) { // Clear state clearJumpState() + + // Clear handler when rejecting + clearActiveHandler() } private fun clearJumpDecoration() { @@ -413,53 +433,62 @@ class NextEditJumpManager(private val project: Project) { } } - private fun registerSelectionChangeHandler() { - val selectionManager = project.getService(SelectionChangeManager::class.java) - - selectionManager.registerListener( - "nextEditJumpManager", - { event, state -> handleSelectionChange(event, state) }, - HandlerPriority.HIGH - ) - } - - private suspend fun handleSelectionChange( - event: SelectionEvent, - state: StateSnapshot - ): Boolean { - // Preserve chain during jump operations - when { - state.jumpInProgress -> { - println("Jump in progress, preserving chain") - - // Check if cursor moved away from expected position - val currentPos = event.editor.caretModel.logicalPosition - val oldPos = jumpState.oldCursorPosition - val jumpPos = jumpState.jumpPosition - - // If cursor moved but not to jump position, reject the jump - if (oldPos != null && jumpPos != null && - !currentPos.equals(oldPos) && !currentPos.equals(jumpPos) - ) { - println("DEBUG: Cursor moved unexpectedly, rejecting jump") - rejectJump() - } - - return true - } - - state.jumpJustAccepted -> { - println("Jump just accepted, preserving chain") - return true - } - - else -> return false - } - } +// private fun registerSelectionChangeHandler() { +// val selectionManager = project.getService(SelectionChangeManager::class.java) +// +// selectionManager.registerListener( +// "nextEditJumpManager", +// { event, state -> handleSelectionChange(event, state) }, +// HandlerPriority.HIGH +// ) +// } +// +// private suspend fun handleSelectionChange( +// event: SelectionEvent, +// state: StateSnapshot +// ): Boolean { +// // Preserve chain during jump operations +// when { +// state.jumpInProgress -> { +// println("Jump in progress, preserving chain") +// +// // Check if cursor moved away from expected position +// val currentPos = event.editor.caretModel.logicalPosition +// val oldPos = jumpState.oldCursorPosition +// val jumpPos = jumpState.jumpPosition +// +// // If cursor moved but not to jump position, reject the jump +// if (oldPos != null && jumpPos != null && +// !currentPos.equals(oldPos) && !currentPos.equals(jumpPos) +// ) { +// println("DEBUG: Cursor moved unexpectedly, rejecting jump") +// rejectJump() +// } +// +// return true +// } +// +// state.jumpJustAccepted -> { +// println("Jump just accepted, preserving chain") +// return true +// } +// +// else -> return false +// } +// } fun cleanup() { clearJumpState() triggerInlineSuggestCallback = null deleteChainCallback = null } + + private fun clearActiveHandler() { + jumpHandler?.let { handler -> + val activeHandlerManager = project.getService(ActiveHandlerManager::class.java) + activeHandlerManager.clearActiveHandler() + handler.dispose() + } + jumpHandler = null + } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt index 7300cb0a3..0736abc40 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt @@ -1,17 +1,15 @@ package com.github.continuedev.continueintellijextension.nextEdit import com.github.continuedev.continueintellijextension.Position -import com.github.continuedev.continueintellijextension.listeners.HandlerPriority -import com.github.continuedev.continueintellijextension.listeners.SelectionChangeManager -import com.github.continuedev.continueintellijextension.listeners.StateSnapshot +import com.github.continuedev.continueintellijextension.listeners.ActiveHandlerManager import com.github.continuedev.continueintellijextension.utils.InlineCompletionUtils import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.components.Service import com.intellij.openapi.editor.Editor +import com.intellij.openapi.editor.LogicalPosition import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.colors.EditorFontType -import com.intellij.openapi.editor.event.SelectionEvent import com.intellij.openapi.editor.markup.* import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopup @@ -33,6 +31,9 @@ class NextEditWindowManager(private val project: Project) { private var isAccepted = false private var currentCompletionId: String? = null + // Handler management + private var windowHandler: NextEditWindowHandler? = null + suspend fun showNextEditWindow( editor: Editor, currCursorPos: Position, @@ -54,6 +55,12 @@ class NextEditWindowManager(private val project: Project) { // Clear existing decorations first hideAllNextEditWindows() + // Register active handler for this window + val cursorPosition = LogicalPosition(currCursorPos.line, currCursorPos.character) + windowHandler = NextEditWindowHandler(project, this, cursorPosition) + val activeHandlerManager = project.getService(ActiveHandlerManager::class.java) + activeHandlerManager.setActiveHandler(windowHandler!!) + // Determine if this is a line deletion case val isLineDelete = determineIfLineDelete( editor, @@ -600,6 +607,10 @@ class NextEditWindowManager(private val project: Project) { println(" isLineDelete: $isLineDelete") isAccepted = true + + // Clear handler before making document changes that move cursor + clearActiveHandler() + hideAllNextEditWindows() try { @@ -695,6 +706,8 @@ class NextEditWindowManager(private val project: Project) { } private fun rejectEdit() { + clearActiveHandler() + hideAllNextEditWindows() // Log rejection and delete chain (placeholder) @@ -719,6 +732,8 @@ class NextEditWindowManager(private val project: Project) { // Clear all deletion decorations without tracking editors clearAllDeletionDecorations() deletionHighlighters = emptyList() + + clearActiveHandler() // TODO: might be redundant } private fun clearAllDeletionDecorations() { @@ -732,6 +747,15 @@ class NextEditWindowManager(private val project: Project) { } } + private fun clearActiveHandler() { + windowHandler?.let { handler -> + val activeHandlerManager = project.getService(ActiveHandlerManager::class.java) + activeHandlerManager.clearActiveHandler() + handler.dispose() + } + windowHandler = null + } + fun hasAccepted(): Boolean = isAccepted fun setAccepted(accepted: Boolean) { @@ -747,30 +771,30 @@ class NextEditWindowManager(private val project: Project) { currentCompletionId = null } - fun registerSelectionChangeHandler() { - val selectionManager = project.getService(SelectionChangeManager::class.java) - - selectionManager.registerListener( - "nextEditWindowManager", - { event, state -> - handleSelectionChange(event, state) - }, - HandlerPriority.HIGH - ) - } - - private suspend fun handleSelectionChange( - event: SelectionEvent, - state: StateSnapshot - ): Boolean { - // If window was just accepted, preserve the chain - if (state.nextEditWindowAccepted) { - println("Next edit window accepted, preserving chain") - return true - } - - return false - } +// fun registerSelectionChangeHandler() { +// val selectionManager = project.getService(SelectionChangeManager::class.java) +// +// selectionManager.registerListener( +// "nextEditWindowManager", +// { event, state -> +// handleSelectionChange(event, state) +// }, +// HandlerPriority.HIGH +// ) +// } +// +// private suspend fun handleSelectionChange( +// event: SelectionEvent, +// state: StateSnapshot +// ): Boolean { +// // If window was just accepted, preserve the chain +// if (state.nextEditWindowAccepted) { +// println("Next edit window accepted, preserving chain") +// return true +// } +// +// return false +// } } enum class PopupAction { From c2ee3aa1ad7fcbd89f5dabd43796e73c868e07da Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 14 Aug 2025 19:16:12 -0700 Subject: [PATCH 24/48] feat: track cursor movements at an application label --- .../services/ContinuePluginService.kt | 37 +++++++++++++++++-- 1 file changed, 34 insertions(+), 3 deletions(-) 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 102981715..c0cb53248 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 @@ -4,18 +4,23 @@ import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger import com.github.continuedev.continueintellijextension.`continue`.CoreMessengerManager import com.github.continuedev.continueintellijextension.`continue`.DiffManager import com.github.continuedev.continueintellijextension.`continue`.IdeProtocolClient +import com.github.continuedev.continueintellijextension.listeners.ActiveHandlerManager +import com.github.continuedev.continueintellijextension.listeners.DocumentChangeTracker import com.github.continuedev.continueintellijextension.toolWindow.ContinuePluginToolWindowFactory import com.github.continuedev.continueintellijextension.utils.uuid -import com.intellij.openapi.Disposable import com.intellij.openapi.components.Service +import com.intellij.openapi.components.service +import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.project.DumbAware +import com.intellij.openapi.project.Project +import com.intellij.openapi.util.Disposer import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel import kotlin.properties.Delegates @Service(Service.Level.PROJECT) -class ContinuePluginService : Disposable, DumbAware { +class ContinuePluginService(private val project: Project) : DumbAware { private val coroutineScope = CoroutineScope(Dispatchers.Main) var continuePluginWindow: ContinuePluginToolWindowFactory.ContinuePluginWindow? = null var listener: (() -> Unit)? = null @@ -29,7 +34,33 @@ class ContinuePluginService : Disposable, DumbAware { var windowId: String = uuid() var diffManager: DiffManager? = null - override fun dispose() { + init { + // Set up active handler manager and document change tracking + setupCursorMovementTracking() + } + + private fun setupCursorMovementTracking() { + val activeHandlerManager = project.service() + val documentChangeTracker = project.service() + + // Register listeners with EditorFactory to handle all editors + // Use Disposer to ensure they get cleaned up when the project is disposed + val editorFactory = EditorFactory.getInstance() + + editorFactory.eventMulticaster.addSelectionListener(activeHandlerManager, project) + editorFactory.eventMulticaster.addCaretListener(activeHandlerManager, project) + editorFactory.eventMulticaster.addDocumentListener(documentChangeTracker, project) + +// setupCompletionTracking(activeHandlerManager) + + // Also register disposal cleanup + Disposer.register(project) { + activeHandlerManager.dispose() + documentChangeTracker.dispose() + } + } + + fun dispose() { coroutineScope.cancel() coreMessenger?.coroutineScope?.let { it.cancel() From 34dac0523b05f0619c2e6a7bfdc3d6a3303543da Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 14 Aug 2025 19:16:50 -0700 Subject: [PATCH 25/48] feat: add an active handler manager that calls the currently set active handler to check for the cause of cursor movements --- .../listeners/ActiveHandlerManager.kt | 184 ++++++++++++++++++ 1 file changed, 184 insertions(+) create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ActiveHandlerManager.kt diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ActiveHandlerManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ActiveHandlerManager.kt new file mode 100644 index 000000000..24b5c5fe1 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ActiveHandlerManager.kt @@ -0,0 +1,184 @@ +package com.github.continuedev.continueintellijextension.listeners + +import com.github.continuedev.continueintellijextension.nextEdit.NextEditService +import com.intellij.openapi.components.Service +import com.intellij.openapi.editor.Editor +import com.intellij.openapi.editor.LogicalPosition +import com.intellij.openapi.editor.event.CaretEvent +import com.intellij.openapi.editor.event.CaretListener +import com.intellij.openapi.editor.event.SelectionEvent +import com.intellij.openapi.editor.event.SelectionListener +import com.intellij.openapi.project.DumbAware +import com.intellij.openapi.project.Project +import kotlinx.coroutines.* + +/** + * Interface for services that need to handle cursor movement events. + */ +interface CursorMovementHandler { + val handlerId: String + + /** + * Called when cursor moves while this handler is active. + * @return true if the cursor movement was expected/handled, false otherwise + */ + suspend fun onCursorMoved(editor: Editor, oldPosition: LogicalPosition?, newPosition: LogicalPosition): Boolean + + /** + * Called when this handler becomes active. + */ + fun onActivated() {} + + /** + * Called when this handler is about to be deactivated. + */ + fun onDeactivated() {} + + /** + * Called when the handler should clean up its resources. + */ + fun dispose() { + onDeactivated() + } +} + +/** + * Manages active cursor movement handlers to distinguish between intentional + * cursor movements and side effects from various IDE operations. + * + * When a service is performing an operation that might move the cursor (like + * accepting a completion, jumping, typing), it should register an active handler. + * If no handler is active when the cursor moves, it's considered an intentional + * movement and the next edit chain is deleted. + */ +@Service(Service.Level.PROJECT) +class ActiveHandlerManager(private val project: Project) : SelectionListener, CaretListener, DumbAware { + + private val coroutineScope = CoroutineScope(Dispatchers.Main + SupervisorJob()) + private var activeHandler: CursorMovementHandler? = null + private var isHandlingEvent = false + + // Track last known cursor position to detect movements + private var lastKnownPosition: LogicalPosition? = null + private var lastKnownEditor: Editor? = null + + /** + * Set an active handler for cursor movement events. + * This should be called when a service is about to perform an operation + * that might cause cursor movement. + */ + fun setActiveHandler(handler: CursorMovementHandler) { + clearActiveHandler() + + activeHandler = handler + handler.onActivated() + + println("ActiveHandlerManager: Set active handler '${handler.handlerId}'") + } + + /** + * Clear the currently active handler. + * This should be called when the operation is complete. + */ + fun clearActiveHandler() { + activeHandler?.let { handler -> + println("ActiveHandlerManager: Clearing active handler '${handler.handlerId}'") + handler.onDeactivated() + handler.dispose() + } + activeHandler = null + } + + /** + * Get the currently active handler. + */ + fun getActiveHandler(): CursorMovementHandler? = activeHandler + + /** + * Check if a specific handler is currently active. + */ + fun isHandlerActive(handlerId: String): Boolean { + return activeHandler?.handlerId == handlerId + } + + // SelectionListener implementation + override fun selectionChanged(event: SelectionEvent) { + if (isHandlingEvent || event.editor.isDisposed) return + + coroutineScope.launch { + handleCursorMovement(event.editor, event.newRange.startOffset) + } + } + + // CaretListener implementation + override fun caretPositionChanged(event: CaretEvent) { + if (isHandlingEvent || event.editor.isDisposed) return + + coroutineScope.launch { + handleCursorMovement(event.editor, event.caret?.offset ?: return@launch) + } + } + + private suspend fun handleCursorMovement(editor: Editor, offset: Int) { + if (isHandlingEvent) return + + isHandlingEvent = true + try { + val currentPosition = editor.offsetToLogicalPosition(offset) + val oldPosition = if (editor == lastKnownEditor) lastKnownPosition else null + + // Update tracking + lastKnownPosition = currentPosition + lastKnownEditor = editor + + // Skip if position hasn't actually changed + if (oldPosition != null && oldPosition == currentPosition) { + return + } + + val handler = activeHandler + if (handler != null) { + // A handler is active - let it decide if this movement was expected + try { + val wasHandled = handler.onCursorMoved(editor, oldPosition, currentPosition) + if (!wasHandled) { + println("ActiveHandlerManager: Active handler '${handler.handlerId}' did not handle cursor movement, treating as deliberate") + handleDeliberateCursorMovement() + } else { + println("ActiveHandlerManager: Active handler '${handler.handlerId}' handled cursor movement") + } + } catch (e: Exception) { + println("ActiveHandlerManager: Error in handler '${handler.handlerId}': ${e.message}") + // Treat as deliberate movement if handler fails + handleDeliberateCursorMovement() + } + } else { + // No active handler - this is a deliberate cursor movement + println("ActiveHandlerManager: No active handler, treating cursor movement as deliberate") + handleDeliberateCursorMovement() + } + } finally { + isHandlingEvent = false + } + } + + private suspend fun handleDeliberateCursorMovement() { + try { + // Clear any active handler since the user moved the cursor deliberately + clearActiveHandler() + + // Delete the next edit chain + val nextEditService = project.getService(NextEditService::class.java) + nextEditService.deleteChain() + + println("ActiveHandlerManager: Deleted next edit chain due to deliberate cursor movement") + } catch (e: Exception) { + println("ActiveHandlerManager: Error handling deliberate cursor movement: ${e.message}") + } + } + + fun dispose() { + clearActiveHandler() + coroutineScope.cancel() + } +} \ No newline at end of file From 1ee5e1f3316bc26fbceb5924048337f4236d4781 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 14 Aug 2025 19:17:16 -0700 Subject: [PATCH 26/48] feat: add a checker to see if the cursor movement happened because of typing --- .../listeners/DocumentChangeTracker.kt | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/DocumentChangeTracker.kt diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/DocumentChangeTracker.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/DocumentChangeTracker.kt new file mode 100644 index 000000000..4c63eb73e --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/DocumentChangeTracker.kt @@ -0,0 +1,62 @@ +package com.github.continuedev.continueintellijextension.listeners + +import com.intellij.openapi.components.Service +import com.intellij.openapi.components.service +import com.intellij.openapi.editor.event.DocumentEvent +import com.intellij.openapi.editor.event.DocumentListener +import com.intellij.openapi.project.Project +import kotlinx.coroutines.* + +/** + * Tracks document changes to detect typing sessions and manage active handlers. + */ +@Service(Service.Level.PROJECT) +class DocumentChangeTracker(private val project: Project) : DocumentListener { + + private val coroutineScope = CoroutineScope(Dispatchers.Main + SupervisorJob()) + private var typingHandler: TypingSessionHandler? = null + private var typingSessionTimer: Job? = null + + private val TYPING_SESSION_TIMEOUT = 2000L // ms + + override fun documentChanged(event: DocumentEvent) { + if (event.document.isWritable) { + handleDocumentChange() + } + } + + private fun handleDocumentChange() { + val activeHandlerManager = project.service() + + // Cancel existing typing session timer + typingSessionTimer?.cancel() + + // If no active handler or it's not already a typing session, create one + val currentHandler = activeHandlerManager.getActiveHandler() + if (currentHandler !is TypingSessionHandler) { + typingHandler = TypingSessionHandler(project) + activeHandlerManager.setActiveHandler(typingHandler!!) + } else { + // Update existing typing handler + (currentHandler as TypingSessionHandler).updateTypingTime() + } + + // Set up timer to clear typing session after inactivity + typingSessionTimer = coroutineScope.launch { + delay(TYPING_SESSION_TIMEOUT) + + // Clear typing handler if it's still active + if (activeHandlerManager.isHandlerActive("typingSession")) { + activeHandlerManager.clearActiveHandler() + typingHandler?.dispose() + typingHandler = null + } + } + } + + fun dispose() { + typingSessionTimer?.cancel() + typingHandler?.dispose() + coroutineScope.cancel() + } +} \ No newline at end of file From 2de814bbff0c3226f4f497aa264549e5bb4744f7 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 14 Aug 2025 19:18:13 -0700 Subject: [PATCH 27/48] feat: add handlers for different actions --- .../listeners/TypingSessionHandler.kt | 58 ++++++++++++++++++ .../nextEdit/NextEditJumpHandler.kt | 61 +++++++++++++++++++ .../nextEdit/NextEditWindowHandler.kt | 49 +++++++++++++++ 3 files changed, 168 insertions(+) create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/TypingSessionHandler.kt create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpHandler.kt create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowHandler.kt diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/TypingSessionHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/TypingSessionHandler.kt new file mode 100644 index 000000000..35fbaba65 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/TypingSessionHandler.kt @@ -0,0 +1,58 @@ +package com.github.continuedev.continueintellijextension.listeners + +import com.intellij.openapi.editor.Editor +import com.intellij.openapi.editor.LogicalPosition +import com.intellij.openapi.project.Project + +/** + * Handler for cursor movements during typing sessions. + * Preserves the chain when user is actively typing. + */ +class TypingSessionHandler( + private val project: Project +) : CursorMovementHandler { + + override val handlerId = "typingSession" + + private var lastDocumentChangeTime = 0L + private val TYPING_DELAY = 1000L // ms - consider movements within this time as typing + + fun updateTypingTime() { + lastDocumentChangeTime = System.currentTimeMillis() + } + + override suspend fun onCursorMoved( + editor: Editor, + oldPosition: LogicalPosition?, + newPosition: LogicalPosition + ): Boolean { + val now = System.currentTimeMillis() + val timeSinceLastEdit = now - lastDocumentChangeTime + + // If recent document change and cursor moved forward/down, likely typing + if (timeSinceLastEdit < TYPING_DELAY) { + val isTypingMovement = oldPosition?.let { old -> + // Same line, moving forward + (newPosition.line == old.line && newPosition.column > old.column) || + // Next line, typical of pressing Enter + (newPosition.line == old.line + 1 && newPosition.column <= old.column) + } ?: false + + if (isTypingMovement) { + println("TypingSessionHandler: Cursor movement during typing session") + return true + } + } + + println("TypingSessionHandler: Not a typing movement (time since edit: ${timeSinceLastEdit}ms)") + return false + } + + override fun onDeactivated() { + println("TypingSessionHandler: Deactivated") + } + + override fun dispose() { + onDeactivated() + } +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpHandler.kt new file mode 100644 index 000000000..54184ee75 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpHandler.kt @@ -0,0 +1,61 @@ +package com.github.continuedev.continueintellijextension.nextEdit + +import com.github.continuedev.continueintellijextension.listeners.CursorMovementHandler +import com.intellij.openapi.editor.Editor +import com.intellij.openapi.editor.LogicalPosition +import com.intellij.openapi.project.Project + +/** + * Handler for cursor movements during jump operations. + */ +class NextEditJumpHandler( + private val project: Project, + private val jumpManager: NextEditJumpManager +) : CursorMovementHandler { + + override val handlerId = "nextEditJump" + + override suspend fun onCursorMoved( + editor: Editor, + oldPosition: LogicalPosition?, + newPosition: LogicalPosition + ): Boolean { + // Check if we're still in a jump operation + if (!jumpManager.isJumpInProgress()) { + // Jump is no longer in progress, cursor movement is deliberate + return false + } + + val jumpPosition = jumpManager.getJumpPosition() + val originalPosition = jumpManager.getOriginalPosition() + + return when { + // Cursor moved to the expected jump position - this is expected + jumpPosition != null && newPosition == jumpPosition -> { + println("NextEditJumpHandler: Cursor moved to expected jump position") + true + } + + // Cursor is still at the original position - no movement yet + originalPosition != null && newPosition == originalPosition -> { + println("NextEditJumpHandler: Cursor still at original position") + true + } + + // Cursor moved somewhere else - user moved manually, abort jump + else -> { + println("NextEditJumpHandler: Cursor moved to unexpected position, aborting jump") + jumpManager.abortJump() + false + } + } + } + + override fun onDeactivated() { + println("NextEditJumpHandler: Deactivated") + } + + override fun dispose() { + onDeactivated() + } +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowHandler.kt new file mode 100644 index 000000000..89bc61a7d --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowHandler.kt @@ -0,0 +1,49 @@ +package com.github.continuedev.continueintellijextension.nextEdit + +import com.github.continuedev.continueintellijextension.listeners.CursorMovementHandler +import com.intellij.openapi.editor.Editor +import com.intellij.openapi.editor.LogicalPosition +import com.intellij.openapi.project.Project + +/** + * Handler for cursor movements during next edit window operations. + */ +class NextEditWindowHandler( + private val project: Project, + private val windowManager: NextEditWindowManager, + private val expectedPosition: LogicalPosition +) : CursorMovementHandler { + + override val handlerId = "nextEditWindow" + + override suspend fun onCursorMoved( + editor: Editor, + oldPosition: LogicalPosition?, + newPosition: LogicalPosition + ): Boolean { + // Check if window was just accepted + if (windowManager.hasAccepted()) { + println("NextEditWindowHandler: Window was accepted, cursor movement is expected") + return true + } + + // Check if cursor is still near the expected position (within the same line) + if (newPosition.line == expectedPosition.line) { + println("NextEditWindowHandler: Cursor movement within same line as suggestion") + return true + } + + // User moved away from the suggestion area - close window and treat as deliberate + println("NextEditWindowHandler: Cursor moved away from suggestion area") + windowManager.hideAllNextEditWindows() + return false + } + + override fun onDeactivated() { + println("NextEditWindowHandler: Deactivated") + } + + override fun dispose() { + onDeactivated() + } +} \ No newline at end of file From dc35ac91e40be6b8cd06f477b6d2546f1c44dd78 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 15 Aug 2025 16:48:44 -0700 Subject: [PATCH 28/48] feat: improve UI --- .../nextEdit/NextEditJumpManager.kt | 87 +++++++++++++++++-- 1 file changed, 78 insertions(+), 9 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt index 05e5b8a90..ee650d7a8 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt @@ -19,17 +19,19 @@ import com.intellij.ui.JBColor import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBPanel import com.intellij.util.ui.JBUI +import com.intellij.util.ui.UIUtil import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch -import java.awt.BorderLayout -import java.awt.Point +import java.awt.* import java.awt.event.ActionEvent import java.awt.event.KeyEvent +import java.awt.geom.RoundRectangle2D import javax.swing.AbstractAction import javax.swing.JComponent import javax.swing.KeyStroke import javax.swing.SwingUtilities +import javax.swing.border.AbstractBorder data class CompletionDataForAfterJump( val completionId: String, @@ -191,16 +193,15 @@ class NextEditJumpManager(private val project: Project) { val popupComponent = createJumpPopupComponent(editor) jumpPopup = JBPopupFactory.getInstance() - .createComponentPopupBuilder(popupComponent, popupComponent) // Set focus component + .createComponentPopupBuilder(popupComponent, popupComponent) .setFocusable(true) .setRequestFocus(true) .setResizable(false) .setMovable(false) .setCancelOnClickOutside(false) .setCancelOnWindowDeactivation(false) - .setCancelKeyEnabled(false) // Disable default Esc handling to use our custom one + .setCancelKeyEnabled(false) .setCancelCallback { - // Only reject jump if we're still in progress and not just accepted if (jumpState.inProgress && !jumpState.justAccepted) { rejectJump() } @@ -214,11 +215,52 @@ class NextEditJumpManager(private val project: Project) { val lineEndOffset = editor.document.getLineEndOffset(position.line) val lineEndPoint = editor.offsetToXY(lineEndOffset) val editorComponent = editor.contentComponent - val screenPoint = Point(lineEndPoint.x + 20, lineEndPoint.y) + + // Calculate the vertical center of the line + val lineHeight = editor.lineHeight + val lineCenterY = lineEndPoint.y + (lineHeight / 2) + + // Get the popup's preferred size to calculate its center + val popupSize = popupComponent.preferredSize + val popupCenterY = popupSize.height / 2 + + // Position the popup so its center aligns with the line's center + val adjustedY = lineCenterY - popupCenterY + + val screenPoint = Point(lineEndPoint.x + 20, adjustedY) SwingUtilities.convertPointToScreen(screenPoint, editorComponent) jumpPopup?.showInScreenCoordinates(editorComponent, screenPoint) + val content = jumpPopup?.content + if (content is JComponent) { + // Remove default border and add custom rounded border + content.border = object : AbstractBorder() { + override fun paintBorder(c: Component, g: Graphics, x: Int, y: Int, width: Int, height: Int) { + val g2 = g.create() as Graphics2D + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) + + val arc = 6f + // g2.color = JBColor.border() + g2.color = Color(0x999998) + g2.stroke = BasicStroke(1f) + g2.draw( + RoundRectangle2D.Float( + x.toFloat(), + y.toFloat(), + width.toFloat() - 1f, + height.toFloat() - 1f, + arc, + arc + ) + ) + g2.dispose() + } + + override fun getBorderInsets(c: Component): Insets = JBUI.insets(1) + } + } + // Force focus after popup is shown ApplicationManager.getApplication().invokeLater { popupComponent.requestFocusInWindow() @@ -234,10 +276,36 @@ class NextEditJumpManager(private val project: Project) { } private fun createJumpPopupComponent(editor: Editor): JComponent { - val panel = JBPanel>().apply { + val panel = object : JBPanel>() { + private val arc = 6f + + init { + isOpaque = false + background = JBColor.namedColor("InfoPopup.background", JBColor(0xE6F3FF, 0x2D3142)) + } + + override fun paintComponent(g: Graphics) { + val g2 = g.create() as Graphics2D + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) + + val width = width.toFloat() + val height = height.toFloat() + + // Draw background with rounded corners + g2.color = background + g2.fill(RoundRectangle2D.Float(0f, 0f, width, height, arc, arc)) + + // Draw border with the SAME dimensions as the background + g2.color = JBColor.border() + g2.stroke = BasicStroke(1f) + g2.draw(RoundRectangle2D.Float(0f, 0f, width, height, arc, arc)) + + g2.dispose() + super.paintComponent(g) + } + }.apply { layout = BorderLayout() - border = JBUI.Borders.empty(4, 8) - background = JBColor.namedColor("InfoPopup.background", JBColor(0xE6F3FF, 0x2D3142)) + border = JBUI.Borders.empty(2, 4) } // Create the message label @@ -246,6 +314,7 @@ class NextEditJumpManager(private val project: Project) { foreground = JBColor.foreground() background = JBColor.namedColor("InfoPopup.background", JBColor(0xE6F3FF, 0x2D3142)) isOpaque = true + font = UIUtil.getLabelFont() } panel.add(label, BorderLayout.CENTER) From 9f2d3c2ea296b9737389edd1facff232b8ad90c6 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 15 Aug 2025 17:55:08 -0700 Subject: [PATCH 29/48] fix: remove margins around code popup --- .../nextEdit/NextEditWindowManager.kt | 65 +++++++++++++++---- 1 file changed, 53 insertions(+), 12 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt index 0736abc40..67e511f66 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt @@ -19,10 +19,12 @@ import com.intellij.ui.JBColor import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBPanel import com.intellij.util.ui.JBUI -import java.awt.BorderLayout +import java.awt.* import java.awt.event.ActionEvent import java.awt.event.KeyEvent +import java.awt.geom.RoundRectangle2D import javax.swing.* +import javax.swing.border.AbstractBorder @Service(Service.Level.PROJECT) class NextEditWindowManager(private val project: Project) { @@ -131,14 +133,14 @@ class NextEditWindowManager(private val project: Project) { val popupComponent = createNextEditPopupComponent(code, diffLines, onAction) val popup = JBPopupFactory.getInstance() - .createComponentPopupBuilder(popupComponent, popupComponent) // Set focus component + .createComponentPopupBuilder(popupComponent, popupComponent) .setFocusable(true) .setRequestFocus(true) .setResizable(false) .setMovable(false) .setCancelOnClickOutside(false) .setCancelOnWindowDeactivation(false) - .setCancelKeyEnabled(false) // Disable default Esc handling to use our custom one + .setCancelKeyEnabled(false) .setCancelCallback { onAction(PopupAction.REJECT) true @@ -158,6 +160,34 @@ class NextEditWindowManager(private val project: Project) { popup.showInScreenCoordinates(editorComponent, screenPoint) + // Add ONLY the popup content border with rounded corners + val content = popup.content + if (content is JComponent) { + content.border = object : AbstractBorder() { + override fun paintBorder(c: Component, g: Graphics, x: Int, y: Int, width: Int, height: Int) { + val g2 = g.create() as Graphics2D + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) + + val arc = 6f + g2.color = Color(0x999998) + g2.stroke = BasicStroke(1f) + g2.draw( + RoundRectangle2D.Float( + x.toFloat(), + y.toFloat(), + width.toFloat() - 1f, + height.toFloat() - 1f, + arc, + arc + ) + ) + g2.dispose() + } + + override fun getBorderInsets(c: Component): Insets = JBUI.insets(1) + } + } + // Force focus after popup is shown ApplicationManager.getApplication().invokeLater { popupComponent.requestFocusInWindow() @@ -179,8 +209,10 @@ class NextEditWindowManager(private val project: Project) { ): JComponent { val panel = JBPanel>().apply { layout = BorderLayout() - border = JBUI.Borders.empty(8) +// border = JBUI.Borders.empty(8, 12) + border = null background = EditorColorsManager.getInstance().globalScheme.defaultBackground + // No custom paintComponent - just use regular panel } // Create syntax-highlighted code display @@ -193,6 +225,7 @@ class NextEditWindowManager(private val project: Project) { return panel } + private fun createCodeDisplayPanel(code: String, diffLines: List): JComponent { val scheme = EditorColorsManager.getInstance().globalScheme @@ -210,10 +243,13 @@ class NextEditWindowManager(private val project: Project) { val panel = JBPanel>().apply { layout = BoxLayout(this, BoxLayout.Y_AXIS) background = scheme.defaultBackground - border = JBUI.Borders.compound( - JBUI.Borders.customLine(JBColor.border()), - JBUI.Borders.empty(4) - ) +// border = JBUI.Borders.compound( +// JBUI.Borders.customLine(JBColor.border()), +// JBUI.Borders.empty() +// ) +// border = +// JBUI.Borders.customLine(JBColor.border()) // Remove the compound border entirely, just keep the line + border = null } var maxWidth = 0 @@ -270,11 +306,12 @@ class NextEditWindowManager(private val project: Project) { val borderInsets = panel.border?.getBorderInsets(panel) ?: java.awt.Insets(0, 0, 0, 0) // Use the actual measured max width plus some padding - val contentWidth = maxWidth + borderInsets.left + borderInsets.right + 24 // More padding for HTML rendering - +// val contentWidth = maxWidth + borderInsets.left + borderInsets.right + 24 // More padding for HTML rendering + val contentWidth = maxWidth // Calculate height based on actual label heights val totalLabelHeight = labels.sumOf { it.preferredSize.height } - val contentHeight = totalLabelHeight + borderInsets.top + borderInsets.bottom + 16 +// val contentHeight = totalLabelHeight + borderInsets.top + borderInsets.bottom + val contentHeight = totalLabelHeight // Set reasonable bounds for the popup with generous sizing // val maxPopupWidth = 1200 // Increased to accommodate longer lines @@ -291,6 +328,10 @@ class NextEditWindowManager(private val project: Project) { border = null preferredSize = java.awt.Dimension(finalWidth, finalHeight) + // Remove any default margins/padding from JScrollPane + viewport.border = null + viewportBorder = null + // Only show scrollbars when actually needed horizontalScrollBarPolicy = if (contentWidth > finalWidth) { JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED @@ -362,7 +403,7 @@ class NextEditWindowManager(private val project: Project) { ) // Use div instead of pre for better control over spacing - return "
$highlightedText
" + return "
$highlightedText
" } private fun addKeyboardShortcuts(panel: JComponent, onAction: (PopupAction) -> Unit) { From 435851c71a5df7761e6273a71815461d03258447 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 15 Aug 2025 19:05:14 -0700 Subject: [PATCH 30/48] fix: use better highlighting --- .../nextEdit/NextEditWindowManager.kt | 407 +++++++++++++----- 1 file changed, 291 insertions(+), 116 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt index 67e511f66..eb8dbea0b 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt @@ -9,14 +9,15 @@ import com.intellij.openapi.components.Service import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.LogicalPosition import com.intellij.openapi.editor.colors.EditorColorsManager -import com.intellij.openapi.editor.colors.EditorFontType import com.intellij.openapi.editor.markup.* +import com.intellij.openapi.fileEditor.FileDocumentManager +import com.intellij.openapi.fileTypes.FileType +import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopup import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.TextRange import com.intellij.ui.JBColor -import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBPanel import com.intellij.util.ui.JBUI import java.awt.* @@ -130,7 +131,7 @@ class NextEditWindowManager(private val project: Project) { diffLines: List, onAction: (PopupAction) -> Unit ) { - val popupComponent = createNextEditPopupComponent(code, diffLines, onAction) + val popupComponent = createNextEditPopupComponent(editor, code, diffLines, onAction) val popup = JBPopupFactory.getInstance() .createComponentPopupBuilder(popupComponent, popupComponent) @@ -203,6 +204,7 @@ class NextEditWindowManager(private val project: Project) { } private fun createNextEditPopupComponent( + editor: Editor, code: String, diffLines: List, onAction: (PopupAction) -> Unit @@ -216,7 +218,7 @@ class NextEditWindowManager(private val project: Project) { } // Create syntax-highlighted code display - val codePanel = createCodeDisplayPanel(code, diffLines) + val codePanel = createCodeDisplayPanel(editor, code, diffLines) panel.add(codePanel, BorderLayout.CENTER) // Add keyboard shortcuts @@ -225,144 +227,317 @@ class NextEditWindowManager(private val project: Project) { return panel } + private fun getActualFontSizeFromEditor(editor: Editor): Int { + try { + val component = editor.contentComponent + val font = component.font + val graphics = component.graphics - private fun createCodeDisplayPanel(code: String, diffLines: List): JComponent { - val scheme = EditorColorsManager.getInstance().globalScheme + if (graphics != null) { + val fontMetrics = graphics.getFontMetrics(font) + val height = fontMetrics.height + val ascent = fontMetrics.ascent - // Use the editor's actual font settings - val editorFont = scheme.getFont(EditorFontType.PLAIN) - val fontSize = scheme.editorFontSize - val actualFont = editorFont.deriveFont(fontSize.toFloat()) + // Check for DPI scaling + val scale = JBUI.scale(1f) + println("DEBUG: UI scale factor: $scale") + println("DEBUG: FontMetrics - height: $height, ascent: $ascent") + println("DEBUG: Font size from font object: ${font.size}") - // Get line spacing from editor settings - val lineSpacing = scheme.lineSpacing - val fontMetrics = java.awt.Toolkit.getDefaultToolkit().getFontMetrics(actualFont) - val baseLineHeight = fontMetrics.height - val actualLineHeight = (baseLineHeight * lineSpacing).toInt() - - val panel = JBPanel>().apply { - layout = BoxLayout(this, BoxLayout.Y_AXIS) - background = scheme.defaultBackground -// border = JBUI.Borders.compound( -// JBUI.Borders.customLine(JBColor.border()), -// JBUI.Borders.empty() -// ) -// border = -// JBUI.Borders.customLine(JBColor.border()) // Remove the compound border entirely, just keep the line - border = null - } - - var maxWidth = 0 - - // Filter out old lines and process only new and same lines from diffLines - val visibleDiffLines = diffLines.filter { it.type != "old" } - - // Create all labels first to measure them properly - val labels = mutableListOf() - - visibleDiffLines.forEach { diffLine -> - val displayText = diffLine.line.ifEmpty { " " } - - // Create HTML content for basic syntax highlighting - val htmlContent = createBasicHighlightedHtml(displayText, actualFont) - - val label = JBLabel(htmlContent).apply { - font = actualFont - isOpaque = true - - when (diffLine.type) { - "new" -> { - // Highlight new additions - background = JBColor(0x2D4A2D, 0x2D4A2D) // Darker green - foreground = scheme.defaultForeground - } - - else -> { // "same" or any other type - // Regular unchanged lines - background = scheme.defaultBackground - foreground = scheme.defaultForeground - } + // Adjust for DPI scaling + val adjustedFontSize = if (scale > 1f) { + (font.size / scale).toInt() + } else { + font.size } - // Match editor's text rendering - alignmentX = JComponent.LEFT_ALIGNMENT + println("DEBUG: Adjusted font size: $adjustedFontSize") + + return adjustedFontSize } - // Let the label calculate its own preferred size based on HTML content - val labelPreferredSize = label.preferredSize - maxWidth = maxOf(maxWidth, labelPreferredSize.width) - - // Set consistent height based on editor line height, but allow for HTML rendering - val adjustedLineHeight = maxOf(actualLineHeight, labelPreferredSize.height) - label.preferredSize = java.awt.Dimension(labelPreferredSize.width, adjustedLineHeight) - label.maximumSize = java.awt.Dimension(Int.MAX_VALUE, adjustedLineHeight) - - labels.add(label) - panel.add(label) + } catch (e: Exception) { + println("DEBUG: Error getting font size: ${e.message}") } - // Calculate dimensions based on actual label measurements - val visibleLineCount = visibleDiffLines.size - val borderInsets = panel.border?.getBorderInsets(panel) ?: java.awt.Insets(0, 0, 0, 0) + return 13 + } - // Use the actual measured max width plus some padding -// val contentWidth = maxWidth + borderInsets.left + borderInsets.right + 24 // More padding for HTML rendering - val contentWidth = maxWidth - // Calculate height based on actual label heights - val totalLabelHeight = labels.sumOf { it.preferredSize.height } -// val contentHeight = totalLabelHeight + borderInsets.top + borderInsets.bottom - val contentHeight = totalLabelHeight + private fun createCodeDisplayPanel(editor: Editor, code: String, diffLines: List): JComponent { + println("DEBUG: createCodeDisplayPanel - START") - // Set reasonable bounds for the popup with generous sizing -// val maxPopupWidth = 1200 // Increased to accommodate longer lines -// val maxPopupHeight = 800 // Increased to show more content -// val minPopupWidth = 500 // Increased minimum width -// val minPopupHeight = maxOf(actualLineHeight * 2, 100) // Minimum 2 lines + try { + val scheme = EditorColorsManager.getInstance().globalScheme + val editorFont = editor.colorsScheme.getFont(com.intellij.openapi.editor.colors.EditorFontType.PLAIN) -// val finalWidth = minOf(maxPopupWidth, maxOf(minPopupWidth, contentWidth)) -// val finalHeight = minOf(maxPopupHeight, maxOf(minPopupHeight, contentHeight)) - val finalWidth = contentWidth - val finalHeight = contentHeight + // Get the actual font size accounting for DPI scaling + val actualFontSize = getActualFontSizeFromEditor(editor) + val fontFamily = editorFont.family - return JScrollPane(panel).apply { - border = null - preferredSize = java.awt.Dimension(finalWidth, finalHeight) + // Also get the line height from editor for consistent spacing + val editorLineHeight = editor.lineHeight + val uiScale = JBUI.scale(1f) +// val adjustedLineHeight = if (uiScale > 1f) (editorLineHeight / uiScale).toInt() else editorLineHeight - // Remove any default margins/padding from JScrollPane - viewport.border = null - viewportBorder = null + val adjustedLineHeight = actualFontSize - // Only show scrollbars when actually needed - horizontalScrollBarPolicy = if (contentWidth > finalWidth) { - JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED - } else { - JScrollPane.HORIZONTAL_SCROLLBAR_NEVER + println("DEBUG: Using font size: $actualFontSize") + println("DEBUG: Editor line height: $editorLineHeight, adjusted: $adjustedLineHeight") + println("DEBUG: UI scale: $uiScale") + + // Get file type for proper syntax highlighting + val fileType = getCurrentFileType(editor) + + // Create panel with proper layout + val panel = JPanel().apply { + layout = BoxLayout(this, BoxLayout.Y_AXIS) + background = scheme.defaultBackground + border = null + isOpaque = true } - verticalScrollBarPolicy = if (contentHeight > finalHeight) { - JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED + val visibleLines = diffLines.filter { it.type != "old" } + val linesToDisplay = if (visibleLines.isEmpty()) { + if (code.isNotEmpty()) { + code.split("\n").map { DiffLine(type = "new", line = it) } + } else { + listOf(DiffLine(type = "new", line = " ")) + } } else { - JScrollPane.VERTICAL_SCROLLBAR_NEVER + visibleLines } - // Use editor's background color - viewport.background = scheme.defaultBackground - background = scheme.defaultBackground + var maxWidth = 200 - // Smooth scrolling like in editor - viewport.scrollMode = javax.swing.JViewport.BACKINGSTORE_SCROLL_MODE + // Create syntax-highlighted labels for each line + linesToDisplay.forEach { diffLine -> + val displayText = if (diffLine.line.isEmpty()) " " else diffLine.line - // Match editor's scroll unit - use actual line height from labels - val averageLineHeight = if (labels.isNotEmpty()) { - labels.sumOf { it.preferredSize.height } / labels.size - } else { - actualLineHeight + val backgroundColor = when (diffLine.type) { + "new" -> JBColor(0x2D4A2D, 0x2D4A2D) + "same" -> scheme.defaultBackground + else -> scheme.defaultBackground + } + + val highlightedHtml = createSyntaxHighlightedHtml( + displayText, + fileType, + scheme, + fontFamily, + actualFontSize, + adjustedLineHeight, // Pass the adjusted line height + backgroundColor + ) + + val label = JLabel(highlightedHtml).apply { + background = backgroundColor + isOpaque = true + border = JBUI.Borders.empty(1, 6) + alignmentX = Component.LEFT_ALIGNMENT + + // Create font with correct size + font = Font(fontFamily, editorFont.style, actualFontSize) + } + + maxWidth = maxOf(maxWidth, label.preferredSize.width + 12) + panel.add(label) + } + + panel.revalidate() + val contentHeight = maxOf(panel.preferredSize.height, 20) + + return JScrollPane(panel).apply { + border = null + preferredSize = Dimension(maxWidth, contentHeight) + minimumSize = Dimension(200, 20) + maximumSize = Dimension(800, 300) + horizontalScrollBarPolicy = JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED + verticalScrollBarPolicy = JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED + viewport.background = scheme.defaultBackground + background = scheme.defaultBackground + } + + } catch (e: Exception) { + println("ERROR: createCodeDisplayPanel failed: ${e.message}") + e.printStackTrace() + return JLabel("Code preview unavailable").apply { + border = JBUI.Borders.empty(10) } - verticalScrollBar.unitIncrement = averageLineHeight - horizontalScrollBar.unitIncrement = fontMetrics.charWidth(' ') * 4 } } + private fun createSyntaxHighlightedHtml( + text: String, + fileType: FileType, + scheme: com.intellij.openapi.editor.colors.EditorColorsScheme, + fontFamily: String, + fontSize: Int, + lineHeight: Int, + backgroundColor: Color + ): String { + // Convert background color to hex + val backgroundHex = + String.format("#%02x%02x%02x", backgroundColor.red, backgroundColor.green, backgroundColor.blue) + + println("DEBUG: HTML font - Family: $fontFamily, Size: ${fontSize}px, LineHeight: ${lineHeight}px") + + if (text.trim().isEmpty()) { + return "" + + "
 
" + + "" + } + + try { + // Get the syntax highlighter for the file type + val syntaxHighlighter = + com.intellij.openapi.fileTypes.SyntaxHighlighterFactory.getSyntaxHighlighter(fileType, project, null) + ?: return createBasicHtml( + text, + fontFamily, + fontSize, + lineHeight, + scheme, + backgroundColor + ) // Updated call + + val lexer = syntaxHighlighter.highlightingLexer + lexer.start(text) + + val highlightedText = StringBuilder() + var lastOffset = 0 + + while (lexer.tokenType != null) { + val tokenStart = lexer.tokenStart + val tokenEnd = lexer.tokenEnd + val tokenType = lexer.tokenType + val tokenText = text.substring(tokenStart, tokenEnd) + + // Add any text between tokens + if (tokenStart > lastOffset) { + val defaultColor = scheme.defaultForeground + val defaultColorHex = + String.format("#%02x%02x%02x", defaultColor.red, defaultColor.green, defaultColor.blue) + highlightedText.append( + "${ + escapeHtml( + text.substring( + lastOffset, + tokenStart + ) + ) + }" + ) + } + + // Get TextAttributesKey from the syntax highlighter + val textAttributesKeys = syntaxHighlighter.getTokenHighlights(tokenType) + + if (textAttributesKeys.isNotEmpty()) { + // Use the first (most specific) attributes key + val textAttributes = scheme.getAttributes(textAttributesKeys[0]) + val color = textAttributes?.foregroundColor ?: scheme.defaultForeground + + val colorHex = String.format("#%02x%02x%02x", color.red, color.green, color.blue) + + var styledToken = "${escapeHtml(tokenText)}" + highlightedText.append(styledToken) + } else { + // No specific highlighting, use default color + val defaultColor = scheme.defaultForeground + val defaultColorHex = + String.format("#%02x%02x%02x", defaultColor.red, defaultColor.green, defaultColor.blue) + highlightedText.append("${escapeHtml(tokenText)}") + } + + lastOffset = tokenEnd + lexer.advance() + } + + // Add any remaining text + if (lastOffset < text.length) { + val defaultColor = scheme.defaultForeground + val defaultColorHex = + String.format("#%02x%02x%02x", defaultColor.red, defaultColor.green, defaultColor.blue) + highlightedText.append("${escapeHtml(text.substring(lastOffset))}") + } + + val toReturn = "" + + "
$highlightedText
" + + "" + return toReturn + + } catch (e: Exception) { + println("DEBUG: Syntax highlighting failed: ${e.message}") + return createBasicHtml(text, fontFamily, fontSize, lineHeight, scheme, backgroundColor) // Updated call + } + } + + private fun createBasicHtml( + text: String, + fontFamily: String, + fontSize: Int, + lineHeight: Int, // Added lineHeight parameter + scheme: com.intellij.openapi.editor.colors.EditorColorsScheme, + backgroundColor: Color + ): String { + val foregroundColor = scheme.defaultForeground + val foregroundHex = + String.format("#%02x%02x%02x", foregroundColor.red, foregroundColor.green, foregroundColor.blue) + val backgroundHex = + String.format("#%02x%02x%02x", backgroundColor.red, backgroundColor.green, backgroundColor.blue) + + return "" + + "
${ + escapeHtml( + text + ) + }
" + + "" + } + + private fun escapeHtml(text: String): String { + return text + .replace("&", "&") + .replace("<", "<") + .replace(">", ">") + .replace("\"", """) + .replace("'", "'") + .replace(" ", " ") + .replace("\t", "    ") + } + + // Then update getCurrentFileType to use it + private fun getCurrentFileType(editor: Editor): FileType { + // Method 1: Use the current editor's virtual file (most reliable) + val virtualFile = FileDocumentManager.getInstance().getFile(editor.document) + virtualFile?.let { file -> + return file.fileType + } + + // Method 2: Try to get from FileEditorManager + val fileEditorManager = com.intellij.openapi.fileEditor.FileEditorManager.getInstance(project) + val currentFile = fileEditorManager.selectedFiles.firstOrNull() + + currentFile?.let { file -> + return file.fileType + } + + // Method 3: Fallback to plain text + return FileTypeManager.getInstance().getFileTypeByExtension("txt") + } + private fun createBasicHighlightedHtml(text: String, font: java.awt.Font): String { if (text.trim() .isEmpty() From 7f5e91d33529092af4ec7122d253bc56c7e00d9f Mon Sep 17 00:00:00 2001 From: Jakub Blach Date: Sun, 17 Aug 2025 02:21:54 +0200 Subject: [PATCH 31/48] fix: migrate to built-in inline completion API from 2024.1 --- .gitignore | 1 + .idea/kotlinc.xml | 6 - extensions/intellij/.gitignore | 1 + .../intellij/.run/Run Extension.run.xml | 3 +- extensions/intellij/build.gradle.kts | 43 +-- extensions/intellij/gradle.properties | 5 +- .../actions/ContinueActionPromote.kt | 20 +- .../autocomplete/AcceptAutocompleteAction.kt | 25 -- .../AutocompleteEditorListener.kt | 151 -------- .../AutocompleteLookupListener.kt | 48 --- .../autocomplete/AutocompleteService.kt | 323 ------------------ .../AutocompleteSpinnerWidgetFactory.kt | 109 ------ .../autocomplete/CancelAutocompleteAction.kt | 35 -- .../autocomplete/CompletionService.kt | 10 + .../autocomplete/ContinueCompletionService.kt | 53 +++ .../autocomplete/ContinueInlayRenderer.kt | 58 ---- .../ContinueInlineCompletionProvider.kt | 54 +++ .../DisableTabAutocompleteAction.kt | 12 - .../EnableTabAutocompleteAction.kt | 12 - .../PartialAcceptAutocompleteAction.kt | 25 -- .../continue/ApplyToFileHandler.kt | 34 +- .../continue/ProfileInfoService.kt | 63 ++++ .../editor/InlineEditPanel.kt | 51 +-- .../license/AddLicenseKeyDialog.kt | 2 +- .../nextEdit/AcceptNextEditAction.kt | 25 -- .../nextEdit/NextEditService.kt | 321 ----------------- .../nextEdit/NextEditWindowService.kt | 304 ----------------- .../src/main/resources/META-INF/plugin.xml | 41 +-- .../e2e/Autocomplete.kt | 4 +- .../unit/ApplyToFileHandlerTest.kt | 16 +- .../ContinueInlineCompletionProviderTest.kt | 122 +++++++ 31 files changed, 368 insertions(+), 1609 deletions(-) delete mode 100644 .idea/kotlinc.xml delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AcceptAutocompleteAction.kt delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteEditorListener.kt delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteLookupListener.kt delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteSpinnerWidgetFactory.kt delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/CancelAutocompleteAction.kt create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/CompletionService.kt create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCompletionService.kt delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlayRenderer.kt create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/DisableTabAutocompleteAction.kt delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/EnableTabAutocompleteAction.kt delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/PartialAcceptAutocompleteAction.kt create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ProfileInfoService.kt delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/AcceptNextEditAction.kt delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditService.kt delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowService.kt create mode 100644 extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinueInlineCompletionProviderTest.kt diff --git a/.gitignore b/.gitignore index bf5b0366d..8eba642ee 100644 --- a/.gitignore +++ b/.gitignore @@ -158,6 +158,7 @@ extensions/intellij/.idea/** **/.idea/shelf/ **/.idea/inspectionProfiles/Project_Default.xml **/.idea/php.xml +**/.idea/kotlinc.xml extensions/intellij/bin diff --git a/.idea/kotlinc.xml b/.idea/kotlinc.xml deleted file mode 100644 index 2b8a50fc2..000000000 --- a/.idea/kotlinc.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - \ No newline at end of file diff --git a/extensions/intellij/.gitignore b/extensions/intellij/.gitignore index 2be56cfd9..147aaa022 100644 --- a/extensions/intellij/.gitignore +++ b/extensions/intellij/.gitignore @@ -4,5 +4,6 @@ src/main/resources/bin src/main/resources/config_schema.json src/main/resources/continue_rc_schema.json video +.intellijPlatform src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue/* !src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue/config.json \ No newline at end of file diff --git a/extensions/intellij/.run/Run Extension.run.xml b/extensions/intellij/.run/Run Extension.run.xml index 30a38f6c4..63b2835d6 100644 --- a/extensions/intellij/.run/Run Extension.run.xml +++ b/extensions/intellij/.run/Run Extension.run.xml @@ -4,14 +4,13 @@ diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts index 8692b35f4..6cd36e473 100644 --- a/extensions/intellij/build.gradle.kts +++ b/extensions/intellij/build.gradle.kts @@ -5,17 +5,14 @@ import org.jetbrains.intellij.platform.gradle.tasks.PrepareSandboxTask fun environment(key: String) = providers.environmentVariable(key) 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" plugins { - kotlin("jvm") version "1.8.0" - id("org.jetbrains.intellij.platform") version "2.6.0" + kotlin("jvm") version "1.9.22" + id("org.jetbrains.intellij.platform") version "2.7.2" 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" @@ -34,42 +31,46 @@ repositories { dependencies { intellijPlatform { - create(platformType, platformVersion) - plugins(listOf("org.jetbrains.plugins.terminal:223.8214.6")) + create("IC", platformVersion) + plugins(listOf("org.jetbrains.plugins.terminal:241.14494.150")) testFramework(TestFrameworkType.Platform) } implementation("com.posthog.java:posthog:1.2.0") + testImplementation("junit:junit:4.13.2") testImplementation("com.intellij.remoterobot:remote-robot:$remoteRobotVersion") testImplementation("com.intellij.remoterobot:remote-fixtures:$remoteRobotVersion") - testImplementation("io.mockk:mockk:1.14.2") + testImplementation("io.mockk:mockk:1.14.2") { + // this transitive dependency (1.6.4) conflicts with built-in version (1.7.3) + // otherwise e2e tests (runIdeForUiTests) will have linkage errors + exclude(group = "org.jetbrains.kotlinx", module = "kotlinx-coroutines-core") + } 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") testRuntimeOnly("org.junit.vintage:junit-vintage-engine:5.10.0") // required to run both JUnit 5 and JUnit 3 } -kotlin { jvmToolchain(17) } +kotlin { + jvmToolchain(17) +} intellijPlatform { pluginConfiguration { ideaVersion { - sinceBuild = pluginSinceBuild + sinceBuild = "241" } } pluginVerification { ides { - ide("IC", "2025.1.4") - ide("IC", "2022.3.3") + ide("IC", "2025.2") + ide("IC", "2025.1") + ide("IC", "2024.3") + ide("IC", "2024.2") + ide("IC", "2024.1") } } } -changelog { - groups.empty() - repositoryUrl = pluginRepositoryUrl -} - qodana { cachePath = provider { file(".qodana").canonicalPath } reportPath = provider { file("build/reports/inspections").canonicalPath } @@ -77,7 +78,11 @@ qodana { showReport = environment("QODANA_SHOW_REPORT").map { it.toBoolean() }.getOrElse(false) } -koverReport { defaults { xml { onCheck = true } } } +koverReport { + defaults { + xml { onCheck = true } + } +} intellijPlatformTesting { runIde { diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index ee83a99f4..50c52640c 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -1,9 +1,6 @@ pluginGroup=com.github.continuedev.continueintellijextension -pluginRepositoryUrl=https://github.com/continuedev/continue pluginVersion=1.0.38 -pluginSinceBuild=223 -platformType=IC -platformVersion=2022.3.3 +platformVersion=2024.1 kotlin.stdlib.default.dependency=false org.gradle.configuration-cache=true org.gradle.caching=true diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt index 747fefd03..c67148937 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt @@ -1,32 +1,14 @@ package com.github.continuedev.continueintellijextension.actions -import com.github.continuedev.continueintellijextension.autocomplete.AcceptAutocompleteAction -import com.github.continuedev.continueintellijextension.nextEdit.AcceptNextEditAction -import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings + import com.intellij.openapi.actionSystem.ActionPromoter import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.DataContext -import com.intellij.openapi.components.service import org.jetbrains.annotations.NotNull class ContinueActionPromote : ActionPromoter { override fun promote(@NotNull actions: List, @NotNull context: DataContext): List? { - // For autocomplete actions - if (actions.any { it is AcceptAutocompleteAction }) { - val settings = service() - if (settings.continueState.showIDECompletionSideBySide) { - return actions.filterIsInstance() - } - } - - if (actions.any { it is AcceptNextEditAction }) { - val settings = service() - if (settings.continueState.showIDECompletionSideBySide) { - return actions.filterIsInstance() - } - } - val rejectDiffActions = actions.filterIsInstance() if (rejectDiffActions.isNotEmpty()) { return rejectDiffActions diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AcceptAutocompleteAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AcceptAutocompleteAction.kt deleted file mode 100644 index 03b91e87c..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AcceptAutocompleteAction.kt +++ /dev/null @@ -1,25 +0,0 @@ -package com.github.continuedev.continueintellijextension.autocomplete - -import com.intellij.openapi.actionSystem.DataContext -import com.intellij.openapi.application.ApplicationManager -import com.intellij.openapi.components.service -import com.intellij.openapi.editor.Caret -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.editor.actionSystem.EditorAction -import com.intellij.openapi.editor.actionSystem.EditorActionHandler - -class AcceptAutocompleteAction : EditorAction(object : EditorActionHandler() { - override fun doExecute(editor: Editor, caret: Caret?, dataContext: DataContext?) { - ApplicationManager.getApplication().runWriteAction { - editor.project?.service()?.accept() - } - } - - override fun isEnabledForCaret(editor: Editor, caret: Caret, dataContext: DataContext?): Boolean { - val autocompleteService = editor.project?.service(); - val enabled = editor == autocompleteService?.pendingCompletion?.editor -// && caret.offset == autocompleteService.pendingCompletion?.offset - && autocompleteService.pendingCompletion?.text != null - return enabled - } -}) \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteEditorListener.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteEditorListener.kt deleted file mode 100644 index 9fca20413..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteEditorListener.kt +++ /dev/null @@ -1,151 +0,0 @@ -package com.github.continuedev.continueintellijextension.autocomplete - -import com.github.continuedev.continueintellijextension.nextEdit.NextEditService -import com.github.continuedev.continueintellijextension.services.ContinuePluginService -import com.github.continuedev.continueintellijextension.utils.castNestedOrNull -import com.intellij.openapi.application.invokeLater -import com.intellij.openapi.components.service -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.editor.EditorKind -import com.intellij.openapi.editor.event.* -import com.intellij.openapi.fileEditor.FileEditorManager -import com.intellij.openapi.fileEditor.FileEditorManagerEvent -import com.intellij.openapi.fileEditor.FileEditorManagerListener -import com.intellij.openapi.util.TextRange - -class AutocompleteCaretListener : CaretListener { - override fun caretPositionChanged(event: CaretEvent) { - if(event.editor.editorKind != EditorKind.MAIN_EDITOR) { - return - } - - val caret = event.caret ?: return - val offset = caret.offset - val editor = caret.editor - val autocompleteService = editor.project?.service() ?: return - - if (autocompleteService.lastChangeWasPartialAccept) { - autocompleteService.lastChangeWasPartialAccept = false - return - } - - val pending = autocompleteService.pendingCompletion; - if (pending != null && pending.editor == editor && pending.offset == offset) { - return - } - autocompleteService.clearCompletions(editor) - } -} - -class AutocompleteDocumentListener(private val editorManager: FileEditorManager, private val editor: Editor) : - DocumentListener { - override fun documentChanged(event: DocumentEvent) { - // Ignore empty changes or changes where content didn't actually change. - if (event.newFragment.isEmpty() && event.oldFragment.isEmpty()) { - return - } - - // Make sure this is an actual text modification event. - if (!event.isWholeTextReplaced && event.offset == 0 && event.oldLength == 0 && event.newLength == 0) { - return - } - - if (editor != editorManager.selectedTextEditor) { - return - } - - val service = editor.project?.service() ?: return - if (service.lastChangeWasPartialAccept) { - return - } - - val nextEditService = editor.project?.service() ?: return - - // Check if we're in a test environment based on some property or condition - val isAutocompleteTestEnvironment = System.getProperty("continue.autocomplete.test.environment") == "true" - val isNextEditTestEnvironment = System.getProperty("continue.nextEdit.test.environment") == "true" - - if (isAutocompleteTestEnvironment) { - invokeLater { - service.triggerCompletion(editor) - } - return - } else if (isNextEditTestEnvironment) { - invokeLater { - nextEditService.triggerNextEdit(editor) - } - return - } - - // Check settings to see if next edit is enabled, and then trigger either autocomplete or next exit. - val continuePluginService = editor.project?.service() - if (continuePluginService == null) { - return - } - - continuePluginService.coreMessenger?.request( - "config/getSerializedProfileInfo", - null, - null, - ({ response -> - val optInNextEditFeature = response.castNestedOrNull( - "content", - "result", - "config", - "experimental", - "optInNextEditFeature" - ) ?: false - - invokeLater { - if (optInNextEditFeature) { - nextEditService.triggerNextEdit(editor) - } else { - // Invoke later is important, otherwise the completion will be triggered before the document is updated - // causing the old caret offset to be used - // TODO: concurrency - service.triggerCompletion(editor) - } - } - }) - ) - } -} - -class AutocompleteEditorListener : EditorFactoryListener { - private val disposables = mutableMapOf Unit>() - override fun editorCreated(event: EditorFactoryEvent) { - val editor = event.editor - val project = editor.project ?: return - val editorManager = project.let { FileEditorManager.getInstance(it) } ?: return - val completionProvider = project.service() - - // Listen to changes to mouse position - val caretListener = AutocompleteCaretListener() - editor.caretModel.addCaretListener(caretListener) - - // Listen to changes to selection - val connection = editor.project?.messageBus?.connect() - connection?.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, object : FileEditorManagerListener { - override fun selectionChanged(event: FileEditorManagerEvent) { - completionProvider.clearCompletions(editor) - } - }) - - // Listen to changes to content - val documentListener = AutocompleteDocumentListener(editorManager, editor) - editor.document.addDocumentListener(documentListener) - - disposables[editor] = { - editor.caretModel.removeCaretListener(caretListener) - connection?.disconnect() - editor.document.removeDocumentListener(documentListener) - } - } - - override fun editorReleased(event: EditorFactoryEvent) { - val editor = event.editor - val disposable = disposables[editor] - disposable?.invoke() - disposables.remove(editor) - } -} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteLookupListener.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteLookupListener.kt deleted file mode 100644 index 2f2fa593b..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteLookupListener.kt +++ /dev/null @@ -1,48 +0,0 @@ -package com.github.continuedev.continueintellijextension.autocomplete - -import com.intellij.codeInsight.lookup.impl.LookupImpl -import com.intellij.codeInsight.lookup.Lookup -import com.intellij.codeInsight.lookup.LookupEvent -import com.intellij.codeInsight.lookup.LookupListener -import com.intellij.codeInsight.lookup.LookupManagerListener -import com.intellij.openapi.application.ApplicationManager -import com.intellij.openapi.components.Service -import com.intellij.openapi.components.service -import com.intellij.openapi.project.Project -import java.util.concurrent.atomic.AtomicBoolean - -@Service(Service.Level.PROJECT) -class AutocompleteLookupListener(project: Project) : LookupManagerListener { - private val isLookupShown = AtomicBoolean(true) - - fun isLookupEmpty(): Boolean { - return isLookupShown.get() - } - - init { - project.messageBus.connect().subscribe(LookupManagerListener.TOPIC, this) - } - - override fun activeLookupChanged(oldLookup: Lookup?, newLookup: Lookup?) { - val newEditor = newLookup?.editor ?: return - if (newLookup is LookupImpl) { - newLookup.addLookupListener( - object : LookupListener { - override fun lookupShown(event: LookupEvent) { - isLookupShown.set(false) - ApplicationManager.getApplication().invokeLater { - event.lookup.editor.project?.service()?.hideCompletions(newEditor) - } - } - - override fun lookupCanceled(event: LookupEvent) { - isLookupShown.set(true) - } - - override fun itemSelected(event: LookupEvent) { - isLookupShown.set(true) - } - }) - } - } -} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt deleted file mode 100644 index 4a84a202b..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt +++ /dev/null @@ -1,323 +0,0 @@ -package com.github.continuedev.continueintellijextension.autocomplete - -import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings -import com.github.continuedev.continueintellijextension.services.ContinuePluginService -import com.github.continuedev.continueintellijextension.utils.toUriOrNull -import com.github.continuedev.continueintellijextension.utils.uuid -import com.intellij.injected.editor.VirtualFileWindow -import com.intellij.openapi.application.* -import com.intellij.openapi.components.Service -import com.intellij.openapi.components.service -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.editor.InlayProperties -import com.intellij.openapi.editor.impl.EditorImpl -import com.intellij.openapi.fileEditor.FileDocumentManager -import com.intellij.openapi.project.Project -import com.intellij.openapi.util.TextRange -import com.intellij.openapi.wm.WindowManager -import com.intellij.psi.PsiDocumentManager -import com.intellij.psi.PsiElement - -data class PendingCompletion( - val editor: Editor, - var offset: Int, - val completionId: String, - var text: String? -) - - -fun PsiElement.isInjectedText(): Boolean { - val virtualFile = this.containingFile.virtualFile ?: return false - if (virtualFile is VirtualFileWindow) { - return true - } - return false -} - -fun Editor.addInlayElement( - lines: List, - offset: Int, - properties: InlayProperties -) { - if (this is EditorImpl) { - if (lines[0].isNotEmpty()) { - inlayModel.addInlineElement(offset, properties, ContinueInlayRenderer(listOf(lines[0]))) - } - if (lines.size > 1) { - inlayModel.addBlockElement(offset, properties, ContinueInlayRenderer(lines.drop(1))) - } - } -} - -@Service(Service.Level.PROJECT) -class AutocompleteService(private val project: Project) { - var pendingCompletion: PendingCompletion? = null - private val autocompleteLookupListener = project.service() - private val widget: AutocompleteSpinnerWidget? by lazy { - WindowManager.getInstance().getStatusBar(project) - ?.getWidget(AutocompleteSpinnerWidget.ID) as? AutocompleteSpinnerWidget - } - - // To avoid triggering another completion on partial acceptance, - // we need to keep track of whether the last change was a partial accept - var lastChangeWasPartialAccept = false - - fun triggerCompletion(editor: Editor) { - val settings = service() - if (!settings.continueState.enableTabAutocomplete) { - return - } - - if (pendingCompletion != null) { - clearCompletions(pendingCompletion!!.editor) - } - - // Set pending completion - val completionId = uuid() - val offset = editor.caretModel.primaryCaret.offset - pendingCompletion = PendingCompletion(editor, offset, completionId, null) - - // Request a completion from the core - val virtualFile = FileDocumentManager.getInstance().getFile(editor.document) - - val uri = virtualFile?.toUriOrNull() ?: return - - widget?.setLoading(true) - - val line = editor.caretModel.primaryCaret.logicalPosition.line - val column = editor.caretModel.primaryCaret.logicalPosition.column - val input = mapOf( - "completionId" to completionId, - "filepath" to uri, - "pos" to mapOf( - "line" to line, - "character" to column - ), - "clipboardText" to "", - "recentlyEditedRanges" to emptyList(), - "recentlyVisitedRanges" to emptyList(), - ) - - project.service().coreMessenger?.request( - "autocomplete/complete", - input, - null, - ({ response -> - if (pendingCompletion == null || pendingCompletion?.completionId == completionId) { - widget?.setLoading(false) - } - - val responseObject = response as Map<*, *> - val completions = responseObject["content"] as List<*> - - if (completions.isNotEmpty()) { - val completion = completions[0].toString() - val finalTextToInsert = deduplicateCompletion(editor, offset, completion) - - if (shouldRenderCompletion(finalTextToInsert, offset, line, editor)) { - renderCompletion(editor, offset, finalTextToInsert) - pendingCompletion = PendingCompletion(editor, offset, completionId, finalTextToInsert) - } - } - }) - ) - } - - private fun shouldRenderCompletion(completion: String, offset: Int, line: Int, editor: Editor): Boolean { - if (completion.isEmpty() || runReadAction { offset != editor.caretModel.offset }) { - return false - } - - if (completion.lines().size == 1) { - return true - } - - val endOffset = editor.document.getLineEndOffset(line) - - // Do not render if completion is multi-line and caret is in middle of line - return offset <= endOffset && editor.document.getText(TextRange(offset, endOffset)).isBlank() - } - - private fun deduplicateCompletion(editor: Editor, offset: Int, completion: String): String { - // Check if completion matches the first 10 characters after the cursor - return ApplicationManager.getApplication().runReadAction { - val document = editor.document - val caretOffset = editor.caretModel.offset - - // Don't care about it if it's at the end of the document - if (caretOffset == document.textLength) return@runReadAction completion - - val N = 10 - var textAfterCursor = if (caretOffset + N <= document.textLength) { - document.getText(TextRange(caretOffset, caretOffset + N)) - } else { - document.getText(TextRange(caretOffset, document.textLength)) - } - - // Avoid truncating the completion text when the text after the cursor is blank - if (textAfterCursor.isBlank()) return@runReadAction completion - - // Determine the index of a newline character within the text following the cursor. - val newlineIndex = textAfterCursor.indexOf("\r\n").takeIf { it >= 0 } ?: textAfterCursor.indexOf('\n') - // If a newline character is found and the current line is not empty, truncate the text at that point. - if (newlineIndex > 0) { - textAfterCursor = textAfterCursor.substring(0, newlineIndex) - } - - val indexOfTextAfterCursorInCompletion = completion.indexOf(textAfterCursor) - if (indexOfTextAfterCursorInCompletion > 0) { - return@runReadAction completion.slice(0..indexOfTextAfterCursorInCompletion - 1) - } else if (indexOfTextAfterCursorInCompletion == 0) { - return@runReadAction "" - } - - return@runReadAction completion - } - } - - private fun renderCompletion(editor: Editor, offset: Int, completion: String) { - if (completion.isEmpty()) { - return - } - if (isInjectedFile(editor)) return - // Skip rendering completions if the code completion dropdown is already visible and the IDE completion side-by-side setting is disabled - if (shouldSkipRender()) { - return - } - - invokeLater { - // Clear existing completions - hideCompletions(editor) - - val properties = InlayProperties() - properties.relatesToPrecedingText(true) - properties.disableSoftWrapping(true) - - val lines = completion.lines() - pendingCompletion = pendingCompletion?.copy(text = lines.joinToString("\n")) - editor.addInlayElement(lines, offset, properties) - -// val attributes = TextAttributes().apply { -// backgroundColor = JBColor.GREEN -// } -// val key = TextAttributesKey.createTextAttributesKey("CONTINUE_AUTOCOMPLETE") -// key.let { editor.colorsScheme.setAttributes(it, attributes) } -// editor.markupModel.addLineHighlighter(key, editor.caretModel.logicalPosition.line, HighlighterLayer.LAST) - } - } - - fun accept() { - val completion = pendingCompletion ?: return - val text = completion.text ?: return - val editor = completion.editor - val offset = completion.offset - editor.document.insertString(offset, text) - - editor.caretModel.moveToOffset(offset + text.length) - - project.service().coreMessenger?.request( - "autocomplete/accept", - hashMapOf("completionId" to completion.completionId), - null, - ({}) - ) - invokeLater { - clearCompletions(editor, completion) - } - } - - private fun shouldSkipRender(): Boolean { - val settings = service() - return !settings.continueState.showIDECompletionSideBySide && !autocompleteLookupListener.isLookupEmpty() - } - - private fun splitKeepingDelimiters(input: String, delimiterPattern: String = "\\s+"): List { - val initialSplit = input.split("(?<=$delimiterPattern)|(?=$delimiterPattern)".toRegex()) - .filter { it.isNotEmpty() } - - val result = mutableListOf() - var currentDelimiter = "" - - for (part in initialSplit) { - if (part.matches(delimiterPattern.toRegex())) { - currentDelimiter += part - } else { - if (currentDelimiter.isNotEmpty()) { - result.add(currentDelimiter) - currentDelimiter = "" - } - result.add(part) - } - } - - if (currentDelimiter.isNotEmpty()) { - result.add(currentDelimiter) - - } - - return result - } - - fun partialAccept() { - val completion = pendingCompletion ?: return - val text = completion.text ?: return - val editor = completion.editor - val offset = completion.offset - - lastChangeWasPartialAccept = true - - // Split the text into words, keeping delimiters - val words = splitKeepingDelimiters(text) - println(words) - val word = words[0] - editor.document.insertString(offset, word) - editor.caretModel.moveToOffset(offset + word.length) - - // Remove the completion and re-display it - hideCompletions(editor) - completion.text = text.substring(word.length) - completion.offset += word.length - renderCompletion(editor, completion.offset, completion.text!!) - } - - private fun cancelCompletion(completion: PendingCompletion) { - // Send cancellation message to core - widget?.setLoading(false) - project.service().coreMessenger?.request("autocomplete/cancel", null, null, ({})) - } - - fun clearCompletions(editor: Editor, completion: PendingCompletion? = pendingCompletion) { - if (isInjectedFile(editor)) return - - if (completion != null) { - cancelCompletion(completion) - if (completion.completionId == pendingCompletion?.completionId) pendingCompletion = null - } - disposeInlayRenderer(editor) - } - - private fun isInjectedFile(editor: Editor): Boolean { - return runReadAction { - PsiDocumentManager.getInstance(project).getPsiFile(editor.document)?.isInjectedText() ?: false - } - } - - fun hideCompletions(editor: Editor) { - if (isInjectedFile(editor)) return - - disposeInlayRenderer(editor) - } - - private fun disposeInlayRenderer(editor: Editor) { - editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength).forEach { - if (it.renderer is ContinueInlayRenderer) { - it.dispose() - } - } - editor.inlayModel.getBlockElementsInRange(0, editor.document.textLength).forEach { - if (it.renderer is ContinueInlayRenderer) { - it.dispose() - } - } - } -} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteSpinnerWidgetFactory.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteSpinnerWidgetFactory.kt deleted file mode 100644 index b19baf669..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteSpinnerWidgetFactory.kt +++ /dev/null @@ -1,109 +0,0 @@ -package com.github.continuedev.continueintellijextension.autocomplete - -import com.github.continuedev.continueintellijextension.Icons -import com.github.continuedev.continueintellijextension.activities.ContinuePluginDisposable -import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings -import com.intellij.openapi.Disposable -import com.intellij.openapi.components.service -import com.intellij.openapi.project.Project -import com.intellij.openapi.util.Disposer -import com.intellij.openapi.wm.StatusBar -import com.intellij.openapi.wm.StatusBarWidget -import com.intellij.openapi.util.IconLoader -import com.intellij.openapi.wm.StatusBarWidgetFactory -import com.intellij.openapi.wm.WindowManager -import com.intellij.openapi.wm.impl.status.EditorBasedWidget -import com.intellij.ui.AnimatedIcon -import com.intellij.util.Consumer -import java.awt.event.MouseEvent -import javax.swing.Icon -import javax.swing.JLabel - -class AutocompleteSpinnerWidget(project: Project) : EditorBasedWidget(project), StatusBarWidget.IconPresentation, - Disposable { - private val iconLabel = JLabel() - private var isLoading = false - - private val animatedIcon = AnimatedIcon.Default() - - init { - Disposer.register(project.service(), this) - updateIcon() - } - - fun show() { - println("Showing autocomplete spinner widget") - } - - override fun dispose() {} - - override fun ID(): String { - return ID - } - - override fun getTooltipText(): String { - val enabled = service().state.enableTabAutocomplete - return if (enabled) "Continue autocomplete enabled" else "Continue autocomplete disabled" - } - - override fun getClickConsumer(): Consumer? { - return null - } - - override fun getIcon(): Icon = if (isLoading) animatedIcon else - Icons.Continue - - fun setLoading(loading: Boolean) { - isLoading = loading - updateIcon() - } - - private fun updateIcon() { - iconLabel.icon = getIcon() - - - // Update the widget - val statusBar = WindowManager.getInstance().getStatusBar(project) - statusBar?.updateWidget(ID()) - } - - override fun install(statusBar: StatusBar) { - updateIcon() - } - - override fun getPresentation(): StatusBarWidget.WidgetPresentation { - return this - } - - companion object { - const val ID = "AutocompleteSpinnerWidget" - } -} - -class AutocompleteSpinnerWidgetFactory : StatusBarWidgetFactory { - fun create(project: Project): AutocompleteSpinnerWidget { - return AutocompleteSpinnerWidget(project) - } - - override fun getId(): String { - return AutocompleteSpinnerWidget.ID - } - - override fun getDisplayName(): String { - return "Continue Autocomplete" - } - - override fun isAvailable(p0: Project): Boolean { - return true - } - - override fun createWidget(project: Project): StatusBarWidget { - return create(project) - } - - override fun disposeWidget(p0: StatusBarWidget) { - Disposer.dispose(p0) - } - - override fun canBeEnabledOn(p0: StatusBar): Boolean = true -} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/CancelAutocompleteAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/CancelAutocompleteAction.kt deleted file mode 100644 index 8b5159d4d..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/CancelAutocompleteAction.kt +++ /dev/null @@ -1,35 +0,0 @@ -package com.github.continuedev.continueintellijextension.autocomplete - -import com.intellij.openapi.actionSystem.ActionUpdateThread -import com.intellij.openapi.actionSystem.AnAction -import com.intellij.openapi.actionSystem.AnActionEvent -import com.intellij.openapi.actionSystem.CommonDataKeys -import com.intellij.openapi.application.ApplicationManager -import com.intellij.openapi.components.service -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.project.Project - -class CancelAutocompleteAction : AnAction() { - override fun actionPerformed(e: AnActionEvent) { - if (isInvokedInEditor(e)) { - val editor = e.getRequiredData(CommonDataKeys.EDITOR) - ApplicationManager.getApplication().runWriteAction { - editor.project?.service()?.clearCompletions(editor) - } - } - } - - override fun update(e: AnActionEvent) { - e.presentation.isEnabledAndVisible = isInvokedInEditor(e) - } - - private fun isInvokedInEditor(e: AnActionEvent): Boolean { - val project: Project? = e.project - val editor: Editor? = e.getData(CommonDataKeys.EDITOR) - return project != null && editor != null && editor.contentComponent.hasFocus() - } - - override fun getActionUpdateThread(): ActionUpdateThread { - return ActionUpdateThread.BGT - } -} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/CompletionService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/CompletionService.kt new file mode 100644 index 000000000..ad06d95d5 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/CompletionService.kt @@ -0,0 +1,10 @@ +package com.github.continuedev.continueintellijextension.autocomplete + + +interface CompletionService { + + suspend fun getAutocomplete(uuid: String, url: String, line: Int, column: Int): String? + + fun acceptAutocomplete(uuid: String?) + +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCompletionService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCompletionService.kt new file mode 100644 index 000000000..4eae86f8d --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueCompletionService.kt @@ -0,0 +1,53 @@ +package com.github.continuedev.continueintellijextension.autocomplete + +import com.github.continuedev.continueintellijextension.`continue`.ProfileInfoService +import com.github.continuedev.continueintellijextension.services.ContinuePluginService +import com.github.continuedev.continueintellijextension.utils.castNestedOrNull +import com.intellij.openapi.components.Service +import com.intellij.openapi.components.service +import com.intellij.openapi.project.Project +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.coroutines.withTimeoutOrNull +import kotlin.time.Duration.Companion.milliseconds + +@Service(Service.Level.PROJECT) +class ContinueCompletionService(private val project: Project) : CompletionService { + + override suspend fun getAutocomplete(uuid: String, url: String, line: Int, column: Int): String? { + val requestInput = getCompletionInput(uuid, url, line, column) + val modelTimeout = project.service().fetchModelTimeoutOrNull() ?: 1000.0 + return withTimeoutOrNull(modelTimeout.milliseconds) { + suspendCancellableCoroutine { continuation -> + project.service().coreMessenger?.request( + "autocomplete/complete", + requestInput, + null + ) { + val content = it.castNestedOrNull>("content")?.firstOrNull() ?: "" + continuation.resumeWith(Result.success(content)) + } + } + } + } + + override fun acceptAutocomplete(uuid: String?) { + project.service().coreMessenger?.request( + "autocomplete/accept", + mapOf("completionId" to uuid), + null + ) {} + } + + private fun getCompletionInput(uuid: String, filepath: String, line: Int, character: Int): Map = mapOf( + "completionId" to uuid, + "filepath" to filepath, + "pos" to mapOf( + "line" to line, + "character" to character + ), + "clipboardText" to "", + "recentlyEditedRanges" to emptyList(), + "recentlyVisitedRanges" to emptyList(), + ) + +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlayRenderer.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlayRenderer.kt deleted file mode 100644 index bcf37fa20..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlayRenderer.kt +++ /dev/null @@ -1,58 +0,0 @@ -package com.github.continuedev.continueintellijextension.autocomplete - -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.editor.EditorCustomElementRenderer -import com.intellij.openapi.editor.Inlay -import com.intellij.openapi.editor.colors.EditorFontType -import com.intellij.openapi.editor.impl.EditorImpl -import com.intellij.openapi.editor.markup.TextAttributes -import com.intellij.ui.JBColor -import com.intellij.util.ui.UIUtil -import java.awt.Font -import java.awt.Graphics -import java.awt.Rectangle - -/** - * The `ContinueInlayRenderer` class is responsible for rendering custom inlay elements within an editor. - * It implements the [EditorCustomElementRenderer] interface to provide custom rendering logic for inlays. - * - * This renderer is designed to display a list of text lines (`lines`) within the editor, calculating the - * necessary width and height based on the content and rendering each line with appropriate font and color. - * - * @author lk - */ -class ContinueInlayRenderer(val lines: List) : EditorCustomElementRenderer { - override fun calcWidthInPixels(inlay: Inlay<*>): Int { - var maxLen = 0; - for (line in lines) { - val len = (inlay.editor as EditorImpl).getFontMetrics(Font.PLAIN).stringWidth(line) - if (len > maxLen) { - maxLen = len - } - } - return maxLen - } - - override fun calcHeightInPixels(inlay: Inlay<*>): Int { - return (inlay.editor as EditorImpl).lineHeight * lines.size - } - - private fun font(editor: Editor): Font { - val editorFont = editor.colorsScheme.getFont(EditorFontType.PLAIN) - return UIUtil.getFontWithFallbackIfNeeded(editorFont, lines.joinToString("\n")) - .deriveFont(editor.colorsScheme.editorFontSize) - } - - override fun paint(inlay: Inlay<*>, g: Graphics, targetRegion: Rectangle, textAttributes: TextAttributes) { - val editor = inlay.editor - g.color = JBColor.GRAY - g.font = font(editor) - var additionalYOffset = 0 - val ascent = editor.ascent - val lineHeight = editor.lineHeight - for (line in lines) { - g.drawString(line, targetRegion.x, targetRegion.y + ascent + additionalYOffset) - additionalYOffset += lineHeight - } - } -} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt new file mode 100644 index 000000000..1d815a62f --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt @@ -0,0 +1,54 @@ +package com.github.continuedev.continueintellijextension.autocomplete + +import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings +import com.github.continuedev.continueintellijextension.utils.uuid +import com.intellij.codeInsight.inline.completion.* +import com.intellij.codeInsight.inline.completion.elements.InlineCompletionElement +import com.intellij.codeInsight.inline.completion.elements.InlineCompletionGrayTextElement +import com.intellij.codeInsight.inline.completion.suggestion.InlineCompletionSingleSuggestion +import com.intellij.codeInsight.inline.completion.suggestion.InlineCompletionSuggestion +import com.intellij.openapi.components.service +import com.intellij.openapi.project.Project +import kotlinx.coroutines.flow.flowOf + +class ContinueInlineCompletionProvider : InlineCompletionProvider { + override val id get() = InlineCompletionProviderID("Continue") + override val insertHandler: InlineCompletionInsertHandler = NotifyingHandler() + private var lastUuid: String? = null + private var lastProject: Project? = null + + override fun isEnabled(event: InlineCompletionEvent): Boolean { + val isSettingEnabled = ContinueExtensionSettings.instance.continueState.enableTabAutocomplete + val isEventOk = event is InlineCompletionEvent.DirectCall + || event is InlineCompletionEvent.DocumentChange + || event is InlineCompletionEvent.LookupChange + return isSettingEnabled && isEventOk + } + + override suspend fun getSuggestion(request: InlineCompletionRequest): InlineCompletionSuggestion { + val editor = request.editor + val project = request.file.project + lastUuid = uuid() + lastProject = project + val variant = project.service().getAutocomplete( + lastUuid!!, + editor.virtualFile.url, + editor.caretModel.primaryCaret.logicalPosition.line, + editor.caretModel.primaryCaret.logicalPosition.column + ) + if (variant == null) + return InlineCompletionSuggestion.Empty + return InlineCompletionSingleSuggestion.build(elements = flowOf(InlineCompletionGrayTextElement(variant))) + } + + private inner class NotifyingHandler : DefaultInlineCompletionInsertHandler() { + + override fun afterInsertion( + environment: InlineCompletionInsertEnvironment, + elements: List + ) { + super.afterInsertion(environment, elements) + lastProject?.service()?.acceptAutocomplete(lastUuid) + } + } +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/DisableTabAutocompleteAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/DisableTabAutocompleteAction.kt deleted file mode 100644 index d7e1f3b13..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/DisableTabAutocompleteAction.kt +++ /dev/null @@ -1,12 +0,0 @@ -package com.github.continuedev.continueintellijextension.autocomplete - -import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings -import com.intellij.openapi.actionSystem.AnAction -import com.intellij.openapi.actionSystem.AnActionEvent -import com.intellij.openapi.components.service -class DisableTabAutocompleteAction : AnAction() { - override fun actionPerformed(e: AnActionEvent) { - val continueSettingsService = service() - continueSettingsService.continueState.enableTabAutocomplete = true - } -} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/EnableTabAutocompleteAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/EnableTabAutocompleteAction.kt deleted file mode 100644 index b14aa2190..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/EnableTabAutocompleteAction.kt +++ /dev/null @@ -1,12 +0,0 @@ -package com.github.continuedev.continueintellijextension.autocomplete - -import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings -import com.intellij.openapi.actionSystem.AnAction -import com.intellij.openapi.actionSystem.AnActionEvent -import com.intellij.openapi.components.service -class EnableTabAutocompleteAction : AnAction() { - override fun actionPerformed(e: AnActionEvent) { - val continueSettingsService = service() - continueSettingsService.continueState.enableTabAutocomplete = true - } -} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/PartialAcceptAutocompleteAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/PartialAcceptAutocompleteAction.kt deleted file mode 100644 index 0af47bbc7..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/PartialAcceptAutocompleteAction.kt +++ /dev/null @@ -1,25 +0,0 @@ -package com.github.continuedev.continueintellijextension.autocomplete - -import com.intellij.openapi.actionSystem.DataContext -import com.intellij.openapi.application.ApplicationManager -import com.intellij.openapi.components.service -import com.intellij.openapi.editor.Caret -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.editor.actionSystem.EditorAction -import com.intellij.openapi.editor.actionSystem.EditorActionHandler - -class PartialAcceptAutocompleteAction : EditorAction(object : EditorActionHandler() { - override fun doExecute(editor: Editor, caret: Caret?, dataContext: DataContext?) { - ApplicationManager.getApplication().runWriteAction { - editor.project?.service()?.partialAccept() - } - } - - override fun isEnabledForCaret(editor: Editor, caret: Caret, dataContext: DataContext?): Boolean { - val autocompleteService = editor.project?.service(); - val enabled = editor == autocompleteService?.pendingCompletion?.editor - && caret.offset == autocompleteService.pendingCompletion?.offset - && autocompleteService.pendingCompletion?.text != null - return enabled - } -}) {} \ No newline at end of file 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 856215be2..158c61a50 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 @@ -9,13 +9,9 @@ import com.github.continuedev.continueintellijextension.editor.DiffStreamService import com.github.continuedev.continueintellijextension.editor.EditorUtils import com.github.continuedev.continueintellijextension.protocol.ApplyToFileParams import com.github.continuedev.continueintellijextension.services.ContinuePluginService -import com.github.continuedev.continueintellijextension.utils.castNestedOrNull import com.intellij.openapi.components.service import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project -import kotlinx.coroutines.suspendCancellableCoroutine -import kotlin.coroutines.resume -import kotlin.coroutines.resumeWithException /** * Handles applying text to a file with streaming diff preview @@ -122,33 +118,9 @@ class ApplyToFileHandler( } private suspend fun fetchApplyLLMConfig(): Any? { - return try { - suspendCancellableCoroutine { continuation -> - continuePluginService.coreMessenger?.request( - "config/getSerializedProfileInfo", null, null - ) { response -> - try { - val selectedModels = response.castNestedOrNull>( - "content", "result", "config", "selectedModelByRole" - ) - - // If "apply" role model is not found, try "chat" role - val applyCodeBlockModel = selectedModels?.get("apply") ?: selectedModels?.get("chat") - - if (applyCodeBlockModel != null) { - continuation.resume(applyCodeBlockModel) - } else { - // If neither "apply" nor "chat" models are available, return with exception - continuation.resumeWithException(IllegalStateException("No 'apply' or 'chat' model found in configuration.")) - } - } catch (e: Exception) { - continuation.resumeWithException(e) - } - } - } - } catch (_: Exception) { - null - } + val selectedModelByRole = project.service().fetchSelectedModelByRoleOrNull() + return selectedModelByRole?.get("apply") + ?: selectedModelByRole?.get("chat") } private fun setupAndStreamDiffs(editorUtils: EditorUtils, llm: Any) { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ProfileInfoService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ProfileInfoService.kt new file mode 100644 index 000000000..676563921 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ProfileInfoService.kt @@ -0,0 +1,63 @@ +package com.github.continuedev.continueintellijextension.`continue` + +import com.github.continuedev.continueintellijextension.services.ContinuePluginService +import com.github.continuedev.continueintellijextension.utils.castNestedOrNull +import com.intellij.openapi.components.Service +import com.intellij.openapi.components.service +import com.intellij.openapi.diagnostic.Logger +import com.intellij.openapi.project.Project +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.coroutines.withTimeoutOrNull +import kotlin.time.Duration.Companion.seconds + +@Service(Service.Level.PROJECT) +class ProfileInfoService(private val project: Project) { + private val log = Logger.getInstance(ProfileInfoService::class.java) + private var fallbackInfo: Any? = null // todo: add type + deserialize + + suspend fun fetchModelTimeoutOrNull() = + fetchOrNull().castNestedOrNull( + "content", + "result", + "config", + "tabAutocompleteOptions", + "modelTimeout" + ) + + suspend fun fetchSelectedModelByRoleOrNull(): Map? = + fetchOrNull().castNestedOrNull>( + "content", + "result", + "config", + "selectedModelByRole" + ) + + suspend fun fetchModelsByRoleOrNull() = + fetchOrNull().castNestedOrNull>( + "content", + "result", + "config", + "modelsByRole" + ) + + private suspend fun fetchOrNull(): Any? { + val actual = withTimeoutOrNull(1.seconds) { + suspendCancellableCoroutine { continuation -> + project.service().coreMessenger?.request( + "config/getSerializedProfileInfo", + null, + null + ) { response -> + continuation.resumeWith(Result.success(response)) + } + } + } + if (actual == null) { + log.warn("Fall back to previous settings due to timeout") + return fallbackInfo + } + fallbackInfo = actual + return actual + } + +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt index f5e8b81ee..e0dbcb0c2 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt @@ -2,8 +2,8 @@ package com.github.continuedev.continueintellijextension.editor import com.github.continuedev.continueintellijextension.Icons import com.github.continuedev.continueintellijextension.`continue`.GetTheme +import com.github.continuedev.continueintellijextension.`continue`.ProfileInfoService import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings -import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.github.continuedev.continueintellijextension.utils.castNestedOrNull import com.github.continuedev.continueintellijextension.utils.getMetaKeyLabel import com.github.continuedev.continueintellijextension.utils.getShiftKeyLabel @@ -14,12 +14,13 @@ import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.colors.EditorFontType import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.project.Project -import com.intellij.openapi.util.IconLoader import com.intellij.openapi.util.Ref import com.intellij.openapi.util.TextRange import com.intellij.ui.JBColor import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeoutOrNull import java.awt.* import java.awt.event.* import java.awt.geom.AffineTransform @@ -34,6 +35,7 @@ import kotlin.math.max import net.miginfocom.swing.MigLayout import org.jdesktop.swingx.JXPanel import org.jdesktop.swingx.JXTextArea +import kotlin.time.Duration.Companion.milliseconds const val MAIN_FONT_SIZE = 13 const val DOWN_ARROW = " ▾" @@ -43,37 +45,21 @@ const val MAX_MODEL_WAIT_TIME = 1500 * Fetches and combines available model titles from both "edit" and "chat" roles. * Edit models are prioritized and appear first in the returned list. * Handles duplicate models by only including them once (prioritizing edit role). - * - * @param continuePluginService The service used to fetch config information - * @return List of model titles with edit models first, duplicates removed - * @throws No exceptions, but will return empty list if request fails or times out after 1.5 seconds */ -fun getModelTitles(continuePluginService: ContinuePluginService): List { - val modelTitles = mutableListOf() - - continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response -> - val modelsByRole = - response.castNestedOrNull>("content", "result", "config", "modelsByRole") ?: return@request - - // Get edit models first - val editModels = modelsByRole.castNestedOrNull>("edit") - ?.mapNotNull { it.castNestedOrNull("title") } ?: emptyList() - - // Then get chat models - val chatModels = modelsByRole.castNestedOrNull>("chat") - ?.mapNotNull { it.castNestedOrNull("title") } ?: emptyList() - - // Add edit models first, then chat models (avoiding duplicates) - modelTitles.addAll(editModels) - modelTitles.addAll(chatModels.filter { it !in editModels }) +fun getModelTitles(project: Project): List { + // fixme: blocking code on EDT (however this is not a regression compared to the latest changes) + return runBlocking { + withTimeoutOrNull(MAX_MODEL_WAIT_TIME.milliseconds) { + val modelsByRole = project.service().fetchModelsByRoleOrNull() + val editModels = modelsByRole.castNestedOrNull>("edit") + ?.mapNotNull { it.castNestedOrNull("title") } + ?: emptyList() + val chatModels = modelsByRole.castNestedOrNull>("chat") + ?.mapNotNull { it.castNestedOrNull("title") } + ?: emptyList() + (editModels + chatModels).distinct() + } ?: emptyList() } - - val startTime = System.currentTimeMillis() - while (modelTitles.isEmpty() && System.currentTimeMillis() - startTime < MAX_MODEL_WAIT_TIME) { - Thread.sleep(20) - } - - return modelTitles } fun makeTextArea(): JTextArea { @@ -161,8 +147,7 @@ fun openInlineEdit(project: Project?, editor: Editor) { val manager = EditorComponentInlaysManager.from(editor, true) - val continuePluginService = project.service() - val modelTitles = getModelTitles(continuePluginService) + val modelTitles = getModelTitles(project) val highlightedRIF = editorUtils.getHighlightedRIF() ?: return val (startLineNumber, endLineNumber) = highlightedRIF.lines diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/license/AddLicenseKeyDialog.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/license/AddLicenseKeyDialog.kt index 9d6a13334..4ba6f2e21 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/license/AddLicenseKeyDialog.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/license/AddLicenseKeyDialog.kt @@ -24,7 +24,7 @@ class AddLicenseKeyDialog(project: Project?) : DialogWrapper(project) { textField().bindText(::licenseKey) .horizontalAlign(HorizontalAlign.FILL) .focused() - .validation { + .validationOnApply { if (it.text.isBlank()) ValidationInfo("License key cannot be empty") else diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/AcceptNextEditAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/AcceptNextEditAction.kt deleted file mode 100644 index 88d43bdb8..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/AcceptNextEditAction.kt +++ /dev/null @@ -1,25 +0,0 @@ -package com.github.continuedev.continueintellijextension.nextEdit - -import com.intellij.openapi.actionSystem.DataContext -import com.intellij.openapi.application.ApplicationManager -import com.intellij.openapi.components.service -import com.intellij.openapi.editor.Caret -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.editor.actionSystem.EditorAction -import com.intellij.openapi.editor.actionSystem.EditorActionHandler - -class AcceptNextEditAction : EditorAction(object : EditorActionHandler() { - override fun doExecute(editor: Editor, caret: Caret?, dataContext: DataContext?) { - ApplicationManager.getApplication().runWriteAction { - editor.project?.service()?.accept() - } - } - - override fun isEnabledForCaret(editor: Editor, caret: Caret, dataContext: DataContext?): Boolean { - val nextEditService = editor.project?.service(); - val enabled = editor == nextEditService?.pendingCompletion?.editor -// && caret.offset == autocompleteService.pendingCompletion?.offset - && nextEditService.pendingCompletion?.text != null - return enabled - } -}) \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditService.kt deleted file mode 100644 index f9279b9b9..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditService.kt +++ /dev/null @@ -1,321 +0,0 @@ -package com.github.continuedev.continueintellijextension.nextEdit - -import com.github.continuedev.continueintellijextension.FimResult -import com.github.continuedev.continueintellijextension.autocomplete.AutocompleteLookupListener -import com.github.continuedev.continueintellijextension.autocomplete.AutocompleteSpinnerWidget -import com.github.continuedev.continueintellijextension.autocomplete.ContinueInlayRenderer -import com.github.continuedev.continueintellijextension.autocomplete.PendingCompletion -import com.github.continuedev.continueintellijextension.autocomplete.addInlayElement -import com.github.continuedev.continueintellijextension.autocomplete.isInjectedText -import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings -import com.github.continuedev.continueintellijextension.services.ContinuePluginService -import com.github.continuedev.continueintellijextension.utils.checkFim -import com.github.continuedev.continueintellijextension.utils.toUriOrNull -import com.github.continuedev.continueintellijextension.utils.uuid -import com.intellij.openapi.application.ApplicationManager -import com.intellij.openapi.application.WriteAction -import com.intellij.openapi.application.invokeLater -import com.intellij.openapi.application.runReadAction -import com.intellij.openapi.components.Service -import com.intellij.openapi.components.service -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.editor.InlayProperties -import com.intellij.openapi.fileEditor.FileDocumentManager -import com.intellij.openapi.project.Project -import com.intellij.openapi.util.TextRange -import com.intellij.openapi.wm.WindowManager -import com.intellij.psi.PsiDocumentManager - -@Service(Service.Level.PROJECT) -class NextEditService(private val project: Project) { - var pendingCompletion: PendingCompletion? = null - private val autocompleteLookupListener = project.service() - private val widget: AutocompleteSpinnerWidget? by lazy { - WindowManager.getInstance().getStatusBar(project) - ?.getWidget(AutocompleteSpinnerWidget.ID) as? AutocompleteSpinnerWidget - } - - // To avoid triggering another completion on partial acceptance, - // we need to keep track of whether the last change was a partial accept. - var lastChangeWasPartialAccept = false - - fun triggerNextEdit(editor: Editor) { - val settings = service() - if (!settings.continueState.enableTabAutocomplete) { - return - } - - if (pendingCompletion != null) { - clearCompletions(pendingCompletion!!.editor) - } - - // Set pending completion. - val completionId = uuid() - val offset = editor.caretModel.primaryCaret.offset - pendingCompletion = PendingCompletion(editor, offset, completionId, null) - - // Request a completion from the core. - val virtualFile = FileDocumentManager.getInstance().getFile(editor.document) - - val uri = virtualFile?.toUriOrNull() ?: return - - widget?.setLoading(true) - - val line = editor.caretModel.primaryCaret.logicalPosition.line - val column = editor.caretModel.primaryCaret.logicalPosition.column - val input = mapOf( - "completionId" to completionId, - "filepath" to uri, - "pos" to mapOf( - "line" to line, - "character" to column - ), - "clipboardText" to "", - "recentlyEditedRanges" to emptyList(), - "recentlyVisitedRanges" to emptyList(), - ) - - // TODO: Add message support for nextEdit/predict. - project.service().coreMessenger?.request( - "nextEdit/predict", - input, - null, - ({ response -> - if (pendingCompletion == null || pendingCompletion?.completionId == completionId) { - widget?.setLoading(false) - } - - val responseObject = response as Map<*, *> - val predictions = responseObject["content"] as List<*> - - if (predictions.isNotEmpty()) { - val prediction = predictions[0].toString() - val oldEditRange = predictions[1].toString() - // Check if the prediction is purely additive. - val result = checkFim( - oldEditRange, - prediction, - Pair(line, column) - ) - when (result) { - is FimResult.FimEdit -> { - // If so, render ghost text. - val finalTextToInsert = deduplicateCompletion(editor, offset, result.fimText) - if (shouldRenderCompletion(finalTextToInsert, offset, line, editor)) { - renderCompletion(editor, offset, finalTextToInsert) - pendingCompletion = PendingCompletion(editor, offset, completionId, finalTextToInsert) - } - } - is FimResult.NotFimEdit -> { - // Else, render a window. - if (shouldRenderCompletion(prediction, offset, line, editor)) { - val nextEditWindowService = NextEditWindowService.getInstance(project) - nextEditWindowService.showCodePreview(prediction, editor, completionId) - } - } - } - } - }) - ) - } - - private fun shouldRenderCompletion(completion: String, offset: Int, line: Int, editor: Editor): Boolean { - if (completion.isEmpty() || runReadAction { offset != editor.caretModel.offset }) { - return false - } - - if (completion.lines().size == 1) { - return true - } - - val endOffset = editor.document.getLineEndOffset(line) - - // Do not render if completion is multi-line and caret is in middle of line - return offset <= endOffset && editor.document.getText(TextRange(offset, endOffset)).isBlank() - } - - private fun deduplicateCompletion(editor: Editor, offset: Int, completion: String): String { - // Check if completion matches the first 10 characters after the cursor - return ApplicationManager.getApplication().runReadAction { - val document = editor.document - val caretOffset = editor.caretModel.offset - - // Don't care about it if it's at the end of the document - if (caretOffset == document.textLength) return@runReadAction completion - - val N = 10 - var textAfterCursor = if (caretOffset + N <= document.textLength) { - document.getText(TextRange(caretOffset, caretOffset + N)) - } else { - document.getText(TextRange(caretOffset, document.textLength)) - } - - // Avoid truncating the completion text when the text after the cursor is blank - if (textAfterCursor.isBlank()) return@runReadAction completion - - // Determine the index of a newline character within the text following the cursor. - val newlineIndex = textAfterCursor.indexOf("\r\n").takeIf { it >= 0 } ?: textAfterCursor.indexOf('\n') - // If a newline character is found and the current line is not empty, truncate the text at that point. - if (newlineIndex > 0) { - textAfterCursor = textAfterCursor.substring(0, newlineIndex) - } - - val indexOfTextAfterCursorInCompletion = completion.indexOf(textAfterCursor) - if (indexOfTextAfterCursorInCompletion > 0) { - return@runReadAction completion.slice(0..indexOfTextAfterCursorInCompletion - 1) - } else if (indexOfTextAfterCursorInCompletion == 0) { - return@runReadAction "" - } - - return@runReadAction completion - } - } - - private fun renderCompletion(editor: Editor, offset: Int, completion: String) { - if (completion.isEmpty()) { - return - } - if (isInjectedFile(editor)) return - // Skip rendering completions if the code completion dropdown is already visible and the IDE completion side-by-side setting is disabled - if (shouldSkipRender()) { - return - } - - ApplicationManager.getApplication().invokeLater { - WriteAction.run { - // Clear existing completions - hideCompletions(editor) - - val properties = InlayProperties() - properties.relatesToPrecedingText(true) - properties.disableSoftWrapping(true) - - val lines = completion.lines() - pendingCompletion = pendingCompletion?.copy(text = lines.joinToString("\n")) - editor.addInlayElement(lines, offset, properties) - -// val attributes = TextAttributes().apply { -// backgroundColor = JBColor.GREEN -// } -// val key = TextAttributesKey.createTextAttributesKey("CONTINUE_AUTOCOMPLETE") -// key.let { editor.colorsScheme.setAttributes(it, attributes) } -// editor.markupModel.addLineHighlighter(key, editor.caretModel.logicalPosition.line, HighlighterLayer.LAST) - } - } - } - - fun accept() { - val completion = pendingCompletion ?: return - val text = completion.text ?: return - val editor = completion.editor - val offset = completion.offset - editor.document.insertString(offset, text) - - editor.caretModel.moveToOffset(offset + text.length) - - project.service().coreMessenger?.request( - "nextEdit/accept", - hashMapOf("completionId" to completion.completionId), - null, - ({}) - ) - invokeLater { - clearCompletions(editor, completion) - } - } - - private fun shouldSkipRender(): Boolean { - val settings = service() - return !settings.continueState.showIDECompletionSideBySide && !autocompleteLookupListener.isLookupEmpty() - } - - private fun splitKeepingDelimiters(input: String, delimiterPattern: String = "\\s+"): List { - val initialSplit = input.split("(?<=$delimiterPattern)|(?=$delimiterPattern)".toRegex()) - .filter { it.isNotEmpty() } - - val result = mutableListOf() - var currentDelimiter = "" - - for (part in initialSplit) { - if (part.matches(delimiterPattern.toRegex())) { - currentDelimiter += part - } else { - if (currentDelimiter.isNotEmpty()) { - result.add(currentDelimiter) - currentDelimiter = "" - } - result.add(part) - } - } - - if (currentDelimiter.isNotEmpty()) { - result.add(currentDelimiter) - - } - - return result - } - - fun partialAccept() { - val completion = pendingCompletion ?: return - val text = completion.text ?: return - val editor = completion.editor - val offset = completion.offset - - lastChangeWasPartialAccept = true - - // Split the text into words, keeping delimiters - val words = splitKeepingDelimiters(text) - println(words) - val word = words[0] - editor.document.insertString(offset, word) - editor.caretModel.moveToOffset(offset + word.length) - - // Remove the completion and re-display it - hideCompletions(editor) - completion.text = text.substring(word.length) - completion.offset += word.length - renderCompletion(editor, completion.offset, completion.text!!) - } - - private fun rejectCompletion(completion: PendingCompletion) { - // Send rejection message to core - widget?.setLoading(false) - project.service().coreMessenger?.request("nextEdit/reject", null, null, ({})) - } - - fun clearCompletions(editor: Editor, completion: PendingCompletion? = pendingCompletion) { - if (isInjectedFile(editor)) return - - if (completion != null) { -// cancelCompletion(completion) - if (completion.completionId == pendingCompletion?.completionId) pendingCompletion = null - } - disposeInlayRenderer(editor) - } - - private fun isInjectedFile(editor: Editor): Boolean { - return runReadAction { - PsiDocumentManager.getInstance(project).getPsiFile(editor.document)?.isInjectedText() ?: false - } - } - - fun hideCompletions(editor: Editor) { - if (isInjectedFile(editor)) return - - disposeInlayRenderer(editor) - } - - private fun disposeInlayRenderer(editor: Editor) { - editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength).forEach { - if (it.renderer is ContinueInlayRenderer) { - it.dispose() - } - } - editor.inlayModel.getBlockElementsInRange(0, editor.document.textLength).forEach { - if (it.renderer is ContinueInlayRenderer) { - it.dispose() - } - } - } -} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowService.kt deleted file mode 100644 index 846db780e..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowService.kt +++ /dev/null @@ -1,304 +0,0 @@ -package com.github.continuedev.continueintellijextension.nextEdit - -import com.github.continuedev.continueintellijextension.services.ContinuePluginService -import com.intellij.openapi.actionSystem.AnAction -import com.intellij.openapi.actionSystem.AnActionEvent -import com.intellij.openapi.actionSystem.CustomShortcutSet -import com.intellij.openapi.command.WriteCommandAction -import com.intellij.openapi.components.Service -import com.intellij.openapi.components.service -import com.intellij.openapi.editor.Document -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.editor.EditorSettings -import com.intellij.openapi.editor.colors.EditorColorsManager -import com.intellij.openapi.editor.ex.EditorEx -import com.intellij.openapi.editor.ex.EditorSettingsExternalizable -import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory -import com.intellij.openapi.fileEditor.FileDocumentManager -import com.intellij.openapi.fileTypes.FileTypeManager -import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory -import com.intellij.openapi.project.Project -import com.intellij.openapi.ui.popup.JBPopupFactory -import com.intellij.openapi.ui.popup.JBPopupListener -import com.intellij.openapi.ui.popup.LightweightWindowEvent -import com.intellij.psi.PsiDocumentManager -import com.intellij.ui.EditorTextField -import com.intellij.ui.components.JBScrollPane -import java.awt.BorderLayout -import java.awt.Color -import java.awt.Dimension -import java.awt.FlowLayout -import java.awt.Point -import java.awt.event.ActionEvent -import java.awt.event.KeyAdapter -import java.awt.event.KeyEvent -import javax.swing.AbstractAction -import javax.swing.JButton -import javax.swing.JComponent -import javax.swing.JPanel -import javax.swing.JScrollPane -import javax.swing.KeyStroke - -@Service(Service.Level.PROJECT) -class NextEditWindowService(private val project: Project) { - /** - * Creates a Swing component that displays syntax-highlighted code. - * - * @param code The code to display - * @param language The language/file extension of the code (e.g. "java", "kotlin", "py") - * @param isEditable Whether the code should be editable (default: false) - * @return A JComponent that can be added to the UI - */ - fun createCodeViewer(code: String, language: String, document: Document, isEditable: Boolean = false): JComponent { - // Get file type based on extension. - // NOTE: This is actually IDE and tier-dependent. For example, TypeScript won't work on IntelliJ CE. - val fileType = FileTypeManager.getInstance().getFileTypeByExtension(language) - - // Create an EditorTextField with the specified code and file type. - val editorTextField = object : EditorTextField(code, project, fileType) { - override fun createEditor(): EditorEx { - val editor = super.createEditor() - - // Configure editor settings. - val settings: EditorSettings = editor.settings - settings.isLineNumbersShown = true - settings.isLineMarkerAreaShown = true - settings.isIndentGuidesShown = true - settings.isVirtualSpace = false - settings.isRightMarginShown = false - settings.additionalLinesCount = 0 - settings.isShowingSpecialChars = false - settings.isCaretRowShown = true - - // Set read-only if not editable. - editor.isViewer = !isEditable - - // Syntax highlighter. - // Get current editor color scheme. - val currentScheme = EditorColorsManager.getInstance().globalScheme - - // Apply syntax highlighting with current theme. - val virtualFile = FileDocumentManager.getInstance().getFile(document) - var syntaxHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(fileType, project, virtualFile) - - // If we couldn't get a syntax highlighter from the file, try to get one just from the file type. - if (syntaxHighlighter == null) { - syntaxHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(fileType, project, null) - } - - // If we have a highlighter, apply it. - if (syntaxHighlighter != null) { - editor.highlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter( - syntaxHighlighter, - currentScheme - ) - } else { - // Fallback to plain text highlighting if all attempts fail. - val plainTextFileType = FileTypeManager.getInstance().getFileTypeByExtension("txt") - editor.highlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter( - project, - plainTextFileType - ) - } - - // Apply the theme's background color. - editor.backgroundColor = currentScheme.defaultBackground - - return editor - } - - // Override to ensure multi-line support. - override fun getPreferredSize(): Dimension { - val lineCount = code.lines().size - // Adjust height based on line count (with some minimum). - val preferredSize = super.getPreferredSize() - val lineHeight = preferredSize.height / (if (lineCount > 0) lineCount else 1) - val newHeight = lineHeight * (if (lineCount > 0) lineCount else 1) + 10 // Add padding - return Dimension(preferredSize.width, newHeight) - } - } - - // Enable multi-line mode. - editorTextField.setOneLineMode(false) - - // Wrap in a scroll pane for larger code blocks. - val panel = JPanel(BorderLayout()) - panel.add(JBScrollPane(editorTextField), BorderLayout.CENTER) - - return panel - } - - /** - * Shows a popup dialog with the code preview. - */ - fun showCodePreview(code: String, parentEditor: Editor, completionId: String) { - // Use invokeAndWait or invokeLater to ensure we're on the EDT. - com.intellij.openapi.application.ApplicationManager.getApplication().invokeLater { - val codeViewer = createCodeViewer(code, getFileLanguage(parentEditor.document), parentEditor.document) - - // Create a button panel. - val buttonPanel = JPanel(FlowLayout(FlowLayout.RIGHT)) - val acceptButton = JButton("Accept (Tab)") - val dismissButton = JButton("Dismiss (Esc)") - buttonPanel.add(acceptButton) - buttonPanel.add(dismissButton) - - // Create a panel to hold the code viewer and buttons. - val panel = JPanel(BorderLayout()) - panel.add(codeViewer, BorderLayout.CENTER) - panel.add(buttonPanel, BorderLayout.SOUTH) - - - // Create the popup. - val popup = JBPopupFactory.getInstance() - .createComponentPopupBuilder(panel, codeViewer) - .setMovable(true) - .setResizable(true) - .setRequestFocus(true) - .setCancelOnClickOutside(true) - .setCancelOnOtherWindowOpen(true) - .setFocusable(true) - .addListener(object : JBPopupListener { - override fun onClosed(event: LightweightWindowEvent) { - if (!event.isOk) { - // This only triggers when dismissed, not when accepted. - println("Dismissing code preview popup") - project.service().coreMessenger?.request( - "nextEdit/reject", - hashMapOf("completionId" to completionId), - null, ({}) - ) - } - } - }) - .createPopup() - - // Helper function to accept the code and apply it to the editor. - fun acceptCode() { - val document = parentEditor.document - val caretModel = parentEditor.caretModel - val caretOffset = caretModel.offset - val caretPosition = document.getLineNumber(caretOffset) - - // Calculate start and end lines. - val totalLines = document.lineCount - val startLine = maxOf(0, caretPosition - 5) - val endLine = minOf(totalLines - 1, caretPosition + 5) - - // Get start and end offsets. - val startOffset = document.getLineStartOffset(startLine) - val endOffset = document.getLineEndOffset(endLine) - - // Write command to replace the text. - WriteCommandAction.runWriteCommandAction(project) { - document.replaceString(startOffset, endOffset, code) - } - - project.service().coreMessenger?.request( - "nextEdit/accept", - hashMapOf("completionId" to completionId), - null, ({}) - ) - } - - // Use ActionManager to handle Tab key globally during popup display. - val acceptAction = object : AnAction() { - override fun actionPerformed(e: AnActionEvent) { - acceptCode() - popup.closeOk(null) - } - } - - // Create a custom shortcut set for the Tab key. - val customShortcutSet = CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0)) - - - // Register action with shortcut. - acceptAction.registerCustomShortcutSet(customShortcutSet, panel) - - // Add button actions. - acceptButton.addActionListener { - acceptCode() - popup.closeOk(null) - } - - dismissButton.addActionListener { - popup.cancel() - } - - // Get the exact position of the cursor. - val visualPosition = parentEditor.caretModel.visualPosition - val cursorPoint = parentEditor.visualPositionToXY(visualPosition) - - // Convert to screen coordinates. - val editorComponent = parentEditor.component - val locationOnScreen = editorComponent.locationOnScreen - val screenPoint = Point( - locationOnScreen.x + cursorPoint.x, - locationOnScreen.y + cursorPoint.y - ) - - // Show the popup at the cursor position. - popup.showInScreenCoordinates(editorComponent, screenPoint) - - // Ensure proper focus for keyboard shortcuts. - codeViewer.requestFocusInWindow() - } - } - - // Move editorConfig to a proper instance property that gets actual editor settings. - private val editorConfig: EditorConfig by lazy { - val settings = EditorSettingsExternalizable.getInstance() - val editorFontSize = EditorColorsManager.getInstance().globalScheme.editorFontSize - val editorFontFamily = EditorColorsManager.getInstance().globalScheme.editorFontName - - EditorConfig( - fontSize = editorFontSize.toDouble(), - fontFamily = editorFontFamily - ) - } - - // Data class to hold editor configuration. - private data class EditorConfig( - val fontSize: Double = 14.0, - val fontFamily: String = "JetBrains Mono" - ) - - /** - * Convenience method to map common programming languages to their file extensions. - */ - fun mapLanguageToExtension(language: String): String { - return when (language.lowercase()) { - "javascript" -> "js" - "typescript" -> "ts" - "python" -> "py" - "java" -> "java" - "kotlin" -> "kt" - "c++" -> "cpp" - "c#" -> "cs" - "go" -> "go" - "rust" -> "rs" - "ruby" -> "rb" - "php" -> "php" - "swift" -> "swift" - "shell", "bash" -> "sh" - "html" -> "html" - "css" -> "css" - "json" -> "json" - "xml" -> "xml" - "yaml", "yml" -> "yaml" - "markdown", "md" -> "md" - // Add more mappings as needed - else -> language - } - } - - private fun getFileLanguage(document: Document): String { - val virtualFile = FileDocumentManager.getInstance().getFile(document) - return virtualFile?.extension?.lowercase() ?: "text" - } - - companion object { - fun getInstance(project: Project): NextEditWindowService = project.service() - } -} \ No newline at end of file diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index 0191d8f60..bcb524f1f 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -15,8 +15,6 @@ - - - + + + + - - - - - - - - - - - - - - - - - - - diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Autocomplete.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Autocomplete.kt index a8bdab796..44171e581 100644 --- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Autocomplete.kt +++ b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/Autocomplete.kt @@ -28,13 +28,11 @@ class Autocomplete { @BeforeEach fun waitForIde(remoteRobot: RemoteRobot) { - System.setProperty("continue.autocomplete.test.environment", "true") waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") } } @AfterEach fun closeProject(remoteRobot: RemoteRobot) { - System.clearProperty("continue.autocomplete.test.environment") CommonSteps(remoteRobot).closeProject() } @@ -54,7 +52,7 @@ class Autocomplete { // Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus. waitFor(ofSeconds(20)) { findAll( - byXpath("//div[@accessiblename='Main.java' and @class='SingleHeightLabel']") + byXpath("//div[@visible_text='Main.java']") ).isNotEmpty() } 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 0a018a18f..474ec82ed 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 @@ -1,8 +1,8 @@ package com.github.continuedev.continueintellijextension.unit +import com.github.continuedev.continueintellijextension.ApplyState import com.github.continuedev.continueintellijextension.ApplyStateStatus import com.github.continuedev.continueintellijextension.IDE -import com.github.continuedev.continueintellijextension.ApplyState import com.github.continuedev.continueintellijextension.`continue`.ApplyToFileHandler import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger import com.github.continuedev.continueintellijextension.editor.DiffStreamService @@ -11,12 +11,12 @@ import com.github.continuedev.continueintellijextension.protocol.ApplyToFilePara import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project -import io.mockk.* +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify import junit.framework.TestCase -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.runBlocking -@ExperimentalCoroutinesApi class ApplyToFileHandlerTest : TestCase() { // Mock all dependencies private val mockProject = mockk(relaxed = true) @@ -54,12 +54,14 @@ class ApplyToFileHandlerTest : TestCase() { ) } - fun `test should insert text directly when document is empty`() = runTest { + fun `test should insert text directly when document is empty`() { // Given every { mockEditorUtils.isDocumentEmpty() } returns true // When - handler.handleApplyToFile() + runBlocking { + handler.handleApplyToFile() + } // Then verify { mockEditorUtils.insertTextIntoEmptyDocument(testParams.text) } diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinueInlineCompletionProviderTest.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinueInlineCompletionProviderTest.kt new file mode 100644 index 000000000..45c6249cd --- /dev/null +++ b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ContinueInlineCompletionProviderTest.kt @@ -0,0 +1,122 @@ +package com.github.continuedev.continueintellijextension.unit + +import com.github.continuedev.continueintellijextension.autocomplete.ContinueInlineCompletionProvider +import com.github.continuedev.continueintellijextension.autocomplete.CompletionService +import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings +import com.intellij.codeInsight.inline.completion.InlineCompletionHandler +import com.intellij.codeInsight.inline.completion.testInlineCompletion +import com.intellij.openapi.fileTypes.PlainTextFileType +import com.intellij.testFramework.fixtures.BasePlatformTestCase +import com.intellij.testFramework.replaceService +import org.junit.jupiter.api.Assertions.assertDoesNotThrow +import java.util.UUID + +@Suppress("UnstableApiUsage") +class ContinueInlineCompletionProviderTest : BasePlatformTestCase() { + + override fun runInDispatchThread() = + false + + override fun setUp() { + super.setUp() + InlineCompletionHandler.registerTestHandler(ContinueInlineCompletionProvider(), testRootDisposable) + } + + fun `test don't show when settings are disabled`() = myFixture.testInlineCompletion { + registerSuggestion("b") + init(PlainTextFileType.INSTANCE, "a") + ContinueExtensionSettings.instance.continueState.enableTabAutocomplete = false + callInlineCompletion() + delay() + assertNoLookup() + } + + + fun `test show completion on Ctrl + Space, then insert with Tab`() = myFixture.testInlineCompletion { + registerSuggestion("subtract(a: Int, b: Int) = a - b") + init( + PlainTextFileType.INSTANCE, + """ + class Calculator { + fun add(a: Int, b: Int) = a + b + fun + } + """.trimIndent() + ) + callInlineCompletion() + delay() + insertWithTab() + assertFileContent( + """ + class Calculator { + fun add(a: Int, b: Int) = a + b + fun subtract(a: Int, b: Int) = a - b + } + """.trimIndent() + ) + } + + fun `test inline completion that updates as the user types`() = myFixture.testInlineCompletion { + registerSuggestion("4567890'") + init(PlainTextFileType.INSTANCE, "digits = '123") + callInlineCompletion() + delay() + typeChar('4') + typeChar('5') + assertInlineRender("67890'") + typeChar('6') + insertWithTab() + assertFileContent("digits = '1234567890'") + } + + fun `test multiline`() = myFixture.testInlineCompletion { + registerSuggestion(": i32) -> i32 {\n a + b\n}") + init(PlainTextFileType.INSTANCE, "fn add(a: i32, b") + callInlineCompletion() + delay() + insertWithTab() + assertFileContent( + """ + fn add(a: i32, b: i32) -> i32 { + a + b + } + """.trimIndent() + ) + } + + fun `test accepting completion notifies the service with valid UUID`() = myFixture.testInlineCompletion { + var uuid: String? = null + registerSuggestion("test") { uuid = it } + init(PlainTextFileType.INSTANCE, "test ") + callInlineCompletion() + delay() + insertWithTab() + assertFileContent("test test") + assertDoesNotThrow { + UUID.fromString(uuid) + } + } + + fun `test not accepting completions is not notifying service with UUID`() = myFixture.testInlineCompletion { + var uuid: String? = null + registerSuggestion("test") { uuid = it } + init(PlainTextFileType.INSTANCE, "test ") + callInlineCompletion() + delay() + assertInlineRender("test") + assertNull(uuid) + } + + private fun registerSuggestion(variant: String?, accept: (String?) -> Unit = {}) = + myFixture.project.replaceService( + CompletionService::class.java, + object : CompletionService { + override suspend fun getAutocomplete(uuid: String, url: String, line: Int, column: Int): String? = + variant + + override fun acceptAutocomplete(uuid: String?) = + accept(uuid) + }, + testRootDisposable + ) +} \ No newline at end of file From 5d61ec9f3271b8da649ff56ff36902490f5c551b Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 19 Aug 2025 14:33:41 -0700 Subject: [PATCH 32/48] refactor: use sealed class for more safety --- .../nextEdit/NextEditUtils.kt | 48 ++++++++++++++----- 1 file changed, 37 insertions(+), 11 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditUtils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditUtils.kt index f908a8846..4bc8c9fe3 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditUtils.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditUtils.kt @@ -6,6 +6,36 @@ import com.github.continuedev.continueintellijextension.utils.castNestedOrNull import com.intellij.openapi.components.service import com.intellij.openapi.project.Project +sealed class NextEditModelMatcher { + abstract fun matches(modelName: String?, title: String?): Boolean + + data object MercuryCoder : NextEditModelMatcher() { + override fun matches(modelName: String?, title: String?): Boolean = + modelName?.lowercase()?.contains("mercury-coder") == true || + title?.lowercase()?.contains("mercury-coder") == true + } + + data object MercuryCoderNextEdit : NextEditModelMatcher() { + override fun matches(modelName: String?, title: String?): Boolean = + modelName?.lowercase()?.contains("mercury-coder-nextedit") == true || + title?.lowercase()?.contains("mercury-coder-nextedit") == true + } + + data object Instinct : NextEditModelMatcher() { + override fun matches(modelName: String?, title: String?): Boolean = + modelName?.lowercase()?.contains("instinct") == true || + title?.lowercase()?.contains("instinct") == true + } + + companion object { + private val allMatchers = listOf(MercuryCoder, MercuryCoderNextEdit, Instinct) + + fun isSupported(modelName: String?, title: String?): Boolean = + allMatchers.any { it.matches(modelName, title) } + } +} + + object NextEditUtils { suspend fun isNextEditSupported(project: Project): Boolean { return try { @@ -35,17 +65,11 @@ object NextEditUtils { title: String?, capabilities: Map? ): Boolean { - // Check capabilities first + // Check capabilities first - this takes precedence. val hasNextEditCapability = capabilities?.get("nextEdit") as? Boolean ?: false - // Check model name and title against known Next Edit models - val supportedModels = listOf("mercury-coder-nextedit", "instinct") - val modelLower = model.lowercase() - val titleLower = title?.lowercase() - return hasNextEditCapability || supportedModels.any { supportedModel -> - modelLower.contains(supportedModel) || - (titleLower?.contains(supportedModel) == true) - } + // Check model name and title against known Next Edit models. + return hasNextEditCapability || NextEditModelMatcher.isSupported(model, title) } /** @@ -65,7 +89,8 @@ object NextEditUtils { var prefixLength = 0 while (prefixLength < oldEditRange.length && prefixLength < newEditRange.length && - oldEditRange[prefixLength] == newEditRange[prefixLength]) { + oldEditRange[prefixLength] == newEditRange[prefixLength] + ) { prefixLength++ } @@ -75,7 +100,8 @@ object NextEditUtils { while (oldSuffixPos >= prefixLength && newSuffixPos >= prefixLength && - oldEditRange[oldSuffixPos] == newEditRange[newSuffixPos]) { + oldEditRange[oldSuffixPos] == newEditRange[newSuffixPos] + ) { oldSuffixPos-- newSuffixPos-- } From 1ba02a5705a2d01086ac1357c4352502bd837237 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 19 Aug 2025 14:43:44 -0700 Subject: [PATCH 33/48] fix: place the completion window to be four spaces after the current line content --- .../nextEdit/NextEditWindowManager.kt | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt index eb8dbea0b..8d0f2800c 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt @@ -154,9 +154,20 @@ class NextEditWindowManager(private val project: Project) { ApplicationManager.getApplication().invokeLater { try { val caretPosition = editor.caretModel.primaryCaret.logicalPosition - val caretPoint = editor.logicalPositionToXY(caretPosition) + val currentLine = caretPosition.line + val lineEndOffset = editor.document.getLineEndOffset(currentLine) + val lineText = editor.document.getText( + TextRange( + editor.document.getLineStartOffset(currentLine), + lineEndOffset + ) + ) + + val endOfLinePosition = LogicalPosition(currentLine, lineText.length + 4) + val endOfLinePoint = editor.logicalPositionToXY(endOfLinePosition) + val editorComponent = editor.contentComponent - val screenPoint = java.awt.Point(caretPoint.x + 20, caretPoint.y + editor.lineHeight) + val screenPoint = java.awt.Point(endOfLinePoint.x, endOfLinePoint.y) javax.swing.SwingUtilities.convertPointToScreen(screenPoint, editorComponent) popup.showInScreenCoordinates(editorComponent, screenPoint) From e44fb333adda159510a3e2eba1af33a57ba8cec4 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 19 Aug 2025 14:55:13 -0700 Subject: [PATCH 34/48] fix: make label easier to read --- .../continueintellijextension/nextEdit/NextEditJumpManager.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt index ee650d7a8..5a9ef2527 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt @@ -18,8 +18,8 @@ import com.intellij.openapi.util.TextRange import com.intellij.ui.JBColor import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBPanel +import com.intellij.util.ui.JBFont import com.intellij.util.ui.JBUI -import com.intellij.util.ui.UIUtil import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch @@ -314,7 +314,7 @@ class NextEditJumpManager(private val project: Project) { foreground = JBColor.foreground() background = JBColor.namedColor("InfoPopup.background", JBColor(0xE6F3FF, 0x2D3142)) isOpaque = true - font = UIUtil.getLabelFont() + font = JBFont.small() } panel.add(label, BorderLayout.CENTER) From 5f8da8fb4b33244731acc869e867ba0cf3fefa39 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 19 Aug 2025 15:38:54 -0700 Subject: [PATCH 35/48] refactor: use coroutines instead of invokeLater callbacks --- .../utils/InlineCompletionUtils.kt | 68 ++----------------- 1 file changed, 7 insertions(+), 61 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/InlineCompletionUtils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/InlineCompletionUtils.kt index cf64183fc..f25297fb3 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/InlineCompletionUtils.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/InlineCompletionUtils.kt @@ -5,8 +5,11 @@ import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.impl.SimpleDataContext import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.application.EDT import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext object InlineCompletionUtils { /** @@ -16,69 +19,12 @@ object InlineCompletionUtils { * * @param editor The editor to trigger completion for * @param project The project context (optional, will be inferred from editor if null) - * @param callback Optional callback to receive the result (called on EDT) */ - fun triggerInlineCompletion( + suspend fun triggerInlineCompletion( editor: Editor, - project: Project? = null, - callback: ((Boolean) -> Unit)? = null - ) { - val application = ApplicationManager.getApplication() - - if (application.isDispatchThread) { - // Already on EDT, execute directly - val result = performTrigger(editor, project) - callback?.invoke(result) - } else { - // Not on EDT, invoke later - application.invokeLater { - val result = performTrigger(editor, project) - callback?.invoke(result) - } - } - } - - /** - * Synchronous version that blocks until completion is triggered (use carefully). - * Only use this if you're already on the EDT or in a context where blocking is acceptable. - * - * @param editor The editor to trigger completion for - * @param project The project context (optional, will be inferred from editor if null) - * @return true if the action was found and executed, false otherwise - */ - fun triggerInlineCompletionSync(editor: Editor, project: Project? = null): Boolean { - val application = ApplicationManager.getApplication() - - return if (application.isDispatchThread) { - performTrigger(editor, project) - } else { - var result = false - application.invokeAndWait { - result = performTrigger(editor, project) - } - result - } - } - - /** - * Triggers inline completion with a delay. - * Useful for scenarios where you want to trigger completion after some processing. - * - * @param editor The editor to trigger completion for - * @param delayMs Delay in milliseconds before triggering - * @param project The project context (optional, will be inferred from editor if null) - * @param callback Optional callback to receive the result (called on EDT after trigger) - */ - fun triggerInlineCompletionDelayed( - editor: Editor, - delayMs: Long = 2000, - project: Project? = null, - callback: ((Boolean) -> Unit)? = null - ) { - ApplicationManager.getApplication().executeOnPooledThread { - Thread.sleep(delayMs) - triggerInlineCompletion(editor, project, callback) - } + project: Project? = null + ): Boolean = withContext(Dispatchers.EDT) { + performTrigger(editor, project) } /** From f769ec9b2c183bd6d4bd848b470e609603fbfbf4 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 19 Aug 2025 15:39:17 -0700 Subject: [PATCH 36/48] refactor: launch coroutines instead of invokeLater --- .../nextEdit/NextEditJumpManager.kt | 8 ++++++-- .../nextEdit/NextEditWindowManager.kt | 18 ++++++++++++++---- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt index 5a9ef2527..9ebb5625d 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt @@ -3,6 +3,7 @@ package com.github.continuedev.continueintellijextension.nextEdit import com.github.continuedev.continueintellijextension.listeners.ActiveHandlerManager import com.github.continuedev.continueintellijextension.utils.InlineCompletionUtils import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.application.EDT import com.intellij.openapi.components.Service import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.LogicalPosition @@ -22,6 +23,7 @@ import com.intellij.util.ui.JBFont import com.intellij.util.ui.JBUI import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch import java.awt.* import java.awt.event.ActionEvent @@ -42,7 +44,7 @@ data class CompletionDataForAfterJump( @Service(Service.Level.PROJECT) class NextEditJumpManager(private val project: Project) { - private val coroutineScope = CoroutineScope(Dispatchers.Main) + private val coroutineScope = CoroutineScope(Dispatchers.Default + SupervisorJob()) // State management private var jumpState = JumpState() @@ -409,7 +411,9 @@ class NextEditJumpManager(private val project: Project) { // Clear decorations (this will cancel popup, but won't trigger reject due to state check) clearJumpDecoration() - InlineCompletionUtils.triggerInlineCompletion(editor, project) { success -> "success: $success" } + coroutineScope.launch(Dispatchers.EDT) { + InlineCompletionUtils.triggerInlineCompletion(editor, project) + } // Reset accepted state after a brief moment coroutineScope.launch { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt index 8d0f2800c..bab1f6cee 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt @@ -4,6 +4,7 @@ import com.github.continuedev.continueintellijextension.Position import com.github.continuedev.continueintellijextension.listeners.ActiveHandlerManager import com.github.continuedev.continueintellijextension.utils.InlineCompletionUtils import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.application.EDT import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.components.Service import com.intellij.openapi.editor.Editor @@ -20,6 +21,10 @@ import com.intellij.openapi.util.TextRange import com.intellij.ui.JBColor import com.intellij.ui.components.JBPanel import com.intellij.util.ui.JBUI +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch import java.awt.* import java.awt.event.ActionEvent import java.awt.event.KeyEvent @@ -29,6 +34,8 @@ import javax.swing.border.AbstractBorder @Service(Service.Level.PROJECT) class NextEditWindowManager(private val project: Project) { + private val coroutineScope = CoroutineScope(Dispatchers.Default + SupervisorJob()) + private var currentPopup: JBPopup? = null private var deletionHighlighters: List = emptyList() private var isAccepted = false @@ -914,10 +921,13 @@ class NextEditWindowManager(private val project: Project) { } println("DEBUG: WriteCommandAction completed successfully") - InlineCompletionUtils.triggerInlineCompletion( - editor, - project - ) { success -> println("invocation: $success") } + + coroutineScope.launch(Dispatchers.EDT) { + InlineCompletionUtils.triggerInlineCompletion( + editor, + project + ) + } } catch (e: Exception) { println("ERROR: Exception in acceptEdit: ${e.message}") e.printStackTrace() From bef0812f0d00b90b1804aa5081be79e062ab4e11 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 20 Aug 2025 15:23:12 -0700 Subject: [PATCH 37/48] chore: cleanup --- .../ContinueInlineCompletionProvider.kt | 2 +- .../nextEdit/NextEditJumpManager.kt | 102 ++------------- .../nextEdit/NextEditService.kt | 9 -- .../nextEdit/NextEditWindowManager.kt | 117 ------------------ 4 files changed, 12 insertions(+), 218 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt index 23e594944..7b2f69665 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt @@ -11,8 +11,8 @@ import com.github.continuedev.continueintellijextension.utils.uuid import com.intellij.codeInsight.inline.completion.* import com.intellij.codeInsight.inline.completion.elements.InlineCompletionElement import com.intellij.codeInsight.inline.completion.elements.InlineCompletionGrayTextElement -import com.intellij.codeInsight.inline.completion.suggestion.InlineCompletionSuggestion import com.intellij.codeInsight.inline.completion.suggestion.InlineCompletionSingleSuggestion +import com.intellij.codeInsight.inline.completion.suggestion.InlineCompletionSuggestion import com.intellij.codeInsight.inline.completion.suggestion.InlineCompletionVariant import com.intellij.openapi.components.service import com.intellij.openapi.project.Project diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt index 9ebb5625d..abe7d7345 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt @@ -121,12 +121,9 @@ class NextEditJumpManager(private val project: Project) { if (completionContent != null && isContentIdentical(editor, nextJumpLocation, completionContent) ) { - println("Skipping jump as content is identical at jump location") return false } - println("Suggesting jump from line ${currentPosition.line} to line ${nextJumpLocation.line}") - // Update state jumpState = jumpState.copy( inProgress = true, @@ -151,9 +148,7 @@ class NextEditJumpManager(private val project: Project) { editor.scrollingModel.scrollTo(nextJumpLocation, ScrollType.CENTER) result = true - println("DEBUG: suggestJump completed successfully") } catch (e: Exception) { - println("DEBUG: Error in suggestJump UI operations: $e") // Reset state on error jumpState = jumpState.copy(inProgress = false) result = false @@ -266,7 +261,6 @@ class NextEditJumpManager(private val project: Project) { // Force focus after popup is shown ApplicationManager.getApplication().invokeLater { popupComponent.requestFocusInWindow() - println("DEBUG: Jump popup shown and focus requested") } } catch (e: Exception) { jumpPopup?.showInBestPositionFor(editor) @@ -331,8 +325,6 @@ class NextEditJumpManager(private val project: Project) { } private fun addKeyboardShortcuts(panel: JComponent, editor: Editor) { - println("DEBUG: Adding keyboard shortcuts to jump panel") - // CRITICAL: Disable focus traversal for Tab key panel.setFocusTraversalKeysEnabled(false) @@ -343,7 +335,6 @@ class NextEditJumpManager(private val project: Project) { inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), "acceptJump") actionMap.put("acceptJump", object : AbstractAction() { override fun actionPerformed(e: ActionEvent?) { - println("DEBUG: Accept jump action triggered!") acceptJump(editor) } }) @@ -352,55 +343,31 @@ class NextEditJumpManager(private val project: Project) { inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "rejectJump") actionMap.put("rejectJump", object : AbstractAction() { override fun actionPerformed(e: ActionEvent?) { - println("DEBUG: Reject jump action triggered!") rejectJump() } }) panel.isFocusable = true - // Debug listeners - panel.addFocusListener(object : java.awt.event.FocusListener { - override fun focusGained(e: java.awt.event.FocusEvent?) { - println("DEBUG: Jump panel gained focus") - } - - override fun focusLost(e: java.awt.event.FocusEvent?) { - println("DEBUG: Jump panel lost focus") - } - }) - - panel.addKeyListener(object : java.awt.event.KeyListener { - override fun keyPressed(e: KeyEvent?) { - println("DEBUG: Jump panel key pressed: ${e?.keyCode} (Tab = ${KeyEvent.VK_TAB}, Esc = ${KeyEvent.VK_ESCAPE})") - } - - override fun keyReleased(e: KeyEvent?) {} - override fun keyTyped(e: KeyEvent?) {} - }) - - panel.addHierarchyListener { e -> - if (e.changeFlags and java.awt.event.HierarchyEvent.SHOWING_CHANGED.toLong() != 0L) { - if (panel.isShowing) { - println("DEBUG: Jump panel is showing, requesting focus") - ApplicationManager.getApplication().invokeLater { - val focusResult = panel.requestFocusInWindow() - println("DEBUG: Jump panel focus request result: $focusResult") - } - } - } - } +// panel.addHierarchyListener { e -> +// if (e.changeFlags and java.awt.event.HierarchyEvent.SHOWING_CHANGED.toLong() != 0L) { +// if (panel.isShowing) { +// println("DEBUG: Jump panel is showing, requesting focus") +// ApplicationManager.getApplication().invokeLater { +// val focusResult = panel.requestFocusInWindow() +// println("DEBUG: Jump panel focus request result: $focusResult") +// } +// } +// } +// } } private fun acceptJump(editor: Editor) { val state = jumpState if (!state.inProgress || state.jumpPosition == null || state.editor == null) { - println("DEBUG: Cannot accept jump - invalid state: ${!state.inProgress} ${state.jumpPosition == null} ${state.editor == null}") return } - println("Accepting jump to position: ${state.jumpPosition}") - // Update state BEFORE clearing decorations to prevent cancel callback from triggering reject jumpState = jumpState.copy(justAccepted = true) @@ -431,12 +398,9 @@ class NextEditJumpManager(private val project: Project) { private fun rejectJump() { if (!jumpState.inProgress) { - println("DEBUG: Cannot reject jump - not in progress") return } - println("Rejecting jump - deleting chain") - // Delete the chain deleteChainCallback?.invoke() @@ -506,50 +470,6 @@ class NextEditJumpManager(private val project: Project) { } } -// private fun registerSelectionChangeHandler() { -// val selectionManager = project.getService(SelectionChangeManager::class.java) -// -// selectionManager.registerListener( -// "nextEditJumpManager", -// { event, state -> handleSelectionChange(event, state) }, -// HandlerPriority.HIGH -// ) -// } -// -// private suspend fun handleSelectionChange( -// event: SelectionEvent, -// state: StateSnapshot -// ): Boolean { -// // Preserve chain during jump operations -// when { -// state.jumpInProgress -> { -// println("Jump in progress, preserving chain") -// -// // Check if cursor moved away from expected position -// val currentPos = event.editor.caretModel.logicalPosition -// val oldPos = jumpState.oldCursorPosition -// val jumpPos = jumpState.jumpPosition -// -// // If cursor moved but not to jump position, reject the jump -// if (oldPos != null && jumpPos != null && -// !currentPos.equals(oldPos) && !currentPos.equals(jumpPos) -// ) { -// println("DEBUG: Cursor moved unexpectedly, rejecting jump") -// rejectJump() -// } -// -// return true -// } -// -// state.jumpJustAccepted -> { -// println("Jump just accepted, preserving chain") -// return true -// } -// -// else -> return false -// } -// } - fun cleanup() { clearJumpState() triggerInlineSuggestCallback = null diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditService.kt index 516ac3bd7..ef7ecb8a8 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditService.kt @@ -56,8 +56,6 @@ class ContinueNextEditService(private val project: Project) : NextEditService { currCursorPos: Pair, lastUuid: String? ): NextEditOutcome? { - println("Case 1: Typing (chain does not exist)") - // Start a new chain startChain() @@ -75,8 +73,6 @@ class ContinueNextEditService(private val project: Project) : NextEditService { // Case 2: Jumping (chain exists, jump was taken). override suspend fun handleCase2(): NextEditOutcome? { - println("Case 2: Jumping (chain exists, jump was taken)") - val jumpManager = project.service() // Reset jump state @@ -90,15 +86,12 @@ class ContinueNextEditService(private val project: Project) : NextEditService { return outcome } else { // This technically should not happen according to the TypeScript comment - println("Error: No saved completion found after jump was taken") return null } } // Case 3: Accepting next edit outcome (chain exists, jump is not taken). override suspend fun handleCase3(editor: Editor, currentCursorPos: Pair): NextEditOutcome? { - println("Case 3: Accepting next edit outcome (chain exists, jump is not taken)") - val jumpManager = project.service() // Try suggesting jump for each location in the chain @@ -107,7 +100,6 @@ class ContinueNextEditService(private val project: Project) : NextEditService { while (chainExists() && !isJumpSuggested) { val nextItemInChain = getNextInChain() if (nextItemInChain == null) { - println("No more items in chain") break } @@ -141,7 +133,6 @@ class ContinueNextEditService(private val project: Project) : NextEditService { } if (!isJumpSuggested) { - println("No suitable jump location found after trying all positions") deleteChain() return null } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt index bab1f6cee..0086cb47c 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowManager.kt @@ -53,15 +53,6 @@ class NextEditWindowManager(private val project: Project) { newCode: String, diffLines: List ) { - println("DEBUG: showNextEditWindow called with:") - println(" currCursorPos: $currCursorPos") - println(" editableRegionStartLine: $editableRegionStartLine") - println(" editableRegionEndLine: $editableRegionEndLine") - println(" oldCode length: ${oldCode.length}") - println(" newCode length: ${newCode.length}") - println(" document total lines: ${editor.document.lineCount}") - println(" document writable: ${editor.document.isWritable}") - // Clear existing decorations first hideAllNextEditWindows() @@ -81,8 +72,6 @@ class NextEditWindowManager(private val project: Project) { diffLines ) - println("DEBUG: isLineDelete: $isLineDelete") - // Show the code popup with the new suggestion showCodePopup(editor, newCode, diffLines) { action -> when (action) { @@ -210,7 +199,6 @@ class NextEditWindowManager(private val project: Project) { // Force focus after popup is shown ApplicationManager.getApplication().invokeLater { popupComponent.requestFocusInWindow() - println("DEBUG: Popup shown and focus requested") } } catch (e: Exception) { popup.showInBestPositionFor(editor) @@ -258,9 +246,6 @@ class NextEditWindowManager(private val project: Project) { // Check for DPI scaling val scale = JBUI.scale(1f) - println("DEBUG: UI scale factor: $scale") - println("DEBUG: FontMetrics - height: $height, ascent: $ascent") - println("DEBUG: Font size from font object: ${font.size}") // Adjust for DPI scaling val adjustedFontSize = if (scale > 1f) { @@ -269,8 +254,6 @@ class NextEditWindowManager(private val project: Project) { font.size } - println("DEBUG: Adjusted font size: $adjustedFontSize") - return adjustedFontSize } @@ -282,8 +265,6 @@ class NextEditWindowManager(private val project: Project) { } private fun createCodeDisplayPanel(editor: Editor, code: String, diffLines: List): JComponent { - println("DEBUG: createCodeDisplayPanel - START") - try { val scheme = EditorColorsManager.getInstance().globalScheme val editorFont = editor.colorsScheme.getFont(com.intellij.openapi.editor.colors.EditorFontType.PLAIN) @@ -299,10 +280,6 @@ class NextEditWindowManager(private val project: Project) { val adjustedLineHeight = actualFontSize - println("DEBUG: Using font size: $actualFontSize") - println("DEBUG: Editor line height: $editorLineHeight, adjusted: $adjustedLineHeight") - println("DEBUG: UI scale: $uiScale") - // Get file type for proper syntax highlighting val fileType = getCurrentFileType(editor) @@ -397,8 +374,6 @@ class NextEditWindowManager(private val project: Project) { val backgroundHex = String.format("#%02x%02x%02x", backgroundColor.red, backgroundColor.green, backgroundColor.blue) - println("DEBUG: HTML font - Family: $fontFamily, Size: ${fontSize}px, LineHeight: ${lineHeight}px") - if (text.trim().isEmpty()) { return "" + "
 
" + @@ -600,8 +575,6 @@ class NextEditWindowManager(private val project: Project) { } private fun addKeyboardShortcuts(panel: JComponent, onAction: (PopupAction) -> Unit) { - println("DEBUG: Adding keyboard shortcuts to panel") - // CRITICAL FIX: Disable focus traversal for Tab key panel.setFocusTraversalKeysEnabled(false) @@ -612,7 +585,6 @@ class NextEditWindowManager(private val project: Project) { inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), "accept") actionMap.put("accept", object : AbstractAction() { override fun actionPerformed(e: ActionEvent?) { - println("DEBUG: Accept action triggered!") onAction(PopupAction.ACCEPT) } }) @@ -621,44 +593,11 @@ class NextEditWindowManager(private val project: Project) { inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "reject") actionMap.put("reject", object : AbstractAction() { override fun actionPerformed(e: ActionEvent?) { - println("DEBUG: Reject action triggered!") onAction(PopupAction.REJECT) } }) panel.isFocusable = true - - // Keep your existing debug listeners - panel.addFocusListener(object : java.awt.event.FocusListener { - override fun focusGained(e: java.awt.event.FocusEvent?) { - println("DEBUG: Panel gained focus") - } - - override fun focusLost(e: java.awt.event.FocusEvent?) { - println("DEBUG: Panel lost focus") - } - }) - - panel.addKeyListener(object : java.awt.event.KeyListener { - override fun keyPressed(e: KeyEvent?) { - println("DEBUG: Key pressed: ${e?.keyCode} (Tab = ${KeyEvent.VK_TAB})") - } - - override fun keyReleased(e: KeyEvent?) {} - override fun keyTyped(e: KeyEvent?) {} - }) - - panel.addHierarchyListener { e -> - if (e.changeFlags and java.awt.event.HierarchyEvent.SHOWING_CHANGED.toLong() != 0L) { - if (panel.isShowing) { - println("DEBUG: Panel is showing, requesting focus") - ApplicationManager.getApplication().invokeLater { - val focusResult = panel.requestFocusInWindow() - println("DEBUG: Focus request result: $focusResult") - } - } - } - } } private fun renderDeletionDecorations( @@ -834,12 +773,6 @@ class NextEditWindowManager(private val project: Project) { endLine: Int, isLineDelete: Boolean = false ) { - println("DEBUG: acceptEdit called with:") - println(" newText: '$newText'") - println(" startLine: $startLine") - println(" endLine: $endLine") - println(" isLineDelete: $isLineDelete") - isAccepted = true // Clear handler before making document changes that move cursor @@ -850,20 +783,16 @@ class NextEditWindowManager(private val project: Project) { try { // Fix: Use the simpler WriteCommandAction.runWriteCommandAction WriteCommandAction.runWriteCommandAction(project) { - println("DEBUG: Inside WriteCommandAction") val document = editor.document // Validate line indices val totalLines = document.lineCount - println("DEBUG: Total lines in document: $totalLines") if (startLine < 0 || startLine >= totalLines) { - println("ERROR: Invalid startLine $startLine (total lines: $totalLines)") return@runWriteCommandAction } if (endLine < 0 || endLine >= totalLines) { - println("ERROR: Invalid endLine $endLine (total lines: $totalLines)") return@runWriteCommandAction } @@ -875,53 +804,33 @@ class NextEditWindowManager(private val project: Project) { // If this isn't the last line, extend to include the newline character if (startLine < document.lineCount - 1) { endOffset = document.getLineStartOffset(startLine + 1) - println("DEBUG: Line delete - including newline, endOffset: $endOffset") } else { // If it's the last line, just delete to end of line endOffset = document.getLineEndOffset(startLine) - println("DEBUG: Line delete - last line, endOffset: $endOffset") } - println("DEBUG: Line deletion offsets:") - println(" startOffset: $startOffset") - println(" endOffset: $endOffset") - val oldText = document.getText(TextRange(startOffset, endOffset)) - println("DEBUG: Deleting text: '$oldText'") // Delete the entire line including newline document.deleteString(startOffset, endOffset) - println("DEBUG: Line deletion completed") } else { // Handle normal text replacement val startOffset = document.getLineStartOffset(startLine) val endOffset = document.getLineEndOffset(endLine) - println("DEBUG: Normal edit offsets:") - println(" startOffset: $startOffset") - println(" endOffset: $endOffset") - println(" document length: ${document.textLength}") - if (startOffset < 0 || endOffset > document.textLength || startOffset > endOffset) { - println("ERROR: Invalid offsets - startOffset: $startOffset, endOffset: $endOffset, docLength: ${document.textLength}") return@runWriteCommandAction } // Show what we're replacing val oldText = document.getText(TextRange(startOffset, endOffset)) - println("DEBUG: Replacing text:") - println(" Old: '$oldText'") - println(" New: '$newText'") // Perform the replacement document.replaceString(startOffset, endOffset, newText) - println("DEBUG: Document replacement completed") } } - println("DEBUG: WriteCommandAction completed successfully") - coroutineScope.launch(Dispatchers.EDT) { InlineCompletionUtils.triggerInlineCompletion( editor, @@ -935,7 +844,6 @@ class NextEditWindowManager(private val project: Project) { // Log acceptance (placeholder) currentCompletionId?.let { - println("DEBUG: Would log acceptance for completion ID: $it") // project.getService(NextEditService::class.java).acceptEdit(it) } @@ -1007,31 +915,6 @@ class NextEditWindowManager(private val project: Project) { hideAllNextEditWindows() currentCompletionId = null } - -// fun registerSelectionChangeHandler() { -// val selectionManager = project.getService(SelectionChangeManager::class.java) -// -// selectionManager.registerListener( -// "nextEditWindowManager", -// { event, state -> -// handleSelectionChange(event, state) -// }, -// HandlerPriority.HIGH -// ) -// } -// -// private suspend fun handleSelectionChange( -// event: SelectionEvent, -// state: StateSnapshot -// ): Boolean { -// // If window was just accepted, preserve the chain -// if (state.nextEditWindowAccepted) { -// println("Next edit window accepted, preserving chain") -// return true -// } -// -// return false -// } } enum class PopupAction { From bbd3f1c51d2125fe5b41573b981b108b31818169 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 20 Aug 2025 15:58:47 -0700 Subject: [PATCH 38/48] chore: cleanup --- .../listeners/ActiveHandlerManager.kt | 9 - .../listeners/SelectionChangeManager.kt | 283 ++++++++++++++++++ .../listeners/TypingSessionHandler.kt | 2 - .../nextEdit/NextEditJumpHandler.kt | 3 - .../nextEdit/NextEditJumpManager.kt | 12 - .../nextEdit/NextEditWindowHandler.kt | 3 - 6 files changed, 283 insertions(+), 29 deletions(-) create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/SelectionChangeManager.kt diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ActiveHandlerManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ActiveHandlerManager.kt index 24b5c5fe1..92dc3c2a3 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ActiveHandlerManager.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ActiveHandlerManager.kt @@ -72,8 +72,6 @@ class ActiveHandlerManager(private val project: Project) : SelectionListener, Ca activeHandler = handler handler.onActivated() - - println("ActiveHandlerManager: Set active handler '${handler.handlerId}'") } /** @@ -82,7 +80,6 @@ class ActiveHandlerManager(private val project: Project) : SelectionListener, Ca */ fun clearActiveHandler() { activeHandler?.let { handler -> - println("ActiveHandlerManager: Clearing active handler '${handler.handlerId}'") handler.onDeactivated() handler.dispose() } @@ -142,10 +139,7 @@ class ActiveHandlerManager(private val project: Project) : SelectionListener, Ca try { val wasHandled = handler.onCursorMoved(editor, oldPosition, currentPosition) if (!wasHandled) { - println("ActiveHandlerManager: Active handler '${handler.handlerId}' did not handle cursor movement, treating as deliberate") handleDeliberateCursorMovement() - } else { - println("ActiveHandlerManager: Active handler '${handler.handlerId}' handled cursor movement") } } catch (e: Exception) { println("ActiveHandlerManager: Error in handler '${handler.handlerId}': ${e.message}") @@ -154,7 +148,6 @@ class ActiveHandlerManager(private val project: Project) : SelectionListener, Ca } } else { // No active handler - this is a deliberate cursor movement - println("ActiveHandlerManager: No active handler, treating cursor movement as deliberate") handleDeliberateCursorMovement() } } finally { @@ -170,8 +163,6 @@ class ActiveHandlerManager(private val project: Project) : SelectionListener, Ca // Delete the next edit chain val nextEditService = project.getService(NextEditService::class.java) nextEditService.deleteChain() - - println("ActiveHandlerManager: Deleted next edit chain due to deliberate cursor movement") } catch (e: Exception) { println("ActiveHandlerManager: Error handling deliberate cursor movement: ${e.message}") } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/SelectionChangeManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/SelectionChangeManager.kt new file mode 100644 index 000000000..bae53affc --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/SelectionChangeManager.kt @@ -0,0 +1,283 @@ +package com.github.continuedev.continueintellijextension.listeners + +import com.github.continuedev.continueintellijextension.nextEdit.NextEditService +import com.github.continuedev.continueintellijextension.nextEdit.NextEditJumpManager +import com.github.continuedev.continueintellijextension.nextEdit.NextEditWindowManager +import com.intellij.openapi.components.Service +import com.intellij.openapi.components.service +import com.intellij.openapi.editor.Document +import com.intellij.openapi.editor.Editor +import com.intellij.openapi.editor.LogicalPosition +import com.intellij.openapi.editor.event.SelectionEvent +import com.intellij.openapi.editor.event.SelectionListener +import com.intellij.openapi.project.DumbAware +import com.intellij.openapi.project.Project +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import java.util.concurrent.ConcurrentLinkedQueue + +enum class HandlerPriority(val value: Int) { + CRITICAL(5), + HIGH(4), + NORMAL(3), + LOW(2), + FALLBACK(1) +} + +data class StateSnapshot( + val nextEditWindowAccepted: Boolean, + val jumpInProgress: Boolean, + val jumpJustAccepted: Boolean, + val lastDocumentChangeTime: Long, + val isTypingSession: Boolean, + val document: Document?, + val cursorPosition: LogicalPosition? +) + +typealias SelectionChangeHandler = suspend (SelectionEvent, StateSnapshot) -> Boolean + +data class HandlerRegistration( + val id: String, + val priority: Int, + val handler: SelectionChangeHandler +) + +@Service(Service.Level.PROJECT) +class SelectionChangeManager(private val project: Project) : SelectionListener, DumbAware { + private val coroutineScope = CoroutineScope(Dispatchers.Main) + private val listeners = mutableListOf() + + // Event processing + private val eventQueue = ConcurrentLinkedQueue() + private var lastEventTime = 0L + private var isProcessingEvent = false + private val processingMutex = Mutex() + private var processingJob: Job? = null + + // Debounce settings + private val DEBOUNCE_DELAY = 50L + private val PROCESSING_TIMEOUT = 500L + + // Track typing session state + private var isTypingSession = false + private var typingTimer: Job? = null + private var lastDocumentChangeTime = 0L + private val TYPING_SESSION_TIMEOUT = 2000L + + init { + // Register the default fallback handler + registerListener( + "defaultFallbackHandler", + ::defaultFallbackHandler, + HandlerPriority.FALLBACK + ) + } + + fun documentChanged() { + isTypingSession = true + lastDocumentChangeTime = System.currentTimeMillis() + resetTypingSession() + } + + private fun resetTypingSession() { + typingTimer?.cancel() + typingTimer = coroutineScope.launch { + delay(TYPING_SESSION_TIMEOUT) + isTypingSession = false + } + } + + /** + * Register a listener for the selection change event. + * @param id Unique id for this handler. + * @param handler Function to handle the event. + * @param priority Higher priority runs first. + * @return Function to unregister this listener. + */ + fun registerListener( + id: String, + handler: SelectionChangeHandler, + priority: HandlerPriority = HandlerPriority.NORMAL + ): () -> Unit { + // Remove any existing handler with the same id + listeners.removeAll { it.id == id } + + // Add the new handler + listeners.add(HandlerRegistration(id, priority.value, handler)) + + // Sort by descending priority + listeners.sortByDescending { it.priority } + + // Return the unregister function + return { + listeners.removeAll { it.id == id } + } + } + + override fun selectionChanged(event: SelectionEvent) { + if (event.editor.isDisposed || event.editor.project?.isDisposed == true) { + return + } + + coroutineScope.launch { + handleSelectionChange(event) + } + } + + /** + * Handle a given selection change event. + * @param e The selection change event. + */ + private suspend fun handleSelectionChange(e: SelectionEvent) { + val now = System.currentTimeMillis() + + // Simple debouncing logic + // Ignore events that come too quickly after the previous one + if (now - lastEventTime < DEBOUNCE_DELAY) { + // Replace the queued event with the most recent one + if (eventQueue.isNotEmpty()) { + eventQueue.clear() + } + eventQueue.offer(e) + return + } + + lastEventTime = now + + // Queue this event for later if the manager is already processing an event + if (isProcessingEvent) { + eventQueue.offer(e) + return + } + + try { + // Process this event first + processEventWithTimeout(e) + + // Process remaining queued events sequentially + while (eventQueue.isNotEmpty()) { + val nextEvent = eventQueue.poll() + if (nextEvent != null) { + processEventWithTimeout(nextEvent) + } + } + } catch (err: Exception) { + println("Error processing selection change event: ${err.message}") + err.printStackTrace() + } + } + + /** + * Process a given event with a timeout. + * This is in attempt to prevent deadlocks between events. + * @param e The selection change event. + */ + private suspend fun processEventWithTimeout(e: SelectionEvent) { + processingMutex.withLock { + isProcessingEvent = true + + try { + // Cancel any existing processing job + processingJob?.cancel() + + // Set up a timeout to prevent deadlocks + processingJob = coroutineScope.launch { + try { + processEvent(e) + } catch (ex: Exception) { + println("Error in processEvent: ${ex.message}") + ex.printStackTrace() + } + } + + // Wait for completion with timeout + val timeoutJob = coroutineScope.launch { + delay(PROCESSING_TIMEOUT) + processingJob?.cancel() + throw Exception("Selection change event processing timed out") + } + + try { + processingJob?.join() + timeoutJob.cancel() + } catch (ex: Exception) { + println("Processing timeout or error: ${ex.message}") + } + + } finally { + isProcessingEvent = false + processingJob = null + } + } + } + + /** + * Core event processing logic. + * @param e The selection change event. + */ + private suspend fun processEvent(e: SelectionEvent) { + val snapshot = captureState(e) + + for (registration in listeners) { + try { + if (registration.handler(e, snapshot)) { + return + } + } catch (err: Exception) { + println("Error in selection change handler '${registration.id}': ${err.message}") + err.printStackTrace() + // Don't break - continue to next handler + } + } + } + + private fun captureState(e: SelectionEvent): StateSnapshot { + val nextEditWindowManager = runCatching { + project.getService(NextEditWindowManager::class.java) + }.getOrNull() + + val jumpManager = runCatching { + project.getService(NextEditJumpManager::class.java) + }.getOrNull() + + val cursorPosition = try { + e.editor.caretModel.primaryCaret.logicalPosition + } catch (ex: Exception) { + null + } + + return StateSnapshot( + nextEditWindowAccepted = nextEditWindowManager?.hasAccepted() ?: false, + jumpInProgress = jumpManager?.isJumpInProgress() ?: false, + jumpJustAccepted = jumpManager?.wasJumpJustAccepted() ?: false, + lastDocumentChangeTime = lastDocumentChangeTime, + isTypingSession = isTypingSession, + document = e.editor.document, + cursorPosition = cursorPosition + ) + } + + private suspend fun defaultFallbackHandler( + e: SelectionEvent, + state: StateSnapshot + ): Boolean { + println("defaultFallbackHandler: deleteChain called from selectionChanged") + + try { + val nextEditService = project.getService(NextEditService::class.java) + nextEditService.deleteChain() + } catch (ex: Exception) { + println("Error deleting chain in defaultFallbackHandler: ${ex.message}") + } + + // TODO: Add prefetch logic similar to VS Code if needed + // This would involve getting next editable regions and enqueuing them + + return true + } +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/TypingSessionHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/TypingSessionHandler.kt index 35fbaba65..c0291b168 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/TypingSessionHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/TypingSessionHandler.kt @@ -39,12 +39,10 @@ class TypingSessionHandler( } ?: false if (isTypingMovement) { - println("TypingSessionHandler: Cursor movement during typing session") return true } } - println("TypingSessionHandler: Not a typing movement (time since edit: ${timeSinceLastEdit}ms)") return false } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpHandler.kt index 54184ee75..65e026d2d 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpHandler.kt @@ -32,19 +32,16 @@ class NextEditJumpHandler( return when { // Cursor moved to the expected jump position - this is expected jumpPosition != null && newPosition == jumpPosition -> { - println("NextEditJumpHandler: Cursor moved to expected jump position") true } // Cursor is still at the original position - no movement yet originalPosition != null && newPosition == originalPosition -> { - println("NextEditJumpHandler: Cursor still at original position") true } // Cursor moved somewhere else - user moved manually, abort jump else -> { - println("NextEditJumpHandler: Cursor moved to unexpected position, aborting jump") jumpManager.abortJump() false } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt index abe7d7345..26401d5ee 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditJumpManager.kt @@ -348,18 +348,6 @@ class NextEditJumpManager(private val project: Project) { }) panel.isFocusable = true - -// panel.addHierarchyListener { e -> -// if (e.changeFlags and java.awt.event.HierarchyEvent.SHOWING_CHANGED.toLong() != 0L) { -// if (panel.isShowing) { -// println("DEBUG: Jump panel is showing, requesting focus") -// ApplicationManager.getApplication().invokeLater { -// val focusResult = panel.requestFocusInWindow() -// println("DEBUG: Jump panel focus request result: $focusResult") -// } -// } -// } -// } } private fun acceptJump(editor: Editor) { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowHandler.kt index 89bc61a7d..27ab3f022 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditWindowHandler.kt @@ -23,18 +23,15 @@ class NextEditWindowHandler( ): Boolean { // Check if window was just accepted if (windowManager.hasAccepted()) { - println("NextEditWindowHandler: Window was accepted, cursor movement is expected") return true } // Check if cursor is still near the expected position (within the same line) if (newPosition.line == expectedPosition.line) { - println("NextEditWindowHandler: Cursor movement within same line as suggestion") return true } // User moved away from the suggestion area - close window and treat as deliberate - println("NextEditWindowHandler: Cursor moved away from suggestion area") windowManager.hideAllNextEditWindows() return false } From fae8c8d2f4e8dafd2e6ce59bff7fedbe176f9966 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 21 Aug 2025 12:11:50 -0700 Subject: [PATCH 39/48] chore: bump --- core/package-lock.json | 8 ++++---- packages/openai-adapters/package-lock.json | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/core/package-lock.json b/core/package-lock.json index cf77facb0..0600995f0 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -201,14 +201,14 @@ }, "../packages/openai-adapters": { "name": "@continuedev/openai-adapters", - "version": "1.1.1", + "version": "1.5.1", "license": "Apache-2.0", "dependencies": { "@aws-sdk/client-bedrock-runtime": "^3.842.0", "@aws-sdk/credential-providers": "^3.840.0", - "@continuedev/config-types": "file:../config-types", - "@continuedev/config-yaml": "file:../config-yaml", - "@continuedev/fetch": "file:../fetch", + "@continuedev/config-types": "^1.0.14", + "@continuedev/config-yaml": "^1.8.0", + "@continuedev/fetch": "^1.0.16", "dotenv": "^16.5.0", "google-auth-library": "^10.1.0", "json-schema": "^0.4.0", diff --git a/packages/openai-adapters/package-lock.json b/packages/openai-adapters/package-lock.json index c7025a39d..3fd70c90c 100644 --- a/packages/openai-adapters/package-lock.json +++ b/packages/openai-adapters/package-lock.json @@ -1369,7 +1369,7 @@ "version": "1.0.14", "license": "Apache-2.0", "dependencies": { - "zod": "^3.24.2" + "zod": "^3.23.8" } }, "node_modules/@continuedev/config-yaml": { From 3786ac6cebf20dfc5fd6be1668571dfa4e03b6f3 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 21 Aug 2025 12:22:36 -0700 Subject: [PATCH 40/48] chore: bump version --- binary/package-lock.json | 16 +++++++++++----- extensions/vscode/package-lock.json | 11 ++++++++--- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/binary/package-lock.json b/binary/package-lock.json index 83a78d4d2..9ede17bca 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -40,7 +40,7 @@ "pkg": "^5.8.1", "rimraf": "^5.0.7", "ts-jest": "^29.1.4", - "typescript": "^5.3.3" + "typescript": "^5.6.3" } }, "../core": { @@ -59,6 +59,11 @@ "@modelcontextprotocol/sdk": "^1.12.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", + "@sentry/cli": "^2.50.2", + "@sentry/core": "^9.43.0", + "@sentry/esbuild-plugin": "^4.0.2", + "@sentry/node": "^9.43.0", + "@sentry/vite-plugin": "^4.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", "@xenova/transformers": "2.14.0", "adf-to-md": "^1.1.0", @@ -91,7 +96,7 @@ "node-html-markdown": "^1.3.0", "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", - "openai": "^4.104.0", + "openai": "^5.13.1", "p-limit": "^6.1.0", "partial-json": "^0.1.7", "pg": "^8.11.3", @@ -6758,10 +6763,11 @@ } }, "node_modules/typescript": { - "version": "5.4.5", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz", - "integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==", + "version": "5.9.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.2.tgz", + "integrity": "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A==", "dev": true, + "license": "Apache-2.0", "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 76e958b38..b4d581f9e 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.71", + "version": "1.1.79", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.71", + "version": "1.1.79", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "file:../../packages/config-types", @@ -111,6 +111,11 @@ "@modelcontextprotocol/sdk": "^1.12.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", + "@sentry/cli": "^2.50.2", + "@sentry/core": "^9.43.0", + "@sentry/esbuild-plugin": "^4.0.2", + "@sentry/node": "^9.43.0", + "@sentry/vite-plugin": "^4.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", "@xenova/transformers": "2.14.0", "adf-to-md": "^1.1.0", @@ -143,7 +148,7 @@ "node-html-markdown": "^1.3.0", "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", - "openai": "^4.104.0", + "openai": "^5.13.1", "p-limit": "^6.1.0", "partial-json": "^0.1.7", "pg": "^8.11.3", From c0d33d7bf7b2085deec66b181b37a6af6fb39bb9 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 21 Aug 2025 12:40:46 -0700 Subject: [PATCH 41/48] fix: import checkFim properly --- .../continuedev/continueintellijextension/unit/CheckFimTest.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 da819ad67..277758d34 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,7 +1,7 @@ package com.github.continuedev.continueintellijextension.unit import com.github.continuedev.continueintellijextension.FimResult -import com.github.continuedev.continueintellijextension.utils.checkFim +import com.github.continuedev.continueintellijextension.nextEdit.NextEditUtils.checkFim import junit.framework.TestCase class CheckFimTest : TestCase() { From d32ff8912bfe3db7ec9d0a0bb92a9396acc19e9c Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 21 Aug 2025 13:56:59 -0700 Subject: [PATCH 42/48] fix: delete stale test --- .../continueintellijextension/e2e/NextEdit.kt | 77 ------------------- 1 file changed, 77 deletions(-) delete mode 100644 extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/NextEdit.kt diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/NextEdit.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/NextEdit.kt deleted file mode 100644 index 938674a20..000000000 --- a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/NextEdit.kt +++ /dev/null @@ -1,77 +0,0 @@ -package com.github.continuedev.continueintellijextension.e2e - -import com.automation.remarks.junit5.Video -import com.github.continuedev.continueintellijextension.fixtures.dialog -import com.github.continuedev.continueintellijextension.fixtures.idea -import com.github.continuedev.continueintellijextension.fixtures.welcomeFrame -import com.github.continuedev.continueintellijextension.utils.RemoteRobotExtension -import com.github.continuedev.continueintellijextension.utils.StepsLogger -import com.intellij.remoterobot.RemoteRobot -import com.intellij.remoterobot.fixtures.ComponentFixture -import com.intellij.remoterobot.search.locators.byXpath -import com.intellij.remoterobot.steps.CommonSteps -import com.intellij.remoterobot.utils.keyboard -import com.intellij.remoterobot.utils.waitFor -import com.intellij.remoterobot.utils.waitForIgnoringError -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.extension.ExtendWith -import java.time.Duration.ofMinutes -import java.time.Duration.ofSeconds - -@ExtendWith(RemoteRobotExtension::class) -class NextEdit { - init { - StepsLogger.init() - } - - @BeforeEach - fun waitForIde(remoteRobot: RemoteRobot) { - System.setProperty("continue.nextEdit.test.environment", "true") - waitForIgnoringError(ofMinutes(3)) { remoteRobot.callJs("true") } - } - - @AfterEach - fun closeProject(remoteRobot: RemoteRobot) { - System.clearProperty("continue.nextEdit.test.environment") - CommonSteps(remoteRobot).closeProject() - } - - @Test - @Video - fun displayCompletion(remoteRobot: RemoteRobot): Unit = with(remoteRobot) { - welcomeFrame { - createNewProjectLink.click() - dialog("New Project") { - findText("Java").click() - checkBox("Add sample code").select() - button("Create").click() - } - } - - // Wait for the default "Main.java" tab to load - // Our "continue_tutorial.java.ft" tab loads first, but then "Main.java" takes focus. - waitFor(ofSeconds(20)) { - findAll( - byXpath("//div[@accessiblename='Main.java' and @class='SingleHeightLabel']") - ).isNotEmpty() - } - - idea { - with(textEditor()) { - val userMsg = "TEST_USER_MESSAGE_0" - editor.insertTextAtLine(0, 0, userMsg) - editor.clickOnOffset(userMsg.length) - - keyboard { - enterText(" ") - } - - waitFor(ofSeconds(20)) { - editor.hasText("= \"Hello world!\"") - } - } - } - } -} \ No newline at end of file From 40a8f214fe006e927089d397104d4dfff52358c4 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 25 Aug 2025 10:49:15 -0700 Subject: [PATCH 43/48] chore: remove println --- .../continueintellijextension/utils/InlineCompletionUtils.kt | 3 --- 1 file changed, 3 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/InlineCompletionUtils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/InlineCompletionUtils.kt index f25297fb3..6c12a236e 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/InlineCompletionUtils.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/InlineCompletionUtils.kt @@ -4,7 +4,6 @@ import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.impl.SimpleDataContext -import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.EDT import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project @@ -33,8 +32,6 @@ object InlineCompletionUtils { */ private fun performTrigger(editor: Editor, project: Project?): Boolean { return try { - println("performTrigger called on EDT: ${ApplicationManager.getApplication().isDispatchThread}") - val actionManager = ActionManager.getInstance() val action = actionManager.getAction("CallInlineCompletionAction") From 1090ad9200e577c9c9f1367fd3f9a1e3c1b9b3d5 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 25 Aug 2025 11:09:39 -0700 Subject: [PATCH 44/48] feat: add a quick filter to only let in continue.dev emails --- .../nextEdit/NextEditUtils.kt | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditUtils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditUtils.kt index 4bc8c9fe3..7153ea65f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditUtils.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditUtils.kt @@ -1,6 +1,7 @@ package com.github.continuedev.continueintellijextension.nextEdit import com.github.continuedev.continueintellijextension.FimResult +import com.github.continuedev.continueintellijextension.auth.ContinueAuthService import com.github.continuedev.continueintellijextension.`continue`.ProfileInfoService import com.github.continuedev.continueintellijextension.utils.castNestedOrNull import com.intellij.openapi.components.service @@ -39,6 +40,16 @@ sealed class NextEditModelMatcher { object NextEditUtils { suspend fun isNextEditSupported(project: Project): Boolean { return try { + // NOTE: Quick filter for non-continue users. + // Remove this once we have a FIM - Next Edit toggle UI. + val authService = project.service() + val sessionInfo = authService.loadControlPlaneSessionInfo() + val userEmail = sessionInfo?.account?.id + + if (userEmail == null || !userEmail.endsWith("@continue.dev")) { + return false + } + val profileInfoService = project.service() val selectedModelByRole = profileInfoService.fetchSelectedModelByRoleOrNull() From cc64b584efb6c117c91d9642c39bad1e6c9c12f7 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 25 Aug 2025 11:10:00 -0700 Subject: [PATCH 45/48] chore: cleanup --- .../services/ContinuePluginService.kt | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) 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 c0cb53248..d755a453b 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 @@ -50,9 +50,7 @@ class ContinuePluginService(private val project: Project) : DumbAware { editorFactory.eventMulticaster.addSelectionListener(activeHandlerManager, project) editorFactory.eventMulticaster.addCaretListener(activeHandlerManager, project) editorFactory.eventMulticaster.addDocumentListener(documentChangeTracker, project) - -// setupCompletionTracking(activeHandlerManager) - + // Also register disposal cleanup Disposer.register(project) { activeHandlerManager.dispose() From 2b0e6a5cf617ce4cb0d7345d4055a448cd7693bd Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 25 Aug 2025 11:16:11 -0700 Subject: [PATCH 46/48] fix: remove nextedit, use mercury-coder for both fim and next edit --- .../continueintellijextension/nextEdit/NextEditUtils.kt | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditUtils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditUtils.kt index 7153ea65f..1f9db0e11 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditUtils.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditUtils.kt @@ -16,12 +16,6 @@ sealed class NextEditModelMatcher { title?.lowercase()?.contains("mercury-coder") == true } - data object MercuryCoderNextEdit : NextEditModelMatcher() { - override fun matches(modelName: String?, title: String?): Boolean = - modelName?.lowercase()?.contains("mercury-coder-nextedit") == true || - title?.lowercase()?.contains("mercury-coder-nextedit") == true - } - data object Instinct : NextEditModelMatcher() { override fun matches(modelName: String?, title: String?): Boolean = modelName?.lowercase()?.contains("instinct") == true || @@ -29,7 +23,7 @@ sealed class NextEditModelMatcher { } companion object { - private val allMatchers = listOf(MercuryCoder, MercuryCoderNextEdit, Instinct) + private val allMatchers = listOf(MercuryCoder, Instinct) fun isSupported(modelName: String?, title: String?): Boolean = allMatchers.any { it.matches(modelName, title) } From 098e3545b1dc6c75e080ceae6ac01c045d31b359 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 26 Aug 2025 10:56:52 -0700 Subject: [PATCH 47/48] fix: roll back action.yml --- .github/actions/run-jetbrains-tests/action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/actions/run-jetbrains-tests/action.yml b/.github/actions/run-jetbrains-tests/action.yml index fa204761b..6c2d431ff 100644 --- a/.github/actions/run-jetbrains-tests/action.yml +++ b/.github/actions/run-jetbrains-tests/action.yml @@ -121,7 +121,7 @@ runs: run: | cd extensions/intellij export DISPLAY=:99.0 - ./gradlew test --info --stacktrace + ./gradlew test - name: Move video if: ${{ failure() }} From a0c9d739ee88d55b226b2bfb7f3c97dd3476cdfa Mon Sep 17 00:00:00 2001 From: Jakub Blach Date: Wed, 27 Aug 2025 21:46:14 +0200 Subject: [PATCH 48/48] fix: remove println --- .../continueintellijextension/editor/DiffStreamService.kt | 2 +- .../continueintellijextension/listeners/TypingSessionHandler.kt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamService.kt index 063f545e1..dedd6c76e 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamService.kt @@ -12,7 +12,7 @@ class DiffStreamService { handlers[editor]?.rejectAll() } handlers[editor] = handler - println("Registered handler for editor") + //println("Registered handler for editor") } fun reject(editor: Editor) { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/TypingSessionHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/TypingSessionHandler.kt index c0291b168..0f794f478 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/TypingSessionHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/TypingSessionHandler.kt @@ -47,7 +47,7 @@ class TypingSessionHandler( } override fun onDeactivated() { - println("TypingSessionHandler: Deactivated") + //println("TypingSessionHandler: Deactivated") } override fun dispose() {