Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import {
3 parseRangeHeader,
4 retrieveArtifact,
5 retrieveBlob,
6} from '@tanstack/ai-persistence'
7import { generationServerPersistence } from '../lib/generation-server-store'
8
9/**
10 * The one route that serves persisted generation media, for every activity.
11 *
12 * `withGenerationPersistence` stores each generated file's bytes in the blob
13 * store and stamps an app-origin URL onto every artifact ref via `artifactUrl`
14 * — that URL points here. Because artifacts are addressed by their own id and
15 * carry their own `mimeType`, nothing about serving them is activity-specific:
16 * an image, a video, a music clip and a speech track all come back through this
17 * handler. Keeping it in one place is also what keeps the authorization check
18 * below in one place.
19 *
20 * `artifactServeUrl` in `../lib/generation-server-store` builds the URL, so the
21 * two stay in step.
22 */
23export const Route = createFileRoute('/api/artifacts')({
24 server: {
25 handlers: {
26 GET: async ({ request }) => {
27 const artifactId = new URL(request.url).searchParams.get('id')
28 if (!artifactId) {
29 return new Response('missing artifact id', { status: 400 })
30 }
31
32 const persistence = generationServerPersistence()
33 const artifact = await retrieveArtifact(persistence, artifactId)
34 if (!artifact) return new Response('not found', { status: 404 })
35
36 // A real multi-user app MUST authorize here before serving: the id
37 // comes from the caller, and `ArtifactRecord` carries the `threadId`
38 // to check it against. This demo is single-user, so there is no
39 // session to check.
40
41 // Video seeking is built on `Range`: the browser asks for a slice and
42 // expects `206` + `Content-Range`, and Safari refuses to play a source
43 // that ignores `Range` outright. `parseRangeHeader` resolves the
44 // header against the known size, so an unsatisfiable range is a `416`
45 // here rather than a bad `206`.
46 const range = parseRangeHeader(
47 request.headers.get('range'),
48 artifact.size,
49 )
50 if (range === 'unsatisfiable') {
51 return new Response('range not satisfiable', {
52 status: 416,
53 headers: { 'content-range': `bytes */${artifact.size}` },
54 })
55 }
56
57 const blob = await retrieveBlob(
58 persistence,
59 artifact,
60 range ? { range } : undefined,
61 )
62 if (!blob) return new Response('not found', { status: 404 })
63
64 const cacheHeaders = {
65 'content-type': artifact.mimeType,
66 // Artifact ids are content-addressed by run: the bytes behind an id
67 // never change, so this is safe to cache hard. `private` because a
68 // real deployment serves these per-user.
69 'cache-control': 'private, max-age=31536000, immutable',
70 // Advertised on every response, so a player knows it can seek.
71 'accept-ranges': 'bytes',
72 }
73 const body = blob.body ?? (await blob.arrayBuffer())
74
75 if (blob.range) {
76 const { offset, length } = blob.range
77 return new Response(body, {
78 status: 206,
79 headers: {
80 ...cacheHeaders,
81 'content-length': String(length),
82 'content-range': `bytes ${offset}-${offset + length - 1}/${artifact.size}`,
83 },
84 })
85 }
86
87 return new Response(body, {
88 headers: {
89 ...cacheHeaders,
90 'content-length': String(artifact.size),
91 },
92 })
93 },
94 },
95 },
96})