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

create-ui.tsrx

767 lines21.0 KB

1import { createContext, memo, useContext } from 'octane'
2import type { ComponentBody, Context, OctaneNode } from 'octane'
3​
4type ComponentType<P = any> = ComponentBody<P>
5type ComponentProps<T> = T extends ComponentBody<infer P> ? P : Record<string, never>
6import {
7 automaticPartsForMessage,
8 collectInlineToolNames,
9 resolveInterruptComponent,
10 selectChatUI,
11 selectMessageUI,
12} from '@tanstack/ai-client/ui'
13import type {
14 ChatUIData,
15 ChatUIHasNamedInterrupts,
16 ChatUIHasNamedTools,
17 ChatUIInterrupt,
18 ChatUIInterruptName,
19 ChatUIInterruptOf,
20 ChatUIInterruptsOf,
21 ChatUIMessages,
22 ChatUINamedInterruptId,
23 ChatUIPartKey,
24 ChatUIPartOf,
25 ChatUISchemaOf,
26 ChatUISelectedPart,
27 ChatUISelectedPartOf,
28 ChatUIToolApproval,
29 ChatUIToolName,
30 ChatUIToolsOf,
31} from '@tanstack/ai-client/ui'
32import type {
33 MessagePart,
34 QueuedMessage,
35 ToolCallPart,
36 ToolResultPart,
37 UIMessage,
38} from '@tanstack/ai-client'
39import type { UseChatReturn } from '../types'
40import { defaultChatUIContexts } from './create-ui-contexts.tsrx'
41import type { ChatUIContexts } from './create-ui-contexts.tsrx'
42​
43export type ChatUIHost<TOptions = unknown> = UseChatReturn<
44 ChatUIToolsOf<TOptions>,
45 ChatUISchemaOf<TOptions>,
46 ChatUIInterruptsOf<TOptions>
48​
49export type ChatUIQueueItem = QueuedMessage & {
50 cancelQueued: () => void
52​
53export type LayoutProps<
54 TOptions,
55 TInput extends ComponentType<any> | undefined = ComponentType<
56 InputProps<TOptions>
57 >,
58> = {
59 Messages: ComponentType
60 Interrupts: ComponentType
61 Queue: ComponentType
62 readonly __ui?: TOptions
63} & (TInput extends ComponentType<any> ? { Input: ComponentType } : {})
64​
65export type MessageProps<TOptions> = {
66 message: UIMessage<ChatUIToolsOf<TOptions>, ChatUIData<TOptions>>
67 Parts: ComponentType
69​
70export type InputProps<TOptions> = {
71 readonly __ui?: TOptions
73​
74export type QueueProps<TOptions> = {
75 item: ChatUIQueueItem
76 readonly __ui?: TOptions
78​
79export type PartProps<TOptions, TKey extends ChatUIPartKey = ChatUIPartKey> = {
80 part: ChatUIPartOf<TOptions, TKey>
82​
83export type ToolProps<
84 TOptions,
85 TName extends ChatUIToolName<TOptions> = ChatUIToolName<TOptions>,
86> = {
87 part: Extract<ToolCallPart<ChatUIToolsOf<TOptions>>, { name: TName }>
88 result?: ToolResultPart
89 interrupt?: ChatUIToolApproval<TOptions, TName>
91​
92export type InterruptProps<
93 TOptions,
94 TName extends ChatUIInterruptName<TOptions> = never,
95> = {
96 interrupt: ChatUIInterruptOf<TOptions, TName>
97 readonly __ui?: TOptions
99​
100type GenericInterruptComponents<TOptions> =
101 ChatUIHasNamedInterrupts<TOptions> extends true
102 ? {
103 [K in ChatUINamedInterruptId<TOptions>]: ComponentType<
104 InterruptProps<TOptions, K & ChatUIInterruptName<TOptions>>
105 >
106 } & {
107 fallback?: ComponentType<InterruptProps<TOptions>>
108 }
109 : {
110 fallback?: ComponentType<InterruptProps<TOptions>>
111 }
112​
113type ToolApprovalMap<TOptions> = {
114 [K in ChatUIToolName<TOptions>]?: ComponentType<
115 InterruptProps<TOptions, K & ChatUIInterruptName<TOptions>>
116 >
118​
119/** The chrome around the message list: `layout`, `message`, and `input`. */
120export type ChatUIChromeComponents<
121 TOptions,
122 TInput extends ComponentType<InputProps<TOptions>> | undefined =
123 ComponentType<InputProps<TOptions>>,
124> = {
125 layout: ComponentType<LayoutProps<TOptions, TInput>>
126 message: ComponentType<MessageProps<TOptions>>
127 input?: TInput
128 queue?: ComponentType<QueueProps<TOptions>>
130​
131export type ChatUIPartsComponents<TOptions> = {
132 [K in ChatUIPartKey]?: ComponentType<PartProps<TOptions, K>>
133} & {
134 fallback?: ComponentType<PartProps<TOptions>>
136​
137export type ChatUIInterruptsComponents<TOptions> = {
138 tools?: ToolApprovalMap<TOptions>
139 generic: GenericInterruptComponents<TOptions>
141​
142export type ChatUIComponents<
143 TOptions,
144 TInput extends ComponentType<InputProps<TOptions>> | undefined =
145 ComponentType<InputProps<TOptions>>,
146> = {
147 components: ChatUIChromeComponents<TOptions, TInput>
148 partsComponents: ChatUIPartsComponents<TOptions>
149} & (ChatUIHasNamedTools<TOptions> extends true
150 ? {
151 toolsComponents: {
152 [K in ChatUIToolName<TOptions>]: ComponentType<ToolProps<TOptions, K>>
153 }
154 }
155 : {
156 toolsComponents?: {
157 [K in ChatUIToolName<TOptions>]?: ComponentType<ToolProps<TOptions, K>>
158 }
159 }) &
160 (ChatUIHasNamedInterrupts<TOptions> extends true
161 ? { interruptsComponents: ChatUIInterruptsComponents<TOptions> }
162 : {
163 interruptsComponents?: {
164 tools?: ToolApprovalMap<TOptions>
165 generic?: GenericInterruptComponents<TOptions>
166 }
167 })
168​
169/** Scoped contexts, for widgets in other files or nested chat trees. */
170export type ChatUIContextConfig = {
171 chatContext?: ChatUIContexts['chatContext']
172 partContext?: ChatUIContexts['partContext']
173 interruptContext?: ChatUIContexts['interruptContext']
175​
176export type ChatUIFactoryConfig<
177 TOptions,
178 TInput extends ComponentType<InputProps<TOptions>> | undefined =
179 ComponentType<InputProps<TOptions>>,
180> = ChatUIComponents<TOptions, TInput> & {
181 context?: ChatUIContextConfig
183​
184/** A zero-prop widget bound to the surrounding part or interrupt. */
185export type BoundWidget = ComponentType<Record<string, never>>
186​
187/** The widgets `UI.Part` mixes onto the selected part it passes to children. */
188export type PartMixins<TOptions> = {
189 [K in ChatUIPartKey]?: BoundWidget
190} & {
191 [K in ChatUIToolName<TOptions>]: BoundWidget
192} & {
193 Render: BoundWidget
195​
196/** The widgets `UI.Interrupt` mixes onto the interrupt it passes to children. */
197export type InterruptMixins<TOptions> = {
198 [K in ChatUINamedInterruptId<TOptions>]: BoundWidget
199} & {
200 [K in ChatUIToolName<TOptions>]?: BoundWidget
201} & {
202 fallback?: BoundWidget
203 Render: BoundWidget
205​
206function createWarnOnce() {
207 const seen = new Set<string>()
208 return (key: string, message: string) => {
209 if (process.env.NODE_ENV === 'production') return
210 if (seen.has(key)) return
211 seen.add(key)
212 console.warn(message)
213 }
215​
216function readMessages<TOptions>(chat: ChatUIHost<TOptions>) {
217 return chat.messages as ChatUIMessages<TOptions>
219​
220function readInterrupts<TOptions>(chat: ChatUIHost<TOptions>) {
221 return chat.interrupts ?? []
223​
224function queueItemEqual(
225 prev: { item: QueuedMessage; cancelQueued: (id: string) => void },
226 next: { item: QueuedMessage; cancelQueued: (id: string) => void },
227) {
228 return (
229 prev.item.id === next.item.id &&
230 prev.item.createdAt === next.item.createdAt &&
231 prev.item.content === next.item.content &&
232 prev.cancelQueued === next.cancelQueued
233 )
235​
236function selectedPartPropsEqual(
237 prev: { selected: ChatUISelectedPart },
238 next: { selected: ChatUISelectedPart },
239) {
240 if (prev.selected.key !== next.selected.key) return false
241 if (prev.selected.part !== next.selected.part) return false
242 if (prev.selected.key === 'toolCall' && next.selected.key === 'toolCall') {
243 return (
244 prev.selected.result === next.selected.result &&
245 prev.selected.interrupt === next.selected.interrupt
246 )
247 }
248 if (
249 prev.selected.key === 'toolResult' &&
250 next.selected.key === 'toolResult'
251 ) {
252 return prev.selected.matched === next.selected.matched
253 }
254 return true
256​
257function isSelectedPart(
258 value: MessagePart | ChatUISelectedPart,
259): value is ChatUISelectedPart {
260 return 'key' in value && 'part' in value
262​
263function bindMap(
264 map: Record<string, ComponentType<any> | undefined> | undefined,
265 bind: (component: ComponentType<any>) => BoundWidget,
266) {
267 const out: Record<string, BoundWidget> = {}
268 for (const [key, component] of Object.entries(map ?? {})) {
269 if (component) out[key] = bind(component)
270 }
271 return out
273​
274/**
275 * Bind chat options and UI widgets once at module scope. This matches Form
276 * `createFormHook` and Table `createTableHook`: widgets register here, mix
277 * onto Part / Interrupt / the UI kit, and automatic dispatch still walks the
278 * message list.
279 *
280 * `chatOptions` is type-only at runtime. Pass optional `chatContext`,
281 * `partContext`, and `interruptContext` from {@link createChatHookContexts}
282 * when widgets live in other files or when nested chats need isolation.
283 */
284export function createChatUI<
285 const TOptions,
286 TInput extends ComponentType<any> | undefined =
287 | ComponentType<InputProps<NoInfer<TOptions>>>
288 | undefined,
289>(options: TOptions, config: ChatUIFactoryConfig<NoInfer<TOptions>, TInput>) {
290 void options
291 const {
292 context: contextOption,
293 components,
294 partsComponents: parts,
295 toolsComponents: tools,
296 interruptsComponents: interrupts,
297 } = config as ChatUIFactoryConfig<TOptions, TInput> & {
298 toolsComponents?: Record<string, ComponentType<any> | undefined>
299 interruptsComponents?: {
300 tools?: Record<string, ComponentType<any> | undefined>
301 generic?: Record<string, ComponentType<any> | undefined>
302 }
303 }
304 const {
305 layout: Layout,
306 message: MessageComponent,
307 input: InputComponent,
308 queue: QueueItemComponent,
309 } = components
310 const {
311 chatContext: chatContextOption,
312 partContext: partContextOption,
313 interruptContext: interruptContextOption,
314 } = contextOption ?? {}
315 const warn = createWarnOnce()
316 const ChatContext = (chatContextOption ??
317 defaultChatUIContexts.chatContext) as Context<ChatUIHost<TOptions> | null>
318 const PartContext = (partContextOption ??
319 defaultChatUIContexts.partContext) as Context<ChatUISelectedPart | null>
320 const InterruptContext = (interruptContextOption ??
321 defaultChatUIContexts.interruptContext) as Context<ChatUIInterrupt | null>
322 const inlineToolNames = collectInlineToolNames(
323 interrupts?.tools as Record<string, unknown> | undefined,
324 Object.keys(tools ?? {}),
325 )
326​
327 function useChatContext() {
328 const chat = useContext(ChatContext)
329 if (!chat) {
330 throw new Error(
331 '`useChatContext` must be used within `UI.Provider` or `UI.Chat`.',
332 )
333 }
334 return chat
335 }
336​
337 function usePartContext<TKey extends ChatUIPartKey = ChatUIPartKey>() {
338 const selected = useContext(PartContext)
339 if (!selected) {
340 throw new Error(
341 '`usePartContext` must be used within `UI.Part` or an automatic part.',
342 )
343 }
344 return selected as ChatUISelectedPartOf<TOptions, TKey>
345 }
346​
347 function useInterruptContext<
348 TName extends ChatUIInterruptName<TOptions> = ChatUIInterruptName<TOptions>,
349 >() {
350 const interrupt = useContext(InterruptContext)
351 if (!interrupt) {
352 throw new Error(
353 '`useInterruptContext` must be used within `UI.Interrupt`.',
354 )
355 }
356 return interrupt as ChatUIInterruptOf<TOptions, TName>
357 }
358​
359 function bindPart(Component: ComponentType<PartProps<TOptions>>) {
360 return function BoundPart() {
361 const selected = usePartContext()
362 return <Component part={selected.part as PartProps<TOptions>['part']} />
363 }
364 }
365​
366 function bindTool(Component: ComponentType<ToolProps<TOptions>>) {
367 return function BoundTool() {
368 const selected = usePartContext()
369 if (selected.key !== 'toolCall') return null
370 return (
371 <Component
372 part={selected.part as ToolProps<TOptions>['part']}
373 result={selected.result}
374 interrupt={selected.interrupt as ToolProps<TOptions>['interrupt']}
375 />
376 )
377 }
378 }
379​
380 function bindInterrupt(Component: ComponentType<InterruptProps<TOptions>>) {
381 return function BoundInterrupt() {
382 const interrupt = useInterruptContext()
383 return (
384 <Component
385 interrupt={interrupt as InterruptProps<TOptions>['interrupt']}
386 />
387 )
388 }
389 }
390​
391 const partMixins = bindMap(
392 parts as Record<string, ComponentType<any> | undefined>,
393 bindPart,
394 )
395 const toolMixins = bindMap(
396 tools as Record<string, ComponentType<any> | undefined>,
397 bindTool,
398 )
399 const interruptMixins = {
400 ...bindMap(
401 interrupts?.generic as
402 | Record<string, ComponentType<any> | undefined>
403 | undefined,
404 bindInterrupt,
405 ),
406 ...bindMap(
407 interrupts?.tools as
408 | Record<string, ComponentType<any> | undefined>
409 | undefined,
410 bindInterrupt,
411 ),
412 }
413​
414 function mixPart(selected: ChatUISelectedPart) {
415 return Object.assign({}, selected, partMixins, toolMixins, {
416 Render: BoundRender,
417 }) as ChatUISelectedPart & PartMixins<TOptions>
418 }
419​
420 function mixInterrupt(interrupt: ChatUIInterrupt) {
421 return Object.assign({}, interrupt, interruptMixins, {
422 Render: BoundInterruptRender,
423 }) as ChatUIInterrupt & InterruptMixins<TOptions>
424 }
425​
426 function Provider({
427 chat,
428 children,
429 }: {
430 chat: ChatUIHost<TOptions>
431 children?: OctaneNode
432 }) {
433 return <ChatContext value={chat}>{children}</ChatContext>
434 }
435​
436 // Backstop for when the conditional `Input` type cannot be inferred (see the
437 // `input` note in docs/ui/react.md). The type hides `Input` when no `input`
438 // is registered, but inference degrades on some config shapes, so always
439 // supply a component: warn once rather than crash on an undefined element.
440 function MissingInput() {
441 warn(
442 'input',
443 '[tanstack-ai-ui] Rendered <Input /> but no `input` component is registered.',
444 )
445 return null
446 }
447​
448 // `Messages`, `Interrupts`, `Queue` and `InputComponent` are declared once
449 // per factory, so these props are stable for the lifetime of the kit.
450 const LayoutSlots = {
451 Messages: Messages as ComponentType,
452 Interrupts: Interrupts as ComponentType,
453 Queue: Queue as ComponentType,
454 Input: (InputComponent ?? MissingInput) as ComponentType,
455 }
456​
457 function Chat({ chat }: { chat: ChatUIHost<TOptions> }) {
458 return (
459 <Provider chat={chat}>
460 <Layout {...(LayoutSlots as ComponentProps<ComponentType<any>>)} />
461 </Provider>
462 )
463 }
464​
465 function Queue() {
466 const chat = useChatContext()
467 if (!QueueItemComponent) return null
468 const items = chat.queue
469 return (
470 <>
471 {items.map((item) => (
472 <QueueItemView
473 key={item.id}
474 cancelQueued={chat.cancelQueued}
475 item={item}
476 />
477 ))}
478 </>
479 )
480 }
481​
482 const QueueItemView = memo(function QueueItemView({
483 item,
484 cancelQueued,
485 }: {
486 item: QueuedMessage
487 cancelQueued: (id: string) => void
488 }) {
489 if (!QueueItemComponent) return null
490 return (
491 <QueueItemComponent
492 item={{
493 ...item,
494 cancelQueued: () => {
495 cancelQueued(item.id)
496 },
497 }}
498 />
499 )
500 }, queueItemEqual)
501​
502 function Messages({
503 children,
504 }: {
505 children?: (messages: ChatUIMessages<TOptions>) => OctaneNode
506 } = {}) {
507 const chat = useChatContext()
508 const messages = readMessages(chat)
509 const interrupts = readInterrupts(chat)
510 if (children) return <>{children(messages)}</>
511 return (
512 <>
513 {messages.map((message) => (
514 <MessageView
515 key={message.id}
516 inlineToolNames={inlineToolNames}
517 interrupts={interrupts}
518 message={message}
519 />
520 ))}
521 </>
522 )
523 }
524​
525 // Scoped to one message render. `Parts` reads it instead of closing over the
526 // message, which is what keeps its identity constant across re-renders — a
527 // fresh component per render would remount every part on each stream chunk.
528 type MessageRenderValue = {
529 message: ChatUIMessages<TOptions>[number]
530 interrupts: ReadonlyArray<ChatUIInterrupt>
531 inlineToolNames: ReadonlyArray<string>
532 }
533 const MessageRenderContext = createContext<MessageRenderValue | null>(null)
534​
535 function Parts() {
536 const scope = useContext(MessageRenderContext)
537 if (!scope) {
538 throw new Error('`Parts` must be rendered by a `message` component.')
539 }
540 return (
541 <AutomaticParts
542 inlineToolNames={scope.inlineToolNames}
543 interrupts={scope.interrupts}
544 message={scope.message}
545 />
546 )
547 }
548​
549 const MessageView = memo(function MessageView({
550 message,
551 interrupts,
552 inlineToolNames: names,
553 children,
554 }: {
555 message: ChatUIMessages<TOptions>[number]
556 interrupts: ReadonlyArray<ChatUIInterrupt>
557 inlineToolNames: ReadonlyArray<string>
558 children?: (parts: Array<ChatUISelectedPart>) => OctaneNode
559 }) {
560 const selected = selectMessageUI(message, {
561 interrupts,
562 inlineToolNames: names,
563 })
564 if (children) return <>{children(selected.parts)}</>
565 return (
566 <MessageRenderContext
567 value={{ message, interrupts, inlineToolNames: names }}
568 >
569 <MessageComponent message={message} Parts={Parts} />
570 </MessageRenderContext>
571 )
572 })
573​
574 function Message({
575 message,
576 children,
577 }: {
578 message: ChatUIMessages<TOptions>[number]
579 children?: (parts: Array<ChatUISelectedPart>) => OctaneNode
580 }) {
581 const chat = useChatContext()
582 return (
583 <MessageView
584 children={children}
585 inlineToolNames={inlineToolNames}
586 interrupts={readInterrupts(chat)}
587 message={message}
588 />
589 )
590 }
591​
592 const AutomaticParts = memo(function AutomaticParts({
593 message,
594 interrupts,
595 inlineToolNames: names,
596 }: {
597 message: ChatUIMessages<TOptions>[number]
598 interrupts: ReadonlyArray<ChatUIInterrupt>
599 inlineToolNames: ReadonlyArray<string>
600 }) {
601 const selected = selectMessageUI(message, {
602 interrupts,
603 inlineToolNames: names,
604 })
605 return (
606 <>
607 {automaticPartsForMessage(selected).map((part, index) => (
608 <SelectedPartView key={`${message.id}-${index}`} selected={part} />
609 ))}
610 </>
611 )
612 })
613​
614 const SelectedPartInner = memo(function SelectedPartInner({
615 selected,
616 }: {
617 selected: ChatUISelectedPart
618 }) {
619 if (selected.key === 'toolCall') {
620 const name = selected.part.name
621 const Tool = tools?.[name as ChatUIToolName<TOptions>] as
622 | ComponentType<ToolProps<TOptions>>
623 | undefined
624 if (!Tool) {
625 warn(`tool:${name}`, `[tanstack-ai-ui] Missing tools.${name} component`)
626 return null
627 }
628 return (
629 <Tool
630 part={selected.part as ToolProps<TOptions>['part']}
631 result={selected.result}
632 interrupt={selected.interrupt as ToolProps<TOptions>['interrupt']}
633 />
634 )
635 }
636​
637 const PartComponent = (parts[selected.key] ?? parts.fallback) as
638 | ComponentType<PartProps<TOptions>>
639 | undefined
640 if (!PartComponent) {
641 warn(
642 `part:${selected.key}`,
643 `[tanstack-ai-ui] Missing parts.${selected.key} component`,
644 )
645 return null
646 }
647 return <PartComponent part={selected.part as PartProps<TOptions>['part']} />
648 }, selectedPartPropsEqual)
649​
650 const SelectedPartView = memo(function SelectedPartView({
651 selected,
652 }: {
653 selected: ChatUISelectedPart
654 }) {
655 return (
656 <PartContext value={selected}>
657 <SelectedPartInner selected={selected} />
658 </PartContext>
659 )
660 })
661​
662 function BoundRender() {
663 const selected = usePartContext()
664 return <SelectedPartInner selected={selected} />
665 }
666​
667 function Part({
668 part,
669 children,
670 }: {
671 part: MessagePart | ChatUISelectedPart
672 children?: (mixed: ChatUISelectedPart & PartMixins<TOptions>) => OctaneNode
673 }) {
674 const chat = useChatContext()
675 const selected = isSelectedPart(part)
676 ? part
677 : selectMessageUI(
678 { id: 'part', role: 'assistant', parts: [part] },
679 { interrupts: readInterrupts(chat), inlineToolNames: [] },
680 ).parts[0]
681 if (!selected) return null
682 return (
683 <PartContext value={selected}>
684 {children ? (
685 children(mixPart(selected))
686 ) : (
687 <SelectedPartInner selected={selected} />
688 )}
689 </PartContext>
690 )
691 }
692​
693 function Interrupts({
694 children,
695 }: {
696 children?: (interrupts: ReadonlyArray<ChatUIInterrupt>) => OctaneNode
697 } = {}) {
698 const chat = useChatContext()
699 const selected = selectChatUI({
700 messages: readMessages(chat),
701 interrupts: readInterrupts(chat),
702 inlineToolNames,
703 })
704 if (children) return <>{children(selected.interrupts)}</>
705 return (
706 <>
707 {selected.interrupts.map((interrupt) => (
708 <Interrupt key={interrupt.id} interrupt={interrupt} />
709 ))}
710 </>
711 )
712 }
713​
714 const InterruptInner = memo(function InterruptInner({
715 interrupt,
716 }: {
717 interrupt: ChatUIInterrupt
718 }) {
719 const Component = resolveInterruptComponent(interrupt, interrupts) as
720 | ComponentType<InterruptProps<TOptions>>
721 | undefined
722 if (!Component) {
723 warn(
724 `interrupt:${interrupt.id}`,
725 `[tanstack-ai-ui] Missing interrupt component for ${interrupt.kind}`,
726 )
727 return null
728 }
729 return <Component interrupt={interrupt} />
730 })
731​
732 function BoundInterruptRender() {
733 const interrupt = useInterruptContext()
734 return <InterruptInner interrupt={interrupt} />
735 }
736​
737 const Interrupt = memo(function Interrupt({
738 interrupt,
739 children,
740 }: {
741 interrupt: ChatUIInterrupt
742 children?: (mixed: ChatUIInterrupt & InterruptMixins<TOptions>) => OctaneNode
743 }) {
744 return (
745 <InterruptContext value={interrupt}>
746 {children ? (
747 children(mixInterrupt(interrupt))
748 ) : (
749 <InterruptInner interrupt={interrupt} />
750 )}
751 </InterruptContext>
752 )
753 })
754​
755 return {
756 Chat,
757 Provider,
758 Messages,
759 Message,
760 Part,
761 Interrupts,
762 Interrupt,
763 Queue,
764 useChatContext,
765 Input: InputComponent,
766 }