Open History to see the last commit
1import { createContext, memo, useContext, useMemo } from 'react'
2import type { ComponentProps, ComponentType, Context, ReactNode } from 'react'
3import {
4 automaticPartsForMessage,
5 collectInlineToolNames,
6 resolveInterruptComponent,
7 selectChatUI,
8 selectMessageUI,
9} from '@tanstack/ai-client/ui'
10import type {
11 ChatUIApprovalToolName,
12 ChatUIData,
13 ChatUIHasNamedInterrupts,
14 ChatUIHasNamedSubagents,
15 ChatUIHasNamedTools,
16 ChatUIInterrupt,
17 ChatUIInterruptName,
18 ChatUIInterruptOf,
19 ChatUIInterruptsOf,
20 ChatUIMessages,
21 ChatUINamedInterruptId,
22 ChatUIPartKey,
23 ChatUIPartOf,
24 ChatUISchemaOf,
25 ChatUISelectedPart,
26 ChatUISelectedPartOf,
27 ChatUISubagentName,
28 ChatUISubagentOf,
29 ChatUISubagentOptions,
30 ChatUIToolApproval,
31 ChatUIToolName,
32 ChatUIToolsOf,
33} from '@tanstack/ai-client/ui'
34import type {
35 MessagePart,
36 QueuedMessage,
37 SubagentHandle,
38 SubagentHandles,
39 ToolCallPart,
40 ToolResultPart,
41 UIMessage,
42} from '@tanstack/ai-client'
43import type { UseChatReturn } from '../types'
44import { defaultChatUIContexts } from './create-ui-contexts'
45import type { ChatUIContexts } from './create-ui-contexts'
46
47export type ChatUIHost<TOptions = unknown> = UseChatReturn<
48 ChatUIToolsOf<TOptions>,
49 ChatUISchemaOf<TOptions>,
50 ChatUIInterruptsOf<TOptions>
51>
52
53export type ChatUIQueueItem = QueuedMessage & {
54 cancelQueued: () => void
55}
56
57export type LayoutProps<
58 TOptions,
59 TInput extends ComponentType<any> | undefined = ComponentType<
60 InputProps<TOptions>
61 >,
62> = {
63 Messages: ComponentType
64 Interrupts: ComponentType
65 Queue: ComponentType
66 Subagents: ComponentType
67 readonly __ui?: TOptions
68} & (TInput extends ComponentType<any> ? { Input: ComponentType } : {})
69
70export type MessageProps<TOptions> = {
71 message: UIMessage<ChatUIToolsOf<TOptions>, ChatUIData<TOptions>>
72 Parts: ComponentType
73}
74
75export type InputProps<TOptions> = {
76 readonly __ui?: TOptions
77}
78
79export type QueueProps<TOptions> = {
80 item: ChatUIQueueItem
81 readonly __ui?: TOptions
82}
83
84export type PartProps<TOptions, TKey extends ChatUIPartKey = ChatUIPartKey> = {
85 part: ChatUIPartOf<TOptions, TKey>
86}
87
88/**
89 * Widgets for one subagent card. Each entry replaces the enclosing entry of
90 * the same key: the root map at top level, the outer card's map when nested.
91 * It applies to this card and the children nested in it. An unset key keeps
92 * the enclosing entry. Tool names and tool props come from that agent's
93 * `tools`.
94 */
95export type SubagentPartsProps<
96 TOptions,
97 TName extends ChatUISubagentName<TOptions> = ChatUISubagentName<TOptions>,
98> = {
99 partsComponents?: ChatUIPartsComponents<
100 ChatUISubagentOptions<TOptions, TName>
101 >
102 toolsComponents?: {
103 [K in ChatUIToolName<
104 ChatUISubagentOptions<TOptions, TName>
105 >]?: ComponentType<ToolProps<ChatUISubagentOptions<TOptions, TName>, K>>
106 }
107}
108
109export type SubagentProps<
110 TOptions,
111 TName extends ChatUISubagentName<TOptions> = ChatUISubagentName<TOptions>,
112> = {
113 subagent: [ChatUISubagentOf<TOptions, TName>] extends [never]
114 ? SubagentHandle & { name: TName }
115 : SubagentHandles<ReadonlyArray<ChatUISubagentOf<TOptions, TName>>>
116 Parts: ComponentType<SubagentPartsProps<TOptions, TName>>
117 readonly __ui?: TOptions
118}
119
120export type ToolProps<
121 TOptions,
122 TName extends ChatUIToolName<TOptions> = ChatUIToolName<TOptions>,
123> = {
124 part: Extract<ToolCallPart<ChatUIToolsOf<TOptions>>, { name: TName }>
125 result?: ToolResultPart
126 interrupt?: ChatUIToolApproval<TOptions, TName>
127}
128
129export type InterruptProps<
130 TOptions,
131 TName extends ChatUIInterruptName<TOptions> = never,
132> = {
133 interrupt: ChatUIInterruptOf<TOptions, TName>
134 readonly __ui?: TOptions
135}
136
137type GenericInterruptComponents<TOptions> =
138 ChatUIHasNamedInterrupts<TOptions> extends true
139 ? {
140 [K in ChatUINamedInterruptId<TOptions>]: ComponentType<
141 InterruptProps<TOptions, K & ChatUIInterruptName<TOptions>>
142 >
143 } & {
144 fallback?: ComponentType<InterruptProps<TOptions>>
145 }
146 : {
147 fallback?: ComponentType<InterruptProps<TOptions>>
148 }
149
150type ToolApprovalMap<TOptions> = {
151 [K in ChatUIApprovalToolName<TOptions>]?: ComponentType<
152 InterruptProps<TOptions, K & ChatUIInterruptName<TOptions>>
153 >
154}
155
156/** The chrome around the message list: `layout`, `message`, and `input`. */
157export type ChatUIChromeComponents<
158 TOptions,
159 TInput extends ComponentType<InputProps<TOptions>> | undefined =
160 ComponentType<InputProps<TOptions>>,
161> = {
162 layout: ComponentType<LayoutProps<TOptions, TInput>>
163 message: ComponentType<MessageProps<TOptions>>
164 input?: TInput
165 queue?: ComponentType<QueueProps<TOptions>>
166}
167
168export type ChatUIPartsComponents<TOptions> = {
169 [K in ChatUIPartKey]?: ComponentType<PartProps<TOptions, K>>
170} & {
171 fallback?: ComponentType<PartProps<TOptions>>
172}
173
174export type ChatUIInterruptsComponents<TOptions> = {
175 tools?: ToolApprovalMap<TOptions>
176 generic: GenericInterruptComponents<TOptions>
177}
178
179export type ChatUIComponents<
180 TOptions,
181 TInput extends ComponentType<InputProps<TOptions>> | undefined =
182 ComponentType<InputProps<TOptions>>,
183> = {
184 components: ChatUIChromeComponents<TOptions, TInput>
185 partsComponents: ChatUIPartsComponents<TOptions>
186} & (ChatUIHasNamedTools<TOptions> extends true
187 ? {
188 toolsComponents: {
189 [K in ChatUIToolName<TOptions>]: ComponentType<ToolProps<TOptions, K>>
190 }
191 }
192 : {
193 toolsComponents?: {
194 [K in ChatUIToolName<TOptions>]?: ComponentType<ToolProps<TOptions, K>>
195 }
196 }) &
197 (ChatUIHasNamedInterrupts<TOptions> extends true
198 ? { interruptsComponents: ChatUIInterruptsComponents<TOptions> }
199 : {
200 interruptsComponents?: {
201 tools?: ToolApprovalMap<TOptions>
202 generic?: GenericInterruptComponents<TOptions>
203 }
204 }) &
205 (ChatUIHasNamedSubagents<TOptions> extends true
206 ? {
207 subagentsComponents: {
208 [K in ChatUISubagentName<TOptions>]: ComponentType<
209 SubagentProps<TOptions, K>
210 >
211 }
212 }
213 : {
214 subagentsComponents?: {
215 [K in ChatUISubagentName<TOptions>]?: ComponentType<
216 SubagentProps<TOptions, K>
217 >
218 }
219 })
220
221/** Scoped contexts, for widgets in other files or nested chat trees. */
222export type ChatUIContextConfig = {
223 chatContext?: ChatUIContexts['chatContext']
224 partContext?: ChatUIContexts['partContext']
225 interruptContext?: ChatUIContexts['interruptContext']
226}
227
228export type ChatUIFactoryConfig<
229 TOptions,
230 TInput extends ComponentType<InputProps<TOptions>> | undefined =
231 ComponentType<InputProps<TOptions>>,
232> = ChatUIComponents<TOptions, TInput> & {
233 context?: ChatUIContextConfig
234}
235
236type BoundWidget = ComponentType<Record<string, never>>
237
238type PartMixins<TOptions> = {
239 [K in ChatUIPartKey]?: BoundWidget
240} & {
241 [K in ChatUIToolName<TOptions>]: BoundWidget
242} & {
243 Render: BoundWidget
244}
245
246type InterruptMixins<TOptions> = {
247 [K in ChatUINamedInterruptId<TOptions>]: BoundWidget
248} & {
249 [K in ChatUIApprovalToolName<TOptions>]?: BoundWidget
250} & {
251 fallback?: BoundWidget
252 Render: BoundWidget
253}
254
255function createWarnOnce() {
256 const seen = new Set<string>()
257 return (key: string, message: string) => {
258 if (process.env.NODE_ENV === 'production') return
259 if (seen.has(key)) return
260 seen.add(key)
261 console.warn(message)
262 }
263}
264
265function readMessages<TOptions>(chat: ChatUIHost<TOptions>) {
266 return chat.messages as ChatUIMessages<TOptions>
267}
268
269function readInterrupts<TOptions>(chat: ChatUIHost<TOptions>) {
270 return chat.interrupts ?? []
271}
272
273function queueItemEqual(
274 prev: { item: QueuedMessage; cancelQueued: (id: string) => void },
275 next: { item: QueuedMessage; cancelQueued: (id: string) => void },
276) {
277 return (
278 prev.item.id === next.item.id &&
279 prev.item.createdAt === next.item.createdAt &&
280 prev.item.content === next.item.content &&
281 prev.cancelQueued === next.cancelQueued
282 )
283}
284
285// The handle is one live object that the client updates in place, so a row
286// gets its changing card fields as separate props. Messages are not one of
287// them: `SubagentMessages` reads them from the chat context, so new child
288// text shows without a row render.
289type SubagentRowProps = {
290 handle: SubagentHandle
291 status: SubagentHandle['status']
292 error: SubagentHandle['error']
293}
294
295function subagentListItemEqual(prev: SubagentRowProps, next: SubagentRowProps) {
296 return (
297 prev.handle.id === next.handle.id &&
298 prev.handle.stop === next.handle.stop &&
299 prev.status === next.status &&
300 prev.error === next.error
301 )
302}
303
304function subagentMessagesEqual(
305 prev: { messages: SubagentHandle['messages'] },
306 next: { messages: SubagentHandle['messages'] },
307) {
308 return prev.messages === next.messages
309}
310
311function selectedPartPropsEqual(
312 prev: { selected: ChatUISelectedPart },
313 next: { selected: ChatUISelectedPart },
314) {
315 if (prev.selected.key !== next.selected.key) return false
316 if (prev.selected.part !== next.selected.part) return false
317 if (prev.selected.key === 'toolCall' && next.selected.key === 'toolCall') {
318 return (
319 prev.selected.result === next.selected.result &&
320 prev.selected.interrupt === next.selected.interrupt
321 )
322 }
323 if (
324 prev.selected.key === 'toolResult' &&
325 next.selected.key === 'toolResult'
326 ) {
327 return prev.selected.matched === next.selected.matched
328 }
329 return true
330}
331
332function isSelectedPart(
333 value: MessagePart | ChatUISelectedPart,
334): value is ChatUISelectedPart {
335 return 'key' in value && 'part' in value
336}
337
338/** `base` with each set entry of `overrides`. An unset entry keeps `base`. */
339function withWidgets(
340 base: Record<string, ComponentType<any> | undefined>,
341 overrides: Record<string, ComponentType<any> | undefined> | undefined,
342) {
343 const out = { ...base }
344 for (const [key, component] of Object.entries(overrides ?? {})) {
345 if (component) out[key] = component
346 }
347 return out
348}
349
350function bindMap(
351 map: Record<string, ComponentType<any> | undefined> | undefined,
352 bind: (component: ComponentType<any>) => BoundWidget,
353) {
354 const out: Record<string, BoundWidget> = {}
355 for (const [key, component] of Object.entries(map ?? {})) {
356 if (component) out[key] = bind(component)
357 }
358 return out
359}
360
361/**
362 * Bind chat options and UI widgets once at module scope. This matches Form
363 * `createFormHook` and Table `createTableHook`: widgets register here, mix
364 * onto Part / Interrupt / the UI kit, and automatic dispatch still walks the
365 * message list.
366 *
367 * `chatOptions` is type-only at runtime. Pass optional `chatContext`,
368 * `partContext`, and `interruptContext` from {@link createChatHookContexts}
369 * when widgets live in other files or when nested chats need isolation.
370 */
371export function createChatUI<
372 const TOptions,
373 TInput extends ComponentType<any> | undefined =
374 | ComponentType<InputProps<NoInfer<TOptions>>>
375 | undefined,
376>(options: TOptions, config: ChatUIFactoryConfig<NoInfer<TOptions>, TInput>) {
377 void options
378 const {
379 context: contextOption,
380 components,
381 partsComponents: parts,
382 toolsComponents: tools,
383 interruptsComponents: interrupts,
384 subagentsComponents: subagentComponents,
385 } = config as ChatUIFactoryConfig<TOptions, TInput> & {
386 toolsComponents?: Record<string, ComponentType<any> | undefined>
387 interruptsComponents?: {
388 tools?: Record<string, ComponentType<any> | undefined>
389 generic?: Record<string, ComponentType<any> | undefined>
390 }
391 subagentsComponents?: Record<string, ComponentType<any> | undefined>
392 }
393 const {
394 layout: Layout,
395 message: MessageComponent,
396 input: InputComponent,
397 queue: QueueItemComponent,
398 } = components
399 const {
400 chatContext: chatContextOption,
401 partContext: partContextOption,
402 interruptContext: interruptContextOption,
403 } = contextOption ?? {}
404 const warn = createWarnOnce()
405 const ChatContext = (chatContextOption ??
406 defaultChatUIContexts.chatContext) as Context<ChatUIHost<TOptions> | null>
407 const PartContext = (partContextOption ??
408 defaultChatUIContexts.partContext) as Context<ChatUISelectedPart | null>
409 const InterruptContext = (interruptContextOption ??
410 defaultChatUIContexts.interruptContext) as Context<ChatUIInterrupt | null>
411 const inlineToolNames = collectInlineToolNames(
412 interrupts?.tools as Record<string, unknown> | undefined,
413 Object.keys(tools ?? {}),
414 )
415
416 function useChatContext() {
417 const chat = useContext(ChatContext)
418 if (!chat) {
419 throw new Error(
420 '`useChatContext` must be used within `UI.Provider` or `UI.Chat`.',
421 )
422 }
423 return chat
424 }
425
426 function usePartContext<TKey extends ChatUIPartKey = ChatUIPartKey>() {
427 const selected = useContext(PartContext)
428 if (!selected) {
429 throw new Error(
430 '`usePartContext` must be used within `UI.Part` or an automatic part.',
431 )
432 }
433 return selected as ChatUISelectedPartOf<TOptions, TKey>
434 }
435
436 function useInterruptContext<
437 TName extends ChatUIInterruptName<TOptions> = ChatUIInterruptName<TOptions>,
438 >() {
439 const interrupt = useContext(InterruptContext)
440 if (!interrupt) {
441 throw new Error(
442 '`useInterruptContext` must be used within `UI.Interrupt`.',
443 )
444 }
445 return interrupt as ChatUIInterruptOf<TOptions, TName>
446 }
447
448 function bindPart(Component: ComponentType<PartProps<TOptions>>) {
449 return function BoundPart() {
450 const selected = usePartContext()
451 return <Component part={selected.part as PartProps<TOptions>['part']} />
452 }
453 }
454
455 function bindTool(Component: ComponentType<ToolProps<TOptions>>) {
456 return function BoundTool() {
457 const selected = usePartContext()
458 if (selected.key !== 'toolCall') return null
459 return (
460 <Component
461 part={selected.part as ToolProps<TOptions>['part']}
462 result={selected.result}
463 interrupt={selected.interrupt as ToolProps<TOptions>['interrupt']}
464 />
465 )
466 }
467 }
468
469 function bindInterrupt(Component: ComponentType<InterruptProps<TOptions>>) {
470 return function BoundInterrupt() {
471 const interrupt = useInterruptContext()
472 return (
473 <Component
474 interrupt={interrupt as InterruptProps<TOptions>['interrupt']}
475 />
476 )
477 }
478 }
479
480 const partMixins = bindMap(
481 parts as Record<string, ComponentType<any> | undefined>,
482 bindPart,
483 )
484 const toolMixins = bindMap(
485 tools as Record<string, ComponentType<any> | undefined>,
486 bindTool,
487 )
488 const interruptMixins = {
489 ...bindMap(
490 interrupts?.generic as
491 | Record<string, ComponentType<any> | undefined>
492 | undefined,
493 bindInterrupt,
494 ),
495 ...bindMap(
496 interrupts?.tools as
497 | Record<string, ComponentType<any> | undefined>
498 | undefined,
499 bindInterrupt,
500 ),
501 }
502
503 function mixPart(selected: ChatUISelectedPart) {
504 return Object.assign({}, selected, partMixins, toolMixins, {
505 Render: BoundRender,
506 }) as ChatUISelectedPart & PartMixins<TOptions>
507 }
508
509 function mixInterrupt(interrupt: ChatUIInterrupt) {
510 return Object.assign({}, interrupt, interruptMixins, {
511 Render: BoundInterruptRender,
512 }) as ChatUIInterrupt & InterruptMixins<TOptions>
513 }
514
515 function Provider({
516 chat,
517 children,
518 }: {
519 chat: ChatUIHost<TOptions>
520 children?: ReactNode
521 }) {
522 return <ChatContext.Provider value={chat}>{children}</ChatContext.Provider>
523 }
524
525 // Backstop for when the conditional `Input` type cannot be inferred (see the
526 // `input` note in docs/ui/react.md). The type hides `Input` when no `input`
527 // is registered, but inference degrades on some config shapes, so always
528 // supply a component: warn once rather than crash on an undefined element.
529 function MissingInput() {
530 warn(
531 'input',
532 '[tanstack-ai-ui] Rendered <Input /> but no `input` component is registered.',
533 )
534 return null
535 }
536
537 // `Messages`, `Interrupts`, `Queue` and `InputComponent` are declared once
538 // per factory, so these props are stable for the lifetime of the kit.
539 const LayoutSlots = {
540 Messages: Messages as ComponentType,
541 Interrupts: Interrupts as ComponentType,
542 Queue: Queue as ComponentType,
543 Subagents: Subagents as ComponentType,
544 Input: (InputComponent ?? MissingInput) as ComponentType,
545 }
546
547 function Chat({ chat }: { chat: ChatUIHost<TOptions> }) {
548 return (
549 <Provider chat={chat}>
550 <Layout {...(LayoutSlots as ComponentProps<ComponentType<any>>)} />
551 </Provider>
552 )
553 }
554
555 function Queue() {
556 const chat = useChatContext()
557 if (!QueueItemComponent) return null
558 const items = chat.queue
559 return (
560 <>
561 {items.map((item) => (
562 <QueueItemView
563 key={item.id}
564 cancelQueued={chat.cancelQueued}
565 item={item}
566 />
567 ))}
568 </>
569 )
570 }
571
572 const QueueItemView = memo(function QueueItemView({
573 item,
574 cancelQueued,
575 }: {
576 item: QueuedMessage
577 cancelQueued: (id: string) => void
578 }) {
579 if (!QueueItemComponent) return null
580 return (
581 <QueueItemComponent
582 item={{
583 ...item,
584 cancelQueued: () => {
585 cancelQueued(item.id)
586 },
587 }}
588 />
589 )
590 }, queueItemEqual)
591
592 function Messages({
593 children,
594 }: {
595 children?: (messages: ChatUIMessages<TOptions>) => ReactNode
596 } = {}) {
597 const chat = useChatContext()
598 const messages = readMessages(chat)
599 const interrupts = readInterrupts(chat)
600 if (children) return <>{children(messages)}</>
601 return (
602 <>
603 {messages.map((message) => (
604 <MessageView
605 key={message.id}
606 inlineToolNames={inlineToolNames}
607 interrupts={interrupts}
608 message={message}
609 />
610 ))}
611 </>
612 )
613 }
614
615 // Scoped to one message render. `Parts` reads it instead of closing over the
616 // message, which is what keeps its identity constant across re-renders — a
617 // fresh component per render would remount every part on each stream chunk.
618 type MessageRenderValue = {
619 message: ChatUIMessages<TOptions>[number]
620 interrupts: ReadonlyArray<ChatUIInterrupt>
621 inlineToolNames: ReadonlyArray<string>
622 }
623 const MessageRenderContext = createContext<MessageRenderValue | null>(null)
624 const SubagentRenderContext = createContext<{
625 handle: SubagentHandle
626 /** A `Subagents` row. Its messages come from the live chat state. */
627 listed?: true
628 } | null>(null)
629 // The widgets that dispatch uses. A subagent card's `Parts` can replace
630 // entries for its subtree. Outside a card these are the factory maps.
631 type WidgetMap = Record<string, ComponentType<any> | undefined>
632 const rootWidgets: { parts: WidgetMap; tools: WidgetMap } = {
633 parts: parts as WidgetMap,
634 tools: tools ?? {},
635 }
636 const WidgetsContext = createContext(rootWidgets)
637
638 function Parts() {
639 const scope = useContext(MessageRenderContext)
640 if (!scope) {
641 throw new Error('`Parts` must be rendered by a `message` component.')
642 }
643 return (
644 <AutomaticParts
645 inlineToolNames={scope.inlineToolNames}
646 interrupts={scope.interrupts}
647 message={scope.message}
648 />
649 )
650 }
651
652 const MessageView = memo(function MessageView({
653 message,
654 interrupts,
655 inlineToolNames: names,
656 children,
657 }: {
658 message: ChatUIMessages<TOptions>[number]
659 interrupts: ReadonlyArray<ChatUIInterrupt>
660 inlineToolNames: ReadonlyArray<string>
661 children?: (parts: Array<ChatUISelectedPart>) => ReactNode
662 }) {
663 const selected = selectMessageUI(message, {
664 interrupts,
665 inlineToolNames: names,
666 })
667 if (children) return <>{children(selected.parts)}</>
668 return (
669 <MessageRenderContext.Provider
670 value={{ message, interrupts, inlineToolNames: names }}
671 >
672 <MessageComponent message={message} Parts={Parts} />
673 </MessageRenderContext.Provider>
674 )
675 })
676
677 function Message({
678 message,
679 children,
680 }: {
681 message: ChatUIMessages<TOptions>[number]
682 children?: (parts: Array<ChatUISelectedPart>) => ReactNode
683 }) {
684 const chat = useChatContext()
685 return (
686 <MessageView
687 children={children}
688 inlineToolNames={inlineToolNames}
689 interrupts={readInterrupts(chat)}
690 message={message}
691 />
692 )
693 }
694
695 const AutomaticParts = memo(function AutomaticParts({
696 message,
697 interrupts,
698 inlineToolNames: names,
699 }: {
700 message: UIMessage
701 interrupts: ReadonlyArray<ChatUIInterrupt>
702 inlineToolNames: ReadonlyArray<string>
703 }) {
704 const selected = selectMessageUI(message, {
705 interrupts,
706 inlineToolNames: names,
707 })
708 return (
709 <>
710 {automaticPartsForMessage(selected).map((part, index) => (
711 <SelectedPartView key={`${message.id}-${index}`} selected={part} />
712 ))}
713 </>
714 )
715 })
716
717 const SelectedPartInner = memo(function SelectedPartInner({
718 selected,
719 }: {
720 selected: ChatUISelectedPart
721 }) {
722 const widgets = useContext(WidgetsContext)
723 if (selected.key === 'toolCall') {
724 const name = selected.part.name
725 const Tool = widgets.tools[name] as
726 | ComponentType<ToolProps<TOptions>>
727 | undefined
728 if (!Tool) {
729 warn(`tool:${name}`, `[tanstack-ai-ui] Missing tools.${name} component`)
730 return null
731 }
732 return (
733 <Tool
734 part={selected.part as ToolProps<TOptions>['part']}
735 result={selected.result}
736 interrupt={selected.interrupt as ToolProps<TOptions>['interrupt']}
737 />
738 )
739 }
740
741 if (selected.key === 'subagent' && selected.part.type === 'subagent') {
742 const name = selected.part.subagent.name
743 const Subagent = subagentComponents?.[name] as
744 | ComponentType<SubagentProps<TOptions>>
745 | undefined
746 if (!Subagent) {
747 throw new Error(`[tanstack-ai-ui] Missing subagentsComponents.${name}`)
748 }
749 return (
750 <SubagentRenderContext.Provider
751 value={{ handle: selected.part.subagent }}
752 >
753 <Subagent
754 Parts={SubagentMessages}
755 subagent={
756 selected.part.subagent as SubagentProps<TOptions>['subagent']
757 }
758 />
759 </SubagentRenderContext.Provider>
760 )
761 }
762
763 const PartComponent = (widgets.parts[selected.key] ??
764 widgets.parts.fallback) as ComponentType<PartProps<TOptions>> | undefined
765 if (!PartComponent) {
766 warn(
767 `part:${selected.key}`,
768 `[tanstack-ai-ui] Missing parts.${selected.key} component`,
769 )
770 return null
771 }
772 return <PartComponent part={selected.part as PartProps<TOptions>['part']} />
773 }, selectedPartPropsEqual)
774
775 const SelectedPartView = memo(function SelectedPartView({
776 selected,
777 }: {
778 selected: ChatUISelectedPart
779 }) {
780 return (
781 <PartContext.Provider value={selected}>
782 <SelectedPartInner selected={selected} />
783 </PartContext.Provider>
784 )
785 })
786
787 function BoundRender() {
788 const selected = usePartContext()
789 return <SelectedPartInner selected={selected} />
790 }
791
792 function Part({
793 part,
794 children,
795 }: {
796 part: MessagePart | ChatUISelectedPart
797 children?: (mixed: ChatUISelectedPart & PartMixins<TOptions>) => ReactNode
798 }) {
799 const chat = useChatContext()
800 const selected = isSelectedPart(part)
801 ? part
802 : selectMessageUI(
803 { id: 'part', role: 'assistant', parts: [part] },
804 { interrupts: readInterrupts(chat), inlineToolNames: [] },
805 ).parts[0]
806 if (!selected) return null
807 return (
808 <PartContext.Provider value={selected}>
809 {children ? (
810 children(mixPart(selected))
811 ) : (
812 <SelectedPartInner selected={selected} />
813 )}
814 </PartContext.Provider>
815 )
816 }
817
818 function Interrupts({
819 children,
820 }: {
821 children?: (interrupts: ReadonlyArray<ChatUIInterrupt>) => ReactNode
822 } = {}) {
823 const chat = useChatContext()
824 const selected = selectChatUI({
825 messages: readMessages(chat),
826 interrupts: readInterrupts(chat),
827 inlineToolNames,
828 })
829 if (children) return <>{children(selected.interrupts)}</>
830 return (
831 <>
832 {selected.interrupts.map((interrupt) => (
833 <Interrupt key={interrupt.id} interrupt={interrupt} />
834 ))}
835 </>
836 )
837 }
838
839 const InterruptInner = memo(function InterruptInner({
840 interrupt,
841 }: {
842 interrupt: ChatUIInterrupt
843 }) {
844 const Component = resolveInterruptComponent(interrupt, interrupts) as
845 | ComponentType<InterruptProps<TOptions>>
846 | undefined
847 if (!Component) {
848 warn(
849 `interrupt:${interrupt.id}`,
850 `[tanstack-ai-ui] Missing interrupt component for ${interrupt.kind}`,
851 )
852 return null
853 }
854 return <Component interrupt={interrupt} />
855 })
856
857 function BoundInterruptRender() {
858 const interrupt = useInterruptContext()
859 return <InterruptInner interrupt={interrupt} />
860 }
861
862 const Interrupt = memo(function Interrupt({
863 interrupt,
864 children,
865 }: {
866 interrupt: ChatUIInterrupt
867 children?: (mixed: ChatUIInterrupt & InterruptMixins<TOptions>) => ReactNode
868 }) {
869 return (
870 <InterruptContext.Provider value={interrupt}>
871 {children ? (
872 children(mixInterrupt(interrupt))
873 ) : (
874 <InterruptInner interrupt={interrupt} />
875 )}
876 </InterruptContext.Provider>
877 )
878 })
879
880 function readSubagentMessages() {
881 const scoped = useContext(SubagentRenderContext)
882 const chat = useChatContext()
883 if (scoped?.listed) {
884 const live = chat.subagents.find((item) => item.id === scoped.handle.id)
885 return (live ?? scoped.handle).messages
886 }
887 if (scoped) return scoped.handle.messages
888 const selected = useContext(PartContext)
889 if (selected?.key === 'subagent' && selected.part.type === 'subagent') {
890 return selected.part.subagent.messages
891 }
892 throw new Error(
893 '`Parts` must be rendered by a subagent component or `Subagents` item.',
894 )
895 }
896
897 const SubagentMessagesBody = memo(function SubagentMessagesBody({
898 messages,
899 }: {
900 messages: SubagentHandle['messages']
901 }) {
902 const chat = useChatContext()
903 const interrupts = readInterrupts(chat)
904 return (
905 <>
906 {messages.map((message) => (
907 <AutomaticParts
908 key={message.id}
909 inlineToolNames={inlineToolNames}
910 interrupts={interrupts}
911 message={message}
912 />
913 ))}
914 </>
915 )
916 }, subagentMessagesEqual)
917
918 function SubagentMessages({
919 partsComponents,
920 toolsComponents,
921 }: SubagentPartsProps<TOptions>) {
922 const messages = readSubagentMessages()
923 const outer = useContext(WidgetsContext)
924 const widgets = useMemo(
925 () =>
926 partsComponents || toolsComponents
927 ? {
928 parts: withWidgets(outer.parts, partsComponents),
929 tools: withWidgets(outer.tools, toolsComponents),
930 }
931 : outer,
932 [outer, partsComponents, toolsComponents],
933 )
934 // ponytail: root `<Interrupts />` still lists an approval for a tool call
935 // inside a card, so it shows in both places. Hiding it needs `selectChatUI`
936 // to collect tool-call ids from nested subagent messages (its `callIds` is
937 // top-level only) plus the card tool names in `inlineToolNames`.
938 return (
939 <WidgetsContext.Provider value={widgets}>
940 <SubagentMessagesBody messages={messages} />
941 </WidgetsContext.Provider>
942 )
943 }
944
945 const SubagentListItem = memo(function SubagentListItem({
946 handle,
947 }: SubagentRowProps) {
948 const Subagent = subagentComponents?.[handle.name] as
949 | ComponentType<SubagentProps<TOptions>>
950 | undefined
951 if (!Subagent) {
952 throw new Error(
953 `[tanstack-ai-ui] Missing subagentsComponents.${handle.name}`,
954 )
955 }
956 return (
957 <SubagentRenderContext.Provider value={{ handle, listed: true }}>
958 <Subagent
959 Parts={SubagentMessages}
960 subagent={handle as SubagentProps<TOptions>['subagent']}
961 />
962 </SubagentRenderContext.Provider>
963 )
964 }, subagentListItemEqual)
965
966 function Subagents({
967 children,
968 }: {
969 children?: (subagents: Array<SubagentHandle>) => ReactNode
970 } = {}) {
971 const chat = useChatContext()
972 const live = chat.subagents
973 if (children) return <>{children(live)}</>
974 if (live.length === 0) return null
975 return (
976 <>
977 {live.map((handle) => (
978 <SubagentListItem
979 key={handle.id}
980 handle={handle}
981 status={handle.status}
982 error={handle.error}
983 />
984 ))}
985 </>
986 )
987 }
988
989 return {
990 Chat,
991 Provider,
992 Messages,
993 Message,
994 Part,
995 Interrupts,
996 Interrupt,
997 Queue,
998 Subagents,
999 SubagentMessages,
1000 useChatContext,
1001 Input: InputComponent,
1002 }
1003}