Open History to see the last commit
1import {
2 createEffect,
3 createMemo,
4 createSignal,
5 on,
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 ResolvableChatInterrupt,
15 ChatResumeState,
16 InferredClientContext,
17 SendMessageOptions,
18 StructuredOutputPart,
19} from '@tanstack/ai-client'
20import type {
21 AnyClientTool,
22 InterruptDefinition,
23 InferSchemaType,
24 ModelMessage,
25 RunAgentResumeItem,
26 SchemaInput,
27 StreamChunk,
28} from '@tanstack/ai'
29import type {
30 DeepPartial,
31 MultimodalContent,
32 UIMessage,
33 UseChatOptions,
34 UseChatReturn,
35} from './types'
36
37export function useChat<
38 const TTools extends ReadonlyArray<AnyClientTool> = any,
39 TSchema extends SchemaInput | undefined = undefined,
40 TContext = InferredClientContext<TTools>,
41 const TInterrupts extends ReadonlyArray<
42 InterruptDefinition<any, any, any, any>
43 > = readonly [],
44>(
45 options: UseChatOptions<
46 TTools,
47 TSchema,
48 TContext,
49 TInterrupts
50 > = {} as UseChatOptions<TTools, TSchema, TContext, TInterrupts>,
51): UseChatReturn<TTools, TSchema, TInterrupts> {
52 // The hook's identity is its `threadId`. Reload with the same `threadId`
53 // restores the same conversation.
54
55 // Structured-output `partial` / `final` are derived from `messages` —
56 // specifically from the structured-output part on the latest assistant
57 // message (the one after the most recent user message). Per-turn parts
58 // keep history coherent without a separate reset signal.
59 type Partial = DeepPartial<InferSchemaType<NonNullable<TSchema>>>
60 type Final = InferSchemaType<NonNullable<TSchema>>
61
62 // Build the client once per threadId. User callbacks read latest options.
63 // Every user-provided callback is wrapped so the LATEST `options.xxx` value
64 // is read at call time. Direct assignment would freeze the callback to the
65 // reference we saw at creation; the wrapper lets reactive `options` or
66 // in-place mutations propagate. When the user clears a callback (sets it to
67 // undefined), `?.` no-ops.
68 const createClient = () => {
69 // Build options with conditional spreads for fields whose source
70 // type is `T | undefined` but the ChatClient target uses a strict
71 // optional (`field?: T`) — `exactOptionalPropertyTypes` rejects
72 // assigning `undefined` to those, so we omit the key when absent.
73 const transport = options.connection
74 ? { connection: options.connection }
75 : { fetcher: options.fetcher }
76 const instance = new ChatClient<TTools, TContext, TInterrupts>({
77 devtoolsBridgeFactory: createChatDevtoolsBridge,
78 ...transport,
79 ...(options.initialMessages !== undefined && {
80 initialMessages: options.initialMessages,
81 }),
82 ...(typeof options.threadId === 'string' && options.persistence === true
83 ? {
84 persistence: true,
85 threadId: options.threadId,
86 ...(options.history !== undefined && {
87 history: options.history,
88 }),
89 }
90 : typeof options.threadId === 'string' && options.persistence
91 ? {
92 persistence: options.persistence,
93 threadId: options.threadId,
94 }
95 : {
96 ...(options.threadId !== undefined && {
97 threadId: options.threadId,
98 }),
99 }),
100 ...(options.initialResumeSnapshot !== undefined && {
101 initialResumeSnapshot: options.initialResumeSnapshot,
102 }),
103 body: options.body,
104 ...(options.forwardedProps !== undefined && {
105 forwardedProps: options.forwardedProps,
106 }),
107 ...(options.byok !== undefined && { byok: options.byok }),
108 byokProvider: () => options.byokProvider?.(),
109 ...(options.context !== undefined && { context: options.context }),
110 devtools: {
111 ...options.devtools,
112 framework: 'solid',
113 hookName: 'useChat',
114 outputKind: options.outputSchema ? 'structured' : 'chat',
115 },
116 onResponse: (response) => options.onResponse?.(response),
117 onChunk: (chunk: StreamChunk) => {
118 options.onChunk?.(chunk)
119 },
120 onFinish: (message) => {
121 options.onFinish?.(message)
122 },
123 onError: (err) => {
124 options.onError?.(err)
125 },
126 // Untracked: a tools change must not rebuild the client. The effect
127 // below syncs it instead.
128 tools: untrack(() => options.tools),
129 ...(options.interrupts !== undefined && {
130 interrupts: options.interrupts,
131 }),
132 onCustomEvent: (eventType, data, context) =>
133 options.onCustomEvent?.(eventType, data, context),
134 ...(options.streamProcessor !== undefined && {
135 streamProcessor: options.streamProcessor,
136 }),
137 ...(options.queue !== undefined && { queue: options.queue }),
138 onInterruptStateChange: (nextInterruptState, context) => {
139 options.onInterruptStateChange?.(nextInterruptState, context)
140 },
141 })
142 return instance
143 }
144 // Rebuild the client only when `threadId` changes. `on` runs `createClient`
145 // untracked, so a reactive `body` or `forwardedProps` change does not start a
146 // new client and drop the transcript. The effects below sync those values.
147 const client = createMemo(on(() => options.threadId, createClient))
148
149 // One signal: the snapshot is frozen and replaced on every change. Seeded
150 // here so constructor hydration (a sync store) is on the first paint.
151 const [snapshot, setSnapshot] = createSignal(client().getSnapshot())
152 createEffect(() => {
153 const target = client()
154 setSnapshot(target.getSnapshot())
155 onCleanup(target.subscribeSnapshot(() => setSnapshot(target.getSnapshot())))
156 })
157 const pick = <TKey extends keyof ReturnType<typeof snapshot>>(key: TKey) =>
158 createMemo(() => snapshot()[key])
159 const messages = pick('messages')
160 const interruptState = pick('interruptState')
161
162 // Sync body / forwardedProps changes to the client.
163 // Both populate the same wire payload; `forwardedProps` is preferred
164 // and `body` is deprecated but still supported.
165 createEffect(() => {
166 // Conditional spread: `updateOptions` declares strict-optional
167 // fields and rejects explicit `undefined` under EOPT.
168 client().updateOptions({
169 ...(options.body !== undefined && { body: options.body }),
170 ...(options.forwardedProps !== undefined && {
171 forwardedProps: options.forwardedProps,
172 }),
173 context: options.context,
174 ...(options.queue !== undefined && { queue: options.queue }),
175 })
176 })
177
178 // Sync tools, so a getter such as `get tools() { return pageTools() }`
179 // updates the client.
180 createEffect(() => {
181 const tools = options.tools
182 if (tools !== undefined) client().updateOptions({ tools })
183 })
184
185 // Apply initial live mode immediately on hook creation.
186 if (options.live) {
187 client().subscribe()
188 } else {
189 client().unsubscribe()
190 }
191
192 // First paint must see constructor hydration (sync store / resume snapshot)
193 // and the live subscribe above. `createEffect` runs after paint, so the
194 // subscribe effect cannot be the first apply.
195 setSnapshot(client().getSnapshot())
196
197 createEffect(() => {
198 if (options.live) {
199 client().subscribe()
200 } else {
201 client().unsubscribe()
202 }
203 })
204
205 onMount(() => {
206 // START TAILING HERE, not in the constructor. A client is idle until a view
207 // attaches it, so a client that gets built and thrown away never opens a
208 // connection — an unreachable stream would hold one of the browser's ~6
209 // connections per origin until the page reloaded.
210 client().attach()
211 client().mountDevtools()
212 })
213
214 // Cleanup on unmount: stop any in-flight requests.
215 onCleanup(() => {
216 // Release the connection first: `detach` is the counterpart of the `attach`
217 // above, and it keeps the transcript and resume pointer so a later mount can
218 // pick the run back up from the durable log.
219 client().detach()
220 if (options.live) {
221 client().unsubscribe()
222 } else {
223 client().stop()
224 }
225 client().dispose()
226 })
227
228 // Callback options are read through `options.xxx` at call time, so reactive
229 // or mutated options propagate without recreating the client.
230
231 const sendMessage = async (
232 content: string | MultimodalContent,
233 sendOptions?: SendMessageOptions,
234 ) => {
235 await client().sendMessage(content, undefined, sendOptions)
236 }
237
238 const append = async (message: ModelMessage | UIMessage<TTools>) => {
239 await client().append(message)
240 }
241
242 const reload = async () => {
243 await client().reload()
244 }
245
246 const loadOlderMessages = async () => {
247 await client().loadOlderMessages()
248 }
249
250 const stop = () => {
251 client().stop()
252 }
253
254 const clear = () => {
255 client().clear()
256 }
257
258 const setMessagesManually = (
259 newMessages: ReadonlyArray<UIMessage<TTools>>,
260 ) => {
261 client().setMessagesManually(newMessages)
262 }
263
264 const addToolResult = async (result: {
265 toolCallId: string
266 tool: string
267 output: any
268 state?: 'output-available' | 'output-error'
269 errorText?: string
270 }) => {
271 await client().addToolResult(result)
272 }
273
274 const addToolApprovalResponse = async (response: {
275 id: string
276 approved: boolean
277 }) => {
278 await client().addToolApprovalResponse(response)
279 }
280
281 const cancelQueued = (id: string) => client().cancelQueued(id)
282
283 const resumeInterrupts = async (
284 resumeItems: Array<RunAgentResumeItem>,
285 state?: ChatResumeState,
286 ) => {
287 return await client().resumeInterrupts(resumeItems, state)
288 }
289
290 const resolveInterrupts = (
291 resolution:
292 | boolean
293 | ((
294 interrupt: ResolvableChatInterrupt<TTools, TInterrupts>,
295 ) => undefined),
296 ) => {
297 if (typeof resolution === 'boolean') {
298 client().resolveInterrupts(resolution)
299 } else {
300 client().resolveInterrupts(resolution)
301 }
302 }
303
304 const cancelInterrupts = () => {
305 client().cancelInterrupts()
306 }
307
308 const retryInterrupts = () => {
309 client().retryInterrupts()
310 }
311
312 const resumeInterruptsUnsafe = (
313 resumeItems: Array<RunAgentResumeItem>,
314 state?: ChatResumeState,
315 ) => client().resumeInterruptsUnsafe(resumeItems, state)
316
317 const interrupts = () => interruptState().interrupts
318 const pendingInterrupts = () => interruptState().pendingInterrupts
319 const interruptErrors = () => interruptState().interruptErrors
320 const resuming = () => interruptState().resuming
321
322 // The "active" structured-output part is on the assistant message after
323 // the latest user message. When no user message exists yet, return null
324 // rather than scanning history — otherwise a stale `final` from
325 // `initialMessages` would leak into the value on first render.
326 const activeStructuredPart = createMemo<StructuredOutputPart | null>(() => {
327 const list = messages()
328 let lastUserIndex = -1
329 for (let i = list.length - 1; i >= 0; i--) {
330 if (list[i]?.role === 'user') {
331 lastUserIndex = i
332 break
333 }
334 }
335 if (lastUserIndex === -1) return null
336 for (let i = list.length - 1; i > lastUserIndex; i--) {
337 const m = list[i]
338 if (m?.role !== 'assistant') continue
339 const part = m.parts.find(
340 (p): p is StructuredOutputPart => p.type === 'structured-output',
341 )
342 if (part) return part
343 }
344 return null
345 })
346
347 const partial = createMemo<Partial>(() => {
348 const part = activeStructuredPart()
349 if (!part) return {} as Partial
350 const v = part.partial ?? part.data
351 return (v ?? {}) as Partial
352 })
353
354 const final = createMemo<Final | null>(() => {
355 const part = activeStructuredPart()
356 if (!part || part.status !== 'complete') return null
357 return part.data as Final
358 })
359
360 // partial / final are runtime-tracked unconditionally; the conditional
361 // return type hides them when no `outputSchema` is supplied.
362 // 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
363 return {
364 messages,
365 queue: pick('queue'),
366 sendMessage,
367 append,
368 reload,
369 stop,
370 isLoading: pick('isLoading'),
371 hasOlderMessages: pick('hasOlderMessages'),
372 loadOlderMessages,
373 error: pick('error'),
374 status: pick('status'),
375 isSubscribed: pick('isSubscribed'),
376 connectionStatus: pick('connectionStatus'),
377 sessionGenerating: pick('sessionGenerating'),
378 isHydrating: pick('isHydrating'),
379 setMessages: setMessagesManually,
380 clear,
381 addToolResult,
382 addToolApprovalResponse,
383 cancelQueued,
384 runId: pick('runId'),
385 interrupts,
386 pendingInterrupts,
387 interruptErrors,
388 resuming,
389 resolveInterrupts,
390 cancelInterrupts,
391 retryInterrupts,
392 resumeInterruptsUnsafe,
393 resumeInterrupts,
394 partial,
395 final,
396 } as unknown as UseChatReturn<TTools, TSchema, TInterrupts>
397}