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