π OpenHands: AI-Driven Development
fix(frontend): frontend connects to WebSocket too early (#11493)
Hiep Lef9694858fb01
diff --git a/frontend/src/contexts/conversation-websocket-context.tsx b/frontend/src/contexts/conversation-websocket-context.tsxindex b04f7aba9b..3de57ad8d0 100644--- a/frontend/src/contexts/conversation-websocket-context.tsx+++ b/frontend/src/contexts/conversation-websocket-context.tsx@@ -68,10 +68,15 @@ export function ConversationWebSocketProvider({const { appendInput, appendOutput } = useCommandStore();// Build WebSocket URL from props- const wsUrl = useMemo(- () => buildWebSocketUrl(conversationId, conversationUrl),- [conversationId, conversationUrl],- );+ // Only build URL if we have both conversationId and conversationUrl+ // This prevents connection attempts during task polling phase+ const wsUrl = useMemo(() => {+ // Don't attempt connection if we're missing required data+ if (!conversationId || !conversationUrl) {+ return null;+ }+ return buildWebSocketUrl(conversationId, conversationUrl);+ }, [conversationId, conversationUrl]);// Reset hasConnected flag when conversation changesuseEffect(() => {@@ -185,9 +190,10 @@ export function ConversationWebSocketProvider({};}, [handleMessage, setErrorMessage, removeErrorMessage, sessionApiKey]);- // Build a fallback URL to prevent hook from connecting if conversation data isn't ready- const websocketUrl = wsUrl || "ws://localhost/placeholder";- const { socket } = useWebSocket(websocketUrl, websocketOptions);+ // Only attempt WebSocket connection when we have a valid URL+ // This prevents connection attempts during task polling phase+ const websocketUrl = wsUrl;+ const { socket } = useWebSocket(websocketUrl || "", websocketOptions);// V1 send message function via WebSocketconst sendMessage = useCallback(@@ -212,7 +218,7 @@ export function ConversationWebSocketProvider({);useEffect(() => {- // Only process socket updates if we have a valid URL+ // Only process socket updates if we have a valid URL and socketif (socket && wsUrl) {// Update state based on socket readyStateconst updateState = () => {diff --git a/frontend/src/hooks/use-websocket.ts b/frontend/src/hooks/use-websocket.tsindex 34f46205fd..96a160838e 100644--- a/frontend/src/hooks/use-websocket.ts+++ b/frontend/src/hooks/use-websocket.ts@@ -123,7 +123,10 @@ export const useWebSocket = <T = string>(shouldReconnectRef.current = true;attemptCountRef.current = 0;- connectWebSocket();+ // Only attempt connection if we have a valid URL+ if (url && url.trim() !== "") {+ connectWebSocket();+ }return () => {// Disable reconnection on unmount to prevent reconnection attempts