File size: 3,981 Bytes
3e646d9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 | /**
* JARVIS β useStreamingChat hook
* Connects to the WebSocket streaming endpoint and manages
* real-time token delivery + tool use events.
*
* Usage:
* const { sendMessage, isStreaming, currentTokens, toolEvents } = useStreamingChat(sessionId)
*/
import { useState, useRef, useCallback, useEffect } from 'react'
const WS_BASE = import.meta.env.VITE_WS_URL ||
(window.location.protocol === 'https:' ? 'wss://' : 'ws://') +
window.location.host + '/api/ws'
export function useStreamingChat(sessionId) {
const [isStreaming, setIsStreaming] = useState(false)
const [currentTokens, setCurrentTokens] = useState('') // accumulates during stream
const [toolEvents, setToolEvents] = useState([])
const [error, setError] = useState(null)
const ws = useRef(null)
const onDoneRef = useRef(null)
// ββ Connect / reconnect βββββββββββββββββββββββββββββββββ
const connect = useCallback(() => {
if (!sessionId) return
if (ws.current?.readyState === WebSocket.OPEN) return
const url = `${WS_BASE}/chat/${sessionId}`
ws.current = new WebSocket(url)
ws.current.onopen = () => {
setError(null)
}
ws.current.onmessage = (event) => {
try {
const msg = JSON.parse(event.data)
switch (msg.type) {
case 'thinking':
setCurrentTokens('...')
break
case 'token':
setCurrentTokens((prev) => prev === '...' ? msg.data : prev + msg.data)
break
case 'tool_use':
setToolEvents((prev) => [...prev, msg.data])
break
case 'done':
setIsStreaming(false)
if (onDoneRef.current) {
onDoneRef.current({
text: currentTokens,
used_tools: msg.data.used_tools || [],
memory_hits: msg.data.memory_hits || 0,
})
}
setCurrentTokens('')
setToolEvents([])
break
case 'error':
setError(msg.data)
setIsStreaming(false)
setCurrentTokens('')
break
default:
break
}
} catch (e) {
console.error('WS parse error:', e)
}
}
ws.current.onerror = () => {
setError('WebSocket connection error')
setIsStreaming(false)
}
ws.current.onclose = () => {
// Auto-reconnect after 2s if not intentionally closed
setTimeout(() => {
if (sessionId) connect()
}, 2000)
}
}, [sessionId])
// ββ Connect on mount / sessionId change βββββββββββββββββ
useEffect(() => {
connect()
return () => {
ws.current?.close()
}
}, [connect])
// ββ Send message βββββββββββββββββββββββββββββββββββββββββ
const sendMessage = useCallback(
(message, imageCaption = null, onDone = null) => {
if (!ws.current || ws.current.readyState !== WebSocket.OPEN) {
connect()
// Retry after connection
setTimeout(() => sendMessage(message, imageCaption, onDone), 500)
return
}
setIsStreaming(true)
setCurrentTokens('')
setToolEvents([])
setError(null)
onDoneRef.current = onDone
ws.current.send(JSON.stringify({
message,
image_caption: imageCaption,
}))
},
[connect],
)
// ββ Disconnect βββββββββββββββββββββββββββββββββββββββββββ
const disconnect = useCallback(() => {
ws.current?.close()
}, [])
return {
sendMessage,
disconnect,
isStreaming,
currentTokens,
toolEvents,
error,
isConnected: ws.current?.readyState === WebSocket.OPEN,
}
}
|