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), then
42// settles briefly so the remounted client's mount probe reliably observes the
43// run as still `running` and takes the `joinRun` path. `DISCONNECT_FALLBACK_MS`
44// only matters if this runtime never fires `request.signal` on disconnect — the
45// run still completes strictly after the reload either way.
46const DISCONNECT_FALLBACK_MS = 3000
47const SETTLE_AFTER_DISCONNECT_MS = 1500
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
55function stringField(body: unknown, key: string): string | undefined {
56 if (typeof body !== 'object' || body === null || !(key in body)) {
57 return undefined
58 }
59 const value: unknown = (body as Record<string, unknown>)[key]
60 return typeof value === 'string' ? value : undefined
61}
62
63function imageArtifact(threadId: string, runId: string) {
64 return {
65 role: 'output',
66 artifactId: 'artifact-image-1',
67 threadId,
68 runId,
69 name: 'image-1.png',
70 mimeType: 'image/png',
71 size: 68,
72 createdAt: new Date(0).toISOString(),
73 url: DURABLE_IMAGE_URL,
74 source: {
75 activity: 'image',
76 path: 'images.0',
77 provider: 'mock',
78 model: 'mock-image-model',
79 mediaType: 'image',
80 },
81 }
82}
83
84/**
85 * The metadata a done-restore would surface. Its id is DELIBERATELY distinct
86 * from the streamed run's `image-1`: this snapshot is only ever served when the
87 * mount probe finds a run already `complete`, i.e. the plain done-restore path.
88 * The spec asserts `image-1`, so if a reload ever degrades to a done-restore
89 * instead of a mid-run rejoin, the test fails loudly instead of passing for the
90 * wrong reason.
91 */
92function persistedResult(threadId: string, runId: string) {
93 return {
94 id: 'image-restored',
95 model: 'mock-image-model',
96 images: [{ url: DURABLE_IMAGE_URL }],
97 artifacts: [imageArtifact(threadId, runId)],
98 }
99}
100
101function delay(ms: number): Promise<void> {
102 return new Promise((resolve) => setTimeout(resolve, ms))
103}
104
105/** Resolves once the client disconnects, or after a fallback if it never does. */
106function waitForDisconnect(signal: AbortSignal): Promise<void> {
107 if (signal.aborted) return Promise.resolve()
108 return new Promise((resolve) => {
109 const finish = () => {
110 clearTimeout(timer)
111 signal.removeEventListener('abort', finish)
112 resolve()
113 }
114 const timer = setTimeout(finish, DISCONNECT_FALLBACK_MS)
115 signal.addEventListener('abort', finish, { once: true })
116 })
117}
118
119function imageRun(
120 threadId: string,
121 runId: string,
122 signal: AbortSignal,
123): AsyncIterable<StreamChunk> {
124 return (async function* () {
125 // Mark the run in flight before the first chunk, so a mount probe that
126 // races in right after the reload still sees the `activeRun` to rejoin.
127 runningByThread.set(threadId, runId)
128 yield {
129 type: 'RUN_STARTED',
130 threadId,
131 runId,
132 timestamp: Date.now(),
133 } as StreamChunk
134 // Hold the result until the client has disconnected (the reload), then a
135 // short settle so the remounted client's probe still sees `running`. This
136 // makes the result land strictly AFTER the reload — the run cannot complete
137 // as a done-restore before the reload, so the rejoin is the path exercised.
138 // A client that reloads here cancels only the socket; the durability pump
139 // keeps draining this generator to its terminal.
140 await waitForDisconnect(signal)
141 await delay(SETTLE_AFTER_DISCONNECT_MS)
142 yield {
143 type: 'CUSTOM',
144 name: 'generation:result',
145 value: {
146 id: 'image-1',
147 model: 'mock-image-model',
148 images: [{ url: DURABLE_IMAGE_URL, b64Json: TINY_PNG_B64 }],
149 artifacts: [imageArtifact(threadId, runId)],
150 },
151 threadId,
152 runId,
153 timestamp: Date.now(),
154 } as StreamChunk
155 yield {
156 type: 'RUN_FINISHED',
157 threadId,
158 runId,
159 timestamp: Date.now(),
160 } as StreamChunk
161 // Terminal reached: record the finished job and drop the active marker, so a
162 // probe after completion restores a `complete` snapshot instead of rejoining.
163 completedByThread.set(threadId, persistedResult(threadId, runId))
164 runningByThread.delete(threadId)
165 })()
166}
167
168export const Route = createFileRoute('/api/generation-persistence-resume')({
169 server: {
170 handlers: {
171 POST: async ({ request }) => {
172 const body: unknown = await request.json()
173 const threadId = stringField(body, 'threadId') ?? 'generation-resume'
174 const runId =
175 request.headers.get('X-Run-Id') ??
176 stringField(body, 'runId') ??
177 `run-${Date.now()}`
178 // Durable delivery: the run survives the reload and drains to the log.
179 // `request.signal` lets the run hold its result until the client is gone.
180 return toServerSentEventsResponse(
181 imageRun(threadId, runId, request.signal),
182 { durability: { adapter: memoryStream(request) } },
183 )
184 },
185
186 GET: ({ request }) => {
187 // 1. A resume offset means this is a `joinRun` replay — tail the log.
188 const durability = memoryStream(request)
189 if (durability.resumeFrom() !== null) {
190 return resumeServerSentEventsResponse({ adapter: durability })
191 }
192
193 // 2. Otherwise a `?threadId=` mount probe: report the in-flight run so
194 // the client rejoins it, or the finished job so it restores.
195 const threadId = new URL(request.url).searchParams.get('threadId') ?? ''
196 const runningRunId = threadId
197 ? runningByThread.get(threadId)
198 : undefined
199 const completed = threadId ? completedByThread.get(threadId) : undefined
200 const body = runningRunId
201 ? {
202 resumeSnapshot: {
203 schemaVersion: 1,
204 resumeState: { threadId, runId: runningRunId },
205 status: 'running',
206 activity: 'image',
207 },
208 activeRun: { runId: runningRunId },
209 }
210 : completed
211 ? {
212 resumeSnapshot: {
213 schemaVersion: 1,
214 resumeState: null,
215 status: 'complete',
216 activity: 'image',
217 result: completed,
218 },
219 activeRun: null,
220 }
221 : { resumeSnapshot: null, activeRun: null }
222 return new Response(JSON.stringify(body), {
223 headers: {
224 'content-type': 'application/json',
225 'cache-control': 'no-store',
226 },
227 })
228 },
229 },
230 },
231})