import { useCallback, useEffect, useRef, useState } from 'react'; import { API_BASE_URL } from '@/lib/api'; import { browserLog } from '@/utils/browserLog'; export interface WebSocketMessage { type: 'connected' | 'run_update' | 'progress' | 'error' | 'completed' | 'pong'; runId?: string; data?: { progress?: number; currentDate?: string; error?: string; results?: unknown }; timestamp?: string; } interface UseWebSocketOptions { runId: string | null; onMessage?: (message: WebSocketMessage) => void; onProgress?: (progress: number, currentDate?: string) => void; onError?: (error: string) => void; onCompleted?: (results?: unknown) => void; } export function useWebSocket({ runId, ...callbacks }: UseWebSocketOptions) { const [isConnected, setIsConnected] = useState(false); const [lastMessage, setLastMessage] = useState(null); const callbacksRef = useRef(callbacks); const wsRef = useRef(null); const connectRef = useRef<() => void>(() => {}); const disconnectRef = useRef<() => void>(() => {}); callbacksRef.current = callbacks; useEffect(() => { let disposed = false; let reconnectTimer: ReturnType | undefined; let pingTimer: ReturnType | undefined; setIsConnected(false); setLastMessage(null); const connect = () => { if (disposed || !runId || wsRef.current) { return; } clearTimeout(reconnectTimer); const url = new URL('/ws', API_BASE_URL); url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'; url.searchParams.set('runId', runId); const retry = () => { if (!disposed) { reconnectTimer = setTimeout(connect, 3000); } }; try { const ws = new WebSocket(url.toString()); wsRef.current = ws; const isCurrent = () => !disposed && wsRef.current === ws; ws.onopen = () => { if (!isCurrent()) { return; } setIsConnected(true); pingTimer = setInterval(() => { if (isCurrent() && ws.readyState === WebSocket.OPEN) { ws.send(JSON.stringify({ type: 'ping' })); } }, 30000); }; ws.onmessage = event => { if (!isCurrent()) { return; } try { const message: WebSocketMessage = JSON.parse(event.data); if (message.runId && message.runId !== runId) { return; } setLastMessage(message); callbacksRef.current.onMessage?.(message); switch (message.type) { case 'progress': if (message.data) { callbacksRef.current.onProgress?.( message.data.progress ?? 0, message.data.currentDate ); } break; case 'error': if (message.data?.error) { callbacksRef.current.onError?.(message.data.error); } break; case 'completed': callbacksRef.current.onCompleted?.(message.data?.results); break; } } catch (error) { browserLog.error('Error parsing WebSocket message:', error); } }; ws.onerror = () => { if (isCurrent()) { setIsConnected(false); } }; ws.onclose = () => { if (!isCurrent()) { return; } wsRef.current = null; setIsConnected(false); clearInterval(pingTimer); // Check ownership before clearing the reference, not after. retry(); }; } catch (error) { browserLog.error('Error creating WebSocket:', error); setIsConnected(false); retry(); } }; const close = () => { clearTimeout(reconnectTimer); clearInterval(pingTimer); const ws = wsRef.current; wsRef.current = null; if (ws) { ws.onopen = null; ws.onmessage = null; ws.onerror = null; ws.onclose = null; ws.close(); } }; connectRef.current = () => { disposed = false; connect(); }; disconnectRef.current = () => { disposed = true; close(); setIsConnected(false); }; connect(); return () => { disposed = true; close(); connectRef.current = () => {}; disconnectRef.current = () => {}; }; }, [runId]); const connect = useCallback(() => connectRef.current(), []); const disconnect = useCallback(() => disconnectRef.current(), []); const sendMessage = useCallback((message: unknown) => { if (wsRef.current?.readyState === WebSocket.OPEN) { wsRef.current.send(JSON.stringify(message)); } }, []); return { isConnected, lastMessage, sendMessage, disconnect, connect }; }