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 initialMessages?: HeadlessOptions<TOptions>['initialMessages']
26}
27
28/**
29 * Bind chat options and UI widgets once at module scope.
30 *
31 * This matches Form `createFormHook` and Table `createTableHook`. The
32 * returned `useAppChat` creates a chat instance. `chat.AppChat` renders it.
33 * `useChatContext` reads that instance. Part and interrupt widgets take
34 * `part` / `interrupt` as props. Do not read those from context.
35 *
36 * Pass `threadId` and other instance overrides into `useAppChat()`.
37 *
38 * @example
39 * ```tsx
40 * const { useAppChat, useChatContext } = createChatHook({
41 * options: chatOptions,
42 * components: { layout: ChatLayout, message: ChatMessage },
43 * partsComponents: { fallback: FallbackPart },
44 * toolsComponents: { getWeather: WeatherTool, purchaseItem: PurchaseTool },
45 * interruptsComponents: { generic: { choosePlan: ChoosePlan } },
46 * })
47 *
48 * function Support() {
49 * const chat = useAppChat({ threadId: 'support-1' })
50 * return <chat.AppChat />
51 * }
52 * ```
53 */
54export function createChatHook<
55 const TOptions,
56 TInput extends ComponentType<any> | undefined =
57 | ComponentType<InputProps<NoInfer<TOptions>>>
58 | undefined,
59>({
60 options,
61 ...chatComponents
62}: {
63 options: TOptions
64} & ChatUIFactoryConfig<NoInfer<TOptions>, TInput>) {
65 const ui = createChatUI(
66 options,
67 chatComponents as ChatUIFactoryConfig<NoInfer<TOptions>, TInput>,
68 )
69
70 function useAppChat(overrides: ChatInstanceOverrides<TOptions>) {
71 const chat = useUnboundChat({
72 ...(options as HeadlessOptions<TOptions>),
73 ...overrides,
74 }) as ChatUIHost<TOptions>
75
76 // `useChat` returns a fresh object on every render. The mixed Chat
77 // component must stay stable, or React remounts the tree on each
78 // update. Read the current instance from a ref.
79 const chatRef = useRef(chat)
80 chatRef.current = chat
81
82 const AppChat = useMemo(() => {
83 function AppChatImpl() {
84 return <ui.Chat chat={chatRef.current} />
85 }
86 return AppChatImpl
87 }, [])
88
89 return Object.assign(chat, { AppChat }) as ChatUIHost<TOptions> & {
90 AppChat: ComponentType
91 }
92 }
93
94 return {
95 useAppChat,
96 useChatContext: ui.useChatContext,
97 }
98}