Open History to see the last commit
1import {
2 createEffect,
3 createMemo,
4 createSignal,
5 createUniqueId,
6 onCleanup,
7 onMount,
8 untrack,
9} from 'solid-js'
10
11import { ChatClient } from '@tanstack/ai-client'
12import { createChatDevtoolsBridge } from '@tanstack/ai-client/devtools'
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'
24import type {
25 AnyClientTool,
26 InterruptDefinition,
27 InferSchemaType,
28 ModelMessage,
29 RunAgentResumeItem,
30 SchemaInput,
31 StreamChunk,
32} from '@tanstack/ai'
33import type {
34 DeepPartial,
35 MultimodalContent,
36 UIMessage,
37 UseChatOptions,
38 UseChatReturn,
39} from './types'
40
41const EMPTY_INTERRUPTS = Object.freeze([])
42const EMPTY_INTERRUPT_ERRORS = Object.freeze([])
43
44export function useChat<
45 const TTools extends ReadonlyArray<AnyClientTool> = any,
46 TSchema extends SchemaInput | undefined = undefined,
47 TContext = InferredClientContext<TTools>,
48 const TInterrupts extends ReadonlyArray<
49 InterruptDefinition<any, any, any, any>
50 > = readonly [],
51>(
52 options: UseChatOptions<
53 TTools,
54 TSchema,
55 TContext,
56 TInterrupts
57 > = {} as UseChatOptions<TTools, TSchema, TContext, TInterrupts>,
58): UseChatReturn<TTools, TSchema, TInterrupts> {
59 // The hook's identity is its `threadId`. Reload with the same `threadId`
60 // restores the same conversation. `hookId` is only a recreation key when no
61 // `threadId` is given. It is never sent on the wire.
62 const hookId = createUniqueId()
63 const clientId = options.threadId ?? hookId
64
65 const [messages, setMessages] = createSignal<Array<UIMessage<TTools>>>(
66 options.initialMessages || [],
67 )
68 const [isLoading, setIsLoading] = createSignal(false)
69 const [hasOlderMessages, setHasOlderMessages] = createSignal(false)
70 const [error, setError] = createSignal<Error | undefined>(undefined)
71 const [status, setStatus] = createSignal<ChatClientState>('ready')
72 const [isSubscribed, setIsSubscribed] = createSignal(false)
73 const [connectionStatus, setConnectionStatus] =
74 createSignal<ConnectionStatus>('disconnected')
75 const [sessionGenerating, setSessionGenerating] = createSignal(false)
76 const [queue, setQueue] = createSignal<Array<QueuedMessage>>([])
77 const [runId, setRunId] = createSignal<string | null>(null)
78 const [interruptState, setInterruptState] = createSignal<
79 ChatInterruptState<TTools, TInterrupts>
80 >({
81 interrupts: EMPTY_INTERRUPTS,
82 pendingInterrupts: EMPTY_INTERRUPTS,
83 interruptErrors: EMPTY_INTERRUPT_ERRORS,
84 resuming: false,
85 })
86
87 const syncResumeState = () => {
88 setRunId(client().getCurrentRunId())
89 setInterruptState(client().getInterruptState())
90 }
91
92 // Structured-output `partial` / `final` are derived from `messages` —
93 // specifically from the structured-output part on the latest assistant
94 // message (the one after the most recent user message). Per-turn parts
95 // keep history coherent without a separate reset signal.
96 type Partial = DeepPartial<InferSchemaType<NonNullable<TSchema>>>
97 type Final = InferSchemaType<NonNullable<TSchema>>
98
99 // Create ChatClient instance with callbacks to sync state.
100 // Every user-provided callback is wrapped so the LATEST `options.xxx` value
101 // is read at call time. Direct assignment would freeze the callback to the
102 // reference we saw at creation; the wrapper lets reactive `options` or
103 // in-place mutations propagate. When the user clears a callback (sets it to
104 // undefined), `?.` no-ops.
105 const client = createMemo(() => {
106 // Build options with conditional spreads for fields whose source
107 // type is `T | undefined` but the ChatClient target uses a strict
108 // optional (`field?: T`) — `exactOptionalPropertyTypes` rejects
109 // assigning `undefined` to those, so we omit the key when absent.
110 const transport = options.connection
111 ? { connection: options.connection }
112 : { fetcher: options.fetcher }
113 const instance = new ChatClient<TTools, TContext, TInterrupts>({
114 devtoolsBridgeFactory: createChatDevtoolsBridge,
115 ...transport,
116 ...(options.initialMessages !== undefined && {
117 initialMessages: options.initialMessages,
118 }),
119 ...(typeof options.threadId === 'string' && options.persistence === true
120 ? {
121 persistence: true,
122 threadId: options.threadId,
123 ...(options.history !== undefined && {
124 history: options.history,
125 }),
126 }
127 : typeof options.threadId === 'string' && options.persistence
128 ? {
129 persistence: options.persistence,
130 threadId: options.threadId,
131 }
132 : {
133 ...(options.threadId !== undefined && {
134 threadId: options.threadId,
135 }),
136 }),
137 ...(options.initialResumeSnapshot !== undefined && {
138 initialResumeSnapshot: options.initialResumeSnapshot,
139 }),
140 body: options.body,
141 ...(options.forwardedProps !== undefined && {
142 forwardedProps: options.forwardedProps,
143 }),
144 ...(options.byok !== undefined && { byok: options.byok }),
145 byokProvider: () => options.byokProvider?.(),
146 ...(options.context !== undefined && { context: options.context }),
147 devtools: {
148 ...options.devtools,
149 framework: 'solid',
150 hookName: 'useChat',
151 outputKind: options.outputSchema ? 'structured' : 'chat',
152 },
153 onResponse: (response) => options.onResponse?.(response),
154 onChunk: (chunk: StreamChunk) => {
155 options.onChunk?.(chunk)
156 },
157 onFinish: (message) => {
158 options.onFinish?.(message)
159 },
160 onError: (err) => {
161 options.onError?.(err)
162 },
163 // Untracked: a tools change must not rebuild the client. The effect
164 // below syncs it instead.
165 tools: untrack(() => options.tools),
166 ...(options.interrupts !== undefined && {
167 interrupts: options.interrupts,
168 }),
169 onCustomEvent: (eventType, data, context) =>
170 options.onCustomEvent?.(eventType, data, context),
171 ...(options.streamProcessor !== undefined && {
172 streamProcessor: options.streamProcessor,
173 }),
174 onMessagesChange: (newMessages: Array<UIMessage<TTools>>) => {
175 setMessages(newMessages)
176 setHasOlderMessages(instance.getHasOlderMessages())
177 },
178 onLoadingChange: (newIsLoading: boolean) => {
179 setIsLoading(newIsLoading)
180 syncResumeState()
181 },
182 onStatusChange: (newStatus: ChatClientState) => {
183 setStatus(newStatus)
184 },
185 onErrorChange: (newError: Error | undefined) => {
186 setError(newError)
187 },
188 onSubscriptionChange: (nextIsSubscribed: boolean) => {
189 setIsSubscribed(nextIsSubscribed)
190 },
191 onConnectionStatusChange: (nextStatus: ConnectionStatus) => {
192 setConnectionStatus(nextStatus)
193 },
194 onSessionGeneratingChange: (isGenerating: boolean) => {
195 setSessionGenerating(isGenerating)
196 },
197 ...(options.queue !== undefined && { queue: options.queue }),
198 onQueueChange: (nextQueue: Array<QueuedMessage>) => {
199 setQueue(nextQueue)
200 },
201 onRunIdChange: (nextRunId) => {
202 setRunId(nextRunId)
203 },
204 onResumeStateChange: (_nextResumeState, nextPendingInterrupts) => {
205 setInterruptState((current) => ({
206 ...current,
207 interrupts: nextPendingInterrupts,
208 pendingInterrupts: nextPendingInterrupts,
209 }))
210 },
211 onInterruptStateChange: (nextInterruptState, context) => {
212 setInterruptState(nextInterruptState)
213 options.onInterruptStateChange?.(nextInterruptState, context)
214 },
215 })
216 // Only recreate when clientId changes
217 // Connection and other options are captured at creation time
218 return instance
219 }, [clientId])
220
221 setMessages(client().getMessages())
222 setHasOlderMessages(client().getHasOlderMessages())
223 syncResumeState()
224
225 // Sync body / forwardedProps changes to the client.
226 // Both populate the same wire payload; `forwardedProps` is preferred
227 // and `body` is deprecated but still supported.
228 createEffect(() => {
229 // Conditional spread: `updateOptions` declares strict-optional
230 // fields and rejects explicit `undefined` under EOPT.
231 client().updateOptions({
232 ...(options.body !== undefined && { body: options.body }),
233 ...(options.forwardedProps !== undefined && {
234 forwardedProps: options.forwardedProps,
235 }),
236 context: options.context,
237 ...(options.queue !== undefined && { queue: options.queue }),
238 })
239 })
240
241 // Sync tools, so a getter such as `get tools() { return pageTools() }`
242 // updates the client.
243 createEffect(() => {
244 const tools = options.tools
245 if (tools !== undefined) client().updateOptions({ tools })
246 })
247
248 // Apply initial live mode immediately on hook creation.
249 if (options.live) {
250 client().subscribe()
251 } else {
252 client().unsubscribe()
253 }
254
255 createEffect(() => {
256 if (options.live) {
257 client().subscribe()
258 } else {
259 client().unsubscribe()
260 }
261 })
262
263 onMount(() => {
264 // START TAILING HERE, not in the constructor. A client is idle until a view
265 // attaches it, so a client that gets built and thrown away never opens a
266 // connection — an unreachable stream would hold one of the browser's ~6
267 // connections per origin until the page reloaded.
268 client().attach()
269 client().mountDevtools()
270 // Delivery-durability resume is transparent: the resumable SSE connection
271 // adapter reattaches via the browser's native Last-Event-ID on reconnect.
272 // We only seed interrupt (state) resume from the client here.
273 syncResumeState()
274 })
275
276 // Cleanup on unmount: stop any in-flight requests.
277 onCleanup(() => {
278 // Release the connection first: `detach` is the counterpart of the `attach`
279 // above, and it keeps the transcript and resume pointer so a later mount can
280 // pick the run back up from the durable log.
281 client().detach()
282 if (options.live) {
283 client().unsubscribe()
284 } else {
285 client().stop()
286 }
287 client().dispose()
288 })
289
290 // Callback options are read through `options.xxx` at call time, so reactive
291 // or mutated options propagate without recreating the client.
292
293 const sendMessage = async (
294 content: string | MultimodalContent,
295 sendOptions?: SendMessageOptions,
296 ) => {
297 try {
298 await client().sendMessage(content, undefined, sendOptions)
299 } finally {
300 syncResumeState()
301 }
302 }
303
304 const append = async (message: ModelMessage | UIMessage<TTools>) => {
305 try {
306 await client().append(message)
307 } finally {
308 syncResumeState()
309 }
310 }
311
312 const reload = async () => {
313 try {
314 await client().reload()
315 } finally {
316 syncResumeState()
317 }
318 }
319
320 const loadOlderMessages = async () => {
321 await client().loadOlderMessages()
322 setHasOlderMessages(client().getHasOlderMessages())
323 }
324
325 const stop = () => {
326 client().stop()
327 }
328
329 const clear = () => {
330 client().clear()
331 syncResumeState()
332 }
333
334 const setMessagesManually = (newMessages: Array<UIMessage<TTools>>) => {
335 client().setMessagesManually(newMessages)
336 }
337
338 const addToolResult = async (result: {
339 toolCallId: string
340 tool: string
341 output: any
342 state?: 'output-available' | 'output-error'
343 errorText?: string
344 }) => {
345 await client().addToolResult(result)
346 }
347
348 const addToolApprovalResponse = async (response: {
349 id: string
350 approved: boolean
351 }) => {
352 await client().addToolApprovalResponse(response)
353 syncResumeState()
354 }
355
356 const cancelQueued = (id: string) => client().cancelQueued(id)
357
358 const resumeInterrupts = async (
359 resumeItems: Array<RunAgentResumeItem>,
360 state?: ChatResumeState,
361 ) => {
362 const result = await client().resumeInterrupts(resumeItems, state)
363 syncResumeState()
364 return result
365 }
366
367 const resolveInterrupts = (
368 resolution:
369 | boolean
370 | ((
371 interrupt: ResolvableChatInterrupt<TTools, TInterrupts>,
372 ) => undefined),
373 ) => {
374 if (typeof resolution === 'boolean') {
375 client().resolveInterrupts(resolution)
376 } else {
377 client().resolveInterrupts(resolution)
378 }
379 }
380
381 const cancelInterrupts = () => {
382 client().cancelInterrupts()
383 }
384
385 const retryInterrupts = () => {
386 client().retryInterrupts()
387 }
388
389 const resumeInterruptsUnsafe = (
390 resumeItems: Array<RunAgentResumeItem>,
391 state?: ChatResumeState,
392 ) => client().resumeInterruptsUnsafe(resumeItems, state)
393
394 const interrupts = () => interruptState().interrupts
395 const pendingInterrupts = () => interruptState().pendingInterrupts
396 const interruptErrors = () => interruptState().interruptErrors
397 const resuming = () => interruptState().resuming
398
399 // The "active" structured-output part is on the assistant message after
400 // the latest user message. When no user message exists yet, return null
401 // rather than scanning history — otherwise a stale `final` from
402 // `initialMessages` would leak into the value on first render.
403 const activeStructuredPart = createMemo<StructuredOutputPart | null>(() => {
404 const list = messages()
405 let lastUserIndex = -1
406 for (let i = list.length - 1; i >= 0; i--) {
407 if (list[i]?.role === 'user') {
408 lastUserIndex = i
409 break
410 }
411 }
412 if (lastUserIndex === -1) return null
413 for (let i = list.length - 1; i > lastUserIndex; i--) {
414 const m = list[i]
415 if (m?.role !== 'assistant') continue
416 const part = m.parts.find(
417 (p): p is StructuredOutputPart => p.type === 'structured-output',
418 )
419 if (part) return part
420 }
421 return null
422 })
423
424 const partial = createMemo<Partial>(() => {
425 const part = activeStructuredPart()
426 if (!part) return {} as Partial
427 const v = part.partial ?? part.data
428 return (v ?? {}) as Partial
429 })
430
431 const final = createMemo<Final | null>(() => {
432 const part = activeStructuredPart()
433 if (!part || part.status !== 'complete') return null
434 return part.data as Final
435 })
436
437 // partial / final are runtime-tracked unconditionally; the conditional
438 // return type hides them when no `outputSchema` is supplied.
439 // oxlint-disable-next-line eslint-js/no-restricted-syntax -- primitive return shape diverges from generic UseChatReturn<TTools, TSchema>; TS can't structurally narrow the conditional partial/final fields
440 return {
441 messages,
442 queue,
443 sendMessage,
444 append,
445 reload,
446 stop,
447 isLoading,
448 hasOlderMessages,
449 loadOlderMessages,
450 error,
451 status,
452 isSubscribed,
453 connectionStatus,
454 sessionGenerating,
455 setMessages: setMessagesManually,
456 clear,
457 addToolResult,
458 addToolApprovalResponse,
459 cancelQueued,
460 runId,
461 interrupts,
462 pendingInterrupts,
463 interruptErrors,
464 resuming,
465 resolveInterrupts,
466 cancelInterrupts,
467 retryInterrupts,
468 resumeInterruptsUnsafe,
469 resumeInterrupts,
470 partial,
471 final,
472 } as unknown as UseChatReturn<TTools, TSchema, TInterrupts>
473}