From 16f066dcbf04ac9441ca4c5d6a0730181ac04424 Mon Sep 17 00:00:00 2001 From: Bee <68532117+abeatrix@users.noreply.github.com> Date: Fri, 11 Jul 2025 17:29:01 -0700 Subject: [PATCH] Host bridge migration: showErrorMessage, showInformationMessage, showWarningMessage (#4745) * host bridge migration: showErrorMessage & showInformationMessage & showWarningMessage Introduces the `showMessage` host API to the VS Code extension, allowing the host to display informational, warning, and error messages to the user. The changes include: - A new `ShowMessageRequest` and `SelectedResponse` message definition in `proto/host/window.proto` to define the request and response structure for showing messages. - A new file `src/hosts/vscode/window/showMessage.ts` that implements the `showErrorMessage`, `showInformationMessage`, and `showWarningMessage` functions. These functions use the VS Code API to display messages based on the `ShowMessageRequest`. - Replace all current call sites with the new implementations * define the request structure This commit introduces the `showErrorMessage`, `showInformationMessage`, and `showWarningMessage` host APIs to the VS Code extension. These APIs allow the host to display informational, warning, and error messages to the user. The changes include: - Added `ShowErrorMessageRequest`, `ShowInformationMessageRequest`, and `ShowWarningMessageRequest` message definitions in `proto/host/window.proto` to define the request structure for showing messages. - Added new files `src/hosts/vscode/window/showErrorMessage.ts`, `src/hosts/vscode/window/showInformationMessage.ts`, and `src/hosts/vscode/window/showWarningMessage.ts` that implement the corresponding functions. These functions use the VS Code API to display messages based on the provided message and options. * Simplify showMessage functions and use options array The `showErrorMessage`, `showInformationMessage`, and `showWarningMessage` functions in `src/hosts/vscode/window/` have been refactored for simplification. - The functions now directly destructure the `modal`, `detail`, and `items` properties from the input object. - The VS Code API calls now directly pass the `modal` and `detail` options, and use the spread operator to pass the `items.options` array as additional arguments. This removes the need for conditional logic to construct the options object. * wip: apply feedback * Update src/integrations/git/commit-message-generator.ts Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com> * merge conflict --------- Co-authored-by: abeatrix Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com> --- proto/host/window.proto | 25 +++++ src/core/controller/file/createRuleFile.ts | 19 +++- src/core/controller/file/deleteRuleFile.ts | 11 +- src/core/controller/index.ts | 106 ++++++++++++++---- src/core/controller/state/resetState.ts | 31 ++++- .../state/updateDefaultTerminalProfile.ts | 20 +++- .../controller/task/deleteAllTaskHistory.ts | 45 +++++--- .../controller/task/deleteTasksWithIds.ts | 13 ++- src/core/mentions/index.ts | 16 ++- src/core/webview/index.ts | 10 +- src/dev/commands/tasks.ts | 10 +- src/extension.ts | 51 +++++++-- src/hosts/vscode/window/showMessage.ts | 24 ++++ .../git/commit-message-generator.ts | 59 +++++++--- src/integrations/misc/export-markdown.ts | 9 +- src/integrations/misc/open-file.ts | 23 +++- src/integrations/misc/process-files.ts | 30 ++++- src/services/mcp/McpHub.ts | 77 +++++++++---- 18 files changed, 461 insertions(+), 118 deletions(-) create mode 100644 src/hosts/vscode/window/showMessage.ts diff --git a/proto/host/window.proto b/proto/host/window.proto index 19a39686..fe84da3a 100644 --- a/proto/host/window.proto +++ b/proto/host/window.proto @@ -11,6 +11,7 @@ service WindowService { // Opens a text document in the editor and returns editor information. rpc showTextDocument(ShowTextDocumentRequest) returns (TextEditorInfo); rpc showOpenDialogue(ShowOpenDialogueRequest) returns (SelectedResources); + rpc showMessage(ShowMessageRequest) returns (SelectedResponse); } message ShowTextDocumentRequest { @@ -46,3 +47,27 @@ message ShowOpenDialogueFilterOption { message SelectedResources { repeated string paths = 1; } + +enum ShowMessageType { + ERROR = 0; + INFORMATION = 1; + WARNING = 2; +} + +message ShowMessageRequest { + cline.Metadata metadata = 1; + ShowMessageType type = 2; + string message = 3; + optional ShowMessageRequestOptions options = 4; +} + +message ShowMessageRequestOptions { + repeated string items = 1; + optional bool modal = 2; + optional string detail = 3; + +} + +message SelectedResponse { + optional string selected_option = 1; +} \ No newline at end of file diff --git a/src/core/controller/file/createRuleFile.ts b/src/core/controller/file/createRuleFile.ts index 2c204603..db5b41ef 100644 --- a/src/core/controller/file/createRuleFile.ts +++ b/src/core/controller/file/createRuleFile.ts @@ -3,11 +3,12 @@ import { RuleFileRequest, RuleFile } from "@shared/proto/file" import { FileMethodHandler } from "./index" import { refreshClineRulesToggles } from "@core/context/instructions/user-instructions/cline-rules" import { createRuleFile as createRuleFileImpl } from "@core/context/instructions/user-instructions/rule-helpers" -import * as vscode from "vscode" import * as path from "path" import { handleFileServiceRequest } from "./index" import { refreshWorkflowToggles } from "@/core/context/instructions/user-instructions/workflows" import { getCwd, getDesktopDir } from "@/utils/path" +import { getHostBridgeProvider } from "@/hosts/host-providers" +import { ShowMessageRequest, ShowMessageType } from "@/shared/proto/host/window" /** * Creates a rule file in either global or workspace rules directory @@ -42,7 +43,13 @@ export const createRuleFile: FileMethodHandler = async (controller: Controller, const fileTypeName = request.type === "workflow" ? "workflow" : "rule" if (fileExists) { - vscode.window.showWarningMessage(`${fileTypeName} file "${request.filename}" already exists.`) + const message = `${fileTypeName} file "${request.filename}" already exists.` + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.WARNING, + message, + }), + ) // Still open it for editing await handleFileServiceRequest(controller, "openFile", { value: filePath }) } else { @@ -55,8 +62,12 @@ export const createRuleFile: FileMethodHandler = async (controller: Controller, await handleFileServiceRequest(controller, "openFile", { value: filePath }) - vscode.window.showInformationMessage( - `Created new ${request.isGlobal ? "global" : "workspace"} ${fileTypeName} file: ${request.filename}`, + const message = `Created new ${request.isGlobal ? "global" : "workspace"} ${fileTypeName} file: ${request.filename}` + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.INFORMATION, + message, + }), ) } diff --git a/src/core/controller/file/deleteRuleFile.ts b/src/core/controller/file/deleteRuleFile.ts index 9c9b03b8..a482270e 100644 --- a/src/core/controller/file/deleteRuleFile.ts +++ b/src/core/controller/file/deleteRuleFile.ts @@ -1,9 +1,10 @@ import { deleteRuleFile as deleteRuleFileImpl } from "@core/context/instructions/user-instructions/rule-helpers" import { RuleFile, RuleFileRequest } from "@shared/proto/file" import * as path from "path" -import * as vscode from "vscode" import { Controller } from ".." import { FileMethodHandler } from "./index" +import { getHostBridgeProvider } from "@/hosts/host-providers" +import { ShowMessageRequest, ShowMessageType } from "@/shared/proto/host/window" /** * Deletes a rule file from either global or workspace rules directory @@ -44,7 +45,13 @@ export const deleteRuleFile: FileMethodHandler = async (controller: Controller, const fileTypeName = request.type === "workflow" ? "workflow" : "rule" - vscode.window.showInformationMessage(`${fileTypeName} file "${fileName}" deleted successfully`) + const message = `${fileTypeName} file "${fileName}" deleted successfully` + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.INFORMATION, + message, + }), + ) return RuleFile.create({ filePath: request.rulePath, diff --git a/src/core/controller/index.ts b/src/core/controller/index.ts index 58891647..2d159ca8 100644 --- a/src/core/controller/index.ts +++ b/src/core/controller/index.ts @@ -27,20 +27,15 @@ import pWaitFor from "p-wait-for" import * as path from "path" import * as vscode from "vscode" import { ensureMcpServersDirectoryExists, ensureSettingsDirectoryExists, GlobalFileNames } from "../storage/disk" -import { - getAllExtensionState, - getGlobalState, - getWorkspaceState, - storeSecret, - updateGlobalState, - updateWorkspaceState, -} from "../storage/state" +import { getAllExtensionState, getGlobalState, getWorkspaceState, storeSecret, updateGlobalState } from "../storage/state" import { Task } from "../task" import { handleGrpcRequest, handleGrpcRequestCancel } from "./grpc-handler" import { sendStateUpdate } from "./state/subscribeToState" import { sendAddToInputEvent } from "./ui/subscribeToAddToInput" import { sendMcpMarketplaceCatalogEvent } from "./mcp/subscribeToMcpMarketplaceCatalog" import { AuthService } from "@/services/auth/AuthService" +import { ShowMessageRequest, ShowMessageType } from "@/shared/proto/host/window" +import { getHostBridgeProvider } from "@/hosts/host-providers" /* https://github.com/microsoft/vscode-webview-ui-toolkit-samples/blob/main/default/weather-webview/src/providers/WeatherViewProvider.ts @@ -118,9 +113,19 @@ export class Controller { await updateGlobalState(this.context, "userInfo", undefined) await updateGlobalState(this.context, "apiProvider", "openrouter") await this.postStateToWebview() - vscode.window.showInformationMessage("Successfully logged out of Cline") + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.INFORMATION, + message: "Successfully logged out of Cline", + }), + ) } catch (error) { - vscode.window.showErrorMessage("Logout failed") + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.INFORMATION, + message: "Logout failed", + }), + ) } } @@ -484,7 +489,12 @@ export class Controller { await this.postStateToWebview() } catch (error) { console.error("Failed to handle auth callback:", error) - vscode.window.showErrorMessage("Failed to log in to Cline") + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: "Failed to log in to Cline", + }), + ) // Even on login failure, we preserve any existing tokens // Only clear tokens on explicit logout } @@ -519,7 +529,12 @@ export class Controller { console.error("Failed to fetch MCP marketplace:", error) if (!silent) { const errorMessage = error instanceof Error ? error.message : "Failed to fetch MCP marketplace" - vscode.window.showErrorMessage(errorMessage) + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: errorMessage, + }), + ) } return undefined } @@ -603,7 +618,12 @@ export class Controller { } catch (error) { console.error("Failed to handle cached MCP marketplace:", error) const errorMessage = error instanceof Error ? error.message : "Failed to handle cached MCP marketplace" - vscode.window.showErrorMessage(errorMessage) + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: errorMessage, + }), + ) } } @@ -967,14 +987,24 @@ export class Controller { // Check if there's a workspace folder open const cwd = await getCwd() if (!cwd) { - vscode.window.showErrorMessage("No workspace folder open") + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: "No workspace folder open", + }), + ) return } // Get the git diff const gitDiff = await getWorkingState(cwd) if (gitDiff === "No changes in working directory") { - vscode.window.showInformationMessage("No changes in workspace for commit message") + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.INFORMATION, + message: "No changes in workspace for commit message", + }), + ) return } @@ -1041,25 +1071,59 @@ Commit message:` if (api && api.repositories.length > 0) { const repo = api.repositories[0] repo.inputBox.value = commitMessage - vscode.window.showInformationMessage("Commit message generated and applied") + const message = "Commit message generated and applied" + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.INFORMATION, + message, + }), + ) } else { - vscode.window.showErrorMessage("No Git repositories found") + const message = "No Git repositories found" + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message, + }), + ) } } else { - vscode.window.showErrorMessage("Git extension not found") + const message = "Git extension not found" + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message, + }), + ) } } else { - vscode.window.showErrorMessage("Failed to generate commit message") + const message = "Failed to generate commit message" + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message, + }), + ) } } catch (innerError) { const innerErrorMessage = innerError instanceof Error ? innerError.message : String(innerError) - vscode.window.showErrorMessage(`Failed to generate commit message: ${innerErrorMessage}`) + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: `Failed to generate commit message: ${innerErrorMessage}`, + }), + ) } }, ) } catch (error) { const errorMessage = error instanceof Error ? error.message : String(error) - vscode.window.showErrorMessage(`Failed to generate commit message: ${errorMessage}`) + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: `Failed to generate commit message: ${errorMessage}`, + }), + ) } } } diff --git a/src/core/controller/state/resetState.ts b/src/core/controller/state/resetState.ts index 2ac9849b..c2d21844 100644 --- a/src/core/controller/state/resetState.ts +++ b/src/core/controller/state/resetState.ts @@ -2,8 +2,9 @@ import { Controller } from ".." import { Empty } from "../../../shared/proto/common" import { ResetStateRequest } from "../../../shared/proto/state" import { resetGlobalState, resetWorkspaceState } from "../../../core/storage/state" -import * as vscode from "vscode" import { sendChatButtonClickedEvent } from "../ui/subscribeToChatButtonClicked" +import { ShowMessageRequest, ShowMessageType } from "@/shared/proto/host/window" +import { getHostBridgeProvider } from "@/hosts/host-providers" /** * Resets the extension state to its defaults @@ -14,10 +15,20 @@ import { sendChatButtonClickedEvent } from "../ui/subscribeToChatButtonClicked" export async function resetState(controller: Controller, request: ResetStateRequest): Promise { try { if (request.global) { - vscode.window.showInformationMessage("Resetting global state...") + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.INFORMATION, + message: "Resetting global state...", + }), + ) await resetGlobalState(controller.context) } else { - vscode.window.showInformationMessage("Resetting workspace state...") + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.INFORMATION, + message: "Resetting workspace state...", + }), + ) await resetWorkspaceState(controller.context) } @@ -26,7 +37,12 @@ export async function resetState(controller: Controller, request: ResetStateRequ controller.task = undefined } - vscode.window.showInformationMessage("State reset") + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.INFORMATION, + message: "State reset", + }), + ) await controller.postStateToWebview() await sendChatButtonClickedEvent(controller.id) @@ -34,7 +50,12 @@ export async function resetState(controller: Controller, request: ResetStateRequ return Empty.create() } catch (error) { console.error("Error resetting state:", error) - vscode.window.showErrorMessage(`Failed to reset state: ${error instanceof Error ? error.message : String(error)}`) + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: `Failed to reset state: ${error instanceof Error ? error.message : String(error)}`, + }), + ) throw error } } diff --git a/src/core/controller/state/updateDefaultTerminalProfile.ts b/src/core/controller/state/updateDefaultTerminalProfile.ts index daf88c12..6695de05 100644 --- a/src/core/controller/state/updateDefaultTerminalProfile.ts +++ b/src/core/controller/state/updateDefaultTerminalProfile.ts @@ -1,8 +1,9 @@ -import * as vscode from "vscode" import { Controller } from "../index" import * as proto from "@/shared/proto" import { updateGlobalState } from "../../storage/state" import { TerminalInfo } from "@/integrations/terminal/TerminalRegistry" +import { getHostBridgeProvider } from "@/hosts/host-providers" +import { ShowMessageRequest, ShowMessageType } from "@/shared/proto/host/window" export async function updateDefaultTerminalProfile( controller: Controller, @@ -25,16 +26,25 @@ export async function updateDefaultTerminalProfile( // Show information message if terminals were closed if (closedCount > 0) { - vscode.window.showInformationMessage( - `Closed ${closedCount} ${closedCount === 1 ? "terminal" : "terminals"} with different profile.`, + const message = `Closed ${closedCount} ${closedCount === 1 ? "terminal" : "terminals"} with different profile.` + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.INFORMATION, + message, + }), ) } // Show warning if there are busy terminals that couldn't be closed if (busyTerminals.length > 0) { - vscode.window.showWarningMessage( + const message = `${busyTerminals.length} busy ${busyTerminals.length === 1 ? "terminal has" : "terminals have"} a different profile. ` + - `Close ${busyTerminals.length === 1 ? "it" : "them"} to use the new profile for all commands.`, + `Close ${busyTerminals.length === 1 ? "it" : "them"} to use the new profile for all commands.` + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.WARNING, + message, + }), ) } } diff --git a/src/core/controller/task/deleteAllTaskHistory.ts b/src/core/controller/task/deleteAllTaskHistory.ts index b6491fcf..9f85f018 100644 --- a/src/core/controller/task/deleteAllTaskHistory.ts +++ b/src/core/controller/task/deleteAllTaskHistory.ts @@ -4,7 +4,8 @@ import { Controller } from ".." import { DeleteAllTaskHistoryCount } from "../../../shared/proto/task" import { getGlobalState, updateGlobalState } from "../../storage/state" import { fileExistsAtPath } from "../../../utils/fs" -import vscode from "vscode" +import { ShowMessageRequest, ShowMessageType } from "@/shared/proto/host/window" +import { getHostBridgeProvider } from "@/hosts/host-providers" /** * Deletes all task history, with an option to preserve favorites @@ -21,12 +22,18 @@ export async function deleteAllTaskHistory(controller: Controller): Promise { if (!mention) { @@ -76,7 +78,12 @@ export async function parseMentions( await urlContentFetcher.launchBrowser() } catch (error) { launchBrowserError = error - vscode.window.showErrorMessage(`Error fetching content for ${urlMention}: ${error.message}`) + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: `Error fetching content for ${urlMention}: ${error.message}`, + }), + ) } } @@ -93,7 +100,12 @@ export async function parseMentions( const markdown = await urlContentFetcher.urlToMarkdown(mention) result = markdown } catch (error) { - vscode.window.showErrorMessage(`Error fetching content for ${mention}: ${error.message}`) + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: `Error fetching content for ${mention}: ${error.message}`, + }), + ) result = `Error fetching content: ${error.message}` } } diff --git a/src/core/webview/index.ts b/src/core/webview/index.ts index ae9a2ed2..47d65673 100644 --- a/src/core/webview/index.ts +++ b/src/core/webview/index.ts @@ -10,6 +10,8 @@ import path from "node:path" import { v4 as uuidv4 } from "uuid" import { Uri } from "vscode" import { ExtensionMessage } from "@/shared/ExtensionMessage" +import { getHostBridgeProvider } from "@/hosts/host-providers" +import { ShowMessageRequest, ShowMessageType } from "@/shared/proto/host/window" export abstract class WebviewProvider { public static readonly sideBarId = "claude-dev.SidebarProvider" // used in package.json as the view's id. This value cannot be changed due to how vscode caches views based on their id, and updating the id would break existing instances of the extension. @@ -260,8 +262,12 @@ export abstract class WebviewProvider { try { await axios.get(`http://${localServerUrl}`) } catch (error) { - vscode.window.showErrorMessage( - "Cline: Local webview dev server is not running, HMR will not work. Please run 'npm run dev:webview' before launching the extension to enable HMR. Using bundled assets.", + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: + "Cline: Local webview dev server is not running, HMR will not work. Please run 'npm run dev:webview' before launching the extension to enable HMR. Using bundled assets.", + }), ) return this.getHtmlContent() diff --git a/src/dev/commands/tasks.ts b/src/dev/commands/tasks.ts index 946fa8a0..b443bf02 100644 --- a/src/dev/commands/tasks.ts +++ b/src/dev/commands/tasks.ts @@ -4,6 +4,8 @@ import * as path from "path" import { Controller } from "@core/controller" import { HistoryItem } from "@shared/HistoryItem" import { ClineMessage } from "@shared/ExtensionMessage" +import { ShowMessageRequest, ShowMessageType } from "@/shared/proto/host/window" +import { getHostBridgeProvider } from "@/hosts/host-providers" /** * Registers development-only commands for task manipulation. @@ -96,7 +98,13 @@ export function registerTaskCommands(context: vscode.ExtensionContext, controlle // Update the UI to show the new tasks await controller.postStateToWebview() - vscode.window.showInformationMessage(`Created ${tasksCount} test tasks`) + const message = `Created ${tasksCount} test tasks` + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.INFORMATION, + message, + }), + ) }, ) }), diff --git a/src/extension.ts b/src/extension.ts index 34c67f75..744de3e9 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -37,7 +37,8 @@ import { VscodeWebviewProvider } from "./core/webview/VscodeWebviewProvider" import { ExtensionContext } from "vscode" import { AuthService } from "./services/auth/AuthService" import { writeTextToClipboard, readTextFromClipboard } from "@/utils/env" - +import { getHostBridgeProvider } from "@hosts/host-providers" +import { ShowMessageRequest, ShowMessageType } from "./shared/proto/host/window" /* Built using https://github.com/microsoft/vscode-webview-ui-toolkit @@ -104,7 +105,12 @@ export async function activate(context: vscode.ExtensionContext) { const message = `Cline has been updated to v${currentVersion}` await vscode.commands.executeCommand("claude-dev.SidebarProvider.focus") await new Promise((resolve) => setTimeout(resolve, 200)) - vscode.window.showInformationMessage(message) + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.INFORMATION, + message, + }), + ) // Record that we've shown the popup for this version. await context.globalState.update("clineLastPopupNotificationVersion", currentVersion) } @@ -310,11 +316,14 @@ export async function activate(context: vscode.ExtensionContext) { // Ask user to confirm on state mismatch. This enables signins initiated from // outside the extension (e.g. Cline web) to be handled correctly. if (authService.authNonce !== state) { - const userConfirmation = await vscode.window.showWarningMessage( - `Store token returned from ${uri.path}`, - "Store", - "Cancel", - ) + const userConfirmation = ( + await getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: "Invalid auth state", + }), + ) + )?.selectedOption if (userConfirmation === "Cancel") { console.log("User declined to continue with auth callback due to state mismatch") return @@ -426,7 +435,12 @@ export async function activate(context: vscode.ExtensionContext) { // Ensure clipboard is restored even if an error occurs await writeTextToClipboard(tempCopyBuffer) console.error("Error getting terminal contents:", error) - vscode.window.showErrorMessage("Failed to get terminal contents") + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: "Failed to get terminal contents", + }), + ) } }), ) @@ -562,7 +576,12 @@ export async function activate(context: vscode.ExtensionContext) { } const selectedText = editor.document.getText(range) if (!selectedText.trim()) { - vscode.window.showInformationMessage("Please select some code to explain.") + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.INFORMATION, + message: "Please select some code to explain.", + }), + ) return } const filePath = editor.document.uri.fsPath @@ -584,7 +603,12 @@ export async function activate(context: vscode.ExtensionContext) { } const selectedText = editor.document.getText(range) if (!selectedText.trim()) { - vscode.window.showInformationMessage("Please select some code to improve.") + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.INFORMATION, + message: "Please select some code to improve.", + }), + ) return } const filePath = editor.document.uri.fsPath @@ -649,8 +673,11 @@ export async function activate(context: vscode.ExtensionContext) { sendFocusChatInputEvent(clientId) } else { console.error("FocusChatInput: Could not find or activate a Cline webview to focus.") - vscode.window.showErrorMessage( - "Could not activate Cline view. Please try opening it manually from the Activity Bar.", + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: "Could not activate Cline view. Please try opening it manually from the Activity Bar.", + }), ) } telemetryService.captureButtonClick("command_focusChatInput", activeWebviewProvider?.controller.task?.taskId, true) diff --git a/src/hosts/vscode/window/showMessage.ts b/src/hosts/vscode/window/showMessage.ts new file mode 100644 index 00000000..c57b06f1 --- /dev/null +++ b/src/hosts/vscode/window/showMessage.ts @@ -0,0 +1,24 @@ +import { window } from "vscode" +import { SelectedResponse, ShowMessageRequest, ShowMessageType } from "@/shared/proto/index.host" + +export async function showMessage(request: ShowMessageRequest): Promise { + const { message, type, options } = request + const { modal, detail, items } = options || {} + const option = items ? { modal, items } : { modal, detail } + + let selectedOption: string | undefined = undefined + + switch (type) { + case ShowMessageType.ERROR: + selectedOption = await window.showErrorMessage(message, option) + break + case ShowMessageType.WARNING: + selectedOption = await window.showWarningMessage(message, option) + break + default: + selectedOption = await window.showInformationMessage(message, option) + break + } + + return SelectedResponse.create({ selectedOption }) +} diff --git a/src/integrations/git/commit-message-generator.ts b/src/integrations/git/commit-message-generator.ts index a92e5a9a..fcca9009 100644 --- a/src/integrations/git/commit-message-generator.ts +++ b/src/integrations/git/commit-message-generator.ts @@ -1,9 +1,7 @@ import * as vscode from "vscode" -import { getWorkingState } from "@utils/git" import { writeTextToClipboard } from "@utils/env" import { getHostBridgeProvider } from "@/hosts/host-providers" -import { ShowTextDocumentRequest } from "@/shared/proto/host/window" - +import { ShowMessageType, ShowTextDocumentRequest, ShowMessageRequest } from "@/shared/proto/host/window" /** * Formats the git diff into a prompt for the AI * @param gitDiff The git diff to format @@ -61,7 +59,12 @@ export function extractCommitMessage(aiResponse: string): string { */ export async function copyCommitMessageToClipboard(message: string): Promise { await writeTextToClipboard(message) - vscode.window.showInformationMessage("Commit message copied to clipboard") + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.INFORMATION, + message: "Commit message copied to clipboard", + }), + ) } /** @@ -73,13 +76,19 @@ export async function showCommitMessageOptions(message: string): Promise { const applyAction = "Apply to Git Input" const editAction = "Edit Message" - const selectedAction = await vscode.window.showInformationMessage( - "Commit message generated", - { modal: false, detail: message }, - copyAction, - applyAction, - editAction, - ) + const selectedAction = ( + await getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.INFORMATION, + message: "Commit message generated", + options: { + modal: false, + detail: message, + items: [copyAction, applyAction, editAction], + }, + }), + ) + )?.selectedOption // Handle user dismissing the dialog (selectedAction is undefined) if (!selectedAction) { @@ -111,13 +120,28 @@ async function applyCommitMessageToGitInput(message: string): Promise { if (api && api.repositories.length > 0) { const repo = api.repositories[0] repo.inputBox.value = message - vscode.window.showInformationMessage("Commit message applied to Git input") + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.INFORMATION, + message: "Commit message applied to Git input", + }), + ) } else { - vscode.window.showErrorMessage("No Git repositories found") + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: "No Git repositories found", + }), + ) await copyCommitMessageToClipboard(message) } } else { - vscode.window.showErrorMessage("Git extension not found") + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: "Git extension not found", + }), + ) await copyCommitMessageToClipboard(message) } } @@ -137,5 +161,10 @@ async function editCommitMessage(message: string): Promise { path: document.uri.fsPath, }), ) - vscode.window.showInformationMessage("Edit the commit message and copy when ready") + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.INFORMATION, + message: "Edit the commit message and copy when ready", + }), + ) } diff --git a/src/integrations/misc/export-markdown.ts b/src/integrations/misc/export-markdown.ts index 6b604e39..a58d2db6 100644 --- a/src/integrations/misc/export-markdown.ts +++ b/src/integrations/misc/export-markdown.ts @@ -3,7 +3,7 @@ import os from "os" import * as path from "path" import * as vscode from "vscode" import { getHostBridgeProvider } from "@/hosts/host-providers" -import { ShowTextDocumentRequest, ShowTextDocumentOptions } from "@/shared/proto/host/window" +import { ShowTextDocumentRequest, ShowTextDocumentOptions, ShowMessageRequest, ShowMessageType } from "@/shared/proto/host/window" import { writeFile } from "@utils/fs" export async function downloadTask(dateTs: number, conversationHistory: Anthropic.MessageParam[]) { @@ -48,8 +48,11 @@ export async function downloadTask(dateTs: number, conversationHistory: Anthropi }), ) } catch (error) { - vscode.window.showErrorMessage( - `Failed to save markdown file: ${error instanceof Error ? error.message : String(error)}`, + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: `Failed to save markdown file: ${error instanceof Error ? error.message : String(error)}`, + }), ) } } diff --git a/src/integrations/misc/open-file.ts b/src/integrations/misc/open-file.ts index d999d0c6..2fe5c363 100644 --- a/src/integrations/misc/open-file.ts +++ b/src/integrations/misc/open-file.ts @@ -3,13 +3,18 @@ import * as os from "os" import * as vscode from "vscode" import { arePathsEqual } from "@utils/path" import { getHostBridgeProvider } from "@/hosts/host-providers" -import { ShowTextDocumentRequest, ShowTextDocumentOptions } from "@/shared/proto/host/window" +import { ShowTextDocumentRequest, ShowTextDocumentOptions, ShowMessageRequest, ShowMessageType } from "@/shared/proto/host/window" import { writeFile } from "@utils/fs" export async function openImage(dataUri: string) { const matches = dataUri.match(/^data:image\/([a-zA-Z]+);base64,(.+)$/) if (!matches) { - vscode.window.showErrorMessage("Invalid data URI format") + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: "Invalid data URI format", + }), + ) return } const [, format, base64Data] = matches @@ -19,7 +24,12 @@ export async function openImage(dataUri: string) { await writeFile(tempFilePath, new Uint8Array(imageBuffer)) await vscode.commands.executeCommand("vscode.open", vscode.Uri.file(tempFilePath)) } catch (error) { - vscode.window.showErrorMessage(`Error opening image: ${error}`) + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: `Error opening image: ${error}`, + }), + ) } } @@ -52,6 +62,11 @@ export async function openFile(absolutePath: string) { }), ) } catch (error) { - vscode.window.showErrorMessage(`Could not open file!`) + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: `Could not open file!`, + }), + ) } } diff --git a/src/integrations/misc/process-files.ts b/src/integrations/misc/process-files.ts index 829bc8ce..764951de 100644 --- a/src/integrations/misc/process-files.ts +++ b/src/integrations/misc/process-files.ts @@ -3,7 +3,7 @@ import fs from "fs/promises" import * as path from "path" import sizeOf from "image-size" import { getHostBridgeProvider } from "@/hosts/host-providers" -import { ShowOpenDialogueRequest } from "@/shared/proto/host/window" +import { ShowMessageRequest, ShowMessageType, ShowOpenDialogueRequest } from "@/shared/proto/host/window" /** * Supports processing of images and other file types @@ -46,14 +46,22 @@ export async function selectFiles(imagesAllowed: boolean): Promise<{ images: str const dimensions = sizeOf(uint8Array) // Get dimensions from Uint8Array if (dimensions.width! > 7500 || dimensions.height! > 7500) { console.warn(`Image dimensions exceed 7500px, skipping: ${filePath}`) - vscode.window.showErrorMessage( - `Image too large: ${path.basename(filePath)} was skipped (dimensions exceed 7500px).`, + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: `Image too large: ${path.basename(filePath)} was skipped (dimensions exceed 7500px).`, + }), ) return null } } catch (error) { console.error(`Error reading file or getting dimensions for ${filePath}:`, error) - vscode.window.showErrorMessage(`Could not read dimensions for ${path.basename(filePath)}, skipping.`) + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: `Could not read dimensions for ${path.basename(filePath)}, skipping.`, + }), + ) return null } @@ -68,12 +76,22 @@ export async function selectFiles(imagesAllowed: boolean): Promise<{ images: str const stats = await fs.stat(filePath) if (stats.size > 20 * 1000 * 1024) { console.warn(`File too large, skipping: ${filePath}`) - vscode.window.showErrorMessage(`File too large: ${path.basename(filePath)} was skipped (size exceeds 20MB).`) + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: `File too large: ${path.basename(filePath)} was skipped (size exceeds 20MB).`, + }), + ) return null } } catch (error) { console.error(`Error checking file size for ${filePath}:`, error) - vscode.window.showErrorMessage(`Could not check file size for ${path.basename(filePath)}, skipping.`) + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: `Could not check file size for ${path.basename(filePath)}, skipping.`, + }), + ) return null } return { type: "file", data: filePath } diff --git a/src/services/mcp/McpHub.ts b/src/services/mcp/McpHub.ts index dd47ddc6..7d6cf365 100644 --- a/src/services/mcp/McpHub.ts +++ b/src/services/mcp/McpHub.ts @@ -20,10 +20,8 @@ import * as path from "path" import * as vscode from "vscode" import { z } from "zod" import { FileChangeEvent_ChangeType, SubscribeToFileRequest } from "../../shared/proto/host/watch" -import { Metadata } from "../../shared/proto/common" import { DEFAULT_MCP_TIMEOUT_SECONDS, - McpMode, McpResource, McpResourceResponse, McpResourceTemplate, @@ -33,15 +31,14 @@ import { MIN_MCP_TIMEOUT_SECONDS, } from "@shared/mcp" import { fileExistsAtPath } from "@utils/fs" -import { arePathsEqual } from "@utils/path" import { secondsToMs } from "@utils/time" import { GlobalFileNames } from "@core/storage/disk" import { ExtensionMessage } from "@shared/ExtensionMessage" import { DEFAULT_REQUEST_TIMEOUT_MS } from "./constants" -import { Transport, McpConnection, McpTransportType, McpServerConfig } from "./types" +import { McpConnection, McpServerConfig } from "./types" import { BaseConfigSchema, ServerConfigSchema, McpSettingsSchema } from "./schemas" import { getHostBridgeProvider } from "@/hosts/host-providers" - +import { ShowMessageRequest, ShowMessageType } from "@/shared/proto/host/window" export class McpHub { getMcpServersPath: () => Promise private getSettingsDirectoryPath: () => Promise @@ -112,8 +109,11 @@ export class McpHub { try { config = JSON.parse(content) } catch (error) { - vscode.window.showErrorMessage( - "Invalid MCP settings format. Please ensure your settings follow the correct JSON format.", + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: "Invalid MCP settings format. Please ensure your settings follow the correct JSON format.", + }), ) return undefined } @@ -121,7 +121,12 @@ export class McpHub { // Validate against schema const result = McpSettingsSchema.safeParse(config) if (!result.success) { - vscode.window.showErrorMessage("Invalid MCP settings schema.") + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: "Invalid MCP settings schema.", + }), + ) return undefined } @@ -153,7 +158,12 @@ export class McpHub { if (settings) { try { await this.updateServerConnections(settings.mcpServers) - vscode.window.showInformationMessage("MCP servers updated") + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.INFORMATION, + message: "MCP servers updated", + }), + ) } catch (error) { console.error("Failed to process MCP settings change:", error) } @@ -403,8 +413,11 @@ export class McpHub { console.log(`[MCP Fallback Notification] ${name}:`, JSON.stringify(notification, null, 2)) // Show in VS Code for visibility - vscode.window.showInformationMessage( - `MCP ${name}: ${notification.method || "unknown"} - ${JSON.stringify(notification.params || {})}`, + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.INFORMATION, + message: `MCP ${name}: ${notification.method || "unknown"} - ${JSON.stringify(notification.params || {})}`, + }), ) } console.log(`[MCP Debug] Successfully set fallback notification handler for ${name}`) @@ -658,7 +671,12 @@ export class McpHub { const connection = this.connections.find((conn) => conn.server.name === serverName) const config = connection?.server.config if (config) { - vscode.window.showInformationMessage(`Restarting ${serverName} MCP server...`) + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.INFORMATION, + message: `Restarting ${serverName} MCP server...`, + }), + ) connection.server.status = "connecting" connection.server.error = "" await this.notifyWebviewOfServerChanges() @@ -667,10 +685,20 @@ export class McpHub { await this.deleteConnection(serverName) // Try to connect again using existing config await this.connectToServer(serverName, JSON.parse(config), "internal") - vscode.window.showInformationMessage(`${serverName} MCP server connected`) + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.INFORMATION, + message: `${serverName} MCP server connected`, + }), + ) } catch (error) { console.error(`Failed to restart connection for ${serverName}:`, error) - vscode.window.showErrorMessage(`Failed to connect to ${serverName} MCP server`) + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: `Failed to connect to ${serverName} MCP server`, + }), + ) } } @@ -756,8 +784,11 @@ export class McpHub { if (error instanceof Error) { console.error("Error details:", error.message, error.stack) } - vscode.window.showErrorMessage( - `Failed to update server state: ${error instanceof Error ? error.message : String(error)}`, + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: `Failed to update server state: ${error instanceof Error ? error.message : String(error)}`, + }), ) throw error } @@ -915,7 +946,12 @@ export class McpHub { } } catch (error) { console.error("Failed to update autoApprove settings:", error) - vscode.window.showErrorMessage("Failed to update autoApprove settings") + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: "Failed to update autoApprove settings", + }), + ) throw error // Re-throw to ensure the error is properly handled } } @@ -1033,8 +1069,11 @@ export class McpHub { if (error instanceof Error) { console.error("Error details:", error.message, error.stack) } - vscode.window.showErrorMessage( - `Failed to update server timeout: ${error instanceof Error ? error.message : String(error)}`, + getHostBridgeProvider().windowClient.showMessage( + ShowMessageRequest.create({ + type: ShowMessageType.ERROR, + message: `Failed to update server timeout: ${error instanceof Error ? error.message : String(error)}`, + }), ) throw error }