-
Notifications
You must be signed in to change notification settings - Fork 416
Expand file tree
/
Copy pathuseSpecChat.ts
More file actions
474 lines (414 loc) · 14.1 KB
/
useSpecChat.ts
File metadata and controls
474 lines (414 loc) · 14.1 KB
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
/**
* Hook for managing spec creation chat WebSocket connection
*/
import { useState, useCallback, useRef, useEffect } from 'react'
import type { ChatMessage, ImageAttachment, SpecChatServerMessage, SpecQuestion } from '../lib/types'
import { getSpecStatus } from '../lib/api'
type ConnectionStatus = 'disconnected' | 'connecting' | 'connected' | 'error'
interface UseSpecChatOptions {
projectName: string
onComplete?: (specPath: string) => void
onError?: (error: string) => void
}
interface UseSpecChatReturn {
messages: ChatMessage[]
isLoading: boolean
isComplete: boolean
connectionStatus: ConnectionStatus
currentQuestions: SpecQuestion[] | null
currentToolId: string | null
start: () => void
sendMessage: (content: string, attachments?: ImageAttachment[]) => void
sendAnswer: (answers: Record<string, string | string[]>) => void
disconnect: () => void
}
function generateId(): string {
return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`
}
export function useSpecChat({
projectName,
// onComplete intentionally not used - user clicks "Continue to Project" button instead
onError,
}: UseSpecChatOptions): UseSpecChatReturn {
const [messages, setMessages] = useState<ChatMessage[]>([])
const [isLoading, setIsLoading] = useState(false)
const [isComplete, setIsComplete] = useState(false)
const [connectionStatus, setConnectionStatus] = useState<ConnectionStatus>('disconnected')
const [currentQuestions, setCurrentQuestions] = useState<SpecQuestion[] | null>(null)
const [currentToolId, setCurrentToolId] = useState<string | null>(null)
const wsRef = useRef<WebSocket | null>(null)
const currentAssistantMessageRef = useRef<string | null>(null)
const reconnectAttempts = useRef(0)
const maxReconnectAttempts = 3
const pingIntervalRef = useRef<number | null>(null)
const reconnectTimeoutRef = useRef<number | null>(null)
const isCompleteRef = useRef(false)
// Keep isCompleteRef in sync with isComplete state
useEffect(() => {
isCompleteRef.current = isComplete
}, [isComplete])
// Clean up on unmount
useEffect(() => {
return () => {
if (pingIntervalRef.current) {
clearInterval(pingIntervalRef.current)
}
if (reconnectTimeoutRef.current) {
clearTimeout(reconnectTimeoutRef.current)
}
if (wsRef.current) {
wsRef.current.close()
}
}
}, [])
// Poll status file as fallback completion detection
// Claude writes .spec_status.json when done with all spec work
useEffect(() => {
// Don't poll if already complete
if (isComplete) return
// Start polling after initial delay (let WebSocket try first)
const startDelay = setTimeout(() => {
const pollInterval = setInterval(async () => {
// Stop if already complete
if (isCompleteRef.current) {
clearInterval(pollInterval)
return
}
try {
const status = await getSpecStatus(projectName)
if (status.exists && status.status === 'complete') {
// Status file indicates completion - set complete state
setIsComplete(true)
setIsLoading(false)
// Mark any streaming message as done
setMessages((prev) => {
const lastMessage = prev[prev.length - 1]
if (lastMessage?.role === 'assistant' && lastMessage.isStreaming) {
return [
...prev.slice(0, -1),
{ ...lastMessage, isStreaming: false },
]
}
return prev
})
// Add system message about completion
setMessages((prev) => [
...prev,
{
id: generateId(),
role: 'system',
content: `Spec creation complete! Files written: ${status.files_written.join(', ')}${status.feature_count ? ` (${status.feature_count} features)` : ''}`,
timestamp: new Date(),
},
])
clearInterval(pollInterval)
}
} catch {
// Silently ignore polling errors - WebSocket is primary mechanism
}
}, 3000) // Poll every 3 seconds
// Cleanup interval on unmount
return () => clearInterval(pollInterval)
}, 3000) // Start polling after 3 second delay
return () => clearTimeout(startDelay)
}, [projectName, isComplete])
const connect = useCallback(() => {
if (wsRef.current?.readyState === WebSocket.OPEN) {
return
}
setConnectionStatus('connecting')
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
const host = window.location.host
const wsUrl = `${protocol}//${host}/api/spec/ws/${encodeURIComponent(projectName)}`
const ws = new WebSocket(wsUrl)
wsRef.current = ws
ws.onopen = () => {
setConnectionStatus('connected')
reconnectAttempts.current = 0
// Start ping interval to keep connection alive
pingIntervalRef.current = window.setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'ping' }))
}
}, 30000)
}
ws.onclose = (event) => {
setConnectionStatus('disconnected')
if (pingIntervalRef.current) {
clearInterval(pingIntervalRef.current)
pingIntervalRef.current = null
}
// Don't retry on application-level errors (4xxx codes won't resolve on retry)
const isAppError = event.code >= 4000 && event.code <= 4999
// Attempt reconnection if not intentionally closed
if (!isAppError && reconnectAttempts.current < maxReconnectAttempts && !isCompleteRef.current) {
reconnectAttempts.current++
const delay = Math.min(1000 * Math.pow(2, reconnectAttempts.current), 10000)
reconnectTimeoutRef.current = window.setTimeout(connect, delay)
}
}
ws.onerror = () => {
setConnectionStatus('error')
onError?.('WebSocket connection error')
}
ws.onmessage = (event) => {
try {
const data = JSON.parse(event.data) as SpecChatServerMessage
switch (data.type) {
case 'text': {
// Append text to current assistant message or create new one
setMessages((prev) => {
const lastMessage = prev[prev.length - 1]
if (lastMessage?.role === 'assistant' && lastMessage.isStreaming) {
// Append to existing streaming message
return [
...prev.slice(0, -1),
{
...lastMessage,
content: lastMessage.content + data.content,
},
]
} else {
// Create new assistant message
currentAssistantMessageRef.current = generateId()
return [
...prev,
{
id: currentAssistantMessageRef.current,
role: 'assistant',
content: data.content,
timestamp: new Date(),
isStreaming: true,
},
]
}
})
break
}
case 'question': {
// Show structured question UI
setCurrentQuestions(data.questions)
setCurrentToolId(data.tool_id || null)
setIsLoading(false)
// Mark current message as done streaming
setMessages((prev) => {
const lastMessage = prev[prev.length - 1]
if (lastMessage?.role === 'assistant' && lastMessage.isStreaming) {
return [
...prev.slice(0, -1),
{
...lastMessage,
isStreaming: false,
questions: data.questions,
},
]
}
return prev
})
break
}
case 'spec_complete': {
setIsComplete(true)
setIsLoading(false)
// Mark current message as done
setMessages((prev) => {
const lastMessage = prev[prev.length - 1]
if (lastMessage?.role === 'assistant' && lastMessage.isStreaming) {
return [
...prev.slice(0, -1),
{ ...lastMessage, isStreaming: false },
]
}
return prev
})
// Add system message about spec completion
setMessages((prev) => [
...prev,
{
id: generateId(),
role: 'system',
content: `Specification file created: ${data.path}`,
timestamp: new Date(),
},
])
// NOTE: Do NOT auto-call onComplete here!
// User should click "Continue to Project" button to start the agent.
// This matches the CLI behavior where user closes the chat manually.
break
}
case 'file_written': {
// Optional: notify about other files being written
setMessages((prev) => [
...prev,
{
id: generateId(),
role: 'system',
content: `File created: ${data.path}`,
timestamp: new Date(),
},
])
break
}
case 'complete': {
setIsComplete(true)
setIsLoading(false)
// Mark current message as done
setMessages((prev) => {
const lastMessage = prev[prev.length - 1]
if (lastMessage?.role === 'assistant' && lastMessage.isStreaming) {
return [
...prev.slice(0, -1),
{ ...lastMessage, isStreaming: false },
]
}
return prev
})
break
}
case 'error': {
setIsLoading(false)
onError?.(data.content)
// Add error as system message
setMessages((prev) => [
...prev,
{
id: generateId(),
role: 'system',
content: `Error: ${data.content}`,
timestamp: new Date(),
},
])
break
}
case 'pong': {
// Keep-alive response, nothing to do
break
}
case 'response_done': {
// Response complete - hide loading indicator and mark message as done
setIsLoading(false)
// Mark current message as done streaming
setMessages((prev) => {
const lastMessage = prev[prev.length - 1]
if (lastMessage?.role === 'assistant' && lastMessage.isStreaming) {
return [
...prev.slice(0, -1),
{ ...lastMessage, isStreaming: false },
]
}
return prev
})
break
}
}
} catch (e) {
console.error('Failed to parse WebSocket message:', e)
}
}
}, [projectName, onError])
const start = useCallback(() => {
connect()
// Wait for connection then send start message
const checkAndSend = () => {
if (wsRef.current?.readyState === WebSocket.OPEN) {
setIsLoading(true)
wsRef.current.send(JSON.stringify({ type: 'start' }))
} else if (wsRef.current?.readyState === WebSocket.CONNECTING) {
setTimeout(checkAndSend, 100)
}
}
setTimeout(checkAndSend, 100)
}, [connect])
const sendMessage = useCallback((content: string, attachments?: ImageAttachment[]) => {
if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) {
onError?.('Not connected')
return
}
// Add user message to chat (with attachments for display)
setMessages((prev) => [
...prev,
{
id: generateId(),
role: 'user',
content,
attachments,
timestamp: new Date(),
},
])
// Clear current questions
setCurrentQuestions(null)
setCurrentToolId(null)
setIsLoading(true)
// Build message payload
const payload: { type: string; content: string; attachments?: Array<{ filename: string; mimeType: string; base64Data: string }> } = {
type: 'message',
content,
}
// Add attachments if present (send base64 data, not preview URL)
if (attachments && attachments.length > 0) {
payload.attachments = attachments.map((a) => ({
filename: a.filename,
mimeType: a.mimeType,
base64Data: a.base64Data,
}))
}
// Send to server
wsRef.current.send(JSON.stringify(payload))
}, [onError])
const sendAnswer = useCallback((answers: Record<string, string | string[]>) => {
if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) {
onError?.('Not connected')
return
}
// Format answers for display
const answerText = Object.values(answers)
.map((v) => (Array.isArray(v) ? v.join(', ') : v))
.join('; ')
// Add user message
setMessages((prev) => [
...prev,
{
id: generateId(),
role: 'user',
content: answerText,
timestamp: new Date(),
},
])
// Clear current questions
setCurrentQuestions(null)
setCurrentToolId(null)
setIsLoading(true)
// Send to server
wsRef.current.send(
JSON.stringify({
type: 'answer',
answers,
tool_id: currentToolId,
})
)
}, [currentToolId, onError])
const disconnect = useCallback(() => {
reconnectAttempts.current = maxReconnectAttempts // Prevent reconnection
if (pingIntervalRef.current) {
clearInterval(pingIntervalRef.current)
pingIntervalRef.current = null
}
if (wsRef.current) {
wsRef.current.close()
wsRef.current = null
}
setConnectionStatus('disconnected')
}, [])
return {
messages,
isLoading,
isComplete,
connectionStatus,
currentQuestions,
currentToolId,
start,
sendMessage,
sendAnswer,
disconnect,
}
}