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