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