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