Open History to see the last commit
1import { GenerationClient } from '@tanstack/ai-client'
2import { createGenerationDevtoolsBridge } from '@tanstack/ai-client/devtools'
3import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
4import type { StreamChunk } from '@tanstack/ai'
5import type {
6 AIDevtoolsClientMetadata,
7 AIDevtoolsDisplayOptions,
8 ConnectConnectionAdapter,
9 GenerationClientOptions,
10 GenerationClientState,
11 GenerationFetcher,
12 GenerationPersistenceOptions,
13 GenerationRestoredResult,
14 InferGenerationOutputFromReturn,
15} from '@tanstack/ai-client'
16import type { ByokClient } from '@tanstack/ai-client/byok'
17import type { ProviderId } from '@tanstack/ai/byok'
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 hook (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: TOutput | null
114 /** Whether a generation is currently in progress */
115 isLoading: boolean
116 /** Current error, if any */
117 error: Error | undefined
118 /** Current state of the generation client */
119 status: 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: string | null
131}
132
133/**
134 * Generic React hook for one-shot generation tasks.
135 *
136 * This is the base hook 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 * ```tsx
145 * const { generate, result, isLoading } = useGeneration<MyInput, MyResult>({
146 * connection: fetchServerSentEvents('/api/generate/custom'),
147 * })
148 *
149 * await generate({ prompt: 'Hello' })
150 * ```
151 */
152// `TTransformed` infers from the `onResult` return position (a covariant
153// inference site that works even for an optional nested property), which types
154// the callback parameter as `TResult` and narrows `result`. Inferring the
155// whole callback as a defaulted type parameter instead collapses to the
156// default, leaving the parameter `any` — a hard error under `strict`. See
157// issue #848.
158export function useGeneration<
159 TInput extends Record<string, any>,
160 TResult,
161 TTransformed = void,
162>(
163 options: Omit<
164 UseGenerationOptions<TInput, TResult>,
165 'onResult' | 'persistence' | 'threadId'
166 > & {
167 onResult?: (result: TResult) => TTransformed
168 } & GenerationPersistenceOptions,
169): UseGenerationReturn<
170 InferGenerationOutputFromReturn<TResult, TTransformed>,
171 TInput
172> {
173 return useGenerationWithDevtoolsIdentity<TInput, TResult, TTransformed>(
174 options,
175 { hookName: 'useGeneration' },
176 )
177}
178
179interface GenerationDevtoolsIdentity {
180 hookName: AIDevtoolsClientMetadata['hookName']
181 outputKind?: AIDevtoolsClientMetadata['outputKind']
182}
183
184/** @internal */
185export function useGenerationWithDevtoolsIdentity<
186 TInput extends Record<string, any>,
187 TResult,
188 TTransformed = void,
189>(
190 options: Omit<
191 UseGenerationOptions<TInput, TResult>,
192 'onResult' | 'persistence' | 'threadId'
193 > & {
194 onResult?: (result: TResult) => TTransformed
195 } & GenerationPersistenceOptions,
196 devtoolsIdentity: GenerationDevtoolsIdentity,
197): UseGenerationReturn<
198 InferGenerationOutputFromReturn<TResult, TTransformed>,
199 TInput
200> {
201 type TOutput = InferGenerationOutputFromReturn<TResult, TTransformed>
202 const hookId = useId()
203 // The hook identity is `threadId`. `hookId` is only a React recreation key.
204 const clientIdentity = options.threadId ?? hookId
205
206 const [result, setResult] = useState<TOutput | null>(null)
207 const [isLoading, setIsLoading] = useState(false)
208 const [error, setError] = useState<Error | undefined>(undefined)
209 const [status, setStatus] = useState<GenerationClientState>('idle')
210 const [runId, setRunId] = useState<string | null>(null)
211
212 const optionsRef = useRef(options)
213 optionsRef.current = options
214 const disposedRef = useRef(false)
215
216 const client = useMemo(() => {
217 const opts = optionsRef.current
218
219 // Conditional spread for `body` (strict-optional in target;
220 // local source is `Record<string, any> | undefined`). Callbacks
221 // wrap optional ones in non-returning bodies so `?.()`'s
222 // implicit `undefined` doesn't pollute the function return type.
223 const clientOptions: Omit<
224 GenerationClientOptions<TInput, TResult, TOutput>,
225 'persistence' | 'threadId'
226 > = {
227 body: opts.body,
228 ...(opts.hydrateGeneration !== undefined && {
229 hydrateGeneration: opts.hydrateGeneration,
230 }),
231 ...(opts.joinRun !== undefined && { joinRun: opts.joinRun }),
232 ...(opts.byok !== undefined && { byok: opts.byok }),
233 byokProvider: () => optionsRef.current.byokProvider?.(),
234 ...(opts.reconstructResult
235 ? { reconstructResult: opts.reconstructResult }
236 : {}),
237 devtoolsBridgeFactory: createGenerationDevtoolsBridge,
238 devtools: {
239 ...opts.devtools,
240 framework: 'react',
241 hookName: devtoolsIdentity.hookName,
242 ...(devtoolsIdentity.outputKind !== undefined && {
243 outputKind: devtoolsIdentity.outputKind,
244 }),
245 },
246 // The transform's raw return type (`TTransformed`) and the stored output
247 // (`TOutput`, with null/void/undefined stripped) are identical at runtime;
248 // the cast bridges the relationship that the conditional type hides.
249 onResult: ((r: TResult) => optionsRef.current.onResult?.(r)) as (
250 result: TResult,
251 ) => TOutput | null | void,
252 onError: (e: Error) => {
253 if (!disposedRef.current) optionsRef.current.onError?.(e)
254 },
255 onProgress: (p: number, m?: string) => {
256 if (!disposedRef.current) optionsRef.current.onProgress?.(p, m)
257 },
258 onChunk: (c: StreamChunk) => {
259 if (!disposedRef.current) optionsRef.current.onChunk?.(c)
260 },
261 onResultChange: (r) => {
262 if (!disposedRef.current) setResult(r)
263 },
264 onLoadingChange: (l) => {
265 if (!disposedRef.current) setIsLoading(l)
266 },
267 onErrorChange: (e) => {
268 if (!disposedRef.current) setError(e)
269 },
270 onStatusChange: (s) => {
271 if (!disposedRef.current) setStatus(s)
272 },
273 onResumeStateChange: (rs) => {
274 if (!disposedRef.current) setRunId(rs?.runId ?? null)
275 },
276 }
277
278 const persistenceProps =
279 typeof opts.threadId === 'string' && opts.persistence
280 ? {
281 persistence: opts.persistence,
282 threadId: opts.threadId,
283 }
284 : {
285 ...(opts.threadId !== undefined && { threadId: opts.threadId }),
286 }
287
288 if (opts.connection) {
289 return new GenerationClient<TInput, TResult, TOutput>({
290 ...clientOptions,
291 ...persistenceProps,
292 connection: opts.connection,
293 })
294 }
295
296 if (opts.fetcher) {
297 return new GenerationClient<TInput, TResult, TOutput>({
298 ...clientOptions,
299 ...persistenceProps,
300 fetcher: opts.fetcher,
301 })
302 }
303
304 throw new Error(
305 'useGeneration requires either a connection or fetcher option',
306 )
307 }, [clientIdentity, hookId])
308
309 // Sync body changes without recreating client
310 useEffect(() => {
311 // Conditional spread: target uses strict-optional `body?: T`.
312 client.updateOptions({
313 ...(options.body !== undefined && { body: options.body }),
314 })
315 }, [client, options.body])
316
317 // Mount devtools and clean up on unmount. Generation runs are never
318 // auto-started on mount — persisted state is only displayed. Mounting
319 // revives the client after a StrictMode dispose → remount replay.
320 useEffect(() => {
321 disposedRef.current = false
322 client.mountDevtools()
323
324 return () => {
325 disposedRef.current = true
326 client.dispose()
327 }
328 }, [client])
329
330 const generate = useCallback(
331 async (input: TInput) => {
332 await client.generate(input)
333 },
334 [client],
335 )
336
337 const stop = useCallback(() => {
338 client.stop()
339 }, [client])
340
341 const reset = useCallback(() => {
342 client.reset()
343 }, [client])
344
345 return {
346 generate,
347 result,
348 isLoading,
349 error,
350 status,
351 stop,
352 reset,
353 runId,
354 }
355}