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

use-chat.ts

407 lines12.6 KB

1import { ChatClient } from '@tanstack/ai-client'
2import { createChatDevtoolsBridge } from '@tanstack/ai-client/devtools'
3import { useSyncExternalStore } from 'preact/compat'
4import { useCallback, useEffect, useMemo, useRef } from 'preact/hooks'
5import type {
6 ResolvableChatInterrupt,
7 ChatResumeState,
8 InferredClientContext,
9 SendMessageOptions,
10} from '@tanstack/ai-client'
11import type {
12 AnyClientTool,
13 InterruptDefinition,
14 ModelMessage,
15 RunAgentResumeItem,
16} from '@tanstack/ai'
17​
18import type {
19 MultimodalContent,
20 UIMessage,
21 UseChatOptions,
22 UseChatReturn,
23} from './types'
24​
25export function useChat<
26 const TTools extends ReadonlyArray<AnyClientTool> = any,
27 TContext = InferredClientContext<TTools>,
28 const TInterrupts extends ReadonlyArray<
29 InterruptDefinition<any, any, any, any>
30 > = readonly [],
31>(
32 options: UseChatOptions<TTools, TContext, TInterrupts>,
33): UseChatReturn<TTools, TInterrupts> {
34 // The hook's identity is its `threadId`. Reload with the same `threadId`
35 // restores the same conversation.
36 const clientId = options.threadId
37​
38 const activeClientRef = useRef<ChatClient | null>(null)
39 const cleanupInvalidationRef = useRef<ReturnType<typeof setTimeout> | null>(
40 null,
41 )
42 const cleanupDisposalRef = useRef<{
43 client: ChatClient
44 timeout: ReturnType<typeof setTimeout>
45 } | null>(null)
46 const optionsRef =
47 useRef<UseChatOptions<TTools, TContext, TInterrupts>>(options)
48​
49 optionsRef.current = options
50​
51 const { client, initialization } = useMemo(() => {
52 const messagesToUse = options.initialMessages || []
53​
54 // Build options with conditional spreads for fields whose source
55 // type is `T | undefined` but the ChatClient target uses a strict
56 // optional (`field?: T`) — `exactOptionalPropertyTypes` rejects
57 // assigning `undefined` to those, so we omit the key when absent.
58 const initialOptions = optionsRef.current
59 const transport = initialOptions.connection
60 ? { connection: initialOptions.connection }
61 : { fetcher: initialOptions.fetcher }
62​
63 const instanceHolder: {
64 current: ChatClient<TTools, TContext, TInterrupts> | undefined
65 } = { current: undefined }
66 const getActiveInstance = () => {
67 const currentInstance = instanceHolder.current
68 if (!currentInstance || activeClientRef.current !== currentInstance) {
69 return undefined
70 }
71 return currentInstance
72 }
73 // ChatClient may publish while its constructor is running or while async
74 // persistence resolves before commit. Preserve those exact notifications
75 // until this render commits; invoking them here would run state setters and
76 // user callbacks for a render that may never mount.
77 const initializationState = {
78 ready: false,
79 callbacks: [] as Array<() => void>,
80 }
81 const runOrQueueForActiveInstance = (callback: () => void) => {
82 if (!initializationState.ready) {
83 initializationState.callbacks.push(callback)
84 return
85 }
86 const currentInstance = instanceHolder.current
87 if (!currentInstance || activeClientRef.current !== currentInstance)
88 return
89 callback()
90 }
91 const instance = new ChatClient<TTools, TContext, TInterrupts>({
92 devtoolsBridgeFactory: createChatDevtoolsBridge,
93 ...transport,
94 initialMessages: messagesToUse,
95 threadId: initialOptions.threadId,
96 ...(initialOptions.persistence === true
97 ? {
98 persistence: true,
99 ...(initialOptions.history !== undefined && {
100 history: initialOptions.history,
101 }),
102 }
103 : { persistence: initialOptions.persistence }),
104 ...(initialOptions.forwardedProps !== undefined && {
105 forwardedProps: initialOptions.forwardedProps,
106 }),
107 ...(initialOptions.byok !== undefined && { byok: initialOptions.byok }),
108 byokProvider: () => optionsRef.current.byokProvider?.(),
109 ...(initialOptions.initialResumeSnapshot !== undefined && {
110 initialResumeSnapshot: initialOptions.initialResumeSnapshot,
111 }),
112 ...(initialOptions.context !== undefined && {
113 context: initialOptions.context,
114 }),
115 devtools: {
116 ...initialOptions.devtools,
117 framework: 'preact',
118 hookName: 'useChat',
119 outputKind: initialOptions.outputSchema ? 'structured' : 'chat',
120 },
121 // Wrap every callback so the latest options are read at call time.
122 // Capturing the function reference directly would freeze it to whatever
123 // the parent passed on the first render.
124 onResponse: (response) => {
125 if (!getActiveInstance()) return
126 return optionsRef.current.onResponse?.(response)
127 },
128 onChunk: (chunk) => {
129 runOrQueueForActiveInstance(() => {
130 optionsRef.current.onChunk?.(chunk)
131 })
132 },
133 onFinish: (message) => {
134 runOrQueueForActiveInstance(() => {
135 optionsRef.current.onFinish?.(message)
136 })
137 },
138 onError: (err) => {
139 runOrQueueForActiveInstance(() => {
140 optionsRef.current.onError?.(err)
141 })
142 },
143 onCustomEvent: (eventType, data, context) => {
144 runOrQueueForActiveInstance(() => {
145 optionsRef.current.onCustomEvent?.(eventType, data, context)
146 })
147 },
148 ...(initialOptions.tools !== undefined && {
149 tools: initialOptions.tools,
150 }),
151 ...(initialOptions.interrupts !== undefined && {
152 interrupts: initialOptions.interrupts,
153 }),
154 ...(options.streamProcessor !== undefined && {
155 streamProcessor: options.streamProcessor,
156 }),
157 ...(optionsRef.current.queue !== undefined && {
158 queue: optionsRef.current.queue,
159 }),
160 onInterruptStateChange: (nextInterruptState, context) => {
161 runOrQueueForActiveInstance(() => {
162 optionsRef.current.onInterruptStateChange?.(
163 nextInterruptState,
164 context,
165 )
166 })
167 },
168 })
169 instanceHolder.current = instance
170 return { client: instance, initialization: initializationState }
171 }, [clientId])
172​
173 useEffect(() => {
174 activeClientRef.current = client
175 try {
176 // Keep initialization closed while draining so callbacks published by a
177 // queued callback are appended and delivered in the same commit.
178 while (initialization.callbacks.length > 0) {
179 if (activeClientRef.current !== client) {
180 initialization.callbacks.length = 0
181 break
182 }
183 initialization.callbacks.shift()?.()
184 }
185 } finally {
186 // A throw from a queued user callback must not leave the queue closed.
187 initialization.ready = true
188 }
189 }, [client, initialization])
190​
191 const snapshot = useSyncExternalStore(
192 client.subscribeSnapshot,
193 client.getSnapshot,
194 )
195​
196 // Sync forwardedProps changes to the client.
197 useEffect(() => {
198 // Conditional spread: `updateOptions` declares strict-optional
199 // fields and rejects explicit `undefined` under EOPT.
200 client.updateOptions({
201 ...(options.forwardedProps !== undefined && {
202 forwardedProps: options.forwardedProps,
203 }),
204 context: options.context,
205 ...(options.queue !== undefined && { queue: options.queue }),
206 })
207 }, [client, options.forwardedProps, options.context, options.queue])
208​
209 useEffect(() => {
210 if (options.tools !== undefined) {
211 client.updateOptions({ tools: options.tools })
212 }
213 }, [client, options.tools])
214​
215 useEffect(() => {
216 if (options.live) {
217 client.subscribe()
218 } else {
219 client.unsubscribe()
220 }
221 }, [client, options.live])
222​
223 // ONLY THE VIEW ON SCREEN HOLDS A STREAM. See the same effect in
224 // `@tanstack/ai-react`. A page can own many chats and a browser allows only ~6
225 // connections per origin, so one long-lived stream per chat starves everything
226 // else once a handful of views have been open. `attach` is idempotent and
227 // `detach` keeps the transcript and the resume pointer, so a remount picks the
228 // run straight back up from the durable log.
229 //
230 // Immediate, unlike the deferred disposal below, which a remount can skip —
231 // correct for disposal, useless for a connection.
232 useEffect(() => {
233 client.attach()
234 return () => {
235 client.detach()
236 }
237 }, [client])
238​
239 // Cleanup on unmount: stop any in-flight requests
240 // Note: We only cleanup when client changes or component unmounts.
241 // DO NOT include isLoading in dependencies - that would cause the cleanup
242 // to run when isLoading changes, aborting continuation requests.
243 useEffect(() => {
244 if (cleanupDisposalRef.current?.client === client) {
245 clearTimeout(cleanupDisposalRef.current.timeout)
246 cleanupDisposalRef.current = null
247 }
248 if (cleanupInvalidationRef.current) {
249 clearTimeout(cleanupInvalidationRef.current)
250 cleanupInvalidationRef.current = null
251 }
252 client.mountDevtools()
253​
254 return () => {
255 cleanupInvalidationRef.current = setTimeout(() => {
256 if (activeClientRef.current === client) {
257 activeClientRef.current = null
258 }
259 cleanupInvalidationRef.current = null
260 }, 0)
261 // Subscribe/unsubscribe on `options.live` is owned by the dedicated
262 // effect above. This cleanup only fires on unmount or client swap,
263 // so read `live` through the ref to avoid disposing the client every
264 // time `live` toggles.
265 if (optionsRef.current.live) {
266 client.unsubscribe()
267 } else {
268 client.stop()
269 }
270 const disposal = {
271 client,
272 timeout: setTimeout(() => {
273 client.dispose()
274 if (cleanupDisposalRef.current === disposal) {
275 cleanupDisposalRef.current = null
276 }
277 }, 0),
278 }
279 cleanupDisposalRef.current = disposal
280 }
281 }, [client])
282​
283 // All callback options are read through optionsRef at call time, so fresh
284 // closures from each render are picked up without recreating the client.
285 const sendMessage = useCallback(
286 async (
287 content: string | MultimodalContent,
288 sendOptions?: SendMessageOptions,
289 ) => {
290 await client.sendMessage(content, undefined, sendOptions)
291 },
292 [client],
293 )
294​
295 const cancelQueued = useCallback(
296 (id: string) => {
297 client.cancelQueued(id)
298 },
299 [client],
300 )
301​
302 const append = useCallback(
303 async (message: ModelMessage | UIMessage) => {
304 await client.append(message)
305 },
306 [client],
307 )
308​
309 const reload = useCallback(async () => {
310 await client.reload()
311 }, [client])
312​
313 const loadOlderMessages = useCallback(async () => {
314 await client.loadOlderMessages()
315 }, [client])
316​
317 const stop = useCallback(() => {
318 client.stop()
319 }, [client])
320​
321 const clear = useCallback(() => {
322 client.clear()
323 }, [client])
324​
325 const setMessagesManually = useCallback(
326 (newMessages: ReadonlyArray<UIMessage<TTools>>) => {
327 client.setMessagesManually(newMessages)
328 },
329 [client],
330 )
331​
332 const addToolResult = useCallback(
333 async (result: {
334 toolCallId: string
335 tool: string
336 output: unknown
337 state?: 'output-available' | 'output-error'
338 errorText?: string
339 }) => {
340 await client.addToolResult(result)
341 },
342 [client],
343 )
344​
345 const resolveInterrupts = useCallback(
346 (
347 resolution:
348 | boolean
349 | ((
350 interrupt: ResolvableChatInterrupt<TTools, TInterrupts>,
351 ) => undefined),
352 ) => {
353 if (typeof resolution === 'boolean') {
354 client.resolveInterrupts(resolution)
355 } else {
356 client.resolveInterrupts(resolution)
357 }
358 },
359 [client],
360 )
361​
362 const cancelInterrupts = useCallback(() => {
363 client.cancelInterrupts()
364 }, [client])
365​
366 const retryInterrupts = useCallback(() => {
367 client.retryInterrupts()
368 }, [client])
369​
370 const resumeInterruptsUnsafe = useCallback(
371 (resumeItems: Array<RunAgentResumeItem>, state?: ChatResumeState) =>
372 client.resumeInterruptsUnsafe(resumeItems, state),
373 [client],
374 )
375​
376 const renderedMessages = snapshot.messages
377​
378 return {
379 messages: renderedMessages,
380 sendMessage,
381 append,
382 reload,
383 stop,
384 isLoading: snapshot.isLoading,
385 hasOlderMessages: snapshot.hasOlderMessages,
386 loadOlderMessages,
387 error: snapshot.error,
388 status: snapshot.status,
389 isSubscribed: snapshot.isSubscribed,
390 connectionStatus: snapshot.connectionStatus,
391 sessionGenerating: snapshot.sessionGenerating,
392 isHydrating: snapshot.isHydrating,
393 setMessages: setMessagesManually,
394 clear,
395 addToolResult,
396 queue: snapshot.queue,
397 cancelQueued,
398 runId: snapshot.runId,
399 interrupts: snapshot.interruptState.interrupts,
400 interruptErrors: snapshot.interruptState.interruptErrors,
401 resuming: snapshot.interruptState.resuming,
402 resolveInterrupts,
403 cancelInterrupts,
404 retryInterrupts,
405 resumeInterruptsUnsafe,
406 }