Open History to see the last commit
1import { GenerationClient } from '@tanstack/ai-client'
2import { createGenerationDevtoolsBridge } from '@tanstack/ai-client/devtools'
3import { onMounted, onScopeDispose, readonly, shallowRef, watch } from 'vue'
4import type { StreamChunk } from '@tanstack/ai'
5import type {
6 AIDevtoolsDisplayOptions,
7 ConnectConnectionAdapter,
8 GenerationClientOptions,
9 GenerationClientState,
10 GenerationFetcher,
11 GenerationPersistenceOptions,
12 GenerationRestoredResult,
13 InferGenerationOutputFromReturn,
14} from '@tanstack/ai-client'
15import type { ByokClient } from '@tanstack/ai-client/byok'
16import type { ProviderId } from '@tanstack/ai/byok'
17import type { DeepReadonly, ShallowRef } from 'vue'
18
19/**
20 * Options for the useGeneration hook.
21 *
22 * Accepts either a `connection` (streaming transport) or a `fetcher` (direct async call).
23 *
24 * @template TInput - The input type for the generation request
25 * @template TResult - The result type returned by the generation
26 * @template TOutput - The output type after optional transform (defaults to TResult)
27 */
28export interface UseGenerationOptions<TInput, TResult, TOutput = TResult> {
29 /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */
30 connection?: ConnectConnectionAdapter
31 /** Direct async function for one-shot generation (no streaming protocol needed) */
32 fetcher?: GenerationFetcher<TInput, TResult>
33 /** Additional body parameters to send with connect-based adapter requests */
34 body?: Record<string, any>
35 /** Optional BYOK keyring. Keys go in `x-byok-*` headers, never the body. */
36 byok?: ByokClient
37 /** Optional provider id. If it returns a slug, only that key is sent. If no slug resolves (`byokProvider`, then `body.provider`), generate throws. */
38 byokProvider?: () => ProviderId | undefined
39 /** Display options for TanStack AI Devtools. */
40 devtools?: AIDevtoolsDisplayOptions
41 /**
42 * How this generation persists across reloads.
43 * - Omit / `false`: ephemeral, in-memory only.
44 * - `true`: server-driven — on mount the client hydrates the last generation
45 * for its `threadId` from the server (needs a connection with a
46 * `hydrateGeneration` handler) and repaints it; it never auto-starts a run.
47 */
48 persistence?: boolean
49 /**
50 * The **scope** this generation belongs to: a stable, app-chosen name for the
51 * slot successive runs fill — not a link to a chat conversation.
52 *
53 * The hook starts empty and produces many runs over its life; each gets its
54 * own `runId`, but all belong to one scope. Persistence keys on this, so
55 * derive it from your own domain and keep it identical across reloads (e.g.
56 * `` `video-${videoId}-start-frame` ``). It is also sent as the AG-UI thread
57 * id on the wire, which the protocol requires.
58 *
59 * **Required whenever `persistence` is set** — an app that cannot name the
60 * scope has nothing to restore to. Optional for ephemeral generations. If
61 * omitted, the client mints a wire id after mount.
62 */
63 threadId?: string
64 /**
65 * Server-driven hydration handler for `persistence: true` when the
66 * connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /
67 * `rpcStream()` adapter built without handlers) — typically a one-line
68 * server-function call. The connection's own handler takes precedence.
69 */
70 hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration']
71 /**
72 * Re-attach handler that replays a run still generating to completion on
73 * mount, when the connection doesn't carry one. Without it, a restored
74 * `running` snapshot surfaces as an (interrupted) error. The connection's
75 * own handler takes precedence.
76 */
77 joinRun?: ConnectConnectionAdapter['joinRun']
78 /**
79 * Callback when a result is received. Can optionally return a transformed value.
80 *
81 * - Return a non-null value to transform and store it as the result
82 * - Return `null` to keep the previous result unchanged
83 * - Return nothing (`void`) to store the raw result as-is
84 */
85 onResult?: (result: TResult) => TOutput | null | void
86 /** Callback when an error occurs */
87 onError?: (error: Error) => void
88 /** Callback when progress is reported (0-100) */
89 onProgress?: (progress: number, message?: string) => void
90 /** Callback for each stream chunk (connect-based adapter mode only) */
91 onChunk?: (chunk: StreamChunk) => void
92 /**
93 * @internal Rebuild a typed result from a restored snapshot, injected by each
94 * specialized composable (image / speech / audio / transcription / summarize).
95 * Forwarded to the client so a server-hydrate restore repaints `result`.
96 */
97 reconstructResult?: (restored: GenerationRestoredResult) => TResult | null
98}
99
100/**
101 * Return type for the useGeneration hook.
102 *
103 * @template TOutput - The output type (after optional transform)
104 * @template TInput - The input type accepted by `generate` (defaults to any object)
105 */
106export interface UseGenerationReturn<
107 TOutput,
108 TInput extends Record<string, any> = Record<string, any>,
109> {
110 /** Trigger a generation request */
111 generate: (input: TInput) => Promise<void>
112 /** The generation result, or null if not yet generated */
113 result: DeepReadonly<ShallowRef<TOutput | null>>
114 /** Whether a generation is currently in progress */
115 isLoading: DeepReadonly<ShallowRef<boolean>>
116 /** Current error, if any */
117 error: DeepReadonly<ShallowRef<Error | undefined>>
118 /** Current state of the generation client */
119 status: DeepReadonly<ShallowRef<GenerationClientState>>
120 /** Abort the current generation */
121 stop: () => void
122 /** Clear result, error, and return to idle */
123 reset: () => void
124 /**
125 * The id of the generation job currently running, or `null` when nothing is in
126 * flight. Each call to `generate` is one job with its own id. Pass it to your
127 * own endpoint to cancel or poll the provider job — `stop()` only aborts the
128 * local stream, it does not stop work already running on the provider.
129 */
130 runId: DeepReadonly<ShallowRef<string | null>>
131}
132
133/**
134 * Generic Vue composable for one-shot generation tasks.
135 *
136 * This is the base composable used by `useGenerateImage`, `useGenerateSpeech`,
137 * `useTranscription`, and `useSummarize`. You can also use it directly
138 * for custom generation types.
139 *
140 * @template TInput - The input type for the generation request
141 * @template TResult - The result type returned by the generation
142 *
143 * @example
144 * ```vue
145 * <script setup>
146 * import { useGeneration } from '@tanstack/ai-vue'
147 * import { fetchServerSentEvents } from '@tanstack/ai-client'
148 *
149 * const { generate, result, isLoading } = useGeneration({
150 * connection: fetchServerSentEvents('/api/generate/custom'),
151 * })
152 * </script>
153 * ```
154 */
155// `TTransformed` infers from the `onResult` return position (a covariant
156// inference site that works even for an optional nested property), which types
157// the callback parameter as `TResult` and narrows `result`. Inferring the
158// whole callback as a defaulted type parameter instead collapses to the
159// default, leaving the parameter `any` — a hard error under `strict`. See
160// issue #848.
161export function useGeneration<
162 TInput extends Record<string, any>,
163 TResult,
164 TTransformed = void,
165>(
166 options: Omit<
167 UseGenerationOptions<TInput, TResult>,
168 'onResult' | 'persistence' | 'threadId'
169 > & {
170 onResult?: (result: TResult) => TTransformed
171 } & GenerationPersistenceOptions,
172): UseGenerationReturn<
173 InferGenerationOutputFromReturn<TResult, TTransformed>,
174 TInput
175> {
176 type TOutput = InferGenerationOutputFromReturn<TResult, TTransformed>
177
178 const result = shallowRef<TOutput | null>(null)
179 const isLoading = shallowRef(false)
180 const error = shallowRef<Error | undefined>(undefined)
181 const status = shallowRef<GenerationClientState>('idle')
182 const runId = shallowRef<string | null>(null)
183 let disposed = false
184
185 // Conditional spread on `body`: `GenerationClientOptions.body` is a strict
186 // optional (`body?: Record<string, any>`), and under EOPT we must omit the
187 // key when absent rather than assign `undefined`.
188 const clientOptions: Omit<
189 GenerationClientOptions<TInput, TResult, TOutput>,
190 'persistence' | 'threadId'
191 > = {
192 body: options.body,
193 ...(options.hydrateGeneration !== undefined && {
194 hydrateGeneration: options.hydrateGeneration,
195 }),
196 ...(options.joinRun !== undefined && { joinRun: options.joinRun }),
197 ...(options.byok !== undefined && { byok: options.byok }),
198 byokProvider: () => options.byokProvider?.(),
199 ...(options.reconstructResult
200 ? { reconstructResult: options.reconstructResult }
201 : {}),
202 devtoolsBridgeFactory: createGenerationDevtoolsBridge,
203 devtools: {
204 ...options.devtools,
205 framework: 'vue',
206 hookName: 'useGeneration',
207 },
208 // The transform's raw return type (`TTransformed`) and the stored output
209 // (`TOutput`, with null/void/undefined stripped) are identical at runtime;
210 // the cast bridges the relationship that the conditional type hides.
211 onResult: ((r: TResult) => options.onResult?.(r)) as (
212 result: TResult,
213 ) => TOutput | null | void,
214 onError: (e: Error) => {
215 if (!disposed) options.onError?.(e)
216 },
217 onProgress: (p: number, m?: string) => {
218 if (!disposed) options.onProgress?.(p, m)
219 },
220 onChunk: (c: StreamChunk) => {
221 if (!disposed) options.onChunk?.(c)
222 },
223 onResultChange: (r: TOutput | null) => {
224 if (disposed) return
225 result.value = r
226 },
227 onLoadingChange: (l: boolean) => {
228 if (disposed) return
229 isLoading.value = l
230 },
231 onErrorChange: (e: Error | undefined) => {
232 if (disposed) return
233 error.value = e
234 },
235 onStatusChange: (s: GenerationClientState) => {
236 if (disposed) return
237 status.value = s
238 },
239 onResumeStateChange: (rs) => {
240 if (disposed) return
241 runId.value = rs?.runId ?? null
242 },
243 }
244
245 const persistenceProps =
246 typeof options.threadId === 'string' && options.persistence
247 ? {
248 persistence: options.persistence,
249 threadId: options.threadId,
250 }
251 : {
252 ...(options.threadId !== undefined && {
253 threadId: options.threadId,
254 }),
255 }
256
257 let client: GenerationClient<TInput, TResult, TOutput>
258
259 if (options.connection) {
260 client = new GenerationClient<TInput, TResult, TOutput>({
261 ...clientOptions,
262 ...persistenceProps,
263 connection: options.connection,
264 })
265 } else if (options.fetcher) {
266 client = new GenerationClient<TInput, TResult, TOutput>({
267 ...clientOptions,
268 ...persistenceProps,
269 fetcher: options.fetcher,
270 })
271 } else {
272 throw new Error(
273 'useGeneration requires either a connection or fetcher option',
274 )
275 }
276
277 // Sync body changes to the client.
278 // Conditional spread: `updateOptions` declares `body?: Record<string, any>`
279 // (strict optional) and rejects explicit `undefined` under EOPT.
280 watch(
281 () => options.body,
282 (newBody) => {
283 client.updateOptions({
284 ...(newBody !== undefined && { body: newBody }),
285 })
286 },
287 )
288
289 // Mount devtools only. Generation runs are never auto-started on mount —
290 // persisted state is read-only for display.
291 onMounted(() => {
292 client.mountDevtools()
293 })
294
295 // Cleanup on scope dispose: stop any in-flight requests and unregister devtools
296 onScopeDispose(() => {
297 disposed = true
298 client.dispose()
299 })
300
301 const generate = async (input: TInput) => {
302 await client.generate(input)
303 }
304
305 const stop = () => {
306 client.stop()
307 }
308
309 const reset = () => {
310 client.reset()
311 }
312
313 return {
314 generate,
315 // `readonly()` distributes `DeepReadonly`/`UnwrapNestedRefs` over the
316 // `TOutput` conditional, which TS can't prove equal to the declared
317 // `DeepReadonly<ShallowRef<TOutput | null>>` while `TTransformed` is free.
318 // They are identical at runtime; the cast restores the declared shape.
319 result: readonly(result) as UseGenerationReturn<TOutput>['result'],
320 isLoading: readonly(isLoading),
321 error: readonly(error),
322 status: readonly(status),
323 stop,
324 reset,
325 runId: readonly(runId),
326 }
327}