Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

use-chat.tsrx

608 lines19.7 KB

1import { ChatClient } from '@tanstack/ai-client'
2import { createChatDevtoolsBridge } from '@tanstack/ai-client/devtools'
3import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'octane'
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>(
44 options: UseChatOptions<TTools, TSchema, TContext, TInterrupts>,
45): UseChatReturn<TTools, TSchema, TInterrupts> {
46 // The hook's identity is its `threadId`. Reload with the same `threadId`
47 // restores the same conversation. `hookId` is only a recreation key when no
48 // `threadId` is given. It is never sent on the wire.
49 const hookId = useId()
50 const clientId = options.threadId ?? hookId
51​
52 const [messages, setMessages] = useState<Array<UIMessage<TTools>>>(
53 options.initialMessages || [],
54 )
55 const [isLoading, setIsLoading] = useState(false)
56 const [hasOlderMessages, setHasOlderMessages] = useState(false)
57 const [error, setError] = useState<Error | undefined>(undefined)
58 const [status, setStatus] = useState<ChatClientState>('ready')
59 const [isSubscribed, setIsSubscribed] = useState(false)
60 const [connectionStatus, setConnectionStatus] =
61 useState<ConnectionStatus>('disconnected')
62 const [sessionGenerating, setSessionGenerating] = useState(false)
63 const [queue, setQueue] = useState<Array<QueuedMessage>>([])
64 const [runId, setRunId] = useState<string | null>(null)
65 const [interruptState, setInterruptState] = useState<
66 ChatInterruptState<TTools, TInterrupts>
67 >(() => ({
68 interrupts: EMPTY_INTERRUPTS,
69 pendingInterrupts: EMPTY_INTERRUPTS,
70 interruptErrors: EMPTY_INTERRUPT_ERRORS,
71 resuming: false,
72 }))
73​
74 type Partial = DeepPartial<InferSchemaType<NonNullable<TSchema>>>
75 type Final = InferSchemaType<NonNullable<TSchema>>
76​
77 // Track the rendered snapshot so a replacement client only synchronizes
78 // state when its messages actually differ.
79 const messagesRef = useRef<Array<UIMessage<TTools>>>(
80 options.initialMessages || [],
81 )
82 const subscribedRef = useRef(false)
83 const activeClientRef = useRef<ChatClient | null>(null)
84 const seenClientRef = useRef<ChatClient | null>(null)
85​
86 // Update ref synchronously during render so it's always current when useMemo runs.
87 messagesRef.current = messages
88​
89 // Track current options in a ref to avoid recreating client when options change
90 const optionsRef =
91 useRef<UseChatOptions<TTools, TSchema, TContext, TInterrupts>>(options)
92 optionsRef.current = options
93​
94 const syncResumeState = useCallback((target: ChatClient | null) => {
95 if (!target) return
96 setRunId(target.getCurrentRunId())
97 setInterruptState(target.getInterruptState())
98 }, [])
99​
100 // Create ChatClient instance with callbacks to sync state
101 const { client, initialization } = useMemo(() => {
102 const messagesToUse = options.initialMessages || []
103​
104 // Build options with conditional spreads for fields whose source
105 // type is `T | undefined` but the ChatClient target uses a strict
106 // optional (`field?: T`) — `exactOptionalPropertyTypes` rejects
107 // assigning `undefined` to those, so we omit the key when absent.
108 const initialOptions = optionsRef.current
109 const transport = initialOptions.connection
110 ? { connection: initialOptions.connection }
111 : { fetcher: initialOptions.fetcher }
112​
113 const instanceHolder: {
114 current: ChatClient<TTools, TContext, TInterrupts> | undefined
115 } = { current: undefined }
116 const getActiveInstance = () => {
117 const currentInstance = instanceHolder.current
118 if (!currentInstance || activeClientRef.current !== currentInstance) {
119 return undefined
120 }
121 return currentInstance
122 }
123 // ChatClient may publish while its constructor is running or while async
124 // persistence resolves before commit. Preserve those notifications until
125 // this render commits.
126 const initializationState = {
127 ready: false,
128 callbacks: [] as Array<() => void>,
129 }
130 const runOrQueueForActiveInstance = (callback: () => void) => {
131 if (!initializationState.ready) {
132 initializationState.callbacks.push(callback)
133 return
134 }
135 const currentInstance = instanceHolder.current
136 if (!currentInstance || activeClientRef.current !== currentInstance)
137 return
138 callback()
139 }
140 const instance = new ChatClient<TTools, TContext, TInterrupts>({
141 devtoolsBridgeFactory: createChatDevtoolsBridge,
142 ...transport,
143 initialMessages: messagesToUse,
144 ...(typeof initialOptions.threadId === 'string' &&
145 initialOptions.persistence === true
146 ? {
147 persistence: true,
148 threadId: initialOptions.threadId,
149 ...(initialOptions.history !== undefined && {
150 history: initialOptions.history,
151 }),
152 }
153 : typeof initialOptions.threadId === 'string' &&
154 initialOptions.persistence
155 ? {
156 persistence: initialOptions.persistence,
157 threadId: initialOptions.threadId,
158 }
159 : {
160 ...(initialOptions.threadId !== undefined && {
161 threadId: initialOptions.threadId,
162 }),
163 }),
164 ...(initialOptions.body !== undefined && { body: initialOptions.body }),
165 ...(initialOptions.forwardedProps !== undefined && {
166 forwardedProps: initialOptions.forwardedProps,
167 }),
168 ...(initialOptions.initialResumeSnapshot !== undefined && {
169 initialResumeSnapshot: initialOptions.initialResumeSnapshot,
170 }),
171 ...(initialOptions.context !== undefined && {
172 context: initialOptions.context,
173 }),
174 devtools: {
175 ...initialOptions.devtools,
176 // OCTANE DIVERGENCE: identify this binding as Octane (not 'react') in TanStack AI Devtools.
177 // Spread AFTER caller metadata so callers cannot override identification.
178 framework: 'octane',
179 hookName: 'useChat',
180 outputKind: initialOptions.outputSchema ? 'structured' : 'chat',
181 },
182 onResponse: (response) => {
183 // ChatClient awaits this return value. Dropping it would skip the promise.
184 if (!getActiveInstance()) return
185 return optionsRef.current.onResponse?.(response)
186 },
187 onChunk: (chunk: StreamChunk) => {
188 runOrQueueForActiveInstance(() => {
189 optionsRef.current.onChunk?.(chunk)
190 })
191 },
192 onFinish: (message: UIMessage<TTools>) => {
193 runOrQueueForActiveInstance(() => {
194 optionsRef.current.onFinish?.(message)
195 })
196 },
197 onError: (error: Error) => {
198 runOrQueueForActiveInstance(() => {
199 optionsRef.current.onError?.(error)
200 })
201 },
202 ...(initialOptions.tools !== undefined && {
203 tools: initialOptions.tools,
204 }),
205 ...(initialOptions.interrupts !== undefined && {
206 interrupts: initialOptions.interrupts,
207 }),
208 onCustomEvent: (eventType, data, context) => {
209 runOrQueueForActiveInstance(() => {
210 optionsRef.current.onCustomEvent?.(eventType, data, context)
211 })
212 },
213 ...(options.streamProcessor !== undefined && {
214 streamProcessor: options.streamProcessor,
215 }),
216 onMessagesChange: (newMessages: Array<UIMessage<TTools>>) => {
217 runOrQueueForActiveInstance(() => {
218 setMessages(newMessages)
219 const currentInstance = getActiveInstance()
220 if (!currentInstance) return
221 setHasOlderMessages(currentInstance.getHasOlderMessages())
222 })
223 },
224 onLoadingChange: (newIsLoading: boolean) => {
225 runOrQueueForActiveInstance(() => {
226 const currentInstance = getActiveInstance()
227 if (!currentInstance) return
228 setIsLoading(newIsLoading)
229 syncResumeState(currentInstance)
230 })
231 },
232 onErrorChange: (newError: Error | undefined) => {
233 runOrQueueForActiveInstance(() => {
234 setError(newError)
235 })
236 },
237 onStatusChange: (status: ChatClientState) => {
238 runOrQueueForActiveInstance(() => {
239 setStatus(status)
240 })
241 },
242 onSubscriptionChange: (nextIsSubscribed: boolean) => {
243 runOrQueueForActiveInstance(() => {
244 setIsSubscribed(nextIsSubscribed)
245 })
246 },
247 onConnectionStatusChange: (nextStatus: ConnectionStatus) => {
248 runOrQueueForActiveInstance(() => {
249 setConnectionStatus(nextStatus)
250 })
251 },
252 onSessionGeneratingChange: (isGenerating: boolean) => {
253 runOrQueueForActiveInstance(() => {
254 setSessionGenerating(isGenerating)
255 })
256 },
257 ...(optionsRef.current.queue !== undefined && {
258 queue: optionsRef.current.queue,
259 }),
260 onQueueChange: (nextQueue: Array<QueuedMessage>) => {
261 runOrQueueForActiveInstance(() => {
262 setQueue(nextQueue)
263 })
264 },
265 onRunIdChange: (nextRunId) => {
266 runOrQueueForActiveInstance(() => {
267 setRunId(nextRunId)
268 })
269 },
270 onResumeStateChange: (_nextResumeState, nextPendingInterrupts) => {
271 runOrQueueForActiveInstance(() => {
272 setInterruptState((current) => ({
273 ...current,
274 interrupts: nextPendingInterrupts,
275 pendingInterrupts: nextPendingInterrupts,
276 }))
277 })
278 },
279 onInterruptStateChange: (nextInterruptState, context) => {
280 runOrQueueForActiveInstance(() => {
281 setInterruptState(nextInterruptState)
282 optionsRef.current.onInterruptStateChange?.(
283 nextInterruptState,
284 context,
285 )
286 })
287 },
288 })
289 instanceHolder.current = instance
290 return { client: instance, initialization: initializationState }
291 }, [clientId, syncResumeState])
292​
293 useEffect(() => {
294 activeClientRef.current = client
295 try {
296 // Keep initialization closed while draining so callbacks published by a
297 // queued callback are appended and delivered in the same commit.
298 while (initialization.callbacks.length > 0) {
299 if (activeClientRef.current !== client) {
300 initialization.callbacks.length = 0
301 break
302 }
303 initialization.callbacks.shift()?.()
304 }
305 } finally {
306 // A throw from a queued user callback must not leave the queue closed.
307 initialization.ready = true
308 }
309 }, [client, initialization])
310​
311 useEffect(() => {
312 const clientMessages = client.getMessages()
313 if (clientMessages !== messagesRef.current) {
314 setMessages(clientMessages)
315 }
316 setHasOlderMessages(client.getHasOlderMessages())
317 }, [client])
318​
319 // OCTANE DIVERGENCE: upstream captures the initial transport. ChatClient
320 // owns transport swaps, including aborting an active request and
321 // resubscribing when needed, so keep its conversation state stable while
322 // applying the latest transport. Skip the first run for each client — it
323 // already has this transport from the constructor, and a no-op swap can
324 // abort constructor rejoin / interrupt resume.
325 useEffect(() => {
326 if (seenClientRef.current !== client) {
327 seenClientRef.current = client
328 return
329 }
330 const transport = options.connection
331 ? { connection: options.connection }
332 : { fetcher: options.fetcher }
333 client.updateOptions(transport)
334 }, [client, options.connection, options.fetcher])
335​
336 // Sync each wire-payload slot in its own effect so an unrelated option
337 // changing doesn't re-run the others. `updateOptions` declares strict-optional
338 // fields and rejects explicit `undefined` under EOPT, so guard the optional
339 // slots before passing them.
340 useEffect(() => {
341 client.updateOptions({ body: options.body })
342 }, [client, options.body])
343​
344 useEffect(() => {
345 if (options.forwardedProps !== undefined) {
346 client.updateOptions({ forwardedProps: options.forwardedProps })
347 }
348 }, [client, options.forwardedProps])
349​
350 useEffect(() => {
351 if (options.tools !== undefined) {
352 client.updateOptions({ tools: options.tools })
353 }
354 }, [client, options.tools])
355​
356 useEffect(() => {
357 client.updateOptions({ context: options.context })
358 }, [client, options.context])
359​
360 useEffect(() => {
361 if (options.queue !== undefined) {
362 client.updateOptions({ queue: options.queue })
363 }
364 }, [client, options.queue])
365​
366 useEffect(() => {
367 if (options.live) {
368 client.subscribe()
369 subscribedRef.current = true
370 } else if (subscribedRef.current) {
371 // Only tear down a subscription we actually started. Calling
372 // `unsubscribe()` on initial mount (when `live` was never enabled) would
373 // abort an in-flight delivery resume — `resumeInFlightRun` is kicked off
374 // in the client constructor, and `unsubscribe()` cancels the shared
375 // in-flight stream.
376 client.unsubscribe()
377 subscribedRef.current = false
378 }
379 }, [client, options.live])
380​
381 // Octane has no StrictMode double-invoke, so attach and dispose are
382 // immediate (Vue-style), not React's deferred setTimeout dispose.
383 useEffect(() => {
384 client.attach()
385 client.mountDevtools()
386 syncResumeState(client)
387 return () => {
388 client.detach()
389 if (optionsRef.current.live) {
390 client.unsubscribe()
391 } else {
392 client.stop()
393 }
394 client.dispose()
395 if (activeClientRef.current === client) {
396 activeClientRef.current = null
397 }
398 }
399 }, [client, syncResumeState])
400​
401 const sendMessage = useCallback(
402 async (
403 content: string | MultimodalContent,
404 sendOptions?: SendMessageOptions,
405 ) => {
406 try {
407 await client.sendMessage(content, undefined, sendOptions)
408 } finally {
409 syncResumeState(client)
410 }
411 },
412 [client, syncResumeState],
413 )
414​
415 const cancelQueued = useCallback(
416 (id: string) => {
417 client.cancelQueued(id)
418 },
419 [client],
420 )
421​
422 const append = useCallback(
423 async (message: ModelMessage | UIMessage) => {
424 try {
425 await client.append(message)
426 } finally {
427 syncResumeState(client)
428 }
429 },
430 [client, syncResumeState],
431 )
432​
433 const reload = useCallback(async () => {
434 try {
435 await client.reload()
436 } finally {
437 syncResumeState(client)
438 }
439 }, [client, syncResumeState])
440​
441 const loadOlderMessages = useCallback(async () => {
442 await client.loadOlderMessages()
443 setHasOlderMessages(client.getHasOlderMessages())
444 }, [client])
445​
446 const stop = useCallback(() => {
447 client.stop()
448 }, [client])
449​
450 const clear = useCallback(() => {
451 client.clear()
452 syncResumeState(client)
453 }, [client, syncResumeState])
454​
455 const setMessagesManually = useCallback(
456 (newMessages: Array<UIMessage<TTools>>) => {
457 client.setMessagesManually(newMessages)
458 },
459 [client],
460 )
461​
462 const addToolResult = useCallback(
463 async (result: {
464 toolCallId: string
465 tool: string
466 output: any
467 state?: 'output-available' | 'output-error'
468 errorText?: string
469 }) => {
470 await client.addToolResult(result)
471 },
472 [client],
473 )
474​
475 const addToolApprovalResponse = useCallback(
476 async (response: { id: string; approved: boolean }) => {
477 await client.addToolApprovalResponse(response)
478 syncResumeState(client)
479 },
480 [client, syncResumeState],
481 )
482​
483 const resumeInterrupts = useCallback(
484 async (resumeItems: Array<RunAgentResumeItem>, state?: ChatResumeState) => {
485 const result = await client.resumeInterrupts(
486 resumeItems,
487 state ?? undefined,
488 )
489 syncResumeState(client)
490 return result
491 },
492 [client, syncResumeState],
493 )
494​
495 const resolveInterrupts = useCallback(
496 (
497 resolution:
498 | boolean
499 | ((
500 interrupt: ResolvableChatInterrupt<TTools, TInterrupts>,
501 ) => undefined),
502 ) => {
503 if (typeof resolution === 'boolean') {
504 client.resolveInterrupts(resolution)
505 } else {
506 client.resolveInterrupts(resolution)
507 }
508 },
509 [client],
510 )
511​
512 const cancelInterrupts = useCallback(() => {
513 client.cancelInterrupts()
514 }, [client])
515​
516 const retryInterrupts = useCallback(() => {
517 client.retryInterrupts()
518 }, [client])
519​
520 const resumeInterruptsUnsafe = useCallback(
521 (resumeItems: Array<RunAgentResumeItem>, state?: ChatResumeState) =>
522 client.resumeInterruptsUnsafe(resumeItems, state),
523 [client],
524 )
525​
526 // The "active" structured-output part is the one on the assistant message
527 // that follows the latest user message. No such message exists between
528 // sendMessage() and the first chunk, so partial/final naturally read as
529 // cleared. Historical parts on earlier assistant messages remain available
530 // via `messages` directly.
531 //
532 // When there is NO user message yet (e.g. `initialMessages` contains only
533 // a stale assistant turn or a system prompt) we deliberately return null
534 // rather than scanning historical assistants — otherwise a `final` from a
535 // previous session would leak into the hook value on first render.
536 const renderedMessages = client.getMessages()
537​
538 const activeStructuredPart = useMemo<StructuredOutputPart | null>(() => {
539 let lastUserIndex = -1
540 for (let i = renderedMessages.length - 1; i >= 0; i--) {
541 if (renderedMessages[i]?.role === 'user') {
542 lastUserIndex = i
543 break
544 }
545 }
546 if (lastUserIndex === -1) return null
547 for (let i = renderedMessages.length - 1; i > lastUserIndex; i--) {
548 const m = renderedMessages[i]
549 if (m?.role !== 'assistant') continue
550 const part = m.parts.find(
551 (p): p is StructuredOutputPart => p.type === 'structured-output',
552 )
553 if (part) return part
554 }
555 return null
556 }, [renderedMessages])
557​
558 const partial = useMemo<Partial>(() => {
559 if (!activeStructuredPart) return {} as Partial
560 const v = activeStructuredPart.partial ?? activeStructuredPart.data
561 return (v ?? {}) as Partial
562 }, [activeStructuredPart])
563​
564 const final = useMemo<Final | null>(() => {
565 if (!activeStructuredPart || activeStructuredPart.status !== 'complete') {
566 return null
567 }
568 return activeStructuredPart.data as Final
569 }, [activeStructuredPart])
570​
571 // The runtime shape unconditionally exposes partial/final; the public
572 // return type hides them when no outputSchema was supplied. TS can't
573 // structurally narrow across that conditional, so the `as` is the seam.
574 // eslint-disable-next-line no-restricted-syntax -- hook return shape diverges from generic UseChatReturn<TTools, TSchema> due to conditional type on TSchema; TS can't structurally narrow
575 return {
576 messages: renderedMessages,
577 sendMessage,
578 append,
579 reload,
580 stop,
581 isLoading,
582 hasOlderMessages,
583 loadOlderMessages,
584 error,
585 status,
586 isSubscribed,
587 connectionStatus,
588 sessionGenerating,
589 setMessages: setMessagesManually,
590 clear,
591 addToolResult,
592 addToolApprovalResponse,
593 queue,
594 cancelQueued,
595 runId,
596 interrupts: interruptState.interrupts,
597 pendingInterrupts: interruptState.pendingInterrupts,
598 interruptErrors: interruptState.interruptErrors,
599 resuming: interruptState.resuming,
600 resolveInterrupts,
601 cancelInterrupts,
602 retryInterrupts,
603 resumeInterruptsUnsafe,
604 resumeInterrupts,
605 partial,
606 final,
607 } as unknown as UseChatReturn<TTools, TSchema, TInterrupts>