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

use-generate-video.ts

333 lines11.8 KB

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