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