Open History to see the last commit
1import { renderHook, waitFor } from '@solidjs/testing-library'
2import { ChatClient } from '@tanstack/ai-client'
3import { describe, expect, it, vi } from 'vitest'
4import { useChat } from '../src/use-chat'
5import {
6 createInterruptResumeSnapshot,
7 createMockConnectionAdapter,
8 createTextChunks,
9 createToolCallChunks,
10 renderUseChat,
11} from './test-utils'
12import type { UIMessage } from '../src/types'
13import type { ModelMessage } from '@tanstack/ai'
14
15describe('useChat', () => {
16 describe('interrupt state', () => {
17 it('projects one immutable reactive snapshot with the deprecated pending alias', async () => {
18 const onInterruptStateChange = vi.fn()
19 const rendered = renderHook(() =>
20 useChat({
21 connection: createMockConnectionAdapter(),
22 initialResumeSnapshot: createInterruptResumeSnapshot(),
23 onInterruptStateChange,
24 }),
25 )
26 const chat = rendered.result
27
28 expect(Object.isFrozen(chat.interrupts())).toBe(true)
29 expect(chat.pendingInterrupts()).toBe(chat.interrupts())
30 expect(chat.interrupts()[0]).toMatchObject({
31 id: 'staged-interrupt',
32 status: 'pending',
33 })
34 expect(chat.interrupts()[1]).toMatchObject({
35 id: 'invalid-interrupt',
36 status: 'pending',
37 })
38 expect(chat.interruptErrors()).toEqual([])
39 expect(chat.resuming()).toBe(false)
40 expect(chat.interrupts()[0]).toEqual(
41 expect.objectContaining({
42 resolveInterrupt: expect.any(Function),
43 cancel: expect.any(Function),
44 clearResolution: expect.any(Function),
45 }),
46 )
47
48 chat.resolveInterrupts(false)
49 await waitFor(() => {
50 expect(chat.interruptErrors()[0]?.code).toBe(
51 'unsupported-bulk-operation',
52 )
53 })
54 expect(onInterruptStateChange).toHaveBeenLastCalledWith(
55 expect.objectContaining({
56 interrupts: chat.interrupts(),
57 interruptErrors: chat.interruptErrors(),
58 }),
59 { source: 'live' },
60 )
61 })
62
63 it('delegates every root interrupt control to ChatClient', async () => {
64 const resolve = vi
65 .spyOn(ChatClient.prototype, 'resolveInterrupts')
66 .mockImplementation(() => {})
67 const cancel = vi
68 .spyOn(ChatClient.prototype, 'cancelInterrupts')
69 .mockImplementation(() => {})
70 const retry = vi
71 .spyOn(ChatClient.prototype, 'retryInterrupts')
72 .mockImplementation(() => {})
73 const unsafe = vi
74 .spyOn(ChatClient.prototype, 'resumeInterruptsUnsafe')
75 .mockResolvedValue(true)
76 const rendered = renderHook(() =>
77 useChat({ connection: createMockConnectionAdapter() }),
78 )
79 const chat = rendered.result
80 const resolver = () => undefined
81 const resume = [{ interruptId: 'one', status: 'cancelled' as const }]
82
83 chat.resolveInterrupts(resolver)
84 chat.cancelInterrupts()
85 chat.retryInterrupts()
86 await expect(chat.resumeInterruptsUnsafe(resume)).resolves.toBe(true)
87
88 expect(resolve).toHaveBeenCalledWith(resolver)
89 expect(cancel).toHaveBeenCalledOnce()
90 expect(retry).toHaveBeenCalledOnce()
91 expect(unsafe).toHaveBeenCalledWith(resume, undefined)
92 })
93 })
94
95 describe('initialization', () => {
96 it('should initialize with default state', () => {
97 const adapter = createMockConnectionAdapter()
98 const { result } = renderUseChat({ connection: adapter })
99
100 expect(result.current.messages).toEqual([])
101 expect(result.current.isLoading).toBe(false)
102 expect(result.current.error).toBeUndefined()
103 expect(result.current.status).toBe('ready')
104 expect(result.current.isSubscribed).toBe(false)
105 expect(result.current.connectionStatus).toBe('disconnected')
106 expect(result.current.sessionGenerating).toBe(false)
107 })
108
109 it('should subscribe immediately when live is true', async () => {
110 const adapter = createMockConnectionAdapter()
111 const { result } = renderUseChat({ connection: adapter, live: true })
112
113 await waitFor(() => {
114 expect(result.current.isSubscribed).toBe(true)
115 })
116 expect(['connecting', 'connected']).toContain(
117 result.current.connectionStatus,
118 )
119 })
120
121 it('should initialize with provided messages', () => {
122 const adapter = createMockConnectionAdapter()
123 const initialMessages: Array<UIMessage> = [
124 {
125 id: 'msg-1',
126 role: 'user',
127 parts: [{ type: 'text', content: 'Hello' }],
128 createdAt: new Date(),
129 },
130 ]
131
132 const { result } = renderUseChat({
133 connection: adapter,
134 initialMessages,
135 })
136
137 expect(result.current.messages).toEqual(initialMessages)
138 })
139
140 it('should initialize with persisted messages', async () => {
141 const adapter = createMockConnectionAdapter()
142 const persistedMessages: Array<UIMessage> = [
143 {
144 id: 'persisted-1',
145 role: 'user',
146 parts: [{ type: 'text', content: 'Persisted' }],
147 createdAt: new Date(),
148 },
149 ]
150 const persistence = {
151 getItem: vi.fn(() => persistedMessages),
152 setItem: vi.fn(),
153 removeItem: vi.fn(),
154 }
155
156 const { result } = renderUseChat({
157 connection: adapter,
158 threadId: 'persisted-chat',
159 persistence: persistence,
160 })
161
162 await waitFor(() => {
163 expect(result.current.messages).toEqual(persistedMessages)
164 })
165 expect(persistence.getItem).toHaveBeenCalledWith('persisted-chat')
166 })
167
168 it('should preserve persisted empty messages over provided initial messages', async () => {
169 const adapter = createMockConnectionAdapter()
170 const initialMessages: Array<UIMessage> = [
171 {
172 id: 'initial-1',
173 role: 'user',
174 parts: [{ type: 'text', content: 'Initial' }],
175 createdAt: new Date(),
176 },
177 ]
178 const persistence = {
179 getItem: vi.fn(() => []),
180 setItem: vi.fn(),
181 removeItem: vi.fn(),
182 }
183
184 const { result } = renderUseChat({
185 connection: adapter,
186 threadId: 'persisted-empty-chat',
187 initialMessages,
188 persistence: persistence,
189 })
190
191 await waitFor(() => {
192 expect(persistence.getItem).toHaveBeenCalledWith('persisted-empty-chat')
193 })
194 expect(result.current.messages).toEqual([])
195 })
196
197 it('should use provided threadId', async () => {
198 const chunks = createTextChunks('Response')
199 const adapter = createMockConnectionAdapter({ chunks })
200
201 const { result } = renderUseChat({
202 connection: adapter,
203 threadId: 'custom-id',
204 })
205
206 await result.current.sendMessage('Test')
207
208 await waitFor(() => {
209 expect(result.current.messages.length).toBeGreaterThan(0)
210 })
211
212 // Message IDs are generated independently, not based on client ID
213 // Just verify messages exist and have IDs
214 const messageId = result.current.messages[0]!.id
215 expect(messageId).toBeDefined()
216 expect(typeof messageId).toBe('string')
217 })
218
219 it('should generate id if not provided', async () => {
220 const chunks = createTextChunks('Response')
221 const adapter = createMockConnectionAdapter({ chunks })
222
223 const { result } = renderUseChat({ connection: adapter })
224
225 await result.current.sendMessage('Test')
226
227 await waitFor(() => {
228 expect(result.current.messages.length).toBeGreaterThan(0)
229 })
230
231 // Message IDs should have a generated prefix (not "custom-id-")
232 const messageId = result.current.messages[0]!.id
233 expect(messageId).toBeTruthy()
234 expect(messageId).not.toMatch(/^custom-id-/)
235 })
236
237 it('should maintain client instance across re-renders', () => {
238 const adapter = createMockConnectionAdapter()
239 const { result, rerender } = renderUseChat({ connection: adapter })
240
241 const initialMessages = result.current.messages
242
243 rerender()
244
245 // Client should be the same instance, state should persist
246 expect(result.current.messages).toBe(initialMessages)
247 })
248 })
249
250 describe('state synchronization', () => {
251 it('should update messages via onMessagesChange callback', async () => {
252 const chunks = createTextChunks('Hello, world!')
253 const adapter = createMockConnectionAdapter({ chunks })
254 const { result } = renderUseChat({ connection: adapter })
255
256 await result.current.sendMessage('Hello')
257
258 await waitFor(() => {
259 expect(result.current.messages.length).toBeGreaterThanOrEqual(2)
260 })
261
262 const userMessage = result.current.messages.find((m) => m.role === 'user')
263 expect(userMessage).toBeDefined()
264 if (userMessage) {
265 expect(userMessage.parts[0]).toEqual({
266 type: 'text',
267 content: 'Hello',
268 })
269 }
270 })
271
272 it('should update loading state via onLoadingChange callback', async () => {
273 const chunks = createTextChunks('Response')
274 const adapter = createMockConnectionAdapter({
275 chunks,
276 chunkDelay: 50,
277 })
278 const { result } = renderUseChat({ connection: adapter })
279
280 expect(result.current.isLoading).toBe(false)
281
282 const sendPromise = result.current.sendMessage('Test')
283
284 // Should be loading during send
285 await waitFor(() => {
286 expect(result.current.isLoading).toBe(true)
287 })
288
289 await sendPromise
290
291 // Should not be loading after completion
292 await waitFor(() => {
293 expect(result.current.isLoading).toBe(false)
294 })
295 })
296
297 it('should update error state via onErrorChange callback', async () => {
298 const error = new Error('Connection failed')
299 const adapter = createMockConnectionAdapter({
300 shouldError: true,
301 error,
302 })
303 const { result } = renderUseChat({ connection: adapter })
304
305 await result.current.sendMessage('Test')
306
307 await waitFor(() => {
308 expect(result.current.error).toBeDefined()
309 })
310
311 expect(result.current.error?.message).toBe('Connection failed')
312 })
313
314 it('should persist state across re-renders', async () => {
315 const chunks = createTextChunks('Response')
316 const adapter = createMockConnectionAdapter({ chunks })
317 const { result, rerender } = renderUseChat({ connection: adapter })
318
319 await result.current.sendMessage('Hello')
320
321 await waitFor(() => {
322 expect(result.current.messages.length).toBeGreaterThan(0)
323 })
324
325 const messageCount = result.current.messages.length
326
327 rerender()
328
329 // State should persist after re-render
330 expect(result.current.messages.length).toBe(messageCount)
331 })
332 })
333
334 describe('sendMessage', () => {
335 it('should send a message and append it', async () => {
336 const chunks = createTextChunks('Hello, world!')
337 const adapter = createMockConnectionAdapter({ chunks })
338 const { result } = renderUseChat({ connection: adapter })
339
340 await result.current.sendMessage('Hello')
341
342 await waitFor(() => {
343 expect(result.current.messages.length).toBeGreaterThan(0)
344 })
345
346 const userMessage = result.current.messages.find((m) => m.role === 'user')
347 expect(userMessage).toBeDefined()
348 if (userMessage) {
349 expect(userMessage.parts[0]).toEqual({
350 type: 'text',
351 content: 'Hello',
352 })
353 }
354 })
355
356 it('should merge sendMessage options.body into the request', async () => {
357 const chunks = createTextChunks('Response')
358 let capturedData: Record<string, unknown> | undefined
359 const adapter = createMockConnectionAdapter({
360 chunks,
361 onConnect: (_messages, data) => {
362 capturedData = data
363 },
364 })
365
366 const { result } = renderUseChat({
367 connection: adapter,
368 body: { provider: 'openai' },
369 })
370
371 await result.current.sendMessage('Test', {
372 whenBusy: 'queue',
373 body: { provider: 'anthropic', attachmentIds: ['a1', 'a2'] },
374 })
375
376 await waitFor(() => {
377 expect(result.current.messages.length).toBeGreaterThan(0)
378 })
379
380 expect(capturedData?.['provider']).toBe('anthropic')
381 expect(capturedData?.['attachmentIds']).toEqual(['a1', 'a2'])
382 expect(capturedData?.['whenBusy']).toBeUndefined()
383 })
384
385 it('should create assistant message from stream chunks', async () => {
386 const chunks = createTextChunks('Hello, world!')
387 const adapter = createMockConnectionAdapter({ chunks })
388 const { result } = renderUseChat({ connection: adapter })
389
390 await result.current.sendMessage('Hello')
391
392 await waitFor(() => {
393 const assistantMessage = result.current.messages.find(
394 (m) => m.role === 'assistant',
395 )
396 expect(assistantMessage).toBeDefined()
397 })
398
399 const assistantMessage = result.current.messages.find(
400 (m) => m.role === 'assistant',
401 )
402 expect(assistantMessage).toBeDefined()
403 if (assistantMessage) {
404 const textPart = assistantMessage.parts.find((p) => p.type === 'text')
405 expect(textPart).toBeDefined()
406 if (textPart && textPart.type === 'text') {
407 expect(textPart.content).toBe('Hello, world!')
408 }
409 }
410 })
411
412 it('should not send empty messages', async () => {
413 const adapter = createMockConnectionAdapter()
414 const { result } = renderUseChat({ connection: adapter })
415
416 await result.current.sendMessage('')
417 await result.current.sendMessage(' ')
418
419 expect(result.current.messages.length).toBe(0)
420 })
421
422 it('should queue a message sent while loading and send it after', async () => {
423 const adapter = createMockConnectionAdapter({
424 chunks: createTextChunks('Response'),
425 chunkDelay: 100,
426 })
427 const { result } = renderUseChat({ connection: adapter })
428
429 const promise1 = result.current.sendMessage('First')
430 const promise2 = result.current.sendMessage('Second')
431
432 await Promise.all([promise1, promise2])
433
434 // The second send is queued (default `whenBusy: 'queue'`) while the
435 // first stream is in flight, then auto-drains once it settles — both
436 // end up sent, in order.
437 const userMessages = result.current.messages.filter(
438 (m) => m.role === 'user',
439 )
440 expect(userMessages.map((m) => m.parts[0])).toEqual([
441 { type: 'text', content: 'First' },
442 { type: 'text', content: 'Second' },
443 ])
444 })
445
446 it('should handle errors during sendMessage', async () => {
447 const error = new Error('Network error')
448 const adapter = createMockConnectionAdapter({
449 shouldError: true,
450 error,
451 })
452 const { result } = renderUseChat({ connection: adapter })
453
454 await result.current.sendMessage('Test')
455
456 await waitFor(() => {
457 expect(result.current.error).toBeDefined()
458 })
459
460 expect(result.current.error?.message).toBe('Network error')
461 expect(result.current.isLoading).toBe(false)
462 })
463 })
464
465 describe('append', () => {
466 it('should append a UIMessage', async () => {
467 const chunks = createTextChunks('Response')
468 const adapter = createMockConnectionAdapter({ chunks })
469 const { result } = renderUseChat({ connection: adapter })
470
471 const message: UIMessage = {
472 id: 'user-1',
473 role: 'user',
474 parts: [{ type: 'text', content: 'Hello' }],
475 createdAt: new Date(),
476 }
477
478 await result.current.append(message)
479
480 await waitFor(() => {
481 expect(result.current.messages.length).toBeGreaterThan(0)
482 })
483
484 expect(result.current.messages[0]!.id).toBe('user-1')
485 })
486
487 it('should convert and append a ModelMessage', async () => {
488 const chunks = createTextChunks('Response')
489 const adapter = createMockConnectionAdapter({ chunks })
490 const { result } = renderUseChat({ connection: adapter })
491
492 const modelMessage: ModelMessage = {
493 role: 'user',
494 content: 'Hello from model',
495 }
496
497 await result.current.append(modelMessage)
498
499 await waitFor(() => {
500 expect(result.current.messages.length).toBeGreaterThan(0)
501 })
502
503 expect(result.current.messages[0]!.role).toBe('user')
504 expect(result.current.messages[0]!.parts[0]).toEqual({
505 type: 'text',
506 content: 'Hello from model',
507 })
508 })
509
510 it('should handle errors during append', async () => {
511 const error = new Error('Append failed')
512 const adapter = createMockConnectionAdapter({
513 shouldError: true,
514 error,
515 })
516 const { result } = renderUseChat({ connection: adapter })
517
518 const message: UIMessage = {
519 id: 'msg-1',
520 role: 'user',
521 parts: [{ type: 'text', content: 'Hello' }],
522 createdAt: new Date(),
523 }
524
525 await result.current.append(message)
526
527 await waitFor(() => {
528 expect(result.current.error).toBeDefined()
529 })
530
531 expect(result.current.error?.message).toBe('Append failed')
532 })
533 })
534
535 describe('reload', () => {
536 it('should reload the last assistant message', async () => {
537 const chunks1 = createTextChunks('First response')
538 const chunks2 = createTextChunks('Second response')
539 let callCount = 0
540
541 const adapter = createMockConnectionAdapter({
542 chunks: chunks1,
543 onConnect: () => {
544 callCount++
545 // Return different chunks on second call
546 if (callCount === 2) {
547 return chunks2
548 }
549 return undefined
550 },
551 })
552
553 // Create a new adapter for the second call
554 const adapter2 = createMockConnectionAdapter({ chunks: chunks2 })
555 const { result, rerender } = renderUseChat({ connection: adapter })
556
557 await result.current.sendMessage('Hello')
558
559 await waitFor(() => {
560 const assistantMessage = result.current.messages.find(
561 (m) => m.role === 'assistant',
562 )
563 expect(assistantMessage).toBeDefined()
564 })
565
566 // Reload with new adapter
567 rerender({ connection: adapter2 })
568 await result.current.reload()
569
570 await waitFor(() => {
571 const assistantMessage = result.current.messages.find(
572 (m) => m.role === 'assistant',
573 )
574 expect(assistantMessage).toBeDefined()
575 })
576
577 // Should have reloaded (though content might be same if adapter doesn't change)
578 const messagesAfterReload = result.current.messages
579 expect(messagesAfterReload.length).toBeGreaterThan(0)
580 })
581
582 it('should maintain conversation history after reload', async () => {
583 const chunks = createTextChunks('Response')
584 const adapter = createMockConnectionAdapter({ chunks })
585 const { result } = renderUseChat({ connection: adapter })
586
587 await result.current.sendMessage('First')
588 await waitFor(() => {
589 expect(result.current.messages.length).toBeGreaterThanOrEqual(2)
590 })
591
592 const messageCountBeforeReload = result.current.messages.length
593
594 await result.current.reload()
595
596 await waitFor(() => {
597 // Should still have the same number of messages (user + assistant)
598 expect(result.current.messages.length).toBeGreaterThanOrEqual(2)
599 })
600
601 // History should be maintained
602 expect(result.current.messages.length).toBeGreaterThanOrEqual(
603 messageCountBeforeReload,
604 )
605 })
606
607 it('should handle errors during reload', async () => {
608 const chunks = createTextChunks('Response')
609 const adapter = createMockConnectionAdapter({ chunks })
610 const { result } = renderUseChat({ connection: adapter })
611
612 await result.current.sendMessage('Hello')
613 await waitFor(() => {
614 expect(result.current.messages.length).toBeGreaterThanOrEqual(2)
615 })
616
617 // Note: We can't easily change the adapter after creation,
618 // so this test verifies error handling in general
619 // The actual error would come from the connection adapter
620 expect(result.current.reload).toBeDefined()
621 })
622 })
623
624 describe('stop', () => {
625 it('should stop current generation', async () => {
626 const chunks = createTextChunks('Long response that will be stopped')
627 const adapter = createMockConnectionAdapter({
628 chunks,
629 chunkDelay: 50,
630 })
631 const { result } = renderUseChat({ connection: adapter })
632
633 const sendPromise = result.current.sendMessage('Test')
634
635 // Wait for loading to start
636 await waitFor(() => {
637 expect(result.current.isLoading).toBe(true)
638 })
639
640 // Stop the generation
641 result.current.stop()
642
643 await sendPromise
644
645 // Should eventually stop loading
646 await waitFor(
647 () => {
648 expect(result.current.isLoading).toBe(false)
649 expect(result.current.status).toBe('ready')
650 },
651 { timeout: 1000 },
652 )
653 })
654
655 it('should be safe to call multiple times', () => {
656 const adapter = createMockConnectionAdapter()
657 const { result } = renderUseChat({ connection: adapter })
658
659 // Should not throw
660 result.current.stop()
661 result.current.stop()
662 result.current.stop()
663
664 expect(result.current.isLoading).toBe(false)
665 expect(result.current.status).toBe('ready')
666 })
667
668 it('should clear loading state when stopped', async () => {
669 const chunks = createTextChunks('Response')
670 const adapter = createMockConnectionAdapter({
671 chunks,
672 chunkDelay: 50,
673 })
674 const { result } = renderUseChat({ connection: adapter })
675
676 const sendPromise = result.current.sendMessage('Test')
677
678 await waitFor(() => {
679 expect(result.current.isLoading).toBe(true)
680 })
681
682 result.current.stop()
683
684 await waitFor(
685 () => {
686 expect(result.current.isLoading).toBe(false)
687 expect(result.current.status).toBe('ready')
688 },
689 { timeout: 1000 },
690 )
691
692 await sendPromise.catch(() => {
693 // Ignore errors from stopped request
694 })
695 })
696 })
697
698 describe('status', () => {
699 it('should transition through states during generation', async () => {
700 const chunks = createTextChunks('Response')
701 const adapter = createMockConnectionAdapter({
702 chunks,
703 chunkDelay: 50,
704 })
705 const { result } = renderUseChat({ connection: adapter })
706
707 const sendPromise = result.current.sendMessage('Test')
708
709 // Should leave ready state
710 await waitFor(() => {
711 expect(result.current.status).not.toBe('ready')
712 })
713
714 // Should be submitted or streaming
715 expect(['submitted', 'streaming']).toContain(result.current.status)
716
717 // Should eventually match streaming
718 await waitFor(() => {
719 expect(result.current.status).toBe('streaming')
720 })
721
722 await sendPromise
723
724 // Should return to ready
725 await waitFor(() => {
726 expect(result.current.status).toBe('ready')
727 })
728 })
729 })
730
731 describe('clear', () => {
732 it('should clear all messages', async () => {
733 const chunks = createTextChunks('Response')
734 const adapter = createMockConnectionAdapter({ chunks })
735 const { result } = renderUseChat({ connection: adapter })
736
737 await result.current.sendMessage('Hello')
738 await waitFor(() => {
739 expect(result.current.messages.length).toBeGreaterThan(0)
740 })
741
742 result.current.clear()
743
744 expect(result.current.messages).toEqual([])
745 })
746
747 it('should reset to initial state', async () => {
748 const initialMessages: Array<UIMessage> = [
749 {
750 id: 'msg-1',
751 role: 'user',
752 parts: [{ type: 'text', content: 'Initial' }],
753 createdAt: new Date(),
754 },
755 ]
756
757 const chunks = createTextChunks('Response')
758 const adapter = createMockConnectionAdapter({ chunks })
759 const { result } = renderUseChat({
760 connection: adapter,
761 initialMessages,
762 })
763
764 await result.current.sendMessage('Hello')
765 await waitFor(() => {
766 expect(result.current.messages.length).toBeGreaterThan(
767 initialMessages.length,
768 )
769 })
770
771 result.current.clear()
772
773 // Should clear all messages, not reset to initial
774 expect(result.current.messages).toEqual([])
775 })
776
777 it('should maintain client instance after clear', async () => {
778 const chunks = createTextChunks('Response')
779 const adapter = createMockConnectionAdapter({ chunks })
780 const { result } = renderUseChat({ connection: adapter })
781
782 await result.current.sendMessage('Hello')
783 await waitFor(() => {
784 expect(result.current.messages.length).toBeGreaterThan(0)
785 })
786
787 result.current.clear()
788
789 // Should still be able to send messages
790 await result.current.sendMessage('New message')
791 await waitFor(() => {
792 expect(result.current.messages.length).toBeGreaterThan(0)
793 })
794 })
795 })
796
797 describe('setMessages', () => {
798 it('should manually set messages', () => {
799 const adapter = createMockConnectionAdapter()
800 const { result } = renderUseChat({ connection: adapter })
801
802 const newMessages: Array<UIMessage> = [
803 {
804 id: 'msg-1',
805 role: 'user',
806 parts: [{ type: 'text', content: 'Manual' }],
807 createdAt: new Date(),
808 },
809 ]
810
811 result.current.setMessages(newMessages)
812
813 expect(result.current.messages).toEqual(newMessages)
814 })
815
816 it('should update state immediately', () => {
817 const adapter = createMockConnectionAdapter()
818 const { result } = renderUseChat({ connection: adapter })
819
820 expect(result.current.messages).toEqual([])
821
822 const newMessages: Array<UIMessage> = [
823 {
824 id: 'msg-1',
825 role: 'user',
826 parts: [{ type: 'text', content: 'Immediate' }],
827 createdAt: new Date(),
828 },
829 ]
830
831 result.current.setMessages(newMessages)
832
833 // Should be updated synchronously
834 expect(result.current.messages).toEqual(newMessages)
835 })
836
837 it('should replace all existing messages', async () => {
838 const chunks = createTextChunks('Response')
839 const adapter = createMockConnectionAdapter({ chunks })
840 const { result } = renderUseChat({ connection: adapter })
841
842 await result.current.sendMessage('Hello')
843 await waitFor(() => {
844 expect(result.current.messages.length).toBeGreaterThan(0)
845 })
846
847 const originalCount = result.current.messages.length
848
849 const newMessages: Array<UIMessage> = [
850 {
851 id: 'msg-new',
852 role: 'user',
853 parts: [{ type: 'text', content: 'Replaced' }],
854 createdAt: new Date(),
855 },
856 ]
857
858 result.current.setMessages(newMessages)
859
860 expect(result.current.messages).toEqual(newMessages)
861 expect(result.current.messages.length).toBe(1)
862 expect(result.current.messages.length).not.toBe(originalCount)
863 })
864 })
865
866 describe('callbacks', () => {
867 it('should call onChunk callback when chunks are received', async () => {
868 const chunks = createTextChunks('Hello')
869 const adapter = createMockConnectionAdapter({ chunks })
870 const onChunk = vi.fn()
871
872 const { result } = renderUseChat({
873 connection: adapter,
874 onChunk,
875 })
876
877 await result.current.sendMessage('Test')
878
879 await waitFor(() => {
880 expect(onChunk).toHaveBeenCalled()
881 })
882
883 // Should have been called for each chunk
884 expect(onChunk.mock.calls.length).toBeGreaterThan(0)
885 })
886
887 it('should call onFinish callback when response finishes', async () => {
888 const chunks = createTextChunks('Response')
889 const adapter = createMockConnectionAdapter({ chunks })
890 const onFinish = vi.fn()
891
892 const { result } = renderUseChat({
893 connection: adapter,
894 onFinish,
895 })
896
897 await result.current.sendMessage('Test')
898
899 await waitFor(() => {
900 expect(onFinish).toHaveBeenCalled()
901 })
902
903 const finishedMessage = onFinish.mock.calls[0]![0]
904 expect(finishedMessage).toBeDefined()
905 expect(finishedMessage.role).toBe('assistant')
906 })
907
908 it('should call onError callback when error occurs', async () => {
909 const error = new Error('Test error')
910 const adapter = createMockConnectionAdapter({
911 shouldError: true,
912 error,
913 })
914 const onError = vi.fn()
915
916 const { result } = renderUseChat({
917 connection: adapter,
918 onError,
919 })
920
921 await result.current.sendMessage('Test')
922
923 await waitFor(() => {
924 expect(onError).toHaveBeenCalled()
925 })
926
927 expect(onError.mock.calls[0]![0].message).toBe('Test error')
928 })
929
930 it('should call onResponse callback when response is received', async () => {
931 const chunks = createTextChunks('Response')
932 const adapter = createMockConnectionAdapter({ chunks })
933 const onResponse = vi.fn()
934
935 const { result } = renderUseChat({
936 connection: adapter,
937 onResponse,
938 })
939
940 await result.current.sendMessage('Test')
941
942 // onResponse may or may not be called depending on adapter implementation
943 // This test verifies the callback is passed through
944 await waitFor(() => {
945 expect(result.current.messages.length).toBeGreaterThan(0)
946 })
947 })
948 })
949
950 describe('edge cases and error handling', () => {
951 describe('options changes', () => {
952 it('should maintain client instance when options change', () => {
953 const adapter1 = createMockConnectionAdapter()
954 const { result, rerender } = renderUseChat({ connection: adapter1 })
955
956 const initialMessages = result.current.messages
957
958 const adapter2 = createMockConnectionAdapter()
959 rerender({ connection: adapter2 })
960
961 // Client instance should persist (current implementation doesn't update)
962 // This documents current behavior - options changes don't update client
963 expect(result.current.messages).toBe(initialMessages)
964 })
965
966 it('should handle body changes', () => {
967 const adapter = createMockConnectionAdapter()
968 const { result, rerender } = renderUseChat({
969 connection: adapter,
970 body: { userId: '123' },
971 })
972
973 rerender({
974 connection: adapter,
975 body: { userId: '456' },
976 })
977
978 // Should not throw
979 expect(result.current).toBeDefined()
980 })
981
982 it('should handle callback changes', () => {
983 const adapter = createMockConnectionAdapter()
984 const onChunk1 = vi.fn()
985 const { result, rerender } = renderUseChat({
986 connection: adapter,
987 onChunk: onChunk1,
988 })
989
990 const onChunk2 = vi.fn()
991 rerender({
992 connection: adapter,
993 onChunk: onChunk2,
994 })
995
996 // Should not throw
997 expect(result.current).toBeDefined()
998 })
999 })
1000
1001 describe('unmount behavior', () => {
1002 it('should not update state after unmount', async () => {
1003 const chunks = createTextChunks('Response')
1004 const adapter = createMockConnectionAdapter({
1005 chunks,
1006 chunkDelay: 100,
1007 })
1008 const { result, unmount } = renderUseChat({ connection: adapter })
1009
1010 const sendPromise = result.current.sendMessage('Test')
1011
1012 // Unmount before completion
1013 unmount()
1014
1015 await sendPromise.catch(() => {
1016 // Ignore errors
1017 })
1018
1019 // State updates after unmount should be ignored (React handles this)
1020 // This test documents the expected behavior
1021 expect(result.current).toBeDefined()
1022 })
1023
1024 it('should stop loading on unmount if active', async () => {
1025 const chunks = createTextChunks('Response')
1026 const adapter = createMockConnectionAdapter({
1027 chunks,
1028 chunkDelay: 100,
1029 })
1030 const { result, unmount } = renderUseChat({ connection: adapter })
1031
1032 result.current.sendMessage('Test')
1033
1034 await waitFor(() => {
1035 expect(result.current.isLoading).toBe(true)
1036 })
1037
1038 unmount()
1039
1040 // After unmount, cleanup should stop active work.
1041 expect(result.current).toBeDefined()
1042 })
1043 })
1044
1045 describe('concurrent operations', () => {
1046 it('should queue and then deliver multiple sendMessage calls in order', async () => {
1047 const adapter = createMockConnectionAdapter({
1048 chunks: createTextChunks('Response'),
1049 chunkDelay: 50,
1050 })
1051 const { result } = renderUseChat({ connection: adapter })
1052
1053 const promise1 = result.current.sendMessage('First')
1054 const promise2 = result.current.sendMessage('Second')
1055
1056 await Promise.all([promise1, promise2])
1057
1058 // The second call is queued while the first stream is in flight,
1059 // then auto-sent once it settles — both land, in order.
1060 const userMessages = result.current.messages.filter(
1061 (m) => m.role === 'user',
1062 )
1063 expect(userMessages.map((m) => m.parts[0])).toEqual([
1064 { type: 'text', content: 'First' },
1065 { type: 'text', content: 'Second' },
1066 ])
1067 })
1068
1069 it('should handle stop during sendMessage', async () => {
1070 const chunks = createTextChunks('Long response')
1071 const adapter = createMockConnectionAdapter({
1072 chunks,
1073 chunkDelay: 50,
1074 })
1075 const { result } = renderUseChat({ connection: adapter })
1076
1077 const sendPromise = result.current.sendMessage('Test')
1078
1079 await waitFor(() => {
1080 expect(result.current.isLoading).toBe(true)
1081 })
1082
1083 result.current.stop()
1084
1085 await waitFor(
1086 () => {
1087 expect(result.current.isLoading).toBe(false)
1088 },
1089 { timeout: 1000 },
1090 )
1091
1092 await sendPromise.catch(() => {
1093 // Ignore errors from stopped request
1094 })
1095 })
1096
1097 it('should handle reload during active stream', async () => {
1098 const chunks = createTextChunks('Response')
1099 const adapter = createMockConnectionAdapter({
1100 chunks,
1101 chunkDelay: 50,
1102 })
1103 const { result } = renderUseChat({ connection: adapter })
1104
1105 const sendPromise = result.current.sendMessage('Test')
1106
1107 await waitFor(() => {
1108 expect(result.current.isLoading).toBe(true)
1109 })
1110
1111 // Try to reload while sending
1112 const reloadPromise = result.current.reload()
1113
1114 await Promise.allSettled([sendPromise, reloadPromise])
1115
1116 // Should eventually complete
1117 await waitFor(() => {
1118 expect(result.current.isLoading).toBe(false)
1119 })
1120 })
1121 })
1122
1123 describe('error scenarios', () => {
1124 it('should handle network errors', async () => {
1125 const error = new Error('Network request failed')
1126 const adapter = createMockConnectionAdapter({
1127 shouldError: true,
1128 error,
1129 })
1130 const { result } = renderUseChat({ connection: adapter })
1131
1132 await result.current.sendMessage('Test')
1133
1134 await waitFor(() => {
1135 expect(result.current.error).toBeDefined()
1136 })
1137
1138 expect(result.current.error?.message).toBe('Network request failed')
1139 expect(result.current.isLoading).toBe(false)
1140 expect(result.current.status).toBe('error')
1141 })
1142
1143 it('should handle stream errors', async () => {
1144 const error = new Error('Stream error')
1145 const adapter = createMockConnectionAdapter({
1146 shouldError: true,
1147 error,
1148 })
1149 const { result } = renderUseChat({ connection: adapter })
1150
1151 await result.current.sendMessage('Test')
1152
1153 await waitFor(() => {
1154 expect(result.current.error).toBeDefined()
1155 expect(result.current.status).toBe('error')
1156 })
1157
1158 expect(result.current.error?.message).toBe('Stream error')
1159 })
1160
1161 it('should clear error on successful operation', async () => {
1162 const errorAdapter = createMockConnectionAdapter({
1163 shouldError: true,
1164 error: new Error('Initial error'),
1165 })
1166 const { result, rerender } = renderUseChat({
1167 connection: errorAdapter,
1168 })
1169
1170 await result.current.sendMessage('Test')
1171
1172 await waitFor(() => {
1173 expect(result.current.error).toBeDefined()
1174 expect(result.current.status).toBe('error')
1175 })
1176
1177 // Switch to working adapter
1178 const workingAdapter = createMockConnectionAdapter({
1179 chunks: createTextChunks('Success'),
1180 })
1181 rerender({ connection: workingAdapter })
1182
1183 await result.current.sendMessage('Test')
1184
1185 await waitFor(() => {
1186 // Error should be cleared on success
1187 expect(result.current.messages.length).toBeGreaterThan(0)
1188 })
1189 })
1190
1191 it.skip('should handle tool execution errors', async () => {
1192 // TODO: This test is complex to set up with SolidJS testing library.
1193 // Tool execution error handling is thoroughly tested in ai-client tests.
1194 // Skipping for now to unblock the build.
1195 })
1196 })
1197
1198 describe('multiple hook instances', () => {
1199 it('should maintain independent state per instance', async () => {
1200 const adapter1 = createMockConnectionAdapter({
1201 chunks: createTextChunks('Response 1'),
1202 })
1203 const adapter2 = createMockConnectionAdapter({
1204 chunks: createTextChunks('Response 2'),
1205 })
1206
1207 const { result: result1 } = renderUseChat({
1208 connection: adapter1,
1209 threadId: 'chat-1',
1210 })
1211 const { result: result2 } = renderUseChat({
1212 connection: adapter2,
1213 threadId: 'chat-2',
1214 })
1215
1216 await result1.current.sendMessage('Hello 1')
1217 await result2.current.sendMessage('Hello 2')
1218
1219 await waitFor(() => {
1220 expect(result1.current.messages.length).toBeGreaterThan(0)
1221 expect(result2.current.messages.length).toBeGreaterThan(0)
1222 })
1223
1224 // Each instance should have its own messages
1225 expect(result1.current.messages.length).toBe(
1226 result2.current.messages.length,
1227 )
1228 expect(result1.current.messages[0]!.parts[0]).not.toEqual(
1229 result2.current.messages[0]!.parts[0],
1230 )
1231 })
1232
1233 it('should handle different IDs correctly', () => {
1234 const adapter = createMockConnectionAdapter()
1235 const { result: result1 } = renderUseChat({
1236 connection: adapter,
1237 threadId: 'chat-1',
1238 })
1239 const { result: result2 } = renderUseChat({
1240 connection: adapter,
1241 threadId: 'chat-2',
1242 })
1243
1244 // Should not interfere with each other
1245 expect(result1.current.messages).toEqual([])
1246 expect(result2.current.messages).toEqual([])
1247 })
1248
1249 it('should not have cross-contamination', async () => {
1250 const adapter1 = createMockConnectionAdapter({
1251 chunks: createTextChunks('One'),
1252 })
1253 const adapter2 = createMockConnectionAdapter({
1254 chunks: createTextChunks('Two'),
1255 })
1256
1257 const { result: result1 } = renderUseChat({
1258 connection: adapter1,
1259 })
1260 const { result: result2 } = renderUseChat({
1261 connection: adapter2,
1262 })
1263
1264 await result1.current.sendMessage('Message 1')
1265 await waitFor(() => {
1266 expect(result1.current.messages.length).toBeGreaterThan(0)
1267 })
1268
1269 // Second instance should still be empty
1270 expect(result2.current.messages.length).toBe(0)
1271
1272 await result2.current.sendMessage('Message 2')
1273 await waitFor(() => {
1274 expect(result2.current.messages.length).toBeGreaterThan(0)
1275 })
1276
1277 // Both should have messages, but different ones
1278 expect(result1.current.messages.length).toBeGreaterThan(0)
1279 expect(result2.current.messages.length).toBeGreaterThan(0)
1280 expect(result1.current.messages[0]!.parts[0]).not.toEqual(
1281 result2.current.messages[0]!.parts[0],
1282 )
1283 })
1284 })
1285
1286 describe('tool operations', () => {
1287 it('should handle addToolResult', async () => {
1288 const toolCalls = createToolCallChunks([
1289 { id: 'tool-1', name: 'testTool', arguments: '{"param": "value"}' },
1290 ])
1291 const adapter = createMockConnectionAdapter({ chunks: toolCalls })
1292 // `onToolCall` is intentionally NOT passed here: it is not part of the
1293 // public `UseChatOptions` surface (it's wired internally by ChatClient
1294 // through the `tools` array). The previous version of this test set it
1295 // via `as any` and then never exercised its result — `addToolResult`
1296 // itself is the public API under test.
1297 const { result } = renderUseChat({
1298 connection: adapter,
1299 })
1300
1301 await result.current.sendMessage('Test')
1302
1303 await waitFor(() => {
1304 const assistantMessage = result.current.messages.find(
1305 (m) => m.role === 'assistant',
1306 )
1307 expect(assistantMessage).toBeDefined()
1308 })
1309
1310 // Find tool call
1311 const assistantMessage = result.current.messages.find(
1312 (m) => m.role === 'assistant',
1313 )
1314 const toolCallPart = assistantMessage?.parts.find(
1315 (p) => p.type === 'tool-call',
1316 )
1317
1318 if (toolCallPart && toolCallPart.type === 'tool-call') {
1319 await result.current.addToolResult({
1320 toolCallId: toolCallPart.id,
1321 tool: toolCallPart.name,
1322 output: { result: 'manual' },
1323 })
1324
1325 // Should update the tool call
1326 await waitFor(() => {
1327 const updatedMessage = result.current.messages.find(
1328 (m) => m.role === 'assistant',
1329 )
1330 const updatedToolCall = updatedMessage?.parts.find(
1331 (p) => p.type === 'tool-call' && p.id === toolCallPart.id,
1332 )
1333 expect(updatedToolCall).toBeDefined()
1334 })
1335 }
1336 })
1337
1338 it('should handle addToolApprovalResponse', async () => {
1339 const toolCalls = createToolCallChunks([
1340 { id: 'tool-1', name: 'testTool', arguments: '{"param": "value"}' },
1341 ])
1342 const adapter = createMockConnectionAdapter({ chunks: toolCalls })
1343 const { result } = renderUseChat({
1344 connection: adapter,
1345 })
1346
1347 await result.current.sendMessage('Test')
1348
1349 await waitFor(() => {
1350 const assistantMessage = result.current.messages.find(
1351 (m) => m.role === 'assistant',
1352 )
1353 expect(assistantMessage).toBeDefined()
1354 })
1355
1356 // Find tool call with approval
1357 const assistantMessage = result.current.messages.find(
1358 (m) => m.role === 'assistant',
1359 )
1360 const toolCallPart = assistantMessage?.parts.find(
1361 (p) => p.type === 'tool-call' && p.approval,
1362 )
1363
1364 if (
1365 toolCallPart &&
1366 toolCallPart.type === 'tool-call' &&
1367 toolCallPart.approval
1368 ) {
1369 await result.current.addToolApprovalResponse({
1370 id: toolCallPart.approval.id,
1371 approved: true,
1372 })
1373
1374 // Should update approval state
1375 await waitFor(() => {
1376 const updatedMessage = result.current.messages.find(
1377 (m) => m.role === 'assistant',
1378 )
1379 const updatedToolCall = updatedMessage?.parts.find(
1380 (p) => p.type === 'tool-call' && p.id === toolCallPart.id,
1381 )
1382 if (updatedToolCall && updatedToolCall.type === 'tool-call') {
1383 expect(updatedToolCall.approval?.approved).toBe(true)
1384 }
1385 })
1386 }
1387 })
1388 })
1389 })
1390})