Open History to see the last commit
1import { VideoGenerationClient } from '@tanstack/ai-client'
2import { createVideoDevtoolsBridge } 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 AIDevtoolsDisplayOptions,
14 ConnectConnectionAdapter,
15 GenerationClientState,
16 GenerationFetcher,
17 GenerationPersistenceOptions,
18 InferGenerationOutputFromReturn,
19 VideoGenerateInput,
20 VideoGenerateResult,
21 VideoGenerationClientOptions,
22 VideoStatusInfo,
23} from '@tanstack/ai-client'
24import type { ByokClient } from '@tanstack/ai-client/byok'
25import type { ProviderId } from '@tanstack/ai/byok'
26
27/**
28 * Options for the useGenerateVideo hook.
29 */
30export interface UseGenerateVideoOptions<TOutput = VideoGenerateResult> {
31 /** Connect-based adapter for streaming transport (server handles polling) */
32 connection?: ConnectConnectionAdapter
33 /** Direct async function that returns a completed video result */
34 fetcher?: GenerationFetcher<VideoGenerateInput, VideoGenerateResult>
35 /** Additional body parameters to send with connect-based adapter requests */
36 body?: Record<string, any>
37 /** Optional BYOK keyring. Keys go in `x-byok-*` headers, never the body. */
38 byok?: ByokClient
39 /** Optional provider id. If it returns a slug, only that key is sent. If no slug resolves (`byokProvider`, then `body.provider`), generate throws. */
40 byokProvider?: () => ProviderId | undefined
41 /** Display options for TanStack AI Devtools. */
42 devtools?: AIDevtoolsDisplayOptions
43 /**
44 * How this generation persists across reloads.
45 * - Omit / `false`: ephemeral, in-memory only.
46 * - `true`: server-driven — on mount the client hydrates the last generation
47 * for its `threadId` from the server (needs a connection with a
48 * `hydrateGeneration` handler) and repaints it; it never auto-starts a run.
49 */
50 persistence?: boolean
51 /**
52 * The **scope** this generation belongs to: a stable, app-chosen name for the
53 * slot successive runs fill — not a link to a chat conversation.
54 *
55 * The hook starts empty and produces many runs over its life; each gets its
56 * own `runId`, but all belong to one scope. Persistence keys on this, so
57 * derive it from your own domain and keep it identical across reloads (e.g.
58 * `` `video-${videoId}-start-frame` ``). It is also sent as the AG-UI thread
59 * id on the wire, which the protocol requires.
60 *
61 * **Required whenever `persistence` is set** — an app that cannot name the
62 * scope has nothing to restore to. Optional for ephemeral generations. If
63 * omitted, the client mints a wire id after mount.
64 */
65 threadId?: string
66 /**
67 * Server-driven hydration handler for `persistence: true` when the
68 * connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /
69 * `rpcStream()` adapter built without handlers) — typically a one-line
70 * server-function call. The connection's own handler takes precedence.
71 */
72 hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration']
73 /**
74 * Re-attach handler that replays a run still generating to completion on
75 * mount, when the connection doesn't carry one. Without it, a restored
76 * `running` snapshot surfaces as an (interrupted) error. The connection's
77 * own handler takes precedence.
78 */
79 joinRun?: ConnectConnectionAdapter['joinRun']
80 /**
81 * Callback when video generation completes. Can optionally return a transformed value.
82 *
83 * - Return a non-null value to transform and store it as the result
84 * - Return `null` to keep the previous result unchanged
85 * - Return nothing (`void`) to store the raw result as-is
86 */
87 onResult?: (result: VideoGenerateResult) => TOutput | null | void
88 /** Callback when an error occurs */
89 onError?: (error: Error) => void
90 /** Callback when progress is reported (0-100) */
91 onProgress?: (progress: number, message?: string) => void
92 /** Callback when a video job is created */
93 onJobCreated?: (jobId: string) => void
94 /** Callback on each status update */
95 onStatusUpdate?: (status: VideoStatusInfo) => void
96 /** Callback for each stream chunk (connect-based adapter mode only) */
97 onChunk?: (chunk: StreamChunk) => void
98}
99
100/**
101 * Return type for the useGenerateVideo hook.
102 *
103 * @template TOutput - The output type (after optional transform)
104 */
105export interface UseGenerateVideoReturn<TOutput = VideoGenerateResult> {
106 /** Trigger video generation */
107 generate: (input: VideoGenerateInput) => Promise<void>
108 /** The final video result (with URL), or null */
109 result: TOutput | null
110 /** The current job ID, or null */
111 jobId: string | null
112 /** Current video generation status info, or null */
113 videoStatus: VideoStatusInfo | null
114 /** Whether generation/polling is in progress */
115 isLoading: boolean
116 /** Current error, if any */
117 error: Error | undefined
118 /** Current state of the generation */
119 status: GenerationClientState
120 /** Abort the current generation/polling */
121 stop: () => void
122 /** Clear all state 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 * React hook for generating videos using AI models.
135 *
136 * Video generation is asynchronous: a job is created, then polled for status
137 * until completion. This hook handles the full lifecycle.
138 *
139 * @example
140 * ```tsx
141 * import { useGenerateVideo } from '@tanstack/ai-react'
142 * import { fetchServerSentEvents } from '@tanstack/ai-client'
143 *
144 * function VideoGenerator() {
145 * const { generate, result, videoStatus, isLoading } = useGenerateVideo({
146 * connection: fetchServerSentEvents('/api/generate/video'),
147 * onStatusUpdate: (status) => console.log(`Progress: ${status.progress}%`),
148 * })
149 *
150 * return (
151 * <div>
152 * <button onClick={() => generate({ prompt: 'A flying car over a city' })}>
153 * Generate Video
154 * </button>
155 * {isLoading && videoStatus && (
156 * <p>Status: {videoStatus.status} ({videoStatus.progress}%)</p>
157 * )}
158 * {result && <video src={result.url} controls />}
159 * </div>
160 * )
161 * }
162 * ```
163 */
164// `TTransformed` infers from the `onResult` return position so the callback
165// parameter is typed as `VideoGenerateResult` and `result` narrows to the
166// transform's return. See issue #848.
167export function useGenerateVideo<TTransformed = void>(
168 options: Omit<
169 UseGenerateVideoOptions,
170 'onResult' | 'persistence' | 'threadId'
171 > & {
172 onResult?: (result: VideoGenerateResult) => TTransformed
173 } & GenerationPersistenceOptions,
174): UseGenerateVideoReturn<
175 InferGenerationOutputFromReturn<VideoGenerateResult, TTransformed>
176> {
177 type TOutput = InferGenerationOutputFromReturn<
178 VideoGenerateResult,
179 TTransformed
180 >
181 const hookId = useId()
182 // The hook identity is `threadId`. `hookId` is only a React recreation key.
183 const clientIdentity = options.threadId ?? hookId
184
185 const optionsRef = useRef(options)
186 optionsRef.current = options
187 const disposedRef = useRef(false)
188
189 const client = useMemo(() => {
190 const opts = optionsRef.current
191
192 // Conditional spread for `body` (strict-optional in target).
193 // Optional callbacks are wrapped in non-returning bodies so
194 // `?.()`'s implicit `undefined` doesn't widen the function
195 // return type (which `exactOptionalPropertyTypes` rejects
196 // against the strict-optional target).
197 const baseOptions: Omit<
198 VideoGenerationClientOptions<TOutput>,
199 'persistence' | 'threadId'
200 > = {
201 body: opts.body,
202 ...(opts.hydrateGeneration !== undefined && {
203 hydrateGeneration: opts.hydrateGeneration,
204 }),
205 ...(opts.joinRun !== undefined && { joinRun: opts.joinRun }),
206 ...(opts.byok !== undefined && { byok: opts.byok }),
207 byokProvider: () => optionsRef.current.byokProvider?.(),
208 devtoolsBridgeFactory: createVideoDevtoolsBridge,
209 devtools: {
210 ...opts.devtools,
211 framework: 'react',
212 hookName: 'useGenerateVideo',
213 outputKind: 'video' as const,
214 },
215 // The transform's raw return type (`TTransformed`) and the stored output
216 // (`TOutput`, with null/void/undefined stripped) are identical at runtime;
217 // the cast bridges the relationship that the conditional type hides.
218 onResult: ((r: VideoGenerateResult) =>
219 optionsRef.current.onResult?.(r)) as (
220 result: VideoGenerateResult,
221 ) => TOutput | null | void,
222 onError: (e: Error) => {
223 if (!disposedRef.current) optionsRef.current.onError?.(e)
224 },
225 onProgress: (p: number, m?: string) => {
226 if (!disposedRef.current) optionsRef.current.onProgress?.(p, m)
227 },
228 onChunk: (c: StreamChunk) => {
229 if (!disposedRef.current) optionsRef.current.onChunk?.(c)
230 },
231 onJobCreated: (id: string) => {
232 if (!disposedRef.current) optionsRef.current.onJobCreated?.(id)
233 },
234 onStatusUpdate: (s: VideoStatusInfo) => {
235 if (!disposedRef.current) optionsRef.current.onStatusUpdate?.(s)
236 },
237 }
238
239 const persistenceProps =
240 typeof opts.threadId === 'string' && opts.persistence
241 ? {
242 persistence: opts.persistence,
243 threadId: opts.threadId,
244 }
245 : {
246 ...(opts.threadId !== undefined && { threadId: opts.threadId }),
247 }
248
249 if (opts.connection) {
250 return new VideoGenerationClient<TOutput>({
251 ...baseOptions,
252 ...persistenceProps,
253 connection: opts.connection,
254 })
255 }
256
257 if (opts.fetcher) {
258 return new VideoGenerationClient<TOutput>({
259 ...baseOptions,
260 ...persistenceProps,
261 fetcher: opts.fetcher,
262 })
263 }
264
265 throw new Error(
266 'useGenerateVideo requires either a connection or fetcher option',
267 )
268 }, [clientIdentity, hookId])
269
270 const snapshot = useSyncExternalStore(
271 client.subscribe,
272 client.getSnapshot,
273 client.getSnapshot,
274 )
275
276 // Sync body changes without recreating client
277 useEffect(() => {
278 // Conditional spread: target uses strict-optional `body?: T`.
279 client.updateOptions({
280 ...(options.body !== undefined && { body: options.body }),
281 })
282 }, [client, options.body])
283
284 // Mount devtools and clean up on unmount. Generation runs are never
285 // auto-started on mount — persisted state is only displayed. Mounting
286 // revives the client after a StrictMode dispose → remount replay.
287 useEffect(() => {
288 disposedRef.current = false
289 client.mountDevtools()
290
291 return () => {
292 disposedRef.current = true
293 client.dispose()
294 }
295 }, [client])
296
297 const generate = useCallback(
298 async (input: VideoGenerateInput) => {
299 await client.generate(input)
300 },
301 [client],
302 )
303
304 const stop = useCallback(() => {
305 client.stop()
306 }, [client])
307
308 const reset = useCallback(() => {
309 client.reset()
310 }, [client])
311
312 return {
313 generate,
314 result: snapshot.result,
315 jobId: snapshot.jobId,
316 videoStatus: snapshot.videoStatus,
317 isLoading: snapshot.isLoading,
318 error: snapshot.error,
319 status: snapshot.status,
320 stop,
321 reset,
322 runId: snapshot.runId,
323 }
324}