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
59 const stream = generateImage({
60 adapter: grokImage('grok-imagine-image'),
61 prompt: input.prompt,
62 // `size` is deliberately not forwarded: the generic image input types
63 // it as `string`, while each adapter narrows it to its own union, and
64 // this page's UI never sends one.
65 ...(input.numberOfImages
66 ? { numberOfImages: input.numberOfImages }
67 : {}),
68 threadId,
69 runId,
70 stream: true,
71 middleware: [
72 withGenerationPersistence(generationServerPersistence(), {
73 threadId,
74 artifactUrl: (ref) => artifactServeUrl(ref.artifactId),
75 }),
76 ],
77 })
78
79 // Delivery durability: chunks are logged and id-tagged, so a reconnect
80 // or a mount-time `joinRun` replays instead of re-running the model.
81 return toServerSentEventsResponse(stream, {
82 durability: { adapter: memoryStream(request) },
83 })
84 },
85
86 // Two independent jobs, resolved in order:
87 // 1. `joinRun` delivery replay, when the request carries a resume offset.
88 // 2. Mount hydration for `persistence: true`: the latest run for
89 // `?threadId=`, as `{ resumeSnapshot, activeRun }`. Pass `authorize`
90 // here in a multi-user app.
91 GET: async ({ request }) =>
92 replayGenerationIfResuming(request) ??
93 (await reconstructGeneration(generationServerPersistence(), request)),
94 },
95 },
96})