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