Add fix, explain, and improve commands to the ProtoBus (#5574)

* Add fix, explain, and improve commands to Cline

- Rename AddToClineRequest to CommandContext for reusability
- Implement fixWithCline, explainWithCline, and improveWithCline commands
- Extract common command utilities to commandUtils.ts
- Move file mention logic to mentions module
- Update command registration and handlers in extension.ts

* Update src/core/controller/commands/addToCline.ts

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

* Update src/extension.ts

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
This commit is contained in:
Sarah Fortuneandellipsis-dev[bot] authored and GitHub committed 2025-08-15 02:21:40 +01:00
1 parent fbc517c9e5
commit b44d3c8793
9 files changed
+207 -214

No files matched your search

+6 -3
View File
@@ -11,13 +11,16 @@ option java_multiple_files = true;
// intended to be called by the IDE directly instead of through the webview,
// because they are triggered by interactions in the IDE.
service CommandsService {
rpc addToCline(AddToClineRequest) returns (Empty);
rpc addToCline(CommandContext) returns (Empty);
rpc fixWithCline(CommandContext) returns (Empty);
rpc explainWithCline(CommandContext) returns (Empty);
rpc improveWithCline(CommandContext) returns (Empty);
}
message AddToClineRequest {
message CommandContext {
// The absolute path of the current file.
optional string file_path = 1;
// The selected source code.
// The selected source text.
optional string selected_text = 2;
// The language identifier for the current file.
optional string language = 3;
+27 -8
View File
@@ -1,14 +1,33 @@
import { Controller } from "../index"
import { AddToClineRequest, Empty } from "@/shared/proto/index.cline"
import { CommandContext, Empty } from "@/shared/proto/index.cline"
import { telemetryService } from "@/services/posthog/PostHogClientProvider"
import { getFileMentionFromPath } from "@/core/mentions"
import { singleFileDiagnosticsToProblemsString } from "@/integrations/diagnostics"
import { WebviewProvider } from "@/core/webview"
import { sendAddToInputEventToClient } from "../ui/subscribeToAddToInput"
export async function addToCline(controller: Controller, request: AddToClineRequest): Promise<Empty> {
await controller.addSelectedCodeToChat(
request.selectedText || "",
request.filePath || "",
request.language || "",
request.diagnostics,
)
// 'Add to Cline' context menu in editor and code action
// Inserts the selected code into the chat.
export async function addToCline(controller: Controller, request: CommandContext): Promise<Empty> {
if (!request.selectedText) {
return {}
}
const filePath = request.filePath || ""
const fileMention = await getFileMentionFromPath(filePath)
let input = `${fileMention}\n\`\`\`\n${request.selectedText}\n\`\`\``
if (request.diagnostics.length) {
const problemsString = await singleFileDiagnosticsToProblemsString(filePath, request.diagnostics)
input += `\nProblems:\n${problemsString}`
}
const lastActiveWebview = WebviewProvider.getLastActiveInstance()
if (lastActiveWebview) {
await sendAddToInputEventToClient(lastActiveWebview.getClientId(), input)
}
console.log("addToCline", request.selectedText, filePath, request.language)
telemetryService.captureButtonClick("codeAction_addToChat", controller.task?.ulid)
return {}
@@ -0,0 +1,23 @@
import { Controller } from "../index"
import { CommandContext, Empty } from "@/shared/proto/index.cline"
import { telemetryService } from "@/services/posthog/PostHogClientProvider"
import { HostProvider } from "@/hosts/host-provider"
import { ShowMessageType } from "@/shared/proto/index.host"
import { getFileMentionFromPath } from "@/core/mentions"
export async function explainWithCline(controller: Controller, request: CommandContext): Promise<Empty> {
if (!request.selectedText || !request.selectedText.trim()) {
HostProvider.window.showMessage({
type: ShowMessageType.INFORMATION,
message: "Please select some code to explain.",
})
return {}
}
const fileMention = await getFileMentionFromPath(request.filePath || "")
const prompt = `Explain the following code from ${fileMention}:
\`\`\`${request.language}\n${request.selectedText}\n\`\`\``
await controller.initTask(prompt)
telemetryService.captureButtonClick("codeAction_explainCode", controller.task?.ulid)
return {}
}
@@ -0,0 +1,20 @@
import { Controller } from "../index"
import { CommandContext, Empty } from "@/shared/proto/index.cline"
import { telemetryService } from "@/services/posthog/PostHogClientProvider"
import { getFileMentionFromPath } from "@/core/mentions"
import { singleFileDiagnosticsToProblemsString } from "@/integrations/diagnostics"
export async function fixWithCline(controller: Controller, request: CommandContext): Promise<Empty> {
const filePath = request.filePath || ""
const fileMention = await getFileMentionFromPath(filePath)
const problemsString = await singleFileDiagnosticsToProblemsString(filePath, request.diagnostics)
await controller.initTask(
`Fix the following code in ${fileMention}
\`\`\`\n${request.selectedText}\n\`\`\`\n\nProblems:\n${problemsString}`,
)
console.log("fixWithCline", request.selectedText, request.filePath, request.language, problemsString)
telemetryService.captureButtonClick("codeAction_fixWithCline", controller.task?.ulid)
return {}
}
@@ -0,0 +1,25 @@
import { Controller } from "../index"
import { CommandContext, Empty } from "@/shared/proto/index.cline"
import { telemetryService } from "@/services/posthog/PostHogClientProvider"
import { HostProvider } from "@/hosts/host-provider"
import { ShowMessageType } from "@/shared/proto/index.host"
import { getFileMentionFromPath } from "@/core/mentions"
export async function improveWithCline(controller: Controller, request: CommandContext): Promise<Empty> {
if (!request.selectedText || !request.selectedText.trim()) {
HostProvider.window.showMessage({
type: ShowMessageType.INFORMATION,
message: "Please select some code to improve.",
})
return {}
}
const fileMention = await getFileMentionFromPath(request.filePath || "")
const prompt = `Improve the following code from ${fileMention} (e.g., suggest refactorings, optimizations, or better practices):
\`\`\`${request.language}\n${request.selectedText}\n\`\`\``
await controller.initTask(prompt)
telemetryService.captureButtonClick("codeAction_improveCode", controller.task?.ulid)
return {}
}
-86
View File
@@ -22,7 +22,6 @@ import { UserInfo } from "@shared/UserInfo"
import { fileExistsAtPath } from "@utils/fs"
import axios from "axios"
import fs from "fs/promises"
import { setTimeout as setTimeoutPromise } from "node:timers/promises"
import pWaitFor from "p-wait-for"
import * as path from "path"
import * as vscode from "vscode"
@@ -31,10 +30,6 @@ import { ensureMcpServersDirectoryExists, ensureSettingsDirectoryExists, GlobalF
import { Task } from "../task"
import { sendMcpMarketplaceCatalogEvent } from "./mcp/subscribeToMcpMarketplaceCatalog"
import { sendStateUpdate } from "./state/subscribeToState"
import { sendAddToInputEvent, sendAddToInputEventToClient } from "./ui/subscribeToAddToInput"
import { WebviewProvider } from "../webview"
import { Diagnostic, FileDiagnostics } from "@/shared/proto/index.cline"
import { diagnosticsToProblemsString, singleFileDiagnosticsToProblemsString } from "@/integrations/diagnostics"
/*
https://github.com/microsoft/vscode-webview-ui-toolkit-samples/blob/main/default/weather-webview/src/providers/WeatherViewProvider.ts
@@ -514,87 +509,6 @@ export class Controller {
return undefined
}
// Context menus and code actions
async getFileMentionFromPath(filePath: string) {
const cwd = await getCwd()
if (!cwd) {
return "@/" + filePath
}
const relativePath = path.relative(cwd, filePath)
return "@/" + relativePath
}
// 'Add to Cline' context menu in editor and code action
async addSelectedCodeToChat(code: string, filePath: string, languageId: string, diagnostics: Diagnostic[]) {
// Post message to webview with the selected code
const fileMention = await this.getFileMentionFromPath(filePath)
let input = `${fileMention}\n\`\`\`\n${code}\n\`\`\``
if (diagnostics.length) {
const problemsString = singleFileDiagnosticsToProblemsString(filePath, diagnostics)
input += `\nProblems:\n${problemsString}`
}
const lastActiveWebview = WebviewProvider.getLastActiveInstance()
if (lastActiveWebview) {
await sendAddToInputEventToClient(lastActiveWebview.getClientId(), input)
}
console.log("addSelectedCodeToChat", code, filePath, languageId)
}
// 'Add to Cline' context menu in Terminal
async addSelectedTerminalOutputToChat(output: string, terminalName: string) {
// Ensure the sidebar view is visible
await vscode.commands.executeCommand("claude-dev.SidebarProvider.focus")
await setTimeoutPromise(100)
await sendAddToInputEvent(`Terminal output:\n\`\`\`\n${output}\n\`\`\``)
console.log("addSelectedTerminalOutputToChat", output, terminalName)
}
// 'Fix with Cline' in code actions
async fixWithCline(code: string, filePath: string, languageId: string, diagnostics: vscode.Diagnostic[]) {
// Ensure the sidebar view is visible
await vscode.commands.executeCommand("claude-dev.SidebarProvider.focus")
await setTimeoutPromise(100)
const fileMention = await this.getFileMentionFromPath(filePath)
const problemsString = this.convertDiagnosticsToProblemsString(diagnostics)
await this.initTask(`Fix the following code in ${fileMention}\n\`\`\`\n${code}\n\`\`\`\n\nProblems:\n${problemsString}`)
console.log("fixWithCline", code, filePath, languageId, diagnostics, problemsString)
}
convertDiagnosticsToProblemsString(diagnostics: vscode.Diagnostic[]) {
let problemsString = ""
for (const diagnostic of diagnostics) {
let label: string
switch (diagnostic.severity) {
case vscode.DiagnosticSeverity.Error:
label = "Error"
break
case vscode.DiagnosticSeverity.Warning:
label = "Warning"
break
case vscode.DiagnosticSeverity.Information:
label = "Information"
break
case vscode.DiagnosticSeverity.Hint:
label = "Hint"
break
default:
label = "Diagnostic"
}
const line = diagnostic.range.start.line + 1 // VSCode lines are 0-indexed
const source = diagnostic.source ? `${diagnostic.source} ` : ""
problemsString += `\n- [${source}${label}] Line ${line}: ${diagnostic.message}`
}
problemsString = problemsString.trim()
return problemsString
}
// Task history
async getTaskWithId(id: string): Promise<{
+9
View File
@@ -44,6 +44,15 @@ export async function openMention(mention?: string): Promise<void> {
}
}
export async function getFileMentionFromPath(filePath: string) {
const cwd = await getCwd()
if (!cwd) {
return "@/" + filePath
}
const relativePath = path.relative(cwd, filePath)
return "@/" + relativePath
}
export async function parseMentions(
text: string,
cwd: string,
+33 -117
View File
@@ -5,7 +5,6 @@ import { DIFF_VIEW_URI_SCHEME } from "@hosts/vscode/VscodeDiffViewProvider"
import { WebviewProviderType as WebviewProviderTypeEnum } from "@shared/proto/cline/ui"
import assert from "node:assert"
import { setTimeout as setTimeoutPromise } from "node:timers/promises"
import pWaitFor from "p-wait-for"
import * as vscode from "vscode"
import { sendAccountButtonClickedEvent } from "./core/controller/ui/subscribeToAccountButtonClicked"
import { sendChatButtonClickedEvent } from "./core/controller/ui/subscribeToChatButtonClicked"
@@ -24,7 +23,13 @@ import { vscodeHostBridgeClient } from "@/hosts/vscode/hostbridge/client/host-gr
import { readTextFromClipboard, writeTextToClipboard } from "@/utils/env"
import type { ExtensionContext } from "vscode"
import { initialize, tearDown } from "./common"
import { addToCline } from "./core/controller/commands/addToCline"
import { explainWithCline } from "./core/controller/commands/explainWithCline"
import { fixWithCline } from "./core/controller/commands/fixWithCline"
import { improveWithCline } from "./core/controller/commands/improveWithCline"
import { sendAddToInputEvent } from "./core/controller/ui/subscribeToAddToInput"
import { sendFocusChatInputEvent } from "./core/controller/ui/subscribeToFocusChatInput"
import { focusChatInput, getContextForCommand } from "./hosts/vscode/commandUtils"
import { VscodeDiffViewProvider } from "./hosts/vscode/VscodeDiffViewProvider"
import { VscodeWebviewProvider } from "./hosts/vscode/VscodeWebviewProvider"
import { GitCommitGenerator } from "./integrations/git/commit-message-generator"
@@ -32,10 +37,6 @@ import { AuthService } from "./services/auth/AuthService"
import { telemetryService } from "./services/posthog/PostHogClientProvider"
import { SharedUriHandler } from "./services/uri/SharedUriHandler"
import { ShowMessageType } from "./shared/proto/host/window"
import { AuthHandler } from "./hosts/external/AuthHandler"
import { addToCline } from "./core/controller/commands/addToCline"
import { FileDiagnostics } from "./shared/proto/index.cline"
import { convertToFileDiagnostics, convertVscodeDiagnostics } from "./hosts/vscode/hostbridge/workspace/getDiagnostics"
/*
Built using https://github.com/microsoft/vscode-webview-ui-toolkit
@@ -240,44 +241,6 @@ export async function activate(context: vscode.ExtensionContext) {
})
}
context.subscriptions.push(
vscode.commands.registerCommand(
"cline.addToChat",
async (range?: vscode.Range, vscodeDiagnostics?: vscode.Diagnostic[]) => {
await vscode.commands.executeCommand("cline.focusChatInput") // Ensure Cline is visible and input focused
const activeWebview = WebviewProvider.getLastActiveInstance()
await pWaitFor(() => !!activeWebview)
const clientId = activeWebview?.getClientId()
if (!activeWebview || !clientId) {
return
}
const editor = vscode.window.activeTextEditor
if (!editor) {
return
}
await sendFocusChatInputEvent(clientId)
// Use provided range if available, otherwise use current selection
// (vscode command passes an argument in the first param by default, so we need to ensure it's a Range object)
const textRange = range instanceof vscode.Range ? range : editor.selection
const selectedText = editor.document.getText(textRange)
if (!selectedText) {
return
}
// Get the file path, language ID and diagnostics.
const filePath = editor.document.uri.fsPath
const language = editor.document.languageId
const diagnostics = convertVscodeDiagnostics(vscodeDiagnostics || [])
await addToCline(activeWebview.controller, { filePath, selectedText, language, diagnostics })
},
),
)
context.subscriptions.push(
vscode.commands.registerCommand("cline.addTerminalOutputToChat", async () => {
const terminal = vscode.window.activeTerminal
@@ -302,24 +265,12 @@ export async function activate(context: vscode.ExtensionContext) {
// No terminal content was copied (either nothing selected or some error)
return
}
// Ensure the sidebar view is visible
await focusChatInput()
// [Optional] Any additional logic to process multi-line content can remain here
// For example:
/*
const lines = terminalContents.split("\n")
const lastLine = lines.pop()?.trim()
if (lastLine) {
let i = lines.length - 1
while (i >= 0 && !lines[i].trim().startsWith(lastLine)) {
i--
}
terminalContents = lines.slice(Math.max(i, 0)).join("\n")
}
*/
await sendAddToInputEvent(`Terminal output:\n\`\`\`\n${terminalContents}\n\`\`\``)
// Send to sidebar provider
const visibleWebview = WebviewProvider.getVisibleInstance()
await visibleWebview?.controller.addSelectedTerminalOutputToChat(terminalContents, terminal.name)
console.log("addSelectedTerminalOutputToChat", terminalContents, terminal.name)
} catch (error) {
// Ensure clipboard is restored even if an error occurs
await writeTextToClipboard(tempCopyBuffer)
@@ -332,10 +283,6 @@ export async function activate(context: vscode.ExtensionContext) {
}),
)
const CONTEXT_LINES_TO_EXPAND = 3
const START_OF_LINE_CHAR_INDEX = 0
const LINE_COUNT_ADJUSTMENT_FOR_ZERO_INDEXING = 1
// Register code action provider
context.subscriptions.push(
vscode.languages.registerCodeActionsProvider(
@@ -348,6 +295,10 @@ export async function activate(context: vscode.ExtensionContext) {
range: vscode.Range,
context: vscode.CodeActionContext,
): vscode.CodeAction[] {
const CONTEXT_LINES_TO_EXPAND = 3
const START_OF_LINE_CHAR_INDEX = 0
const LINE_COUNT_ADJUSTMENT_FOR_ZERO_INDEXING = 1
const actions: vscode.CodeAction[] = []
const editor = vscode.window.activeTextEditor // Get active editor for selection check
@@ -430,76 +381,41 @@ export async function activate(context: vscode.ExtensionContext) {
),
)
// Register the command handler
// Register the command handlers
context.subscriptions.push(
vscode.commands.registerCommand("cline.addToChat", async (range?: vscode.Range, diagnostics?: vscode.Diagnostic[]) => {
const context = await getContextForCommand(range, diagnostics)
if (!context) {
return
}
await addToCline(context.controller, context.commandContext)
}),
)
context.subscriptions.push(
vscode.commands.registerCommand("cline.fixWithCline", async (range: vscode.Range, diagnostics: vscode.Diagnostic[]) => {
// Add this line to focus the chat input first
await vscode.commands.executeCommand("cline.focusChatInput")
// Wait for a webview instance to become available after focusing
await pWaitFor(() => !!WebviewProvider.getLastActiveInstance())
const editor = vscode.window.activeTextEditor
if (!editor) {
const context = await getContextForCommand(range, diagnostics)
if (!context) {
return
}
const selectedText = editor.document.getText(range)
const filePath = editor.document.uri.fsPath
const languageId = editor.document.languageId
// Send to last active instance with diagnostics
const activeWebview = WebviewProvider.getLastActiveInstance()
await activeWebview?.controller.fixWithCline(selectedText, filePath, languageId, diagnostics)
telemetryService.captureButtonClick("codeAction_fixWithCline", activeWebview?.controller.task?.ulid)
await fixWithCline(context.controller, context.commandContext)
}),
)
context.subscriptions.push(
vscode.commands.registerCommand("cline.explainCode", async (range: vscode.Range) => {
await vscode.commands.executeCommand("cline.focusChatInput") // Ensure Cline is visible and input focused
await pWaitFor(() => !!WebviewProvider.getLastActiveInstance())
const editor = vscode.window.activeTextEditor
if (!editor) {
const context = await getContextForCommand(range)
if (!context) {
return
}
const selectedText = editor.document.getText(range)
if (!selectedText.trim()) {
HostProvider.window.showMessage({
type: ShowMessageType.INFORMATION,
message: "Please select some code to explain.",
})
return
}
const filePath = editor.document.uri.fsPath
const activeWebview = WebviewProvider.getLastActiveInstance()
const fileMention = activeWebview?.controller.getFileMentionFromPath(filePath) || filePath
const prompt = `Explain the following code from ${fileMention}:\n\`\`\`${editor.document.languageId}\n${selectedText}\n\`\`\``
await activeWebview?.controller.initTask(prompt)
telemetryService.captureButtonClick("codeAction_explainCode", activeWebview?.controller.task?.ulid)
await explainWithCline(context.controller, context.commandContext)
}),
)
context.subscriptions.push(
vscode.commands.registerCommand("cline.improveCode", async (range: vscode.Range) => {
await vscode.commands.executeCommand("cline.focusChatInput") // Ensure Cline is visible and input focused
await pWaitFor(() => !!WebviewProvider.getLastActiveInstance())
const editor = vscode.window.activeTextEditor
if (!editor) {
const context = await getContextForCommand(range)
if (!context) {
return
}
const selectedText = editor.document.getText(range)
if (!selectedText.trim()) {
HostProvider.window.showMessage({
type: ShowMessageType.INFORMATION,
message: "Please select some code to improve.",
})
return
}
const filePath = editor.document.uri.fsPath
const activeWebview = WebviewProvider.getLastActiveInstance()
const fileMention = activeWebview?.controller.getFileMentionFromPath(filePath) || filePath
const prompt = `Improve the following code from ${fileMention} (e.g., suggest refactorings, optimizations, or better practices):\n\`\`\`${editor.document.languageId}\n${selectedText}\n\`\`\``
await activeWebview?.controller.initTask(prompt)
telemetryService.captureButtonClick("codeAction_improveCode", activeWebview?.controller.task?.ulid)
await improveWithCline(context.controller, context.commandContext)
}),
)
+64
View File
@@ -0,0 +1,64 @@
import { CommandContext } from "@/shared/proto/index.cline"
import pWaitFor from "p-wait-for"
import * as vscode from "vscode"
import { Controller } from "../../core/controller"
import { WebviewProvider } from "../../core/webview"
import { convertVscodeDiagnostics } from "./hostbridge/workspace/getDiagnostics"
/**
* Gets the context needed for VSCode commands that interact with the editor
* @param range Optional range to use instead of current selection
* @param vscodeDiagnostics Optional diagnostics to include
* @returns Context object with controller, selected text, file info, and problems
*/
export async function getContextForCommand(
range?: vscode.Range,
vscodeDiagnostics?: vscode.Diagnostic[],
): Promise<
| undefined
| {
controller: Controller
commandContext: CommandContext
}
> {
const activeWebview = await focusChatInput()
if (!activeWebview) {
return
}
// Use the controller from the last active instance
const controller = activeWebview.controller
const editor = vscode.window.activeTextEditor
if (!editor) {
return
}
// Use provided range if available, otherwise use current selection
// (vscode command passes an argument in the first param by default, so we need to ensure it's a Range object)
const textRange = range instanceof vscode.Range ? range : editor.selection
const selectedText = editor.document.getText(textRange)
const filePath = editor.document.uri.fsPath
const language = editor.document.languageId
const diagnostics = convertVscodeDiagnostics(vscodeDiagnostics || [])
const commandContext: CommandContext = {
selectedText,
filePath,
diagnostics,
language,
}
return { controller, commandContext }
}
export async function focusChatInput(): Promise<WebviewProvider | undefined> {
await vscode.commands.executeCommand("cline.focusChatInput")
// Wait for a webview instance to become available after focusing
await pWaitFor(() => !!WebviewProvider.getLastActiveInstance())
const activeWebview = WebviewProvider.getLastActiveInstance()
if (!activeWebview) {
console.error("No active webview to receive command")
return
}
return activeWebview
}