Open History to see the last commit
1import { useCallback, useEffect, useState } from 'react'
2import type { RefObject } from 'react'
3import type { RpcStub } from 'capnweb'
4import type {
5 ChatApi,
6 ChatMessage,
7 ChatNotification,
8 ChatRoomState,
9} from '../../chat-server/chat-api'
10import type { ChatNotifier } from '@/lib/chat-notifier'
11
12export type { ChatMessage, ChatRoomState }
13
14function notificationToMessage(notification: ChatNotification): ChatMessage {
15 return {
16 id: notification.id || Math.random().toString(36).slice(2, 11),
17 username: notification.username || 'System',
18 message: notification.message,
19 timestamp: notification.timestamp || new Date().toISOString(),
20 type: notification.type,
21 }
22}
23
24function formatError(error: unknown) {
25 if (error instanceof Error) return error.message
26 if (typeof error === 'object' && error !== null && 'message' in error) {
27 return String(error.message)
28 }
29 return String(error)
30}
31
32export function useChatMessages(
33 api: RpcStub<ChatApi> | null,
34 apiRef: RefObject<RpcStub<ChatApi> | null>,
35 notifier: ChatNotifier | null,
36 isConnected: boolean,
37 username: string | null,
38) {
39 const getApi = useCallback(() => apiRef.current ?? api, [api, apiRef])
40 const [chatState, setChatState] = useState<ChatRoomState>({
41 onlineUsers: [],
42 messages: [],
43 })
44
45 const [isJoined, setIsJoined] = useState(false)
46
47 useEffect(() => {
48 if (!notifier) return
49
50 return notifier.addHandler((notification: ChatNotification) => {
51 // Status / sync events — not chat lines
52 if (
53 notification.type === 'todos_updated' ||
54 notification.type === 'claude_mode_changed' ||
55 notification.type === 'claude_responding' ||
56 notification.type === 'claude_idle'
57 ) {
58 return
59 }
60
61 setChatState((prev) => {
62 const nextMessages = [
63 ...prev.messages,
64 notificationToMessage(notification),
65 ]
66
67 return {
68 onlineUsers: notification.onlineUsers ?? prev.onlineUsers,
69 messages: nextMessages.slice(-100),
70 }
71 })
72 })
73 }, [notifier])
74
75 const sendMessage = useCallback(
76 async (messageText: string) => {
77 const activeApi = getApi()
78 if (!activeApi || !messageText.trim()) {
79 return { success: false, error: 'Cannot send empty message' }
80 }
81
82 if (!isJoined) {
83 return { success: false, error: 'Still joining the chat room…' }
84 }
85
86 try {
87 await activeApi.sendMessage(messageText)
88 return { success: true }
89 } catch (error) {
90 console.error('Error sending message:', formatError(error), error)
91 return {
92 success: false,
93 error: formatError(error) || 'Failed to send message',
94 }
95 }
96 },
97 [getApi, isJoined],
98 )
99
100 const joinChat = useCallback(
101 async (chatUsername: string) => {
102 const activeApi = getApi()
103 if (!activeApi) return { success: false, error: 'Not connected' }
104
105 try {
106 await activeApi.leaveChat()
107 const result = await activeApi.joinChat(chatUsername)
108
109 setChatState({
110 onlineUsers: result.onlineUsers,
111 messages: result.recentMessages,
112 })
113 setIsJoined(true)
114
115 return { success: true }
116 } catch (error) {
117 console.error('Error joining chat:', formatError(error), error)
118 setIsJoined(false)
119 return {
120 success: false,
121 error: formatError(error) || 'Failed to join chat',
122 }
123 }
124 },
125 [getApi],
126 )
127
128 const leaveChat = useCallback(async () => {
129 const activeApi = getApi()
130 if (!activeApi) return
131
132 try {
133 await activeApi.leaveChat()
134 setChatState({ onlineUsers: [], messages: [] })
135 setIsJoined(false)
136 } catch (error) {
137 console.error('Error leaving chat:', formatError(error), error)
138 }
139 }, [getApi])
140
141 useEffect(() => {
142 const activeApi = getApi()
143 if (!activeApi || !isConnected) return
144
145 // Object flag so cancellation stays visible across sync RpcStub awaits.
146 const cancelled: { current: boolean } = { current: false }
147
148 const switchPersona = async () => {
149 setIsJoined(false)
150
151 try {
152 // Always leave first so the previous persona is removed from the room.
153 await activeApi.leaveChat()
154
155 if (!username) {
156 if (!cancelled.current) {
157 setChatState({ onlineUsers: [], messages: [] })
158 }
159 return
160 }
161
162 const result = await activeApi.joinChat(username)
163 if (cancelled.current) return
164
165 setChatState({
166 onlineUsers: result.onlineUsers,
167 messages: result.recentMessages,
168 })
169 setIsJoined(true)
170 } catch (error) {
171 if (!cancelled.current) {
172 console.error(
173 'Error switching chat persona:',
174 formatError(error),
175 error,
176 )
177 }
178 }
179 }
180
181 void switchPersona()
182
183 return () => {
184 cancelled.current = true
185 }
186 }, [api, getApi, isConnected, username])
187
188 return {
189 chatState,
190 sendMessage,
191 joinChat,
192 leaveChat,
193 isJoined,
194 }
195}