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