Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import {
3 generateImage,
4 generationParamsFromRequest,
5 memoryStream,
6 toServerSentEventsResponse,
7} from '@tanstack/ai'
8import { grokImage } 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 * Image generation with SERVER-side persistence — the other half of the
21 * client-driven adapter in `generation-persistence.ts`.
22 *
23 * `withGenerationPersistence` records each run in `stores.generationRuns` and,
24 * because this backend also has `artifacts` + `blobs`, copies the generated
25 * bytes out of the provider's expiring URL into our own store. `artifactUrl`
26 * then stamps an app-origin serve URL onto every ref and rewrites the live
27 * result to it — so both the live and the restored image render from here.
28 *
29 * The stores are SQLite-backed, so a generated image is still there after a
30 * dev-server restart — reload the page and it renders from the database.
31 *
32 * The bytes themselves are served by the shared `/api/artifacts` route, which
33 * every generation activity here shares.
34 *
35 * Chunks are also logged for replay (see `../lib/generation-durability`), so
36 * the GET does two independent jobs, like the persistent-chat route: a
37 * `joinRun` delivery replay when the request carries a resume offset, and
38 * otherwise the `?threadId=` mount hydration that `persistence: true` calls.
39 */
40export const Route = createFileRoute('/api/generate/image')({
41 server: {
42 handlers: {
43 POST: async ({ request }) => {
44 // Carries `threadId` / `runId` off the AG-UI envelope as well as the
45 // input, so the run record is filed under the scope the client will
46 // later hydrate by.
47 const { input, threadId, runId } = await generationParamsFromRequest(
48 'image',
49 request,
50 )
51 if (typeof input.prompt !== 'string') {
52 throw new Error('This endpoint accepts text image prompts only.')
53 }
54
55 // Persistence needs the scope named. It is a type error to wire the
56 // middleware without one, so reject the request rather than inventing
57 // an id the client could never hydrate by.
58 if (!threadId) {
59 return new Response(
60 '`threadId` is required — it is the scope this generation is filed under.',
61 { status: 400 },
62 )
63 }
64
65 const stream = generateImage({
66 adapter: grokImage('grok-imagine-image'),
67 prompt: input.prompt,
68 // `size` is deliberately not forwarded: the generic image input types
69 // it as `string`, while each adapter narrows it to its own union, and
70 // this page's UI never sends one.
71 ...(input.numberOfImages
72 ? { numberOfImages: input.numberOfImages }
73 : {}),
74 ...(threadId ? { threadId } : {}),
75 ...(runId ? { runId } : {}),
76 stream: true,
77 middleware: [
78 withGenerationPersistence(generationServerPersistence(), {
79 threadId,
80 artifactUrl: (ref) => artifactServeUrl(ref.artifactId),
81 }),
82 ],
83 })
84
85 // Delivery durability: chunks are logged and id-tagged, so a reconnect
86 // or a mount-time `joinRun` replays instead of re-running the model.
87 return toServerSentEventsResponse(stream, {
88 durability: { adapter: memoryStream(request) },
89 })
90 },
91
92 // Two independent jobs, resolved in order:
93 // 1. `joinRun` delivery replay, when the request carries a resume offset.
94 // 2. Mount hydration for `persistence: true`: the latest run for
95 // `?threadId=`, as `{ resumeSnapshot, activeRun }`. Pass `authorize`
96 // here in a multi-user app.
97 GET: async ({ request }) =>
98 replayGenerationIfResuming(request) ??
99 (await reconstructGeneration(generationServerPersistence(), request)),
100 },
101 },
102})