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

use-chat.tsrx

498 lines16.3 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 ResolvableChatInterrupt,
15 ChatResumeState,
16 InferredClientContext,
17 SendMessageOptions,
18 StructuredOutputPart,
19} from '@tanstack/ai-client'
20​
21import type {
22 DeepPartial,
23 MultimodalContent,
24 UIMessage,
25 UseChatOptions,
26 UseChatReturn,
27} from './types'
28​
29export function useChat<
30 const TTools extends ReadonlyArray<AnyClientTool> = any,
31 TSchema extends SchemaInput | undefined = undefined,
32 TContext = InferredClientContext<TTools>,
33 const TInterrupts extends ReadonlyArray<
34 InterruptDefinition<any, any, any, any>
35 > = readonly [],
36>(
37 options: UseChatOptions<TTools, TSchema, TContext, TInterrupts>,
38): UseChatReturn<TTools, TSchema, TInterrupts> {
39 // The hook's identity is its `threadId`. Reload with the same `threadId`
40 // restores the same conversation. `hookId` is only a recreation key when no
41 // `threadId` is given. It is never sent on the wire.
42 const hookId = useId()
43 const clientId = options.threadId ?? hookId
44​
45 const subscribedRef = useRef(false)
46 const activeClientRef = useRef<ChatClient | null>(null)
47 const seenClientRef = useRef<ChatClient | null>(null)
48 const optionsRef =
49 useRef<UseChatOptions<TTools, TSchema, TContext, TInterrupts>>(options)
50 optionsRef.current = options
51​
52 // Create ChatClient instance with callbacks to sync state
53 const { client, initialization } = useMemo(() => {
54 const messagesToUse = options.initialMessages || []
55​
56 // Build options with conditional spreads for fields whose source
57 // type is `T | undefined` but the ChatClient target uses a strict
58 // optional (`field?: T`) — `exactOptionalPropertyTypes` rejects
59 // assigning `undefined` to those, so we omit the key when absent.
60 const initialOptions = optionsRef.current
61 const transport = initialOptions.connection
62 ? { connection: initialOptions.connection }
63 : { fetcher: initialOptions.fetcher }
64​
65 const instanceHolder: {
66 current: ChatClient<TTools, TContext, TInterrupts> | undefined
67 } = { current: undefined }
68 const getActiveInstance = () => {
69 const currentInstance = instanceHolder.current
70 if (!currentInstance || activeClientRef.current !== currentInstance) {
71 return undefined
72 }
73 return currentInstance
74 }
75 // ChatClient may publish while its constructor is running or while async
76 // persistence resolves before commit. Preserve those notifications until
77 // this render commits.
78 const initializationState = {
79 ready: false,
80 callbacks: [] as Array<() => void>,
81 }
82 const runOrQueueForActiveInstance = (callback: () => void) => {
83 if (!initializationState.ready) {
84 initializationState.callbacks.push(callback)
85 return
86 }
87 const currentInstance = instanceHolder.current
88 if (!currentInstance || activeClientRef.current !== currentInstance)
89 return
90 callback()
91 }
92 const instance = new ChatClient<TTools, TContext, TInterrupts>({
93 devtoolsBridgeFactory: createChatDevtoolsBridge,
94 ...transport,
95 initialMessages: messagesToUse,
96 ...(typeof initialOptions.threadId === 'string' &&
97 initialOptions.persistence === true
98 ? {
99 persistence: true,
100 threadId: initialOptions.threadId,
101 ...(initialOptions.history !== undefined && {
102 history: initialOptions.history,
103 }),
104 }
105 : typeof initialOptions.threadId === 'string' &&
106 initialOptions.persistence
107 ? {
108 persistence: initialOptions.persistence,
109 threadId: initialOptions.threadId,
110 }
111 : {
112 ...(initialOptions.threadId !== undefined && {
113 threadId: initialOptions.threadId,
114 }),
115 }),
116 ...(initialOptions.body !== undefined && { body: initialOptions.body }),
117 ...(initialOptions.forwardedProps !== undefined && {
118 forwardedProps: initialOptions.forwardedProps,
119 }),
120 ...(initialOptions.initialResumeSnapshot !== undefined && {
121 initialResumeSnapshot: initialOptions.initialResumeSnapshot,
122 }),
123 ...(initialOptions.context !== undefined && {
124 context: initialOptions.context,
125 }),
126 devtools: {
127 ...initialOptions.devtools,
128 // OCTANE DIVERGENCE: identify this binding as Octane (not 'react') in TanStack AI Devtools.
129 // Spread AFTER caller metadata so callers cannot override identification.
130 framework: 'octane',
131 hookName: 'useChat',
132 outputKind: initialOptions.outputSchema ? 'structured' : 'chat',
133 },
134 onResponse: (response) => {
135 // ChatClient awaits this return value. Dropping it would skip the promise.
136 if (!getActiveInstance()) return
137 return optionsRef.current.onResponse?.(response)
138 },
139 onChunk: (chunk: StreamChunk) => {
140 runOrQueueForActiveInstance(() => {
141 optionsRef.current.onChunk?.(chunk)
142 })
143 },
144 onFinish: (message: UIMessage<TTools>) => {
145 runOrQueueForActiveInstance(() => {
146 optionsRef.current.onFinish?.(message)
147 })
148 },
149 onError: (error: Error) => {
150 runOrQueueForActiveInstance(() => {
151 optionsRef.current.onError?.(error)
152 })
153 },
154 ...(initialOptions.tools !== undefined && {
155 tools: initialOptions.tools,
156 }),
157 ...(initialOptions.interrupts !== undefined && {
158 interrupts: initialOptions.interrupts,
159 }),
160 onCustomEvent: (eventType, data, context) => {
161 runOrQueueForActiveInstance(() => {
162 optionsRef.current.onCustomEvent?.(eventType, data, context)
163 })
164 },
165 ...(options.streamProcessor !== undefined && {
166 streamProcessor: options.streamProcessor,
167 }),
168 ...(optionsRef.current.queue !== undefined && {
169 queue: optionsRef.current.queue,
170 }),
171 onInterruptStateChange: (nextInterruptState, context) => {
172 runOrQueueForActiveInstance(() => {
173 optionsRef.current.onInterruptStateChange?.(
174 nextInterruptState,
175 context,
176 )
177 })
178 },
179 })
180 instanceHolder.current = instance
181 return { client: instance, initialization: initializationState }
182 }, [clientId])
183​
184 type Partial = DeepPartial<InferSchemaType<NonNullable<TSchema>>>
185 type Final = InferSchemaType<NonNullable<TSchema>>
186​
187 // Constructor hydration (sync store / resume snapshot) must be on the first
188 // paint. `useEffect` runs after paint, so seed from the snapshot here.
189 // Tagged with its client: after a thread switch, the new client's snapshot
190 // shows on the first render, before the effect below subscribes.
191 const [held, setHeld] = useState(() => ({
192 client,
193 snapshot: client.getSnapshot(),
194 }))
195 const snapshot =
196 held.client === client ? held.snapshot : client.getSnapshot()
197​
198 useEffect(() => {
199 activeClientRef.current = client
200 try {
201 // Keep initialization closed while draining so callbacks published by a
202 // queued callback are appended and delivered in the same commit.
203 while (initialization.callbacks.length > 0) {
204 if (activeClientRef.current !== client) {
205 initialization.callbacks.length = 0
206 break
207 }
208 initialization.callbacks.shift()?.()
209 }
210 } finally {
211 // A throw from a queued user callback must not leave the queue closed.
212 initialization.ready = true
213 }
214 }, [client, initialization])
215​
216 useEffect(() => {
217 const applySnapshot = () => {
218 const next = client.getSnapshot()
219 setHeld((prev) =>
220 prev.client === client && prev.snapshot === next
221 ? prev
222 : { client, snapshot: next },
223 )
224 }
225 applySnapshot()
226 return client.subscribeSnapshot(applySnapshot)
227 }, [client])
228​
229 // OCTANE DIVERGENCE: upstream captures the initial transport. ChatClient
230 // owns transport swaps, including aborting an active request and
231 // resubscribing when needed, so keep its conversation state stable while
232 // applying the latest transport. Skip the first run for each client — it
233 // already has this transport from the constructor, and a no-op swap can
234 // abort constructor rejoin / interrupt resume.
235 useEffect(() => {
236 if (seenClientRef.current !== client) {
237 seenClientRef.current = client
238 return
239 }
240 const transport = options.connection
241 ? { connection: options.connection }
242 : { fetcher: options.fetcher }
243 client.updateOptions(transport)
244 }, [client, options.connection, options.fetcher])
245​
246 // Sync each wire-payload slot in its own effect so an unrelated option
247 // changing doesn't re-run the others. `updateOptions` declares strict-optional
248 // fields and rejects explicit `undefined` under EOPT, so guard the optional
249 // slots before passing them.
250 useEffect(() => {
251 client.updateOptions({ body: options.body })
252 }, [client, options.body])
253​
254 useEffect(() => {
255 if (options.forwardedProps !== undefined) {
256 client.updateOptions({ forwardedProps: options.forwardedProps })
257 }
258 }, [client, options.forwardedProps])
259​
260 useEffect(() => {
261 if (options.tools !== undefined) {
262 client.updateOptions({ tools: options.tools })
263 }
264 }, [client, options.tools])
265​
266 useEffect(() => {
267 client.updateOptions({ context: options.context })
268 }, [client, options.context])
269​
270 useEffect(() => {
271 if (options.queue !== undefined) {
272 client.updateOptions({ queue: options.queue })
273 }
274 }, [client, options.queue])
275​
276 useEffect(() => {
277 if (options.live) {
278 client.subscribe()
279 subscribedRef.current = true
280 } else if (subscribedRef.current) {
281 // Only tear down a subscription we actually started. Calling
282 // `unsubscribe()` on initial mount (when `live` was never enabled) would
283 // abort an in-flight delivery resume — `resumeInFlightRun` is kicked off
284 // in the client constructor, and `unsubscribe()` cancels the shared
285 // in-flight stream.
286 client.unsubscribe()
287 subscribedRef.current = false
288 }
289 }, [client, options.live])
290​
291 // Octane has no StrictMode double-invoke, so attach and dispose are
292 // immediate (Vue-style), not React's deferred setTimeout dispose.
293 useEffect(() => {
294 client.attach()
295 client.mountDevtools()
296 return () => {
297 client.detach()
298 if (optionsRef.current.live) {
299 client.unsubscribe()
300 } else {
301 client.stop()
302 }
303 client.dispose()
304 if (activeClientRef.current === client) {
305 activeClientRef.current = null
306 }
307 }
308 }, [client])
309​
310 const sendMessage = useCallback(
311 async (
312 content: string | MultimodalContent,
313 sendOptions?: SendMessageOptions,
314 ) => {
315 await client.sendMessage(content, undefined, sendOptions)
316 },
317 [client],
318 )
319​
320 const cancelQueued = useCallback(
321 (id: string) => {
322 client.cancelQueued(id)
323 },
324 [client],
325 )
326​
327 const append = useCallback(
328 async (message: ModelMessage | UIMessage) => {
329 await client.append(message)
330 },
331 [client],
332 )
333​
334 const reload = useCallback(async () => {
335 await client.reload()
336 }, [client])
337​
338 const loadOlderMessages = useCallback(async () => {
339 await client.loadOlderMessages()
340 }, [client])
341​
342 const stop = useCallback(() => {
343 client.stop()
344 }, [client])
345​
346 const clear = useCallback(() => {
347 client.clear()
348 }, [client])
349​
350 const setMessagesManually = useCallback(
351 (newMessages: ReadonlyArray<UIMessage<TTools>>) => {
352 client.setMessagesManually(newMessages)
353 },
354 [client],
355 )
356​
357 const addToolResult = useCallback(
358 async (result: {
359 toolCallId: string
360 tool: string
361 output: any
362 state?: 'output-available' | 'output-error'
363 errorText?: string
364 }) => {
365 await client.addToolResult(result)
366 },
367 [client],
368 )
369​
370 const addToolApprovalResponse = useCallback(
371 async (response: { id: string; approved: boolean }) => {
372 await client.addToolApprovalResponse(response)
373 },
374 [client],
375 )
376​
377 const resumeInterrupts = useCallback(
378 async (resumeItems: Array<RunAgentResumeItem>, state?: ChatResumeState) => {
379 return await client.resumeInterrupts(resumeItems, state ?? undefined)
380 },
381 [client],
382 )
383​
384 const resolveInterrupts = useCallback(
385 (
386 resolution:
387 | boolean
388 | ((
389 interrupt: ResolvableChatInterrupt<TTools, TInterrupts>,
390 ) => undefined),
391 ) => {
392 if (typeof resolution === 'boolean') {
393 client.resolveInterrupts(resolution)
394 } else {
395 client.resolveInterrupts(resolution)
396 }
397 },
398 [client],
399 )
400​
401 const cancelInterrupts = useCallback(() => {
402 client.cancelInterrupts()
403 }, [client])
404​
405 const retryInterrupts = useCallback(() => {
406 client.retryInterrupts()
407 }, [client])
408​
409 const resumeInterruptsUnsafe = useCallback(
410 (resumeItems: Array<RunAgentResumeItem>, state?: ChatResumeState) =>
411 client.resumeInterruptsUnsafe(resumeItems, state),
412 [client],
413 )
414​
415 // The "active" structured-output part is the one on the assistant message
416 // that follows the latest user message. No such message exists between
417 // sendMessage() and the first chunk, so partial/final naturally read as
418 // cleared. Historical parts on earlier assistant messages remain available
419 // via `messages` directly.
420 //
421 // When there is NO user message yet (e.g. `initialMessages` contains only
422 // a stale assistant turn or a system prompt) we deliberately return null
423 // rather than scanning historical assistants — otherwise a `final` from a
424 // previous session would leak into the hook value on first render.
425 const renderedMessages = snapshot.messages
426​
427 const activeStructuredPart = useMemo<StructuredOutputPart | null>(() => {
428 let lastUserIndex = -1
429 for (let i = renderedMessages.length - 1; i >= 0; i--) {
430 if (renderedMessages[i]?.role === 'user') {
431 lastUserIndex = i
432 break
433 }
434 }
435 if (lastUserIndex === -1) return null
436 for (let i = renderedMessages.length - 1; i > lastUserIndex; i--) {
437 const m = renderedMessages[i]
438 if (m?.role !== 'assistant') continue
439 const part = m.parts.find(
440 (p): p is StructuredOutputPart => p.type === 'structured-output',
441 )
442 if (part) return part
443 }
444 return null
445 }, [renderedMessages])
446​
447 const partial = useMemo<Partial>(() => {
448 if (!activeStructuredPart) return {} as Partial
449 const v = activeStructuredPart.partial ?? activeStructuredPart.data
450 return (v ?? {}) as Partial
451 }, [activeStructuredPart])
452​
453 const final = useMemo<Final | null>(() => {
454 if (!activeStructuredPart || activeStructuredPart.status !== 'complete') {
455 return null
456 }
457 return activeStructuredPart.data as Final
458 }, [activeStructuredPart])
459​
460 // The runtime shape unconditionally exposes partial/final; the public
461 // return type hides them when no outputSchema was supplied. TS can't
462 // structurally narrow across that conditional, so the `as` is the seam.
463 // 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
464 return {
465 messages: renderedMessages,
466 sendMessage,
467 append,
468 reload,
469 stop,
470 isLoading: snapshot.isLoading,
471 hasOlderMessages: snapshot.hasOlderMessages,
472 loadOlderMessages,
473 error: snapshot.error,
474 status: snapshot.status,
475 isSubscribed: snapshot.isSubscribed,
476 connectionStatus: snapshot.connectionStatus,
477 sessionGenerating: snapshot.sessionGenerating,
478 isHydrating: snapshot.isHydrating,
479 setMessages: setMessagesManually,
480 clear,
481 addToolResult,
482 addToolApprovalResponse,
483 queue: snapshot.queue,
484 cancelQueued,
485 runId: snapshot.runId,
486 interrupts: snapshot.interruptState.interrupts,
487 pendingInterrupts: snapshot.interruptState.pendingInterrupts,
488 interruptErrors: snapshot.interruptState.interruptErrors,
489 resuming: snapshot.interruptState.resuming,
490 resolveInterrupts,
491 cancelInterrupts,
492 retryInterrupts,
493 resumeInterruptsUnsafe,
494 resumeInterrupts,
495 partial,
496 final,
497 } as unknown as UseChatReturn<TTools, TSchema, TInterrupts>