diff --git a/.continue/rules/intellij-test-standards.yaml b/.continue/rules/intellij-test-standards.yaml new file mode 100644 index 000000000..f706757e2 --- /dev/null +++ b/.continue/rules/intellij-test-standards.yaml @@ -0,0 +1,10 @@ +name: IntelliJ Test Standards +version: 0.0.1 +schema: v1 +rules: + - name: IntelliJ Test Standards + rule: When writing tests for the IntelliJ plugin, use the mockk library for + mocking. Prefer mockk's idiomatic syntax for creating and verifying mocks. + Always structure tests with clear Arrange-Act-Assert patterns and use + descriptive test names that indicate the scenario being tested. + globs: "**/test/**/*.kt" diff --git a/binary/build.js b/binary/build.js index 574a90444..b67afb94f 100644 --- a/binary/build.js +++ b/binary/build.js @@ -64,7 +64,7 @@ async function buildWithEsbuild() { format: "cjs", platform: "node", sourcemap: true, - minify: true, + minify: !esbuildOnly, treeShaking: true, loader: { // eslint-disable-next-line @typescript-eslint/naming-convention diff --git a/core/index.d.ts b/core/index.d.ts index 9636edffc..47caac060 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1230,12 +1230,27 @@ export interface ApplyState { toolCallId?: string; } +export interface StreamDiffLinesPayload { + prefix: string; + highlighted: string; + suffix: string; + input: string; + language: string | undefined; + modelTitle: string | undefined; + includeRulesInSystemMessage: boolean; +} + export interface HighlightedCodePayload { rangeInFileWithContents: RangeInFileWithContents; prompt?: string; shouldRun?: boolean; } +export interface AcceptOrRejectDiffPayload { + filepath: string; + streamId?: string; +} + export interface RangeInFileWithContents { filepath: string; range: { diff --git a/core/llm/templates/edit/gpt.ts b/core/llm/templates/edit/gpt.ts index 4dcc39523..61d23a732 100644 --- a/core/llm/templates/edit/gpt.ts +++ b/core/llm/templates/edit/gpt.ts @@ -64,6 +64,8 @@ export const gptEditPrompt: PromptTemplateFunction = (history, otherData) => { \`\`\` The user's request is: "${otherData.userInput}" + + DO NOT output any natural language, only output the code changes. Here is the rewritten code:`); diff --git a/core/protocol/core.ts b/core/protocol/core.ts index de061c730..ef4cde60b 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -9,7 +9,7 @@ import { AutocompleteInput } from "../autocomplete/util/types"; import { SharedConfigSchema } from "../config/sharedConfig"; import { GlobalContextModelSelections } from "../util/GlobalContext"; -import type { +import { BrowserSerializedContinueConfig, ChatMessage, ContextItem, @@ -29,6 +29,7 @@ import type { SessionMetadata, SiteIndexingConfig, SlashCommandDescription, + StreamDiffLinesPayload, ToolCall, } from "../"; import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager"; @@ -142,18 +143,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, AsyncGenerator, ]; - streamDiffLines: [ - { - prefix: string; - highlighted: string; - suffix: string; - input: string; - language: string | undefined; - modelTitle: string | undefined; - includeRulesInSystemMessage: boolean; - }, - AsyncGenerator, - ]; + streamDiffLines: [StreamDiffLinesPayload, AsyncGenerator]; "chatDescriber/describe": [ { text: string; diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 66c07f03c..3c836126a 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -7,6 +7,7 @@ import { HighlightedCodePayload, MessageContent, RangeInFileWithContents, + AcceptOrRejectDiffPayload, } from "../"; export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { @@ -43,8 +44,8 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { "jetbrains/getColors": [undefined, Record]; "vscode/openMoveRightMarkdown": [undefined, void]; setGitHubAuthToken: [{ token: string }, void]; - acceptDiff: [{ filepath: string; streamId?: string }, void]; - rejectDiff: [{ filepath: string; streamId?: string }, void]; + acceptDiff: [AcceptOrRejectDiffPayload, void]; + rejectDiff: [AcceptOrRejectDiffPayload, void]; "edit/sendPrompt": [ { prompt: MessageContent; 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 76338f0f6..a8edd5527 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 @@ -68,7 +68,7 @@ class ApplyToFileHandler( ) { val payload = ApplyState( streamId = params.streamId, - status = status, + status = status.status, numDiffs = numDiffs, filepath = params.filepath, fileContent = params.text, diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 1c593479a..cc9f018fa 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -14,7 +14,6 @@ import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.service -import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.SelectionModel import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.DumbAware @@ -32,6 +31,8 @@ class IdeProtocolClient( private val project: Project ) : DumbAware { private val ide: IDE = IntelliJIDE(project, continuePluginService) + private val diffStreamService = project.service() + /** * Create a dispatcher with limited parallelism to prevent UI freezing. @@ -441,7 +442,13 @@ class IdeProtocolClient( ) val filepath = params.filepath; - acceptOrRejectDiff(filepath, true) + val editor = EditorUtils.getOrOpenEditor(project, filepath)?.editor + + if (editor != null) { + diffStreamService.accept(editor) + } + + respond(null) } "rejectDiff" -> { @@ -450,7 +457,13 @@ class IdeProtocolClient( RejectDiffParams::class.java ) val filepath = params.filepath; - acceptOrRejectDiff(filepath, false) + + val editor = EditorUtils.getOrOpenEditor(project, filepath)?.editor + if (editor != null) { + diffStreamService.reject(editor) + } + respond(null) + } "applyToFile" -> { @@ -496,28 +509,6 @@ class IdeProtocolClient( continuePluginService.sendToWebview("acceptRejectDiff", AcceptRejectDiff(accepted, stepIndex), uuid()) } - fun acceptOrRejectDiff(filepath: String, accepted: Boolean) { - val virtualFile = VirtualFileManager.getInstance().findFileByUrl(filepath) - - if (virtualFile != null) { - ApplicationManager.getApplication().invokeAndWait { - val openedEditor = - FileEditorManager.getInstance(project).openFile(virtualFile, true)?.first() - if (openedEditor != null) { - val editor: Editor? = FileEditorManager.getInstance(project).selectedTextEditor - - if (editor != null) { - val diffStreamService = project.service() - if (accepted) { - diffStreamService.accept(editor) - } else { - diffStreamService.reject(editor) - } - } - } - } - } - } fun deleteAtIndex(index: Int) { continuePluginService.sendToWebview("deleteAtIndex", DeleteAtIndex(index), uuid()) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt index 29ea9f164..b4c9d14ca 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt @@ -1,5 +1,8 @@ package com.github.continuedev.continueintellijextension.editor +import com.github.continuedev.continueintellijextension.ApplyState +import com.github.continuedev.continueintellijextension.ApplyStateStatus +import com.github.continuedev.continueintellijextension.StreamDiffLinesPayload import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction @@ -12,7 +15,6 @@ import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.project.Project -import com.intellij.openapi.vfs.VirtualFile import kotlin.math.max import kotlin.math.min @@ -35,44 +37,41 @@ class DiffStreamHandler( var index: Int, var highlighter: RangeHighlighter? = null, var diffBlock: VerticalDiffBlock? = null ) - private var editorUtils = EditorUtils(editor) + private val diffBlocks: MutableList = mutableListOf() private var curLine = CurLineState(startLine) private var isRunning: Boolean = false private var hasAcceptedOrRejectedBlock: Boolean = false - private val unfinishedHighlighters: MutableList = mutableListOf() - private val diffBlocks: MutableList = mutableListOf() + private val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java) + private val virtualFile = FileDocumentManager.getInstance().getFile(editor.document) - private val curLineKey = editorUtils.createTextAttributesKey("CONTINUE_DIFF_CURRENT_LINE", 0x40888888) - private val unfinishedKey = editorUtils.createTextAttributesKey("CONTINUE_DIFF_UNFINISHED_LINE", 0x20888888) init { initUnfinishedRangeHighlights() } - private fun sendUpdate(status: String) { - if (this.streamId == null) { + private fun sendUpdate(status: ApplyStateStatus) { + if (streamId == null) { return } - val virtualFile = getVirtualFile() - val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java) - continuePluginService.sendToWebview( - "updateApplyState", mapOf( - "numDiffs" to this.diffBlocks.size, - "streamId" to this.streamId, - "status" to status, - "fileContent" to "not implemented", - "toolCallId" to this.toolCallId, - "filepath" to virtualFile?.url - ) + + // Define a single payload and use it for sending + val payload = ApplyState( + streamId = streamId, + status = status.status, + numDiffs = diffBlocks.size, + filepath = virtualFile?.url, + fileContent = "not implemented", + toolCallId = toolCallId?.toString() ) + + continuePluginService.sendToWebview("updateApplyState", payload) } fun acceptAll() { - editor.markupModel.removeAllHighlighters(); - sendUpdate("closed") - - resetState() + ApplicationManager.getApplication().invokeLater { + diffBlocks.toList().forEach { it.handleAccept() } + } } fun rejectAll() { @@ -80,13 +79,16 @@ class DiffStreamHandler( // to our changes. However, if the user has accepted or rejected one or more diff blocks, there isn't a simple // way to undo our changes without also undoing the diff that the user accepted or rejected. if (hasAcceptedOrRejectedBlock) { - diffBlocks.forEach { it.handleReject() } + ApplicationManager.getApplication().invokeLater { + val blocksToReject = diffBlocks.toList() + blocksToReject.toList().forEach { it.handleReject() } + } } else { undoChanges() + // We have to manually call `handleClosedState`, but above, + // this is done by invoking the button handlers + setClosed() } - sendUpdate("closed") - - resetState() } fun streamDiffLinesToEditor( @@ -98,21 +100,18 @@ class DiffStreamHandler( includeRulesInSystemMessage: Boolean ) { isRunning = true - this.sendUpdate("streaming") - - val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java) - val virtualFile = getVirtualFile() + sendUpdate(ApplyStateStatus.STREAMING) continuePluginService.coreMessenger?.request( "streamDiffLines", - createRequestParams( - input, - prefix, - highlighted, - suffix, - virtualFile, - modelTitle, - includeRulesInSystemMessage + StreamDiffLinesPayload( + input = input, + prefix = prefix, + highlighted = highlighted, + suffix = suffix, + language = virtualFile?.fileType?.name, + modelTitle = modelTitle, + includeRulesInSystemMessage = includeRulesInSystemMessage ), null ) { response -> @@ -122,7 +121,6 @@ class DiffStreamHandler( if (response["done"] as? Boolean == true) { handleFinishedResponse() - sendUpdate(if (diffBlocks.isEmpty()) "closed" else "done") return@request } @@ -131,6 +129,9 @@ class DiffStreamHandler( } private fun initUnfinishedRangeHighlights() { + val editorUtils = EditorUtils(editor) + val unfinishedKey = editorUtils.createTextAttributesKey("CONTINUE_DIFF_UNFINISHED_LINE", 0x20888888) + for (i in startLine..endLine) { val highlighter = editor.markupModel.addLineHighlighter( unfinishedKey, min( @@ -173,10 +174,11 @@ class DiffStreamHandler( } if (diffBlocks.isEmpty()) { - sendUpdate("closed") - onClose() + setClosed() } else { - sendUpdate("done") + // TODO: It's confusing that we pass `DONE` here. What we're doing is updating the UI with the latest + // diff count. We should have a dedicated status for this. + sendUpdate(ApplyStateStatus.DONE) } } @@ -187,8 +189,6 @@ class DiffStreamHandler( ) diffBlocks.add(diffBlock) - sendUpdate("streaming") - return diffBlock } @@ -221,12 +221,17 @@ class DiffStreamHandler( } private fun updateProgressHighlighters(type: DiffLineType) { + val editorUtils = EditorUtils(editor) + val curLineKey = editorUtils.createTextAttributesKey("CONTINUE_DIFF_CURRENT_LINE", 0x40888888) + // Update the highlighter to show the current line curLine.highlighter?.let { editor.markupModel.removeHighlighter(it) } curLine.highlighter = editor.markupModel.addLineHighlighter( curLineKey, min(curLine.index, max(0, editor.document.lineCount - 1)), HighlighterLayer.LAST ) + editorUtils.scrollToLine(curLine.index) + // Remove the unfinished lines highlighter if (type != DiffLineType.OLD && unfinishedHighlighters.isNotEmpty()) { editor.markupModel.removeHighlighter(unfinishedHighlighters.removeAt(0)) @@ -260,15 +265,18 @@ class DiffStreamHandler( curLine = CurLineState(startLine) isRunning = false - // Close the Edit input + // Close the Edit input if editing onClose() } private fun undoChanges() { + if (virtualFile == null) { + return + } + WriteCommandAction.runWriteCommandAction(project) { val undoManager = UndoManager.getInstance(project) - val virtualFile = getVirtualFile() ?: return@runWriteCommandAction val fileEditor = FileEditorManager.getInstance(project).getSelectedEditor(virtualFile) as TextEditor if (undoManager.isUndoAvailable(fileEditor)) { @@ -278,33 +286,9 @@ class DiffStreamHandler( undoManager.undo(fileEditor) } } - sendUpdate("done") } } - private fun getVirtualFile(): VirtualFile? { - return FileDocumentManager.getInstance().getFile(editor.document) ?: return null - } - - private fun createRequestParams( - input: String, - prefix: String, - highlighted: String, - suffix: String, - virtualFile: VirtualFile?, - modelTitle: String, - includeRulesInSystemMessage: Boolean - ): Map { - return mapOf( - "input" to input, - "prefix" to prefix, - "highlighted" to highlighted, - "suffix" to suffix, - "language" to virtualFile?.fileType?.name, - "modelTitle" to modelTitle, - "includeRulesInSystemMessage" to includeRulesInSystemMessage, - ) - } private fun handleFinishedResponse() { ApplicationManager.getApplication().invokeLater { @@ -314,6 +298,12 @@ class DiffStreamHandler( onFinish() cleanupProgressHighlighters() + + if (diffBlocks.isEmpty()) { + setClosed() + } else { + sendUpdate(ApplyStateStatus.DONE) + } } } @@ -343,4 +333,10 @@ class DiffStreamHandler( else -> throw Exception("Unknown diff line type: $type") } } + + private fun setClosed() { + sendUpdate(ApplyStateStatus.CLOSED) + resetState() + onClose() + } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorUtils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorUtils.kt index 83dc6fd74..23b1b1bcd 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorUtils.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorUtils.kt @@ -2,7 +2,6 @@ package com.github.continuedev.continueintellijextension.editor import com.github.continuedev.continueintellijextension.Position import com.github.continuedev.continueintellijextension.Range -import com.github.continuedev.continueintellijextension.RangeInFileWithContents import com.github.continuedev.continueintellijextension.utils.toUriOrNull import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction @@ -16,6 +15,7 @@ import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.ui.JBColor +import com.intellij.openapi.editor.ScrollType /** * Utility class for working with Editor instances. @@ -61,6 +61,18 @@ class EditorUtils(val editor: Editor) { insertTextAtPos(0, text) } + + /** + * Scrolls the editor to make the specified line visible + */ + fun scrollToLine(lineNumber: Int) { + val safeLineNumber = lineNumber.coerceIn(0, editor.document.lineCount - 1) + val lineStartOffset = editor.document.getLineStartOffset(safeLineNumber) + val logicalPosition = editor.offsetToLogicalPosition(lineStartOffset) + editor.scrollingModel.scrollTo(logicalPosition, ScrollType.CENTER_UP) + } + + /** * Extracts code ranges from the editor: (prefix, highlighted/selected text, suffix) */ @@ -71,10 +83,12 @@ class EditorUtils(val editor: Editor) { // If no highlight, use the whole document as highlighted Triple("", editor.document.text, "") } else { - val prefix = editor.document.getText(TextRange(0, rif.range.start.character)) + // Use the RangeInFileWithContents to get absolute offsets + val startOffset = rif.getStartOffset(editor.document) + val endOffset = rif.getEndOffset(editor.document) + val prefix = editor.document.getText(TextRange(0, startOffset)) val highlighted = rif.contents - val suffix = - editor.document.getText(TextRange(rif.range.end.character, editor.document.textLength)) + val suffix = editor.document.getText(TextRange(endOffset, editor.document.textLength)) // Remove the selection after processing ApplicationManager.getApplication().invokeLater { @@ -94,11 +108,8 @@ class EditorUtils(val editor: Editor) { val virtualFile = FileDocumentManager.getInstance().getFile(editor.document) ?: return@runReadAction null - // Get the selection range and content + // Get the selection range val selectionModel: SelectionModel = editor.selectionModel - val selectedText = selectionModel.selectedText ?: "" - - val document = editor.document val startOffset = selectionModel.selectionStart val endOffset = selectionModel.selectionEnd @@ -106,18 +117,12 @@ class EditorUtils(val editor: Editor) { return@runReadAction null } - val startLine = document.getLineNumber(startOffset) - val endLine = document.getLineNumber(endOffset) - - val startChar = startOffset - document.getLineStartOffset(startLine) - val endChar = endOffset - document.getLineStartOffset(endLine) - return@runReadAction virtualFile.toUriOrNull()?.let { - RangeInFileWithContents( - it, Range( - Position(startLine, startChar), - Position(endLine, endChar) - ), selectedText + RangeInFileWithContents.fromSelection( + it, + editor.document, + startOffset, + endOffset ) } } @@ -141,7 +146,7 @@ class EditorUtils(val editor: Editor) { val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return null return EditorUtils(editor) } - + /** * Gets or opens an editor for the specified filepath and returns an EditorUtils instance */ diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/RangeInFileWithContents.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/RangeInFileWithContents.kt new file mode 100644 index 000000000..98d2041d0 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/RangeInFileWithContents.kt @@ -0,0 +1,62 @@ +package com.github.continuedev.continueintellijextension.editor + +import com.github.continuedev.continueintellijextension.Position +import com.github.continuedev.continueintellijextension.Range +import com.intellij.openapi.editor.Document +import com.intellij.openapi.util.TextRange + +/** + * Represents a range of text in a file with its contents. + * Provides utility methods for working with document positions and offsets. + */ +class RangeInFileWithContents( + val filepath: String, + val range: Range, + val contents: String +) { + /** + * Returns the absolute document offset for the start position + */ + fun getStartOffset(document: Document): Int { + return document.getLineStartOffset(range.start.line) + range.start.character + } + + /** + * Returns the absolute document offset for the end position + */ + fun getEndOffset(document: Document): Int { + return document.getLineStartOffset(range.end.line) + range.end.character + } + + + companion object { + /** + * Create a RangeInFileWithContents from a document selection + */ + fun fromSelection( + filepath: String, + document: Document, + selectionStart: Int, + selectionEnd: Int + ): RangeInFileWithContents { + val startLine = document.getLineNumber(selectionStart) + val endLine = document.getLineNumber(selectionEnd) + + val startChar = selectionStart - document.getLineStartOffset(startLine) + val endChar = selectionEnd - document.getLineStartOffset(endLine) + + val selectedText = document.getText( + TextRange(selectionStart, selectionEnd) + ) + + return RangeInFileWithContents( + filepath, + Range( + Position(startLine, startChar), + Position(endLine, endChar) + ), + selectedText + ) + } + } +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt index 0a48f24fb..ad902a8b9 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt @@ -27,14 +27,11 @@ class VerticalDiffBlock( ) { val deletedLines: MutableList = mutableListOf() val addedLines: MutableList = mutableListOf() - private var editorUtils = EditorUtils(editor) private val acceptButton: JButton private val rejectButton: JButton private var deletionInlay: Disposable? = null private var textArea: JTextArea? = null // Used for calculation of the text area height when rendering buttons private var hasRenderedDiffBlock: Boolean = false - private val editorComponentInlaysManager = EditorComponentInlaysManager.from(editor, false) - private val greenKey = editorUtils.createTextAttributesKey("CONTINUE_DIFF_NEW_LINE", 0x3000FF00) init { val (acceptBtn, rejectBtn) = createButtons() @@ -79,6 +76,8 @@ class VerticalDiffBlock( fun addNewLine(text: String, line: Int) { + val greenKey = EditorUtils(editor).createTextAttributesKey("CONTINUE_DIFF_NEW_LINE", 0x3000FF00) + if (line == editor.document.lineCount) { editor.document.insertString(editor.document.textLength, "\n") } @@ -98,7 +97,7 @@ class VerticalDiffBlock( return } - if (deletedLines.size > 0) { + if (deletedLines.isNotEmpty()) { renderDeletedLinesInlay() } @@ -108,20 +107,32 @@ class VerticalDiffBlock( } fun handleReject() { - revertDiff() + // Note that the logic for clearing editor UI state assumes that we do it + // prior to undoing the diff changes, changing this order will break things clearEditorUI() + revertDiff() + + onAcceptReject(this@VerticalDiffBlock, false) } + fun handleAccept() { + clearEditorUI() + onAcceptReject(this@VerticalDiffBlock, true) + } + + private fun refreshEditor() { editor.contentComponent.revalidate() editor.contentComponent.repaint() } private fun renderDeletedLinesInlay() { - val textArea = createDeletionTextArea(deletedLines.joinToString("\n")) - this.textArea = textArea + val editorComponentInlaysManager = EditorComponentInlaysManager.from(editor, false) + val newTextArea = createDeletionTextArea(deletedLines.joinToString("\n")) - val disposable = editorComponentInlaysManager.insert(startLine, textArea, true) + textArea = newTextArea + + val disposable = editorComponentInlaysManager.insert(startLine, newTextArea, true) deletionInlay = disposable } @@ -159,7 +170,6 @@ class VerticalDiffBlock( ).apply { addActionListener { handleReject() - onAcceptReject(this@VerticalDiffBlock, false) } } @@ -172,7 +182,6 @@ class VerticalDiffBlock( ).apply { addActionListener { handleAccept() - onAcceptReject(this@VerticalDiffBlock, true) } } @@ -186,9 +195,6 @@ class VerticalDiffBlock( refreshEditor() } - private fun handleAccept() { - clearEditorUI() - } private fun revertDiff() { WriteCommandAction.runWriteCommandAction(project) { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt index 0f6442c6a..aaa4a8e8e 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt @@ -1,5 +1,6 @@ package com.github.continuedev.continueintellijextension +import com.github.continuedev.continueintellijextension.editor.RangeInFileWithContents import com.google.gson.JsonElement enum class ToastType(val value: String) { @@ -214,25 +215,16 @@ data class AcceptRejectDiff(val accepted: Boolean, val stepIndex: Int) data class DeleteAtIndex(val index: Int) -enum class ApplyStateStatus { - NOT_STARTED, // Apply state created but not necessarily streaming - STREAMING, // Changes are being applied to the file - DONE, // All changes have been applied, awaiting user to accept/reject - CLOSED; // All changes have been applied. Note that for new files, we immediately set the status to "closed" - - companion object { - fun toString(status: ApplyStateStatus): String = when (status) { - NOT_STARTED -> "not-started" - STREAMING -> "streaming" - DONE -> "done" - CLOSED -> "closed" - } - } +enum class ApplyStateStatus(val status: String) { + NOT_STARTED("not-started"), + STREAMING("streaming"), + DONE("done"), + CLOSED("closed"); } data class ApplyState( val streamId: String, - val status: ApplyStateStatus? = null, + val status: String, val numDiffs: Int? = null, val filepath: String? = null, val fileContent: String? = null, @@ -245,3 +237,17 @@ data class HighlightedCodePayload( val shouldRun: Boolean? = null ) +data class StreamDiffLinesPayload( + val prefix: String, + val highlighted: String, + val suffix: String, + val input: String, + val language: String?, + val modelTitle: String?, + val includeRulesInSystemMessage: Boolean +) + +data class AcceptOrRejectDiffPayload( + val filepath: String, + val streamId: String? = null +) \ No newline at end of file diff --git a/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ApplyToFileHandlerTest.kt b/extensions/intellij/src/test/kotlin/com/github/continuedev/continueintellijextension/unit/ApplyToFileHandlerTest.kt index 476df7654..4e12e270e 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 @@ -74,7 +74,7 @@ class ApplyToFileHandlerTest { eq("updateApplyState"), withArg { payload -> assert(payload is ApplyState) - assert((payload as ApplyState).status == ApplyStateStatus.STREAMING) + assert((payload as ApplyState).status == ApplyStateStatus.STREAMING.status) }, any() ) @@ -85,7 +85,7 @@ class ApplyToFileHandlerTest { eq("updateApplyState"), withArg { payload -> assert(payload is ApplyState) - assert((payload as ApplyState).status == ApplyStateStatus.CLOSED) + assert((payload as ApplyState).status == ApplyStateStatus.CLOSED.status) }, any() ) diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 5048582ec..09ee927d9 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.34", + "version": "1.1.35", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.34", + "version": "1.1.35", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", diff --git a/gui/src/components/AcceptRejectAllButtons.tsx b/gui/src/components/AcceptRejectDiffButtons.tsx similarity index 100% rename from gui/src/components/AcceptRejectAllButtons.tsx rename to gui/src/components/AcceptRejectDiffButtons.tsx diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx index b08fd5a1f..f825758eb 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx @@ -1,6 +1,5 @@ import { CheckIcon, PlayIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { ApplyState } from "core"; -import { useEffect, useState } from "react"; import { getMetaKeyLabel } from "../../../util"; import Spinner from "../../gui/Spinner"; import { ToolTip } from "../../gui/Tooltip"; @@ -16,47 +15,10 @@ interface ApplyActionsProps { } export function ApplyActions(props: ApplyActionsProps) { - const [hasRejected, setHasRejected] = useState(false); - const [showApplied, setShowApplied] = useState(false); - const isClosed = props.applyState?.status === "closed"; - const isSuccessful = !hasRejected && props.applyState?.numDiffs === 0; - - useEffect(() => { - if (isClosed && isSuccessful) { - setShowApplied(true); - const timer = setTimeout(() => { - setShowApplied(false); - }, 3_000); - return () => clearTimeout(timer); - } - }, [isClosed, isSuccessful]); - function onClickReject() { props.onClickReject(); - setHasRejected(true); } - const applyButton = (text: string) => ( - - - - {text} Code - - - ); - switch (props.applyState ? props.applyState.status : null) { case "streaming": return ( @@ -94,21 +56,30 @@ export function ApplyActions(props: ApplyActionsProps) { ); case "closed": - if (isSuccessful) { - if (showApplied || props.disableManualApply) { - return ( - - Applied - - - ); - } - return applyButton("Reapply"); - } default: if (props.disableManualApply) { return null; } - return applyButton("Apply"); + + return ( + + + + Apply Code + + + ); } } diff --git a/gui/src/components/mainInput/EditModeDetails.tsx b/gui/src/components/mainInput/EditModeDetails.tsx index 1a8cf51ab..69746bcc2 100644 --- a/gui/src/components/mainInput/EditModeDetails.tsx +++ b/gui/src/components/mainInput/EditModeDetails.tsx @@ -2,7 +2,7 @@ import { useContext } from "react"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { exitEditMode } from "../../redux/thunks/editMode"; -import AcceptRejectAllButtons from "../AcceptRejectAllButtons"; +import AcceptRejectDiffButtons from "../AcceptRejectDiffButtons"; import { useMainEditor } from "./TipTapEditor"; const EditModeDetails = () => { @@ -28,7 +28,7 @@ const EditModeDetails = () => {
{`${editApplyState.numDiffs} diff${plural} remaining`}
- { if (outcome === "acceptDiff") { diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 9efee1697..71b87c93a 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -1,8 +1,6 @@ import { ArrowLeftIcon, ChatBubbleOvalLeftIcon, - CodeBracketSquareIcon, - ExclamationTriangleIcon, } from "@heroicons/react/24/outline"; import { Editor, JSONContent } from "@tiptap/react"; import { InputModifiers } from "core"; @@ -20,7 +18,6 @@ import { import { ErrorBoundary } from "react-error-boundary"; import styled from "styled-components"; import { Button, lightGray, vscBackground } from "../../components"; -import AcceptRejectAllButtons from "../../components/AcceptRejectAllButtons"; import FeedbackDialog from "../../components/dialogs/FeedbackDialog"; import FreeTrialOverDialog from "../../components/dialogs/FreeTrialOverDialog"; import { useFindWidget } from "../../components/find/FindWidget"; @@ -50,7 +47,7 @@ import { import { cancelStream } from "../../redux/thunks/cancelStream"; import { streamEditThunk } from "../../redux/thunks/editMode"; import { loadLastSession } from "../../redux/thunks/session"; -import { streamResponseThunk } from "../../redux/thunks/streamResponse"; +import { streamResponseThunk } from "../../redux/thunks"; import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util"; import { FREE_TRIAL_LIMIT_REQUESTS, @@ -64,6 +61,7 @@ import { EmptyChatBody } from "./EmptyChatBody"; import { ExploreDialogWatcher } from "./ExploreDialogWatcher"; import { ToolCallDiv } from "./ToolCallDiv"; import { useAutoScroll } from "./useAutoScroll"; +import AcceptRejectDiffButtons from "../../components/AcceptRejectDiffButtons"; const StepsDiv = styled.div` position: relative; @@ -74,7 +72,7 @@ const StepsDiv = styled.div` } .thread-message { - margin: 0px 0px 0px 1px; + margin: 0 0 0 1px; } `; @@ -112,7 +110,7 @@ export function Chat() { (store) => store.config?.config.selectedModelByRole, ); const isStreaming = useAppSelector((state) => state.session.isStreaming); - const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]); + const [stepsOpen] = useState<(boolean | undefined)[]>([]); const mainTextInputRef = useRef(null); const stepsDivRef = useRef(null); const history = useAppSelector((state) => state.session.history); @@ -202,7 +200,7 @@ export function Chat() { if (newCount >= FREE_TRIAL_LIMIT_REQUESTS) { // Show this message whether using platform or not // So that something happens if in new chat - ideMessenger.ide.showToast( + void ideMessenger.ide.showToast( "error", "You've reached the free trial limit. Please configure a model to continue.", ); @@ -356,23 +354,11 @@ export function Chat() { - ) : false ? ( - - ) : ( - - ) + } open={ typeof stepsOpen[index] === "undefined" - ? false - ? false - : true + ? true : stepsOpen[index]! } onToggle={() => {}} @@ -392,7 +378,7 @@ export function Chat() {
<> {!isStreaming && mode !== "edit" && ( - {}} /> diff --git a/manual-testing-sandbox/test.kt b/manual-testing-sandbox/test.kt index bb13ae9ee..512c34c25 100644 --- a/manual-testing-sandbox/test.kt +++ b/manual-testing-sandbox/test.kt @@ -31,3 +31,6 @@ class Test { } } + + +