From 150af1607e45fecb8cc6a23edfe1cc1fe8d5fa9c Mon Sep 17 00:00:00 2001 From: celestial-vault <58194240+celestial-vault@users.noreply.github.com> Date: Fri, 6 Jun 2025 19:05:16 -0700 Subject: [PATCH] Migrate workspaceUpdated protobus (#4014) * migrate workspaceUpdated * fix linter warning about empty proto object creation --------- Co-authored-by: Elephant Lumps --- proto/file.proto | 3 + .../file/subscribeToWorkspaceUpdates.ts | 58 +++++++++++++++++++ src/core/controller/index.ts | 2 +- .../ui/subscribeToChatButtonClicked.ts | 2 +- .../ui/subscribeToHistoryButtonClicked.ts | 2 +- .../ui/subscribeToMcpButtonClicked.ts | 2 +- .../workspace/WorkspaceTracker.ts | 17 +++--- src/shared/ExtensionMessage.ts | 2 - .../src/context/ExtensionStateContext.tsx | 29 ++++++++-- 9 files changed, 96 insertions(+), 21 deletions(-) create mode 100644 src/core/controller/file/subscribeToWorkspaceUpdates.ts diff --git a/proto/file.proto b/proto/file.proto index 694ee8b4..2a1279b5 100644 --- a/proto/file.proto +++ b/proto/file.proto @@ -55,6 +55,9 @@ service FileService { // Opens a task's conversation history file on disk rpc openTaskHistory(StringRequest) returns (Empty); + + // Subscribe to workspace file updates + rpc subscribeToWorkspaceUpdates(EmptyRequest) returns (stream StringArray); } // Response for refreshRules operation diff --git a/src/core/controller/file/subscribeToWorkspaceUpdates.ts b/src/core/controller/file/subscribeToWorkspaceUpdates.ts new file mode 100644 index 00000000..db94e8c8 --- /dev/null +++ b/src/core/controller/file/subscribeToWorkspaceUpdates.ts @@ -0,0 +1,58 @@ +import { Controller } from "../index" +import { EmptyRequest, StringArray } from "@shared/proto/common" +import { StreamingResponseHandler, getRequestRegistry } from "../grpc-handler" + +// Keep track of active subscriptions +const activeWorkspaceUpdateSubscriptions = new Set() + +/** + * Subscribe to workspace file updates + * @param controller The controller instance + * @param request The empty request + * @param responseStream The streaming response handler + * @param requestId The ID of the request (passed by the gRPC handler) + */ +export async function subscribeToWorkspaceUpdates( + controller: Controller, + request: EmptyRequest, + responseStream: StreamingResponseHandler, + requestId?: string, +): Promise { + // Add this subscription to the active subscriptions + activeWorkspaceUpdateSubscriptions.add(responseStream) + + // Register cleanup when the connection is closed + const cleanup = () => { + activeWorkspaceUpdateSubscriptions.delete(responseStream) + } + + // Register the cleanup function with the request registry if we have a requestId + if (requestId) { + getRequestRegistry().registerRequest(requestId, cleanup, { type: "workspace_update_subscription" }, responseStream) + } +} + +/** + * Send a workspace update event to all active subscribers + * @param filePaths Array of file paths to send + */ +export async function sendWorkspaceUpdateEvent(filePaths: string[]): Promise { + // Send the event to all active subscribers + const promises = Array.from(activeWorkspaceUpdateSubscriptions).map(async (responseStream) => { + try { + const event = StringArray.create({ + values: filePaths, + }) + await responseStream( + event, + false, // Not the last message + ) + } catch (error) { + console.error("Error sending workspace update event:", error) + // Remove the subscription if there was an error + activeWorkspaceUpdateSubscriptions.delete(responseStream) + } + }) + + await Promise.all(promises) +} diff --git a/src/core/controller/index.ts b/src/core/controller/index.ts index 909ec07a..cb8e73f2 100644 --- a/src/core/controller/index.ts +++ b/src/core/controller/index.ts @@ -68,7 +68,7 @@ export class Controller { this.outputChannel.appendLine("ClineProvider instantiated") this.postMessage = postMessage - this.workspaceTracker = new WorkspaceTracker((msg) => this.postMessageToWebview(msg)) + this.workspaceTracker = new WorkspaceTracker() this.mcpHub = new McpHub( () => ensureMcpServersDirectoryExists(), () => ensureSettingsDirectoryExists(this.context), diff --git a/src/core/controller/ui/subscribeToChatButtonClicked.ts b/src/core/controller/ui/subscribeToChatButtonClicked.ts index 729397e9..587f1a6b 100644 --- a/src/core/controller/ui/subscribeToChatButtonClicked.ts +++ b/src/core/controller/ui/subscribeToChatButtonClicked.ts @@ -50,7 +50,7 @@ export async function sendChatButtonClickedEvent(controllerId: string): Promise< } try { - const event: Empty = Empty.create({}) + const event = Empty.create({}) await responseStream( event, false, // Not the last message diff --git a/src/core/controller/ui/subscribeToHistoryButtonClicked.ts b/src/core/controller/ui/subscribeToHistoryButtonClicked.ts index 366b2a4a..cf3d1fde 100644 --- a/src/core/controller/ui/subscribeToHistoryButtonClicked.ts +++ b/src/core/controller/ui/subscribeToHistoryButtonClicked.ts @@ -50,7 +50,7 @@ export async function sendHistoryButtonClickedEvent(webviewType?: WebviewProvide } try { - const event: Empty = Empty.create({}) + const event = Empty.create({}) await responseStream( event, false, // Not the last message diff --git a/src/core/controller/ui/subscribeToMcpButtonClicked.ts b/src/core/controller/ui/subscribeToMcpButtonClicked.ts index ef3fe384..fe6e34fd 100644 --- a/src/core/controller/ui/subscribeToMcpButtonClicked.ts +++ b/src/core/controller/ui/subscribeToMcpButtonClicked.ts @@ -41,7 +41,7 @@ export async function subscribeToMcpButtonClicked( * @param webviewType The type of webview that triggered the event (SIDEBAR or TAB) */ export async function sendMcpButtonClickedEvent(webviewType?: WebviewProviderType): Promise { - const event: Empty = Empty.create({}) + const event = Empty.create({}) // Process all subscriptions, filtering based on the source const promises = Array.from(mcpButtonClickedSubscriptions.entries()).map(async ([responseStream, providerType]) => { diff --git a/src/integrations/workspace/WorkspaceTracker.ts b/src/integrations/workspace/WorkspaceTracker.ts index d56f7f82..c64ce321 100644 --- a/src/integrations/workspace/WorkspaceTracker.ts +++ b/src/integrations/workspace/WorkspaceTracker.ts @@ -1,7 +1,7 @@ import * as vscode from "vscode" import * as path from "path" import { listFiles } from "@services/glob/list-files" -import { ExtensionMessage } from "@shared/ExtensionMessage" +import { sendWorkspaceUpdateEvent } from "@core/controller/file/subscribeToWorkspaceUpdates" const cwd = vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0) @@ -18,8 +18,7 @@ class WorkspaceTracker { ) } - constructor(private readonly postMessageToWebview: (message: ExtensionMessage) => Promise) { - this.postMessageToWebview = postMessageToWebview + constructor() { this.registerListeners() } @@ -91,17 +90,15 @@ class WorkspaceTracker { this.workspaceDidUpdate() } - private workspaceDidUpdate() { + private async workspaceDidUpdate() { if (!cwd) { return } - this.postMessageToWebview({ - type: "workspaceUpdated", - filePaths: Array.from(new Set([...this.activeFiles, ...this.filePaths])).map((file) => { - const relativePath = path.relative(cwd, file).toPosix() - return file.endsWith("/") ? relativePath + "/" : relativePath - }), + const filePaths = Array.from(new Set([...this.activeFiles, ...this.filePaths])).map((file) => { + const relativePath = path.relative(cwd, file).toPosix() + return file.endsWith("/") ? relativePath + "/" : relativePath }) + await sendWorkspaceUpdateEvent(filePaths) } private normalizeFilePath(filePath: string): string { diff --git a/src/shared/ExtensionMessage.ts b/src/shared/ExtensionMessage.ts index d3d186d7..1bf7ccc5 100644 --- a/src/shared/ExtensionMessage.ts +++ b/src/shared/ExtensionMessage.ts @@ -17,7 +17,6 @@ export interface ExtensionMessage { | "action" | "state" | "selectedImages" - | "workspaceUpdated" | "openAiModels" | "requestyModels" | "mcpServers" @@ -35,7 +34,6 @@ export interface ExtensionMessage { ollamaModels?: string[] lmStudioModels?: string[] vsCodeLmModels?: { vendor?: string; family?: string; version?: string; id?: string }[] - filePaths?: string[] openAiModels?: string[] requestyModels?: Record mcpServers?: McpServer[] diff --git a/webview-ui/src/context/ExtensionStateContext.tsx b/webview-ui/src/context/ExtensionStateContext.tsx index 570b7a00..39b90107 100644 --- a/webview-ui/src/context/ExtensionStateContext.tsx +++ b/webview-ui/src/context/ExtensionStateContext.tsx @@ -1,5 +1,12 @@ import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from "react" import { useEvent } from "react-use" +import { + StateServiceClient, + ModelsServiceClient, + UiServiceClient, + FileServiceClient, + McpServiceClient, +} from "../services/grpc-client" import { EmptyRequest } from "@shared/proto/common" import { UpdateSettingsRequest } from "@shared/proto/state" import { WebviewProviderType as WebviewProviderTypeEnum, WebviewProviderTypeRequest } from "@shared/proto/ui" @@ -19,7 +26,6 @@ import { requestyDefaultModelInfo, } from "../../../src/shared/api" import { McpMarketplaceCatalog, McpServer, McpViewTab } from "../../../src/shared/mcp" -import { ModelsServiceClient, StateServiceClient, UiServiceClient, McpServiceClient } from "../services/grpc-client" import { convertTextMateToHljs } from "../utils/textMateToHljs" import { vscode } from "../utils/vscode" import { OpenRouterCompatibleModelInfo } from "@shared/proto/models" @@ -201,10 +207,6 @@ export const ExtensionStateContextProvider: React.FC<{ const handleMessage = useCallback((event: MessageEvent) => { const message: ExtensionMessage = event.data switch (message.type) { - case "workspaceUpdated": { - setFilePaths(message.filePaths ?? []) - break - } case "openAiModels": { const updatedModels = message.openAiModels ?? [] setOpenAiModels(updatedModels) @@ -238,6 +240,7 @@ export const ExtensionStateContextProvider: React.FC<{ const mcpMarketplaceUnsubscribeRef = useRef<(() => void) | null>(null) const themeSubscriptionRef = useRef<(() => void) | null>(null) const openRouterModelsUnsubscribeRef = useRef<(() => void) | null>(null) + const workspaceUpdatesUnsubscribeRef = useRef<(() => void) | null>(null) // Subscribe to state updates and UI events using the gRPC streaming API useEffect(() => { @@ -367,6 +370,18 @@ export const ExtensionStateContextProvider: React.FC<{ onComplete: () => {}, }) + // Subscribe to workspace file updates + workspaceUpdatesUnsubscribeRef.current = FileServiceClient.subscribeToWorkspaceUpdates(EmptyRequest.create({}), { + onResponse: (response) => { + console.log("[DEBUG] Received workspace update event from gRPC stream") + setFilePaths(response.values || []) + }, + onError: (error) => { + console.error("Error in workspace updates subscription:", error) + }, + onComplete: () => {}, + }) + // Set up settings button clicked subscription settingsButtonClickedSubscriptionRef.current = UiServiceClient.subscribeToSettingsButtonClicked( WebviewProviderTypeRequest.create({ @@ -542,6 +557,10 @@ export const ExtensionStateContextProvider: React.FC<{ openRouterModelsUnsubscribeRef.current() openRouterModelsUnsubscribeRef.current = null } + if (workspaceUpdatesUnsubscribeRef.current) { + workspaceUpdatesUnsubscribeRef.current() + workspaceUpdatesUnsubscribeRef.current = null + } } }, [])