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

use-chat.ts

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