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