From 802cb43cd6b6abf8613591eb38c445e6bd4daa7d Mon Sep 17 00:00:00 2001 From: Test Date: Sat, 26 Oct 2024 17:10:49 -0700 Subject: [PATCH] feat(jb): impl "apply" button --- core/edit/streamDiffLines.ts | 3 +- core/protocol/ideWebview.ts | 7 +- extensions/intellij/.run/Prompt Logs.run.xml | 17 +++ extensions/intellij/.run/Run Continue.run.xml | 2 +- .../continue/Diffs.kt | 15 +- .../continue/IdeProtocolClient.kt | 98 ++++++++++++- .../vscode/src/extension/VsCodeMessenger.ts | 25 ++-- .../components/markdown/CodeBlockToolbar.tsx | 133 +++++++++--------- 8 files changed, 199 insertions(+), 101 deletions(-) create mode 100644 extensions/intellij/.run/Prompt Logs.run.xml diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index cad33b3a2..dbab5841c 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -60,7 +60,7 @@ export async function* streamDiffLines( language: string | undefined, onlyOneInsertion?: boolean, ): AsyncGenerator { - Telemetry.capture( + void Telemetry.capture( "inlineEdit", { model: llm.model, @@ -94,7 +94,6 @@ export async function* streamDiffLines( ); const inept = modelIsInept(llm.model); - const options: LLMFullCompletionOptions = {}; const completion = typeof prompt === "string" ? llm.streamComplete(prompt, { raw: true }) diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 3b357b679..b155470a3 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -15,7 +15,12 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { }, ]; openUrl: [string, void]; - applyToCurrentFile: [{ text: string; streamId: string }, void]; + // We pass the `curSelectedModel` because we currently cannot access the + // default model title in the GUI from JB + applyToCurrentFile: [ + { text: string; streamId: string; curSelectedModelTitle: string }, + void, + ]; showTutorial: [undefined, void]; showFile: [{ filepath: string }, void]; openConfigJson: [undefined, void]; diff --git a/extensions/intellij/.run/Prompt Logs.run.xml b/extensions/intellij/.run/Prompt Logs.run.xml new file mode 100644 index 000000000..48c8392d3 --- /dev/null +++ b/extensions/intellij/.run/Prompt Logs.run.xml @@ -0,0 +1,17 @@ + + + + \ No newline at end of file diff --git a/extensions/intellij/.run/Run Continue.run.xml b/extensions/intellij/.run/Run Continue.run.xml index cc705773b..927201c59 100644 --- a/extensions/intellij/.run/Run Continue.run.xml +++ b/extensions/intellij/.run/Run Continue.run.xml @@ -3,7 +3,7 @@ - + \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt index 196af8e87..d7e912499 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt @@ -6,8 +6,6 @@ import com.intellij.diff.DiffContentFactory import com.intellij.diff.DiffManager import com.intellij.diff.DiffRequestPanel import com.intellij.diff.contents.DiffContent -import com.intellij.diff.contents.DocumentContent -import com.intellij.diff.requests.DiffRequest import com.intellij.diff.requests.SimpleDiffRequest import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction @@ -18,7 +16,6 @@ import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.LocalFileSystem -import com.intellij.ui.content.ContentFactory import java.awt.Toolkit import java.io.File import java.nio.file.Paths @@ -51,10 +48,9 @@ interface DiffInfo { class DiffManager(private val project: Project) : DumbAware { - private val diffContentFactory = DiffContentFactory.getInstance() - // Mapping from file2 to relevant info private val diffInfoMap: MutableMap = mutableMapOf() + private var lastFile2: String? = null fun showDiff(filepath: String, replacement: String, stepIndex: Int) { val diffDir = getDiffDirectory() @@ -68,7 +64,7 @@ class DiffManager(private val project: Project) : DumbAware { openDiffWindow(filepath, file.path, stepIndex) } - fun cleanUpFile(file2: String) { + private fun cleanUpFile(file2: String) { diffInfoMap[file2]?.dialog?.close(0) diffInfoMap.remove(file2) File(file2).delete() @@ -77,7 +73,6 @@ class DiffManager(private val project: Project) : DumbAware { } } - private var lastFile2: String? = null fun acceptDiff(file2: String?) { val file = (file2 ?: lastFile2) ?: return @@ -128,7 +123,7 @@ class DiffManager(private val project: Project) : DumbAware { // Create a SimpleDiffRequest and populate it with the DiffContents and titles val diffRequest = SimpleDiffRequest("Continue Diff", content1, content2, "Old", "New") - + // Get a DiffRequestPanel from the DiffManager and set the DiffRequest to it val diffInfo = diffInfoMap[file2] @@ -176,10 +171,10 @@ class DiffManager(private val project: Project) : DumbAware { } override fun createActions(): Array { - val okAction = getOKAction() + val okAction = okAction okAction.putValue(Action.NAME, "Accept (${getAltKeyLabel()} ⇧ Y)") - val cancelAction = getCancelAction() + val cancelAction = cancelAction cancelAction.putValue(Action.NAME, "Reject (${getAltKeyLabel()} ⇧ N)") return arrayOf(okAction, cancelAction) 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 2b07229ae..ad0b89e00 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 @@ -5,6 +5,8 @@ import com.github.continuedev.continueintellijextension.auth.ContinueAuthService import com.github.continuedev.continueintellijextension.constants.getConfigJsPath import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath +import com.github.continuedev.continueintellijextension.editor.DiffStreamHandler +import com.github.continuedev.continueintellijextension.editor.DiffStreamService import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.google.gson.Gson @@ -16,9 +18,9 @@ import com.intellij.execution.util.ExecUtil import com.intellij.ide.plugins.PluginManager import com.intellij.ide.plugins.PluginManagerCore import com.intellij.lang.annotation.HighlightSeverity -import com.intellij.notification.NotificationType import com.intellij.notification.NotificationAction import com.intellij.notification.NotificationGroupManager +import com.intellij.notification.NotificationType import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.ApplicationManager @@ -34,6 +36,7 @@ import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.util.IconLoader +import com.intellij.openapi.util.TextRange import com.intellij.openapi.vfs.* import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.psi.PsiDocumentManager @@ -48,6 +51,7 @@ import java.nio.charset.Charset import java.nio.file.Paths import java.util.* + fun uuid(): String { return UUID.randomUUID().toString() } @@ -550,7 +554,6 @@ class IdeProtocolClient( } "openFile" -> { - setFileOpen((data as Map)["path"] as String) respond(null) } @@ -619,7 +622,73 @@ class IdeProtocolClient( } } - "applyToFile" -> { + "applyToCurrentFile" -> { + val msg = data as Map; + val text = msg["text"] as String + val curSelectedModelTitle = msg["curSelectedModelTitle"] as String + + val config = readConfigJson() + var llm = getModelByRole(config, "applyCodeBlock") + + if (llm == null) { + val models = (config as? Map<*, *>)?.get("models") as? List> + llm = models?.find { model -> model["title"] == curSelectedModelTitle } as Map + + if (llm == null) { + showToast("error", "Model '$curSelectedModelTitle' not found in config.") + respond(null) + return@launch + } + } + + val llmTitle = (llm as? Map<*, *>)?.get("title") as? String ?: "" + + val prompt = + "The following code was suggested as an edit:\n```\n${text}\n```\nPlease apply it to the previous code." + + val editor = FileEditorManager.getInstance(project).selectedTextEditor + + if (editor == null) { + showToast("error", "No active editor to apply edits to") + respond(null) + return@launch + } + + 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), + {}, {}) + + val diffStreamService = project.service() + diffStreamService.register(diffStreamHandler, editor) + + diffStreamHandler.streamDiffLinesToEditor( + prompt, prefix, highlighted, suffix, llmTitle + ) + + respond(null) } "getGitHubAuthToken" -> { @@ -692,11 +761,11 @@ class IdeProtocolClient( ) } - fun uniqueId(): String { + private fun uniqueId(): String { return getMachineUniqueID() } - suspend fun getBranch(dir: String): String = withContext(Dispatchers.IO) { + private suspend fun getBranch(dir: String): String = withContext(Dispatchers.IO) { try { val builder = ProcessBuilder("git", "rev-parse", "--abbrev-ref", "HEAD") builder.directory(File(dir)) @@ -715,7 +784,7 @@ class IdeProtocolClient( data class IndexTag(val directory: String, val branch: String, val artifactId: String) - suspend fun getTags(artifactId: String): List { + private suspend fun getTags(artifactId: String): List { val workspaceDirs = workspaceDirectories() // Collect branches concurrently using Kotlin coroutines @@ -731,7 +800,7 @@ class IdeProtocolClient( } } - fun readFile(filepath: String): String { + private fun readFile(filepath: String): String { try { val content = ApplicationManager.getApplication().runReadAction { val virtualFile = LocalFileSystem.getInstance().findFileByPath(filepath) @@ -982,4 +1051,19 @@ class IdeProtocolClient( command.setWorkDirectory(project.basePath) return ExecUtil.execAndGetOutput(command).stdout ?: "" } + + private fun getModelByRole( + config: Any, + role: Any + ): Any? { + val experimental = (config as? Map<*, *>)?.get("experimental") as? Map<*, *> + val roleTitle = (experimental?.get("modelRoles") as? Map<*, *>)?.get(role) as? String ?: return null + + val models = (config as? Map<*, *>)?.get("models") as? List<*> + val matchingModel = models?.find { model -> + (model as? Map<*, *>)?.get("title") == roleTitle + } + + return matchingModel + } } \ No newline at end of file diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index cd4e36a99..524b61801 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -35,6 +35,7 @@ import { VsCodeWebviewProtocol } from "../webviewProtocol"; type TODO = any; type ToIdeOrWebviewFromCoreProtocol = ToIdeFromCoreProtocol & ToWebviewFromCoreProtocol; + export class VsCodeMessenger { onWebview( messageType: T, @@ -149,7 +150,7 @@ export class VsCodeMessenger { await vscode.commands.executeCommand("continue.rejectDiff", filepath); }); - this.onWebview("applyToCurrentFile", async (msg) => { + this.onWebview("applyToCurrentFile", async ({ data }) => { // Get active text editor const editor = vscode.window.activeTextEditor; if (!editor) { @@ -164,16 +165,11 @@ export class VsCodeMessenger { let llm = getModelByRole(config, "applyCodeBlock"); if (!llm) { - const defaultModelTitle = await this.webviewProtocol.request( - "getDefaultModelTitle", - undefined, - ); - - llm = config.models.find((model) => model.title === defaultModelTitle); + llm = config.models.find((model) => model.title === data.curSelectedModelTitle); if (!llm) { vscode.window.showErrorMessage( - `Model ${defaultModelTitle} not found in config.`, + `Model ${data.curSelectedModelTitle} not found in config.`, ); return; } @@ -184,20 +180,20 @@ export class VsCodeMessenger { // Generate the diff and pass through diff manager const [instant, diffLines] = await applyCodeBlock( editor.document.getText(), - msg.data.text, + data.text, getBasename(editor.document.fileName), llm, fastLlm, ); const verticalDiffManager = await this.verticalDiffManagerPromise; if (instant) { - verticalDiffManager.streamDiffLines( + await verticalDiffManager.streamDiffLines( diffLines, instant, - msg.data.streamId, + data.streamId, ); } else { - const prompt = `The following code was suggested as an edit:\n\`\`\`\n${msg.data.text}\n\`\`\`\nPlease apply it to the previous code.`; + const prompt = `The following code was suggested as an edit:\n\`\`\`\n${data.text}\n\`\`\`\nPlease apply it to the previous code.`; const fullEditorRange = new vscode.Range( 0, 0, @@ -207,10 +203,11 @@ export class VsCodeMessenger { const rangeToApplyTo = editor.selection.isEmpty ? fullEditorRange : editor.selection; - verticalDiffManager.streamEdit( + + await verticalDiffManager.streamEdit( prompt, llm.title, - msg.data.streamId, + data.streamId, undefined, undefined, rangeToApplyTo, diff --git a/gui/src/components/markdown/CodeBlockToolbar.tsx b/gui/src/components/markdown/CodeBlockToolbar.tsx index c2049d7b4..b5380e26d 100644 --- a/gui/src/components/markdown/CodeBlockToolbar.tsx +++ b/gui/src/components/markdown/CodeBlockToolbar.tsx @@ -29,6 +29,7 @@ import ButtonWithTooltip from "../ButtonWithTooltip"; import FileIcon from "../FileIcon"; import { CopyButton as CopyButtonHeader } from "./CopyButton"; import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip"; +import { defaultModelSelector } from "../../redux/selectors/modelSelectors"; const ToolbarDiv = styled.div` display: flex; @@ -127,6 +128,7 @@ function getTerminalCommand(text: string): string { function CodeBlockToolBar(props: CodeBlockToolBarProps) { const ideMessenger = useContext(IdeMessengerContext); const dispatch = useDispatch(); + const defaultModel = useSelector(defaultModelSelector); const isTerminal = isTerminalCodeBlock(props.language, props.text); const [isCopied, setIsCopied] = useState(false); const [isApplying, setIsApplying] = useState(false); @@ -148,6 +150,7 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { "applyCodeFromChat", async () => { await ideMessenger.request("applyToCurrentFile", { + curSelectedModelTitle: defaultModel.title, text: props.text, streamId: streamIdRef.current, }); @@ -157,24 +160,25 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { !props.isNextCodeBlock, ); - function onClickCopy() { + async function onClickCopy() { if (isJetBrains()) { - ideMessenger.request("copyText", { text: props.text }); + await ideMessenger.request("copyText", { text: props.text }); } else { - navigator.clipboard.writeText(props.text); + await navigator.clipboard.writeText(props.text); } setIsCopied(true); setTimeout(() => setIsCopied(false), 2000); } - function onClickApply() { + async function onClickApply() { if (isApplying) return; if (isTerminal) { - ideMessenger.ide.runCommand(getTerminalCommand(props.text)); + await ideMessenger.ide.runCommand(getTerminalCommand(props.text)); } else { ideMessenger.post("applyToCurrentFile", { + curSelectedModelTitle: defaultModel.title, text: props.text, streamId: streamIdRef.current, }); @@ -214,7 +218,9 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { ); } - if (!props.filepath) { + // Currently we only use the "old" apply logic in JetBrains. This check can be removed once + // we implement the "new" lazy apply logic. + if (!props.filepath || isJetBrains()) { return ( @@ -284,69 +290,64 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { - {!isJetBrains() && ( -
- {applyState === "closed" ? ( - + {applyState === "closed" ? ( + +
-
- - Apply -
- - ) : applyState === "done" ? ( - <> - - -
- Reject -
-
- - - -
- Accept -
-
- - ) : ( -
- - - - + + Apply
- )} -
- )} +
+ ) : applyState === "done" ? ( + <> + + +
+ Reject +
+
+ + + +
+ Accept +
+
+ + ) : ( +
+ + + + +
+ )} +
);