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

api.generate.video.ts

87 lines3.6 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
42 // `forwardedProps`: `size` and `model` are adapter-specific unions
43 // that the provider-agnostic video input widens to `string`.
44 const { prompt, size, duration, model } = body.forwardedProps
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​
51 const stream = generateVideo({
52 adapter: grokVideo(model ?? 'grok-imagine-video'),
53 prompt,
54 size,
55 duration,
56 stream: true,
57 pollingInterval: 3000,
58 maxDuration: 600_000,
59 threadId,
60 runId,
61 middleware: [
62 withGenerationPersistence(generationServerPersistence(), {
63 threadId,
64 artifactUrl: (ref) => artifactServeUrl(ref.artifactId),
65 }),
66 ],
67 })
68​
69 // Durable delivery: the run survives a reload and keeps polling to
70 // completion into the log; a mount-time `joinRun` tails it to the end.
71 return toServerSentEventsResponse(stream, {
72 durability: { adapter: memoryStream(request) },
73 })
74 },
75​
76 // Two independent jobs, resolved in order (like the image route):
77 // 1. `joinRun` delivery replay, when the request carries a resume offset —
78 // re-attach to a run still in flight from a previous request.
79 // 2. Mount hydration for `persistence: true`: the latest run for
80 // `?threadId=`, as `{ resumeSnapshot, activeRun }`, so a completed
81 // video (aged out of the delivery log) still restores after a reload.
82 GET: async ({ request }) =>
83 replayGenerationIfResuming(request) ??
84 (await reconstructGeneration(generationServerPersistence(), request)),
85 },
86 },
87})