Merge branch 'main' of https://github.com/continuedev/continue into dallin/theme-colors-framework

This commit is contained in:
Dallin Romney 2025-05-21 17:45:12 -07:00
commit e89e420d2c
25 changed files with 921 additions and 1094 deletions

View file

@ -93,6 +93,7 @@
"p-limit": "^6.1.0",
"partial-json": "^0.1.7",
"pg": "^8.11.3",
"plist": "^3.1.0",
"posthog-node": "^3.6.3",
"puppeteer": "^22.4.0",
"puppeteer-chromium-resolver": "^23.0.0",
@ -129,6 +130,7 @@
"@types/mustache": "^4.2.5",
"@types/node-fetch": "^2.6.11",
"@types/pg": "^8.11.6",
"@types/plist": "^3.0.5",
"@types/request": "^2.48.12",
"@types/tar": "^6.1.13",
"@types/uuid": "^9.0.7",

View file

@ -53,16 +53,10 @@ function getContentsForNewBlock(blockType: BlockType): ConfigYaml {
configYaml.mcpServers = [
{
name: "New MCP server",
type: "stdio",
command: "npx",
args: ["-y", "<your-mcp-server>"],
env: {},
},
{
name: "New MCP server",
type: "sse",
url: "https://example.org/sse"
},
];
break;
}

View file

@ -1,107 +0,0 @@
import { MCPServer } from "@continuedev/config-yaml";
import { convertYamlMcpToContinueMcp } from "./loadYaml";
describe("MCP Server Configuration Tests", () => {
test("should convert stdio MCP server correctly", () => {
const stdioServer: MCPServer = {
name: "Test Stdio Server",
type: "stdio",
command: "uvx",
args: ["mcp-server-sqlite", "--db-path", "/test.db"],
env: { TEST_ENV: "value" },
connectionTimeout: 5000
};
const result = convertYamlMcpToContinueMcp(stdioServer);
expect(result).toEqual({
transport: {
type: "stdio",
command: "uvx",
args: ["mcp-server-sqlite", "--db-path", "/test.db"],
env: { TEST_ENV: "value" }
},
timeout: 5000
});
});
test("should convert SSE MCP server correctly", () => {
const sseServer: MCPServer = {
name: "Test SSE Server",
type: "sse",
url: "http://localhost:8150/cosmos/mcp/v1/sse",
connectionTimeout: 3000
};
const result = convertYamlMcpToContinueMcp(sseServer);
expect(result).toEqual({
transport: {
type: "sse",
url: "http://localhost:8150/cosmos/mcp/v1/sse"
},
timeout: 3000
});
});
test("should convert WebSocket MCP server correctly", () => {
const wsServer: MCPServer = {
name: "Test WebSocket Server",
type: "websocket",
url: "ws://localhost:8150/cosmos/mcp/v1/ws",
connectionTimeout: 10000
};
const result = convertYamlMcpToContinueMcp(wsServer);
expect(result).toEqual({
transport: {
type: "websocket",
url: "ws://localhost:8150/cosmos/mcp/v1/ws"
},
timeout: 10000
});
});
test("should handle legacy MCP server format for backward compatibility", () => {
// Test with old format that doesn't have a type field
const legacyServer = {
name: "Legacy Server",
command: "old-command",
args: ["--legacy"],
connectionTimeout: 2000
} as any;
const result = convertYamlMcpToContinueMcp(legacyServer);
expect(result).toEqual({
transport: {
type: "stdio",
command: "old-command",
args: ["--legacy"],
env: undefined
},
timeout: 2000
});
});
test("should handle missing optional fields", () => {
const minimalServer: MCPServer = {
name: "Minimal Server",
type: "stdio",
command: "minimal"
};
const result = convertYamlMcpToContinueMcp(minimalServer);
expect(result).toEqual({
transport: {
type: "stdio",
command: "minimal",
args: [],
env: undefined
},
timeout: undefined
});
});
});

View file

@ -62,42 +62,17 @@ function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
}
}
export function convertYamlMcpToContinueMcp(
function convertYamlMcpToContinueMcp(
server: MCPServer,
): ExperimentalMCPOptions {
const transportConfig = (() => {
switch (server.type) {
case "stdio":
return {
type: "stdio" as const,
command: server.command,
args: server.args ?? [],
env: server.env,
};
case "sse":
return {
type: "sse" as const,
url: server.url,
};
case "websocket":
return {
type: "websocket" as const,
url: server.url,
};
default:
// Default to stdio for backward compatibility
return {
type: "stdio" as const,
command: (server as any).command,
args: (server as any).args ?? [],
env: (server as any).env,
};
}
})();
return {
transport: transportConfig,
timeout: server.connectionTimeout
transport: {
type: "stdio",
command: server.command,
args: server.args ?? [],
env: server.env,
},
timeout: server.connectionTimeout,
};
}
@ -269,7 +244,7 @@ async function configYamlToContinueConfig(options: {
config.mcpServers?.forEach((mcpServer) => {
const mcpArgVariables =
(mcpServer.type === "stdio" ? mcpServer.args?.filter((arg) => TEMPLATE_VAR_REGEX.test(arg)) : []) ?? [];
mcpServer.args?.filter((arg) => TEMPLATE_VAR_REGEX.test(arg)) ?? [];
if (mcpArgVariables.length === 0) {
return;
@ -481,6 +456,7 @@ async function configYamlToContinueConfig(options: {
id: server.name,
name: server.name,
transport: {
type: "stdio",
args: [],
...server,
},

View file

@ -155,6 +155,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
expect(supportsFn("pixtral-12b-2409")).toBe(true);
expect(supportsFn("pixtral-large-latest")).toBe(true);
expect(supportsFn("open-mistral-nemo")).toBe(true);
expect(supportsFn("devstral-latest")).toBe(true);
});
it("should return false for other unsupported models", () => {
@ -170,6 +171,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
expect(supportsFn("CODESTRAL-LATEST")).toBe(true);
expect(supportsFn("MINISTRAL-8B-LATEST")).toBe(true);
expect(supportsFn("PIXTRAL-12B-2409")).toBe(true);
expect(supportsFn("DEVSTRAL-LATEST")).toBe(true);
});
});
@ -192,6 +194,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
expect(supportsFn("aya-expanse")).toBe(true);
expect(supportsFn("firefunction-v2")).toBe(true);
expect(supportsFn("mistral-7b")).toBe(true);
expect(supportsFn("devstral-24b")).toBe(true);
});
it("should return false for explicitly unsupported models", () => {

View file

@ -88,6 +88,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<
return (
!model.toLowerCase().includes("mamba") &&
[
"devstral",
"codestral",
"mistral-large",
"mistral-small",
@ -136,6 +137,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<
"aya-expanse",
"firefunction-v2",
"mistral",
"devstral",
].some((part) => modelName.toLowerCase().includes(part))
) {
return true;

View file

@ -20,15 +20,11 @@ To set up your own MCP server, read the [MCP quickstart](https://modelcontextpro
```yaml title="config.yaml"
mcpServers:
- name: My MCP Server
type: stdio
command: uvx
args:
- mcp-server-sqlite
- --db-path
- /Users/NAME/test.db
- name: My MCP Server with SSE
type: sse
url: "https://example.com/mcp-server/sse"
```
</TabItem>
<TabItem value="json" label="JSON">
@ -42,12 +38,6 @@ To set up your own MCP server, read the [MCP quickstart](https://modelcontextpro
"command": "uvx",
"args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"]
}
},
{
"transport": {
"type": "sse",
"url": "https://example.com/mcp-server/sse"
}
}
]
}

View file

@ -379,33 +379,21 @@ prompts, context, and tool use. Continue supports any MCP server with the MCP co
**Properties:**
- `name` (**required**): The name of the MCP server.
- `type"` (**required**): The type of the MCP server. Can be "stdio", "sse", or "websocket".
**Stdio type**
- `command` (**required**): The command used to start the server.
- `args`: An optional array of arguments for the command.
- `env`: An optional map of environment variables for the server process.
- `connectionTimeout`: An optional connection timeout number to the server in milliseconds.
**SSE or Websocket type**
- `url` (**required**): The URL of the MCP server.
**Example:**
```yaml title="config.yaml"
mcpServers:
- name: My MCP Server with stdio
type: stdio
- name: My MCP Server
command: uvx
args:
- mcp-server-sqlite
- --db-path
- /Users/NAME/test.db
- name: My MCP Server with SSE
type: sse
url: "https://example.com/mcp-server/sse"
```
### `data`

View file

@ -11,15 +11,19 @@ import org.jetbrains.annotations.NotNull
class ContinueActionPromote : ActionPromoter {
override fun promote(@NotNull actions: List<AnAction>, @NotNull context: DataContext): List<AnAction>? {
if (actions.none { it is AcceptAutocompleteAction }) {
return null
} else {
// For autocomplete actions
if (actions.any { it is AcceptAutocompleteAction }) {
val settings = ServiceManager.getService(ContinueExtensionSettings::class.java)
if (!settings.continueState.showIDECompletionSideBySide) {
return null;
if (settings.continueState.showIDECompletionSideBySide) {
return actions.filterIsInstance<AcceptAutocompleteAction>()
}
return actions.filterIsInstance<AcceptAutocompleteAction>()
}
val rejectDiffActions = actions.filterIsInstance<RejectDiffAction>()
if (rejectDiffActions.isNotEmpty()) {
return rejectDiffActions
}
return null
}
}

View file

@ -1,25 +1,12 @@
package com.github.continuedev.continueintellijextension.actions
import com.github.continuedev.continueintellijextension.editor.DiffStreamService
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.service
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.ToolWindowManager
fun getPluginService(project: Project?): ContinuePluginService? {
if (project == null) {
return null
}
return ServiceManager.getService(
project,
ContinuePluginService::class.java
)
}
class AcceptDiffAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
@ -29,7 +16,7 @@ class AcceptDiffAction : AnAction() {
private fun acceptHorizontalDiff(e: AnActionEvent) {
val continuePluginService = getPluginService(e.project) ?: return
continuePluginService?.diffManager?.acceptDiff(null)
continuePluginService.diffManager?.acceptDiff(null)
}
private fun acceptVerticalDiff(e: AnActionEvent) {
@ -61,28 +48,6 @@ class RejectDiffAction : AnAction() {
}
}
fun getContinuePluginService(project: Project?): ContinuePluginService? {
if (project != null) {
val toolWindowManager = ToolWindowManager.getInstance(project)
val toolWindow = toolWindowManager.getToolWindow("Continue")
if (toolWindow != null) {
if (!toolWindow.isVisible) {
toolWindow.activate(null)
}
}
}
return getPluginService(project)
}
fun focusContinueInput(project: Project?) {
val continuePluginService = getContinuePluginService(project) ?: return
continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
continuePluginService.sendToWebview("focusContinueInputWithoutClear", null)
continuePluginService.ideProtocolClient?.sendHighlightedCode()
}
class FocusContinueInputWithoutClearAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
@ -134,8 +99,11 @@ class OpenLogsAction : AnAction() {
if (logFile.exists()) {
val virtualFile = com.intellij.openapi.vfs.LocalFileSystem.getInstance().findFileByIoFile(logFile)
if (virtualFile != null) {
com.intellij.openapi.fileEditor.FileEditorManager.getInstance(project).openFile(virtualFile, true)
FileEditorManager.getInstance(project).openFile(virtualFile, true)
}
}
}
}

View file

@ -0,0 +1,39 @@
package com.github.continuedev.continueintellijextension.actions
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.ToolWindowManager
fun getContinuePluginService(project: Project?): ContinuePluginService? {
if (project != null) {
val toolWindowManager = ToolWindowManager.getInstance(project)
val toolWindow = toolWindowManager.getToolWindow("Continue")
if (toolWindow != null) {
if (!toolWindow.isVisible) {
toolWindow.activate(null)
}
}
}
return getPluginService(project)
}
fun focusContinueInput(project: Project?) {
val continuePluginService = getContinuePluginService(project) ?: return
continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
continuePluginService.sendToWebview("focusContinueInputWithoutClear", null)
continuePluginService.ideProtocolClient?.sendHighlightedCode()
}
fun getPluginService(project: Project?): ContinuePluginService? {
if (project == null) {
return null
}
return ServiceManager.getService(
project,
ContinuePluginService::class.java
)
}

View file

@ -1,29 +0,0 @@
package com.github.continuedev.continueintellijextension.autocomplete
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.components.service
class AutocompleteActionGroup : DefaultActionGroup() {
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.EDT
}
override fun update(e: AnActionEvent) {
super.update(e)
removeAll()
val continueSettingsService = service<ContinueExtensionSettings>()
if (continueSettingsService.continueState.enableTabAutocomplete) {
addAll(
DisableTabAutocompleteAction(),
)
} else {
addAll(
EnableTabAutocompleteAction(),
)
}
}
}

View file

@ -121,10 +121,10 @@ class ApplyToFileHandler(
val prompt = buildApplyPrompt()
// Extract the code ranges (highlighted or full document)
val (prefix, highlighted, suffix) = editorUtils.extractCodeRanges()
val (prefix, highlighted, suffix) = editorUtils.getHighlightedRangeTriplet()
// Get the line range for the diff stream
val rif = editorUtils.getHighlightedCode()
val rif = editorUtils.getHighlightedRIF()
val startLine = rif?.range?.start?.line ?: 0
val endLine = rif?.range?.end?.line ?: (editorUtils.getLineCount() - 1)

View file

@ -502,7 +502,7 @@ class IdeProtocolClient(
fun sendHighlightedCode(edit: Boolean = false) {
val editor = EditorUtils.getEditor(project)
val rif = editor?.getHighlightedCode() ?: return
val rif = editor?.getHighlightedRIF() ?: return
continuePluginService.sendToWebview(
"highlightedCode",

View file

@ -337,6 +337,5 @@ class DiffStreamHandler(
private fun setClosed() {
sendUpdate(ApplyStateStatus.CLOSED)
resetState()
onClose()
}
}

View file

@ -1,7 +1,5 @@
package com.github.continuedev.continueintellijextension.editor
import com.github.continuedev.continueintellijextension.Position
import com.github.continuedev.continueintellijextension.Range
import com.github.continuedev.continueintellijextension.utils.toUriOrNull
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.WriteCommandAction
@ -72,28 +70,33 @@ class EditorUtils(val editor: Editor) {
editor.scrollingModel.scrollTo(logicalPosition, ScrollType.CENTER_UP)
}
/**
* Remove the selected range in a thread-safe manner
*/
fun removeSelection() {
ApplicationManager.getApplication().invokeLater {
editor.selectionModel.removeSelection()
}
}
/**
* Extracts code ranges from the editor: (prefix, highlighted/selected text, suffix)
*/
fun extractCodeRanges(): Triple<String, String, String> {
val rif = getHighlightedCode()
fun getHighlightedRangeTriplet(): Triple<String, String, String> {
val rif = getHighlightedRIF()
return if (rif == null) {
// If no highlight, use the whole document as highlighted
Triple("", editor.document.text, "")
} else {
// Use the RangeInFileWithContents to get absolute offsets
val startOffset = rif.getStartOffset(editor.document)
val endOffset = rif.getEndOffset(editor.document)
val (startOffset, endOffset) = rif.offsets
val prefix = editor.document.getText(TextRange(0, startOffset))
val highlighted = rif.contents
val suffix = editor.document.getText(TextRange(endOffset, editor.document.textLength))
// Remove the selection after processing
ApplicationManager.getApplication().invokeLater {
editor.selectionModel.removeSelection()
}
removeSelection()
Triple(prefix, highlighted, suffix)
}
@ -103,7 +106,7 @@ class EditorUtils(val editor: Editor) {
* Gets the selected code from the current editor.
* Returns null if there is no selection.
*/
fun getHighlightedCode(): RangeInFileWithContents? {
fun getHighlightedRIF(): RangeInFileWithContents? {
return ApplicationManager.getApplication().runReadAction<RangeInFileWithContents?> {
val virtualFile =
FileDocumentManager.getInstance().getFile(editor.document) ?: return@runReadAction null

View file

@ -1,337 +1,11 @@
package com.github.continuedev.continueintellijextension.editor
import com.github.continuedev.continueintellijextension.`continue`.GetTheme
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
import com.github.continuedev.continueintellijextension.utils.getMetaKeyLabel
import com.github.continuedev.continueintellijextension.utils.getShiftKeyLabel
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.TextRange
import com.intellij.ui.JBColor
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import java.awt.*
import java.awt.event.*
import java.awt.geom.AffineTransform
import java.awt.geom.Path2D
import java.awt.geom.RoundRectangle2D
import javax.swing.*
import javax.swing.event.DocumentEvent
import javax.swing.event.DocumentListener
import javax.swing.event.ListDataListener
import javax.swing.plaf.basic.BasicComboBoxUI
import kotlin.math.max
import net.miginfocom.swing.MigLayout
import org.jdesktop.swingx.JXPanel
import org.jdesktop.swingx.JXTextArea
const val MAIN_FONT_SIZE = 13
const val DOWN_ARROW = " ▾"
fun makeTextArea(): JTextArea {
val textArea =
CustomTextArea(1, 40).apply {
lineWrap = true
wrapStyleWord = true
isOpaque = false
background = GetTheme().getSecondaryDark()
maximumSize = Dimension(400, Short.MAX_VALUE.toInt())
margin = JBUI.insets(6, 8, 2, 4)
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE)
preferredSize = Dimension(400, 75)
}
textArea.putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
return textArea
}
fun makePanel(
project: Project,
customPanelRef: Ref<CustomPanel>,
textArea: JTextArea,
inlayRef: Ref<Disposable>,
comboBoxRef: Ref<JComboBox<String>>,
leftInset: Int,
modelTitles: List<String>,
onEnter: () -> Unit,
onCancel: () -> Unit,
onAccept: () -> Unit,
onReject: () -> Unit
): JPanel {
val topPanel =
ShadowPanel(MigLayout("wrap 1, insets 2 $leftInset 2 2, gap 0!")).apply {
background = JBColor(0x20888888, 0x20888888)
isOpaque = false
}
val panel =
CustomPanel(
MigLayout("wrap 1, insets 4 10 0 2, gap 0!, fillx"),
project,
modelTitles,
comboBoxRef,
onEnter,
onCancel,
onAccept,
onReject,
textArea
)
.apply {
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
background = defaultBackground
add(textArea, "grow, gap 0!, height 100%")
putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
preferredSize = textArea.preferredSize
setup()
}
customPanelRef.set(panel)
textArea.addComponentListener(
object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent?) {
panel.revalidate()
panel.repaint()
}
})
topPanel.add(panel, "grow, gap 0!")
return topPanel
}
fun openInlineEdit(project: Project?, editor: Editor) {
if (project == null) return
// Don't open in terminal
if (EditorUtils(editor).isTerminal()) {
return
}
val manager = EditorComponentInlaysManager.from(editor, true)
// Get list of model titles
val continuePluginService = project.service<ContinuePluginService>()
val modelTitles = mutableListOf<String>()
continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
val modelsByRole =
response.castNestedOrNull<Map<String, Any>>("content", "result", "config", "modelsByRole") ?: return@request
val role = if (modelsByRole.containsKey("edit")) "edit" else "chat"
modelsByRole.castNestedOrNull<List<*>>(role)
?.mapNotNull { it.castNestedOrNull<String>("title") }
?.let(modelTitles::addAll)
}
// This is a hacky way to not complicate getting model titles with coroutines
// 1500 feels like way upper limit of "would be weird if panel showed up after that long"
// And should always allow enough time to load config
val maxWaitTime = 1500
val startTime = System.currentTimeMillis()
while (modelTitles.isEmpty() && System.currentTimeMillis() - startTime < maxWaitTime) {
Thread.sleep(20)
}
// Get highlighted range
val selectionModel = editor.selectionModel
val startOffset = selectionModel.selectionStart
val endOffset = selectionModel.selectionEnd
val startLineNumber = editor.document.getLineNumber(startOffset)
var endLineNumber = editor.document.getLineNumber(endOffset)
// Doesn't seem to be any built-in methods to check for a line selection that contains trailing
// newlines.
// The only case this matters is when a user double-clicks to highlight a full line. Without this
// check.
// the highlighted range will continue to the following line.
val isSingleLineSelection =
endLineNumber > startLineNumber &&
endLineNumber < editor.document.lineCount &&
editor.document.getLineStartOffset(endLineNumber) == endOffset
if (isSingleLineSelection) {
endLineNumber--
}
val prefix = editor.document.getText(TextRange(0, startOffset))
val highlighted = editor.document.getText(TextRange(startOffset, endOffset))
val suffix = editor.document.getText(TextRange(endOffset, editor.document.textLength))
val lineNumber = if (startLineNumber == 0) 0 else max(0, startLineNumber - 1)
// Un-highlight the selected text
selectionModel.removeSelection()
// Get indentation width in pixels
val indentationLineNum = if (startLineNumber == 0) 0 else lineNumber + 1
val lineStart = editor.document.getLineStartOffset(indentationLineNum)
val lineEnd = editor.document.getLineEndOffset(indentationLineNum)
val text = editor.document.getText(TextRange(lineStart, lineEnd))
val indentation = text.takeWhile { it == ' ' }.length
val charWidth =
editor.contentComponent
.getFontMetrics(editor.colorsScheme.getFont(EditorFontType.PLAIN))
.charWidth(' ')
val leftInset = indentation * charWidth * 2 / 3
val inlayRef = Ref<Disposable>()
val customPanelRef = Ref<CustomPanel>()
// Create text area, attach key listener
val textArea = makeTextArea()
// Create diff stream handler
val diffStreamHandler =
DiffStreamHandler(
project,
editor,
startLineNumber,
endLineNumber,
{
inlayRef.get()?.dispose()
},
{
textArea.document.insertString(textArea.caretPosition, ", ", null)
textArea.requestFocus()
customPanelRef.get().finish()
},
null,
null
)
val diffStreamService = project.service<DiffStreamService>()
diffStreamService.register(diffStreamHandler, editor)
val comboBoxRef = Ref<JComboBox<String>>()
fun onEnter() {
val selectedModelStrippedOfCaret = (comboBoxRef.get().selectedItem as String).removeSuffix(DOWN_ARROW)
customPanelRef.get().enter()
diffStreamHandler.streamDiffLinesToEditor(
textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret, true
)
}
val panel =
makePanel(
project,
customPanelRef,
textArea,
inlayRef,
comboBoxRef,
leftInset,
modelTitles,
{ onEnter() },
{
diffStreamService.reject(editor)
selectionModel.setSelection(startOffset, endOffset)
},
{
diffStreamService.accept(editor)
inlayRef.get().dispose()
},
{
diffStreamService.reject(editor)
inlayRef.get().dispose()
})
val inlay = manager.insert(startLineNumber, panel, true)
panel.revalidate()
inlayRef.set(inlay)
val viewport = (editor as? EditorImpl)?.scrollPane?.viewport
viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED))
// Add key listener to text area
textArea.addKeyListener(
object : KeyAdapter() {
override fun keyTyped(e: KeyEvent) {
if (customPanelRef.get().isFinished) {
customPanelRef.get().setup()
}
}
override fun keyPressed(e: KeyEvent) {
when (e.keyCode) {
KeyEvent.VK_ESCAPE -> {
diffStreamService.reject(editor)
selectionModel.setSelection(startOffset, endOffset)
}
KeyEvent.VK_ENTER -> {
when (e.modifiersEx) {
KeyEvent.SHIFT_DOWN_MASK -> {
textArea.document.insertString(textArea.caretPosition, "\n", null)
}
0 -> {
onEnter()
e.consume()
}
}
}
}
}
// We need this because backspace/delete is not registering properly on keyPressed for an
// unknown reason
override fun keyReleased(e: KeyEvent) {
if (e.keyCode == KeyEvent.VK_BACK_SPACE || e.keyCode == KeyEvent.VK_DELETE) {
if (customPanelRef.get().isFinished) {
customPanelRef.get().setup()
}
}
}
})
// Listen for changes to textarea line count
textArea.document.addDocumentListener(
object : DocumentListener {
private var lastNumLines: Int = 0
private fun updateSize() {
val numLines = textArea.text.lines().size
if (numLines != lastNumLines) {
lastNumLines = numLines
viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED))
}
}
override fun insertUpdate(e: DocumentEvent?) {
updateSize()
}
override fun removeUpdate(e: DocumentEvent?) {
updateSize()
}
override fun changedUpdate(e: DocumentEvent?) {
updateSize()
}
})
textArea.requestFocus()
}
/**
* Adapted from
* https://github.com/cursive-ide/component-inlay-example/blob/master/src/main/kotlin/inlays/InlineEditAction.kt
*/
class InlineEditAction : AnAction(), DumbAware {
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = true
@ -347,417 +21,4 @@ class InlineEditAction : AnAction(), DumbAware {
val project = e.getData(PlatformDataKeys.PROJECT) ?: return
openInlineEdit(project, editor)
}
}
class CustomPanel(
layout: MigLayout,
project: Project,
modelTitles: List<String>,
comboBoxRef: Ref<JComboBox<String>>,
private val onEnter: () -> Unit,
private val onCancel: () -> Unit,
private val onAccept: () -> Unit,
private val onReject: () -> Unit,
private val textArea: JTextArea
) : JPanel(layout) {
private val shadowSize = 5
private val cornerRadius = 8
private val shadowColor = Color(0, 0, 0, 40) // Lighter shadow
private val borderColor = Color(128, 128, 128, 128)
private val borderThickness = 1
private val triangleSize = 6
private val rightMargin = 3.0
private val closeButton: JComponent = createCloseButton()
private val originalTextColor: Color = textArea.foreground
private val greyTextColor: Color = Color(128, 128, 128, 200)
var isFinished = false
init {
isOpaque = false
add(closeButton, "pos 100%-33 0 -3 3, w 20!, h 20!")
}
private fun createCloseButton(): JComponent {
val closeIcon = IconLoader.getIcon("/icons/close.svg", javaClass)
return JLabel(closeIcon).apply {
background = Color(0, 0, 0, 0)
border = JBUI.Borders.empty(2, 6, 2, 0)
toolTipText = "`esc` to cancel"
isOpaque = false
addMouseListener(
object : MouseAdapter() {
override fun mouseEntered(e: MouseEvent) {
cursor = Cursor(Cursor.HAND_CURSOR)
}
override fun mouseExited(e: MouseEvent) {
cursor = Cursor.getDefaultCursor()
}
override fun mouseClicked(e: MouseEvent) {
onCancel()
}
})
}
}
private val subPanelA: JPanel =
JPanel(MigLayout("insets 0, fillx")).apply {
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
val continueSettingsService = service<ContinueExtensionSettings>()
val dropdown =
JComboBox(modelTitles.toTypedArray()).apply {
setUI(TransparentArrowButtonUI())
isEditable = true
background = defaultBackground
foreground = Color(128, 128, 128, 200)
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 12)
border = JBUI.Borders.empty(8)
isOpaque = false
isEditable = false
cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
preferredSize = Dimension(200, 30)
renderer = object : DefaultListCellRenderer() {
override fun getListCellRendererComponent(
list: JList<*>?,
value: Any?,
index: Int,
isSelected: Boolean,
cellHasFocus: Boolean
): Component {
val component =
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus)
if (component is JLabel) {
component.border = JBUI.Borders.empty(4, 6)
}
return component
}
}.apply {
horizontalAlignment = SwingConstants.LEFT
}
selectedIndex =
if (itemCount == 0) -1 else continueSettingsService.continueState.lastSelectedInlineEditModel?.let {
if (modelTitles.isEmpty()) -1
else {
val index = modelTitles.indexOf(it)
if (index != -1) index else 0
}
} ?: 0
addActionListener {
continueSettingsService.continueState.lastSelectedInlineEditModel =
(selectedItem as String).removeSuffix(DOWN_ARROW)
}
}
comboBoxRef.set(dropdown)
val rightButton =
CustomButton("⏎ Enter") { onEnter() }
.apply {
background = globalScheme.defaultForeground
foreground = globalScheme.defaultBackground
border = JBUI.Borders.empty(2, 6)
}
val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply {
isOpaque = false
add(rightButton, "align right")
}
border = JBUI.Borders.empty(0, 0, 16, 12)
isOpaque = false
add(dropdown, "align left")
add(rightPanel, "align right")
cursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)
}
private val subPanelB: JPanel =
JPanel(BorderLayout()).apply {
isOpaque = false
val progressBar = JProgressBar().apply { isIndeterminate = true }
add(progressBar, BorderLayout.CENTER)
border = JBUI.Borders.empty(0, 0, 16, 12)
}
private val subPanelC: JPanel =
JPanel(MigLayout("insets 0, fillx")).apply {
val leftLabel =
JLabel("Type to re-prompt").apply {
foreground = Color(156, 163, 175) // text-gray-400
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
border = JBUI.Borders.emptyLeft(4)
}
val leftButton =
CustomButton("Reject All (${getMetaKeyLabel()}${getShiftKeyLabel()}⌫)") { onReject() }
.apply {
background = JBColor(0x30FF0000, 0x30FF0000)
}
val rightButton =
CustomButton("Accept All (${getMetaKeyLabel()}${getShiftKeyLabel()}⏎)") { onAccept() }
.apply {
background = JBColor(0x3000FF00, 0x3000FF00)
}
val rightPanel =
JPanel(MigLayout("insets 0, fillx")).apply {
isOpaque = false
add(leftButton, "align right")
add(rightButton, "align right")
border = JBUI.Borders.empty()
}
add(leftLabel, "align left")
add(rightPanel, "align right")
border = JBUI.Borders.empty(0, 0, 16, 12)
isOpaque = false
}
fun setup() {
remove(subPanelB)
remove(subPanelC)
add(subPanelA, "grow, gap 0!")
isFinished = false
revalidate()
repaint()
textArea.foreground = originalTextColor
}
fun enter() {
remove(subPanelA)
remove(subPanelC)
add(subPanelB, "grow, gap 0!")
revalidate()
repaint()
}
fun finish() {
remove(subPanelB)
add(subPanelC, "grow, gap 0!")
revalidate()
repaint()
isFinished = true
textArea.foreground = greyTextColor
}
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
val g2 = g as Graphics2D
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
val w = width - shadowSize
val h = height - shadowSize
// Create the shape for the tooltip/triangle
val shape = Path2D.Double()
shape.moveTo(borderThickness / 2.0, cornerRadius.toDouble())
shape.quadTo(
borderThickness / 2.0,
borderThickness / 2.0,
cornerRadius.toDouble(),
borderThickness / 2.0
)
shape.lineTo(w - cornerRadius.toDouble() - rightMargin, borderThickness / 2.0)
shape.quadTo(
w - borderThickness / 2.0 - rightMargin,
borderThickness / 2.0,
w - borderThickness / 2.0 - rightMargin,
cornerRadius.toDouble()
)
shape.lineTo(
w - borderThickness / 2.0 - rightMargin, h - cornerRadius - triangleSize.toDouble()
)
shape.quadTo(
w - borderThickness / 2.0 - rightMargin,
h - triangleSize.toDouble(),
w - cornerRadius.toDouble() - rightMargin,
h - triangleSize.toDouble()
)
shape.lineTo(triangleSize.toDouble(), h - triangleSize.toDouble())
shape.lineTo(borderThickness / 2.0, h.toDouble())
shape.lineTo(borderThickness / 2.0, cornerRadius.toDouble())
// Draw shadow
g2.color = shadowColor
g2.fill(
shape.createTransformedShape(
AffineTransform.getTranslateInstance(shadowSize.toDouble(), shadowSize.toDouble())
)
)
// Draw main shape
g2.color = background
g2.fill(shape)
// Draw border
g2.color = borderColor
g2.stroke = BasicStroke(borderThickness.toFloat())
g2.draw(shape)
}
}
class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) {
private var isHovered = false
init {
isOpaque = false
cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
addMouseListener(
object : MouseAdapter() {
override fun mouseEntered(e: MouseEvent?) {
isHovered = true
repaint()
}
override fun mouseExited(e: MouseEvent?) {
isHovered = false
repaint()
}
override fun mouseClicked(e: MouseEvent?) {
onClick()
}
})
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
border = JBUI.Borders.empty(2, 6)
}
override fun paintComponent(g: Graphics) {
val g2 = g as Graphics2D
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
val cornerRadius = 8
val rect = Rectangle(0, 0, width, height)
val roundRect =
RoundRectangle2D.Float(
rect.x.toFloat(),
rect.y.toFloat(),
rect.width.toFloat(),
rect.height.toFloat(),
cornerRadius.toFloat(),
cornerRadius.toFloat()
)
g2.color = background
g2.fill(roundRect)
g2.color = foreground
g2.drawString(
text,
(width / 2 - g.fontMetrics.stringWidth(text) / 2).toFloat(),
(height / 2 + g.fontMetrics.ascent / 2).toFloat()
)
}
}
class CustomTextArea(rows: Int, columns: Int) : JXTextArea("") {
init {
setRows(rows)
setColumns(columns)
}
override fun paintComponent(g: Graphics) {
// Draw placeholder
if (text.isEmpty()) {
g.color = Color(128, 128, 128, 255)
g.font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE)
g.drawString("Enter instructions...", 8, 20)
}
super.paintComponent(g)
}
}
class ShadowPanel(layout: LayoutManager) : JXPanel(layout) {
override fun getPreferredSize(): Dimension {
val prefSize = super.getPreferredSize()
val insets = getInsets()
prefSize.width += insets.left + insets.right
prefSize.height += insets.top + insets.bottom
return prefSize
}
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
}
}
class TransparentArrowButtonUI : BasicComboBoxUI() {
override fun createArrowButton() =
JButton().apply {
isVisible = false
preferredSize = Dimension(0, 0)
}
override fun getInsets(): Insets {
return JBUI.insetsLeft(6)
}
override fun installUI(c: JComponent?) {
super.installUI(c)
comboBox.isOpaque = false
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
comboBox.background = defaultBackground
// Modify the ComboBoxModel to include the down symbol
val originalModel = comboBox.model
comboBox.model =
object : ComboBoxModel<Any> {
override fun getSize(): Int = originalModel.size
override fun getElementAt(index: Int): Any? = originalModel.getElementAt(index)
override fun setSelectedItem(anItem: Any?) {
originalModel.selectedItem = anItem
}
override fun getSelectedItem(): Any? {
val item = originalModel.selectedItem
return "$item$DOWN_ARROW"
}
override fun addListDataListener(l: ListDataListener?) {
originalModel.addListDataListener(l)
}
override fun removeListDataListener(l: ListDataListener?) {
originalModel.removeListDataListener(l)
}
}
}
override fun paintCurrentValueBackground(g: Graphics, bounds: Rectangle, hasFocus: Boolean) {
// Do nothing to prevent painting the background
}
override fun paintCurrentValue(g: Graphics, bounds: Rectangle, hasFocus: Boolean) {
val renderer = comboBox.renderer
val item = comboBox.selectedItem
if (item != null) {
val c = renderer.getListCellRendererComponent(listBox, item, -1, false, false)
c.font = comboBox.font
c.foreground = Color(156, 163, 175) // text-gray-400
c.background = comboBox.background
if (c is JComponent) {
c.isOpaque = false
}
val currentValuePane = currentValuePane
currentValuePane.paintComponent(
g, c, comboBox, bounds.x, bounds.y, bounds.width, bounds.height, true
)
}
}
}
}

View file

@ -0,0 +1,746 @@
package com.github.continuedev.continueintellijextension.editor
import com.github.continuedev.continueintellijextension.`continue`.GetTheme
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
import com.github.continuedev.continueintellijextension.utils.getMetaKeyLabel
import com.github.continuedev.continueintellijextension.utils.getShiftKeyLabel
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.TextRange
import com.intellij.ui.JBColor
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import java.awt.*
import java.awt.event.*
import java.awt.geom.AffineTransform
import java.awt.geom.Path2D
import java.awt.geom.RoundRectangle2D
import javax.swing.*
import javax.swing.event.DocumentEvent
import javax.swing.event.DocumentListener
import javax.swing.event.ListDataListener
import javax.swing.plaf.basic.BasicComboBoxUI
import kotlin.math.max
import net.miginfocom.swing.MigLayout
import org.jdesktop.swingx.JXPanel
import org.jdesktop.swingx.JXTextArea
const val MAIN_FONT_SIZE = 13
const val DOWN_ARROW = " ▾"
const val MAX_MODEL_WAIT_TIME = 1500
/**
* Fetches and combines available model titles from both "edit" and "chat" roles.
* Edit models are prioritized and appear first in the returned list.
* Handles duplicate models by only including them once (prioritizing edit role).
*
* @param continuePluginService The service used to fetch config information
* @return List of model titles with edit models first, duplicates removed
* @throws No exceptions, but will return empty list if request fails or times out after 1.5 seconds
*/
fun getModelTitles(continuePluginService: ContinuePluginService): List<String> {
val modelTitles = mutableListOf<String>()
continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
val modelsByRole =
response.castNestedOrNull<Map<String, Any>>("content", "result", "config", "modelsByRole") ?: return@request
// Get edit models first
val editModels = modelsByRole.castNestedOrNull<List<*>>("edit")
?.mapNotNull { it.castNestedOrNull<String>("title") } ?: emptyList()
// Then get chat models
val chatModels = modelsByRole.castNestedOrNull<List<*>>("chat")
?.mapNotNull { it.castNestedOrNull<String>("title") } ?: emptyList()
// Add edit models first, then chat models (avoiding duplicates)
modelTitles.addAll(editModels)
modelTitles.addAll(chatModels.filter { it !in editModels })
}
val startTime = System.currentTimeMillis()
while (modelTitles.isEmpty() && System.currentTimeMillis() - startTime < MAX_MODEL_WAIT_TIME) {
Thread.sleep(20)
}
return modelTitles
}
fun makeTextArea(): JTextArea {
val textArea =
CustomTextArea(1, 40).apply {
lineWrap = true
wrapStyleWord = true
isOpaque = false
background = GetTheme().getSecondaryDark()
maximumSize = Dimension(400, Short.MAX_VALUE.toInt())
margin = JBUI.insets(6, 8, 2, 4)
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE)
preferredSize = Dimension(400, 75)
}
textArea.putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
return textArea
}
fun makePanel(
project: Project,
customPanelRef: Ref<CustomPanel>,
textArea: JTextArea,
inlayRef: Ref<Disposable>,
comboBoxRef: Ref<JComboBox<String>>,
leftInset: Int,
modelTitles: List<String>,
onEnter: () -> Unit,
onCancel: () -> Unit,
onAccept: () -> Unit,
onReject: () -> Unit
): JPanel {
val topPanel =
ShadowPanel(MigLayout("wrap 1, insets 2 $leftInset 2 2, gap 0!")).apply {
background = JBColor(0x20888888, 0x20888888)
isOpaque = false
}
val panel =
CustomPanel(
MigLayout("wrap 1, insets 4 10 0 2, gap 0!, fillx"),
project,
modelTitles,
comboBoxRef,
onEnter,
onCancel,
onAccept,
onReject,
textArea
)
.apply {
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
background = defaultBackground
add(textArea, "grow, gap 0!, height 100%")
putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
preferredSize = textArea.preferredSize
setup()
}
customPanelRef.set(panel)
textArea.addComponentListener(
object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent?) {
panel.revalidate()
panel.repaint()
}
})
topPanel.add(panel, "grow, gap 0!")
return topPanel
}
fun openInlineEdit(project: Project?, editor: Editor) {
if (project == null) return
val editorUtils = EditorUtils(editor)
// Don't open in terminal
if (editorUtils.isTerminal()) {
return
}
val manager = EditorComponentInlaysManager.from(editor, true)
val continuePluginService = project.service<ContinuePluginService>()
val modelTitles = getModelTitles(continuePluginService)
val highlightedRIF = editorUtils.getHighlightedRIF() ?: return
val (startLineNumber, endLineNumber) = highlightedRIF.lines
val (highlightedStartOffset, highlightedEndOffset) = highlightedRIF.offsets
val (prefix, highlighted, suffix) = editorUtils.getHighlightedRangeTriplet()
val lineNumber = if (startLineNumber == 0) 0 else max(0, startLineNumber - 1)
editorUtils.removeSelection()
// Get indentation width in pixels
val indentationLineNum = if (startLineNumber == 0) 0 else lineNumber + 1
val lineStart = editor.document.getLineStartOffset(indentationLineNum)
val lineEnd = editor.document.getLineEndOffset(indentationLineNum)
val text = editor.document.getText(TextRange(lineStart, lineEnd))
val indentation = text.takeWhile { it == ' ' }.length
val charWidth =
editor.contentComponent
.getFontMetrics(editor.colorsScheme.getFont(EditorFontType.PLAIN))
.charWidth(' ')
val leftInset = indentation * charWidth * 2 / 3
val inlayRef = Ref<Disposable>()
val customPanelRef = Ref<CustomPanel>()
// Create text area, attach key listener
val textArea = makeTextArea()
// Create diff stream handler
val diffStreamHandler =
DiffStreamHandler(
project,
editor,
startLineNumber,
endLineNumber,
{
inlayRef.get()?.dispose()
},
{
textArea.document.insertString(textArea.caretPosition, ", ", null)
textArea.requestFocus()
customPanelRef.get().finish()
},
null,
null
)
val diffStreamService = project.service<DiffStreamService>()
diffStreamService.register(diffStreamHandler, editor)
val comboBoxRef = Ref<JComboBox<String>>()
fun onEnter() {
val selectedModelStrippedOfCaret = (comboBoxRef.get().selectedItem as String).removeSuffix(DOWN_ARROW)
customPanelRef.get().enter()
diffStreamHandler.streamDiffLinesToEditor(
textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret, true
)
}
val panel =
makePanel(
project,
customPanelRef,
textArea,
inlayRef,
comboBoxRef,
leftInset,
modelTitles,
{ onEnter() },
{
diffStreamService.reject(editor)
editorUtils.editor.selectionModel.setSelection(highlightedStartOffset, highlightedEndOffset)
},
{
diffStreamService.accept(editor)
inlayRef.get().dispose()
},
{
diffStreamService.reject(editor)
inlayRef.get().dispose()
})
val inlay = manager.insert(startLineNumber, panel, true)
panel.revalidate()
inlayRef.set(inlay)
val viewport = (editor as? EditorImpl)?.scrollPane?.viewport
viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED))
// Add key listener to text area
textArea.addKeyListener(
object : KeyAdapter() {
override fun keyTyped(e: KeyEvent) {
if (customPanelRef.get().isFinished) {
customPanelRef.get().setup()
}
}
override fun keyPressed(e: KeyEvent) {
when (e.keyCode) {
KeyEvent.VK_ESCAPE -> {
diffStreamService.reject(editor)
editorUtils.editor.selectionModel.setSelection(
highlightedStartOffset,
highlightedEndOffset
)
}
KeyEvent.VK_ENTER -> {
when (e.modifiersEx) {
KeyEvent.SHIFT_DOWN_MASK -> {
textArea.document.insertString(textArea.caretPosition, "\n", null)
}
0 -> {
onEnter()
e.consume()
}
}
}
}
}
// We need this because backspace/delete is not registering properly on keyPressed for an
// unknown reason
override fun keyReleased(e: KeyEvent) {
if (e.keyCode == KeyEvent.VK_BACK_SPACE || e.keyCode == KeyEvent.VK_DELETE) {
if (customPanelRef.get().isFinished) {
customPanelRef.get().setup()
}
}
}
})
// Listen for changes to textarea line count
textArea.document.addDocumentListener(
object : DocumentListener {
private var lastNumLines: Int = 0
private fun updateSize() {
val numLines = textArea.text.lines().size
if (numLines != lastNumLines) {
lastNumLines = numLines
viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED))
}
}
override fun insertUpdate(e: DocumentEvent?) {
updateSize()
}
override fun removeUpdate(e: DocumentEvent?) {
updateSize()
}
override fun changedUpdate(e: DocumentEvent?) {
updateSize()
}
})
textArea.requestFocus()
}
class CustomPanel(
layout: MigLayout,
project: Project,
modelTitles: List<String>,
comboBoxRef: Ref<JComboBox<String>>,
private val onEnter: () -> Unit,
private val onCancel: () -> Unit,
private val onAccept: () -> Unit,
private val onReject: () -> Unit,
private val textArea: JTextArea
) : JPanel(layout) {
private val shadowSize = 5
private val cornerRadius = 8
private val shadowColor = Color(0, 0, 0, 40) // Lighter shadow
private val borderColor = Color(128, 128, 128, 128)
private val borderThickness = 1
private val triangleSize = 6
private val rightMargin = 3.0
private val closeButton: JComponent = createCloseButton()
private val originalTextColor: Color = textArea.foreground
private val greyTextColor: Color = Color(128, 128, 128, 200)
var isFinished = false
init {
isOpaque = false
add(closeButton, "pos 100%-33 0 -3 3, w 20!, h 20!")
}
private fun createCloseButton(): JComponent {
val closeIcon = IconLoader.getIcon("/icons/close.svg", javaClass)
return JLabel(closeIcon).apply {
background = Color(0, 0, 0, 0)
border = JBUI.Borders.empty(2, 6, 2, 0)
toolTipText = "`esc` to cancel"
isOpaque = false
addMouseListener(
object : MouseAdapter() {
override fun mouseEntered(e: MouseEvent) {
cursor = Cursor(Cursor.HAND_CURSOR)
}
override fun mouseExited(e: MouseEvent) {
cursor = Cursor.getDefaultCursor()
}
override fun mouseClicked(e: MouseEvent) {
onCancel()
}
})
}
}
private val subPanelA: JPanel =
JPanel(MigLayout("insets 0, fillx")).apply {
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
val continueSettingsService = service<ContinueExtensionSettings>()
val dropdown =
JComboBox(modelTitles.toTypedArray()).apply {
setUI(TransparentArrowButtonUI())
isEditable = true
background = defaultBackground
foreground = Color(128, 128, 128, 200)
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 12)
border = JBUI.Borders.empty(8)
isOpaque = false
isEditable = false
cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
preferredSize = Dimension(200, 30)
renderer = object : DefaultListCellRenderer() {
override fun getListCellRendererComponent(
list: JList<*>?,
value: Any?,
index: Int,
isSelected: Boolean,
cellHasFocus: Boolean
): Component {
val component =
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus)
if (component is JLabel) {
component.border = JBUI.Borders.empty(4, 6)
}
return component
}
}.apply {
horizontalAlignment = SwingConstants.LEFT
}
selectedIndex =
if (itemCount == 0) -1 else continueSettingsService.continueState.lastSelectedInlineEditModel?.let {
if (modelTitles.isEmpty()) -1
else {
val index = modelTitles.indexOf(it)
if (index != -1) index else 0
}
} ?: 0
addActionListener {
continueSettingsService.continueState.lastSelectedInlineEditModel =
(selectedItem as String).removeSuffix(DOWN_ARROW)
}
}
comboBoxRef.set(dropdown)
val rightButton =
CustomButton("⏎ Enter") { onEnter() }
.apply {
background = JBColor.namedColor("Button.startBackground")
foreground = JBColor.namedColor("Button.foreground")
border = JBUI.Borders.empty(2, 6)
}
val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply {
isOpaque = false
add(rightButton, "align right")
}
border = JBUI.Borders.empty(0, 0, 16, 12)
isOpaque = false
add(dropdown, "align left")
add(rightPanel, "align right")
cursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)
}
private val subPanelB: JPanel =
JPanel(BorderLayout()).apply {
isOpaque = false
val progressBar = JProgressBar().apply { isIndeterminate = true }
add(progressBar, BorderLayout.CENTER)
border = JBUI.Borders.empty(0, 0, 16, 12)
}
private val subPanelC: JPanel =
JPanel(MigLayout("insets 0, fillx")).apply {
val leftLabel =
JLabel("Type to re-prompt").apply {
foreground = Color(156, 163, 175) // text-gray-400
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
border = JBUI.Borders.emptyLeft(4)
}
val leftButton =
CustomButton("Reject All (${getMetaKeyLabel()}${getShiftKeyLabel()}⌫)") { onReject() }
.apply {
background = Color(0, 0, 0, 0)
foreground = JBColor.foreground()
border = JBUI.Borders.empty(2, 6)
}
val rightButton =
CustomButton("Accept All (${getMetaKeyLabel()}${getShiftKeyLabel()}⏎)") { onAccept() }
.apply {
background = JBColor.namedColor("Button.startBackground")
foreground = JBColor.namedColor("Button.foreground")
border = JBUI.Borders.empty(2, 6)
}
val rightPanel =
JPanel(MigLayout("insets 0, fillx")).apply {
isOpaque = false
add(leftButton, "align right")
add(rightButton, "align right")
border = JBUI.Borders.empty()
}
add(leftLabel, "align left")
add(rightPanel, "align right")
border = JBUI.Borders.empty(0, 0, 16, 12)
isOpaque = false
}
fun setup() {
remove(subPanelB)
remove(subPanelC)
add(subPanelA, "grow, gap 0!")
isFinished = false
revalidate()
repaint()
textArea.foreground = originalTextColor
}
fun enter() {
remove(subPanelA)
remove(subPanelC)
add(subPanelB, "grow, gap 0!")
revalidate()
repaint()
}
fun finish() {
remove(subPanelB)
add(subPanelC, "grow, gap 0!")
revalidate()
repaint()
isFinished = true
textArea.foreground = greyTextColor
}
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
val g2 = g as Graphics2D
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
val w = width - shadowSize
val h = height - shadowSize
// Create the shape for the tooltip/triangle
val shape = Path2D.Double()
shape.moveTo(borderThickness / 2.0, cornerRadius.toDouble())
shape.quadTo(
borderThickness / 2.0,
borderThickness / 2.0,
cornerRadius.toDouble(),
borderThickness / 2.0
)
shape.lineTo(w - cornerRadius.toDouble() - rightMargin, borderThickness / 2.0)
shape.quadTo(
w - borderThickness / 2.0 - rightMargin,
borderThickness / 2.0,
w - borderThickness / 2.0 - rightMargin,
cornerRadius.toDouble()
)
shape.lineTo(
w - borderThickness / 2.0 - rightMargin, h - cornerRadius - triangleSize.toDouble()
)
shape.quadTo(
w - borderThickness / 2.0 - rightMargin,
h - triangleSize.toDouble(),
w - cornerRadius.toDouble() - rightMargin,
h - triangleSize.toDouble()
)
shape.lineTo(triangleSize.toDouble(), h - triangleSize.toDouble())
shape.lineTo(borderThickness / 2.0, h.toDouble())
shape.lineTo(borderThickness / 2.0, cornerRadius.toDouble())
// Draw shadow
g2.color = shadowColor
g2.fill(
shape.createTransformedShape(
AffineTransform.getTranslateInstance(shadowSize.toDouble(), shadowSize.toDouble())
)
)
// Draw main shape
g2.color = background
g2.fill(shape)
// Draw border
g2.color = borderColor
g2.stroke = BasicStroke(borderThickness.toFloat())
g2.draw(shape)
}
}
class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) {
private var isHovered = false
init {
isOpaque = false
cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
addMouseListener(
object : MouseAdapter() {
override fun mouseEntered(e: MouseEvent?) {
isHovered = true
repaint()
}
override fun mouseExited(e: MouseEvent?) {
isHovered = false
repaint()
}
override fun mouseClicked(e: MouseEvent?) {
onClick()
}
})
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
border = JBUI.Borders.empty(2, 6)
}
override fun paintComponent(g: Graphics) {
val g2 = g as Graphics2D
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
val cornerRadius = 8
val rect = Rectangle(0, 0, width, height)
val roundRect =
RoundRectangle2D.Float(
rect.x.toFloat(),
rect.y.toFloat(),
rect.width.toFloat(),
rect.height.toFloat(),
cornerRadius.toFloat(),
cornerRadius.toFloat()
)
g2.color = background
g2.fill(roundRect)
g2.color = foreground
g2.drawString(
text,
(width / 2 - g.fontMetrics.stringWidth(text) / 2).toFloat(),
(height / 2 + g.fontMetrics.ascent / 2).toFloat()
)
}
}
class CustomTextArea(rows: Int, columns: Int) : JXTextArea("") {
init {
setRows(rows)
setColumns(columns)
}
override fun paintComponent(g: Graphics) {
// Draw placeholder
if (text.isEmpty()) {
g.color = Color(128, 128, 128, 255)
g.font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE)
g.drawString("Enter instructions...", 8, 20)
}
super.paintComponent(g)
}
}
class ShadowPanel(layout: LayoutManager) : JXPanel(layout) {
override fun getPreferredSize(): Dimension {
val prefSize = super.getPreferredSize()
val insets = getInsets()
prefSize.width += insets.left + insets.right
prefSize.height += insets.top + insets.bottom
return prefSize
}
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
}
}
class TransparentArrowButtonUI : BasicComboBoxUI() {
override fun createArrowButton() =
JButton().apply {
isVisible = false
preferredSize = Dimension(0, 0)
}
override fun getInsets(): Insets {
return JBUI.insetsLeft(6)
}
override fun installUI(c: JComponent?) {
super.installUI(c)
comboBox.isOpaque = false
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
comboBox.background = defaultBackground
// Modify the ComboBoxModel to include the down symbol
val originalModel = comboBox.model
comboBox.model =
object : ComboBoxModel<Any> {
override fun getSize(): Int = originalModel.size
override fun getElementAt(index: Int): Any? = originalModel.getElementAt(index)
override fun setSelectedItem(anItem: Any?) {
originalModel.selectedItem = anItem
}
override fun getSelectedItem(): Any? {
val item = originalModel.selectedItem
return "$item$DOWN_ARROW"
}
override fun addListDataListener(l: ListDataListener?) {
originalModel.addListDataListener(l)
}
override fun removeListDataListener(l: ListDataListener?) {
originalModel.removeListDataListener(l)
}
}
}
override fun paintCurrentValueBackground(g: Graphics, bounds: Rectangle, hasFocus: Boolean) {
// Do nothing to prevent painting the background
}
override fun paintCurrentValue(g: Graphics, bounds: Rectangle, hasFocus: Boolean) {
val renderer = comboBox.renderer
val item = comboBox.selectedItem
if (item != null) {
val c = renderer.getListCellRendererComponent(listBox, item, -1, false, false)
c.font = comboBox.font
c.foreground = Color(156, 163, 175) // text-gray-400
c.background = comboBox.background
if (c is JComponent) {
c.isOpaque = false
}
val currentValuePane = currentValuePane
currentValuePane.paintComponent(
g, c, comboBox, bounds.x, bounds.y, bounds.width, bounds.height, true
)
}
}
}

View file

@ -12,22 +12,43 @@ import com.intellij.openapi.util.TextRange
class RangeInFileWithContents(
val filepath: String,
val range: Range,
val contents: String
val contents: String,
val document: Document
) {
/**
* Returns the absolute document offset for the start position
* The absolute document offset for the start position
*/
fun getStartOffset(document: Document): Int {
return document.getLineStartOffset(range.start.line) + range.start.character
}
val startOffset: Int
get() = document.getLineStartOffset(range.start.line) + range.start.character
/**
* Returns the absolute document offset for the end position
* The absolute document offset for the end position
*/
fun getEndOffset(document: Document): Int {
return document.getLineStartOffset(range.end.line) + range.end.character
}
val endOffset: Int
get() = document.getLineStartOffset(range.end.line) + range.end.character
/**
* The line number where the highlighted range starts (zero-based)
*/
val startLine: Int
get() = range.start.line
/**
* The line number where the highlighted range ends (zero-based)
* This already accounts for proper line ending calculations.
*/
val endLine: Int
get() = range.end.line
/**
* Both the start and end line numbers of the highlighted range as a pair
*/
val lines: Pair<Int, Int>
get() = Pair(startLine, endLine)
val offsets: Pair<Int, Int>
get() = Pair(startOffset, endOffset)
companion object {
/**
@ -45,6 +66,13 @@ class RangeInFileWithContents(
val startChar = selectionStart - document.getLineStartOffset(startLine)
val endChar = selectionEnd - document.getLineStartOffset(endLine)
// Adjust end line if it's a single line selection with trailing newlines
val adjustedEndLine = if (isSelectionWithTrailingNewline(document, selectionStart, selectionEnd)) {
endLine - 1
} else {
endLine
}
val selectedText = document.getText(
TextRange(selectionStart, selectionEnd)
)
@ -53,10 +81,30 @@ class RangeInFileWithContents(
filepath,
Range(
Position(startLine, startChar),
Position(endLine, endChar)
Position(adjustedEndLine, endChar)
),
selectedText
selectedText,
document
)
}
/**
* Checks if the selection spans to the next line only because of trailing newlines.
* This matters when a user double-clicks to highlight a full line.
*
* @return true if the selection is actually a single line selection with trailing newline
*/
fun isSelectionWithTrailingNewline(
document: Document,
selectionStart: Int,
selectionEnd: Int
): Boolean {
val startLine = document.getLineNumber(selectionStart)
val endLine = document.getLineNumber(selectionEnd)
return endLine > startLine &&
endLine < document.lineCount &&
document.getLineStartOffset(endLine) == selectionEnd
}
}
}

View file

@ -166,7 +166,7 @@ class VerticalDiffBlock(
val rejectBtn =
createButton(
"${getAltKeyLabel()}${getShiftKeyLabel()}N",
JBColor(0x77FF0000, 0x77FF0000)
JBColor(0xFF0000, 0xFF0000)
).apply {
addActionListener {
handleReject()
@ -178,13 +178,14 @@ class VerticalDiffBlock(
createButton(
"${getAltKeyLabel()}${
getShiftKeyLabel()
}Y", JBColor(0x7700BB00, 0x7700BB00)
}Y", JBColor(0x00BB00, 0x00BB00)
).apply {
addActionListener {
handleAccept()
}
}
return Pair(acceptBtn, rejectBtn)
}

View file

@ -78,9 +78,9 @@
class="com.github.continuedev.continueintellijextension.actions.RejectDiffAction"
text="Reject Diff" description="Reject Diff">
<keyboard-shortcut keymap="$default"
first-keystroke="shift ctrl DELETE"/>
first-keystroke="shift ctrl BACK_SPACE"/>
<keyboard-shortcut keymap="Mac OS X"
first-keystroke="shift meta DELETE"/>
first-keystroke="shift meta BACK_SPACE"/>
<override-text place="GoToAction" text="Continue: Reject Diff"/>
</action>

View file

@ -105,7 +105,7 @@
"continue.enableQuickActions": {
"type": "boolean",
"default": false,
"markdownDescription": "Enable the experimental Quick Actions feature. Read our walkthrough to learn about configuration and how to share feedback: [continue.dev › Walkthrough: Quick Actions (experimental)](https://docs.continue.dev/features/quick-actions)"
"markdownDescription": "Enable the experimental Quick Actions feature. Read our walkthrough to learn about configuration and how to share feedback: [continue.dev › Walkthrough: Quick Actions (experimental)](https://docs.continue.dev/customize/deep-dives/vscode-actions#quick-actions)"
},
"continue.enableTabAutocomplete": {
"type": "boolean",

View file

@ -9,7 +9,7 @@ class Calculator {
this.result += number;
return this;
}
subtract(number: number): Calculator {
this.result -= number;
return this;
@ -38,4 +38,4 @@ class Calculator {
}
}
export default Calculator;
export default Calculator;

View file

@ -128,48 +128,14 @@ function convertCustomCommand(
function convertMcp(mcp: any): NonNullable<ConfigYaml["mcpServers"]>[number] {
const { transport } = mcp;
const { type } = transport;
const { command, args, env, server_name } = transport;
// Common properties for all server types
const baseServer: any = {
name: mcp.name,
type: type,
return {
command,
args,
env,
name: server_name || "MCP Server",
};
if (mcp.faviconUrl) {
baseServer.faviconUrl = mcp.faviconUrl
}
if (mcp.connectionTimeout) {
baseServer.connectionTimeout = mcp.connectionTimeout
}
// Type-specific properties
switch (type) {
case "stdio":
const stdioServer = {
...baseServer,
command: transport.command,
};
if (transport.args) {
stdioServer.args = transport.args
}
if (transport.env) {
stdioServer.env = transport.env
}
return stdioServer;
case "sse":
case "websocket":
return {
...baseServer,
url: transport.url
};
default:
throw new Error(`Unknown MCP server type: ${type}`);
}
}
function convertDoc(

View file

@ -9,31 +9,14 @@ export const contextSchema = z.object({
params: z.any().optional(),
});
const mcpServerSchema = z.discriminatedUnion("type", [
z.object({
name: z.string(),
type: z.literal("stdio"),
command: z.string(),
faviconUrl: z.string().optional(),
args: z.array(z.string()).optional(),
env: z.record(z.string()).optional(),
connectionTimeout: z.number().gt(0).optional()
}),
z.object({
name: z.string(),
type: z.literal("sse"),
url: z.string(),
faviconUrl: z.string().optional(),
connectionTimeout: z.number().gt(0).optional()
}),
z.object({
name: z.string(),
type: z.literal("websocket"),
url: z.string(),
faviconUrl: z.string().optional(),
connectionTimeout: z.number().gt(0).optional()
})
]);
const mcpServerSchema = z.object({
name: z.string(),
command: z.string(),
faviconUrl: z.string().optional(),
args: z.array(z.string()).optional(),
env: z.record(z.string()).optional(),
connectionTimeout: z.number().gt(0).optional()
});
export type MCPServer = z.infer<typeof mcpServerSchema>;
@ -78,17 +61,7 @@ export const blockItemWrapperSchema = <T extends z.AnyZodObject>(
export const blockOrSchema = <T extends z.AnyZodObject>(
schema: T,
usesSchema: z.ZodTypeAny = defaultUsesSchema,
isDiscriminatedUnion?: boolean,
) => {
if (isDiscriminatedUnion) {
return z.union([schema, z.object({
uses: usesSchema,
with: z.record(z.string()).optional(),
override: z.any().optional(),
})]);
}
return z.union([schema, blockItemWrapperSchema(schema, usesSchema)]);
};
) => z.union([schema, blockItemWrapperSchema(schema, usesSchema)]);
export const commonMetadataSchema = z.object({
tags: z.string().optional(),
@ -125,7 +98,7 @@ export const configYamlSchema = baseConfigYamlSchema.extend({
.optional(),
context: z.array(blockOrSchema(contextSchema)).optional(),
data: z.array(blockOrSchema(dataSchema)).optional(),
mcpServers: z.array(blockOrSchema(mcpServerSchema as any, defaultUsesSchema, true)).optional(),
mcpServers: z.array(blockOrSchema(mcpServerSchema)).optional(),
rules: z
.array(
z.union([
@ -250,4 +223,4 @@ export const configSchema = z.object({
api_key: z.string().optional(),
});
export type Config = z.infer<typeof configSchema>;
export type Config = z.infer<typeof configSchema>;