Open History to see the last commit
1// Cap'n Web RPC server implementation for chat
2import { RpcTarget } from 'capnweb'
3import { ChatLogic } from './chat-logic.js'
4import { TodoLogic } from './todo-logic.js'
5import type {
6 ChatApi,
7 ChatNotification,
8 ChatNotifierApi,
9 ClaudeMode,
10 ClaudeQueueStatus,
11 JoinResult,
12 SendResult,
13 TodoItem,
14} from './chat-api.js'
15import type { ClaudeService } from './claude-service.js'
16import type { WebSocket } from 'ws'
17
18type NotifyTarget = ChatNotifierApi
19
20// Global registry of client notification targets (Cap'n Web RpcTarget stubs)
21export const clients = new Map<string, NotifyTarget>()
22
23let claudeMode: ClaudeMode = 'passive'
24
25// Lazy-load claude service to avoid importing AI packages at module parse time
26let globalClaudeService: ClaudeService | null = null
27async function getClaudeService(): Promise<ClaudeService> {
28 if (!globalClaudeService) {
29 const { ClaudeService } = await import('./claude-service.js')
30 globalClaudeService = new ClaudeService(globalTodos)
31 }
32 return globalClaudeService
33}
34
35function pushNotification(
36 notifier: ChatNotifierApi,
37 notification: ChatNotification,
38) {
39 // Defer server→client RPC so we never nest calls inside an in-flight handler
40 // (Cap'n Web 0.10 throws "' is not a function" in the browser otherwise).
41 queueMicrotask(() => {
42 void Promise.resolve(notifier.notify(notification)).catch((error) => {
43 console.error('Failed to push notification to client:', error)
44 })
45 })
46}
47
48function normalizeNotification(
49 notification: ChatNotification,
50): ChatNotification {
51 return {
52 ...notification,
53 timestamp: notification.timestamp || new Date().toISOString(),
54 id: notification.id || Math.random().toString(36).slice(2, 11),
55 }
56}
57
58function isClaudeMention(messageText: string): boolean {
59 const trimmedMessage = messageText.trim()
60 return (
61 /@Claude/i.test(messageText) ||
62 /^Claude/i.test(trimmedMessage) ||
63 /^@Claude/i.test(trimmedMessage)
64 )
65}
66
67function isNoReply(response: string): boolean {
68 return response.trim().toUpperCase() === 'NO_REPLY'
69}
70
71// Global shared todo list
72export const globalTodos = new TodoLogic({
73 async onTodosChanged(todos) {
74 await ChatServer.broadcastToAll({
75 type: 'todos_updated',
76 message: 'Todo list updated',
77 username: 'System',
78 todos,
79 })
80 },
81})
82
83// Global shared chat instance
84export const globalChat = new ChatLogic({
85 async onUserJoined(username) {
86 await ChatServer.broadcastToAll({
87 type: 'user_joined',
88 message: `${username} joined the chat`,
89 username,
90 onlineUsers: globalChat.getOnlineUsers(),
91 })
92 },
93
94 async onUserLeft(username) {
95 await ChatServer.broadcastToAll(
96 {
97 type: 'user_left',
98 message: `${username} left the chat`,
99 username,
100 onlineUsers: globalChat.getOnlineUsers(),
101 },
102 username,
103 )
104 },
105
106 async onMessageSent(message) {
107 await ChatServer.broadcastToAll({
108 type: 'message',
109 message: message.message,
110 username: message.username,
111 timestamp: message.timestamp,
112 id: message.id,
113 })
114 },
115})
116
117// Global registry of active RPC server instances
118export const activeServers = new Set<ChatServer>()
119
120// Chat Server Implementation (one per connection)
121export class ChatServer extends RpcTarget implements ChatApi {
122 public currentUsername: string | null = null
123 private clientNotifier: ChatNotifierApi | null = null
124
125 constructor() {
126 super()
127 activeServers.add(this)
128 console.log(`📡 Registered new chat server. Total: ${activeServers.size}`)
129 }
130
131 setClientNotifier(notifier: ChatNotifierApi) {
132 this.clientNotifier = notifier
133 }
134
135 setWebSocket(ws: WebSocket) {
136 ws.on('close', () => {
137 if (this.currentUsername) {
138 this.leaveChat()
139 console.log(`🔌 WebSocket disconnected for ${this.currentUsername}`)
140 }
141 this.dispose()
142 })
143 }
144
145 static broadcastToAll(notification: ChatNotification, excludeUser?: string) {
146 const payload = normalizeNotification(notification)
147 const msgPreview = payload.message.substring(0, 50)
148 console.log(
149 `\n📬 broadcastToAll() - type: ${payload.type}, from: ${payload.username}, message: "${msgPreview}..."`,
150 )
151 console.log(`📬 Connected users: ${Array.from(clients.keys()).join(', ')}`)
152 console.log(`📬 Exclude user: ${excludeUser || 'none'}`)
153
154 let successCount = 0
155 const successful: Array<string> = []
156
157 for (const [username, callback] of clients.entries()) {
158 if (excludeUser && username === excludeUser) {
159 console.log(`📬 Skipping excluded user: ${username}`)
160 continue
161 }
162
163 try {
164 pushNotification(callback, payload)
165 successCount++
166 successful.push(username)
167 console.log(`📬 Queued push to ${username}`)
168 } catch (error) {
169 console.error(`📬 Failed to notify ${username}:`, error)
170 }
171 }
172
173 console.log(
174 `📬 Broadcast complete: ${successCount} users notified (${successful.join(
175 ', ',
176 )})\n`,
177 )
178 return { successful, successCount }
179 }
180
181 dispose() {
182 activeServers.delete(this)
183 if (this.currentUsername) {
184 clients.delete(this.currentUsername)
185 }
186 console.log(`📡 Unregistered chat server. Total: ${activeServers.size}`)
187 }
188
189 joinChat(username: string): JoinResult {
190 console.log(`${username} is joining the chat`)
191
192 if (!this.clientNotifier) {
193 throw new Error('Client notifier not available on this connection')
194 }
195
196 const trimmed = username.trim()
197 if (!trimmed) {
198 throw new Error('Username cannot be empty')
199 }
200
201 // Same connection switching personas: leave the previous identity first
202 // so it is not left registered in `clients` (which double-delivers pushes).
203 if (this.currentUsername && this.currentUsername !== trimmed) {
204 console.log(
205 `🔄 Switching identity on connection: ${this.currentUsername} → ${trimmed}`,
206 )
207 this.leaveChat()
208 }
209
210 if (this.currentUsername === trimmed) {
211 return {
212 message: 'Already joined the chat',
213 onlineUsers: globalChat.getOnlineUsers(),
214 recentMessages: globalChat.getMessages().slice(-20),
215 todos: globalTodos.getTodos(),
216 claudeMode,
217 }
218 }
219
220 this.currentUsername = trimmed
221 clients.set(trimmed, this.clientNotifier)
222
223 globalChat.addUserSync(trimmed)
224
225 const welcomeMessage = normalizeNotification({
226 type: 'welcome',
227 message: `Welcome to the chat, ${trimmed}! 👋`,
228 username: 'System',
229 })
230
231 pushNotification(this.clientNotifier, welcomeMessage)
232
233 return {
234 message: 'Successfully joined the chat',
235 onlineUsers: globalChat.getOnlineUsers(),
236 recentMessages: globalChat.getMessages().slice(-20),
237 todos: globalTodos.getTodos(),
238 claudeMode,
239 }
240 }
241
242 leaveChat() {
243 if (!this.currentUsername) {
244 return { message: 'Not in chat' }
245 }
246
247 const username = this.currentUsername
248 console.log(`${username} is leaving the chat`)
249 globalChat.removeUserSync(username)
250 clients.delete(username)
251 this.currentUsername = null
252
253 return {
254 message: 'Successfully left the chat',
255 }
256 }
257
258 getChatState() {
259 return {
260 ...globalChat.getChatState(),
261 todos: globalTodos.getTodos(),
262 claudeMode,
263 }
264 }
265
266 getTodos(): Array<TodoItem> {
267 return globalTodos.getTodos()
268 }
269
270 addTodo(text: string) {
271 if (!this.currentUsername) {
272 throw new Error('You must join the chat first')
273 }
274
275 const todo = globalTodos.addTodo(text, this.currentUsername)
276 return {
277 todo,
278 todos: globalTodos.getTodos(),
279 }
280 }
281
282 removeTodo(id: string) {
283 if (!this.currentUsername) {
284 throw new Error('You must join the chat first')
285 }
286
287 const success = globalTodos.removeTodo(id)
288 return {
289 success,
290 todos: globalTodos.getTodos(),
291 }
292 }
293
294 getClaudeMode(): ClaudeMode {
295 return claudeMode
296 }
297
298 setClaudeMode(mode: ClaudeMode) {
299 claudeMode = mode
300 console.log(`🤖 Claude mode set to ${mode}`)
301
302 void ChatServer.broadcastToAll({
303 type: 'claude_mode_changed',
304 message: `Claude is now in ${mode} mode`,
305 username: 'System',
306 claudeMode: mode,
307 })
308
309 return { mode: claudeMode }
310 }
311
312 sendMessage(messageText: string): SendResult {
313 console.log(
314 `\n📨 [${this.currentUsername}] sendMessage called: "${messageText}"`,
315 )
316
317 if (!this.currentUsername) {
318 throw new Error('You must join the chat first')
319 }
320
321 if (!messageText.trim()) {
322 throw new Error('Message cannot be empty')
323 }
324
325 const trimmedMessage = messageText.trim()
326 const mentioned = isClaudeMention(trimmedMessage)
327 const shouldAskClaude =
328 mentioned ||
329 (claudeMode === 'active' && this.currentUsername !== 'Claude')
330
331 const message = globalChat.sendMessageSync(
332 this.currentUsername,
333 trimmedMessage,
334 )
335
336 if (shouldAskClaude) {
337 void this.enqueueClaudeRequest(trimmedMessage, mentioned)
338 return {
339 message: mentioned
340 ? 'Claude request queued'
341 : 'Message sent; Claude is watching in active mode',
342 chatMessage: message,
343 }
344 }
345
346 return {
347 message: 'Message sent successfully',
348 chatMessage: message,
349 }
350 }
351
352 private async enqueueClaudeRequest(messageText: string, mentioned: boolean) {
353 const conversationHistory = globalChat.getMessages().map((msg) => ({
354 role: 'user' as const,
355 content: `${msg.username}: ${msg.message}`,
356 }))
357
358 const claudeService = await getClaudeService()
359 claudeService.enqueue({
360 id: Math.random().toString(36).slice(2, 11),
361 username: this.currentUsername!,
362 message: messageText,
363 conversationHistory,
364 mode: claudeMode,
365 mentioned,
366 })
367
368 void this.processClaudeQueue()
369 }
370
371 private async processClaudeQueue() {
372 const claudeService = await getClaudeService()
373 const status = claudeService.getQueueStatus()
374
375 if (status.isProcessing || status.queue.length === 0) {
376 return
377 }
378
379 claudeService.startProcessing()
380 const currentRequest = claudeService.getCurrentRequest()
381 const requestMode = currentRequest?.mode ?? claudeMode
382 const mentioned = currentRequest?.mentioned ?? false
383 const showResponding = claudeService.getQueueStatus().showResponding
384
385 try {
386 // Only announce when a visible reply is expected (not active silent watches).
387 if (showResponding) {
388 await ChatServer.broadcastToAll({
389 type: 'claude_responding',
390 message: 'Claude is responding',
391 username: currentRequest?.username ?? 'System',
392 })
393 }
394
395 const conversationHistory = globalChat.getMessages().map((msg) => ({
396 role: 'user' as const,
397 content: `${msg.username}: ${msg.message}`,
398 }))
399
400 let accumulatedResponse = ''
401 for await (const chunk of claudeService.streamResponse(
402 conversationHistory,
403 requestMode,
404 mentioned,
405 )) {
406 if (chunk.type === 'TEXT_MESSAGE_CONTENT' && chunk.delta) {
407 accumulatedResponse += chunk.delta
408 }
409 }
410
411 if (!isNoReply(accumulatedResponse) && accumulatedResponse.trim()) {
412 await globalChat.sendMessage('Claude', accumulatedResponse.trim())
413 } else {
414 console.log('🤖 Claude: Skipping empty / NO_REPLY response')
415 }
416 } catch (error) {
417 console.error('Error in processClaudeQueue:', error)
418
419 await ChatServer.broadcastToAll({
420 type: 'claude_error',
421 message: 'Claude encountered an error responding',
422 username: 'System',
423 })
424 } finally {
425 claudeService.finishProcessing()
426 // Clear any "responding" UI state (not shown as a chat line).
427 await ChatServer.broadcastToAll({
428 type: 'claude_idle',
429 message: 'Claude finished',
430 username: 'System',
431 })
432 void this.processClaudeQueue()
433 }
434 }
435
436 getClaudeQueueStatus(): ClaudeQueueStatus {
437 if (!globalClaudeService) {
438 return {
439 current: null,
440 queue: [],
441 isProcessing: false,
442 showResponding: false,
443 }
444 }
445
446 return globalClaudeService.getQueueStatus()
447 }
448}