refactor: replace platform conditional __is_standalone__ with a platform configuration (#6122)
This commit is contained in:
1 parent
0936634fe5
commit
7a27f09224
8 files changed
+153
-95
No files matched your search
@@ -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 (
|
||||
<ExtensionStateContextProvider>
|
||||
<CustomPostHogProvider>
|
||||
<ClineAuthProvider>
|
||||
<HeroUIProvider>{children}</HeroUIProvider>
|
||||
</ClineAuthProvider>
|
||||
</CustomPostHogProvider>
|
||||
</ExtensionStateContextProvider>
|
||||
<PlatformProvider>
|
||||
<ExtensionStateContextProvider>
|
||||
<CustomPostHogProvider>
|
||||
<ClineAuthProvider>
|
||||
<HeroUIProvider>{children}</HeroUIProvider>
|
||||
</ClineAuthProvider>
|
||||
</CustomPostHogProvider>
|
||||
</ExtensionStateContextProvider>
|
||||
</PlatformProvider>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<ChatLayout isHidden={isHidden}>
|
||||
<div className="flex flex-col flex-1 overflow-hidden">
|
||||
{IS_STANDALONE && <Navbar />}
|
||||
{showNavbar && <Navbar />}
|
||||
{task ? (
|
||||
<TaskSection
|
||||
apiMetrics={apiMetrics}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"vscode": {
|
||||
"messageEncoding": "none",
|
||||
"showNavbar": false,
|
||||
"postMessageHandler": "vscode"
|
||||
},
|
||||
"standalone": {
|
||||
"messageEncoding": "json",
|
||||
"showNavbar": true,
|
||||
"postMessageHandler": "standalone"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import platformConfigs from "./platform-configs.json"
|
||||
|
||||
export interface PlatformConfig {
|
||||
messageEncoding: MessageEncoding
|
||||
showNavbar: boolean
|
||||
postMessage: PostMessageFunction
|
||||
encodeMessage: MessageEncoder
|
||||
decodeMessage: MessageDecoder
|
||||
}
|
||||
|
||||
// Internal type for JSON structure (not exported)
|
||||
type PlatformConfigJson = {
|
||||
messageEncoding: "none" | "json"
|
||||
showNavbar: boolean
|
||||
postMessageHandler: "vscode" | "standalone"
|
||||
}
|
||||
|
||||
type PlatformConfigs = Record<string, PlatformConfigJson>
|
||||
|
||||
// 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<string, PostMessageFunction> = {
|
||||
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<string, MessageEncoder> = {
|
||||
none: <T>(message: T, _encoder: (_: T) => unknown) => message,
|
||||
json: <T>(message: T, encoder: (_: T) => unknown) => encoder(message),
|
||||
}
|
||||
|
||||
// Implementations for message decoding
|
||||
const messageDecoders: Record<string, MessageDecoder> = {
|
||||
none: <T>(message: any, _decoder: (_: { [key: string]: any }) => T) => message,
|
||||
json: <T>(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 = <T>(message: T, encoder: (_: T) => unknown) => any
|
||||
type MessageDecoder = <T>(message: any, decoder: (_: { [key: string]: any }) => T) => T
|
||||
@@ -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<PlatformConfig>(PLATFORM_CONFIG)
|
||||
|
||||
export const PlatformProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
return <PlatformContext.Provider value={PLATFORM_CONFIG}>{children}</PlatformContext.Provider>
|
||||
}
|
||||
|
||||
export const usePlatform = () => {
|
||||
return useContext(PlatformContext)
|
||||
}
|
||||
|
||||
// Optional convenience hooks for individual config values
|
||||
export const useMessageEncoding = () => usePlatform().messageEncoding
|
||||
export const useShowNavbar = () => usePlatform().showNavbar
|
||||
@@ -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<TResponse> {
|
||||
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<T>(message: T, encoder: (_: T) => unknown): any {
|
||||
if (window.__is_standalone__) {
|
||||
return encoder(message)
|
||||
}
|
||||
// VScode does not JSON encode ProtoBus messages
|
||||
return message
|
||||
}
|
||||
|
||||
static decode<T>(message: any, decoder: (_: { [key: string]: any }) => T): T {
|
||||
if (window.__is_standalone__) {
|
||||
return decoder(message)
|
||||
}
|
||||
// VScode does not JSON encode ProtoBus messages
|
||||
return message
|
||||
}
|
||||
}
|
||||
@@ -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<unknown> | 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()
|
||||
@@ -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),
|
||||
|
||||
Reference in new issue
Block a user