Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import {
3 memoryStream,
4 resumeServerSentEventsResponse,
5 toServerSentEventsResponse,
6} from '@tanstack/ai'
7import type { StreamChunk } from '@tanstack/ai'
8
9/**
10 * Provider-free harness for the DURABLE, mid-run reload story — the guarantee a
11 * plain `persistence: true` restore can't prove: a one-shot generation whose
12 * client disconnects while it is still producing keeps running to its terminal
13 * and is tailed to completion by a mount-time `joinRun`.
14 *
15 * The run deliberately pauses between `RUN_STARTED` and its result, opening a
16 * window to reload mid-run. Because the POST wraps the stream in a `memoryStream`
17 * durability sink, the producer is decoupled from the delivery socket: cancelling
18 * the response (the reload) cancels only the reader, while the run drains its
19 * remaining chunks into the log. On mount the client GETs `?threadId=`, sees an
20 * `activeRun`, and `joinRun`s the log's resume cursor to the end — so the run
21 * finishes even though no client was connected when it did.
22 *
23 * The GET does double duty, exactly like the production generation routes:
24 * - a request carrying a resume offset is a `joinRun` replay — serve the log;
25 * - otherwise a `?threadId=` mount probe — answer with the
26 * `reconstructGeneration` shape (`{ resumeSnapshot, activeRun }`), reporting
27 * `activeRun` while the run is in flight and a `complete` snapshot once done.
28 *
29 * Exempt from the aimock policy: a fixed AG-UI sequence, never an LLM provider.
30 */
31
32// 1x1 transparent PNG — the live result's inline bytes.
33const TINY_PNG_B64 =
34 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=='
35
36// Durable app-origin serve URL, the way `withGenerationPersistence`'s
37// `artifactUrl` would stamp it. Present on the streamed result too, so the
38// rejoined image renders from our own origin.
39const DURABLE_IMAGE_URL = '/durable/generation-resume/image-1.png'
40
41// The run holds its result until the client has disconnected (the reload) AND a
42// later mount probe has observed the run as still `running`. A fixed settle
43// loses when CI hydration is slower than the timer, and the probe then restores
44// the finished snapshot (`image-restored`) instead of tailing the live run.
45// `DISCONNECT_FALLBACK_MS` only matters if this runtime never fires
46// `request.signal` on disconnect.
47const DISCONNECT_FALLBACK_MS = 3000
48
49// Runs still in flight per thread (the `activeRun` a mount probe reports), and
50// the finished job per thread (the `complete` snapshot a late probe restores).
51// Process-lifetime maps: the e2e server stays up across reloads.
52const runningByThread = new Map<string, string>()
53const completedByThread = new Map<string, Record<string, unknown>>()
54// Resolved when a mount probe has reported this run as `running`.
55const releaseResultByRun = new Map<string, () => void>()
56
57function stringField(body: unknown, key: string): string | undefined {
58 if (typeof body !== 'object' || body === null || !(key in body)) {
59 return undefined
60 }
61 const value: unknown = (body as Record<string, unknown>)[key]
62 return typeof value === 'string' ? value : undefined
63}
64
65function imageArtifact(threadId: string, runId: string) {
66 return {
67 role: 'output',
68 artifactId: 'artifact-image-1',
69 threadId,
70 runId,
71 name: 'image-1.png',
72 mimeType: 'image/png',
73 size: 68,
74 createdAt: new Date(0).toISOString(),
75 url: DURABLE_IMAGE_URL,
76 source: {
77 activity: 'image',
78 path: 'images.0',
79 provider: 'mock',
80 model: 'mock-image-model',
81 mediaType: 'image',
82 },
83 }
84}
85
86/**
87 * The metadata a done-restore would surface. Its id is DELIBERATELY distinct
88 * from the streamed run's `image-1`: this snapshot is only ever served when the
89 * mount probe finds a run already `complete`, i.e. the plain done-restore path.
90 * The spec asserts `image-1`, so if a reload ever degrades to a done-restore
91 * instead of a mid-run rejoin, the test fails loudly instead of passing for the
92 * wrong reason.
93 */
94function persistedResult(threadId: string, runId: string) {
95 return {
96 id: 'image-restored',
97 model: 'mock-image-model',
98 images: [{ url: DURABLE_IMAGE_URL }],
99 artifacts: [imageArtifact(threadId, runId)],
100 }
101}
102
103/** Resolves once the client disconnects, or after a fallback if it never does. */
104function waitForDisconnect(signal: AbortSignal): Promise<void> {
105 if (signal.aborted) return Promise.resolve()
106 return new Promise((resolve) => {
107 const finish = () => {
108 clearTimeout(timer)
109 signal.removeEventListener('abort', finish)
110 resolve()
111 }
112 const timer = setTimeout(finish, DISCONNECT_FALLBACK_MS)
113 signal.addEventListener('abort', finish, { once: true })
114 })
115}
116
117function imageRun(
118 threadId: string,
119 runId: string,
120 signal: AbortSignal,
121): AsyncIterable<StreamChunk> {
122 let releaseResult!: () => void
123 const resultObserved = new Promise<void>((resolve) => {
124 releaseResult = resolve
125 })
126 releaseResultByRun.set(runId, releaseResult)
127 return (async function* () {
128 try {
129 // Mark the run in flight before the first chunk, so a mount probe that
130 // races in right after the reload still sees the `activeRun` to rejoin.
131 runningByThread.set(threadId, runId)
132 yield {
133 type: 'RUN_STARTED',
134 threadId,
135 runId,
136 timestamp: Date.now(),
137 } as StreamChunk
138 // Hold the result until the client has disconnected (the reload) and the
139 // remounted client's probe has observed `running`. The result then lands
140 // in the durability log for `joinRun` to tail. A disconnect cancels only
141 // the socket; the durability pump keeps draining this generator.
142 await waitForDisconnect(signal)
143 await resultObserved
144 yield {
145 type: 'CUSTOM',
146 name: 'generation:result',
147 value: {
148 id: 'image-1',
149 model: 'mock-image-model',
150 images: [{ url: DURABLE_IMAGE_URL, b64Json: TINY_PNG_B64 }],
151 artifacts: [imageArtifact(threadId, runId)],
152 },
153 threadId,
154 runId,
155 timestamp: Date.now(),
156 } as StreamChunk
157 yield {
158 type: 'RUN_FINISHED',
159 threadId,
160 runId,
161 timestamp: Date.now(),
162 } as StreamChunk
163 // Terminal reached: record the finished job and drop the active marker, so a
164 // probe after completion restores a `complete` snapshot instead of rejoining.
165 completedByThread.set(threadId, persistedResult(threadId, runId))
166 runningByThread.delete(threadId)
167 } finally {
168 releaseResultByRun.delete(runId)
169 }
170 })()
171}
172
173export const Route = createFileRoute('/api/generation-persistence-resume')({
174 server: {
175 handlers: {
176 POST: async ({ request }) => {
177 const body: unknown = await request.json()
178 const threadId = stringField(body, 'threadId') ?? 'generation-resume'
179 const runId =
180 request.headers.get('X-Run-Id') ??
181 stringField(body, 'runId') ??
182 `run-${Date.now()}`
183 // Durable delivery: the run survives the reload and drains to the log.
184 // `request.signal` lets the run hold its result until the client is gone.
185 return toServerSentEventsResponse(
186 imageRun(threadId, runId, request.signal),
187 { durability: { adapter: memoryStream(request) } },
188 )
189 },
190
191 GET: ({ request }) => {
192 // 1. A resume offset means this is a `joinRun` replay — tail the log.
193 const durability = memoryStream(request)
194 if (durability.resumeFrom() !== null) {
195 return resumeServerSentEventsResponse({ adapter: durability })
196 }
197
198 // 2. Otherwise a `?threadId=` mount probe: report the in-flight run so
199 // the client rejoins it, or the finished job so it restores.
200 const threadId = new URL(request.url).searchParams.get('threadId') ?? ''
201 const runningRunId = threadId
202 ? runningByThread.get(threadId)
203 : undefined
204 const completed = threadId ? completedByThread.get(threadId) : undefined
205 if (runningRunId) releaseResultByRun.get(runningRunId)?.()
206 const body = runningRunId
207 ? {
208 resumeSnapshot: {
209 schemaVersion: 1,
210 resumeState: { threadId, runId: runningRunId },
211 status: 'running',
212 activity: 'image',
213 },
214 activeRun: { runId: runningRunId },
215 }
216 : completed
217 ? {
218 resumeSnapshot: {
219 schemaVersion: 1,
220 resumeState: null,
221 status: 'complete',
222 activity: 'image',
223 result: completed,
224 },
225 activeRun: null,
226 }
227 : { resumeSnapshot: null, activeRun: null }
228 return new Response(JSON.stringify(body), {
229 headers: {
230 'content-type': 'application/json',
231 'cache-control': 'no-store',
232 },
233 })
234 },
235 },
236 },
237})