Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

use-generate-video.ts

340 lines12.2 KB

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