import { useRef, useCallback } from 'react'; import { useChatStore } from '../stores/chatStore'; import type { WSEvent, StreamMessage } from '../utils/types'; let msgCounter = 0; function makeMsg( role: 'user' | 'assistant' | 'system', content: string, type: StreamMessage['type'], extra?: Partial, ): StreamMessage { return { id: `msg-${Date.now()}-${++msgCounter}`, role, content, type, timestamp: Date.now(), ...extra, }; } export function useWebSocket() { const wsRef = useRef(null); const { addMessage, setStreaming } = useChatStore(); const connect = useCallback((conversationId: number) => { const token = localStorage.getItem('access_token'); if (!token) return; const proto = window.location.protocol === 'https:' ? 'wss' : 'ws'; const host = window.location.host; const url = `${proto}://${host}/api/ws/chat/${conversationId}?token=${token}`; if (wsRef.current) { wsRef.current.close(); } const ws = new WebSocket(url); wsRef.current = ws; ws.onmessage = (ev) => { const event: WSEvent = JSON.parse(ev.data); switch (event.type) { case 'thinking': addMessage(makeMsg('assistant', event.content, 'thinking')); break; case 'tool_call': addMessage( makeMsg('assistant', '', 'tool_call', { toolName: event.tool_name, toolInput: event.tool_input, }), ); break; case 'tool_result': addMessage( makeMsg('assistant', '', 'tool_result', { toolName: event.tool_name, toolResult: event.result, }), ); break; case 'final_response': addMessage(makeMsg('assistant', event.content, 'final_response')); break; case 'done': setStreaming(false); break; case 'error': addMessage(makeMsg('system', event.content, 'error')); setStreaming(false); break; } }; ws.onerror = () => { addMessage(makeMsg('system', 'WebSocket connection error', 'error')); setStreaming(false); }; ws.onclose = () => { setStreaming(false); }; return ws; }, [addMessage, setStreaming]); const sendMessage = useCallback((content: string) => { if (wsRef.current?.readyState === WebSocket.OPEN) { setStreaming(true); addMessage(makeMsg('user', content, 'text')); wsRef.current.send(JSON.stringify({ type: 'user_message', content })); } }, [addMessage, setStreaming]); const disconnect = useCallback(() => { wsRef.current?.close(); wsRef.current = null; }, []); return { connect, sendMessage, disconnect, wsRef }; }