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 useMemo,
7 useRef,
8 useSyncExternalStore,
9} from 'react'
10import type { StreamChunk } from '@tanstack/ai'
11import type {
12 AIDevtoolsDisplayOptions,
13 ConnectConnectionAdapter,
14 GenerationClientState,
15 GenerationFetcher,
16 InferGenerationOutputFromReturn,
17 VideoGenerateInput,
18 VideoGenerateResult,
19 VideoGenerationClientOptions,
20 VideoStatusInfo,
21} from '@tanstack/ai-client'
22import type { ByokClient } from '@tanstack/ai-client/byok'
23import type { ProviderId } from '@tanstack/ai/byok'
24
25/**
26 * Options for the useGenerateVideo hook.
27 */
28export interface UseGenerateVideoOptions<TOutput = VideoGenerateResult> {
29 /** Connect-based adapter for streaming transport (server handles polling) */
30 connection?: ConnectConnectionAdapter
31 /** Direct async function that returns a completed video result */
32 fetcher?: GenerationFetcher<VideoGenerateInput, VideoGenerateResult>
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. A generated id would change on every reload, so persistence
60 * would restore nothing.
61 */
62 threadId: string
63 /**
64 * Server-driven hydration handler for `persistence: true` when the
65 * connection doesn't carry one (e.g. alongside `fetcher`, or a `stream()` /
66 * `rpcStream()` adapter built without handlers) — typically a one-line
67 * server-function call. The connection's own handler takes precedence.
68 */
69 hydrateGeneration?: ConnectConnectionAdapter['hydrateGeneration']
70 /**
71 * Re-attach handler that replays a run still generating to completion on
72 * mount, when the connection doesn't carry one. Without it, a restored
73 * `running` snapshot surfaces as an (interrupted) error. The connection's
74 * own handler takes precedence.
75 */
76 joinRun?: ConnectConnectionAdapter['joinRun']
77 /**
78 * Callback when video generation completes. Can optionally return a transformed value.
79 *
80 * - Return a non-null value to transform and store it as the result
81 * - Return `null` to keep the previous result unchanged
82 * - Return nothing (`void`) to store the raw result as-is
83 */
84 onResult?: (result: VideoGenerateResult) => TOutput | null | void
85 /** Callback when an error occurs */
86 onError?: (error: Error) => void
87 /** Callback when progress is reported (0-100) */
88 onProgress?: (progress: number, message?: string) => void
89 /** Callback when a video job is created */
90 onJobCreated?: (jobId: string) => void
91 /** Callback on each status update */
92 onStatusUpdate?: (status: VideoStatusInfo) => void
93 /** Callback for each stream chunk (connect-based adapter mode only) */
94 onChunk?: (chunk: StreamChunk) => void
95}
96
97/**
98 * Return type for the useGenerateVideo hook.
99 *
100 * @template TOutput - The output type (after optional transform)
101 */
102export interface UseGenerateVideoReturn<TOutput = VideoGenerateResult> {
103 /** Trigger video generation */
104 generate: (input: VideoGenerateInput) => Promise<void>
105 /** The final video result (with URL), or null */
106 result: TOutput | null
107 /** The current job ID, or null */
108 jobId: string | null
109 /** Current video generation status info, or null */
110 videoStatus: VideoStatusInfo | null
111 /** Whether generation/polling is in progress */
112 isLoading: boolean
113 /** Current error, if any */
114 error: Error | undefined
115 /** Current state of the generation */
116 status: GenerationClientState
117 /** Abort the current generation/polling */
118 stop: () => void
119 /** Clear all state and return to idle */
120 reset: () => void
121 /**
122 * The id of the generation job currently running, or `null` when nothing is in
123 * flight. Each call to `generate` is one job with its own id. Pass it to your
124 * own endpoint to cancel or poll the provider job — `stop()` only aborts the
125 * local stream, it does not stop work already running on the provider.
126 */
127 runId: string | null
128}
129
130/**
131 * React hook for generating videos using AI models.
132 *
133 * Video generation is asynchronous: a job is created, then polled for status
134 * until completion. This hook handles the full lifecycle.
135 *
136 * @example
137 * ```tsx
138 * import { useGenerateVideo } from '@tanstack/ai-react'
139 * import { fetchServerSentEvents } from '@tanstack/ai-client'
140 *
141 * function VideoGenerator() {
142 * const { generate, result, videoStatus, isLoading } = useGenerateVideo({
143 * threadId: 'intro-video',
144 * connection: fetchServerSentEvents('/api/generate/video'),
145 * onStatusUpdate: (status) => console.log(`Progress: ${status.progress}%`),
146 * })
147 *
148 * return (
149 * <div>
150 * <button onClick={() => generate({ prompt: 'A flying car over a city' })}>
151 * Generate Video
152 * </button>
153 * {isLoading && videoStatus && (
154 * <p>Status: {videoStatus.status} ({videoStatus.progress}%)</p>
155 * )}
156 * {result && <video src={result.url} controls />}
157 * </div>
158 * )
159 * }
160 * ```
161 */
162// `TTransformed` infers from the `onResult` return position so the callback
163// parameter is typed as `VideoGenerateResult` and `result` narrows to the
164// transform's return. See issue #848.
165export function useGenerateVideo<TTransformed = void>(
166 options: Omit<UseGenerateVideoOptions, 'onResult'> & {
167 onResult?: (result: VideoGenerateResult) => TTransformed
168 },
169): UseGenerateVideoReturn<
170 InferGenerationOutputFromReturn<VideoGenerateResult, TTransformed>
171> {
172 type TOutput = InferGenerationOutputFromReturn<
173 VideoGenerateResult,
174 TTransformed
175 >
176 const optionsRef = useRef(options)
177 optionsRef.current = options
178 const disposedRef = useRef(false)
179
180 const client = useMemo(() => {
181 const opts = optionsRef.current
182
183 // Conditional spread for `body` (strict-optional in target).
184 // Optional callbacks are wrapped in non-returning bodies so
185 // `?.()`'s implicit `undefined` doesn't widen the function
186 // return type (which `exactOptionalPropertyTypes` rejects
187 // against the strict-optional target).
188 const baseOptions: VideoGenerationClientOptions<TOutput> = {
189 persistence: opts.persistence,
190 threadId: opts.threadId,
191 body: opts.body,
192 ...(opts.hydrateGeneration !== undefined && {
193 hydrateGeneration: opts.hydrateGeneration,
194 }),
195 ...(opts.joinRun !== undefined && { joinRun: opts.joinRun }),
196 ...(opts.byok !== undefined && { byok: opts.byok }),
197 byokProvider: () => optionsRef.current.byokProvider?.(),
198 devtoolsBridgeFactory: createVideoDevtoolsBridge,
199 devtools: {
200 ...opts.devtools,
201 framework: 'react',
202 hookName: 'useGenerateVideo',
203 outputKind: 'video' as const,
204 },
205 // The transform's raw return type (`TTransformed`) and the stored output
206 // (`TOutput`, with null/void/undefined stripped) are identical at runtime;
207 // the cast bridges the relationship that the conditional type hides.
208 onResult: ((r: VideoGenerateResult) =>
209 optionsRef.current.onResult?.(r)) as (
210 result: VideoGenerateResult,
211 ) => TOutput | null | void,
212 onError: (e: Error) => {
213 if (!disposedRef.current) optionsRef.current.onError?.(e)
214 },
215 onProgress: (p: number, m?: string) => {
216 if (!disposedRef.current) optionsRef.current.onProgress?.(p, m)
217 },
218 onChunk: (c: StreamChunk) => {
219 if (!disposedRef.current) optionsRef.current.onChunk?.(c)
220 },
221 onJobCreated: (id: string) => {
222 if (!disposedRef.current) optionsRef.current.onJobCreated?.(id)
223 },
224 onStatusUpdate: (s: VideoStatusInfo) => {
225 if (!disposedRef.current) optionsRef.current.onStatusUpdate?.(s)
226 },
227 }
228
229 if (opts.connection) {
230 return new VideoGenerationClient<TOutput>({
231 ...baseOptions,
232 connection: opts.connection,
233 })
234 }
235
236 if (opts.fetcher) {
237 return new VideoGenerationClient<TOutput>({
238 ...baseOptions,
239 fetcher: opts.fetcher,
240 })
241 }
242
243 throw new Error(
244 'useGenerateVideo requires either a connection or fetcher option',
245 )
246 }, [options.threadId])
247
248 const snapshot = useSyncExternalStore(
249 client.subscribe,
250 client.getSnapshot,
251 client.getSnapshot,
252 )
253
254 // Sync body changes without recreating client
255 useEffect(() => {
256 // Conditional spread: target uses strict-optional `body?: T`.
257 client.updateOptions({
258 ...(options.body !== undefined && { body: options.body }),
259 })
260 }, [client, options.body])
261
262 // Mount devtools and clean up on unmount. Generation runs are never
263 // auto-started on mount — persisted state is only displayed. Mounting
264 // revives the client after a StrictMode dispose → remount replay.
265 useEffect(() => {
266 disposedRef.current = false
267 client.mountDevtools()
268
269 return () => {
270 disposedRef.current = true
271 client.dispose()
272 }
273 }, [client])
274
275 const generate = useCallback(
276 async (input: VideoGenerateInput) => {
277 await client.generate(input)
278 },
279 [client],
280 )
281
282 const stop = useCallback(() => {
283 client.stop()
284 }, [client])
285
286 const reset = useCallback(() => {
287 client.reset()
288 }, [client])
289
290 return {
291 generate,
292 result: snapshot.result,
293 jobId: snapshot.jobId,
294 videoStatus: snapshot.videoStatus,
295 isLoading: snapshot.isLoading,
296 error: snapshot.error,
297 status: snapshot.status,
298 stop,
299 reset,
300 runId: snapshot.runId,
301 }
302}