Open History to see the last commit
1/**
2 * Runtime tests for `useChat({ outputSchema })`:
3 *
4 * - `partial` updates per `TEXT_MESSAGE_CONTENT` delta (progressive JSON parse)
5 * - `final` snaps on the terminal `CUSTOM structured-output.complete` event
6 * - State resets between `sendMessage` calls (on `RUN_STARTED`)
7 * - User's own `onChunk` callback fires after internal tracking
8 * - Without `outputSchema`, no partial/final tracking runs
9 */
10
11import { act, renderHook, waitFor } from '@testing-library/react'
12import { describe, expect, it, vi } from 'vitest'
13import type { StandardJSONSchemaV1 } from '@standard-schema/spec'
14import type { StreamChunk } from '@tanstack/ai'
15import { createMockConnectionAdapter } from '../../ai-client/tests/test-utils'
16import { useChat } from '../src/use-chat'
17
18type Person = { name: string; age: number; email: string }
19type PersonSchema = StandardJSONSchemaV1<Person, Person>
20const personSchema = {} as PersonSchema
21
22/**
23 * Build a chunk sequence simulating a streaming structured-output run:
24 * RUN_STARTED → TEXT_MESSAGE_CONTENT deltas (each delta moves the buffer
25 * one character closer to `fullJson`) → CUSTOM structured-output.complete
26 * → RUN_FINISHED.
27 */
28function buildStructuredStream(
29 fullJson: string,
30 finalObject: Person,
31 runId = 'run-1',
32): Array<StreamChunk> {
33 const chunks: Array<StreamChunk> = [
34 {
35 type: 'RUN_STARTED',
36 runId,
37 threadId: `thread-${runId}`,
38 model: 'test',
39 timestamp: Date.now(),
40 } as StreamChunk,
41 ]
42 // Split fullJson into a few large-ish slices so we test progressive parsing
43 // without producing a flood of one-char chunks.
44 const sliceSize = Math.max(4, Math.floor(fullJson.length / 4))
45 for (let i = 0; i < fullJson.length; i += sliceSize) {
46 chunks.push({
47 type: 'TEXT_MESSAGE_CONTENT',
48 messageId: `msg-${runId}`,
49 delta: fullJson.slice(i, i + sliceSize),
50 content: fullJson.slice(0, i + sliceSize),
51 model: 'test',
52 timestamp: Date.now(),
53 } as StreamChunk)
54 }
55 chunks.push({
56 type: 'CUSTOM',
57 name: 'structured-output.complete',
58 value: { object: finalObject, raw: fullJson },
59 model: 'test',
60 timestamp: Date.now(),
61 } as StreamChunk)
62 chunks.push({
63 type: 'RUN_FINISHED',
64 runId,
65 threadId: `thread-${runId}`,
66 model: 'test',
67 timestamp: Date.now(),
68 finishReason: 'stop',
69 } as StreamChunk)
70 return chunks
71}
72
73describe('useChat({ outputSchema }) — runtime', () => {
74 const person: Person = {
75 name: 'John Doe',
76 age: 30,
77 email: 'john@example.com',
78 }
79 const json = JSON.stringify(person)
80
81 it('updates `partial` progressively and snaps `final` on the terminal event', async () => {
82 const chunks = buildStructuredStream(json, person)
83 const adapter = createMockConnectionAdapter({ chunks })
84
85 const { result } = renderHook(() =>
86 useChat({ connection: adapter, outputSchema: personSchema }),
87 )
88
89 // Initial state.
90 expect(result.current.partial).toEqual({})
91 expect(result.current.final).toBeNull()
92
93 await act(async () => {
94 await result.current.sendMessage('Extract')
95 })
96
97 // The schema-validated `final` lands once the terminal event fires.
98 await waitFor(() => {
99 expect(result.current.final).toEqual(person)
100 })
101
102 // `partial` should end with the same shape (parsePartialJSON on the
103 // complete buffer returns the fully-formed object).
104 expect(result.current.partial).toEqual(person)
105 })
106
107 it('resets `partial` and `final` between runs', async () => {
108 const personA: Person = {
109 name: 'Alice',
110 age: 25,
111 email: 'alice@example.com',
112 }
113 const personB: Person = { name: 'Bob', age: 40, email: 'bob@example.com' }
114
115 // Stateful adapter that yields a different stream per connect() call.
116 // Without this, createMockConnectionAdapter would yield the same array
117 // on every sendMessage — the "reset" couldn't be observed between runs
118 // because final would race past personA straight to personB on call #1.
119 let call = 0
120 const adapter = {
121 async *connect() {
122 const chunks =
123 call === 0
124 ? buildStructuredStream(JSON.stringify(personA), personA, 'run-a')
125 : buildStructuredStream(JSON.stringify(personB), personB, 'run-b')
126 call++
127 for (const chunk of chunks) yield chunk
128 },
129 }
130
131 const { result } = renderHook(() =>
132 useChat({ connection: adapter, outputSchema: personSchema }),
133 )
134
135 await act(async () => {
136 await result.current.sendMessage('A')
137 })
138 await waitFor(() => {
139 expect(result.current.final).toEqual(personA)
140 })
141 expect(result.current.partial).toEqual(personA)
142
143 // Second run — RUN_STARTED at the head must clear partial/final before
144 // run-b's deltas land. If the reset didn't happen, run-b's progressive
145 // partial would be shadowed by leftover state from run-a (since
146 // parsePartialJSON would parse run-b's accumulated buffer cleanly, but
147 // the spread-onto-stale-state class of bug would still surface in `final`).
148 await act(async () => {
149 await result.current.sendMessage('B')
150 })
151 await waitFor(() => {
152 expect(result.current.final).toEqual(personB)
153 })
154 expect(result.current.partial).toEqual(personB)
155 })
156
157 it('attaches a structured-output part to the assistant message', async () => {
158 // With structured-output.start emitted, the JSON deltas route into a
159 // StructuredOutputPart on the assistant message instead of a TextPart.
160 // History walks `messages` and finds the typed part on each turn.
161 const chunks: Array<StreamChunk> = [
162 {
163 type: 'RUN_STARTED',
164 runId: 'run-x',
165 threadId: 'thread-x',
166 model: 'test',
167 timestamp: Date.now(),
168 } as StreamChunk,
169 {
170 type: 'TEXT_MESSAGE_START',
171 messageId: 'msg-x',
172 role: 'assistant',
173 model: 'test',
174 timestamp: Date.now(),
175 } as StreamChunk,
176 {
177 type: 'CUSTOM',
178 name: 'structured-output.start',
179 value: { messageId: 'msg-x' },
180 model: 'test',
181 timestamp: Date.now(),
182 } as StreamChunk,
183 {
184 type: 'TEXT_MESSAGE_CONTENT',
185 messageId: 'msg-x',
186 delta: json,
187 content: json,
188 model: 'test',
189 timestamp: Date.now(),
190 } as StreamChunk,
191 {
192 type: 'CUSTOM',
193 name: 'structured-output.complete',
194 value: { object: person, raw: json, messageId: 'msg-x' },
195 model: 'test',
196 timestamp: Date.now(),
197 } as StreamChunk,
198 {
199 type: 'RUN_FINISHED',
200 runId: 'run-x',
201 threadId: 'thread-x',
202 model: 'test',
203 timestamp: Date.now(),
204 finishReason: 'stop',
205 } as StreamChunk,
206 ]
207 const adapter = createMockConnectionAdapter({ chunks })
208
209 const { result } = renderHook(() =>
210 useChat({ connection: adapter, outputSchema: personSchema }),
211 )
212
213 await act(async () => {
214 await result.current.sendMessage('Extract')
215 })
216 await waitFor(() => {
217 expect(result.current.final).toEqual(person)
218 })
219
220 // Find the assistant message and the structured-output part on it.
221 const assistant = result.current.messages.find(
222 (m) => m.role === 'assistant',
223 )
224 expect(assistant).toBeDefined()
225 const sop = assistant!.parts.find((p) => p.type === 'structured-output')
226 expect(sop).toBeDefined()
227 expect((sop as any).status).toBe('complete')
228 expect((sop as any).data).toEqual(person)
229 expect((sop as any).raw).toBe(json)
230
231 // With start emitted, no text part should be on the assistant message
232 // (the JSON bytes were routed into the structured-output part).
233 const textPart = assistant!.parts.find((p) => p.type === 'text')
234 expect(textPart).toBeUndefined()
235 })
236
237 it("preserves each turn's structured part across multi-turn history", async () => {
238 const personA: Person = {
239 name: 'Alice',
240 age: 25,
241 email: 'alice@example.com',
242 }
243 const personB: Person = { name: 'Bob', age: 40, email: 'bob@example.com' }
244
245 function streamFor(
246 p: Person,
247 runId: string,
248 messageId: string,
249 ): Array<StreamChunk> {
250 const raw = JSON.stringify(p)
251 return [
252 {
253 type: 'RUN_STARTED',
254 runId,
255 threadId: `thread-${runId}`,
256 model: 'test',
257 timestamp: Date.now(),
258 } as StreamChunk,
259 {
260 type: 'TEXT_MESSAGE_START',
261 messageId,
262 role: 'assistant',
263 model: 'test',
264 timestamp: Date.now(),
265 } as StreamChunk,
266 {
267 type: 'CUSTOM',
268 name: 'structured-output.start',
269 value: { messageId },
270 model: 'test',
271 timestamp: Date.now(),
272 } as StreamChunk,
273 {
274 type: 'TEXT_MESSAGE_CONTENT',
275 messageId,
276 delta: raw,
277 content: raw,
278 model: 'test',
279 timestamp: Date.now(),
280 } as StreamChunk,
281 {
282 type: 'CUSTOM',
283 name: 'structured-output.complete',
284 value: { object: p, raw, messageId },
285 model: 'test',
286 timestamp: Date.now(),
287 } as StreamChunk,
288 {
289 type: 'RUN_FINISHED',
290 runId,
291 threadId: `thread-${runId}`,
292 model: 'test',
293 timestamp: Date.now(),
294 finishReason: 'stop',
295 } as StreamChunk,
296 ]
297 }
298
299 let call = 0
300 const adapter = {
301 async *connect() {
302 const chunks =
303 call === 0
304 ? streamFor(personA, 'run-a', 'msg-a')
305 : streamFor(personB, 'run-b', 'msg-b')
306 call++
307 for (const chunk of chunks) yield chunk
308 },
309 }
310
311 const { result } = renderHook(() =>
312 useChat({ connection: adapter, outputSchema: personSchema }),
313 )
314
315 await act(async () => {
316 await result.current.sendMessage('A')
317 })
318 await waitFor(() => {
319 expect(result.current.final).toEqual(personA)
320 })
321
322 await act(async () => {
323 await result.current.sendMessage('B')
324 })
325 await waitFor(() => {
326 expect(result.current.final).toEqual(personB)
327 })
328
329 // History walk: every assistant message carries its own structured part.
330 const assistants = result.current.messages.filter(
331 (m) => m.role === 'assistant',
332 )
333 expect(assistants.length).toBe(2)
334
335 const partA = assistants[0]!.parts.find(
336 (p) => p.type === 'structured-output',
337 )
338 const partB = assistants[1]!.parts.find(
339 (p) => p.type === 'structured-output',
340 )
341 expect((partA as any)?.data).toEqual(personA)
342 expect((partB as any)?.data).toEqual(personB)
343
344 // `final` reflects the latest, but the earlier turn's data is still
345 // recoverable via the part on the historical message.
346 expect(result.current.final).toEqual(personB)
347 })
348
349 it('reads `final` as null between sendMessage and the first chunk', async () => {
350 // Park the second connect() so no chunks ever arrive for run-b. The
351 // assertion is that, immediately after sendMessage('B'), the latest user
352 // message has no assistant message after it yet, so `final` returns null.
353 const personA: Person = {
354 name: 'Alice',
355 age: 25,
356 email: 'alice@example.com',
357 }
358 let call = 0
359 let releaseSecond!: () => void
360 const secondStarted = new Promise<void>((resolve) => {
361 releaseSecond = resolve
362 })
363 const adapter = {
364 async *connect() {
365 if (call === 0) {
366 call++
367 const raw = JSON.stringify(personA)
368 const chunks: Array<StreamChunk> = [
369 {
370 type: 'RUN_STARTED',
371 runId: 'run-a',
372 threadId: 'thread-a',
373 model: 'test',
374 timestamp: Date.now(),
375 } as StreamChunk,
376 {
377 type: 'TEXT_MESSAGE_START',
378 messageId: 'msg-a',
379 role: 'assistant',
380 model: 'test',
381 timestamp: Date.now(),
382 } as StreamChunk,
383 {
384 type: 'CUSTOM',
385 name: 'structured-output.start',
386 value: { messageId: 'msg-a' },
387 model: 'test',
388 timestamp: Date.now(),
389 } as StreamChunk,
390 {
391 type: 'TEXT_MESSAGE_CONTENT',
392 messageId: 'msg-a',
393 delta: raw,
394 content: raw,
395 model: 'test',
396 timestamp: Date.now(),
397 } as StreamChunk,
398 {
399 type: 'CUSTOM',
400 name: 'structured-output.complete',
401 value: { object: personA, raw, messageId: 'msg-a' },
402 model: 'test',
403 timestamp: Date.now(),
404 } as StreamChunk,
405 {
406 type: 'RUN_FINISHED',
407 runId: 'run-a',
408 threadId: 'thread-a',
409 model: 'test',
410 timestamp: Date.now(),
411 finishReason: 'stop',
412 } as StreamChunk,
413 ]
414 for (const c of chunks) yield c
415 return
416 }
417 await secondStarted
418 },
419 }
420
421 const { result } = renderHook(() =>
422 useChat({ connection: adapter, outputSchema: personSchema }),
423 )
424
425 await act(async () => {
426 await result.current.sendMessage('A')
427 })
428 await waitFor(() => {
429 expect(result.current.final).toEqual(personA)
430 })
431
432 act(() => {
433 void result.current.sendMessage('B')
434 })
435
436 await waitFor(() => {
437 expect(result.current.final).toBeNull()
438 expect(result.current.partial).toEqual({})
439 })
440
441 releaseSecond()
442 })
443
444 it('clears `partial` and `final` on clear()', async () => {
445 // `clear()` empties the messages array; the derivation then has no
446 // assistant message to find an active structured-output part on, so
447 // both views naturally read as cleared without any extra plumbing.
448 const chunks = buildStructuredStream(json, person)
449 const adapter = createMockConnectionAdapter({ chunks })
450
451 const { result } = renderHook(() =>
452 useChat({ connection: adapter, outputSchema: personSchema }),
453 )
454
455 await act(async () => {
456 await result.current.sendMessage('Extract')
457 })
458 await waitFor(() => {
459 expect(result.current.final).toEqual(person)
460 })
461
462 act(() => {
463 result.current.clear()
464 })
465
466 expect(result.current.partial).toEqual({})
467 expect(result.current.final).toBeNull()
468 })
469
470 it("invokes the user's onChunk callback alongside internal tracking", async () => {
471 const chunks = buildStructuredStream(json, person)
472 const adapter = createMockConnectionAdapter({ chunks })
473 const onChunk = vi.fn()
474
475 const { result } = renderHook(() =>
476 useChat({
477 connection: adapter,
478 outputSchema: personSchema,
479 onChunk,
480 }),
481 )
482
483 await act(async () => {
484 await result.current.sendMessage('Extract')
485 })
486 await waitFor(() => {
487 expect(result.current.final).toEqual(person)
488 })
489
490 // User callback fires for every chunk the hook sees, including the
491 // terminal structured-output.complete event.
492 const completeCalls = onChunk.mock.calls.filter(
493 ([c]) => c.type === 'CUSTOM' && c.name === 'structured-output.complete',
494 )
495 expect(completeCalls.length).toBe(1)
496 expect(completeCalls[0]![0].value).toEqual({ object: person, raw: json })
497
498 const deltaCalls = onChunk.mock.calls.filter(
499 ([c]) => c.type === 'TEXT_MESSAGE_CONTENT',
500 )
501 expect(deltaCalls.length).toBeGreaterThan(0)
502 })
503})
504
505describe('useChat({ outputSchema }) — initialMessages handling', () => {
506 const person: Person = {
507 name: 'John Doe',
508 age: 30,
509 email: 'john@example.com',
510 }
511 const json = JSON.stringify(person)
512
513 it('does not leak `final` from a stale initialMessages assistant when no user message exists yet', async () => {
514 // Regression: `activeStructuredPart` previously walked all assistant
515 // messages from the end when there was no user message — so a structured
516 // assistant turn carried in via `initialMessages` would leak into `final`
517 // before the consumer ever sent anything. With the fix, `final` reads
518 // null until a user message exists.
519 const adapter = createMockConnectionAdapter({ chunks: [] })
520
521 const { result } = renderHook(() =>
522 useChat({
523 connection: adapter,
524 outputSchema: personSchema,
525 initialMessages: [
526 {
527 id: 'stale-assistant',
528 role: 'assistant',
529 parts: [
530 {
531 type: 'structured-output',
532 status: 'complete',
533 raw: json,
534 data: person,
535 partial: person,
536 },
537 ],
538 createdAt: new Date(),
539 },
540 ],
541 }),
542 )
543
544 // The stale assistant message is visible in history…
545 await waitFor(() => {
546 expect(result.current.messages.length).toBeGreaterThan(0)
547 })
548 expect(result.current.messages[0]?.id).toBe('stale-assistant')
549
550 // …but `final` and `partial` must NOT be derived from it.
551 expect(result.current.final).toBeNull()
552 expect(result.current.partial).toEqual({})
553 })
554})
555
556describe('useChat() without outputSchema — runtime', () => {
557 it('does not break or track structured state when no schema is supplied', async () => {
558 const adapter = createMockConnectionAdapter({
559 chunks: [
560 {
561 type: 'RUN_STARTED',
562 runId: 'r',
563 threadId: 't',
564 model: 'test',
565 timestamp: Date.now(),
566 } as StreamChunk,
567 {
568 type: 'TEXT_MESSAGE_CONTENT',
569 messageId: 'm',
570 delta: 'Hello',
571 content: 'Hello',
572 model: 'test',
573 timestamp: Date.now(),
574 } as StreamChunk,
575 {
576 type: 'RUN_FINISHED',
577 runId: 'r',
578 threadId: 't',
579 model: 'test',
580 timestamp: Date.now(),
581 finishReason: 'stop',
582 } as StreamChunk,
583 ],
584 })
585
586 const { result } = renderHook(() => useChat({ connection: adapter }))
587
588 await act(async () => {
589 await result.current.sendMessage('hi')
590 })
591 await waitFor(() => {
592 expect(result.current.messages.length).toBeGreaterThan(0)
593 })
594 // The return object doesn't expose `partial`/`final` at the type level
595 // (the discriminated `UseChatReturn` only adds them when `outputSchema` is
596 // supplied), and the runtime branch in onChunk is gated on
597 // `outputSchema !== undefined` so the internal state never updates.
598 // Runtime access is the only way to verify the no-op branch. TS cannot
599 // express "this object happens to also carry these fields at runtime
600 // even though the type says it doesn't", so a single bridge cast to
601 // `unknown` is the minimum legal escape.
602 const runtimeView: { partial?: unknown; final?: unknown } =
603 result.current as unknown as { partial?: unknown; final?: unknown }
604 expect(runtimeView.partial).toEqual({})
605 expect(runtimeView.final).toBeNull()
606 })
607})