|
| 1 | +import { useState, useRef, useCallback, useEffect } from 'react'; |
| 2 | +import axios from 'axios'; |
| 3 | + |
| 4 | +interface StreamingOptions { |
| 5 | + authorId: string; |
| 6 | + conversationHistory: Array<{ authorRole: string; message: string; timestamp: string }>; |
| 7 | + url: string; |
| 8 | +} |
| 9 | + |
| 10 | +interface UseStreamingResponseReturn { |
| 11 | + startStreaming: (message: string, options: StreamingOptions, onToken: (token: string) => void, onComplete: () => void, onError: (error: string) => void) => Promise<void>; |
| 12 | + stopStreaming: () => void; |
| 13 | + isStreaming: boolean; |
| 14 | +} |
| 15 | + |
| 16 | +export const useStreamingResponse = (channelId: string): UseStreamingResponseReturn => { |
| 17 | + const [isStreaming, setIsStreaming] = useState(false); |
| 18 | + const eventSourceRef = useRef<EventSource | null>(null); |
| 19 | + |
| 20 | + const stopStreaming = useCallback(() => { |
| 21 | + if (eventSourceRef.current) { |
| 22 | + console.log('[SSE] Closing connection'); |
| 23 | + eventSourceRef.current.close(); |
| 24 | + eventSourceRef.current = null; |
| 25 | + } |
| 26 | + setIsStreaming(false); |
| 27 | + }, []); |
| 28 | + |
| 29 | + // Cleanup on unmount |
| 30 | + useEffect(() => { |
| 31 | + return () => { |
| 32 | + if (eventSourceRef.current) { |
| 33 | + eventSourceRef.current.close(); |
| 34 | + } |
| 35 | + }; |
| 36 | + }, []); |
| 37 | + |
| 38 | + const startStreaming = useCallback( |
| 39 | + async ( |
| 40 | + message: string, |
| 41 | + options: StreamingOptions, |
| 42 | + onToken: (token: string) => void, |
| 43 | + onComplete: () => void, |
| 44 | + onError: (error: string) => void |
| 45 | + ) => { |
| 46 | + console.log('[SSE] Starting streaming for channel:', channelId); |
| 47 | + |
| 48 | + // Close any existing connection |
| 49 | + stopStreaming(); |
| 50 | + |
| 51 | + try { |
| 52 | + // Step 1: Open SSE connection FIRST |
| 53 | + const sseUrl = `https://est-rag-rtc.rootcode.software/notifications-server/sse/stream/${channelId}`; |
| 54 | + console.log('[SSE] Connecting to:', sseUrl); |
| 55 | + |
| 56 | + const eventSource = new EventSource(sseUrl); |
| 57 | + eventSourceRef.current = eventSource; |
| 58 | + |
| 59 | + eventSource.onopen = () => { |
| 60 | + console.log('[SSE] Connection opened'); |
| 61 | + }; |
| 62 | + |
| 63 | + eventSource.onmessage = (event) => { |
| 64 | + console.log('[SSE] Message received:', event.data); |
| 65 | + |
| 66 | + try { |
| 67 | + const data = JSON.parse(event.data); |
| 68 | + |
| 69 | + if (data.type === 'stream_start') { |
| 70 | + console.log('[SSE] Stream started'); |
| 71 | + setIsStreaming(true); |
| 72 | + } else if (data.type === 'stream_chunk' && data.content) { |
| 73 | + console.log('[SSE] Token:', data.content); |
| 74 | + onToken(data.content); |
| 75 | + } else if (data.type === 'stream_end') { |
| 76 | + console.log('[SSE] Stream ended'); |
| 77 | + setIsStreaming(false); |
| 78 | + eventSource.close(); |
| 79 | + eventSourceRef.current = null; |
| 80 | + onComplete(); |
| 81 | + } else if (data.type === 'stream_error') { |
| 82 | + console.error('[SSE] Stream error:', data.error); |
| 83 | + setIsStreaming(false); |
| 84 | + eventSource.close(); |
| 85 | + eventSourceRef.current = null; |
| 86 | + onError(data.error || 'Stream error occurred'); |
| 87 | + } |
| 88 | + } catch (e) { |
| 89 | + console.error('[SSE] Failed to parse message:', e); |
| 90 | + } |
| 91 | + }; |
| 92 | + |
| 93 | + eventSource.onerror = (err) => { |
| 94 | + console.error('[SSE] Connection error:', err); |
| 95 | + setIsStreaming(false); |
| 96 | + eventSource.close(); |
| 97 | + eventSourceRef.current = null; |
| 98 | + onError('Connection error'); |
| 99 | + }; |
| 100 | + |
| 101 | + // Step 2: Wait a moment for SSE connection to establish, then trigger the stream |
| 102 | + await new Promise(resolve => setTimeout(resolve, 500)); |
| 103 | + |
| 104 | + // Step 3: POST to trigger streaming |
| 105 | + const postUrl = `https://est-rag-rtc.rootcode.software/notifications-server/channels/${channelId}/orchestrate/stream`; |
| 106 | + console.log('[API] Triggering stream:', postUrl); |
| 107 | + |
| 108 | + await axios.post(postUrl, { |
| 109 | + message, |
| 110 | + options, |
| 111 | + }); |
| 112 | + |
| 113 | + console.log('[API] Stream triggered successfully'); |
| 114 | + |
| 115 | + } catch (err) { |
| 116 | + console.error('[SSE] Error starting stream:', err); |
| 117 | + stopStreaming(); |
| 118 | + onError(err instanceof Error ? err.message : 'Failed to start streaming'); |
| 119 | + } |
| 120 | + }, |
| 121 | + [channelId, stopStreaming] |
| 122 | + ); |
| 123 | + |
| 124 | + return { |
| 125 | + startStreaming, |
| 126 | + stopStreaming, |
| 127 | + isStreaming, |
| 128 | + }; |
| 129 | +}; |
| 130 | + |
0 commit comments