Open History to see the last commit
1import { ByokBlockedError, ByokMissingError } from '@tanstack/ai/byok'
2import { byokFallbackProviderId } from './byok/client'
3import {
4 prepareResolvedByokHeaders,
5 resolveByokProviderId,
6} from './byok/resolve'
7import {
8 GENERATION_EVENTS,
9 GENERATION_STREAM_TRUNCATED_MESSAGE,
10 GENERATION_UNRESTORABLE_RESULT_MESSAGE,
11 clientStateFromResumeStatus,
12 createGenerationHydrationError,
13 createGenerationResultSnapshot,
14 parseGenerationResumeSnapshot,
15 updateGenerationResumeSnapshot,
16} from './generation-types'
17import { createNoOpVideoDevtoolsBridge } from './devtools-noop'
18import { parseSSEResponse } from './sse-parser'
19import { restoreInboundChunk } from '@tanstack/ai/client'
20import type { StreamChunk } from '@tanstack/ai/client'
21import type { ByokClient } from './byok'
22import type {
23 ConnectConnectionAdapter,
24 GenerationHydrationResult,
25 RunAgentInputContext,
26} from './connection-adapters'
27import type {
28 AIDevtoolsClientMetadata,
29 AIDevtoolsGenerationProgress,
30 VideoDevtoolsBridge,
31 VideoDevtoolsBridgeOptions,
32} from './devtools'
33import type {
34 GenerationClientState,
35 GenerationFetcher,
36 GenerationPersistenceOptions,
37 GenerationResumeSnapshot,
38 GenerationResumeState,
39 GenerationTransport,
40 VideoGenerateInput,
41 VideoGenerateResult,
42 VideoGenerationClientOptions,
43 VideoStatusInfo,
44} from './generation-types'
45
46/**
47 * Callbacks stored in a ref so hooks can update them without recreating the client.
48 */
49// All optional fields explicitly allow `| undefined` so callers can spread
50// option bags (where each callback may be `undefined`) into the callbacks
51// ref under `exactOptionalPropertyTypes`.
52interface VideoCallbacks<TOutput> {
53 onResult?:
54 | ((result: VideoGenerateResult) => TOutput | null | void)
55 | undefined
56 onError?: ((error: Error) => void) | undefined
57 onProgress?: ((progress: number, message?: string) => void) | undefined
58 onChunk?: ((chunk: StreamChunk) => void) | undefined
59 onJobCreated?: ((jobId: string) => void) | undefined
60 onStatusUpdate?: ((status: VideoStatusInfo) => void) | undefined
61 onResultChange?: ((result: TOutput | null) => void) | undefined
62 onLoadingChange?: ((isLoading: boolean) => void) | undefined
63 onErrorChange?: ((error: Error | undefined) => void) | undefined
64 onStatusChange?: ((status: GenerationClientState) => void) | undefined
65 onJobIdChange?: ((jobId: string | null) => void) | undefined
66 onVideoStatusChange?: ((status: VideoStatusInfo | null) => void) | undefined
67 onResumeSnapshotChange?:
68 | ((snapshot: GenerationResumeSnapshot | undefined) => void)
69 | undefined
70 onResumeStateChange?:
71 | ((resumeState: GenerationResumeState | null) => void)
72 | undefined
73}
74
75/**
76 * A specialized client for job-based video generation.
77 *
78 * Video generation is asynchronous: a job is created, then polled for status
79 * until completion. This client handles the full lifecycle.
80 *
81 * Supports two transport modes:
82 * - **ConnectConnectionAdapter** — Server handles the polling loop internally and
83 * streams status updates via CUSTOM events.
84 * - **Fetcher** — Direct async function that returns a completed
85 * `VideoGenerateResult`.
86 *
87 * @example
88 * ```typescript
89 * // With streaming connection adapter (server-driven polling)
90 * const client = new VideoGenerationClient({
91 * connection: fetchServerSentEvents('/api/generate/video'),
92 * onResultChange: setResult,
93 * onVideoStatusChange: setVideoStatus,
94 * })
95 *
96 * // With fetcher (direct result)
97 * const client = new VideoGenerationClient({
98 * fetcher: async (input) => {
99 * const res = await fetch('/api/video/generate', {
100 * method: 'POST',
101 * body: JSON.stringify(input),
102 * })
103 * return res.json() // { jobId, status: 'completed', url, expiresAt }
104 * },
105 * })
106 *
107 * await client.generate({ prompt: 'A flying car over a city' })
108 * ```
109 */
110export class VideoGenerationClient<TOutput = VideoGenerateResult> {
111 private readonly connection: ConnectConnectionAdapter | undefined
112 // Persistence handlers supplied as options (e.g. alongside a `fetcher`), used
113 // when the connection doesn't carry its own — the connection's handlers take
114 // precedence when both exist.
115 private readonly hydrateGenerationHandler:
116 | ConnectConnectionAdapter['hydrateGeneration']
117 | undefined
118 private readonly joinRunHandler:
119 | ConnectConnectionAdapter['joinRun']
120 | undefined
121 private readonly fetcher:
122 | GenerationFetcher<VideoGenerateInput, VideoGenerateResult>
123 | undefined
124 private uniqueId: string
125 private readonly devtoolsMetadata: AIDevtoolsClientMetadata
126 private readonly devtoolsBridge: VideoDevtoolsBridge<TOutput>
127 private threadId: string
128 // Server-driven mode (`persistence: true`): no local snapshot store; on mount
129 // the client hydrates the last generation for `threadId` from the server.
130 private readonly serverDriven: boolean = false
131 private body: Record<string, any>
132 private byok: ByokClient | undefined
133 private byokProvider: (() => string | undefined) | undefined
134
135 private result: TOutput | null = null
136 private input: VideoGenerateInput | null = null
137 private progress: AIDevtoolsGenerationProgress | null = null
138 private jobId: string | null = null
139 private videoStatus: VideoStatusInfo | null = null
140 private isLoading = false
141 private error: Error | undefined = undefined
142 private status: GenerationClientState = 'idle'
143 private resumeSnapshot: GenerationResumeSnapshot | undefined
144 private abortController: AbortController | null = null
145 private rejoinedRunId: string | undefined
146 private readonly callbacksRef: VideoCallbacks<TOutput>
147 private devtoolsMounted = false
148 private disposed = false
149 private serverHydrationStarted = false
150
151 constructor(
152 options: Omit<
153 VideoGenerationClientOptions<TOutput>,
154 'persistence' | 'threadId'
155 > &
156 GenerationPersistenceOptions &
157 GenerationTransport<VideoGenerateInput, VideoGenerateResult>,
158 ) {
159 // `threadId` is the only identity. Do not mint a random id during
160 // construct: hooks build this client during render.
161 this.threadId = options.threadId ?? ''
162 this.uniqueId = this.threadId
163 this.connection = options.connection
164 this.fetcher = options.fetcher
165 this.hydrateGenerationHandler = options.hydrateGeneration
166 this.joinRunHandler = options.joinRun
167 this.body = options.body ?? {}
168 this.byok = options.byok
169 this.byokProvider = options.byokProvider
170 // `persistence` is `false`/omitted (ephemeral) or `true` (server-driven:
171 // hydrate the last generation for `threadId` from the server on mount).
172 this.serverDriven = options.persistence === true
173 this.callbacksRef = {
174 onResult: options.onResult,
175 onError: options.onError,
176 onProgress: options.onProgress,
177 onChunk: options.onChunk,
178 onJobCreated: options.onJobCreated,
179 onStatusUpdate: options.onStatusUpdate,
180 onResultChange: options.onResultChange,
181 onLoadingChange: options.onLoadingChange,
182 onErrorChange: options.onErrorChange,
183 onStatusChange: options.onStatusChange,
184 onJobIdChange: options.onJobIdChange,
185 onVideoStatusChange: options.onVideoStatusChange,
186 onResumeSnapshotChange: options.onResumeSnapshotChange,
187 onResumeStateChange: options.onResumeStateChange,
188 }
189
190 this.devtoolsMetadata = this.createDevtoolsMetadata(options.devtools)
191 this.devtoolsBridge = (
192 options.devtoolsBridgeFactory ?? createNoOpVideoDevtoolsBridge
193 )<TOutput>(this.buildDevtoolsBridgeOptions())
194
195 // Mount hydration (`maybeHydrateFromServer`) is deliberately NOT run here. The framework
196 // hooks build this client inside `useMemo`, so the constructor executes in
197 // React's render phase; hydrating here would re-fire the hydrate GET on
198 // every discarded/speculative render, flooding the connection pool when
199 // several clients mount together. It is kicked off once from
200 // `mountDevtools`, which the hooks call from a commit-phase mount effect.
201 }
202
203 private buildDevtoolsBridgeOptions(): VideoDevtoolsBridgeOptions<TOutput> {
204 const client = this
205 return {
206 get hookId() {
207 return client.uniqueId
208 },
209 get clientId() {
210 return client.uniqueId
211 },
212 get threadId() {
213 return client.threadId
214 },
215 metadata: this.devtoolsMetadata,
216 getCoreState: () => ({
217 input: this.input,
218 result: this.result,
219 progress: this.progress,
220 status: this.status,
221 isLoading: this.isLoading,
222 jobId: this.jobId,
223 videoStatus: this.videoStatus,
224 ...(this.error ? { error: this.error.message } : {}),
225 }),
226 }
227 }
228
229 mountDevtools(): void {
230 this.ensureThreadId()
231 // Mounting revives a disposed client. Framework hooks call this from
232 // their mount effect, so a dispose → remount cycle (e.g. React
233 // StrictMode's mount → cleanup → mount replay against the same memoized
234 // client) leaves the client usable again.
235 this.disposed = false
236 this.maybeHydrateFromServer()
237 // Re-attach to an already-loaded `running` snapshot (remount case); see the
238 // note in GenerationClient.mountDevtools. Guarded by rejoinInFlight.
239 this.maybeResumeInFlight()
240 if (this.devtoolsMounted) {
241 return
242 }
243
244 this.devtoolsMounted = true
245 this.devtoolsBridge.emitRegistered()
246 this.devtoolsBridge.emitSnapshot()
247 }
248
249 /**
250 * Trigger video generation.
251 * Only one generation can be in-flight at a time.
252 */
253 async generate(input: VideoGenerateInput): Promise<void> {
254 if (this.disposed) return
255 if (this.isLoading) return
256 this.mountDevtools()
257
258 this.input = input
259 this.progress = null
260 const runId = this.devtoolsBridge.beginRun(input)
261 this.setIsLoading(true)
262 this.setStatus('generating')
263 this.setError(undefined)
264 this.setJobId(null)
265 this.setVideoStatus(null)
266
267 const abortController = new AbortController()
268 this.abortController = abortController
269 const { signal } = abortController
270
271 try {
272 let headers: Record<string, string> | undefined
273 if (this.byok) {
274 const provider = resolveByokProviderId(
275 this.byokProvider,
276 this.body.provider,
277 byokFallbackProviderId(this.byok),
278 )
279 headers = await prepareResolvedByokHeaders(this.byok, provider)
280 }
281
282 if (this.fetcher) {
283 await this.generateWithFetcher(input, signal, runId, headers)
284 } else if (this.connection) {
285 const mergedData = { ...this.body, ...input }
286 const stream = this.connection.connect(
287 [],
288 mergedData,
289 signal,
290 this.createRunContext(runId, headers),
291 )
292 await this.processStream(stream, runId, signal)
293 } else {
294 throw new Error(
295 'VideoGenerationClient requires either a connection or fetcher option',
296 )
297 }
298 if (!signal.aborted && this.status === 'success') {
299 this.devtoolsBridge.finishRun(
300 this.devtoolsBridge.getActiveRunId() ?? runId,
301 'run:completed',
302 'completed',
303 )
304 }
305 } catch (err: unknown) {
306 if (signal.aborted) return
307 const error = err instanceof Error ? err : new Error(String(err))
308 if (error instanceof ByokMissingError) {
309 this.byok?.request(error.provider, 'missing')
310 }
311 if (error instanceof ByokBlockedError && error.reason === 'locked') {
312 this.byok?.request(error.provider, 'locked')
313 }
314 this.setError(error)
315 this.setStatus('error')
316 this.recordResumeSnapshotError(error)
317 this.devtoolsBridge.finishRun(
318 this.devtoolsBridge.getActiveRunId() ?? runId,
319 'run:errored',
320 'errored',
321 error.message,
322 )
323 this.callbacksRef.onError?.(error)
324 } finally {
325 if (this.abortController === abortController) {
326 this.abortController = null
327 this.setIsLoading(false)
328 }
329 }
330 }
331
332 /**
333 * Direct fetcher mode: call fetcher and set result.
334 */
335 private async generateWithFetcher(
336 input: VideoGenerateInput,
337 signal: AbortSignal,
338 runId: string,
339 headers?: Record<string, string>,
340 ): Promise<void> {
341 if (!this.fetcher) return
342
343 // Fetcher returns a completed result directly, or a Response with SSE body
344 const result = await this.fetcher(
345 input,
346 headers === undefined ? { signal } : { signal, headers },
347 )
348 if (signal.aborted) return
349
350 if (result instanceof Response) {
351 // Server function returned SSE Response — parse stream
352 await this.processStream(parseSSEResponse(result, signal), runId, signal)
353 } else {
354 this.devtoolsBridge.ensureRunStarted(runId)
355 this.setResult(result)
356 this.setStatus('success')
357 this.completePlainFetcherResumeSnapshot(result)
358 }
359 }
360
361 /**
362 * Process a stream of AG-UI events from the streaming connection adapter.
363 * The server handles the polling loop and streams status updates.
364 *
365 * Throws {@link GENERATION_STREAM_TRUNCATED_MESSAGE} when the iteration ends
366 * without a terminal chunk — see the note on
367 * `GenerationClient.processStream`. Video runs are long enough that a proxy
368 * idle timeout mid-poll is the likeliest way to hit it.
369 */
370 private async processStream(
371 source: AsyncIterable<StreamChunk>,
372 fallbackRunId: string,
373 signal: AbortSignal,
374 ): Promise<void> {
375 let streamRunId: string | undefined
376 let sawTerminalChunk = false
377
378 for await (const raw of source) {
379 if (signal.aborted) break
380
381 const chunk = restoreInboundChunk(raw)
382 this.callbacksRef.onChunk?.(chunk)
383 this.observeResumeSnapshot(chunk)
384 const chunkRunId =
385 'runId' in chunk && typeof chunk.runId === 'string'
386 ? chunk.runId
387 : undefined
388
389 // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check -- AG-UI EventType has ~22 variants; this consumer only handles the subset relevant to video generation lifecycle.
390 switch (chunk.type) {
391 case 'RUN_STARTED': {
392 streamRunId = chunk.runId
393 this.devtoolsBridge.ensureRunStarted(chunk.runId)
394 break
395 }
396 case 'CUSTOM': {
397 this.devtoolsBridge.ensureRunStarted(streamRunId ?? fallbackRunId)
398 if (chunk.name === GENERATION_EVENTS.VIDEO_JOB_CREATED) {
399 const { jobId } = chunk.value as { jobId: string }
400 this.setJobId(jobId)
401 this.callbacksRef.onJobCreated?.(jobId)
402 } else if (chunk.name === GENERATION_EVENTS.VIDEO_STATUS) {
403 const statusInfo = chunk.value as VideoStatusInfo
404 this.setVideoStatus(statusInfo)
405 this.callbacksRef.onStatusUpdate?.(statusInfo)
406 if (statusInfo.progress !== undefined) {
407 this.setProgress(statusInfo.progress)
408 }
409 } else if (chunk.name === GENERATION_EVENTS.RESULT) {
410 this.setResult(chunk.value as VideoGenerateResult)
411 } else if (chunk.name === GENERATION_EVENTS.PROGRESS) {
412 const { progress, message } = chunk.value as {
413 progress: number
414 message?: string
415 }
416 this.setProgress(progress, message)
417 }
418 break
419 }
420 case 'RUN_FINISHED': {
421 streamRunId = chunk.runId
422 sawTerminalChunk = true
423 this.devtoolsBridge.ensureRunStarted(chunk.runId)
424 this.setStatus('success')
425 break
426 }
427 case 'RUN_ERROR': {
428 this.devtoolsBridge.ensureRunStarted(
429 chunkRunId ?? streamRunId ?? fallbackRunId,
430 )
431 // Spec RUN_ERROR message. Missing message uses this fallback.
432 const msg =
433 (chunk.message as string | undefined) || 'An error occurred'
434 throw new Error(msg)
435 }
436 default:
437 break
438 }
439 }
440
441 // An aborted read is a deliberate stop/dispose, not a truncation.
442 if (!sawTerminalChunk && !signal.aborted) {
443 throw new Error(GENERATION_STREAM_TRUNCATED_MESSAGE)
444 }
445 }
446
447 /**
448 * Abort any in-flight generation or polling.
449 */
450 stop(): void {
451 const runId = this.devtoolsBridge.getActiveRunId()
452 if (this.abortController) {
453 this.abortController.abort()
454 this.abortController = null
455 }
456 this.setIsLoading(false)
457 if (this.status === 'generating') {
458 this.setStatus('idle')
459 if (runId) {
460 this.devtoolsBridge.finishRun(runId, 'run:cancelled', 'cancelled')
461 }
462 }
463 // A stopped run is no longer resumable. Without this the in-memory
464 // snapshot stays `running`, and a remount's `maybeResumeInFlight` would
465 // rejoin a run the user just cancelled.
466 if (this.resumeSnapshot && this.resumeSnapshot.status === 'running') {
467 this.resumeSnapshot = {
468 ...this.resumeSnapshot,
469 resumeState: null,
470 status: 'idle',
471 }
472 this.notifyResumeSnapshotChanged()
473 }
474 }
475
476 /**
477 * Clear all state and return to idle. Also drops the client's in-memory
478 * resume snapshot, so a remount restores nothing. The server-side record is
479 * untouched — this client no longer writes one — so a full page reload under
480 * `persistence: true` re-hydrates the last generation again.
481 */
482 reset(): void {
483 this.stop()
484 this.setResult(null)
485 this.input = null
486 this.progress = null
487 this.devtoolsBridge.resetRuns()
488 this.setJobId(null)
489 this.setVideoStatus(null)
490 this.setError(undefined)
491 this.setStatus('idle')
492 this.clearResumeSnapshot()
493 this.devtoolsBridge.emitState()
494 }
495
496 /**
497 * Update options without recreating the client.
498 */
499 updateOptions(
500 options: Partial<
501 Pick<
502 VideoGenerationClientOptions<TOutput>,
503 | 'body'
504 | 'byok'
505 | 'byokProvider'
506 | 'onResult'
507 | 'onError'
508 | 'onProgress'
509 | 'onChunk'
510 | 'onJobCreated'
511 | 'onStatusUpdate'
512 >
513 >,
514 ): void {
515 if (options.body !== undefined) {
516 this.body = options.body ?? {}
517 }
518 if (options.byok !== undefined) {
519 this.byok = options.byok
520 }
521 if (options.byokProvider !== undefined) {
522 this.byokProvider = options.byokProvider
523 }
524 if (options.onResult !== undefined) {
525 this.callbacksRef.onResult = options.onResult
526 }
527 if (options.onError !== undefined) {
528 this.callbacksRef.onError = options.onError
529 }
530 if (options.onProgress !== undefined) {
531 this.callbacksRef.onProgress = options.onProgress
532 }
533 if (options.onChunk !== undefined) {
534 this.callbacksRef.onChunk = options.onChunk
535 }
536 if (options.onJobCreated !== undefined) {
537 this.callbacksRef.onJobCreated = options.onJobCreated
538 }
539 if (options.onStatusUpdate !== undefined) {
540 this.callbacksRef.onStatusUpdate = options.onStatusUpdate
541 }
542 }
543
544 dispose(): void {
545 this.disposed = true
546 // Teardown, NOT a user cancel (see GenerationClient.dispose): abort in-flight
547 // delivery but keep the `running` snapshot resumable so a remount rejoins.
548 if (this.abortController) {
549 this.abortController.abort()
550 this.abortController = null
551 }
552 this.setIsLoading(false)
553 this.devtoolsBridge.dispose()
554 this.devtoolsMounted = false
555 this.serverHydrationStarted = false
556 this.rejoinedRunId = undefined
557 }
558
559 // ===========================
560 // Getters
561 // ===========================
562
563 getResult(): TOutput | null {
564 return this.result
565 }
566
567 getJobId(): string | null {
568 return this.jobId
569 }
570
571 getVideoStatus(): VideoStatusInfo | null {
572 return this.videoStatus
573 }
574
575 getIsLoading(): boolean {
576 return this.isLoading
577 }
578
579 getError(): Error | undefined {
580 return this.error
581 }
582
583 getStatus(): GenerationClientState {
584 return this.status
585 }
586
587 getResumeSnapshot(): GenerationResumeSnapshot | undefined {
588 return this.resumeSnapshot
589 ? {
590 ...this.resumeSnapshot,
591 ...(this.resumeSnapshot.pendingArtifacts
592 ? { pendingArtifacts: [...this.resumeSnapshot.pendingArtifacts] }
593 : {}),
594 ...(this.resumeSnapshot.result
595 ? {
596 result: {
597 ...this.resumeSnapshot.result,
598 ...(this.resumeSnapshot.result.artifacts
599 ? { artifacts: [...this.resumeSnapshot.result.artifacts] }
600 : {}),
601 },
602 }
603 : {}),
604 ...(this.resumeSnapshot.error
605 ? { error: { ...this.resumeSnapshot.error } }
606 : {}),
607 ...(this.resumeSnapshot.lastEvent
608 ? { lastEvent: { ...this.resumeSnapshot.lastEvent } }
609 : {}),
610 }
611 : undefined
612 }
613
614 // ===========================
615 // Private state setters
616 // ===========================
617
618 private setResult(rawResult: VideoGenerateResult | null): void {
619 if (rawResult === null) {
620 this.result = null
621 this.callbacksRef.onResultChange?.(null)
622 this.devtoolsBridge.recordResultChange()
623 return
624 }
625
626 const completedStatus = this.createCompletedVideoStatus(rawResult)
627 if (this.progress?.value !== 100) {
628 this.setProgress(100, this.progress?.message)
629 }
630 this.setJobId(rawResult.jobId)
631 this.setVideoStatus(completedStatus)
632
633 if (this.callbacksRef.onResult) {
634 const transformed = this.callbacksRef.onResult(rawResult)
635 if (transformed === null) {
636 // null return → keep previous result unchanged, just re-emit
637 this.devtoolsBridge.emitState()
638 return
639 }
640 if (transformed !== undefined) {
641 // Non-null, non-undefined → use transformed value
642 this.result = transformed
643 this.callbacksRef.onResultChange?.(this.result)
644 this.devtoolsBridge.recordResultChange()
645 return
646 }
647 }
648
649 // No onResult callback, or callback returned void → use raw value as
650 // TOutput. When the caller did not supply an onResult transform,
651 // `TOutput` defaults to `VideoGenerateResult`, so the runtime cast is
652 // sound.
653 // oxlint-disable-next-line eslint-js/no-restricted-syntax -- TOutput defaults to VideoGenerateResult when no onResult transform is supplied
654 this.result = rawResult as unknown as TOutput
655 this.callbacksRef.onResultChange?.(this.result)
656 this.devtoolsBridge.recordResultChange()
657 }
658
659 private setJobId(jobId: string | null): void {
660 this.jobId = jobId
661 this.callbacksRef.onJobIdChange?.(jobId)
662 this.devtoolsBridge.recordJobIdChange()
663 }
664
665 private setVideoStatus(status: VideoStatusInfo | null): void {
666 this.videoStatus = status
667 this.callbacksRef.onVideoStatusChange?.(status)
668 this.devtoolsBridge.recordVideoStatusChange()
669 }
670
671 private setIsLoading(isLoading: boolean): void {
672 this.isLoading = isLoading
673 this.callbacksRef.onLoadingChange?.(isLoading)
674 this.devtoolsBridge.recordLoadingChange()
675 }
676
677 private setError(error: Error | undefined): void {
678 this.error = error
679 this.callbacksRef.onErrorChange?.(error)
680 this.devtoolsBridge.recordErrorChange(error)
681 }
682
683 private setStatus(status: GenerationClientState): void {
684 this.status = status
685 this.callbacksRef.onStatusChange?.(status)
686 this.devtoolsBridge.recordStatusChange(status)
687 }
688
689 private setProgress(value: number, message?: string): void {
690 this.progress = {
691 value,
692 ...(message ? { message } : {}),
693 }
694 if (message === undefined) {
695 this.callbacksRef.onProgress?.(value)
696 } else {
697 this.callbacksRef.onProgress?.(value, message)
698 }
699 this.devtoolsBridge.recordProgressChange()
700 }
701
702 private createCompletedVideoStatus(
703 result: VideoGenerateResult,
704 ): VideoStatusInfo {
705 return {
706 jobId: result.jobId,
707 status: result.status,
708 progress: 100,
709 url: result.url,
710 }
711 }
712
713 private createDevtoolsMetadata(
714 metadata?: Partial<AIDevtoolsClientMetadata>,
715 ): AIDevtoolsClientMetadata {
716 return {
717 hookName: metadata?.hookName ?? 'useGenerateVideo',
718 outputKind: metadata?.outputKind ?? 'video',
719 ...(metadata?.framework ? { framework: metadata.framework } : {}),
720 ...(metadata?.name ? { name: metadata.name } : {}),
721 }
722 }
723
724 private ensureThreadId(): string {
725 if (!this.threadId) {
726 this.threadId = this.generateUniqueId('video')
727 }
728 this.uniqueId = this.threadId
729 return this.threadId
730 }
731
732 private generateUniqueId(prefix: string): string {
733 return `${prefix}-${Date.now()}-${Math.random().toString(36).substring(7)}`
734 }
735
736 private createRunContext(
737 runId: string,
738 headers?: Record<string, string>,
739 ): RunAgentInputContext {
740 return {
741 threadId: this.threadId,
742 runId,
743 ...(headers ? { headers } : {}),
744 }
745 }
746
747 private observeResumeSnapshot(chunk: StreamChunk): void {
748 this.resumeSnapshot = updateGenerationResumeSnapshot(
749 this.resumeSnapshot,
750 chunk,
751 )
752 this.notifyResumeSnapshotChanged()
753 }
754
755 /** Notify the internal snapshot listener AND emit the public resume state. */
756 private notifyResumeSnapshotChanged(): void {
757 this.callbacksRef.onResumeSnapshotChange?.(this.resumeSnapshot)
758 this.emitResumeState()
759 }
760
761 /** Derive the public `resumeState` from the internal snapshot. */
762 private emitResumeState(): void {
763 const snapshot = this.resumeSnapshot
764 const state = snapshot?.resumeState
765 const resumeState: GenerationResumeState | null = state
766 ? {
767 ...state,
768 ...(snapshot?.pendingArtifacts && snapshot.pendingArtifacts.length > 0
769 ? { pendingArtifacts: [...snapshot.pendingArtifacts] }
770 : {}),
771 }
772 : null
773 this.callbacksRef.onResumeStateChange?.(resumeState)
774 }
775
776 /**
777 * Repaint the normal fields from a restored snapshot so a reload presents the
778 * video in `result` / `status` / `error` / `jobId`, never a snapshot object.
779 * `isLoading` stays false (no auto-tail). Not re-persisted (it came from
780 * storage / the server).
781 *
782 * A `complete` snapshot with no durable video artifact cannot be rebuilt, so
783 * it repaints as an error rather than a `success` with a `null` result — see
784 * the note on `GenerationClient.repaintFromSnapshot`.
785 */
786 private repaintFromSnapshot(snapshot: GenerationResumeSnapshot): void {
787 this.resumeSnapshot = snapshot
788 this.notifyResumeSnapshotChanged()
789 this.setStatus(clientStateFromResumeStatus(snapshot.status))
790 this.setError(
791 snapshot.error
792 ? Object.assign(
793 new Error(snapshot.error.message),
794 snapshot.error.code ? { code: snapshot.error.code } : {},
795 )
796 : undefined,
797 )
798 if (snapshot.result?.providerJobId)
799 this.setJobId(snapshot.result.providerJobId)
800 const restored = this.reconstructVideoResult(snapshot)
801 if (restored !== null) {
802 this.setResult(restored)
803 } else if (snapshot.status === 'complete') {
804 this.reportUnrestorableResult()
805 }
806 }
807
808 /**
809 * Report a `complete` snapshot with no durable video artifact to rebuild
810 * from. Runs after the status/error repaint above, so it wins over the
811 * snapshot's own `complete` status.
812 */
813 private reportUnrestorableResult(): void {
814 const error = new Error(GENERATION_UNRESTORABLE_RESULT_MESSAGE)
815 this.setStatus('error')
816 this.setError(error)
817 this.callbacksRef.onError?.(error)
818 }
819
820 /**
821 * Repaint a restored snapshot (client store or server hydrate) and, when it
822 * reports a run still in flight, tail that run to completion via `joinRun`
823 * (from the connection, or the `joinRun` option when the transport can't
824 * carry one).
825 *
826 * A `running` snapshot that no `joinRun` handler can tail is repainted as an
827 * interrupted error instead of a `generating` status that would never
828 * settle: an interrupted generation cannot be resumed, only re-run.
829 */
830 private repaintRestoredSnapshot(
831 snapshot: GenerationResumeSnapshot,
832 activeRunId?: string,
833 ): void {
834 if (snapshot.status !== 'running') {
835 this.repaintFromSnapshot(snapshot)
836 return
837 }
838 const joinRun = this.connection?.joinRun ?? this.joinRunHandler
839 const runId = activeRunId ?? snapshot.resumeState?.runId
840 if (runId && joinRun) {
841 this.repaintFromSnapshot(snapshot)
842 this.rejoinInFlight(runId)
843 return
844 }
845 this.repaintFromSnapshot({
846 ...snapshot,
847 resumeState: null,
848 status: 'error',
849 error: {
850 message:
851 'The previous generation was interrupted before it finished and cannot be resumed — generate again to retry.',
852 },
853 })
854 }
855
856 /**
857 * Rebuild a `VideoGenerateResult` from a restored snapshot: the video's bytes
858 * are served from the durable artifact URL, so the restored result renders
859 * from your own origin. Returns `null` when there is no durable video artifact.
860 */
861 private reconstructVideoResult(
862 snapshot: GenerationResumeSnapshot,
863 ): VideoGenerateResult | null {
864 const result = snapshot.result
865 const artifacts = result?.artifacts ?? []
866 const output = artifacts.find(
867 (a) =>
868 a.role === 'output' && a.source.mediaType === 'video' && a.url != null,
869 )
870 if (!output?.url) return null
871 return {
872 jobId: result?.providerJobId ?? '',
873 status: 'completed',
874 url: output.url,
875 ...(result?.expiresAt ? { expiresAt: new Date(result.expiresAt) } : {}),
876 artifacts,
877 }
878 }
879
880 /**
881 * The plain (non-Response) fetcher path never observes stream chunks, so
882 * the terminal snapshot is built here from the fetcher's own result. A
883 * stale `error` from a previous run is intentionally dropped — this run
884 * succeeded.
885 */
886 private completePlainFetcherResumeSnapshot(rawResult: unknown): void {
887 const previous = this.resumeSnapshot
888 const result = createGenerationResultSnapshot(rawResult)
889 this.resumeSnapshot = {
890 schemaVersion: 1,
891 resumeState: null,
892 status: 'complete',
893 ...(previous?.activity ? { activity: previous.activity } : {}),
894 ...(previous?.pendingArtifacts && previous.pendingArtifacts.length > 0
895 ? { pendingArtifacts: [...previous.pendingArtifacts] }
896 : {}),
897 ...(result
898 ? { result }
899 : previous?.result
900 ? { result: { ...previous.result } }
901 : {}),
902 }
903 this.notifyResumeSnapshotChanged()
904 }
905
906 /**
907 * Records a transport-level failure (network drop, throwing callback) in
908 * the snapshot. Without this, only a server-emitted RUN_ERROR chunk would
909 * mark the snapshot `error`, leaving a persisted record that claims the
910 * run is still in flight.
911 */
912 private recordResumeSnapshotError(error: Error): void {
913 // Surface the failure on the observable fields FIRST, unconditionally (see
914 // the note in GenerationClient.recordResumeSnapshotError): a RUN_ERROR
915 // already flipped the snapshot to `error`, so the early-return would else
916 // skip this and leave `status` stuck on `generating`. The guard avoids a
917 // duplicate `error` emission on the live `generate()` path.
918 if (this.status !== 'error') this.setStatus('error')
919 this.setError(error)
920 if (this.resumeSnapshot?.status === 'error') return
921 if (!this.resumeSnapshot && !this.serverDriven) return
922 const previous = this.resumeSnapshot
923 this.resumeSnapshot = {
924 schemaVersion: 1,
925 resumeState: null,
926 status: 'error',
927 ...(previous?.activity ? { activity: previous.activity } : {}),
928 ...(previous?.pendingArtifacts && previous.pendingArtifacts.length > 0
929 ? { pendingArtifacts: [...previous.pendingArtifacts] }
930 : {}),
931 ...(previous?.result ? { result: { ...previous.result } } : {}),
932 error: { message: error.message },
933 }
934 this.notifyResumeSnapshotChanged()
935 }
936
937 /**
938 * Drop the client's in-memory snapshot and re-emit. Purely local — this
939 * client writes no storage, so nothing persisted is removed.
940 */
941 private clearResumeSnapshot(): void {
942 this.resumeSnapshot = undefined
943 this.notifyResumeSnapshotChanged()
944 }
945
946 /**
947 * Server-driven mount hydration entry point (`persistence: true`). Runs at
948 * most once, from the commit-phase mount path (`mountDevtools`) — never the
949 * constructor / render phase — so remounts and speculative renders can't
950 * re-fire the hydrate GET.
951 */
952 private maybeHydrateFromServer(): void {
953 if (!this.serverDriven || this.serverHydrationStarted) return
954 this.serverHydrationStarted = true
955 if (this.connection?.hydrateGeneration ?? this.hydrateGenerationHandler) {
956 this.hydrateFromServer()
957 } else {
958 // `persistence: true` without any hydrate source can never restore
959 // anything — warn rather than silently no-op.
960 console.warn(
961 '[TanStack AI] `persistence: true` (server-driven) needs a `hydrateGeneration` handler — either a connection that implements one (e.g. `fetchServerSentEvents` / `fetchHttpStream`, or `stream()` / `rpcStream()` with persistence handlers) or the `hydrateGeneration` option. Without one, nothing is persisted or restored.',
962 )
963 }
964 }
965
966 /**
967 * Server-driven mount hydration (`persistence: true`). The client holds no
968 * local snapshot; on mount it asks the server — keyed by the stable threadId —
969 * for the last generation's resume snapshot, validates it, and repaints it. It
970 * never auto-starts a run, and never blocks: a `generate()` that starts first
971 * owns the client and hydration backs off, mirroring the chat client.
972 *
973 * A genuine **miss** (no record for the thread) is silent; a genuine
974 * **failure** (transport error, authorize rejection, malformed body, a record
975 * the validator rejects) surfaces through `status` / `error` / `onError` — see
976 * the note on `GenerationClient.hydrateFromServer`.
977 */
978 private hydrateFromServer(): void {
979 const hydrate =
980 this.connection?.hydrateGeneration ?? this.hydrateGenerationHandler
981 if (!hydrate) return
982 // A send that already started owns the client; don't stomp it.
983 if (this.resumeSnapshot || this.isLoading || this.status !== 'idle') return
984 void (async () => {
985 let res: GenerationHydrationResult
986 try {
987 res = await hydrate(this.threadId)
988 } catch (cause) {
989 this.failHydration(
990 createGenerationHydrationError(
991 'the request to the server did not succeed',
992 cause,
993 ),
994 )
995 return
996 }
997 // No record for this thread — a fresh thread, not a failure.
998 if (!res.resumeSnapshot) return
999 const snapshot = parseGenerationResumeSnapshot(res.resumeSnapshot)
1000 if (!snapshot) {
1001 this.failHydration(
1002 createGenerationHydrationError(
1003 'the server returned a record this client cannot read (unknown schema version, or a missing/invalid `status` or `resumeState`)',
1004 ),
1005 )
1006 return
1007 }
1008 // Re-check: a send may have started while the fetch was in flight.
1009 if (this.resumeSnapshot || this.isLoading || this.status !== 'idle')
1010 return
1011 // A run still generating on the server: re-attach and finish it in place.
1012 this.repaintRestoredSnapshot(snapshot, res.activeRun?.runId)
1013 })()
1014 }
1015
1016 /**
1017 * Surface a hydration failure on the observable fields. Skipped when a
1018 * `generate()` took ownership while the hydrate GET was in flight.
1019 */
1020 private failHydration(error: Error): void {
1021 if (this.resumeSnapshot || this.isLoading || this.status !== 'idle') return
1022 this.setStatus('error')
1023 this.setError(error)
1024 this.callbacksRef.onError?.(error)
1025 }
1026
1027 /**
1028 * Re-attach to an already-loaded `running` snapshot (remount case); see the
1029 * note in GenerationClient.maybeResumeInFlight. Guarded by `rejoinInFlight`.
1030 */
1031 private maybeResumeInFlight(): void {
1032 if (this.resumeSnapshot?.status !== 'running') return
1033 const runId = this.resumeSnapshot.resumeState?.runId
1034 if (runId) this.rejoinInFlight(runId)
1035 }
1036
1037 /**
1038 * Re-attach to a video run still generating and stream it to completion,
1039 * mirroring the chat client's mount-time rejoin. Reuses `processStream`, so
1040 * the job status and result repaint from the replayed chunks. A live
1041 * `generate()` owns the client and is never stomped; a run is rejoined once.
1042 */
1043 private rejoinInFlight(runId: string): void {
1044 const joinRun = this.connection?.joinRun ?? this.joinRunHandler
1045 if (!joinRun) return
1046 if (this.rejoinedRunId === runId) return
1047 if (this.isLoading || this.abortController) return
1048 this.rejoinedRunId = runId
1049 const controller = new AbortController()
1050 this.abortController = controller
1051 this.setIsLoading(true)
1052 this.setStatus('generating')
1053 void (async () => {
1054 try {
1055 await this.processStream(
1056 joinRun(runId, controller.signal),
1057 runId,
1058 controller.signal,
1059 )
1060 } catch (error) {
1061 if (!controller.signal.aborted) {
1062 const failure =
1063 error instanceof Error ? error : new Error(String(error))
1064 // Settles `status`/`error` AND rewrites the snapshot to a terminal
1065 // `error` with a null `resumeState`, so the next mount does not
1066 // rejoin this run again.
1067 this.recordResumeSnapshotError(failure)
1068 this.callbacksRef.onError?.(failure)
1069 }
1070 } finally {
1071 // Only reset if this rejoin still owns the client: a `stop()` +
1072 // fresh `generate()` may have replaced the controller while the tail
1073 // was settling, and that live run owns `isLoading` now.
1074 if (this.abortController === controller) {
1075 this.abortController = null
1076 this.setIsLoading(false)
1077 }
1078 }
1079 })()
1080 }
1081}