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

video-generation-client.ts

1,288 lines43.6 KB

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