Open History to see the last commit
1import { ChatClient } from '@tanstack/ai-client'
2import { createChatDevtoolsBridge } from '@tanstack/ai-client/devtools'
3import {
4 useCallback,
5 useEffect,
6 useId,
7 useMemo,
8 useRef,
9 useState,
10} from 'preact/hooks'
11import type {
12 ChatClientState,
13 ResolvableChatInterrupt,
14 ChatInterruptState,
15 ChatResumeState,
16 ConnectionStatus,
17 InferredClientContext,
18 QueuedMessage,
19 SendMessageOptions,
20} from '@tanstack/ai-client'
21import type {
22 AnyClientTool,
23 InterruptDefinition,
24 ModelMessage,
25 RunAgentResumeItem,
26} from '@tanstack/ai'
27
28import type {
29 MultimodalContent,
30 UIMessage,
31 UseChatOptions,
32 UseChatReturn,
33} from './types'
34
35const EMPTY_INTERRUPTS = Object.freeze([])
36const EMPTY_INTERRUPT_ERRORS = Object.freeze([])
37
38export function useChat<
39 const TTools extends ReadonlyArray<AnyClientTool> = any,
40 TContext = InferredClientContext<TTools>,
41 const TInterrupts extends ReadonlyArray<
42 InterruptDefinition<any, any, any, any>
43 > = readonly [],
44>(
45 options: UseChatOptions<TTools, TContext, TInterrupts>,
46): UseChatReturn<TTools, TInterrupts> {
47 // The hook's identity is its `threadId`. Reload with the same `threadId`
48 // restores the same conversation. `hookId` is only a recreation key when no
49 // `threadId` is given. It is never sent on the wire.
50 const hookId = useId()
51 const clientId = options.threadId ?? hookId
52
53 const [messages, setMessages] = useState<Array<UIMessage<TTools>>>(
54 options.initialMessages || [],
55 )
56 const [isLoading, setIsLoading] = useState(false)
57 const [hasOlderMessages, setHasOlderMessages] = useState(false)
58 const [error, setError] = useState<Error | undefined>(undefined)
59 const [status, setStatus] = useState<ChatClientState>('ready')
60 const [isSubscribed, setIsSubscribed] = useState(false)
61 const [connectionStatus, setConnectionStatus] =
62 useState<ConnectionStatus>('disconnected')
63 const [sessionGenerating, setSessionGenerating] = useState(false)
64 const [queue, setQueue] = useState<Array<QueuedMessage>>([])
65 const [runId, setRunId] = useState<string | null>(null)
66 const [interruptState, setInterruptState] = useState<
67 ChatInterruptState<TTools, TInterrupts>
68 >(() => ({
69 interrupts: EMPTY_INTERRUPTS,
70 pendingInterrupts: EMPTY_INTERRUPTS,
71 interruptErrors: EMPTY_INTERRUPT_ERRORS,
72 resuming: false,
73 }))
74
75 // Track current messages in a ref to preserve them when client is recreated
76 const messagesRef = useRef<Array<UIMessage<TTools>>>(
77 options.initialMessages || [],
78 )
79 const isFirstMountRef = useRef(true)
80 const activeClientRef = useRef<ChatClient | null>(null)
81 const cleanupInvalidationRef = useRef<ReturnType<typeof setTimeout> | null>(
82 null,
83 )
84 const cleanupDisposalRef = useRef<{
85 client: ChatClient
86 timeout: ReturnType<typeof setTimeout>
87 } | null>(null)
88 const optionsRef =
89 useRef<UseChatOptions<TTools, TContext, TInterrupts>>(options)
90
91 optionsRef.current = options
92
93 const syncResumeState = useCallback((target: ChatClient | null) => {
94 if (!target) return
95 setRunId(target.getCurrentRunId())
96 setInterruptState(target.getInterruptState())
97 }, [])
98
99 useEffect(() => {
100 messagesRef.current = messages
101 }, [messages])
102
103 const { client, initialization } = useMemo(() => {
104 const messagesToUse = options.initialMessages || []
105 isFirstMountRef.current = false
106
107 // Build options with conditional spreads for fields whose source
108 // type is `T | undefined` but the ChatClient target uses a strict
109 // optional (`field?: T`) — `exactOptionalPropertyTypes` rejects
110 // assigning `undefined` to those, so we omit the key when absent.
111 const initialOptions = optionsRef.current
112 const transport = initialOptions.connection
113 ? { connection: initialOptions.connection }
114 : { fetcher: initialOptions.fetcher }
115
116 const instanceHolder: {
117 current: ChatClient<TTools, TContext, TInterrupts> | undefined
118 } = { current: undefined }
119 const getActiveInstance = () => {
120 const currentInstance = instanceHolder.current
121 if (!currentInstance || activeClientRef.current !== currentInstance) {
122 return undefined
123 }
124 return currentInstance
125 }
126 // ChatClient may publish while its constructor is running or while async
127 // persistence resolves before commit. Preserve those exact notifications
128 // until this render commits; invoking them here would run state setters and
129 // user callbacks for a render that may never mount.
130 const initializationState = {
131 ready: false,
132 callbacks: [] as Array<() => void>,
133 }
134 const runOrQueueForActiveInstance = (callback: () => void) => {
135 if (!initializationState.ready) {
136 initializationState.callbacks.push(callback)
137 return
138 }
139 const currentInstance = instanceHolder.current
140 if (!currentInstance || activeClientRef.current !== currentInstance)
141 return
142 callback()
143 }
144 const instance = new ChatClient<TTools, TContext, TInterrupts>({
145 devtoolsBridgeFactory: createChatDevtoolsBridge,
146 ...transport,
147 initialMessages: messagesToUse,
148 ...(initialOptions.body !== undefined && { body: initialOptions.body }),
149 ...(typeof initialOptions.threadId === 'string' &&
150 initialOptions.persistence === true
151 ? {
152 persistence: true,
153 threadId: initialOptions.threadId,
154 ...(initialOptions.history !== undefined && {
155 history: initialOptions.history,
156 }),
157 }
158 : typeof initialOptions.threadId === 'string' &&
159 initialOptions.persistence
160 ? {
161 persistence: initialOptions.persistence,
162 threadId: initialOptions.threadId,
163 }
164 : {
165 ...(initialOptions.threadId !== undefined && {
166 threadId: initialOptions.threadId,
167 }),
168 }),
169 ...(initialOptions.forwardedProps !== undefined && {
170 forwardedProps: initialOptions.forwardedProps,
171 }),
172 ...(initialOptions.byok !== undefined && { byok: initialOptions.byok }),
173 byokProvider: () => optionsRef.current.byokProvider?.(),
174 ...(initialOptions.initialResumeSnapshot !== undefined && {
175 initialResumeSnapshot: initialOptions.initialResumeSnapshot,
176 }),
177 ...(initialOptions.context !== undefined && {
178 context: initialOptions.context,
179 }),
180 devtools: {
181 ...initialOptions.devtools,
182 framework: 'preact',
183 hookName: 'useChat',
184 outputKind: initialOptions.outputSchema ? 'structured' : 'chat',
185 },
186 // Wrap every callback so the latest options are read at call time.
187 // Capturing the function reference directly would freeze it to whatever
188 // the parent passed on the first render.
189 onResponse: (response) => {
190 if (!getActiveInstance()) return
191 return optionsRef.current.onResponse?.(response)
192 },
193 onChunk: (chunk) => {
194 runOrQueueForActiveInstance(() => {
195 optionsRef.current.onChunk?.(chunk)
196 })
197 },
198 onFinish: (message) => {
199 runOrQueueForActiveInstance(() => {
200 optionsRef.current.onFinish?.(message)
201 })
202 },
203 onError: (err) => {
204 runOrQueueForActiveInstance(() => {
205 optionsRef.current.onError?.(err)
206 })
207 },
208 onCustomEvent: (eventType, data, context) => {
209 runOrQueueForActiveInstance(() => {
210 optionsRef.current.onCustomEvent?.(eventType, data, context)
211 })
212 },
213 ...(initialOptions.tools !== undefined && {
214 tools: initialOptions.tools,
215 }),
216 ...(initialOptions.interrupts !== undefined && {
217 interrupts: initialOptions.interrupts,
218 }),
219 ...(options.streamProcessor !== undefined && {
220 streamProcessor: options.streamProcessor,
221 }),
222 onMessagesChange: (newMessages: Array<UIMessage<TTools>>) => {
223 runOrQueueForActiveInstance(() => {
224 setMessages(newMessages)
225 const currentInstance = getActiveInstance()
226 if (!currentInstance) return
227 setHasOlderMessages(currentInstance.getHasOlderMessages())
228 })
229 },
230 onLoadingChange: (newIsLoading: boolean) => {
231 runOrQueueForActiveInstance(() => {
232 const currentInstance = getActiveInstance()
233 if (!currentInstance) return
234 setIsLoading(newIsLoading)
235 syncResumeState(currentInstance)
236 })
237 },
238 onStatusChange: (newStatus: ChatClientState) => {
239 runOrQueueForActiveInstance(() => {
240 setStatus(newStatus)
241 })
242 },
243 onErrorChange: (newError: Error | undefined) => {
244 runOrQueueForActiveInstance(() => {
245 setError(newError)
246 })
247 },
248 onSubscriptionChange: (nextIsSubscribed: boolean) => {
249 runOrQueueForActiveInstance(() => {
250 setIsSubscribed(nextIsSubscribed)
251 })
252 },
253 onConnectionStatusChange: (nextStatus: ConnectionStatus) => {
254 runOrQueueForActiveInstance(() => {
255 setConnectionStatus(nextStatus)
256 })
257 },
258 onSessionGeneratingChange: (isGenerating: boolean) => {
259 runOrQueueForActiveInstance(() => {
260 setSessionGenerating(isGenerating)
261 })
262 },
263 ...(optionsRef.current.queue !== undefined && {
264 queue: optionsRef.current.queue,
265 }),
266 onQueueChange: (nextQueue: Array<QueuedMessage>) => {
267 runOrQueueForActiveInstance(() => {
268 setQueue(nextQueue)
269 })
270 },
271 onRunIdChange: (nextRunId) => {
272 runOrQueueForActiveInstance(() => {
273 setRunId(nextRunId)
274 })
275 },
276 onResumeStateChange: (_nextResumeState, nextPendingInterrupts) => {
277 runOrQueueForActiveInstance(() => {
278 setInterruptState((current) => ({
279 ...current,
280 interrupts: nextPendingInterrupts,
281 pendingInterrupts: nextPendingInterrupts,
282 }))
283 })
284 },
285 onInterruptStateChange: (nextInterruptState, context) => {
286 runOrQueueForActiveInstance(() => {
287 setInterruptState(nextInterruptState)
288 optionsRef.current.onInterruptStateChange?.(
289 nextInterruptState,
290 context,
291 )
292 })
293 },
294 })
295 instanceHolder.current = instance
296 return { client: instance, initialization: initializationState }
297 }, [clientId, syncResumeState])
298
299 useEffect(() => {
300 activeClientRef.current = client
301 try {
302 // Keep initialization closed while draining so callbacks published by a
303 // queued callback are appended and delivered in the same commit.
304 while (initialization.callbacks.length > 0) {
305 if (activeClientRef.current !== client) {
306 initialization.callbacks.length = 0
307 break
308 }
309 initialization.callbacks.shift()?.()
310 }
311 } finally {
312 // A throw from a queued user callback must not leave the queue closed.
313 initialization.ready = true
314 }
315 }, [client, initialization])
316
317 useEffect(() => {
318 const clientMessages = client.getMessages()
319 if (clientMessages !== messagesRef.current) {
320 setMessages(clientMessages)
321 }
322 setHasOlderMessages(client.getHasOlderMessages())
323 }, [client])
324
325 // Sync body / forwardedProps changes to the client.
326 // Both populate the same wire payload; `forwardedProps` is preferred
327 // and `body` is deprecated but still supported.
328 useEffect(() => {
329 // Conditional spread: `updateOptions` declares strict-optional
330 // fields and rejects explicit `undefined` under EOPT.
331 client.updateOptions({
332 body: options.body,
333 ...(options.forwardedProps !== undefined && {
334 forwardedProps: options.forwardedProps,
335 }),
336 context: options.context,
337 ...(options.queue !== undefined && { queue: options.queue }),
338 })
339 }, [
340 client,
341 options.body,
342 options.forwardedProps,
343 options.context,
344 options.queue,
345 ])
346
347 useEffect(() => {
348 if (options.tools !== undefined) {
349 client.updateOptions({ tools: options.tools })
350 }
351 }, [client, options.tools])
352
353 useEffect(() => {
354 if (options.live) {
355 client.subscribe()
356 } else {
357 client.unsubscribe()
358 }
359 }, [client, options.live])
360
361 // ONLY THE VIEW ON SCREEN HOLDS A STREAM. See the same effect in
362 // `@tanstack/ai-react`. A page can own many chats and a browser allows only ~6
363 // connections per origin, so one long-lived stream per chat starves everything
364 // else once a handful of views have been open. `attach` is idempotent and
365 // `detach` keeps the transcript and the resume pointer, so a remount picks the
366 // run straight back up from the durable log.
367 //
368 // Immediate, unlike the deferred disposal below, which a remount can skip —
369 // correct for disposal, useless for a connection.
370 useEffect(() => {
371 client.attach()
372 return () => {
373 client.detach()
374 }
375 }, [client])
376
377 // Cleanup on unmount: stop any in-flight requests
378 // Note: We only cleanup when client changes or component unmounts.
379 // DO NOT include isLoading in dependencies - that would cause the cleanup
380 // to run when isLoading changes, aborting continuation requests.
381 useEffect(() => {
382 if (cleanupDisposalRef.current?.client === client) {
383 clearTimeout(cleanupDisposalRef.current.timeout)
384 cleanupDisposalRef.current = null
385 }
386 if (cleanupInvalidationRef.current) {
387 clearTimeout(cleanupInvalidationRef.current)
388 cleanupInvalidationRef.current = null
389 }
390 client.mountDevtools()
391 // Delivery-durability resume is transparent: the resumable SSE connection
392 // adapter reattaches via the browser's native Last-Event-ID on reconnect.
393 // We only seed interrupt (state) resume from the client here.
394 syncResumeState(client)
395
396 return () => {
397 cleanupInvalidationRef.current = setTimeout(() => {
398 if (activeClientRef.current === client) {
399 activeClientRef.current = null
400 }
401 cleanupInvalidationRef.current = null
402 }, 0)
403 // Subscribe/unsubscribe on `options.live` is owned by the dedicated
404 // effect above. This cleanup only fires on unmount or client swap,
405 // so read `live` through the ref to avoid disposing the client every
406 // time `live` toggles.
407 if (optionsRef.current.live) {
408 client.unsubscribe()
409 } else {
410 client.stop()
411 }
412 const disposal = {
413 client,
414 timeout: setTimeout(() => {
415 client.dispose()
416 if (cleanupDisposalRef.current === disposal) {
417 cleanupDisposalRef.current = null
418 }
419 }, 0),
420 }
421 cleanupDisposalRef.current = disposal
422 }
423 }, [client, syncResumeState])
424
425 // All callback options are read through optionsRef at call time, so fresh
426 // closures from each render are picked up without recreating the client.
427 const sendMessage = useCallback(
428 async (
429 content: string | MultimodalContent,
430 sendOptions?: SendMessageOptions,
431 ) => {
432 try {
433 await client.sendMessage(content, undefined, sendOptions)
434 } finally {
435 syncResumeState(client)
436 }
437 },
438 [client, syncResumeState],
439 )
440
441 const cancelQueued = useCallback(
442 (id: string) => {
443 client.cancelQueued(id)
444 },
445 [client, syncResumeState],
446 )
447
448 const append = useCallback(
449 async (message: ModelMessage | UIMessage) => {
450 try {
451 await client.append(message)
452 } finally {
453 syncResumeState(client)
454 }
455 },
456 [client, syncResumeState],
457 )
458
459 const reload = useCallback(async () => {
460 try {
461 await client.reload()
462 } finally {
463 syncResumeState(client)
464 }
465 }, [client, syncResumeState])
466
467 const loadOlderMessages = useCallback(async () => {
468 await client.loadOlderMessages()
469 setHasOlderMessages(client.getHasOlderMessages())
470 }, [client])
471
472 const stop = useCallback(() => {
473 client.stop()
474 }, [client])
475
476 const clear = useCallback(() => {
477 client.clear()
478 syncResumeState(client)
479 }, [client, syncResumeState])
480
481 const setMessagesManually = useCallback(
482 (newMessages: Array<UIMessage<TTools>>) => {
483 client.setMessagesManually(newMessages)
484 },
485 [client],
486 )
487
488 const addToolResult = useCallback(
489 async (result: {
490 toolCallId: string
491 tool: string
492 output: unknown
493 state?: 'output-available' | 'output-error'
494 errorText?: string
495 }) => {
496 await client.addToolResult(result)
497 },
498 [client],
499 )
500
501 const addToolApprovalResponse = useCallback(
502 async (response: { id: string; approved: boolean }) => {
503 await client.addToolApprovalResponse(response)
504 syncResumeState(client)
505 },
506 [client, syncResumeState],
507 )
508
509 const resumeInterrupts = useCallback(
510 async (resumeItems: Array<RunAgentResumeItem>, state?: ChatResumeState) => {
511 const result = await client.resumeInterrupts(resumeItems, state)
512 syncResumeState(client)
513 return result
514 },
515 [client, syncResumeState],
516 )
517
518 const resolveInterrupts = useCallback(
519 (
520 resolution:
521 | boolean
522 | ((
523 interrupt: ResolvableChatInterrupt<TTools, TInterrupts>,
524 ) => undefined),
525 ) => {
526 if (typeof resolution === 'boolean') {
527 client.resolveInterrupts(resolution)
528 } else {
529 client.resolveInterrupts(resolution)
530 }
531 },
532 [client],
533 )
534
535 const cancelInterrupts = useCallback(() => {
536 client.cancelInterrupts()
537 }, [client])
538
539 const retryInterrupts = useCallback(() => {
540 client.retryInterrupts()
541 }, [client])
542
543 const resumeInterruptsUnsafe = useCallback(
544 (resumeItems: Array<RunAgentResumeItem>, state?: ChatResumeState) =>
545 client.resumeInterruptsUnsafe(resumeItems, state),
546 [client],
547 )
548
549 const renderedMessages = client.getMessages()
550
551 return {
552 messages: renderedMessages,
553 sendMessage,
554 append,
555 reload,
556 stop,
557 isLoading,
558 hasOlderMessages,
559 loadOlderMessages,
560 error,
561 status,
562 isSubscribed,
563 connectionStatus,
564 sessionGenerating,
565 setMessages: setMessagesManually,
566 clear,
567 addToolResult,
568 addToolApprovalResponse,
569 queue,
570 cancelQueued,
571 runId,
572 interrupts: interruptState.interrupts,
573 pendingInterrupts: interruptState.pendingInterrupts,
574 interruptErrors: interruptState.interruptErrors,
575 resuming: interruptState.resuming,
576 resolveInterrupts,
577 cancelInterrupts,
578 retryInterrupts,
579 resumeInterruptsUnsafe,
580 resumeInterrupts,
581 }
582}