|
| 1 | +import { getCluster } from '@kinvolk/headlamp-plugin/lib/Utils'; |
| 2 | +import React from 'react'; |
| 3 | + |
| 4 | +// Check if we're running in Electron |
| 5 | +const isElectron = !!(window as any)?.desktopApi; |
| 6 | + |
| 7 | +/** |
| 8 | + * Hook that monitors cluster changes and notifies the Electron main process |
| 9 | + * This enables MCP servers to restart when cluster context changes |
| 10 | + */ |
| 11 | +export function useClusterChangeNotifier() { |
| 12 | + const [currentCluster, setCurrentCluster] = React.useState<string | null>(null); |
| 13 | + const previousClusterRef = React.useRef<string | null>(null); |
| 14 | + |
| 15 | + React.useEffect(() => { |
| 16 | + // Function to check and update cluster |
| 17 | + const checkClusterChange = () => { |
| 18 | + const cluster = getCluster() || null; |
| 19 | + |
| 20 | + // Update state if cluster changed |
| 21 | + if (cluster !== currentCluster) { |
| 22 | + setCurrentCluster(cluster); |
| 23 | + } |
| 24 | + }; |
| 25 | + |
| 26 | + // Check initially |
| 27 | + checkClusterChange(); |
| 28 | + |
| 29 | + // Set up interval to check for cluster changes |
| 30 | + const interval = setInterval(checkClusterChange, 1000); // Check every second |
| 31 | + |
| 32 | + return () => clearInterval(interval); |
| 33 | + }, [currentCluster]); |
| 34 | + |
| 35 | + React.useEffect(() => { |
| 36 | + // Only notify if running in Electron |
| 37 | + if (!isElectron || !(window as any)?.desktopApi?.notifyClusterChange) { |
| 38 | + return; |
| 39 | + } |
| 40 | + |
| 41 | + const previousCluster = previousClusterRef.current; |
| 42 | + |
| 43 | + // Only notify if cluster actually changed and it's not the initial load |
| 44 | + if (currentCluster !== previousCluster && previousClusterRef.current !== undefined) { |
| 45 | + console.log('Cluster change detected, notifying electron:', { |
| 46 | + from: previousCluster, |
| 47 | + to: currentCluster, |
| 48 | + }); |
| 49 | + |
| 50 | + // Notify the electron main process |
| 51 | + (window as any).desktopApi.notifyClusterChange(currentCluster); |
| 52 | + } |
| 53 | + |
| 54 | + // Update the ref for next comparison |
| 55 | + previousClusterRef.current = currentCluster; |
| 56 | + }, [currentCluster]); |
| 57 | + |
| 58 | + return currentCluster; |
| 59 | +} |
| 60 | + |
| 61 | +/** |
| 62 | + * Component that automatically monitors cluster changes and notifies Electron |
| 63 | + * This component should be included once in the app root to enable MCP server restart functionality |
| 64 | + */ |
| 65 | +export function ClusterChangeNotifier(): null { |
| 66 | + useClusterChangeNotifier(); |
| 67 | + return null; |
| 68 | +} |
0 commit comments