diff --git a/core/index.d.ts b/core/index.d.ts index d15c73b50..0c7dcf45c 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -197,15 +197,14 @@ export interface CustomContextProvider { description?: string; renderInlineAs?: string; type?: ContextProviderType; + loadSubmenuItems?: ( + args: LoadSubmenuItemsArgs, + ) => Promise; getContextItems( query: string, extras: ContextProviderExtras, ): Promise; - - loadSubmenuItems?: ( - args: LoadSubmenuItemsArgs, - ) => Promise; } export interface ContextSubmenuItem { @@ -1167,6 +1166,7 @@ export interface MCPResource { description?: string; mimeType?: string; } + export interface MCPTool { name: string; description?: string; @@ -1220,7 +1220,7 @@ export type ApplyStateStatus = | "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" -export interface ApplyState { +export interface UpdateApplyStatePayload { streamId: string; status?: ApplyStateStatus; numDiffs?: number; @@ -1229,6 +1229,12 @@ export interface ApplyState { toolCallId?: string; } +export interface HighlightedCodePayload { + rangeInFileWithContents: RangeInFileWithContents; + prompt?: string; + shouldRun?: boolean; +} + export interface RangeInFileWithContents { filepath: string; range: { @@ -1238,7 +1244,7 @@ export interface RangeInFileWithContents { contents: string; } -export type CodeToEdit = RangeInFileWithContents | FileWithContents; +export type SetCodeToEditPayload = RangeInFileWithContents | FileWithContents; /** * Represents the configuration for a quick action in the Code Lens. diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 17c09a348..aab39aad3 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -1,9 +1,10 @@ import { ToIdeFromWebviewOrCoreProtocol } from "./ide"; import { ToWebviewFromIdeOrCoreProtocol } from "./webview"; -import type { - ApplyState, - CodeToEdit, +import { + UpdateApplyStatePayload, + SetCodeToEditPayload, + HighlightedCodePayload, MessageContent, RangeInFileWithContents, } from "../"; @@ -63,15 +64,8 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { focusContinueInput: [undefined, void]; focusContinueInputWithoutClear: [undefined, void]; focusContinueInputWithNewSession: [undefined, void]; - highlightedCode: [ - { - rangeInFileWithContents: RangeInFileWithContents; - prompt?: string; - shouldRun?: boolean; - }, - void, - ]; - setCodeToEdit: [CodeToEdit, void]; + highlightedCode: [HighlightedCodePayload, void]; + setCodeToEdit: [SetCodeToEditPayload, void]; navigateTo: [{ path: string; toggle?: boolean }, void]; addModel: [undefined, void]; @@ -86,7 +80,7 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { incrementFtc: [undefined, void]; openOnboardingCard: [undefined, void]; applyCodeFromChat: [undefined, void]; - updateApplyState: [ApplyState, void]; + updateApplyState: [UpdateApplyStatePayload, void]; exitEditMode: [undefined, void]; focusEdit: [undefined, void]; }; 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 new file mode 100644 index 000000000..c5f46a415 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt @@ -0,0 +1,194 @@ +package com.github.continuedev.continueintellijextension.`continue` + +import com.github.continuedev.continueintellijextension.UpdateApplyStatePayload +import com.github.continuedev.continueintellijextension.ApplyStateStatus +import com.github.continuedev.continueintellijextension.IDE +import com.github.continuedev.continueintellijextension.ToastType +import com.github.continuedev.continueintellijextension.editor.DiffStreamHandler +import com.github.continuedev.continueintellijextension.editor.DiffStreamService +import com.github.continuedev.continueintellijextension.editor.EditorUtils +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 + */ +class ApplyToFileHandler( + private val project: Project, + private val continuePluginService: ContinuePluginService, + private val ide: IDE, + private val streamId: String, + private val toolCallId: String, + private val text: String, + private val filepath: String?, +) { + + suspend fun handleApplyToFile() { + // Notify webview that we're starting to stream + notifyStreamStarted() + + val editorUtils = EditorUtils.getOrOpenEditor(project, filepath) + + if (editorUtils == null) { + ide.showToast(ToastType.ERROR, "No active editor to apply edits to") + notifyStreamClosed() + return + } + + if (editorUtils.isDocumentEmpty()) { + editorUtils.insertTextIntoEmptyDocument(text) + notifyStreamClosed() + return + } + + // Get the LLM configuration for applying edits + val llm = fetchApplyLLMConfig() ?: run { + ide.showToast(ToastType.ERROR, "Failed to fetch model configuration") + notifyStreamClosed() + return + } + + setupAndStreamDiffs(editorUtils, llm) + } + + private fun notifyStreamStarted() { + sendApplyStateUpdate(ApplyStateStatus.STREAMING) + } + + private fun notifyStreamClosed(numDiffs: Int? = 0) { + sendApplyStateUpdate(ApplyStateStatus.CLOSED, numDiffs) + } + + private fun sendApplyStateUpdate( + status: ApplyStateStatus, + numDiffs: Int? = null + ) { + val payload = UpdateApplyStatePayload( + streamId = streamId, + status = status, + numDiffs = numDiffs, + filepath = filepath, + fileContent = text, + toolCallId = toolCallId + ) + + continuePluginService.sendToWebview("updateApplyState", payload) + } + + 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 + } + } + + private fun setupAndStreamDiffs(editorUtils: EditorUtils, llm: Any) { + val diffStreamService = project.service() + + // Clear all diff blocks before running the diff stream + diffStreamService.reject(editorUtils.editor) + + val llmTitle = (llm as? Map<*, *>)?.get("title") as? String ?: "" + val prompt = buildApplyPrompt() + + // Extract the code ranges (highlighted or full document) + val (prefix, highlighted, suffix) = editorUtils.extractCodeRanges() + + // Get the line range for the diff stream + val rif = editorUtils.getHighlightedCode() + val startLine = rif?.range?.start?.line ?: 0 + val endLine = rif?.range?.end?.line ?: (editorUtils.getLineCount() - 1) + + // Create and register the diff stream handler + val diffStreamHandler = createDiffStreamHandler(editorUtils.editor, startLine, endLine) + diffStreamService.register(diffStreamHandler, editorUtils.editor) + + // Stream the diffs + diffStreamHandler.streamDiffLinesToEditor( + prompt, prefix, highlighted, suffix, llmTitle, false + ) + } + + private fun buildApplyPrompt(): String { + return "The following code was suggested as an edit:\n```\n${text}\n```\nPlease apply it to the previous code." + } + + private fun createDiffStreamHandler( + editor: Editor, + startLine: Int, + endLine: Int + ): DiffStreamHandler { + return DiffStreamHandler( + project, + editor, + startLine, + endLine, + {}, + {}, + streamId, + toolCallId + ) + } + + companion object { + /** + * Factory method to create and execute a new handler for a single apply-to-file operation + */ + suspend fun apply( + project: Project, + continuePluginService: ContinuePluginService, + ide: IDE, + filepath: String?, + streamId: String, + toolCallId: String, + text: String + ) { + + val handler = ApplyToFileHandler( + project, + continuePluginService, + ide, + streamId, + toolCallId, + text, + filepath, + ) + + handler.handleApplyToFile() + } + } +} \ No newline at end of file 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 fbf86dca6..02cfdbd7f 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 @@ -4,10 +4,9 @@ import IntelliJIDE import com.github.continuedev.continueintellijextension.* import com.github.continuedev.continueintellijextension.activities.ContinuePluginDisposable import com.github.continuedev.continueintellijextension.activities.showTutorial -import com.github.continuedev.continueintellijextension.auth.AuthListener import com.github.continuedev.continueintellijextension.auth.ContinueAuthService -import com.github.continuedev.continueintellijextension.editor.DiffStreamHandler import com.github.continuedev.continueintellijextension.editor.DiffStreamService +import com.github.continuedev.continueintellijextension.editor.EditorUtils import com.github.continuedev.continueintellijextension.protocol.* import com.github.continuedev.continueintellijextension.services.* import com.github.continuedev.continueintellijextension.utils.* @@ -18,19 +17,14 @@ 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.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project -import com.intellij.openapi.util.TextRange import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.wm.ToolWindowManager import kotlinx.coroutines.* import java.awt.Toolkit import java.awt.datatransfer.StringSelection -import java.lang.IllegalStateException -import kotlin.coroutines.resume -import kotlin.coroutines.resumeWithException class IdeProtocolClient( @@ -464,141 +458,16 @@ class IdeProtocolClient( dataElement.toString(), ApplyToFileParams::class.java ) - val filepath = params.filepath - continuePluginService.sendToWebview( - "updateApplyState", mapOf( - "streamId" to params.streamId, - "status" to "streaming", - "fileContent" to params.text, - "toolCallId" to params.toolCallId, - "filepath" to filepath - ) + ApplyToFileHandler.apply( + project, + continuePluginService, + ide, + params.filepath, + params.streamId, + params.toolCallId.toString(), + params.text ) - - - fun closeStream() { - continuePluginService.sendToWebview( - "updateApplyState", mapOf( - "numDiffs" to 0, - "streamId" to params.streamId, - "status" to "closed", - "fileContent" to params.text, - "toolCallId" to params.toolCallId, - "filepath" to filepath - ) - ) - } - - var editor: Editor? = null; - - if (!filepath.isNullOrEmpty()) { - val virtualFile = VirtualFileManager.getInstance().findFileByUrl(filepath) - if (virtualFile != null) { - ApplicationManager.getApplication().invokeAndWait { - FileEditorManager.getInstance(project).openFile(virtualFile, true)?.first() - } - } - } - editor = FileEditorManager.getInstance(project).selectedTextEditor - - if (editor == null) { - ide.showToast(ToastType.ERROR, "No active editor to apply edits to") - closeStream() - respond(null) - return@launch - } - - if (editor.document.text.trim().isEmpty()) { - WriteCommandAction.runWriteCommandAction(project) { - editor.document.insertString(0, params.text) - } - closeStream() - respond(null) - return@launch - } - - val llm: Any = 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 (e: Exception) { - launch { - ide.showToast( - ToastType.ERROR, "Failed to fetch model configuration" - ) - } - closeStream() - respond(null) - return@launch - } - - val diffStreamService = project.service() - // Clear all diff blocks before running the diff stream - diffStreamService.reject(editor) - - val llmTitle = (llm as? Map<*, *>)?.get("title") as? String ?: "" - - val prompt = - "The following code was suggested as an edit:\n```\n${params.text}\n```\nPlease apply it to the previous code." - - val rif = getHighlightedCode() - - val (prefix, highlighted, suffix) = if (rif == null) { - // 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)) - val highlighted = rif.contents - val suffix = - editor.document.getText(TextRange(rif.range.end.character, editor.document.textLength)) - - // Remove the selection after processing - ApplicationManager.getApplication().invokeLater { - editor.selectionModel.removeSelection() - } - - Triple(prefix, highlighted, suffix) - } - - val diffStreamHandler = - DiffStreamHandler( - project, - editor, - rif?.range?.start?.line ?: 0, - rif?.range?.end?.line ?: (editor.document.lineCount - 1), - {}, - {}, - params.streamId, - params.toolCallId - ) - - diffStreamService.register(diffStreamHandler, editor) - - diffStreamHandler.streamDiffLinesToEditor( - prompt, prefix, highlighted, suffix, llmTitle, false - ) - respond(null) } @@ -612,52 +481,15 @@ class IdeProtocolClient( } } - private fun getHighlightedCode(): RangeInFileWithContents? { - val result = ApplicationManager.getApplication().runReadAction { - // Get the editor instance for the currently active editor window - val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return@runReadAction null - val virtualFile = - editor.let { FileDocumentManager.getInstance().getFile(it.document) } ?: return@runReadAction null - - // Get the selection range and content - val selectionModel: SelectionModel = editor.selectionModel - val selectedText = selectionModel.selectedText ?: "" - - val document = editor.document - val startOffset = selectionModel.selectionStart - val endOffset = selectionModel.selectionEnd - - if (startOffset == endOffset) { - 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 - ) - } - } - - return result - } - fun sendHighlightedCode(edit: Boolean = false) { - val rif = getHighlightedCode() ?: return + val editor = EditorUtils.getEditor(project) + val rif = editor?.getHighlightedCode() ?: return continuePluginService.sendToWebview( "highlightedCode", - mapOf( - "rangeInFileWithContents" to rif, - "edit" to edit + HighlightedCodePayload( + rangeInFileWithContents = rif, + shouldRun = edit ) ) } 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 d8aa0b353..29ea9f164 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 @@ -35,6 +35,7 @@ class DiffStreamHandler( var index: Int, var highlighter: RangeHighlighter? = null, var diffBlock: VerticalDiffBlock? = null ) + private var editorUtils = EditorUtils(editor) private var curLine = CurLineState(startLine) private var isRunning: Boolean = false private var hasAcceptedOrRejectedBlock: Boolean = false @@ -42,27 +43,29 @@ class DiffStreamHandler( private val unfinishedHighlighters: MutableList = mutableListOf() private val diffBlocks: MutableList = mutableListOf() - private val curLineKey = createTextAttributesKey("CONTINUE_DIFF_CURRENT_LINE", 0x40888888, editor) - private val unfinishedKey = createTextAttributesKey("CONTINUE_DIFF_UNFINISHED_LINE", 0x20888888, editor) + 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) { + if (this.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 - )) + 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 + ) + ) } fun acceptAll() { @@ -87,7 +90,12 @@ class DiffStreamHandler( } fun streamDiffLinesToEditor( - input: String, prefix: String, highlighted: String, suffix: String, modelTitle: String, includeRulesInSystemMessage: Boolean + input: String, + prefix: String, + highlighted: String, + suffix: String, + modelTitle: String, + includeRulesInSystemMessage: Boolean ) { isRunning = true this.sendUpdate("streaming") @@ -96,7 +104,17 @@ class DiffStreamHandler( val virtualFile = getVirtualFile() continuePluginService.coreMessenger?.request( - "streamDiffLines", createRequestParams(input, prefix, highlighted, suffix, virtualFile, modelTitle, includeRulesInSystemMessage), null + "streamDiffLines", + createRequestParams( + input, + prefix, + highlighted, + suffix, + virtualFile, + modelTitle, + includeRulesInSystemMessage + ), + null ) { response -> if (!isRunning) return@request @@ -104,7 +122,7 @@ class DiffStreamHandler( if (response["done"] as? Boolean == true) { handleFinishedResponse() - sendUpdate(if (diffBlocks.isEmpty()) "closed" else "done") + sendUpdate(if (diffBlocks.isEmpty()) "closed" else "done") return@request } 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 0fbc90923..83dc6fd74 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 @@ -1,22 +1,162 @@ 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 import com.intellij.openapi.editor.Editor +import com.intellij.openapi.editor.SelectionModel import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.editor.markup.TextAttributes +import com.intellij.openapi.fileEditor.FileDocumentManager +import com.intellij.openapi.fileEditor.FileEditorManager +import com.intellij.openapi.project.Project +import com.intellij.openapi.util.TextRange +import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.ui.JBColor -class EditorUtils { - fun isTerminal(editor: Editor): Boolean { - return editor.javaClass.name.contains("Terminal") - } -} +/** + * Utility class for working with Editor instances. + */ +class EditorUtils(val editor: Editor) { + private val project: Project + get() = editor.project!! -fun createTextAttributesKey(name: String, color: Int, editor: Editor): TextAttributesKey { - val attributes = TextAttributes().apply { - backgroundColor = JBColor(color, color) + /** + * Checks if the editor is a terminal editor + */ + fun isTerminal(): Boolean { + return editor.javaClass.name.contains("Terminal") } - return TextAttributesKey.createTextAttributesKey(name).also { - editor.colorsScheme.setAttributes(it, attributes) + /** + * Checks if the document is empty (contains only whitespace) + */ + fun isDocumentEmpty(): Boolean { + return editor.document.text.trim().isEmpty() + } + + /** + * Gets the total number of lines in the document + */ + fun getLineCount(): Int { + return editor.document.lineCount + } + + /** + * Inserts text at the specified position in the document + */ + fun insertTextAtPos(pos: Int, text: String) { + WriteCommandAction.runWriteCommandAction(project) { + editor.document.insertString(pos, text) + } + } + + /** + * Inserts text at the beginning of the document + */ + fun insertTextIntoEmptyDocument(text: String) { + insertTextAtPos(0, text) + } + + /** + * Extracts code ranges from the editor: (prefix, highlighted/selected text, suffix) + */ + fun extractCodeRanges(): Triple { + val rif = getHighlightedCode() + + return if (rif == null) { + // 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)) + val highlighted = rif.contents + val suffix = + editor.document.getText(TextRange(rif.range.end.character, editor.document.textLength)) + + // Remove the selection after processing + ApplicationManager.getApplication().invokeLater { + editor.selectionModel.removeSelection() + } + + Triple(prefix, highlighted, suffix) + } + } + + /** + * Gets the selected code from the current editor. + * Returns null if there is no selection. + */ + fun getHighlightedCode(): RangeInFileWithContents? { + return ApplicationManager.getApplication().runReadAction { + val virtualFile = + FileDocumentManager.getInstance().getFile(editor.document) ?: return@runReadAction null + + // Get the selection range and content + val selectionModel: SelectionModel = editor.selectionModel + val selectedText = selectionModel.selectedText ?: "" + + val document = editor.document + val startOffset = selectionModel.selectionStart + val endOffset = selectionModel.selectionEnd + + if (startOffset == endOffset) { + 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 + ) + } + } + } + + fun createTextAttributesKey(name: String, color: Int): TextAttributesKey { + val attributes = TextAttributes().apply { + backgroundColor = JBColor(color, color) + } + + return TextAttributesKey.createTextAttributesKey(name).also { + editor.colorsScheme.setAttributes(it, attributes) + } + } + + companion object { + /** + * Gets an editor for the currently selected file without opening any new files + */ + fun getEditor(project: Project): EditorUtils? { + 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 + */ + fun getOrOpenEditor(project: Project, filepath: String?): EditorUtils? { + if (!filepath.isNullOrEmpty()) { + val virtualFile = VirtualFileManager.getInstance().findFileByUrl(filepath) + if (virtualFile != null) { + ApplicationManager.getApplication().invokeAndWait { + FileEditorManager.getInstance(project).openFile(virtualFile, true).first() + } + } + } + + val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return null + return EditorUtils(editor) + } } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt index a4316c32b..9e597b621 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt @@ -120,7 +120,7 @@ fun openInlineEdit(project: Project?, editor: Editor) { if (project == null) return // Don't open in terminal - if (EditorUtils().isTerminal(editor)) { + if (EditorUtils(editor).isTerminal()) { return } @@ -131,7 +131,8 @@ fun openInlineEdit(project: Project?, editor: Editor) { val modelTitles = mutableListOf() continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response -> - val modelsByRole = response.castNestedOrNull>("content", "result", "config", "modelsByRole") ?: return@request + val modelsByRole = + response.castNestedOrNull>("content", "result", "config", "modelsByRole") ?: return@request val role = if (modelsByRole.containsKey("edit")) "edit" else "chat" modelsByRole.castNestedOrNull>(role) ?.mapNotNull { it.castNestedOrNull("title") } 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 20e8624ac..0a48f24fb 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,13 +27,14 @@ 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 = createTextAttributesKey("CONTINUE_DIFF_NEW_LINE", 0x3000FF00, editor) + private val greenKey = editorUtils.createTextAttributesKey("CONTINUE_DIFF_NEW_LINE", 0x3000FF00) init { val (acceptBtn, rejectBtn) = createButtons() 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 acd9a1d77..da351f915 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 @@ -213,3 +213,35 @@ data class Message( 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" + } + } +} + +data class UpdateApplyStatePayload( + val streamId: String, + val status: ApplyStateStatus? = null, + val numDiffs: Int? = null, + val filepath: String? = null, + val fileContent: String? = null, + val toolCallId: String? = null +) + +data class HighlightedCodePayload( + val rangeInFileWithContents: RangeInFileWithContents, + val prompt: String? = null, + val shouldRun: Boolean? = null +) + diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts index 24456ab22..a3ea9b316 100644 --- a/extensions/vscode/src/diff/vertical/handler.ts +++ b/extensions/vscode/src/diff/vertical/handler.ts @@ -9,36 +9,30 @@ import { indexDecorationType, } from "./decorations"; -import type { ApplyState, DiffLine } from "core"; +import type { UpdateApplyStatePayload, DiffLine } from "core"; import type { VerticalDiffCodeLens } from "./manager"; export interface VerticalDiffHandlerOptions { input?: string; instant?: boolean; onStatusUpdate: ( - status?: ApplyState["status"], - numDiffs?: ApplyState["numDiffs"], - fileContent?: ApplyState["fileContent"], + status?: UpdateApplyStatePayload["status"], + numDiffs?: UpdateApplyStatePayload["numDiffs"], + fileContent?: UpdateApplyStatePayload["fileContent"], ) => void; } export class VerticalDiffHandler implements vscode.Disposable { + public insertedInCurrentBlock = 0; + disposables: vscode.Disposable[] = []; private currentLineIndex: number; private cancelled = false; private newLinesAdded = 0; private deletionBuffer: string[] = []; private removedLineDecorations: RemovedLineDecorationManager; private addedLineDecorations: AddedLineDecorationManager; - - private get fileUri() { - return this.editor.document.uri.toString(); - } - public insertedInCurrentBlock = 0; - public get range(): vscode.Range { - const startLine = Math.min(this.startLine, this.endLine); - const endLine = Math.max(this.startLine, this.endLine); - return new vscode.Range(startLine, 0, endLine, Number.MAX_SAFE_INTEGER); - } + private _diffLinesQueue: DiffLine[] = []; + private _queueLock = false; constructor( private startLine: number, @@ -79,6 +73,308 @@ export class VerticalDiffHandler implements vscode.Disposable { this.disposables.push(disposable); } + public get range(): vscode.Range { + const startLine = Math.min(this.startLine, this.endLine); + const endLine = Math.max(this.startLine, this.endLine); + return new vscode.Range(startLine, 0, endLine, Number.MAX_SAFE_INTEGER); + } + + get isCancelled() { + return this.cancelled; + } + + private get fileUri() { + return this.editor.document.uri.toString(); + } + + async clear(accept: boolean) { + vscode.commands.executeCommand( + "setContext", + "continue.streamingDiff", + false, + ); + + const removedRanges = this.removedLineDecorations.ranges; + if (accept) { + // Accept all: delete all the red ranges and clear green decorations + await this.deleteRangeLines(removedRanges.map((r) => r.range)); + } else { + // Reject all: Re-insert red lines, delete green ones + for (const r of removedRanges) { + await this.deleteRangeLines([r.range]); + await this.insertTextAboveLine(r.range.start.line, r.line); + } + await this.deleteRangeLines(this.addedLineDecorations.ranges); + } + + this.clearDecorations(); + + this.options.onStatusUpdate( + "closed", + this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0, + this.editor.document.getText(), + ); + + this.cancelled = true; + this.refreshCodeLens(); + this.dispose(); + } + + dispose() { + this.disposables.forEach((disposable) => disposable.dispose()); + } + + async queueDiffLine(diffLine: DiffLine | undefined) { + if (diffLine) { + this._diffLinesQueue.push(diffLine); + } + + if (this._queueLock || this.editor !== vscode.window.activeTextEditor) { + return; + } + + this._queueLock = true; + + while (this._diffLinesQueue.length) { + const line = this._diffLinesQueue.shift(); + if (!line) { + break; + } + + try { + await this._handleDiffLine(line); + } catch (e) { + // If editor is switched between calling _handleDiffLine and the edit actually being executed + this._diffLinesQueue.push(line); + break; + } + } + + this._queueLock = false; + } + + async run(diffLineGenerator: AsyncGenerator) { + let diffLines = []; + + try { + // As an indicator of loading + this.updateIndexLineDecorations(); + + for await (const diffLine of diffLineGenerator) { + if (this.isCancelled) { + return; + } + diffLines.push(diffLine); + await this.queueDiffLine(diffLine); + } + + // Clear deletion buffer + await this.insertDeletionBuffer(); + + await this.reapplyWithMyersDiff(diffLines); + + const range = new vscode.Range(this.startLine, 0, this.startLine, 0); + this.editor.revealRange( + range, + vscode.TextEditorRevealType.Default, + ); + + this.options.onStatusUpdate( + "done", + this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0, + this.editor.document.getText(), + ); + + // Reject on user typing + // const listener = vscode.workspace.onDidChangeTextDocument((e) => { + // if (URI.equal(e.document.uri.toString(), this.fileUri)) { + // this.clear(false); + // listener.dispose(); + // } + // }); + } catch (e) { + this.clearForFileUri(this.fileUri, false); + throw e; + } + return diffLines; + } + + async acceptRejectBlock( + accept: boolean, + startLine: number, + numGreen: number, + numRed: number, + skipStatusUpdate?: boolean, + ) { + if (numGreen > 0) { + // Delete the editor decoration + this.addedLineDecorations.deleteRangeStartingAt(startLine + numRed); + if (!accept) { + // Delete the actual lines + await this.deleteLinesAt(startLine + numRed, numGreen); + } + } + + if (numRed > 0) { + const deleted = + this.removedLineDecorations.deleteRangesStartingAt(startLine); + + await this.deleteLinesAt(startLine, numRed); + if (deleted && !accept) { + await this.insertTextAboveLine( + startLine, + deleted.map((r) => r.line).join("\n"), + ); + } + } + + // Shift everything below upward + const offset = -(accept ? numRed : numGreen); + + this.removedLineDecorations.shiftDownAfterLine(startLine, offset); + this.addedLineDecorations.shiftDownAfterLine(startLine, offset); + + // Shift the codelens objects + this.shiftCodeLensObjects(startLine, offset); + + if (!skipStatusUpdate) { + const numDiffs = + this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0; + + const status = numDiffs === 0 ? "closed" : undefined; + + this.options.onStatusUpdate( + status, + numDiffs, + this.editor.document.getText(), + ); + } + } + + public updateLineDelta( + fileUri: string, + startLine: number, + lineDelta: number, + ) { + // Retrieve the diff blocks for the given file + const blocks = this.editorToVerticalDiffCodeLens.get(fileUri); + if (!blocks) { + return; + } + + // Update decorations + this.removedLineDecorations.shiftDownAfterLine(startLine, lineDelta); + this.addedLineDecorations.shiftDownAfterLine(startLine, lineDelta); + + // Update code lens + this.shiftCodeLensObjects(startLine, lineDelta); + } + + public hasDiffForCurrentFile(): boolean { + const diffBlocks = this.editorToVerticalDiffCodeLens.get(this.fileUri); + return diffBlocks !== undefined && diffBlocks.length > 0; + } + + clearDecorations() { + this.removedLineDecorations.clear(); + this.addedLineDecorations.clear(); + this.clearIndexLineDecorations(); + this.editorToVerticalDiffCodeLens.delete(this.fileUri); + this.refreshCodeLens(); + } + + /** + * This method is used to apply diff decorations after the intiial stream. + * This is to handle scenarios where we miscalculate the original diff blocks, + * and decide to follow up with a deterministic algorithm like Myers Diff once + * we have received all of the diff lines. + */ + async reapplyWithMyersDiff(diffLines: DiffLine[]) { + // Diff is messed up without this delay. + await new Promise((resolve) => setTimeout(resolve, 100)); + + // First, we reset the original diff by rejecting all pending diff blocks + const blocks = this.editorToVerticalDiffCodeLens.get(this.fileUri) ?? []; + for (const block of blocks.reverse()) { + await this.acceptRejectBlock( + false, + block.start, + block.numGreen, + block.numRed, + true, + ); + } + + this.clearDecorations(); + + // Then, get our old/new file content based on the original lines + // We need the input to be "newline terminated" rather than + // newline separated, because myersDiff() would consider + // ["A"] => "A" and ["A", ""] => "A\n" to be the same single line. + // "A\n" and "A\n\n" are unambiguous. + const oldFileContent = + diffLines + .filter((line) => line.type === "same" || line.type === "old") + .map((line) => line.line) + .join("\n") + "\n"; + + const newFileContent = + diffLines + .filter((line) => line.type === "same" || line.type === "new") + .map((line) => line.line) + .join("\n") + "\n"; + + const myersDiffs = myersDiff(oldFileContent, newFileContent); + + const replaceContent = myersDiffs + .map((diff) => (diff.type === "old" ? "" : diff.line)) + .join("\n"); + + // Then, we insert our diff lines + await this.editor.edit((editBuilder) => { + editBuilder.replace(this.range, replaceContent), + { + undoStopAfter: false, + undoStopBefore: false, + }; + }); + + // Lastly, we apply decorations + let numRed = 0; + let numGreen = 0; + + const codeLensBlocks: VerticalDiffCodeLens[] = []; + + myersDiffs.forEach((diff, index) => { + if (diff.type === "old") { + this.removedLineDecorations.addLine(this.startLine + index, diff.line); + numRed++; + } else if (diff.type === "new") { + this.addedLineDecorations.addLine(this.startLine + index); + numGreen++; + } else if (diff.type === "same" && (numRed > 0 || numGreen > 0)) { + codeLensBlocks.push({ + numRed, + numGreen, + start: this.startLine + index - numRed - numGreen, + }); + numRed = 0; + numGreen = 0; + } + }); + + if (numRed > 0 || numGreen > 0) { + codeLensBlocks.push({ + numGreen, + numRed, + start: this.startLine + myersDiffs.length - numRed - numGreen, + }); + } + + this.editorToVerticalDiffCodeLens.set(this.fileUri, codeLensBlocks); + this.refreshCodeLens(); + } + private async insertDeletionBuffer() { if (this.deletionBuffer.length || this.insertedInCurrentBlock > 0) { const blocks = this.editorToVerticalDiffCodeLens.get(this.fileUri) || []; @@ -229,81 +525,6 @@ export class VerticalDiffHandler implements vscode.Disposable { this.editor.setDecorations(indexDecorationType, []); } - async clear(accept: boolean) { - vscode.commands.executeCommand( - "setContext", - "continue.streamingDiff", - false, - ); - - const removedRanges = this.removedLineDecorations.ranges; - if (accept) { - // Accept all: delete all the red ranges and clear green decorations - await this.deleteRangeLines(removedRanges.map((r) => r.range)); - } else { - // Reject all: Re-insert red lines, delete green ones - for (const r of removedRanges) { - await this.deleteRangeLines([r.range]); - await this.insertTextAboveLine(r.range.start.line, r.line); - } - await this.deleteRangeLines(this.addedLineDecorations.ranges); - } - - this.clearDecorations(); - - this.options.onStatusUpdate( - "closed", - this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0, - this.editor.document.getText(), - ); - - this.cancelled = true; - this.refreshCodeLens(); - this.dispose(); - } - - disposables: vscode.Disposable[] = []; - - dispose() { - this.disposables.forEach((disposable) => disposable.dispose()); - } - - get isCancelled() { - return this.cancelled; - } - - private _diffLinesQueue: DiffLine[] = []; - private _queueLock = false; - - async queueDiffLine(diffLine: DiffLine | undefined) { - if (diffLine) { - this._diffLinesQueue.push(diffLine); - } - - if (this._queueLock || this.editor !== vscode.window.activeTextEditor) { - return; - } - - this._queueLock = true; - - while (this._diffLinesQueue.length) { - const line = this._diffLinesQueue.shift(); - if (!line) { - break; - } - - try { - await this._handleDiffLine(line); - } catch (e) { - // If editor is switched between calling _handleDiffLine and the edit actually being executed - this._diffLinesQueue.push(line); - break; - } - } - - this._queueLock = false; - } - private async _handleDiffLine(diffLine: DiffLine) { switch (diffLine.type) { case "same": @@ -323,104 +544,6 @@ export class VerticalDiffHandler implements vscode.Disposable { } } - async run(diffLineGenerator: AsyncGenerator) { - let diffLines = []; - - try { - // As an indicator of loading - this.updateIndexLineDecorations(); - - for await (const diffLine of diffLineGenerator) { - if (this.isCancelled) { - return; - } - diffLines.push(diffLine); - await this.queueDiffLine(diffLine); - } - - // Clear deletion buffer - await this.insertDeletionBuffer(); - - await this.reapplyWithMyersDiff(diffLines); - - const range = new vscode.Range(this.startLine, 0, this.startLine, 0); - this.editor.revealRange( - range, - vscode.TextEditorRevealType.Default, - ); - - this.options.onStatusUpdate( - "done", - this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0, - this.editor.document.getText(), - ); - - // Reject on user typing - // const listener = vscode.workspace.onDidChangeTextDocument((e) => { - // if (URI.equal(e.document.uri.toString(), this.fileUri)) { - // this.clear(false); - // listener.dispose(); - // } - // }); - } catch (e) { - this.clearForFileUri(this.fileUri, false); - throw e; - } - return diffLines; - } - - async acceptRejectBlock( - accept: boolean, - startLine: number, - numGreen: number, - numRed: number, - skipStatusUpdate?: boolean, - ) { - if (numGreen > 0) { - // Delete the editor decoration - this.addedLineDecorations.deleteRangeStartingAt(startLine + numRed); - if (!accept) { - // Delete the actual lines - await this.deleteLinesAt(startLine + numRed, numGreen); - } - } - - if (numRed > 0) { - const deleted = - this.removedLineDecorations.deleteRangesStartingAt(startLine); - - await this.deleteLinesAt(startLine, numRed); - if (deleted && !accept) { - await this.insertTextAboveLine( - startLine, - deleted.map((r) => r.line).join("\n"), - ); - } - } - - // Shift everything below upward - const offset = -(accept ? numRed : numGreen); - - this.removedLineDecorations.shiftDownAfterLine(startLine, offset); - this.addedLineDecorations.shiftDownAfterLine(startLine, offset); - - // Shift the codelens objects - this.shiftCodeLensObjects(startLine, offset); - - if (!skipStatusUpdate) { - const numDiffs = - this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0; - - const status = numDiffs === 0 ? "closed" : undefined; - - this.options.onStatusUpdate( - status, - numDiffs, - this.editor.document.getText(), - ); - } - } - private shiftCodeLensObjects(startLine: number, offset: number) { // Shift the codelens objects const blocks = @@ -437,128 +560,4 @@ export class VerticalDiffHandler implements vscode.Disposable { this.refreshCodeLens(); } - - public updateLineDelta( - fileUri: string, - startLine: number, - lineDelta: number, - ) { - // Retrieve the diff blocks for the given file - const blocks = this.editorToVerticalDiffCodeLens.get(fileUri); - if (!blocks) { - return; - } - - // Update decorations - this.removedLineDecorations.shiftDownAfterLine(startLine, lineDelta); - this.addedLineDecorations.shiftDownAfterLine(startLine, lineDelta); - - // Update code lens - this.shiftCodeLensObjects(startLine, lineDelta); - } - - public hasDiffForCurrentFile(): boolean { - const diffBlocks = this.editorToVerticalDiffCodeLens.get(this.fileUri); - return diffBlocks !== undefined && diffBlocks.length > 0; - } - - clearDecorations() { - this.removedLineDecorations.clear(); - this.addedLineDecorations.clear(); - this.clearIndexLineDecorations(); - this.editorToVerticalDiffCodeLens.delete(this.fileUri); - this.refreshCodeLens(); - } - - /** - * This method is used to apply diff decorations after the intiial stream. - * This is to handle scenarios where we miscalculate the original diff blocks, - * and decide to follow up with a deterministic algorithm like Myers Diff once - * we have received all of the diff lines. - */ - async reapplyWithMyersDiff(diffLines: DiffLine[]) { - // Diff is messed up without this delay. - await new Promise((resolve) => setTimeout(resolve, 100)); - - // First, we reset the original diff by rejecting all pending diff blocks - const blocks = this.editorToVerticalDiffCodeLens.get(this.fileUri) ?? []; - for (const block of blocks.reverse()) { - await this.acceptRejectBlock( - false, - block.start, - block.numGreen, - block.numRed, - true, - ); - } - - this.clearDecorations(); - - // Then, get our old/new file content based on the original lines - // We need the input to be "newline terminated" rather than - // newline separated, because myersDiff() would consider - // ["A"] => "A" and ["A", ""] => "A\n" to be the same single line. - // "A\n" and "A\n\n" are unambiguous. - const oldFileContent = - diffLines - .filter((line) => line.type === "same" || line.type === "old") - .map((line) => line.line) - .join("\n") + "\n"; - - const newFileContent = - diffLines - .filter((line) => line.type === "same" || line.type === "new") - .map((line) => line.line) - .join("\n") + "\n"; - - const myersDiffs = myersDiff(oldFileContent, newFileContent); - - const replaceContent = myersDiffs - .map((diff) => (diff.type === "old" ? "" : diff.line)) - .join("\n"); - - // Then, we insert our diff lines - await this.editor.edit((editBuilder) => { - editBuilder.replace(this.range, replaceContent), - { - undoStopAfter: false, - undoStopBefore: false, - }; - }); - - // Lastly, we apply decorations - let numRed = 0; - let numGreen = 0; - - const codeLensBlocks: VerticalDiffCodeLens[] = []; - - myersDiffs.forEach((diff, index) => { - if (diff.type === "old") { - this.removedLineDecorations.addLine(this.startLine + index, diff.line); - numRed++; - } else if (diff.type === "new") { - this.addedLineDecorations.addLine(this.startLine + index); - numGreen++; - } else if (diff.type === "same" && (numRed > 0 || numGreen > 0)) { - codeLensBlocks.push({ - numRed, - numGreen, - start: this.startLine + index - numRed - numGreen, - }); - numRed = 0; - numGreen = 0; - } - }); - - if (numRed > 0 || numGreen > 0) { - codeLensBlocks.push({ - numGreen, - numRed, - start: this.startLine + myersDiffs.length - numRed - numGreen, - }); - } - - this.editorToVerticalDiffCodeLens.set(this.fileUri, codeLensBlocks); - this.refreshCodeLens(); - } } diff --git a/gui/src/components/AcceptRejectAllButtons.tsx b/gui/src/components/AcceptRejectAllButtons.tsx index 941c19b67..0a47c07df 100644 --- a/gui/src/components/AcceptRejectAllButtons.tsx +++ b/gui/src/components/AcceptRejectAllButtons.tsx @@ -1,12 +1,12 @@ import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; -import { ApplyState } from "core"; +import { UpdateApplyStatePayload } from "core"; import { useContext } from "react"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { getMetaKeyLabel } from "../util"; import { useFontSize } from "./ui/font"; export interface AcceptRejectAllButtonsProps { - applyStates: ApplyState[]; + applyStates: UpdateApplyStatePayload[]; onAcceptOrReject?: (outcome: AcceptOrRejectOutcome) => void; } @@ -22,6 +22,7 @@ export default function AcceptRejectAllButtons({ const ideMessenger = useContext(IdeMessengerContext); const tinyFont = useFontSize(-3); + async function handleAcceptOrReject(status: AcceptOrRejectOutcome) { for (const { filepath = "", streamId } of pendingApplyStates) { ideMessenger.post(status, { diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx index b08fd5a1f..30ae8369e 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx @@ -1,5 +1,5 @@ import { CheckIcon, PlayIcon, XMarkIcon } from "@heroicons/react/24/outline"; -import { ApplyState } from "core"; +import { UpdateApplyStatePayload } from "core"; import { useEffect, useState } from "react"; import { getMetaKeyLabel } from "../../../util"; import Spinner from "../../gui/Spinner"; @@ -9,7 +9,7 @@ import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip"; interface ApplyActionsProps { disableManualApply?: boolean; - applyState?: ApplyState; + applyState?: UpdateApplyStatePayload; onClickAccept: () => void; onClickReject: () => void; onClickApply: () => void; diff --git a/gui/src/components/mainInput/CodeToEditCard.tsx b/gui/src/components/mainInput/CodeToEditCard.tsx index ae31bb684..1c22f5ddf 100644 --- a/gui/src/components/mainInput/CodeToEditCard.tsx +++ b/gui/src/components/mainInput/CodeToEditCard.tsx @@ -1,5 +1,5 @@ import { ChevronRightIcon, XMarkIcon } from "@heroicons/react/24/outline"; -import { CodeToEdit } from "core"; +import { SetCodeToEditPayload } from "core"; import { getMarkdownLanguageTagForFile } from "core/util"; import { getUriPathBasename } from "core/util/uri"; import { useContext, useMemo, useState } from "react"; @@ -26,7 +26,7 @@ const NoPaddingWrapper = styled.div` `; interface CodeToEditItemProps { - code: CodeToEdit; + code: SetCodeToEditPayload; } function CodeToEditItem({ code }: CodeToEditItemProps) { @@ -143,6 +143,7 @@ function CodeToEditItem({ code }: CodeToEditItemProps) { ); } + export default function CodeToEditCard() { // Array from previous multi-file edit const codeToEditArray = useAppSelector( diff --git a/gui/src/redux/slices/editModeState.ts b/gui/src/redux/slices/editModeState.ts index 52a05a97e..061514566 100644 --- a/gui/src/redux/slices/editModeState.ts +++ b/gui/src/redux/slices/editModeState.ts @@ -1,16 +1,21 @@ import { createSlice, PayloadAction } from "@reduxjs/toolkit"; -import { ApplyState, CodeToEdit, MessageModes } from "core"; +import { + UpdateApplyStatePayload, + SetCodeToEditPayload, + MessageModes, +} from "core"; import { EDIT_MODE_STREAM_ID } from "core/edit/constants"; + export interface EditModeState { // Array because of previous multi-file edit functionality // Keeping array to not break persisted redux for now - codeToEdit: CodeToEdit[]; - applyState: ApplyState; + codeToEdit: SetCodeToEditPayload[]; + applyState: UpdateApplyStatePayload; returnToMode: MessageModes; lastNonEditSessionWasEmpty: boolean; } -export const INITIAL_EDIT_APPLY_STATE: ApplyState = { +export const INITIAL_EDIT_APPLY_STATE: UpdateApplyStatePayload = { streamId: EDIT_MODE_STREAM_ID, status: "not-started", }; @@ -34,7 +39,7 @@ export const editModeStateSlice = createSlice({ }, updateEditStateApplyState: ( state, - { payload }: PayloadAction, + { payload }: PayloadAction, ) => { state.applyState = { ...state.applyState, @@ -46,7 +51,7 @@ export const editModeStateSlice = createSlice({ { payload, }: PayloadAction<{ - codeToEdit: CodeToEdit | CodeToEdit[]; + codeToEdit: SetCodeToEditPayload | SetCodeToEditPayload[]; }>, ) => { state.codeToEdit = Array.isArray(payload.codeToEdit) diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index e81545d8b..75d8acdda 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -7,7 +7,7 @@ import { } from "@reduxjs/toolkit"; import { JSONContent } from "@tiptap/react"; import { - ApplyState, + UpdateApplyStatePayload, ChatHistoryItem, ChatMessage, ContextItem, @@ -47,7 +47,7 @@ type SessionState = { symbols: FileSymbolMap; mode: MessageModes; codeBlockApplyStates: { - states: ApplyState[]; + states: UpdateApplyStatePayload[]; curIndex: number; }; newestToolbarPreviewForInput: Record; @@ -521,7 +521,10 @@ export const sessionSlice = createSlice({ state.history[state.history.length - 1].contextItems = contextItems; }, - updateApplyState: (state, { payload }: PayloadAction) => { + updateApplyState: ( + state, + { payload }: PayloadAction, + ) => { const applyState = state.codeBlockApplyStates.states.find( (state) => state.streamId === payload.streamId, ); diff --git a/gui/src/redux/thunks/editMode.ts b/gui/src/redux/thunks/editMode.ts index 4341b14a4..8a7771a24 100644 --- a/gui/src/redux/thunks/editMode.ts +++ b/gui/src/redux/thunks/editMode.ts @@ -1,6 +1,10 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; import { JSONContent } from "@tiptap/core"; -import { CodeToEdit, MessageModes, RangeInFileWithContents } from "core"; +import { + SetCodeToEditPayload, + MessageModes, + RangeInFileWithContents, +} from "core"; import { stripImages } from "core/util/messageContent"; import { resolveEditorContent } from "../../components/mainInput/TipTapEditor"; import { @@ -18,7 +22,7 @@ export const streamEditThunk = createAsyncThunk< void, { editorState: JSONContent; - codeToEdit: CodeToEdit[]; + codeToEdit: SetCodeToEditPayload[]; }, ThunkApiType >(