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