Open History to see the last commit
1import type { Component } from 'solid-js'
2import type { InferredClientContext } from '@tanstack/ai-client'
3import type {
4 ChatUIInterruptsOf,
5 ChatUISchemaOf,
6 ChatUIToolsOf,
7} from '@tanstack/ai-client/ui'
8import { useChat as useUnboundChat } from '../use-chat'
9import type { UseChatOptions } from '../types'
10import { createChatUI } from './create-ui'
11import type { ChatUIFactoryConfig, ChatUIHost, InputProps } from './create-ui'
12
13type HeadlessOptions<TOptions> = UseChatOptions<
14 ChatUIToolsOf<TOptions>,
15 ChatUISchemaOf<TOptions>,
16 InferredClientContext<ChatUIToolsOf<TOptions>>,
17 ChatUIInterruptsOf<TOptions>
18>
19
20type ChatInstanceOverrides<TOptions> = {
21 threadId: string
22 live?: boolean
23 forwardedProps?: Record<string, any>
24 initialMessages?: HeadlessOptions<TOptions>['initialMessages']
25}
26
27/**
28 * Bind chat options and UI widgets once at module scope.
29 *
30 * This matches Form `createFormHook` and Table `createTableHook`. The
31 * returned `useAppChat` creates a chat instance. `chat.AppChat` renders it.
32 * Context `useChatContext` reads that instance. Part and interrupt
33 * widgets take `part` / `interrupt` as props.
34 *
35 * Pass `threadId` and other instance overrides into `useAppChat()`.
36 */
37export function createChatHook<
38 const TOptions,
39 TInput extends Component<any> | undefined =
40 | Component<InputProps<NoInfer<TOptions>>>
41 | undefined,
42>({
43 options,
44 ...chatComponents
45}: {
46 options: TOptions
47} & ChatUIFactoryConfig<NoInfer<TOptions>, TInput>) {
48 const ui = createChatUI(
49 options,
50 chatComponents as ChatUIFactoryConfig<NoInfer<TOptions>, TInput>,
51 )
52
53 function useAppChat(overrides: ChatInstanceOverrides<TOptions>) {
54 const chat = useUnboundChat({
55 ...(options as HeadlessOptions<TOptions>),
56 ...overrides,
57 }) as ChatUIHost<TOptions>
58
59 function AppChat() {
60 return <ui.Chat chat={chat} />
61 }
62
63 return Object.assign(chat, { AppChat }) as ChatUIHost<TOptions> & {
64 AppChat: Component
65 }
66 }
67
68 return {
69 useAppChat,
70 useChatContext: ui.useChatContext,
71 }
72}