Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { toServerSentEventsResponse } from '@tanstack/ai'
3import type { StreamChunk } from '@tanstack/ai'
4
5/**
6 * Provider-free harness route for the SERVER-DRIVEN generation-persistence
7 * story (`persistence: true` + `threadId`). It is the server-authoritative
8 * counterpart to `api.generation-persistence.ts` (the client-driven variant).
9 *
10 * The client keeps NO local store; on mount it probes the GET below with a
11 * `?threadId=` query and restores transparently from the returned
12 * `reconstructGeneration`-shaped JSON (`{ resumeSnapshot, activeRun }`) into the
13 * normal `result` / `status` fields. To make the round-trip real, POST records
14 * the finished job in a module-level in-memory map keyed by `threadId`, and GET
15 * reads it back — so a full `page.reload()` (empty client storage) still
16 * restores the last run's status + a `result` whose image comes from the durable
17 * artifact URL, exactly the path `reconstructGeneration` serves in production.
18 *
19 * We hand-build the JSON here rather than pull `@tanstack/ai-persistence` into
20 * the e2e app (it is not a dependency), mirroring the `server-interrupt`
21 * scenario in `api.persistence-durability.ts`. `reconstructGeneration` itself is
22 * unit-tested in `@tanstack/ai-persistence`; this proves the CLIENT restore.
23 *
24 * Exempt from the aimock policy: this route streams a fixed AG-UI sequence and
25 * never reaches an LLM provider's HTTP layer, so there is nothing to mock.
26 */
27
28// 1x1 transparent PNG — the live result's inline bytes, never persisted.
29const TINY_PNG_B64 =
30 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=='
31
32// Durable app-origin serve URL for the generated image (as
33// `withGenerationPersistence`'s `artifactUrl` would stamp it).
34const DURABLE_IMAGE_URL = '/durable/generation-server/image-1.png'
35
36// Server-authoritative record of the last completed generation per thread. In
37// production this is a `GenerationRunStore` row; here a process-lifetime map is
38// enough for the reload round-trip (the e2e server stays up across reloads).
39const completedByThread = new Map<string, Record<string, unknown>>()
40
41function stringField(body: unknown, key: string): string | undefined {
42 if (typeof body !== 'object' || body === null || !(key in body)) {
43 return undefined
44 }
45 const value: unknown = (body as Record<string, unknown>)[key]
46 return typeof value === 'string' ? value : undefined
47}
48
49function imageArtifact(threadId: string, runId: string) {
50 return {
51 role: 'output',
52 artifactId: 'artifact-image-1',
53 threadId,
54 runId,
55 name: 'image-1.png',
56 mimeType: 'image/png',
57 size: 68,
58 createdAt: new Date(0).toISOString(),
59 url: DURABLE_IMAGE_URL,
60 source: {
61 activity: 'image',
62 path: 'images.0',
63 provider: 'mock',
64 model: 'mock-image-model',
65 mediaType: 'image',
66 },
67 }
68}
69
70/** The metadata + durable artifact ref the server persists (never the bytes). */
71function persistedResult(threadId: string, runId: string) {
72 return {
73 id: 'image-1',
74 model: 'mock-image-model',
75 artifacts: [imageArtifact(threadId, runId)],
76 }
77}
78
79function imageRun(threadId: string, runId: string): AsyncIterable<StreamChunk> {
80 return (async function* () {
81 yield {
82 type: 'RUN_STARTED',
83 threadId,
84 runId,
85 timestamp: Date.now(),
86 } as StreamChunk
87 yield {
88 type: 'CUSTOM',
89 name: 'generation:result',
90 value: {
91 id: 'image-1',
92 model: 'mock-image-model',
93 images: [{ b64Json: TINY_PNG_B64 }],
94 artifacts: [imageArtifact(threadId, runId)],
95 },
96 threadId,
97 runId,
98 timestamp: Date.now(),
99 } as StreamChunk
100 yield {
101 type: 'RUN_FINISHED',
102 threadId,
103 runId,
104 timestamp: Date.now(),
105 } as StreamChunk
106 // The run finished: record the job the way `withGenerationPersistence`
107 // would, so the GET restore below can rebuild it after a reload.
108 completedByThread.set(threadId, persistedResult(threadId, runId))
109 })()
110}
111
112export const Route = createFileRoute('/api/generation-persistence-server')({
113 server: {
114 handlers: {
115 POST: async ({ request }) => {
116 // The client sends an AG-UI RunAgentInput body carrying the hook's
117 // stable `threadId` (via runContext) — the same id the GET restore
118 // probe queries — plus the run id in the X-Run-Id header.
119 const body: unknown = await request.json()
120 const threadId = stringField(body, 'threadId') ?? 'generation-server'
121 const runId =
122 request.headers.get('X-Run-Id') ??
123 stringField(body, 'runId') ??
124 `run-${Date.now()}`
125 return toServerSentEventsResponse(imageRun(threadId, runId))
126 },
127
128 // Server-authoritative restore: the `persistence: true` client's mount
129 // probe (`?threadId=`). Returns the same `{ resumeSnapshot, activeRun }`
130 // shape `reconstructGeneration` produces — a `complete` snapshot whose
131 // result carries the durable artifact ref once the thread has a recorded
132 // job, else the empty first-load answer.
133 GET: ({ request }) => {
134 const threadId = new URL(request.url).searchParams.get('threadId') ?? ''
135 const result = threadId ? completedByThread.get(threadId) : undefined
136 const body = result
137 ? {
138 resumeSnapshot: {
139 schemaVersion: 1,
140 resumeState: null,
141 status: 'complete',
142 activity: 'image',
143 result,
144 },
145 activeRun: null,
146 }
147 : { resumeSnapshot: null, activeRun: null }
148 return new Response(JSON.stringify(body), {
149 headers: {
150 'content-type': 'application/json',
151 'cache-control': 'no-store',
152 },
153 })
154 },
155 },
156 },
157})