diff --git a/webview-ui/src/Providers.tsx b/webview-ui/src/Providers.tsx index b078eb1f..ed1a5edf 100644 --- a/webview-ui/src/Providers.tsx +++ b/webview-ui/src/Providers.tsx @@ -3,15 +3,18 @@ import { type ReactNode } from "react" import { CustomPostHogProvider } from "./CustomPostHogProvider" import { ClineAuthProvider } from "./context/ClineAuthContext" import { ExtensionStateContextProvider } from "./context/ExtensionStateContext" +import { PlatformProvider } from "./context/PlatformContext" export function Providers({ children }: { children: ReactNode }) { return ( - - - - {children} - - - + + + + + {children} + + + + ) } diff --git a/webview-ui/src/components/chat/ChatView.tsx b/webview-ui/src/components/chat/ChatView.tsx index ea0e4dcc..80d8d398 100644 --- a/webview-ui/src/components/chat/ChatView.tsx +++ b/webview-ui/src/components/chat/ChatView.tsx @@ -8,6 +8,7 @@ import { useCallback, useEffect, useMemo } from "react" import { useMount } from "react-use" import { normalizeApiConfiguration } from "@/components/settings/utils/providerUtils" import { useExtensionState } from "@/context/ExtensionStateContext" +import { useShowNavbar } from "@/context/PlatformContext" import { FileServiceClient, UiServiceClient } from "@/services/grpc-client" import { Navbar } from "../menu/Navbar" import AutoApproveBar from "./auto-approve-menu/AutoApproveBar" @@ -39,16 +40,14 @@ interface ChatViewProps { const MAX_IMAGES_AND_FILES_PER_MESSAGE = CHAT_CONSTANTS.MAX_IMAGES_AND_FILES_PER_MESSAGE const QUICK_WINS_HISTORY_THRESHOLD = 3 -const IS_STANDALONE = window?.__is_standalone__ ?? false - const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryView }: ChatViewProps) => { + const showNavbar = useShowNavbar() const { version, clineMessages: messages, taskHistory, apiConfiguration, telemetrySetting, - navigateToChat, mode, userInfo, currentFocusChainChecklist, @@ -335,7 +334,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie return (
- {IS_STANDALONE && } + {showNavbar && } {task ? ( + +// Global type declarations for postMessage and vscode API +declare global { + interface Window { + // This is the post message handler injected by JetBrains. + // !! Do not change the name of the handler without updating it on + // the JetBrains side as well. !! + standalonePostMessage?: (message: string) => void + } + function acquireVsCodeApi(): any +} + +// Initialize the vscode API if available +const vsCodeApi = typeof acquireVsCodeApi === "function" ? acquireVsCodeApi() : null + +// Implementations for post message handling +const postMessageStrategies: Record = { + vscode: (message: any) => { + if (vsCodeApi) { + vsCodeApi.postMessage(message) + } else { + console.log("postMessage fallback: ", message) + } + }, + standalone: (message: any) => { + if (!window.standalonePostMessage) { + console.error("Standalone postMessage not found.") + return + } + const json = JSON.stringify(message) + console.log("Standalone postMessage: " + json.slice(0, 200)) + window.standalonePostMessage(json) + }, +} + +// Implementations for message encoding +const messageEncoders: Record = { + none: (message: T, _encoder: (_: T) => unknown) => message, + json: (message: T, encoder: (_: T) => unknown) => encoder(message), +} + +// Implementations for message decoding +const messageDecoders: Record = { + none: (message: any, _decoder: (_: { [key: string]: any }) => T) => message, + json: (message: any, decoder: (_: { [key: string]: any }) => T) => decoder(message), +} + +// Local declaration of the platform compile-time constant +declare const __PLATFORM__: string + +// Get the specific platform config at compile time +const configs = platformConfigs as PlatformConfigs +const selectedConfig = configs[__PLATFORM__] +console.log("[PLATFORM_CONFIG] Build platform:", __PLATFORM__) + +// Build the platform config with injected functions +export const PLATFORM_CONFIG: PlatformConfig = { + messageEncoding: selectedConfig.messageEncoding, + showNavbar: selectedConfig.showNavbar, + postMessage: postMessageStrategies[selectedConfig.postMessageHandler], + encodeMessage: messageEncoders[selectedConfig.messageEncoding], + decodeMessage: messageDecoders[selectedConfig.messageEncoding], +} + +type MessageEncoding = "none" | "json" + +// Function types for platform-specific behaviors +type PostMessageFunction = (message: any) => void +type MessageEncoder = (message: T, encoder: (_: T) => unknown) => any +type MessageDecoder = (message: any, decoder: (_: { [key: string]: any }) => T) => T diff --git a/webview-ui/src/context/PlatformContext.tsx b/webview-ui/src/context/PlatformContext.tsx new file mode 100644 index 00000000..07b0d879 --- /dev/null +++ b/webview-ui/src/context/PlatformContext.tsx @@ -0,0 +1,17 @@ +import React, { createContext, useContext } from "react" +import type { PlatformConfig } from "../config/platform.config" +import { PLATFORM_CONFIG } from "../config/platform.config" + +const PlatformContext = createContext(PLATFORM_CONFIG) + +export const PlatformProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { + return {children} +} + +export const usePlatform = () => { + return useContext(PlatformContext) +} + +// Optional convenience hooks for individual config values +export const useMessageEncoding = () => usePlatform().messageEncoding +export const useShowNavbar = () => usePlatform().showNavbar diff --git a/webview-ui/src/services/grpc-client-base.ts b/webview-ui/src/services/grpc-client-base.ts index b3a189e4..c28d6cab 100644 --- a/webview-ui/src/services/grpc-client-base.ts +++ b/webview-ui/src/services/grpc-client-base.ts @@ -1,7 +1,12 @@ /** biome-ignore-all lint/complexity/noThisInStatic: In static methods, this refers to the constructor (the subclass that invoked the method) when we want to refer to the subclass serviceName. + * + * NOTE: This file imports PLATFORM_CONFIG directly rather than using the PlatformProvider + * because it contains static utility methods that are called from various contexts, + * including non-React code. The configuration is compile-time constant, so direct + * import is safe and ensures the methods work consistently regardless of React context. */ import { v4 as uuidv4 } from "uuid" -import { vscode } from "../utils/vscode" +import { PLATFORM_CONFIG } from "../config/platform.config" export interface Callbacks { onResponse: (response: TResponse) => void @@ -28,7 +33,7 @@ export abstract class ProtoBusClient { // Remove listener once we get our response window.removeEventListener("message", handleResponse) if (message.grpc_response.message) { - const response = this.decode(message.grpc_response.message, decodeResponse) + const response = PLATFORM_CONFIG.decodeMessage(message.grpc_response.message, decodeResponse) resolve(response) } else if (message.grpc_response.error) { reject(new Error(message.grpc_response.error)) @@ -39,13 +44,12 @@ export abstract class ProtoBusClient { } window.addEventListener("message", handleResponse) - // Send the request - vscode.postMessage({ + PLATFORM_CONFIG.postMessage({ type: "grpc_request", grpc_request: { service: this.serviceName, method: methodName, - message: this.encode(request, encodeRequest), + message: PLATFORM_CONFIG.encodeMessage(request, encodeRequest), request_id: requestId, is_streaming: false, }, @@ -67,7 +71,7 @@ export abstract class ProtoBusClient { if (message.type === "grpc_response" && message.grpc_response?.request_id === requestId) { if (message.grpc_response.message) { // Process streaming message - const response = this.decode(message.grpc_response.message, decodeResponse) + const response = PLATFORM_CONFIG.decodeMessage(message.grpc_response.message, decodeResponse) callbacks.onResponse(response) } else if (message.grpc_response.error) { // Handle error @@ -89,13 +93,12 @@ export abstract class ProtoBusClient { } } window.addEventListener("message", handleResponse) - // Send the streaming request - vscode.postMessage({ + PLATFORM_CONFIG.postMessage({ type: "grpc_request", grpc_request: { service: this.serviceName, method: methodName, - message: this.encode(request, encodeRequest), + message: PLATFORM_CONFIG.encodeMessage(request, encodeRequest), request_id: requestId, is_streaming: true, }, @@ -103,8 +106,7 @@ export abstract class ProtoBusClient { // Return a function to cancel the stream return () => { window.removeEventListener("message", handleResponse) - // Send cancellation message - vscode.postMessage({ + PLATFORM_CONFIG.postMessage({ type: "grpc_request_cancel", grpc_request_cancel: { request_id: requestId, @@ -113,20 +115,4 @@ export abstract class ProtoBusClient { console.log(`[DEBUG] Sent cancellation for request: ${requestId}`) } } - - static encode(message: T, encoder: (_: T) => unknown): any { - if (window.__is_standalone__) { - return encoder(message) - } - // VScode does not JSON encode ProtoBus messages - return message - } - - static decode(message: any, decoder: (_: { [key: string]: any }) => T): T { - if (window.__is_standalone__) { - return decoder(message) - } - // VScode does not JSON encode ProtoBus messages - return message - } } diff --git a/webview-ui/src/utils/vscode.ts b/webview-ui/src/utils/vscode.ts deleted file mode 100644 index 575d2f46..00000000 --- a/webview-ui/src/utils/vscode.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { WebviewMessage } from "@shared/WebviewMessage" -import type { WebviewApi } from "vscode-webview" - -/** - * A utility wrapper around the acquireVsCodeApi() function, which enables - * message passing and state management between the webview and extension - * contexts. - * - * This utility also enables webview code to be run in a web browser-based - * dev server by using native web browser features that mock the functionality - * enabled by acquireVsCodeApi. - */ -declare global { - interface Window { - __is_standalone__?: boolean - standalonePostMessage?: (event: any) => void - } -} - -class VSCodeAPIWrapper { - private readonly vsCodeApi: WebviewApi | undefined - - constructor() { - // Check if the acquireVsCodeApi function exists in the current development - // context (i.e. VS Code development window or web browser) - if (typeof acquireVsCodeApi === "function") { - this.vsCodeApi = acquireVsCodeApi() - } - } - - /** - * Post a message (i.e. send arbitrary data) to the owner of the webview. - * - * @remarks When running webview code inside a web browser, postMessage will instead - * log the given message to the console. - * - * @param message Arbitrary data (must be JSON serializable) to send to the extension context. - */ - public postMessage(message: WebviewMessage) { - if (this.vsCodeApi) { - this.vsCodeApi.postMessage(message) - } else if (window.__is_standalone__) { - if (!window.standalonePostMessage) { - console.warn("Standalone postMessage not found.") - return - } - const json = JSON.stringify(message) - console.log("Standalone postMessage: " + json.slice(0, 200)) - window.standalonePostMessage(json) - } else { - console.log("postMessage fallback: ", message) - } - } -} - -// Exports class singleton to prevent multiple invocations of acquireVsCodeApi. -export const vscode = new VSCodeAPIWrapper() diff --git a/webview-ui/vite.config.ts b/webview-ui/vite.config.ts index e06fd274..c9ea1c6d 100644 --- a/webview-ui/vite.config.ts +++ b/webview-ui/vite.config.ts @@ -28,6 +28,15 @@ const writePortToFile = (): Plugin => { const isDevBuild = process.argv.includes("--dev-build") +// Valid platforms, these should the keys in platform-configs.json +const VALID_PLATFORMS = ["vscode", "standalone"] +const platform = process.env.PLATFORM || "vscode" // Default to vscode + +if (!VALID_PLATFORMS.includes(platform)) { + throw new Error(`Invalid PLATFORM "${platform}". Must be one of: ${VALID_PLATFORMS.join(", ")}`) +} +console.log("Building webview for", platform) + export default defineConfig({ plugins: [react(), tailwindcss(), writePortToFile()], test: { @@ -79,6 +88,7 @@ export default defineConfig({ }, }, define: { + __PLATFORM__: JSON.stringify(platform), "process.env": { NODE_ENV: JSON.stringify(process.env.IS_DEV ? "development" : "production"), IS_DEV: JSON.stringify(process.env.IS_DEV),