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

video-generation-client.ts

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