Open History to see the last commit
1import { ChatClient } from '@tanstack/ai-client'
2import { createChatDevtoolsBridge } from '@tanstack/ai-client/devtools'
3import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
4import type {
5 AnyClientTool,
6 InferSchemaType,
7 InterruptDefinition,
8 ModelMessage,
9 RunAgentResumeItem,
10 SchemaInput,
11 StreamChunk,
12} from '@tanstack/ai/client'
13import type {
14 ChatClientState,
15 ResolvableChatInterrupt,
16 ChatInterruptState,
17 ChatResumeState,
18 ConnectionStatus,
19 InferredClientContext,
20 QueuedMessage,
21 SendMessageOptions,
22 StructuredOutputPart,
23} from '@tanstack/ai-client'
24
25import type {
26 DeepPartial,
27 MultimodalContent,
28 UIMessage,
29 UseChatOptions,
30 UseChatReturn,
31} from './types'
32
33const EMPTY_INTERRUPTS = Object.freeze([])
34const EMPTY_INTERRUPT_ERRORS = Object.freeze([])
35
36export function useChat<
37 const TTools extends ReadonlyArray<AnyClientTool> = any,
38 TSchema extends SchemaInput | undefined = undefined,
39 TContext = InferredClientContext<TTools>,
40 const TInterrupts extends ReadonlyArray<
41 InterruptDefinition<any, any, any, any>
42 > = readonly [],
43 const TSubagents extends ReadonlyArray<{ name: string }> | undefined =
44 undefined,
45>(
46 options: UseChatOptions<TTools, TSchema, TContext, TInterrupts, TSubagents>,
47): UseChatReturn<TTools, TSchema, TInterrupts, TSubagents> {
48 // The hook's identity is its `threadId`. Reload with the same `threadId`
49 // restores the same conversation. `hookId` is only a React recreation key
50 // when no `threadId` is given. It is never sent on the wire.
51 const hookId = useId()
52 const clientId = options.threadId ?? hookId
53
54 const [messages, setMessages] = useState<Array<UIMessage<TTools>>>(
55 options.initialMessages || [],
56 )
57 const [isLoading, setIsLoading] = useState(false)
58 const [hasOlderMessages, setHasOlderMessages] = useState(false)
59 const [error, setError] = useState<Error | undefined>(undefined)
60 const [status, setStatus] = useState<ChatClientState>('ready')
61 const [isSubscribed, setIsSubscribed] = useState(false)
62 const [connectionStatus, setConnectionStatus] =
63 useState<ConnectionStatus>('disconnected')
64 const [sessionGenerating, setSessionGenerating] = useState(false)
65 const [queue, setQueue] = useState<Array<QueuedMessage>>([])
66 const [runId, setRunId] = useState<string | null>(null)
67 const [interruptState, setInterruptState] = useState<
68 ChatInterruptState<TTools, TInterrupts>
69 >(() => ({
70 interrupts: EMPTY_INTERRUPTS,
71 pendingInterrupts: EMPTY_INTERRUPTS,
72 interruptErrors: EMPTY_INTERRUPT_ERRORS,
73 resuming: false,
74 }))
75
76 type Partial = DeepPartial<InferSchemaType<NonNullable<TSchema>>>
77 type Final = InferSchemaType<NonNullable<TSchema>>
78
79 // Track current messages in a ref to preserve them when client is recreated
80 const messagesRef = useRef<Array<UIMessage<TTools>>>(
81 options.initialMessages || [],
82 )
83 const isFirstMountRef = useRef(true)
84 const subscribedRef = useRef(false)
85 const activeClientRef = useRef<ChatClient | null>(null)
86 const cleanupInvalidationRef = useRef<ReturnType<typeof setTimeout> | null>(
87 null,
88 )
89 const cleanupDisposalRef = useRef<{
90 client: ChatClient
91 timeout: ReturnType<typeof setTimeout>
92 } | null>(null)
93
94 // Update ref synchronously during render so it's always current when useMemo runs.
95 messagesRef.current = messages
96
97 // Track current options in a ref to avoid recreating client when options change
98 const optionsRef =
99 useRef<UseChatOptions<TTools, TSchema, TContext, TInterrupts, TSubagents>>(
100 options,
101 )
102 optionsRef.current = options
103
104 const syncResumeState = useCallback((target: ChatClient | null) => {
105 if (!target) return
106 setRunId(target.getCurrentRunId())
107 setInterruptState(target.getInterruptState())
108 }, [])
109
110 // Create ChatClient instance with callbacks to sync state
111 const { client, initialization } = useMemo(() => {
112 const messagesToUse = options.initialMessages || []
113 isFirstMountRef.current = false
114
115 // Build options with conditional spreads for fields whose source
116 // type is `T | undefined` but the ChatClient target uses a strict
117 // optional (`field?: T`) — `exactOptionalPropertyTypes` rejects
118 // assigning `undefined` to those, so we omit the key when absent.
119 const initialOptions = optionsRef.current
120 const transport = initialOptions.connection
121 ? { connection: initialOptions.connection }
122 : { fetcher: initialOptions.fetcher }
123
124 const instanceHolder: {
125 current: ChatClient<TTools, TContext, TInterrupts> | undefined
126 } = { current: undefined }
127 const getActiveInstance = () => {
128 const currentInstance = instanceHolder.current
129 if (!currentInstance || activeClientRef.current !== currentInstance) {
130 return undefined
131 }
132 return currentInstance
133 }
134 // ChatClient may publish while its constructor is running or while async
135 // persistence resolves before commit. Preserve those exact notifications
136 // until this render commits; invoking them here would run state setters and
137 // user callbacks for a client React may abandon.
138 const initializationState = {
139 ready: false,
140 callbacks: [] as Array<() => void>,
141 }
142 const runOrQueueForActiveInstance = (callback: () => void) => {
143 if (!initializationState.ready) {
144 initializationState.callbacks.push(callback)
145 return
146 }
147 const currentInstance = instanceHolder.current
148 if (!currentInstance || activeClientRef.current !== currentInstance)
149 return
150 callback()
151 }
152 const instance = new ChatClient<TTools, TContext, TInterrupts>({
153 devtoolsBridgeFactory: createChatDevtoolsBridge,
154 ...transport,
155 initialMessages: messagesToUse,
156 ...(typeof initialOptions.threadId === 'string' &&
157 initialOptions.persistence === true
158 ? {
159 persistence: true,
160 threadId: initialOptions.threadId,
161 ...(initialOptions.history !== undefined && {
162 history: initialOptions.history,
163 }),
164 }
165 : typeof initialOptions.threadId === 'string' &&
166 initialOptions.persistence
167 ? {
168 persistence: initialOptions.persistence,
169 threadId: initialOptions.threadId,
170 }
171 : {
172 ...(initialOptions.threadId !== undefined && {
173 threadId: initialOptions.threadId,
174 }),
175 }),
176 ...(initialOptions.body !== undefined && { body: initialOptions.body }),
177 ...(initialOptions.forwardedProps !== undefined && {
178 forwardedProps: initialOptions.forwardedProps,
179 }),
180 ...(initialOptions.byok !== undefined && { byok: initialOptions.byok }),
181 byokProvider: () => optionsRef.current.byokProvider?.(),
182 ...(initialOptions.initialResumeSnapshot !== undefined && {
183 initialResumeSnapshot: initialOptions.initialResumeSnapshot,
184 }),
185 ...(initialOptions.context !== undefined && {
186 context: initialOptions.context,
187 }),
188 devtools: {
189 ...initialOptions.devtools,
190 framework: 'react',
191 hookName: 'useChat',
192 outputKind: initialOptions.outputSchema ? 'structured' : 'chat',
193 },
194 onResponse: (response) => {
195 // ChatClient awaits this return value. Queuing would drop the promise.
196 if (!getActiveInstance()) return
197 return optionsRef.current.onResponse?.(response)
198 },
199 onChunk: (chunk: StreamChunk) => {
200 runOrQueueForActiveInstance(() => {
201 optionsRef.current.onChunk?.(chunk)
202 })
203 },
204 onFinish: (message: UIMessage<TTools>) => {
205 runOrQueueForActiveInstance(() => {
206 optionsRef.current.onFinish?.(message)
207 })
208 },
209 onError: (error: Error) => {
210 runOrQueueForActiveInstance(() => {
211 optionsRef.current.onError?.(error)
212 })
213 },
214 ...(initialOptions.tools !== undefined && {
215 tools: initialOptions.tools,
216 }),
217 ...(initialOptions.interrupts !== undefined && {
218 interrupts: initialOptions.interrupts,
219 }),
220 onCustomEvent: (eventType, data, context) => {
221 runOrQueueForActiveInstance(() => {
222 optionsRef.current.onCustomEvent?.(eventType, data, context)
223 })
224 },
225 ...(options.streamProcessor !== undefined && {
226 streamProcessor: options.streamProcessor,
227 }),
228 onMessagesChange: (newMessages: Array<UIMessage<TTools>>) => {
229 runOrQueueForActiveInstance(() => {
230 setMessages(newMessages)
231 const currentInstance = getActiveInstance()
232 if (!currentInstance) return
233 setHasOlderMessages(currentInstance.getHasOlderMessages())
234 })
235 },
236 onLoadingChange: (newIsLoading: boolean) => {
237 runOrQueueForActiveInstance(() => {
238 const currentInstance = getActiveInstance()
239 if (!currentInstance) return
240 setIsLoading(newIsLoading)
241 syncResumeState(currentInstance)
242 })
243 },
244 onErrorChange: (newError: Error | undefined) => {
245 runOrQueueForActiveInstance(() => {
246 setError(newError)
247 })
248 },
249 onStatusChange: (status: ChatClientState) => {
250 runOrQueueForActiveInstance(() => {
251 setStatus(status)
252 })
253 },
254 onSubscriptionChange: (nextIsSubscribed: boolean) => {
255 runOrQueueForActiveInstance(() => {
256 setIsSubscribed(nextIsSubscribed)
257 })
258 },
259 onConnectionStatusChange: (nextStatus: ConnectionStatus) => {
260 runOrQueueForActiveInstance(() => {
261 setConnectionStatus(nextStatus)
262 })
263 },
264 onSessionGeneratingChange: (isGenerating: boolean) => {
265 runOrQueueForActiveInstance(() => {
266 setSessionGenerating(isGenerating)
267 })
268 },
269 ...(optionsRef.current.queue !== undefined && {
270 queue: optionsRef.current.queue,
271 }),
272 onQueueChange: (nextQueue: Array<QueuedMessage>) => {
273 runOrQueueForActiveInstance(() => {
274 setQueue(nextQueue)
275 })
276 },
277 onRunIdChange: (nextRunId) => {
278 runOrQueueForActiveInstance(() => {
279 setRunId(nextRunId)
280 })
281 },
282 onResumeStateChange: (_nextResumeState, nextPendingInterrupts) => {
283 runOrQueueForActiveInstance(() => {
284 setInterruptState((current) => ({
285 ...current,
286 interrupts: nextPendingInterrupts,
287 pendingInterrupts: nextPendingInterrupts,
288 }))
289 })
290 },
291 onInterruptStateChange: (nextInterruptState, context) => {
292 runOrQueueForActiveInstance(() => {
293 setInterruptState(nextInterruptState)
294 optionsRef.current.onInterruptStateChange?.(
295 nextInterruptState,
296 context,
297 )
298 })
299 },
300 })
301 instanceHolder.current = instance
302 return { client: instance, initialization: initializationState }
303 }, [clientId, syncResumeState])
304
305 useEffect(() => {
306 activeClientRef.current = client
307 try {
308 // Keep initialization closed while draining so callbacks published by a
309 // queued callback are appended and delivered in the same commit.
310 while (initialization.callbacks.length > 0) {
311 if (activeClientRef.current !== client) {
312 initialization.callbacks.length = 0
313 break
314 }
315 initialization.callbacks.shift()?.()
316 }
317 } finally {
318 // A throw from a queued user callback must not leave the queue closed.
319 initialization.ready = true
320 }
321 }, [client, initialization])
322
323 useEffect(() => {
324 const clientMessages = client.getMessages()
325 if (clientMessages !== messagesRef.current) {
326 setMessages(clientMessages)
327 }
328 setHasOlderMessages(client.getHasOlderMessages())
329 }, [client])
330
331 // Sync each wire-payload slot in its own effect so an unrelated option
332 // changing doesn't re-run the others. `updateOptions` declares strict-optional
333 // fields and rejects explicit `undefined` under EOPT, so guard the optional
334 // slots before passing them.
335 useEffect(() => {
336 client.updateOptions({ body: options.body })
337 }, [client, options.body])
338
339 useEffect(() => {
340 if (options.forwardedProps !== undefined) {
341 client.updateOptions({ forwardedProps: options.forwardedProps })
342 }
343 }, [client, options.forwardedProps])
344
345 useEffect(() => {
346 if (options.tools !== undefined) {
347 client.updateOptions({ tools: options.tools })
348 }
349 }, [client, options.tools])
350
351 useEffect(() => {
352 client.updateOptions({ context: options.context })
353 }, [client, options.context])
354
355 useEffect(() => {
356 if (options.queue !== undefined) {
357 client.updateOptions({ queue: options.queue })
358 }
359 }, [client, options.queue])
360
361 useEffect(() => {
362 if (options.live) {
363 client.subscribe()
364 subscribedRef.current = true
365 } else if (subscribedRef.current) {
366 // Only tear down a subscription we actually started. Calling
367 // `unsubscribe()` on initial mount (when `live` was never enabled) would
368 // abort an in-flight delivery resume — `resumeInFlightRun` is kicked off
369 // in the client constructor, and `unsubscribe()` cancels the shared
370 // in-flight stream — so a mid-stream reload would drop its rejoin before
371 // it delivers a single chunk. This is exactly why a reload froze instead
372 // of continuing.
373 client.unsubscribe()
374 subscribedRef.current = false
375 }
376 }, [client, options.live])
377
378 // ONLY THE VIEW ON SCREEN HOLDS A STREAM.
379 //
380 // A page can own many chats — 40 sandboxes, 40 conversations — and a browser
381 // allows only ~6 connections per origin. One long-lived stream per chat reaches
382 // that ceiling after a handful of views, and every request after it QUEUES:
383 // measured, an in-page fetch took over two minutes while the same request from
384 // outside the browser took 17ms. So the connection follows the view.
385 //
386 // Immediate, not deferred: the deferred teardown below can be skipped when the
387 // same client remounts, which is right for disposal but useless for a
388 // connection. `attach` is idempotent and `detach` keeps the transcript and the
389 // resume pointer, so a Strict Mode remount is just detach-then-attach and the
390 // run is picked straight back up from the durable log.
391 useEffect(() => {
392 client.attach()
393 return () => {
394 client.detach()
395 }
396 }, [client])
397
398 useEffect(() => {
399 if (cleanupDisposalRef.current?.client === client) {
400 clearTimeout(cleanupDisposalRef.current.timeout)
401 cleanupDisposalRef.current = null
402 }
403 if (cleanupInvalidationRef.current) {
404 clearTimeout(cleanupInvalidationRef.current)
405 cleanupInvalidationRef.current = null
406 }
407 client.mountDevtools()
408 // Delivery-durability resume is transparent: the resumable SSE connection
409 // adapter re-attaches via the browser's native Last-Event-ID on reconnect.
410 // We only seed interrupt (state) resume from the client here.
411 syncResumeState(client)
412
413 return () => {
414 cleanupInvalidationRef.current = setTimeout(() => {
415 if (activeClientRef.current === client) {
416 activeClientRef.current = null
417 }
418 cleanupInvalidationRef.current = null
419 }, 0)
420 // Soft cleanup only: do NOT stop/unsubscribe here. React Strict Mode
421 // remounts fire this cleanup then re-attach the same client one tick
422 // later; calling `stop()` would abort a constructor rejoin
423 // (`resumeInFlightRun`) and can wipe the durable resume pointer before
424 // the first chunk. Real teardown lives in the deferred dispose path
425 // below, which only runs when the client is not remounted.
426 // Subscribe/unsubscribe on `options.live` is still owned by the
427 // dedicated effect above for live toggles.
428 const disposal = {
429 client,
430 timeout: setTimeout(() => {
431 if (optionsRef.current.live) {
432 client.unsubscribe()
433 } else {
434 client.stop()
435 }
436 client.dispose()
437 if (cleanupDisposalRef.current === disposal) {
438 cleanupDisposalRef.current = null
439 }
440 }, 0),
441 }
442 cleanupDisposalRef.current = disposal
443 }
444 }, [client, syncResumeState])
445
446 const sendMessage = useCallback(
447 async (
448 content: string | MultimodalContent,
449 sendOptions?: SendMessageOptions,
450 ) => {
451 try {
452 await client.sendMessage(content, undefined, sendOptions)
453 } finally {
454 syncResumeState(client)
455 }
456 },
457 [client, syncResumeState],
458 )
459
460 const cancelQueued = useCallback(
461 (id: string) => {
462 client.cancelQueued(id)
463 },
464 [client, syncResumeState],
465 )
466
467 const append = useCallback(
468 async (message: ModelMessage | UIMessage) => {
469 try {
470 await client.append(message)
471 } finally {
472 syncResumeState(client)
473 }
474 },
475 [client, syncResumeState],
476 )
477
478 const reload = useCallback(async () => {
479 try {
480 await client.reload()
481 } finally {
482 syncResumeState(client)
483 }
484 }, [client, syncResumeState])
485
486 const loadOlderMessages = useCallback(async () => {
487 await client.loadOlderMessages()
488 setHasOlderMessages(client.getHasOlderMessages())
489 }, [client])
490
491 const stop = useCallback(() => {
492 client.stop()
493 }, [client])
494
495 const clear = useCallback(() => {
496 client.clear()
497 syncResumeState(client)
498 }, [client, syncResumeState])
499
500 const setMessagesManually = useCallback(
501 (newMessages: Array<UIMessage<TTools>>) => {
502 client.setMessagesManually(newMessages)
503 },
504 [client],
505 )
506
507 const addToolResult = useCallback(
508 async (result: {
509 toolCallId: string
510 tool: string
511 output: any
512 state?: 'output-available' | 'output-error'
513 errorText?: string
514 }) => {
515 await client.addToolResult(result)
516 },
517 [client],
518 )
519
520 const addToolApprovalResponse = useCallback(
521 async (response: { id: string; approved: boolean }) => {
522 await client.addToolApprovalResponse(response)
523 syncResumeState(client)
524 },
525 [client, syncResumeState],
526 )
527
528 const resumeInterrupts = useCallback(
529 async (resumeItems: Array<RunAgentResumeItem>, state?: ChatResumeState) => {
530 const result = await client.resumeInterrupts(
531 resumeItems,
532 state ?? undefined,
533 )
534 syncResumeState(client)
535 return result
536 },
537 [client, syncResumeState],
538 )
539
540 const resolveInterrupts = useCallback(
541 (
542 resolution:
543 | boolean
544 | ((
545 interrupt: ResolvableChatInterrupt<TTools, TInterrupts>,
546 ) => undefined),
547 ) => {
548 if (typeof resolution === 'boolean') {
549 client.resolveInterrupts(resolution)
550 } else {
551 client.resolveInterrupts(resolution)
552 }
553 },
554 [client],
555 )
556
557 const cancelInterrupts = useCallback(() => {
558 client.cancelInterrupts()
559 }, [client])
560
561 const retryInterrupts = useCallback(() => {
562 client.retryInterrupts()
563 }, [client])
564
565 const resumeInterruptsUnsafe = useCallback(
566 (resumeItems: Array<RunAgentResumeItem>, state?: ChatResumeState) =>
567 client.resumeInterruptsUnsafe(resumeItems, state),
568 [client],
569 )
570
571 // The "active" structured-output part is the one on the assistant message
572 // that follows the latest user message. No such message exists between
573 // sendMessage() and the first chunk, so partial/final naturally read as
574 // cleared. Historical parts on earlier assistant messages remain available
575 // via `messages` directly.
576 //
577 // When there is NO user message yet (e.g. `initialMessages` contains only
578 // a stale assistant turn or a system prompt) we deliberately return null
579 // rather than scanning historical assistants — otherwise a `final` from a
580 // previous session would leak into the hook value on first render.
581 const renderedMessages = client.getMessages()
582
583 const activeStructuredPart = useMemo<StructuredOutputPart | null>(() => {
584 let lastUserIndex = -1
585 for (let i = renderedMessages.length - 1; i >= 0; i--) {
586 if (renderedMessages[i]?.role === 'user') {
587 lastUserIndex = i
588 break
589 }
590 }
591 if (lastUserIndex === -1) return null
592 for (let i = renderedMessages.length - 1; i > lastUserIndex; i--) {
593 const m = renderedMessages[i]
594 if (m?.role !== 'assistant') continue
595 const part = m.parts.find(
596 (p): p is StructuredOutputPart => p.type === 'structured-output',
597 )
598 if (part) return part
599 }
600 return null
601 }, [renderedMessages])
602
603 const partial = useMemo<Partial>(() => {
604 if (!activeStructuredPart) return {} as Partial
605 const v = activeStructuredPart.partial ?? activeStructuredPart.data
606 return (v ?? {}) as Partial
607 }, [activeStructuredPart])
608
609 const final = useMemo<Final | null>(() => {
610 if (!activeStructuredPart || activeStructuredPart.status !== 'complete') {
611 return null
612 }
613 return activeStructuredPart.data as Final
614 }, [activeStructuredPart])
615
616 const subagents = useMemo(() => client.getSubagents(), [renderedMessages])
617
618 // The runtime shape unconditionally exposes partial/final; the public
619 // return type hides them when no outputSchema was supplied. TS can't
620 // structurally narrow across that conditional, so the `as` is the seam.
621 // oxlint-disable-next-line eslint-js/no-restricted-syntax -- hook return shape diverges from generic UseChatReturn<TTools, TSchema> due to conditional type on TSchema; TS can't structurally narrow
622 return {
623 messages: renderedMessages,
624 subagents,
625 sendMessage,
626 append,
627 reload,
628 stop,
629 isLoading,
630 hasOlderMessages,
631 loadOlderMessages,
632 error,
633 status,
634 isSubscribed,
635 connectionStatus,
636 sessionGenerating,
637 setMessages: setMessagesManually,
638 clear,
639 addToolResult,
640 addToolApprovalResponse,
641 queue,
642 cancelQueued,
643 runId,
644 interrupts: interruptState.interrupts,
645 pendingInterrupts: interruptState.pendingInterrupts,
646 interruptErrors: interruptState.interruptErrors,
647 resuming: interruptState.resuming,
648 resolveInterrupts,
649 cancelInterrupts,
650 retryInterrupts,
651 resumeInterruptsUnsafe,
652 resumeInterrupts,
653 partial,
654 final,
655 } as unknown as UseChatReturn<TTools, TSchema, TInterrupts, TSubagents>
656}