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

use-chat.test.ts

1,459 lines44.9 KB

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