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

use-chat.ts

398 lines12.4 KB

1import { ChatClient } from '@tanstack/ai-client'
2import { createChatDevtoolsBridge } from '@tanstack/ai-client/devtools'
3import {
4 computed,
5 onMounted,
6 onScopeDispose,
7 readonly,
8 shallowRef,
9 toValue,
10 watch,
11} from 'vue'
12import type {
13 AnyClientTool,
14 InterruptDefinition,
15 InferSchemaType,
16 ModelMessage,
17 RunAgentResumeItem,
18 SchemaInput,
19 StreamChunk,
20} from '@tanstack/ai'
21import type {
22 ResolvableChatInterrupt,
23 ChatResumeState,
24 InferredClientContext,
25 SendMessageOptions,
26 StructuredOutputPart,
27} from '@tanstack/ai-client'
28import type {
29 DeepPartial,
30 MultimodalContent,
31 UIMessage,
32 UseChatOptions,
33 UseChatReturn,
34} from './types'
35​
36export function useChat<
37 const TTools extends ReadonlyArray<AnyClientTool> = any,
38 TSchema extends SchemaInput | undefined = undefined,
39 TContext = InferredClientContext<TTools>,
40 const TInterrupts extends ReadonlyArray<
41 InterruptDefinition<any, any, any, any>
42 > = readonly [],
43>(
44 options: UseChatOptions<
45 TTools,
46 TSchema,
47 TContext,
48 TInterrupts
49 > = {} as UseChatOptions<TTools, TSchema, TContext, TInterrupts>,
50): UseChatReturn<TTools, TSchema, TInterrupts> {
51 // Structured-output `partial` / `final` are derived from `messages` —
52 // specifically from the structured-output part on the latest assistant
53 // message (the one after the most recent user message). This keeps
54 // history coherent: every assistant turn carries its own typed
55 // structured-output part, and the hook-level sugar always reflects the
56 // freshest turn without a separate reset signal.
57 type Partial = DeepPartial<InferSchemaType<NonNullable<TSchema>>>
58 type Final = InferSchemaType<NonNullable<TSchema>>
59​
60 // Create ChatClient instance with callbacks to sync state.
61 // Every user-provided callback is wrapped so the LATEST `options.xxx` value
62 // is read at call time. Direct assignment would freeze the callback to the
63 // reference we saw at setup time; the wrapper lets reactive `options` or
64 // in-place mutations propagate. When the user clears a callback (sets it to
65 // undefined), `?.` no-ops — unlike `client.updateOptions`, which silently
66 // skips undefined and leaves the old callback installed.
67 //
68 // Conditional spreads for `initialMessages`, `body`, `forwardedProps`, and
69 // `tools`: the ChatClient target declares those as strict-optional
70 // (`field?: T`), so under `exactOptionalPropertyTypes` we omit the key when
71 // the source value is `undefined` instead of assigning `undefined`.
72 const transport = options.connection
73 ? { connection: options.connection }
74 : { fetcher: options.fetcher }
75​
76 // The hook's identity is its `threadId`. When no `threadId` is given the
77 // client mints one after mount, so an ephemeral chat still works but is not
78 // restored on reload.
79 const client = new ChatClient<TTools, TContext, TInterrupts>({
80 devtoolsBridgeFactory: createChatDevtoolsBridge,
81 ...transport,
82 ...(options.initialMessages !== undefined && {
83 initialMessages: options.initialMessages,
84 }),
85 ...(typeof options.threadId === 'string' && options.persistence === true
86 ? {
87 persistence: true,
88 threadId: options.threadId,
89 ...(options.history !== undefined && {
90 history: options.history,
91 }),
92 }
93 : typeof options.threadId === 'string' && options.persistence
94 ? {
95 persistence: options.persistence,
96 threadId: options.threadId,
97 }
98 : {
99 ...(options.threadId !== undefined && {
100 threadId: options.threadId,
101 }),
102 }),
103 ...(options.initialResumeSnapshot !== undefined && {
104 initialResumeSnapshot: options.initialResumeSnapshot,
105 }),
106 ...(options.body !== undefined && { body: options.body }),
107 ...(options.forwardedProps !== undefined && {
108 forwardedProps: options.forwardedProps,
109 }),
110 ...(options.byok !== undefined && { byok: options.byok }),
111 byokProvider: () => options.byokProvider?.(),
112 ...(options.context !== undefined && { context: options.context }),
113 devtools: {
114 ...options.devtools,
115 framework: 'vue',
116 hookName: 'useChat',
117 outputKind: options.outputSchema ? 'structured' : 'chat',
118 },
119 onResponse: (response) => options.onResponse?.(response),
120 onChunk: (chunk: StreamChunk) => {
121 options.onChunk?.(chunk)
122 },
123 onFinish: (message) => {
124 options.onFinish?.(message)
125 },
126 onError: (err) => {
127 options.onError?.(err)
128 },
129 tools: toValue(options.tools),
130 ...(options.interrupts !== undefined && {
131 interrupts: options.interrupts,
132 }),
133 onCustomEvent: (eventType, data, context) =>
134 options.onCustomEvent?.(eventType, data, context),
135 ...(options.streamProcessor !== undefined && {
136 streamProcessor: options.streamProcessor,
137 }),
138 ...(options.queue !== undefined && { queue: options.queue }),
139 onInterruptStateChange: (nextInterruptState, context) => {
140 options.onInterruptStateChange?.(nextInterruptState, context)
141 },
142 })
143​
144 // One shallow ref: the snapshot is frozen and replaced on every change.
145 const snapshot = shallowRef(client.getSnapshot())
146 onScopeDispose(
147 client.subscribeSnapshot(() => {
148 snapshot.value = client.getSnapshot()
149 }),
150 )
151 const pick = <TKey extends keyof typeof snapshot.value>(key: TKey) =>
152 readonly(computed(() => snapshot.value[key]))
153​
154 // Sync body / forwardedProps changes to the client.
155 // Both populate the same wire payload; `forwardedProps` is preferred
156 // and `body` is deprecated but still supported.
157 // Conditional spread: `updateOptions` declares strict-optional fields and
158 // rejects explicit `undefined` under EOPT.
159 watch(
160 () =>
161 [
162 options.body,
163 options.forwardedProps,
164 options.context,
165 options.queue,
166 ] as const,
167 ([newBody, newForwardedProps, newContext, newQueue]) => {
168 client.updateOptions({
169 body: newBody,
170 ...(newForwardedProps !== undefined && {
171 forwardedProps: newForwardedProps,
172 }),
173 context: newContext,
174 ...(newQueue !== undefined && { queue: newQueue }),
175 })
176 },
177 )
178​
179 watch(
180 () => toValue(options.tools),
181 (tools) => {
182 if (tools !== undefined) client.updateOptions({ tools })
183 },
184 )
185​
186 watch(
187 () => options.live,
188 (live) => {
189 if (live) {
190 client.subscribe()
191 } else {
192 client.unsubscribe()
193 }
194 },
195 { immediate: true },
196 )
197​
198 onMounted(() => {
199 // START TAILING HERE, not in the constructor. A client is idle until a view
200 // attaches it, so a client that gets built and thrown away never opens a
201 // connection — an unreachable stream would hold one of the browser's ~6
202 // connections per origin until the page reloaded.
203 client.attach()
204 client.mountDevtools()
205 })
206​
207 // Cleanup on unmount: stop any in-flight requests
208 // Note: client.stop() is safe to call even if nothing is in progress
209 onScopeDispose(() => {
210 // Release the connection first: the counterpart of the `attach` above. It keeps
211 // the transcript and resume pointer, so a later mount picks the run back up.
212 client.detach()
213 if (options.live) {
214 client.unsubscribe()
215 } else {
216 client.stop()
217 }
218 client.dispose()
219 })
220​
221 // Callback options are read through `options.xxx` at call time, so reactive
222 // or mutated options propagate without recreating the client.
223​
224 const sendMessage = async (
225 content: string | MultimodalContent,
226 sendOptions?: SendMessageOptions,
227 ) => {
228 await client.sendMessage(content, undefined, sendOptions)
229 }
230​
231 const cancelQueued = (id: string) => client.cancelQueued(id)
232​
233 const append = async (message: ModelMessage | UIMessage<TTools>) => {
234 await client.append(message)
235 }
236​
237 const reload = async () => {
238 await client.reload()
239 }
240​
241 const loadOlderMessages = async () => {
242 await client.loadOlderMessages()
243 }
244​
245 const stop = () => {
246 client.stop()
247 }
248​
249 const clear = () => {
250 client.clear()
251 }
252​
253 const setMessagesManually = (
254 newMessages: ReadonlyArray<UIMessage<TTools>>,
255 ) => {
256 client.setMessagesManually(newMessages)
257 }
258​
259 const addToolResult = async (result: {
260 toolCallId: string
261 tool: string
262 output: any
263 state?: 'output-available' | 'output-error'
264 errorText?: string
265 }) => {
266 await client.addToolResult(result)
267 }
268​
269 const addToolApprovalResponse = async (response: {
270 id: string
271 approved: boolean
272 }) => {
273 await client.addToolApprovalResponse(response)
274 }
275​
276 const resumeInterrupts = async (
277 resumeItems: Array<RunAgentResumeItem>,
278 state?: ChatResumeState,
279 ) => {
280 return await client.resumeInterrupts(resumeItems, state)
281 }
282​
283 const interrupts = computed(() => snapshot.value.interruptState.interrupts)
284 const pendingInterrupts = computed(
285 () => snapshot.value.interruptState.interrupts,
286 )
287 const interruptErrors = computed(
288 () => snapshot.value.interruptState.interruptErrors,
289 )
290 const resuming = computed(() => snapshot.value.interruptState.resuming)
291​
292 const resolveInterrupts = (
293 resolution:
294 | boolean
295 | ((
296 interrupt: ResolvableChatInterrupt<TTools, TInterrupts>,
297 ) => undefined),
298 ) => {
299 if (typeof resolution === 'boolean') {
300 client.resolveInterrupts(resolution)
301 } else {
302 client.resolveInterrupts(resolution)
303 }
304 }
305​
306 const cancelInterrupts = () => {
307 client.cancelInterrupts()
308 }
309​
310 const retryInterrupts = () => {
311 client.retryInterrupts()
312 }
313​
314 const resumeInterruptsUnsafe = (
315 resumeItems: Array<RunAgentResumeItem>,
316 state?: ChatResumeState,
317 ) => client.resumeInterruptsUnsafe(resumeItems, state)
318​
319 // The "active" structured-output part is the one on the assistant message
320 // that follows the latest user message. No such message exists between
321 // sendMessage() and the first chunk, so partial/final naturally read as
322 // cleared. If there is no user message yet (e.g. initialMessages only has
323 // a stale assistant turn), we return null rather than scanning history —
324 // otherwise a `final` from a previous session would leak into the value
325 // on first render.
326 const activeStructuredPart = computed<StructuredOutputPart | null>(() => {
327 const list = snapshot.value.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 = computed<Partial>(() => {
348 const part = activeStructuredPart.value
349 if (!part) return {} as Partial
350 const v = part.partial ?? part.data
351 return (v ?? {}) as Partial
352 })
353​
354 const final = computed<Final | null>(() => {
355 const part = activeStructuredPart.value
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 (UseChatReturn<TTools, TSchema>) hides them from callers that
362 // didn't supply `outputSchema`.
363 // oxlint-disable-next-line eslint-js/no-restricted-syntax -- composable return shape diverges from conditional UseChatReturn<TTools, TSchema>; TS can't structurally narrow the TSchema-gated partial/final refs
364 return {
365 messages: pick('messages'),
366 sendMessage,
367 queue: pick('queue'),
368 cancelQueued,
369 append,
370 reload,
371 stop,
372 isLoading: pick('isLoading'),
373 hasOlderMessages: pick('hasOlderMessages'),
374 loadOlderMessages,
375 error: pick('error'),
376 status: pick('status'),
377 isSubscribed: pick('isSubscribed'),
378 connectionStatus: pick('connectionStatus'),
379 sessionGenerating: pick('sessionGenerating'),
380 isHydrating: pick('isHydrating'),
381 setMessages: setMessagesManually,
382 clear,
383 addToolResult,
384 addToolApprovalResponse,
385 runId: pick('runId'),
386 interrupts: readonly(interrupts),
387 pendingInterrupts: readonly(pendingInterrupts),
388 interruptErrors: readonly(interruptErrors),
389 resuming: readonly(resuming),
390 resolveInterrupts,
391 cancelInterrupts,
392 retryInterrupts,
393 resumeInterruptsUnsafe,
394 resumeInterrupts,
395 partial: readonly(partial),
396 final: readonly(final),
397 } as unknown as UseChatReturn<TTools, TSchema, TInterrupts>