Open History to see the last commit
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 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. A generated id would change on every reload, so persistence
63 * would restore nothing.
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 transformed output type (defaults to VideoGenerateResult)
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: Accessor<TOutput | null>
110 /** The current job ID, or null */
111 jobId: Accessor<string | null>
112 /** Current video generation status info, or null */
113 videoStatus: Accessor<VideoStatusInfo | null>
114 /** Whether generation/polling is in progress */
115 isLoading: Accessor<boolean>
116 /** Current error, if any */
117 error: Accessor<Error | undefined>
118 /** Current state of the generation */
119 status: Accessor<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: Accessor<string | null>
131}
132
133/**
134 * Solid 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-solid'
142 * import { fetchServerSentEvents } from '@tanstack/ai-client'
143 *
144 * function VideoGenerator() {
145 * const { generate, result, videoStatus, isLoading } = useGenerateVideo({
146 * threadId: 'intro-video',
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<UseGenerateVideoOptions, 'onResult'> & {
170 onResult?: (result: VideoGenerateResult) => TTransformed
171 },
172): UseGenerateVideoReturn<
173 InferGenerationOutputFromReturn<VideoGenerateResult, TTransformed>
174> {
175 type TOutput = InferGenerationOutputFromReturn<
176 VideoGenerateResult,
177 TTransformed
178 >
179 const [result, setResult] = createSignal<TOutput | null>(null)
180 const [jobId, setJobId] = createSignal<string | null>(null)
181 const [videoStatus, setVideoStatus] = createSignal<VideoStatusInfo | null>(
182 null,
183 )
184 const [isLoading, setIsLoading] = createSignal(false)
185 const [error, setError] = createSignal<Error | undefined>(undefined)
186 const [status, setStatus] = createSignal<GenerationClientState>('idle')
187 const [runId, setRunId] = createSignal<string | null>(null)
188 let disposed = false
189
190 // Built once. `untrack` keeps the option reads below from subscribing
191 // construction to `options.persistence` / `options.devtools` /
192 // `options.body`: a re-run would build a second client
193 // and orphan the first (only the live one is disposed on cleanup). Later
194 // `options.body` changes are pushed through `updateOptions` instead.
195 const client = untrack((): VideoGenerationClient<TOutput> => {
196 // Conditional spread on `body`: VideoGenerationClientOptions.body
197 // is a strict optional; EOPT forbids passing `T | undefined`.
198 const baseOptions = {
199 body: options.body,
200 persistence: options.persistence,
201 threadId: options.threadId,
202 ...(options.hydrateGeneration !== undefined && {
203 hydrateGeneration: options.hydrateGeneration,
204 }),
205 ...(options.joinRun !== undefined && { joinRun: options.joinRun }),
206 ...(options.byok !== undefined && { byok: options.byok }),
207 byokProvider: () => options.byokProvider?.(),
208 devtoolsBridgeFactory: createVideoDevtoolsBridge,
209 devtools: {
210 ...options.devtools,
211 framework: 'solid',
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) => options.onResult?.(r)) as (
219 result: VideoGenerateResult,
220 ) => TOutput | null | void,
221 onError: (e: Error) => {
222 if (!disposed) options.onError?.(e)
223 },
224 onProgress: (p: number, m?: string) => {
225 if (!disposed) options.onProgress?.(p, m)
226 },
227 onChunk: (c: StreamChunk) => {
228 if (!disposed) options.onChunk?.(c)
229 },
230 onJobCreated: (id: string) => {
231 if (!disposed) options.onJobCreated?.(id)
232 },
233 onStatusUpdate: (s: VideoStatusInfo) => {
234 if (!disposed) options.onStatusUpdate?.(s)
235 },
236 }
237
238 if (options.connection) {
239 return new VideoGenerationClient<TOutput>({
240 ...baseOptions,
241 connection: options.connection,
242 })
243 }
244
245 if (options.fetcher) {
246 return new VideoGenerationClient<TOutput>({
247 ...baseOptions,
248 fetcher: options.fetcher,
249 })
250 }
251
252 throw new Error(
253 'useGenerateVideo requires either a connection or fetcher option',
254 )
255 })
256
257 const applySnapshot = () => {
258 const next = client.getSnapshot()
259 // One batch, so effects never see half of a snapshot.
260 batch(() => {
261 setResult(() => next.result)
262 setIsLoading(next.isLoading)
263 setError(next.error)
264 setStatus(next.status)
265 setRunId(next.runId)
266 setJobId(next.jobId)
267 setVideoStatus(next.videoStatus)
268 })
269 }
270 applySnapshot()
271 onCleanup(client.subscribe(applySnapshot))
272
273 // Sync body changes without recreating client
274 createEffect(() => {
275 const currentBody = options.body
276 client.updateOptions({
277 ...(currentBody !== undefined && { body: currentBody }),
278 })
279 })
280
281 // Mount devtools only. Generation runs are never auto-started on mount — a
282 // persisted snapshot is hydrated for display, never replayed.
283 onMount(() => {
284 client.mountDevtools()
285 })
286
287 // Cleanup on unmount: stop any in-flight requests and unregister devtools
288 onCleanup(() => {
289 disposed = true
290 client.dispose()
291 })
292
293 const generate = async (input: VideoGenerateInput) => {
294 await client.generate(input)
295 }
296
297 const stop = () => {
298 client.stop()
299 }
300
301 const reset = () => {
302 client.reset()
303 }
304
305 return {
306 generate,
307 result,
308 jobId,
309 videoStatus,
310 isLoading,
311 error,
312 status,
313 stop,
314 reset,
315 runId,
316 }
317}