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

create-ui.test.tsx

710 lines20.1 KB

1import { renderToStaticMarkup } from 'react-dom/server'
2import { describe, expect, it, vi } from 'vitest'
3import { createChatUI } from '../../src/chat-ui/create-ui'
4import { createChatHook } from '../../src/chat-ui/create-chat-hook'
5import { createChatHookContexts } from '../../src/chat-ui/create-ui-contexts'
6import type {
7 ChatUIFactoryConfig,
8 ChatUIHost,
9 SubagentProps,
10} from '../../src/chat-ui/create-ui'
11import {
12 chatOptions,
13 createChatResult,
14 genericInterrupt,
15 messageWithToolResults,
16 orphanResultMessage,
17 purchaseApprovalInterrupt,
18 purchaseApprovalMessage,
19 unboundInterrupt,
20 unknownToolMessage,
21} from '../../../ai-client/tests/ui-fixtures'
22import type { ToolCallState } from '@tanstack/ai-client'
23​
24function host(
25 init?: Parameters<typeof createChatResult>[0],
26): ChatUIHost<typeof chatOptions> {
27 return createChatResult(init ?? {}) as unknown as ChatUIHost<
28 typeof chatOptions
29 >
31​
32const baseConfig: ChatUIFactoryConfig<typeof chatOptions> = {
33 components: {
34 layout: ({ Messages, Interrupts }) => (
35 <>
36 <Messages />
37 <Interrupts />
38 </>
39 ),
40 message: ({ Parts }) => (
41 <article>
42 <Parts />
43 </article>
44 ),
45 },
46 partsComponents: { fallback: ({ part }) => <span>{part.type}</span> },
47 toolsComponents: {
48 getWeather: ({ part }) => <strong>{part.input?.city}</strong>,
49 purchaseItem: () => null,
50 },
51 interruptsComponents: {
52 generic: {
53 choosePlan: () => null,
54 fallback: ({ interrupt }) => <i>{interrupt.reason}</i>,
55 },
56 },
58​
59type Config = ChatUIFactoryConfig<typeof chatOptions>
60​
61// The helper keeps `layout` / `message` / `input` flat for brevity and
62// assembles them into `components`; the shape under test is what reaches
63// `createChatUI`.
64function makeUI(patch?: {
65 context?: Config['context']
66 layout?: Config['components']['layout']
67 message?: Config['components']['message']
68 input?: Config['components']['input']
69 queue?: Config['components']['queue']
70 partsComponents?: Config['partsComponents']
71 subagentsComponents?: Config['subagentsComponents']
72 toolsComponents?: Config['toolsComponents']
73 interruptsComponents?: {
74 tools?: Config['interruptsComponents']['tools']
75 generic?: Partial<Config['interruptsComponents']['generic']>
76 }
77}) {
78 return createChatUI(chatOptions, {
79 ...(patch?.context ? { context: patch.context } : {}),
80 components: {
81 ...baseConfig.components,
82 ...(patch?.layout ? { layout: patch.layout } : {}),
83 ...(patch?.message ? { message: patch.message } : {}),
84 ...(patch?.input ? { input: patch.input } : {}),
85 ...(patch?.queue ? { queue: patch.queue } : {}),
86 },
87 partsComponents: {
88 ...baseConfig.partsComponents,
89 ...patch?.partsComponents,
90 },
91 toolsComponents: {
92 ...baseConfig.toolsComponents,
93 ...patch?.toolsComponents,
94 },
95 interruptsComponents: {
96 tools: {
97 ...baseConfig.interruptsComponents.tools,
98 ...patch?.interruptsComponents?.tools,
99 },
100 generic: {
101 ...baseConfig.interruptsComponents.generic,
102 ...patch?.interruptsComponents?.generic,
103 },
104 },
105 ...(patch?.subagentsComponents
106 ? { subagentsComponents: patch.subagentsComponents }
107 : {}),
108 })
110​
111describe('createChatHook', () => {
112 it('mixes AppChat onto the instance from options and chatComponents', () => {
113 const { useAppChat, useChatContext } = createChatHook({
114 options: chatOptions,
115 ...baseConfig,
116 })
117 expect(typeof useAppChat).toBe('function')
118 expect(typeof useChatContext).toBe('function')
119​
120 function Screen() {
121 const chat = useAppChat({
122 initialMessages: [messageWithToolResults] as ChatUIHost<
123 typeof chatOptions
124 >['messages'],
125 })
126 return <chat.AppChat />
127 }
128​
129 const markup = renderToStaticMarkup(<Screen />)
130 expect(markup).toContain('<strong>Paris</strong>')
131 })
132})
133​
134describe('createChatUI', () => {
135 it('renders automatic and manual trees', () => {
136 const UI = makeUI()
137 const chat = host({ messages: [messageWithToolResults] })
138 const automatic = renderToStaticMarkup(<UI.Chat chat={chat} />)
139 expect(automatic).toContain('<strong>Paris</strong>')
140​
141 const manual = renderToStaticMarkup(
142 <UI.Provider chat={chat}>
143 <UI.Messages>
144 {(messages) => <span>{messages.length}</span>}
145 </UI.Messages>
146 </UI.Provider>,
147 )
148 expect(manual).toContain('<span>1</span>')
149 })
150​
151 it('warns once for a missing runtime key', () => {
152 const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
153 const UI = makeUI()
154 const chat = host({ messages: [unknownToolMessage] })
155 renderToStaticMarkup(<UI.Chat chat={chat} />)
156 renderToStaticMarkup(<UI.Chat chat={chat} />)
157 expect(warn).toHaveBeenCalledTimes(1)
158 warn.mockRestore()
159 })
160​
161 it('renders nested subagent text through Parts', () => {
162 const handle = {
163 id: 'sub-1',
164 name: 'researcher',
165 status: 'running' as const,
166 messages: [
167 {
168 id: 'child-1',
169 role: 'assistant' as const,
170 parts: [{ type: 'text' as const, content: 'Notes from the child' }],
171 },
172 ],
173 }
174 const UI = makeUI({
175 partsComponents: {
176 text: ({ part }) => <p>{part.content}</p>,
177 },
178 subagentsComponents: {
179 researcher: ({
180 subagent,
181 Parts,
182 }: SubagentProps<typeof chatOptions>) => (
183 <section>
184 <strong>{subagent.name}</strong>
185 <Parts />
186 </section>
187 ),
188 },
189 })
190 const markup = renderToStaticMarkup(
191 <UI.Chat
192 chat={host({
193 messages: [
194 {
195 id: 'parent-1',
196 role: 'assistant',
197 parts: [{ type: 'subagent', subagent: handle }],
198 },
199 ],
200 })}
201 />,
202 )
203 expect(markup).toContain('researcher')
204 expect(markup).toContain('Notes from the child')
205 })
206​
207 it('lets a card override part and tool widgets for its subtree', () => {
208 const thinking = { type: 'thinking' as const, content: 'plan' }
209 const weather = {
210 type: 'tool-call' as const,
211 id: 'call-1',
212 name: 'getWeather' as const,
213 arguments: '{"city":"Rome"}',
214 input: { city: 'Rome' },
215 state: 'input-complete' as const,
216 }
217 const nested = {
218 id: 'sub-2',
219 name: 'writer',
220 status: 'running' as const,
221 messages: [
222 { id: 'grandchild', role: 'assistant' as const, parts: [thinking] },
223 ],
224 }
225 const handle = {
226 id: 'sub-1',
227 name: 'researcher',
228 status: 'running' as const,
229 messages: [
230 {
231 id: 'child-1',
232 role: 'assistant' as const,
233 parts: [
234 thinking,
235 weather,
236 { type: 'text' as const, content: 'child text' },
237 { type: 'subagent' as const, subagent: nested },
238 ],
239 },
240 ],
241 }
242 const cardParts = {
243 thinking: ({ part }: { part: { content: string } }) => (
244 <em>card:{part.content}</em>
245 ),
246 }
247 const cardTools = {
248 getWeather: ({ part }: { part: { arguments: string } }) => (
249 <b>card:{part.arguments}</b>
250 ),
251 }
252 const UI = makeUI({
253 partsComponents: {
254 text: ({ part }) => <p>root:{part.content}</p>,
255 thinking: ({ part }) => <i>root:{part.content}</i>,
256 },
257 subagentsComponents: {
258 researcher: ({ Parts }: SubagentProps<typeof chatOptions>) => (
259 <section>
260 <Parts partsComponents={cardParts} toolsComponents={cardTools} />
261 </section>
262 ),
263 writer: ({ Parts }: SubagentProps<typeof chatOptions>) => (
264 <aside>
265 <Parts />
266 </aside>
267 ),
268 },
269 })
270 const markup = renderToStaticMarkup(
271 <UI.Chat
272 chat={host({
273 messages: [
274 {
275 id: 'parent-1',
276 role: 'assistant',
277 parts: [
278 thinking,
279 weather,
280 { type: 'subagent', subagent: handle },
281 ],
282 },
283 ],
284 })}
285 />,
286 )
287 // The root message keeps the root widgets.
288 expect(markup).toContain('<i>root:plan</i>')
289 expect(markup).toContain('<strong>Rome</strong>')
290 // The card uses its overrides, and the root for keys it does not set.
291 expect(markup).toContain('<b>card:{&quot;city&quot;:&quot;Rome&quot;}</b>')
292 expect(markup).toContain('<p>root:child text</p>')
293 // A nested child inherits the card overrides.
294 expect(markup).toContain('<aside><em>card:plan</em></aside>')
295 expect(markup.match(/<em>card:plan<\/em>/g)).toHaveLength(2)
296 })
297​
298 it('renders the live subagent list through Subagents', () => {
299 const handle = {
300 id: 'sub-1',
301 name: 'writer',
302 status: 'running' as const,
303 messages: [],
304 }
305 const UI = makeUI({
306 layout: ({ Subagents }) => <Subagents />,
307 subagentsComponents: {
308 writer: ({ subagent }: SubagentProps<typeof chatOptions>) => (
309 <p>
310 {subagent.name}:{subagent.status}
311 </p>
312 ),
313 },
314 })
315 const markup = renderToStaticMarkup(
316 <UI.Chat chat={host({ subagents: [handle] })} />,
317 )
318 expect(markup).toContain('writer:running')
319 })
320​
321 it('throws when a subagent name has no component', () => {
322 const handle = {
323 id: 'sub-1',
324 name: 'researcher',
325 status: 'running' as const,
326 messages: [],
327 }
328 const UI = makeUI()
329 expect(() =>
330 renderToStaticMarkup(
331 <UI.Chat
332 chat={host({
333 messages: [
334 {
335 id: 'parent-1',
336 role: 'assistant',
337 parts: [{ type: 'subagent', subagent: handle }],
338 },
339 ],
340 })}
341 />,
342 ),
343 ).toThrow('Missing subagentsComponents.researcher')
344 })
345​
346 it('keeps unmatched tool results and suppresses matched ones', () => {
347 const UI = makeUI({
348 partsComponents: {
349 toolResult: ({ part }) =>
350 part.type === 'tool-result' ? <em>{String(part.content)}</em> : null,
351 fallback: () => null,
352 },
353 toolsComponents: {
354 getWeather: () => <strong>weather</strong>,
355 purchaseItem: () => null,
356 },
357 })
358​
359 const matched = renderToStaticMarkup(
360 <UI.Chat chat={host({ messages: [messageWithToolResults] })} />,
361 )
362 expect(matched).toContain('<strong>weather</strong>')
363 expect(matched).not.toContain('<em>')
364​
365 const unmatched = renderToStaticMarkup(
366 <UI.Chat chat={host({ messages: [orphanResultMessage] })} />,
367 )
368 expect(unmatched).toContain('<em>standalone</em>')
369 })
370​
371 it('puts list approvals in Interrupts when interrupts.tools has the tool', () => {
372 const UI = makeUI({
373 toolsComponents: {
374 getWeather: () => null,
375 purchaseItem: () => <div>tool</div>,
376 },
377 interruptsComponents: {
378 tools: {
379 purchaseItem: () => <b>list-approval</b>,
380 },
381 generic: { choosePlan: () => null, fallback: () => null },
382 },
383 })
384​
385 const listMarkup = renderToStaticMarkup(
386 <UI.Chat
387 chat={host({
388 messages: [purchaseApprovalMessage],
389 interrupts: [purchaseApprovalInterrupt],
390 })}
391 />,
392 )
393 expect(listMarkup).toContain('list-approval')
394 expect(listMarkup).toContain('tool')
395 })
396​
397 it('lets a tool render its approval from interrupt without a registered interrupt component', () => {
398 const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
399 const UI = makeUI({
400 toolsComponents: {
401 getWeather: () => null,
402 purchaseItem: ({ interrupt }) =>
403 interrupt ? <b>{interrupt.toolName}</b> : <span>tool</span>,
404 },
405 interruptsComponents: {
406 generic: { choosePlan: () => null, fallback: () => <i>list</i> },
407 },
408 })
409 const markup = renderToStaticMarkup(
410 <UI.Chat
411 chat={host({
412 messages: [purchaseApprovalMessage],
413 interrupts: [purchaseApprovalInterrupt],
414 })}
415 />,
416 )
417 expect(markup).toContain('<b>purchaseItem</b>')
418 expect(markup).not.toContain('<i>list</i>')
419 expect(
420 warn.mock.calls.filter((call) =>
421 String(call[0]).includes('[tanstack-ai-ui]'),
422 ),
423 ).toHaveLength(0)
424 warn.mockRestore()
425 })
426​
427 it('renders registered generic interrupts and sends the rest to fallback', () => {
428 const UI = makeUI({
429 layout: ({ Interrupts }) => <Interrupts />,
430 interruptsComponents: {
431 generic: {
432 choosePlan: () => <span>plan</span>,
433 fallback: () => <span>fallback</span>,
434 },
435 },
436 })
437​
438 const markup = renderToStaticMarkup(
439 <UI.Chat
440 chat={host({
441 interrupts: [genericInterrupt, unboundInterrupt],
442 })}
443 />,
444 )
445 expect(markup).toContain('plan')
446 expect(markup).toContain('fallback')
447 })
448​
449 it('warns once when layout renders an Input that was never registered', () => {
450 const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
451 const UI = makeUI({
452 layout: ({ Input }) => (
453 <main>
454 <Input />
455 </main>
456 ),
457 })
458 // Twice: the warning is once per kit, not once per render.
459 renderToStaticMarkup(<UI.Chat chat={host({})} />)
460 const markup = renderToStaticMarkup(<UI.Chat chat={host({})} />)
461 expect(markup).toBe('<main></main>')
462 expect(warn).toHaveBeenCalledTimes(1)
463 expect(String(warn.mock.calls[0]?.[0])).toContain(
464 'no `input` component is registered',
465 )
466 warn.mockRestore()
467 })
468​
469 it('passes Input to layout when an input component is registered', () => {
470 const UI = createChatUI(chatOptions, {
471 ...baseConfig,
472 components: {
473 ...baseConfig.components,
474 input: () => <textarea defaultValue="prompt" />,
475 layout: ({ Input }) => (
476 <main>
477 <Input />
478 </main>
479 ),
480 },
481 })
482 const markup = renderToStaticMarkup(<UI.Chat chat={host({})} />)
483 expect(markup).toContain('prompt')
484 })
485​
486 it('mixes Input onto the UI kit when one is registered', () => {
487 const UI = makeUI({
488 input: () => <textarea defaultValue="prompt" />,
489 })
490 const Input = UI.Input
491 if (!Input) throw new Error('expected Input')
492 const markup = renderToStaticMarkup(
493 <UI.Provider chat={host({})}>
494 <Input />
495 </UI.Provider>,
496 )
497 expect(markup).toContain('prompt')
498 })
499​
500 it('lets Message children pick a mixed part or tool widget', () => {
501 const UI = makeUI({
502 partsComponents: {
503 fallback: () => <span>fallback</span>,
504 text: ({ part }) =>
505 part.type === 'text' ? <em>{part.content}</em> : null,
506 },
507 })
508 const chat = host({ messages: [messageWithToolResults] })
509 const markup = renderToStaticMarkup(
510 <UI.Provider chat={chat}>
511 <UI.Messages>
512 {(messages) =>
513 messages.map((message) => (
514 <UI.Message key={message.id} message={message}>
515 {(parts) =>
516 parts.map((part, index) => (
517 <UI.Part key={index} part={part}>
518 {(p) =>
519 part.key === 'toolCall' ? (
520 <p.getWeather />
521 ) : (
522 <p.Render />
523 )
524 }
525 </UI.Part>
526 ))
527 }
528 </UI.Message>
529 ))
530 }
531 </UI.Messages>
532 </UI.Provider>,
533 )
534 expect(markup).toContain('<strong>Paris</strong>')
535 })
536​
537 it('lets Interrupt children pick a mixed interrupt widget', () => {
538 const UI = makeUI({
539 layout: ({ Interrupts }) => <Interrupts />,
540 interruptsComponents: {
541 generic: {
542 choosePlan: () => <span>plan</span>,
543 fallback: () => <span>fallback</span>,
544 },
545 },
546 })
547 const markup = renderToStaticMarkup(
548 <UI.Provider
549 chat={host({
550 interrupts: [genericInterrupt],
551 })}
552 >
553 <UI.Interrupts>
554 {(interrupts) =>
555 interrupts.map((interrupt) => (
556 <UI.Interrupt key={interrupt.id} interrupt={interrupt}>
557 {(item) => {
558 const ChoosePlan = item.choosePlan
559 return <ChoosePlan />
560 }}
561 </UI.Interrupt>
562 ))
563 }
564 </UI.Interrupts>
565 </UI.Provider>,
566 )
567 expect(markup).toContain('plan')
568 })
569​
570 it('reads chat from nested provider context and throws outside a provider', () => {
571 const UI = makeUI({
572 layout: () => {
573 const chat = UI.useChatContext()
574 return <p>{chat.messages.length}</p>
575 },
576 })
577​
578 const inner = host({ messages: [messageWithToolResults] })
579 const outer = host({ messages: [] })
580 const markup = renderToStaticMarkup(
581 <UI.Provider chat={outer}>
582 <UI.Chat chat={inner} />
583 </UI.Provider>,
584 )
585 expect(markup).toContain('<p>1</p>')
586​
587 function Broken() {
588 UI.useChatContext()
589 return null
590 }
591 expect(() => renderToStaticMarkup(<Broken />)).toThrow(/useChatContext/)
592 })
593​
594 it('isolates nested chats when createChatHookContexts is passed in', () => {
595 const innerContexts = createChatHookContexts()
596 const Outer = makeUI({
597 layout: () => {
598 const chat = Outer.useChatContext()
599 return <p data-outer="">{chat.messages.length}</p>
600 },
601 })
602 const Inner = makeUI({
603 context: {
604 chatContext: innerContexts.chatContext,
605 partContext: innerContexts.partContext,
606 interruptContext: innerContexts.interruptContext,
607 },
608 layout: () => {
609 const chat = Inner.useChatContext()
610 return <p data-inner="">{chat.messages.length}</p>
611 },
612 })
613​
614 const markup = renderToStaticMarkup(
615 <Outer.Provider chat={host({ messages: [] })}>
616 <Inner.Chat chat={host({ messages: [messageWithToolResults] })} />
617 </Outer.Provider>,
618 )
619 expect(markup).toContain('data-inner')
620 expect(markup).toContain('<p data-inner="">1</p>')
621 })
622​
623 it('renders a tool component for every ToolCallState', () => {
624 const states: Array<ToolCallState> = [
625 'awaiting-input',
626 'input-streaming',
627 'input-complete',
628 'approval-requested',
629 'approval-responded',
630 'complete',
631 'error',
632 ]
633 const UI = makeUI({
634 toolsComponents: {
635 getWeather: ({ part }) => <span>{part.state}</span>,
636 purchaseItem: () => null,
637 },
638 })
639​
640 for (const state of states) {
641 const markup = renderToStaticMarkup(
642 <UI.Chat
643 chat={host({
644 messages: [
645 {
646 id: state,
647 role: 'assistant',
648 parts: [
649 {
650 type: 'tool-call',
651 id: `call-${state}`,
652 name: 'getWeather',
653 arguments: '{}',
654 state,
655 },
656 ],
657 },
658 ],
659 })}
660 />,
661 )
662 expect(markup).toContain(`<span>${state}</span>`)
663 }
664 })
665​
666 it('renders each queued item and binds cancelQueued', () => {
667 const cancelled: Array<string> = []
668 const UI = makeUI({
669 layout: ({ Queue }) => <Queue />,
670 queue: ({ item }) => {
671 item.cancelQueued()
672 return <em>{typeof item.content === 'string' ? item.content : ''}</em>
673 },
674 })
675 const markup = renderToStaticMarkup(
676 <UI.Chat
677 chat={host({
678 queue: [
679 { id: 'q1', content: 'later', createdAt: 1 },
680 { id: 'q2', content: 'after', createdAt: 2 },
681 ],
682 cancelQueued: (id) => {
683 cancelled.push(id)
684 },
685 })}
686 />,
687 )
688 expect(markup).toContain('<em>later</em>')
689 expect(markup).toContain('<em>after</em>')
690 expect(cancelled).toEqual(['q1', 'q2'])
691 })
692​
693 it('renders nothing from Queue when no queue component exists', () => {
694 const UI = makeUI({
695 layout: ({ Queue }) => (
696 <main>
697 <Queue />
698 </main>
699 ),
700 })
701 const markup = renderToStaticMarkup(
702 <UI.Chat
703 chat={host({
704 queue: [{ id: 'q1', content: 'later', createdAt: 1 }],
705 })}
706 />,
707 )
708 expect(markup).toBe('<main></main>')
709 })
710})