Open History to see the last commit
1import { useMemo, useRef } from 'react'
2import type { ComponentType } from 'react'
3import type { InferredClientContext } from '@tanstack/ai-client'
4import type {
5 ChatUIInterruptsOf,
6 ChatUISchemaOf,
7 ChatUIToolsOf,
8} from '@tanstack/ai-client/ui'
9import { useChat as useUnboundChat } from '../use-chat'
10import type { UseChatOptions } from '../types'
11import { createChatUI } from './create-ui'
12import type { ChatUIFactoryConfig, ChatUIHost, InputProps } from './create-ui'
13
14type HeadlessOptions<TOptions> = UseChatOptions<
15 ChatUIToolsOf<TOptions>,
16 ChatUISchemaOf<TOptions>,
17 InferredClientContext<ChatUIToolsOf<TOptions>>,
18 ChatUIInterruptsOf<TOptions>
19>
20
21type ChatInstanceOverrides<TOptions> = {
22 threadId?: string
23 live?: boolean
24 forwardedProps?: Record<string, any>
25 body?: Record<string, any>
26 initialMessages?: HeadlessOptions<TOptions>['initialMessages']
27}
28
29/**
30 * Bind chat options and UI widgets once at module scope.
31 *
32 * This matches Form `createFormHook` and Table `createTableHook`. The
33 * returned `useAppChat` creates a chat instance. `chat.AppChat` renders it.
34 * `useChatContext` reads that instance. Part and interrupt widgets take
35 * `part` / `interrupt` as props. Do not read those from context.
36 *
37 * Pass instance overrides such as `threadId` into `useAppChat()`.
38 *
39 * @example
40 * ```tsx
41 * const { useAppChat, useChatContext } = createChatHook({
42 * options: chatOptions,
43 * components: { layout: ChatLayout, message: ChatMessage },
44 * partsComponents: { fallback: FallbackPart },
45 * toolsComponents: { getWeather: WeatherTool, purchaseItem: PurchaseTool },
46 * interruptsComponents: { generic: { choosePlan: ChoosePlan } },
47 * })
48 *
49 * function Support() {
50 * const chat = useAppChat({ threadId: 'support-1' })
51 * return <chat.AppChat />
52 * }
53 * ```
54 */
55export function createChatHook<
56 const TOptions,
57 TInput extends ComponentType<any> | undefined =
58 | ComponentType<InputProps<NoInfer<TOptions>>>
59 | undefined,
60>({
61 options,
62 ...chatComponents
63}: {
64 options: TOptions
65} & ChatUIFactoryConfig<NoInfer<TOptions>, TInput>) {
66 const ui = createChatUI(
67 options,
68 chatComponents as ChatUIFactoryConfig<NoInfer<TOptions>, TInput>,
69 )
70
71 function useAppChat(overrides?: ChatInstanceOverrides<TOptions>) {
72 const chat = (
73 overrides
74 ? useUnboundChat({
75 ...(options as HeadlessOptions<TOptions>),
76 ...overrides,
77 })
78 : useUnboundChat(options as HeadlessOptions<TOptions>)
79 ) as ChatUIHost<TOptions>
80
81 // `useChat` returns a fresh object on every render. The mixed Chat
82 // component must stay stable, or React remounts the tree on each
83 // update. Read the current instance from a ref.
84 const chatRef = useRef(chat)
85 chatRef.current = chat
86
87 const AppChat = useMemo(() => {
88 function AppChatImpl() {
89 return <ui.Chat chat={chatRef.current} />
90 }
91 return AppChatImpl
92 }, [])
93
94 return Object.assign(chat, { AppChat }) as ChatUIHost<TOptions> & {
95 AppChat: ComponentType
96 }
97 }
98
99 return {
100 useAppChat,
101 useChatContext: ui.useChatContext,
102 }
103}