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

create-ui.tsrx

764 lines20.8 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​
184type BoundWidget = ComponentType<Record<string, never>>
185​
186type PartMixins<TOptions> = {
187 [K in ChatUIPartKey]?: BoundWidget
188} & {
189 [K in ChatUIToolName<TOptions>]: BoundWidget
190} & {
191 Render: BoundWidget
193​
194type InterruptMixins<TOptions> = {
195 [K in ChatUINamedInterruptId<TOptions>]: BoundWidget
196} & {
197 [K in ChatUIToolName<TOptions>]?: BoundWidget
198} & {
199 fallback?: BoundWidget
200 Render: BoundWidget
202​
203function createWarnOnce() {
204 const seen = new Set<string>()
205 return (key: string, message: string) => {
206 if (process.env.NODE_ENV === 'production') return
207 if (seen.has(key)) return
208 seen.add(key)
209 console.warn(message)
210 }
212​
213function readMessages<TOptions>(chat: ChatUIHost<TOptions>) {
214 return chat.messages as ChatUIMessages<TOptions>
216​
217function readInterrupts<TOptions>(chat: ChatUIHost<TOptions>) {
218 return chat.interrupts ?? []
220​
221function queueItemEqual(
222 prev: { item: QueuedMessage; cancelQueued: (id: string) => void },
223 next: { item: QueuedMessage; cancelQueued: (id: string) => void },
224) {
225 return (
226 prev.item.id === next.item.id &&
227 prev.item.createdAt === next.item.createdAt &&
228 prev.item.content === next.item.content &&
229 prev.cancelQueued === next.cancelQueued
230 )
232​
233function selectedPartPropsEqual(
234 prev: { selected: ChatUISelectedPart },
235 next: { selected: ChatUISelectedPart },
236) {
237 if (prev.selected.key !== next.selected.key) return false
238 if (prev.selected.part !== next.selected.part) return false
239 if (prev.selected.key === 'toolCall' && next.selected.key === 'toolCall') {
240 return (
241 prev.selected.result === next.selected.result &&
242 prev.selected.interrupt === next.selected.interrupt
243 )
244 }
245 if (
246 prev.selected.key === 'toolResult' &&
247 next.selected.key === 'toolResult'
248 ) {
249 return prev.selected.matched === next.selected.matched
250 }
251 return true
253​
254function isSelectedPart(
255 value: MessagePart | ChatUISelectedPart,
256): value is ChatUISelectedPart {
257 return 'key' in value && 'part' in value
259​
260function bindMap(
261 map: Record<string, ComponentType<any> | undefined> | undefined,
262 bind: (component: ComponentType<any>) => BoundWidget,
263) {
264 const out: Record<string, BoundWidget> = {}
265 for (const [key, component] of Object.entries(map ?? {})) {
266 if (component) out[key] = bind(component)
267 }
268 return out
270​
271/**
272 * Bind chat options and UI widgets once at module scope. This matches Form
273 * `createFormHook` and Table `createTableHook`: widgets register here, mix
274 * onto Part / Interrupt / the UI kit, and automatic dispatch still walks the
275 * message list.
276 *
277 * `chatOptions` is type-only at runtime. Pass optional `chatContext`,
278 * `partContext`, and `interruptContext` from {@link createChatHookContexts}
279 * when widgets live in other files or when nested chats need isolation.
280 */
281export function createChatUI<
282 const TOptions,
283 TInput extends ComponentType<any> | undefined =
284 | ComponentType<InputProps<NoInfer<TOptions>>>
285 | undefined,
286>(options: TOptions, config: ChatUIFactoryConfig<NoInfer<TOptions>, TInput>) {
287 void options
288 const {
289 context: contextOption,
290 components,
291 partsComponents: parts,
292 toolsComponents: tools,
293 interruptsComponents: interrupts,
294 } = config as ChatUIFactoryConfig<TOptions, TInput> & {
295 toolsComponents?: Record<string, ComponentType<any> | undefined>
296 interruptsComponents?: {
297 tools?: Record<string, ComponentType<any> | undefined>
298 generic?: Record<string, ComponentType<any> | undefined>
299 }
300 }
301 const {
302 layout: Layout,
303 message: MessageComponent,
304 input: InputComponent,
305 queue: QueueItemComponent,
306 } = components
307 const {
308 chatContext: chatContextOption,
309 partContext: partContextOption,
310 interruptContext: interruptContextOption,
311 } = contextOption ?? {}
312 const warn = createWarnOnce()
313 const ChatContext = (chatContextOption ??
314 defaultChatUIContexts.chatContext) as Context<ChatUIHost<TOptions> | null>
315 const PartContext = (partContextOption ??
316 defaultChatUIContexts.partContext) as Context<ChatUISelectedPart | null>
317 const InterruptContext = (interruptContextOption ??
318 defaultChatUIContexts.interruptContext) as Context<ChatUIInterrupt | null>
319 const inlineToolNames = collectInlineToolNames(
320 interrupts?.tools as Record<string, unknown> | undefined,
321 Object.keys(tools ?? {}),
322 )
323​
324 function useChatContext() {
325 const chat = useContext(ChatContext)
326 if (!chat) {
327 throw new Error(
328 '`useChatContext` must be used within `UI.Provider` or `UI.Chat`.',
329 )
330 }
331 return chat
332 }
333​
334 function usePartContext<TKey extends ChatUIPartKey = ChatUIPartKey>() {
335 const selected = useContext(PartContext)
336 if (!selected) {
337 throw new Error(
338 '`usePartContext` must be used within `UI.Part` or an automatic part.',
339 )
340 }
341 return selected as ChatUISelectedPartOf<TOptions, TKey>
342 }
343​
344 function useInterruptContext<
345 TName extends ChatUIInterruptName<TOptions> = ChatUIInterruptName<TOptions>,
346 >() {
347 const interrupt = useContext(InterruptContext)
348 if (!interrupt) {
349 throw new Error(
350 '`useInterruptContext` must be used within `UI.Interrupt`.',
351 )
352 }
353 return interrupt as ChatUIInterruptOf<TOptions, TName>
354 }
355​
356 function bindPart(Component: ComponentType<PartProps<TOptions>>) {
357 return function BoundPart() {
358 const selected = usePartContext()
359 return <Component part={selected.part as PartProps<TOptions>['part']} />
360 }
361 }
362​
363 function bindTool(Component: ComponentType<ToolProps<TOptions>>) {
364 return function BoundTool() {
365 const selected = usePartContext()
366 if (selected.key !== 'toolCall') return null
367 return (
368 <Component
369 part={selected.part as ToolProps<TOptions>['part']}
370 result={selected.result}
371 interrupt={selected.interrupt as ToolProps<TOptions>['interrupt']}
372 />
373 )
374 }
375 }
376​
377 function bindInterrupt(Component: ComponentType<InterruptProps<TOptions>>) {
378 return function BoundInterrupt() {
379 const interrupt = useInterruptContext()
380 return (
381 <Component
382 interrupt={interrupt as InterruptProps<TOptions>['interrupt']}
383 />
384 )
385 }
386 }
387​
388 const partMixins = bindMap(
389 parts as Record<string, ComponentType<any> | undefined>,
390 bindPart,
391 )
392 const toolMixins = bindMap(
393 tools as Record<string, ComponentType<any> | undefined>,
394 bindTool,
395 )
396 const interruptMixins = {
397 ...bindMap(
398 interrupts?.generic as
399 | Record<string, ComponentType<any> | undefined>
400 | undefined,
401 bindInterrupt,
402 ),
403 ...bindMap(
404 interrupts?.tools as
405 | Record<string, ComponentType<any> | undefined>
406 | undefined,
407 bindInterrupt,
408 ),
409 }
410​
411 function mixPart(selected: ChatUISelectedPart) {
412 return Object.assign({}, selected, partMixins, toolMixins, {
413 Render: BoundRender,
414 }) as ChatUISelectedPart & PartMixins<TOptions>
415 }
416​
417 function mixInterrupt(interrupt: ChatUIInterrupt) {
418 return Object.assign({}, interrupt, interruptMixins, {
419 Render: BoundInterruptRender,
420 }) as ChatUIInterrupt & InterruptMixins<TOptions>
421 }
422​
423 function Provider({
424 chat,
425 children,
426 }: {
427 chat: ChatUIHost<TOptions>
428 children?: OctaneNode
429 }) {
430 return <ChatContext value={chat}>{children}</ChatContext>
431 }
432​
433 // Backstop for when the conditional `Input` type cannot be inferred (see the
434 // `input` note in docs/ui/react.md). The type hides `Input` when no `input`
435 // is registered, but inference degrades on some config shapes, so always
436 // supply a component: warn once rather than crash on an undefined element.
437 function MissingInput() {
438 warn(
439 'input',
440 '[tanstack-ai-ui] Rendered <Input /> but no `input` component is registered.',
441 )
442 return null
443 }
444​
445 // `Messages`, `Interrupts`, `Queue` and `InputComponent` are declared once
446 // per factory, so these props are stable for the lifetime of the kit.
447 const LayoutSlots = {
448 Messages: Messages as ComponentType,
449 Interrupts: Interrupts as ComponentType,
450 Queue: Queue as ComponentType,
451 Input: (InputComponent ?? MissingInput) as ComponentType,
452 }
453​
454 function Chat({ chat }: { chat: ChatUIHost<TOptions> }) {
455 return (
456 <Provider chat={chat}>
457 <Layout {...(LayoutSlots as ComponentProps<ComponentType<any>>)} />
458 </Provider>
459 )
460 }
461​
462 function Queue() {
463 const chat = useChatContext()
464 if (!QueueItemComponent) return null
465 const items = chat.queue
466 return (
467 <>
468 {items.map((item) => (
469 <QueueItemView
470 key={item.id}
471 cancelQueued={chat.cancelQueued}
472 item={item}
473 />
474 ))}
475 </>
476 )
477 }
478​
479 const QueueItemView = memo(function QueueItemView({
480 item,
481 cancelQueued,
482 }: {
483 item: QueuedMessage
484 cancelQueued: (id: string) => void
485 }) {
486 if (!QueueItemComponent) return null
487 return (
488 <QueueItemComponent
489 item={{
490 ...item,
491 cancelQueued: () => {
492 cancelQueued(item.id)
493 },
494 }}
495 />
496 )
497 }, queueItemEqual)
498​
499 function Messages({
500 children,
501 }: {
502 children?: (messages: ChatUIMessages<TOptions>) => OctaneNode
503 } = {}) {
504 const chat = useChatContext()
505 const messages = readMessages(chat)
506 const interrupts = readInterrupts(chat)
507 if (children) return <>{children(messages)}</>
508 return (
509 <>
510 {messages.map((message) => (
511 <MessageView
512 key={message.id}
513 inlineToolNames={inlineToolNames}
514 interrupts={interrupts}
515 message={message}
516 />
517 ))}
518 </>
519 )
520 }
521​
522 // Scoped to one message render. `Parts` reads it instead of closing over the
523 // message, which is what keeps its identity constant across re-renders — a
524 // fresh component per render would remount every part on each stream chunk.
525 type MessageRenderValue = {
526 message: ChatUIMessages<TOptions>[number]
527 interrupts: ReadonlyArray<ChatUIInterrupt>
528 inlineToolNames: ReadonlyArray<string>
529 }
530 const MessageRenderContext = createContext<MessageRenderValue | null>(null)
531​
532 function Parts() {
533 const scope = useContext(MessageRenderContext)
534 if (!scope) {
535 throw new Error('`Parts` must be rendered by a `message` component.')
536 }
537 return (
538 <AutomaticParts
539 inlineToolNames={scope.inlineToolNames}
540 interrupts={scope.interrupts}
541 message={scope.message}
542 />
543 )
544 }
545​
546 const MessageView = memo(function MessageView({
547 message,
548 interrupts,
549 inlineToolNames: names,
550 children,
551 }: {
552 message: ChatUIMessages<TOptions>[number]
553 interrupts: ReadonlyArray<ChatUIInterrupt>
554 inlineToolNames: ReadonlyArray<string>
555 children?: (parts: Array<ChatUISelectedPart>) => OctaneNode
556 }) {
557 const selected = selectMessageUI(message, {
558 interrupts,
559 inlineToolNames: names,
560 })
561 if (children) return <>{children(selected.parts)}</>
562 return (
563 <MessageRenderContext
564 value={{ message, interrupts, inlineToolNames: names }}
565 >
566 <MessageComponent message={message} Parts={Parts} />
567 </MessageRenderContext>
568 )
569 })
570​
571 function Message({
572 message,
573 children,
574 }: {
575 message: ChatUIMessages<TOptions>[number]
576 children?: (parts: Array<ChatUISelectedPart>) => OctaneNode
577 }) {
578 const chat = useChatContext()
579 return (
580 <MessageView
581 children={children}
582 inlineToolNames={inlineToolNames}
583 interrupts={readInterrupts(chat)}
584 message={message}
585 />
586 )
587 }
588​
589 const AutomaticParts = memo(function AutomaticParts({
590 message,
591 interrupts,
592 inlineToolNames: names,
593 }: {
594 message: ChatUIMessages<TOptions>[number]
595 interrupts: ReadonlyArray<ChatUIInterrupt>
596 inlineToolNames: ReadonlyArray<string>
597 }) {
598 const selected = selectMessageUI(message, {
599 interrupts,
600 inlineToolNames: names,
601 })
602 return (
603 <>
604 {automaticPartsForMessage(selected).map((part, index) => (
605 <SelectedPartView key={`${message.id}-${index}`} selected={part} />
606 ))}
607 </>
608 )
609 })
610​
611 const SelectedPartInner = memo(function SelectedPartInner({
612 selected,
613 }: {
614 selected: ChatUISelectedPart
615 }) {
616 if (selected.key === 'toolCall') {
617 const name = selected.part.name
618 const Tool = tools?.[name as ChatUIToolName<TOptions>] as
619 | ComponentType<ToolProps<TOptions>>
620 | undefined
621 if (!Tool) {
622 warn(`tool:${name}`, `[tanstack-ai-ui] Missing tools.${name} component`)
623 return null
624 }
625 return (
626 <Tool
627 part={selected.part as ToolProps<TOptions>['part']}
628 result={selected.result}
629 interrupt={selected.interrupt as ToolProps<TOptions>['interrupt']}
630 />
631 )
632 }
633​
634 const PartComponent = (parts[selected.key] ?? parts.fallback) as
635 | ComponentType<PartProps<TOptions>>
636 | undefined
637 if (!PartComponent) {
638 warn(
639 `part:${selected.key}`,
640 `[tanstack-ai-ui] Missing parts.${selected.key} component`,
641 )
642 return null
643 }
644 return <PartComponent part={selected.part as PartProps<TOptions>['part']} />
645 }, selectedPartPropsEqual)
646​
647 const SelectedPartView = memo(function SelectedPartView({
648 selected,
649 }: {
650 selected: ChatUISelectedPart
651 }) {
652 return (
653 <PartContext value={selected}>
654 <SelectedPartInner selected={selected} />
655 </PartContext>
656 )
657 })
658​
659 function BoundRender() {
660 const selected = usePartContext()
661 return <SelectedPartInner selected={selected} />
662 }
663​
664 function Part({
665 part,
666 children,
667 }: {
668 part: MessagePart | ChatUISelectedPart
669 children?: (mixed: ChatUISelectedPart & PartMixins<TOptions>) => OctaneNode
670 }) {
671 const chat = useChatContext()
672 const selected = isSelectedPart(part)
673 ? part
674 : selectMessageUI(
675 { id: 'part', role: 'assistant', parts: [part] },
676 { interrupts: readInterrupts(chat), inlineToolNames: [] },
677 ).parts[0]
678 if (!selected) return null
679 return (
680 <PartContext value={selected}>
681 {children ? (
682 children(mixPart(selected))
683 ) : (
684 <SelectedPartInner selected={selected} />
685 )}
686 </PartContext>
687 )
688 }
689​
690 function Interrupts({
691 children,
692 }: {
693 children?: (interrupts: ReadonlyArray<ChatUIInterrupt>) => OctaneNode
694 } = {}) {
695 const chat = useChatContext()
696 const selected = selectChatUI({
697 messages: readMessages(chat),
698 interrupts: readInterrupts(chat),
699 inlineToolNames,
700 })
701 if (children) return <>{children(selected.interrupts)}</>
702 return (
703 <>
704 {selected.interrupts.map((interrupt) => (
705 <Interrupt key={interrupt.id} interrupt={interrupt} />
706 ))}
707 </>
708 )
709 }
710​
711 const InterruptInner = memo(function InterruptInner({
712 interrupt,
713 }: {
714 interrupt: ChatUIInterrupt
715 }) {
716 const Component = resolveInterruptComponent(interrupt, interrupts) as
717 | ComponentType<InterruptProps<TOptions>>
718 | undefined
719 if (!Component) {
720 warn(
721 `interrupt:${interrupt.id}`,
722 `[tanstack-ai-ui] Missing interrupt component for ${interrupt.kind}`,
723 )
724 return null
725 }
726 return <Component interrupt={interrupt} />
727 })
728​
729 function BoundInterruptRender() {
730 const interrupt = useInterruptContext()
731 return <InterruptInner interrupt={interrupt} />
732 }
733​
734 const Interrupt = memo(function Interrupt({
735 interrupt,
736 children,
737 }: {
738 interrupt: ChatUIInterrupt
739 children?: (mixed: ChatUIInterrupt & InterruptMixins<TOptions>) => OctaneNode
740 }) {
741 return (
742 <InterruptContext value={interrupt}>
743 {children ? (
744 children(mixInterrupt(interrupt))
745 ) : (
746 <InterruptInner interrupt={interrupt} />
747 )}
748 </InterruptContext>
749 )
750 })
751​
752 return {
753 Chat,
754 Provider,
755 Messages,
756 Message,
757 Part,
758 Interrupts,
759 Interrupt,
760 Queue,
761 useChatContext,
762 Input: InputComponent,
763 }