Open History to see the last commit
1import { validateReconstructGenerationStores } from './types'
2import type { AIPersistence, GenerationRunRecord } from './types'
3
4/**
5 * The JSON body `reconstructGeneration` returns and a server-authoritative
6 * client hydrates from on mount.
7 *
8 * `resumeSnapshot` mirrors the last generation run for the requested thread (or
9 * a specific run id): its terminal/running `status`, the `result` metadata and
10 * `error` it recorded, the `activity` it ran, and a `resumeState` cursor
11 * (present only while the run is still `running`) the client can use to tail the
12 * live generation. `null` when there is no matching run.
13 *
14 * `activeRun` is `{ runId }` when the resolved run is still `running`, else
15 * `null` — the parallel of {@link ReconstructedChat.activeRun}.
16 */
17export interface ReconstructedGeneration {
18 resumeSnapshot: {
19 schemaVersion: 1
20 resumeState: { threadId: string; runId: string } | null
21 status: 'idle' | 'running' | 'complete' | 'error'
22 result?: unknown
23 error?: { message: string; code?: string }
24 activity?: string
25 } | null
26 activeRun: { runId: string } | null
27}
28
29export interface ReconstructGenerationOptions {
30 /** Query parameter carrying the thread id. Defaults to `threadId`. */
31 param?: string
32 /** Query parameter carrying the run id. Defaults to `runId`. */
33 runParam?: string
34 /**
35 * Authorize access to the requested generation before loading it.
36 *
37 * ⚠️ Without this, any caller who knows or guesses `?threadId=` / `?runId=`
38 * receives the generation's status and result metadata. Multi-user /
39 * multi-tenant deployments **must** supply an authorization check (session →
40 * owned thread/run) or resolve a validated id in the route.
41 *
42 * Called with whichever id was supplied — the `runId` when present, else the
43 * `threadId`. Return:
44 * - `true` to allow the load
45 * - `false` for a default `403` response
46 * - a `Response` to return as-is (e.g. `401` with a body)
47 */
48 authorize?: (
49 id: string,
50 request: Request,
51 ) => boolean | Response | Promise<boolean | Response>
52}
53
54/**
55 * Map the persisted run status to the client-facing resume-snapshot status.
56 * An `interrupted` or `aborted` run surfaces as `error` — the client has no live
57 * run to resume, and neither produced a usable result. (A generation abort is
58 * always terminal: there is no journal to reattach to, so `withGenerationPersistence`
59 * writes `'aborted'` rather than parking the run.)
60 */
61function snapshotStatus(
62 status: GenerationRunRecord['status'],
63): 'running' | 'complete' | 'error' {
64 switch (status) {
65 case 'running':
66 return 'running'
67 case 'completed':
68 return 'complete'
69 case 'failed':
70 case 'interrupted':
71 case 'aborted':
72 return 'error'
73 }
74}
75
76function runToSnapshot(
77 run: GenerationRunRecord,
78): NonNullable<ReconstructedGeneration['resumeSnapshot']> {
79 const status = snapshotStatus(run.status)
80 return {
81 schemaVersion: 1,
82 resumeState:
83 status === 'running'
84 ? { runId: run.runId, threadId: run.threadId }
85 : null,
86 status,
87 ...(run.result !== undefined ? { result: run.result } : {}),
88 ...(run.error !== undefined ? { error: run.error } : {}),
89 ...(run.activity !== undefined ? { activity: run.activity } : {}),
90 }
91}
92
93function jsonResponse(body: ReconstructedGeneration): Response {
94 return new Response(JSON.stringify(body), {
95 headers: {
96 'content-type': 'application/json',
97 'cache-control': 'no-store',
98 },
99 })
100}
101
102export interface GetGenerationHydrationOptions {
103 /**
104 * How to interpret `id`:
105 * - `'runId'` loads exactly that run via `stores.generationRuns.get`.
106 * - `'threadId'` (default) loads the latest run linked to the thread via
107 * `stores.generationRuns.findLatestForThread`.
108 */
109 by?: 'threadId' | 'runId'
110}
111
112/**
113 * The request-free core of {@link reconstructGeneration}: read the last
114 * generation run for a thread (or a specific run) straight from the
115 * `generationRuns` store and return the plain `{ resumeSnapshot, activeRun }`
116 * hydration payload a server-authoritative client adopts on mount.
117 *
118 * Use this from a TanStack Start server function (or any direct call) to back
119 * a client's `hydrateGeneration` handler without fabricating a `Request`:
120 *
121 * ```ts
122 * async function loadImageHydration({ data: threadId }: { data: string }) {
123 * // Do your own auth here — this helper does not enforce tenancy.
124 * return await getGenerationHydration(persistence, threadId)
125 * }
126 * ```
127 *
128 * Wire that body up as the server function's handler — build it with
129 * `createServerFn({ method: 'GET' })`, add an `inputValidator` that returns
130 * the thread id, then hand it the function above. (The chained call is shown
131 * split apart on purpose: Start's server-fn plugin decides which modules to
132 * transform by scanning source text for that call, and a package whose shipped
133 * comments contain it gets pulled into the transform.)
134 *
135 * ⚠️ Unlike {@link reconstructGeneration} this helper takes **no** `authorize`
136 * option — there is no `Request` to authorize against. Server-function callers
137 * must gate the call themselves (session → owned thread/run) before resolving
138 * the id, or any caller who guesses an id receives the run's status and result
139 * metadata.
140 *
141 * Returns `{ resumeSnapshot: null, activeRun: null }` when `id` is empty or no
142 * matching run exists, so the caller never has to special-case a first load.
143 */
144export async function getGenerationHydration(
145 persistence: AIPersistence,
146 id: string,
147 options?: GetGenerationHydrationOptions,
148): Promise<ReconstructedGeneration> {
149 validateReconstructGenerationStores(persistence)
150 const runStore = persistence.stores.generationRuns
151 if (!runStore) {
152 // validateReconstructGenerationStores already throws; this narrows for TS.
153 throw new Error('getGenerationHydration requires stores.generationRuns.')
154 }
155
156 if (!id) {
157 return { resumeSnapshot: null, activeRun: null }
158 }
159
160 const run =
161 options?.by === 'runId'
162 ? await runStore.get(id)
163 : await runStore.findLatestForThread(id)
164
165 if (!run) {
166 return { resumeSnapshot: null, activeRun: null }
167 }
168
169 return {
170 resumeSnapshot: runToSnapshot(run),
171 activeRun: run.status === 'running' ? { runId: run.runId } : null,
172 }
173}
174
175/**
176 * Build the JSON `Response` a server-authoritative client hydrates a generation
177 * from on load. Reads a `?runId=` (preferred) or `?threadId=` from the request
178 * query and returns `{ resumeSnapshot, activeRun }`
179 * ({@link ReconstructedGeneration}):
180 *
181 * - Resolves the run by `runId` via `stores.generationRuns.get`, else the
182 * latest run filed under `threadId` via the required
183 * `stores.generationRuns.findLatestForThread`.
184 * - `resumeSnapshot` — the run mapped to a client snapshot (status, result,
185 * error, activity, and a `resumeState` cursor while still running), or `null`.
186 * - `activeRun` — `{ runId }` when the run is still generating, else `null`.
187 *
188 * Requires `stores.generationRuns`. Returns
189 * `{ resumeSnapshot: null, activeRun: null }` when no id is supplied or no
190 * matching run exists, so the caller never has to special-case a first load.
191 *
192 * This helper does **not** enforce tenancy by itself. Pass
193 * {@link ReconstructGenerationOptions.authorize} (or wrap the call in your own
194 * session gate) before exposing it on a public route.
195 *
196 * ```ts
197 * export async function GET(request: Request) {
198 * return reconstructGeneration(persistence, request, {
199 * authorize: async (id, req) => {
200 * const userId = await getSessionUserId(req)
201 * return userId != null && (await userOwnsThread(userId, id))
202 * },
203 * })
204 * }
205 * ```
206 */
207export async function reconstructGeneration(
208 persistence: AIPersistence,
209 request: Request,
210 options?: ReconstructGenerationOptions,
211): Promise<Response> {
212 const params = new URL(request.url).searchParams
213 const runParam = options?.runParam ?? 'runId'
214 const threadParam = options?.param ?? 'threadId'
215 const runId = params.get(runParam) ?? ''
216 const threadId = params.get(threadParam) ?? ''
217
218 const id = runId || threadId
219 if (!id) {
220 return jsonResponse({ resumeSnapshot: null, activeRun: null })
221 }
222
223 if (options?.authorize) {
224 const decision = await options.authorize(id, request)
225 if (decision instanceof Response) {
226 return decision
227 }
228 if (!decision) {
229 return new Response(JSON.stringify({ error: 'Forbidden' }), {
230 status: 403,
231 headers: {
232 'content-type': 'application/json',
233 'cache-control': 'no-store',
234 },
235 })
236 }
237 }
238
239 return jsonResponse(
240 await getGenerationHydration(persistence, id, {
241 by: runId ? 'runId' : 'threadId',
242 }),
243 )
244}