Open History to see the last commit
1import { ChatClient } from '@tanstack/ai-client'
2import { createChatDevtoolsBridge } from '@tanstack/ai-client/devtools'
3import { useCallback, useEffect, 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 ChatClientPersistence,
15 ResolvableChatInterrupt,
16 ChatResumeState,
17 InferredClientContext,
18 SendMessageOptions,
19 StructuredOutputPart,
20} from '@tanstack/ai-client'
21
22import type {
23 DeepPartial,
24 MultimodalContent,
25 UIMessage,
26 UseChatOptions,
27 UseChatReturn,
28} from './types'
29
30export function useChat<
31 const TTools extends ReadonlyArray<AnyClientTool> = any,
32 TSchema extends SchemaInput | undefined = undefined,
33 TContext = InferredClientContext<TTools>,
34 const TInterrupts extends ReadonlyArray<
35 InterruptDefinition<any, any, any, any>
36 > = readonly [],
37 const TSubagents extends ReadonlyArray<{ name: string }> | undefined =
38 undefined,
39>(
40 options: UseChatOptions<TTools, TSchema, TContext, TInterrupts, TSubagents>,
41): UseChatReturn<TTools, TSchema, TInterrupts, TSubagents> {
42 type Partial = DeepPartial<InferSchemaType<NonNullable<TSchema>>>
43 type Final = InferSchemaType<NonNullable<TSchema>>
44
45 const subscribedRef = useRef(false)
46 const activeClientRef = useRef<ChatClient | null>(null)
47 const cleanupInvalidationRef = useRef<ReturnType<typeof setTimeout> | null>(
48 null,
49 )
50 const cleanupDisposalRef = useRef<{
51 client: ChatClient
52 timeout: ReturnType<typeof setTimeout>
53 } | null>(null)
54
55 // Track current options in a ref to avoid recreating client when options change
56 const optionsRef =
57 useRef<UseChatOptions<TTools, TSchema, TContext, TInterrupts, TSubagents>>(
58 options,
59 )
60 optionsRef.current = options
61
62 // Create ChatClient once per threadId. Reload with the same threadId
63 // restores the same conversation. User callbacks read latest options.
64 const { client, initialization, serverSnapshot, startPersistenceHydration } =
65 useMemo(() => {
66 const messagesToUse = options.initialMessages || []
67
68 const initialOptions = optionsRef.current
69 const { persistence, release: releasePersistenceHydration } =
70 gatePersistence(initialOptions.persistence)
71 const transport = initialOptions.connection
72 ? { connection: initialOptions.connection }
73 : { fetcher: initialOptions.fetcher }
74
75 const instanceHolder: {
76 current: ChatClient<TTools, TContext, TInterrupts> | undefined
77 } = { current: undefined }
78 const getActiveInstance = () => {
79 const currentInstance = instanceHolder.current
80 if (!currentInstance || activeClientRef.current !== currentInstance) {
81 return undefined
82 }
83 return currentInstance
84 }
85 // Queue user callbacks until this instance is the committed client.
86 // Invoking them here would run onChunk/onFinish/onError for a client
87 // React may abandon. Browser persistence is gated until attach so the
88 // first paint stays on initialMessages / initialResumeSnapshot.
89 const initializationState = {
90 ready: false,
91 callbacks: [] as Array<() => void>,
92 }
93 const runOrQueueForActiveInstance = (callback: () => void) => {
94 if (!initializationState.ready) {
95 initializationState.callbacks.push(callback)
96 return
97 }
98 const currentInstance = instanceHolder.current
99 if (!currentInstance || activeClientRef.current !== currentInstance)
100 return
101 callback()
102 }
103 const instance = new ChatClient<TTools, TContext, TInterrupts>({
104 devtoolsBridgeFactory: createChatDevtoolsBridge,
105 ...transport,
106 initialMessages: messagesToUse,
107 threadId: initialOptions.threadId,
108 ...(persistence === true
109 ? {
110 persistence: true,
111 ...(initialOptions.history !== undefined && {
112 history: initialOptions.history,
113 }),
114 }
115 : { persistence }),
116 ...(initialOptions.forwardedProps !== undefined && {
117 forwardedProps: initialOptions.forwardedProps,
118 }),
119 ...(initialOptions.byok !== undefined && { byok: initialOptions.byok }),
120 byokProvider: () => optionsRef.current.byokProvider?.(),
121 ...(initialOptions.initialResumeSnapshot !== undefined && {
122 initialResumeSnapshot: initialOptions.initialResumeSnapshot,
123 }),
124 ...(initialOptions.context !== undefined && {
125 context: initialOptions.context,
126 }),
127 devtools: {
128 ...initialOptions.devtools,
129 framework: 'react',
130 hookName: 'useChat',
131 outputKind: initialOptions.outputSchema ? 'structured' : 'chat',
132 },
133 onResponse: (response) => {
134 // ChatClient awaits this return value. Queuing would drop the promise.
135 if (!getActiveInstance()) return
136 return optionsRef.current.onResponse?.(response)
137 },
138 onChunk: (chunk: StreamChunk) => {
139 runOrQueueForActiveInstance(() => {
140 optionsRef.current.onChunk?.(chunk)
141 })
142 },
143 onFinish: (message: UIMessage<TTools>) => {
144 runOrQueueForActiveInstance(() => {
145 optionsRef.current.onFinish?.(message)
146 })
147 },
148 onError: (error: Error) => {
149 runOrQueueForActiveInstance(() => {
150 optionsRef.current.onError?.(error)
151 })
152 },
153 ...(initialOptions.tools !== undefined && {
154 tools: initialOptions.tools,
155 }),
156 ...(initialOptions.interrupts !== undefined && {
157 interrupts: initialOptions.interrupts,
158 }),
159 onCustomEvent: (eventType, data, context) => {
160 runOrQueueForActiveInstance(() => {
161 optionsRef.current.onCustomEvent?.(eventType, data, context)
162 })
163 },
164 ...(options.streamProcessor !== undefined && {
165 streamProcessor: options.streamProcessor,
166 }),
167 ...(optionsRef.current.queue !== undefined && {
168 queue: optionsRef.current.queue,
169 }),
170 onInterruptStateChange: (nextInterruptState, context) => {
171 runOrQueueForActiveInstance(() => {
172 optionsRef.current.onInterruptStateChange?.(
173 nextInterruptState,
174 context,
175 )
176 })
177 },
178 })
179 instanceHolder.current = instance
180 const capturedServerSnapshot = instance.getSnapshot()
181 return {
182 client: instance,
183 initialization: initializationState,
184 serverSnapshot: capturedServerSnapshot,
185 startPersistenceHydration: releasePersistenceHydration,
186 }
187 }, [options.threadId])
188
189 useEffect(() => {
190 activeClientRef.current = client
191 try {
192 // Keep initialization closed while draining so callbacks published by a
193 // queued callback are appended and delivered in the same commit.
194 while (initialization.callbacks.length > 0) {
195 if (activeClientRef.current !== client) {
196 initialization.callbacks.length = 0
197 break
198 }
199 initialization.callbacks.shift()?.()
200 }
201 } finally {
202 // A throw from a queued user callback must not leave the queue closed.
203 initialization.ready = true
204 }
205 }, [client, initialization])
206
207 // Plain state, not useSyncExternalStore: that renders synchronously on every
208 // change, so a buffered stream rendered once per chunk. setState batches the
209 // changes into one render per task.
210 const [held, setHeld] = useState(() => ({ client, snapshot: serverSnapshot }))
211 useEffect(() => {
212 const sync = () => {
213 const next = client.getSnapshot()
214 setHeld((prev) =>
215 prev.client === client && prev.snapshot === next
216 ? prev
217 : { client, snapshot: next },
218 )
219 }
220 sync()
221 return client.subscribeSnapshot(sync)
222 }, [client])
223 const snapshot = held.client === client ? held.snapshot : serverSnapshot
224
225 // Sync each wire-payload slot in its own effect so an unrelated option
226 // changing doesn't re-run the others. `updateOptions` declares strict-optional
227 // fields and rejects explicit `undefined` under EOPT, so guard the optional
228 // slots before passing them.
229 useEffect(() => {
230 if (options.forwardedProps !== undefined) {
231 client.updateOptions({ forwardedProps: options.forwardedProps })
232 }
233 }, [client, options.forwardedProps])
234
235 useEffect(() => {
236 if (options.tools !== undefined) {
237 client.updateOptions({ tools: options.tools })
238 }
239 }, [client, options.tools])
240
241 useEffect(() => {
242 client.updateOptions({ context: options.context })
243 }, [client, options.context])
244
245 useEffect(() => {
246 if (options.queue !== undefined) {
247 client.updateOptions({ queue: options.queue })
248 }
249 }, [client, options.queue])
250
251 useEffect(() => {
252 if (options.live) {
253 client.subscribe()
254 subscribedRef.current = true
255 } else if (subscribedRef.current) {
256 // Only tear down a subscription we actually started. Calling
257 // `unsubscribe()` on initial mount (when `live` was never enabled) would
258 // abort an in-flight delivery resume — `resumeInFlightRun` is kicked off
259 // in the client constructor, and `unsubscribe()` cancels the shared
260 // in-flight stream — so a mid-stream reload would drop its rejoin before
261 // it delivers a single chunk. This is exactly why a reload froze instead
262 // of continuing.
263 client.unsubscribe()
264 subscribedRef.current = false
265 }
266 }, [client, options.live])
267
268 // ONLY THE VIEW ON SCREEN HOLDS A STREAM.
269 //
270 // A page can own many chats — 40 sandboxes, 40 conversations — and a browser
271 // allows only ~6 connections per origin. One long-lived stream per chat reaches
272 // that ceiling after a handful of views, and every request after it QUEUES:
273 // measured, an in-page fetch took over two minutes while the same request from
274 // outside the browser took 17ms. So the connection follows the view.
275 //
276 // Immediate, not deferred: the deferred teardown below can be skipped when the
277 // same client remounts, which is right for disposal but useless for a
278 // connection. `attach` is idempotent and `detach` keeps the transcript and the
279 // resume pointer, so a Strict Mode remount is just detach-then-attach and the
280 // run is picked straight back up from the durable log.
281 useEffect(() => {
282 client.attach()
283 startPersistenceHydration()
284 return () => {
285 client.detach()
286 }
287 }, [client, startPersistenceHydration])
288
289 useEffect(() => {
290 if (cleanupDisposalRef.current?.client === client) {
291 clearTimeout(cleanupDisposalRef.current.timeout)
292 cleanupDisposalRef.current = null
293 }
294 if (cleanupInvalidationRef.current) {
295 clearTimeout(cleanupInvalidationRef.current)
296 cleanupInvalidationRef.current = null
297 }
298 client.mountDevtools()
299
300 return () => {
301 cleanupInvalidationRef.current = setTimeout(() => {
302 if (activeClientRef.current === client) {
303 activeClientRef.current = null
304 }
305 cleanupInvalidationRef.current = null
306 }, 0)
307 // Soft cleanup only: do NOT stop/unsubscribe here. React Strict Mode
308 // remounts fire this cleanup then re-attach the same client one tick
309 // later; calling `stop()` would abort a constructor rejoin
310 // (`resumeInFlightRun`) and can wipe the durable resume pointer before
311 // the first chunk. Real teardown lives in the deferred dispose path
312 // below, which only runs when the client is not remounted.
313 // Subscribe/unsubscribe on `options.live` is still owned by the
314 // dedicated effect above for live toggles.
315 const disposal = {
316 client,
317 timeout: setTimeout(() => {
318 if (optionsRef.current.live) {
319 client.unsubscribe()
320 } else {
321 client.stop()
322 }
323 client.dispose()
324 if (cleanupDisposalRef.current === disposal) {
325 cleanupDisposalRef.current = null
326 }
327 }, 0),
328 }
329 cleanupDisposalRef.current = disposal
330 }
331 }, [client])
332
333 const sendMessage = useCallback(
334 async (
335 content: string | MultimodalContent,
336 sendOptions?: SendMessageOptions,
337 ) => {
338 await client.sendMessage(content, undefined, sendOptions)
339 },
340 [client],
341 )
342
343 const cancelQueued = useCallback(
344 (id: string) => {
345 client.cancelQueued(id)
346 },
347 [client],
348 )
349
350 const append = useCallback(
351 async (message: ModelMessage | UIMessage) => {
352 await client.append(message)
353 },
354 [client],
355 )
356
357 const reload = useCallback(async () => {
358 await client.reload()
359 }, [client])
360
361 const loadOlderMessages = useCallback(async () => {
362 await client.loadOlderMessages()
363 }, [client])
364
365 const stop = useCallback(() => {
366 client.stop()
367 }, [client])
368
369 const clear = useCallback(() => {
370 client.clear()
371 }, [client])
372
373 const setMessagesManually = useCallback(
374 (newMessages: ReadonlyArray<UIMessage<TTools>>) => {
375 client.setMessagesManually(newMessages)
376 },
377 [client],
378 )
379
380 const addToolResult = useCallback(
381 async (result: {
382 toolCallId: string
383 tool: string
384 output: any
385 state?: 'output-available' | 'output-error'
386 errorText?: string
387 }) => {
388 await client.addToolResult(result)
389 },
390 [client],
391 )
392
393 const resolveInterrupts = useCallback(
394 (
395 resolution:
396 | boolean
397 | ((
398 interrupt: ResolvableChatInterrupt<TTools, TInterrupts>,
399 ) => undefined),
400 ) => {
401 if (typeof resolution === 'boolean') {
402 client.resolveInterrupts(resolution)
403 } else {
404 client.resolveInterrupts(resolution)
405 }
406 },
407 [client],
408 )
409
410 const cancelInterrupts = useCallback(() => {
411 client.cancelInterrupts()
412 }, [client])
413
414 const retryInterrupts = useCallback(() => {
415 client.retryInterrupts()
416 }, [client])
417
418 const resumeInterruptsUnsafe = useCallback(
419 (resumeItems: Array<RunAgentResumeItem>, state?: ChatResumeState) =>
420 client.resumeInterruptsUnsafe(resumeItems, state),
421 [client],
422 )
423
424 // The "active" structured-output part is the one on the assistant message
425 // that follows the latest user message. No such message exists between
426 // sendMessage() and the first chunk, so partial/final naturally read as
427 // cleared. Historical parts on earlier assistant messages remain available
428 // via `messages` directly.
429 //
430 // When there is NO user message yet (e.g. `initialMessages` contains only
431 // a stale assistant turn or a system prompt) we deliberately return null
432 // rather than scanning historical assistants — otherwise a `final` from a
433 // previous session would leak into the hook value on first render.
434 const renderedMessages = snapshot.messages
435
436 const activeStructuredPart = useMemo<StructuredOutputPart | null>(() => {
437 let lastUserIndex = -1
438 for (let i = renderedMessages.length - 1; i >= 0; i--) {
439 if (renderedMessages[i]?.role === 'user') {
440 lastUserIndex = i
441 break
442 }
443 }
444 if (lastUserIndex === -1) return null
445 for (let i = renderedMessages.length - 1; i > lastUserIndex; i--) {
446 const m = renderedMessages[i]
447 if (m?.role !== 'assistant') continue
448 const part = m.parts.find(
449 (p): p is StructuredOutputPart => p.type === 'structured-output',
450 )
451 if (part) return part
452 }
453 return null
454 }, [renderedMessages])
455
456 const partial = useMemo<Partial>(() => {
457 if (!activeStructuredPart) return {} as Partial
458 const v = activeStructuredPart.partial ?? activeStructuredPart.data
459 return (v ?? {}) as Partial
460 }, [activeStructuredPart])
461
462 const final = useMemo<Final | null>(() => {
463 if (!activeStructuredPart || activeStructuredPart.status !== 'complete') {
464 return null
465 }
466 return activeStructuredPart.data as Final
467 }, [activeStructuredPart])
468
469 const subagents = useMemo(() => client.getSubagents(), [renderedMessages])
470
471 // The runtime shape unconditionally exposes partial/final; the public
472 // return type hides them when no outputSchema was supplied. TS can't
473 // structurally narrow across that conditional, so the `as` is the seam.
474 // 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
475 return {
476 messages: renderedMessages,
477 subagents,
478 sendMessage,
479 append,
480 reload,
481 stop,
482 isLoading: snapshot.isLoading,
483 hasOlderMessages: snapshot.hasOlderMessages,
484 loadOlderMessages,
485 error: snapshot.error,
486 status: snapshot.status,
487 isSubscribed: snapshot.isSubscribed,
488 connectionStatus: snapshot.connectionStatus,
489 sessionGenerating: snapshot.sessionGenerating,
490 isHydrating: snapshot.isHydrating,
491 setMessages: setMessagesManually,
492 clear,
493 addToolResult,
494 queue: snapshot.queue,
495 cancelQueued,
496 runId: snapshot.runId,
497 interrupts: snapshot.interruptState.interrupts,
498 interruptErrors: snapshot.interruptState.interruptErrors,
499 resuming: snapshot.interruptState.resuming,
500 resolveInterrupts,
501 cancelInterrupts,
502 retryInterrupts,
503 resumeInterruptsUnsafe,
504 partial,
505 final,
506 } as unknown as UseChatReturn<TTools, TSchema, TInterrupts, TSubagents>
507}
508
509/**
510 * Hold a browser store's first read until `release()`. React's first commit
511 * then matches the server snapshot (`initialMessages`), and the stored
512 * transcript applies after the hook attaches.
513 */
514function gatePersistence<TTools extends ReadonlyArray<AnyClientTool>>(
515 source: boolean | ChatClientPersistence<TTools> | undefined,
516): {
517 persistence: boolean | ChatClientPersistence<TTools> | undefined
518 release: () => void
519} {
520 if (!source || source === true) {
521 return { persistence: source, release: () => {} }
522 }
523 const store = source
524 let released = false
525 let startRead: (() => void) | undefined
526 let read: ReturnType<ChatClientPersistence<TTools>['getItem']> | undefined
527 return {
528 persistence: {
529 getItem(id) {
530 read ??= new Promise((resolve, reject) => {
531 startRead = () => {
532 startRead = undefined
533 try {
534 resolve(store.getItem(id))
535 } catch (error) {
536 reject(error)
537 }
538 }
539 })
540 if (released) startRead?.()
541 return read
542 },
543 setItem: (id, state) => store.setItem(id, state),
544 removeItem: (id) => store.removeItem(id),
545 },
546 release: () => {
547 released = true
548 startRead?.()
549 },
550 }
551}