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

use-chat-structured-output.test.ts

635 lines19.1 KB

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