Spaces:
Runtime error

File size: 2,818 Bytes
ccab613
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b255fb0
ccab613
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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>,
): StreamMessage {
  return {
    id: `msg-${Date.now()}-${++msgCounter}`,
    role,
    content,
    type,
    timestamp: Date.now(),
    ...extra,
  };
}

export function useWebSocket() {
  const wsRef = useRef<WebSocket | null>(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 };
}