Open History to see the last commit
1import { EventType } from '@tanstack/ai/client'
2import { afterEach, describe, expect, it, vi } from 'vitest'
3import { ChatClient } from '@tanstack/ai-client'
4import { createChat } from '../src/create-chat'
5import type { AnyClientTool } from '@tanstack/ai-client'
6import type { Handle } from 'remix/ui'
7import type { StreamChunk } from '@tanstack/ai/client'
8
9const abortControllers: Array<AbortController> = []
10
11afterEach(() => {
12 for (const abort of abortControllers) {
13 abort.abort()
14 }
15 abortControllers.length = 0
16 vi.restoreAllMocks()
17})
18
19function createHandle() {
20 const abort = new AbortController()
21 abortControllers.push(abort)
22 const frame = Object.assign(new EventTarget(), {
23 src: '',
24 reload: async () => abort.signal,
25 replace: async () => {},
26 })
27 const handle: Handle = {
28 id: 'handle-1',
29 update: vi.fn(async () => abort.signal),
30 signal: abort.signal,
31 props: {},
32 context: {
33 set() {},
34 get() {
35 return undefined
36 },
37 },
38 queueTask() {},
39 frame,
40 frames: {
41 top: frame,
42 get() {
43 return undefined
44 },
45 },
46 }
47 return { handle, abort }
48}
49
50function textChunk(delta: string, messageId = 'assistant-1'): StreamChunk {
51 return {
52 type: EventType.TEXT_MESSAGE_CONTENT,
53 messageId,
54 timestamp: Date.now(),
55 delta,
56 }
57}
58
59function runFinished(runId = 'run-1'): StreamChunk {
60 return {
61 type: EventType.RUN_FINISHED,
62 runId,
63 threadId: 'thread-1',
64 timestamp: Date.now(),
65 }
66}
67
68function createConnection(chunks: Array<StreamChunk>) {
69 return {
70 async *connect() {
71 for (const chunk of chunks) {
72 yield chunk
73 }
74 },
75 }
76}
77
78describe('createChat', () => {
79 it('sends the current getter tools when a run starts', async () => {
80 const { handle } = createHandle()
81 const updateOptions = vi.spyOn(ChatClient.prototype, 'updateOptions')
82 let tools: Array<AnyClientTool> = []
83 const chat = createChat(handle, {
84 threadId: 'thread-1',
85 connection: createConnection([textChunk('Hi'), runFinished()]),
86 get tools() {
87 return tools
88 },
89 })
90
91 tools = [{ __toolSide: 'client', name: 'late', description: 'Late' }]
92 await chat.sendMessage('Hello')
93
94 expect(updateOptions).toHaveBeenCalledWith({ tools })
95 })
96
97 it('records user and assistant messages and calls handle.update after sendMessage', async () => {
98 const { handle } = createHandle()
99 const chat = createChat(handle, {
100 threadId: 'thread-1',
101 connection: createConnection([textChunk('Hi'), runFinished()]),
102 })
103
104 await chat.sendMessage('Hello')
105
106 expect(chat.messages.map((message) => message.role)).toEqual([
107 'user',
108 'assistant',
109 ])
110 expect(handle.update).toHaveBeenCalled()
111 })
112
113 it('does not call handle.update after the handle signal aborts', async () => {
114 const { handle, abort } = createHandle()
115 const chat = createChat(handle, {
116 threadId: 'thread-1',
117 connection: createConnection([textChunk('Hi'), runFinished()]),
118 })
119
120 vi.mocked(handle.update).mockClear()
121 abort.abort()
122
123 await chat.sendMessage('Hello').catch(() => {})
124
125 expect(handle.update).not.toHaveBeenCalled()
126 })
127
128 it('reads the frozen client snapshot and updates on every snapshot change until abort', async () => {
129 const { handle, abort } = createHandle()
130 const chat = createChat(handle, {
131 threadId: 'thread-1',
132 connection: createConnection([textChunk('Hi'), runFinished()]),
133 })
134
135 await chat.sendMessage('Hello')
136 const messages = chat.messages
137 expect(Object.isFrozen(messages)).toBe(true)
138 expect(() => (messages as Array<unknown>).push({})).toThrow(TypeError)
139
140 vi.mocked(handle.update).mockClear()
141 chat.setMessages(messages.slice(0, 1))
142 expect(chat.messages).toHaveLength(1)
143 expect(handle.update).toHaveBeenCalledTimes(1)
144
145 abort.abort()
146 vi.mocked(handle.update).mockClear()
147 chat.setMessages([])
148 expect(handle.update).not.toHaveBeenCalled()
149 })
150})