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

api.generate.video.ts

93 lines3.8 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 generateVideo,
4 generationParamsFromBody,
5 memoryStream,
6 toServerSentEventsResponse,
7} from '@tanstack/ai'
8import { grokVideo } from '@tanstack/ai-grok'
9import {
10 reconstructGeneration,
11 withGenerationPersistence,
12} from '@tanstack/ai-persistence'
13import { replayGenerationIfResuming } from '../lib/generation-durability'
14import {
15 artifactServeUrl,
16 generationServerPersistence,
17} from '../lib/generation-server-store'
18​
19/**
20 * Video generation, durable end to end — the activity that needs it most: a run
21 * takes minutes, so a refresh mid-job is the normal case rather than the edge.
22 *
23 * - STATE: `withGenerationPersistence` records the run and copies the finished
24 * video into our blob store, and `artifactUrl` rewrites the result to the
25 * shared `/api/artifacts` route — so it still plays after the provider's link
26 * expires.
27 * - DELIVERY + LIFETIME: `memoryStream` logs each chunk for replay, and because
28 * a durable response is decoupled from its request, a reload cancels only the
29 * reader — the run keeps polling to completion into the log, and the client's
30 * `joinRun` on mount tails it to the end. No route-side detachment needed; the
31 * library owns the run's lifetime once `durability` is set.
32 *
33 * The GET does two jobs: `joinRun` delivery replay for an in-flight run, then
34 * `?threadId=` mount hydration for a finished run whose delivery log aged out.
35 */
36export const Route = createFileRoute('/api/generate/video')({
37 server: {
38 handlers: {
39 POST: async ({ request }) => {
40 const body = await request.json()
41 // Adapter arguments come straight off the envelope's `data`: `size` and
42 // `model` are adapter-specific unions that the provider-agnostic video
43 // input widens to `string`.
44 const { prompt, size, duration, model } = body.data
45 const { threadId, runId } = generationParamsFromBody('video', body)
46​
47 // Persistence needs the scope named. It is a type error to wire the
48 // middleware without one, so reject the request rather than inventing
49 // an id the client could never hydrate by.
50 if (!threadId) {
51 return new Response(
52 '`threadId` is required — it is the scope this generation is filed under.',
53 { status: 400 },
54 )
55 }
56​
57 const stream = generateVideo({
58 adapter: grokVideo(model ?? 'grok-imagine-video'),
59 prompt,
60 size,
61 duration,
62 stream: true,
63 pollingInterval: 3000,
64 maxDuration: 600_000,
65 ...(threadId ? { threadId } : {}),
66 ...(runId ? { runId } : {}),
67 middleware: [
68 withGenerationPersistence(generationServerPersistence(), {
69 threadId,
70 artifactUrl: (ref) => artifactServeUrl(ref.artifactId),
71 }),
72 ],
73 })
74​
75 // Durable delivery: the run survives a reload and keeps polling to
76 // completion into the log; a mount-time `joinRun` tails it to the end.
77 return toServerSentEventsResponse(stream, {
78 durability: { adapter: memoryStream(request) },
79 })
80 },
81​
82 // Two independent jobs, resolved in order (like the image route):
83 // 1. `joinRun` delivery replay, when the request carries a resume offset —
84 // re-attach to a run still in flight from a previous request.
85 // 2. Mount hydration for `persistence: true`: the latest run for
86 // `?threadId=`, as `{ resumeSnapshot, activeRun }`, so a completed
87 // video (aged out of the delivery log) still restores after a reload.
88 GET: async ({ request }) =>
89 replayGenerationIfResuming(request) ??
90 (await reconstructGeneration(generationServerPersistence(), request)),
91 },
92 },
93})