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

use-generate-video.ts

329 lines11.6 KB

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