Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

useChatConnection.ts

107 lines2.6 KB

1import { useState, useRef, useCallback } from 'react'
2import { newWebSocketRpcSession } from 'capnweb'
3​
4export interface ChatAPI {
5 joinChat(username: string, notificationCallback: Function): Promise<any>
6 sendMessage(message: string): Promise<any>
7 getChatState(): Promise<any>
8 pollMessages(): Promise<any[]>
9 leaveChat(): Promise<any>
10 getClaudeQueueStatus(): Promise<{
11 current: string | null
12 queue: string[]
13 isProcessing: boolean
14 }>
16​
17export interface ConnectionState {
18 isConnected: boolean
19 isConnecting: boolean
20 connectionStatus: string
21 error: string | null
23​
24export function useChatConnection() {
25 const [state, setState] = useState<ConnectionState>({
26 isConnected: false,
27 isConnecting: false,
28 connectionStatus: 'Disconnected',
29 error: null,
30 })
31​
32 const apiRef = useRef<ChatAPI | null>(null)
33​
34 const connect = useCallback(() => {
35 setState((prev) => ({
36 ...prev,
37 isConnecting: true,
38 connectionStatus: 'Connecting...',
39 error: null,
40 }))
41​
42 try {
43 const protocol =
44 typeof window !== 'undefined' && window.location.protocol === 'https:'
45 ? 'wss:'
46 : 'ws:'
47 const wsUrl =
48 typeof window !== 'undefined'
49 ? `${protocol}//${window.location.host}/api/websocket`
50 : 'ws://localhost:3000/api/websocket'
51​
52 console.log('Connecting to chat:', wsUrl)
53​
54 const api = newWebSocketRpcSession(wsUrl) as any as ChatAPI
55 apiRef.current = api
56​
57 // Test connection
58 api
59 .getChatState()
60 .then(() => {
61 console.log('Chat RPC connection established')
62 setState({
63 isConnected: true,
64 isConnecting: false,
65 connectionStatus: 'Connected',
66 error: null,
67 })
68 })
69 .catch((error) => {
70 console.error('Chat connection failed:', error)
71 setState({
72 isConnected: false,
73 isConnecting: false,
74 connectionStatus: 'Failed to connect',
75 error: error.message,
76 })
77 })
78 } catch (error) {
79 console.error('Failed to create chat session:', error)
80 setState({
81 isConnected: false,
82 isConnecting: false,
83 connectionStatus: 'Failed to connect',
84 error: error instanceof Error ? error.message : 'Unknown error',
85 })
86 }
87 }, [])
88​
89 const disconnect = useCallback(() => {
90 if (apiRef.current) {
91 apiRef.current = null
92 }
93 setState({
94 isConnected: false,
95 isConnecting: false,
96 connectionStatus: 'Disconnected',
97 error: null,
98 })
99 }, [])
100​
101 return {
102 ...state,
103 api: apiRef.current,
104 connect,
105 disconnect,
106 }