File size: 6,107 Bytes
666aab6 | 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 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | // βββ WebSocket Client with Auto-Reconnect + Event Buffering ββββββββββββββββββ
import { StreamEvent } from '@/types'
const WS_URL = process.env.NEXT_PUBLIC_WS_URL || 'ws://localhost:7860'
type EventHandler = (event: StreamEvent) => void
interface WSOptions {
onEvent?: EventHandler
onConnect?: () => void
onDisconnect?: () => void
onError?: (err: Event) => void
maxRetries?: number
heartbeatInterval?: number
}
export class AgentWebSocket {
private ws: WebSocket | null = null
private url: string
private opts: WSOptions
private retryCount = 0
private maxRetries: number
private retryTimer: ReturnType<typeof setTimeout> | null = null
private heartbeatTimer: ReturnType<typeof setInterval> | null = null
private seenIds = new Set<string>()
private connected = false
private intentionalClose = false
constructor(path: string, opts: WSOptions = {}) {
this.url = `${WS_URL}${path}`
this.opts = opts
this.maxRetries = opts.maxRetries ?? 10
}
connect() {
if (this.ws?.readyState === WebSocket.OPEN) return
this.intentionalClose = false
this._connect()
}
private _connect() {
try {
this.ws = new WebSocket(this.url)
this.ws.onopen = () => {
this.connected = true
this.retryCount = 0
this.opts.onConnect?.()
this._startHeartbeat()
}
this.ws.onmessage = (e) => {
try {
const event: StreamEvent = JSON.parse(e.data)
// Deduplicate
if (event.id && this.seenIds.has(event.id)) return
if (event.id) this.seenIds.add(event.id)
if (this.seenIds.size > 500) {
const arr = Array.from(this.seenIds)
this.seenIds = new Set(arr.slice(arr.length - 300))
}
this.opts.onEvent?.(event)
} catch {}
}
this.ws.onclose = () => {
this.connected = false
this._stopHeartbeat()
this.opts.onDisconnect?.()
if (!this.intentionalClose) this._scheduleReconnect()
}
this.ws.onerror = (e) => {
this.opts.onError?.(e)
}
} catch (err) {
if (!this.intentionalClose) this._scheduleReconnect()
}
}
private _scheduleReconnect() {
if (this.retryCount >= this.maxRetries) return
const delay = Math.min(1000 * Math.pow(2, this.retryCount), 30000)
this.retryCount++
this.retryTimer = setTimeout(() => this._connect(), delay)
}
private _startHeartbeat() {
this.heartbeatTimer = setInterval(() => {
if (this.ws?.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify({ type: 'ping', timestamp: Date.now() / 1000 }))
}
}, this.opts.heartbeatInterval ?? 15000)
}
private _stopHeartbeat() {
if (this.heartbeatTimer) {
clearInterval(this.heartbeatTimer)
this.heartbeatTimer = null
}
}
send(data: object) {
if (this.ws?.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify(data))
}
}
disconnect() {
this.intentionalClose = true
if (this.retryTimer) clearTimeout(this.retryTimer)
this._stopHeartbeat()
this.ws?.close()
this.ws = null
this.connected = false
}
isConnected() { return this.connected }
getRetryCount() { return this.retryCount }
}
// βββ SSE Client for task streaming ββββββββββββββββββββββββββββββββββββββββββββ
export class TaskSSEClient {
private url: string
private eventSource: EventSource | null = null
private onEvent: EventHandler
constructor(taskId: string, onEvent: EventHandler) {
this.url = `${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:7860'}/api/v1/tasks/${taskId}/stream`
this.onEvent = onEvent
}
connect() {
this.eventSource = new EventSource(this.url)
this.eventSource.onmessage = (e) => {
try {
const event: StreamEvent = JSON.parse(e.data)
this.onEvent(event)
if (event.type === 'stream_end' || event.type === 'task_completed' || event.type === 'task_failed') {
this.disconnect()
}
} catch {}
}
this.eventSource.onerror = () => {
this.disconnect()
}
}
disconnect() {
this.eventSource?.close()
this.eventSource = null
}
}
// βββ Chat streaming via fetch (SSE) βββββββββββββββββββββββββββββββββββββββββββ
export async function streamChatSSE(
messages: any[],
sessionId: string,
onChunk: (chunk: string) => void,
onDone: (full: string) => void,
onError?: (err: string) => void
) {
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:7860'
try {
const res = await fetch(`${API_URL}/api/v1/chat/stream`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ messages, session_id: sessionId, stream: true }),
})
if (!res.ok) {
onError?.(`HTTP ${res.status}: ${res.statusText}`)
return
}
const reader = res.body?.getReader()
if (!reader) return
const decoder = new TextDecoder()
let full = ''
let buffer = ''
while (true) {
const { done, value } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
const lines = buffer.split('\n')
buffer = lines.pop() ?? ''
for (const line of lines) {
if (!line.startsWith('data:')) continue
const raw = line.slice(5).trim()
if (!raw || raw === '[DONE]') continue
try {
const event = JSON.parse(raw)
if (event.type === 'llm_chunk') {
const chunk = event.data?.chunk || ''
full += chunk
onChunk(chunk)
} else if (event.type === 'stream_end') {
onDone(event.data?.full_response || full)
return
}
} catch {}
}
}
onDone(full)
} catch (err: any) {
onError?.(err.message || 'Stream error')
}
}
|