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

chat.spec.ts

390 lines11.7 KB

1import { test, expect } from './fixtures'
2import {
3 collectHydrationErrors,
4 sendMessage,
5 waitForResponse,
6 getLastAssistantMessage,
7 featureUrl,
8} from './helpers'
9import { providersFor } from './test-matrix'
10​
11// The server conversion test in this spec does not call a provider HTTP
12// endpoint, so it intentionally does not configure aimock.
13​
14for (const provider of providersFor('chat')) {
15 test.describe(`${provider} — chat`, () => {
16 test('sends a message and receives a streaming response', async ({
17 page,
18 testId,
19 aimockPort,
20 }) => {
21 await page.goto(featureUrl(provider, 'chat', testId, aimockPort))
22​
23 await sendMessage(page, '[chat] recommend a guitar')
24 await waitForResponse(page)
25​
26 const response = await getLastAssistantMessage(page)
27 expect(response).toContain('Fender Stratocaster')
28 })
29​
30 test('fetcher mode — streams an SSE Response through useChat({ fetcher })', async ({
31 page,
32 testId,
33 aimockPort,
34 }) => {
35 await page.goto(
36 featureUrl(provider, 'chat', testId, aimockPort, 'fetcher'),
37 )
38​
39 // Positively assert the fetcher path executed by waiting for the
40 // POST that carries our sentinel header. Without this, a silent
41 // fallback to the connection adapter would still make the response
42 // assertion pass (both paths return the same SSE).
43 const fetcherRequest = page.waitForRequest(
44 (req) =>
45 req.url().endsWith('/api/chat') &&
46 req.method() === 'POST' &&
47 req.headers()['x-tanstack-ai-transport'] === 'fetcher',
48 )
49​
50 await sendMessage(page, '[chat] recommend a guitar')
51 await fetcherRequest
52 await waitForResponse(page)
53​
54 const response = await getLastAssistantMessage(page)
55 expect(response).toContain('Fender Stratocaster')
56 })
57 })
59​
60test('preserves UI message IDs at the server conversion boundary', async ({
61 request,
62}) => {
63 const response = await request.post('/api/message-ids', {
64 data: {
65 messages: [
66 {
67 id: 'user-1',
68 role: 'user',
69 parts: [{ type: 'text', content: 'Hello' }],
70 },
71 {
72 id: 'assistant-1',
73 role: 'assistant',
74 parts: [
75 { type: 'text', content: 'Let me check.' },
76 {
77 type: 'tool-call',
78 id: 'tool-1',
79 name: 'getWeather',
80 arguments: '{}',
81 state: 'input-complete',
82 },
83 {
84 type: 'tool-result',
85 id: 'result-1',
86 name: 'getWeather',
87 toolCallId: 'tool-1',
88 content: [{ type: 'text', content: '{"temp":72}' }],
89 state: 'complete',
90 metadata: { source: 'e2e' },
91 createdAt: '2026-08-20T00:00:00.000Z',
92 },
93 ],
94 },
95 ],
96 },
97 })
98​
99 expect(response.ok()).toBe(true)
100 const { modelMessages, wireMessages, snapshots, mergedSnapshots } =
101 await response.json()
102​
103 expect(modelMessages).toEqual([
104 { id: 'user-1', role: 'user', content: 'Hello' },
105 {
106 id: 'assistant-1',
107 role: 'assistant',
108 content: 'Let me check.',
109 toolCalls: [
110 {
111 id: 'tool-1',
112 type: 'function',
113 function: { name: 'getWeather', arguments: '{}' },
114 },
115 ],
116 },
117 {
118 id: 'result-1',
119 role: 'tool',
120 name: 'getWeather',
121 content: [{ type: 'text', content: '{"temp":72}' }],
122 toolCallId: 'tool-1',
123 metadata: { source: 'e2e' },
124 createdAt: '2026-08-20T00:00:00.000Z',
125 },
126 ])
127 expect(wireMessages).toEqual(
128 expect.arrayContaining([
129 expect.objectContaining({ role: 'assistant', id: 'assistant-1' }),
130 expect.objectContaining({
131 role: 'tool',
132 toolCallId: 'tool-1',
133 id: 'result-1',
134 metadata: {
135 source: 'e2e',
136 tanstack: {
137 toolResult: {
138 id: 'result-1',
139 createdAt: '2026-08-20T00:00:00.000Z',
140 content: [{ type: 'text', content: '{"temp":72}' }],
141 },
142 },
143 },
144 }),
145 ]),
146 )
147 expect(snapshots).toEqual(
148 expect.arrayContaining([
149 expect.objectContaining({
150 id: 'assistant-1',
151 role: 'assistant',
152 parts: expect.arrayContaining([
153 expect.objectContaining({
154 type: 'tool-result',
155 id: 'result-1',
156 content: [{ type: 'text', content: '{"temp":72}' }],
157 metadata: { source: 'e2e' },
158 }),
159 ]),
160 }),
161 ]),
162 )
163 const mergedAssistant = mergedSnapshots.find(
164 (message: { id?: string }) => message.id === 'assistant-1',
165 )
166 expect(mergedAssistant?.parts).toEqual(
167 expect.arrayContaining([
168 expect.objectContaining({
169 type: 'tool-result',
170 id: 'result-1',
171 content: [{ type: 'text', content: '{"temp":72}' }],
172 metadata: { source: 'e2e' },
173 createdAt: '2026-08-20T00:00:00.000Z',
174 }),
175 ]),
176 )
177})
178​
179test('merges assistant segments that share a UI message ID', async ({
180 request,
181}) => {
182 const response = await request.post('/api/message-ids', {
183 data: {
184 messages: [
185 {
186 id: 'assistant-round-trip',
187 role: 'assistant',
188 parts: [
189 { type: 'text', content: 'First step.' },
190 {
191 type: 'tool-call',
192 id: 'tool-1',
193 name: 'first',
194 arguments: '{}',
195 state: 'input-complete',
196 },
197 {
198 type: 'tool-result',
199 toolCallId: 'tool-1',
200 content: '{"ok":true}',
201 state: 'complete',
202 },
203 { type: 'text', content: 'Second step.' },
204 ],
205 },
206 ],
207 },
208 })
209​
210 expect(response.ok()).toBe(true)
211 const { modelMessages, mergedSnapshots } = await response.json()
212​
213 const assistantSegments = modelMessages.filter(
214 (message: { role: string }) => message.role === 'assistant',
215 )
216 expect(assistantSegments).toHaveLength(2)
217 expect(
218 assistantSegments.map((message: { id?: string }) => message.id),
219 ).toEqual(['assistant-round-trip', 'assistant-round-trip'])
220​
221 const assistantMessages = mergedSnapshots.filter(
222 (message: { role: string }) => message.role === 'assistant',
223 )
224 expect(assistantMessages).toHaveLength(1)
225 expect(assistantMessages[0]).toMatchObject({
226 id: 'assistant-round-trip',
227 parts: [
228 expect.objectContaining({ type: 'text', content: 'First step.' }),
229 expect.objectContaining({ type: 'tool-call', id: 'tool-1' }),
230 expect.objectContaining({ type: 'tool-result', toolCallId: 'tool-1' }),
231 expect.objectContaining({ type: 'text', content: 'Second step.' }),
232 ],
233 })
234})
235​
236test('rejects malformed JSON at the server conversion boundary', async ({
237 request,
238}) => {
239 const response = await request.post('/api/message-ids', {
240 data: '{',
241 headers: { 'Content-Type': 'application/json' },
242 })
243​
244 expect(response.status()).toBe(400)
245})
246​
247test('rejects invalid message parts at the server conversion boundary', async ({
248 request,
249}) => {
250 const response = await request.post('/api/message-ids', {
251 data: {
252 messages: [
253 {
254 id: 'user-1',
255 role: 'user',
256 parts: [{ type: 'text', content: 42 }],
257 },
258 ],
259 },
260 })
261​
262 expect(response.status()).toBe(400)
263})
264​
265test.describe('openai chat persistence', () => {
266 test('persists chat messages across browser reload with localStorage', async ({
267 page,
268 testId,
269 aimockPort,
270 }) => {
271 await page.goto(
272 `${featureUrl('openai', 'chat', testId, aimockPort)}&persistence=localStorage`,
273 )
274​
275 await sendMessage(page, '[chat] recommend a guitar')
276 await waitForResponse(page)
277​
278 await expect(page.getByTestId('user-message')).toContainText(
279 '[chat] recommend a guitar',
280 )
281 await expect(page.getByTestId('assistant-message')).toContainText(
282 'Fender Stratocaster',
283 )
284​
285 const hydrationErrors = collectHydrationErrors(page)
286​
287 await page.reload()
288​
289 await expect(page.getByTestId('user-message')).toContainText(
290 '[chat] recommend a guitar',
291 )
292 await expect(page.getByTestId('assistant-message')).toContainText(
293 'Fender Stratocaster',
294 )
295 expect(hydrationErrors).toEqual([])
296 })
297​
298 test('clear() removes the persisted conversation so a reload starts empty', async ({
299 page,
300 testId,
301 aimockPort,
302 }) => {
303 await page.goto(
304 `${featureUrl('openai', 'chat', testId, aimockPort)}&persistence=localStorage`,
305 )
306​
307 await sendMessage(page, '[chat] recommend a guitar')
308 await waitForResponse(page)
309 await expect(page.getByTestId('user-message')).toContainText(
310 '[chat] recommend a guitar',
311 )
312​
313 await page.getByTestId('clear-button').click()
314 await expect(page.getByTestId('user-message')).toHaveCount(0)
315 await expect(page.getByTestId('assistant-message')).toHaveCount(0)
316​
317 // The conversation was removed from storage, not just from memory — a
318 // reload must not resurrect it.
319 await page.reload()
320 await expect(page.getByTestId('message-list')).toBeVisible()
321 await expect(page.getByTestId('user-message')).toHaveCount(0)
322 await expect(page.getByTestId('assistant-message')).toHaveCount(0)
323 })
324​
325 test('setMessages() takes the frozen messages back and the chat keeps working', async ({
326 page,
327 testId,
328 aimockPort,
329 }) => {
330 await page.goto(
331 `${featureUrl('openai', 'chat', testId, aimockPort)}&persistence=localStorage`,
332 )
333 const pageErrors: Array<string> = []
334 page.on('pageerror', (error) => pageErrors.push(error.message))
335​
336 await sendMessage(page, '[chat] recommend a guitar')
337 await waitForResponse(page)
338​
339 // Pass the hook's own frozen `messages` array straight back in.
340 await page.getByTestId('set-messages-button').click()
341 await expect(page.getByTestId('user-message')).toHaveCount(1)
342 await expect(page.getByTestId('assistant-message')).toContainText(
343 'Fender Stratocaster',
344 )
345​
346 await sendMessage(page, '[per-call-body] send with per-call body')
347 await waitForResponse(page)
348 await expect(page.getByTestId('user-message')).toHaveCount(2)
349 await expect(page.getByTestId('assistant-message').last()).toContainText(
350 'Acknowledged the per-call body send.',
351 )
352 expect(pageErrors).toEqual([])
353 })
354​
355 test('switches per-thread history when the chat id changes in place', async ({
356 page,
357 testId,
358 aimockPort,
359 }) => {
360 await page.goto(
361 `${featureUrl('openai', 'chat', testId, aimockPort)}&persistence=localStorage`,
362 )
363​
364 // The page loads on thread A. Send a message (persisted under A's own id).
365 await sendMessage(page, '[chat] recommend a guitar')
366 await waitForResponse(page)
367 await expect(page.getByTestId('user-message')).toHaveCount(1)
368​
369 // Switch to thread B in place — its own (empty) history loads, proving the
370 // id swap doesn't leak thread A's messages into thread B.
371 await page.getByTestId('select-thread-b').click()
372 await expect(page.getByTestId('user-message')).toHaveCount(0)
373 await expect(page.getByTestId('assistant-message')).toHaveCount(0)
374​
375 await sendMessage(page, '[chat] recommend a guitar')
376 await waitForResponse(page)
377 await expect(page.getByTestId('user-message')).toHaveCount(1)
378​
379 // Switch back to thread A — its persisted history is restored from storage
380 // on the in-place swap (render-from-getMessages), exactly one message.
381 await page.getByTestId('select-thread-a').click()
382 await expect(page.getByTestId('user-message')).toHaveCount(1)
383 await expect(page.getByTestId('user-message')).toContainText(
384 '[chat] recommend a guitar',
385 )
386 await expect(page.getByTestId('assistant-message')).toContainText(
387 'Fender Stratocaster',
388 )
389 })
390})