Open History to see the last commit
1import { isTerminalRunStatus, modelMessagesToUIMessages } from '@tanstack/ai'
2import type {
3 ModelMessage,
4 RunRecord,
5 SubagentPart,
6 TerminalRunStatus,
7 UIMessage,
8} from '@tanstack/ai'
9import { storedSubagentInfo } from './subagent-runs'
10import { validateReconstructChatStores } from './types'
11import type {
12 AIPersistence,
13 ChatTranscriptStores,
14 InterruptRecord,
15 MessagePage,
16 MessageStore,
17} from './types'
18
19const MAX_PAGE_SIZE = 500
20
21/**
22 * The JSON body `reconstructChat` returns and a server-authoritative client
23 * hydrates from on mount.
24 *
25 * `messages` is the stored transcript as UI messages (ready to paint).
26 * `activeRun` is a cursor to a run still generating for the thread, or `null` —
27 * resolved from the STABLE thread id via `stores.runs.findActiveRun`, so the
28 * client learns "there is a live run to tail" without ever handling a run id.
29 * `interrupts` is the thread's pending human-in-the-loop interrupts (tool
30 * approvals, client-tool/generic waits) and the run they paused, or `null` —
31 * so a reload (or another device) re-prompts the approval from the SERVER, not
32 * from client storage. Resolved via `stores.interrupts.listPending`.
33 * `page` is set only when the GET included a valid `limit`. `truncated` is true
34 * when older UI messages exist. `cursor` is the opaque `before` token for the
35 * next older window.
36 */
37export interface ReconstructedChat {
38 messages: Array<UIMessage>
39 activeRun: { runId: string } | null
40 interrupts: {
41 runId: string
42 pending: Array<Record<string, unknown>>
43 } | null
44 page?: { truncated: false } | { truncated: true; cursor: string }
45 /**
46 * The thread's finished runs, ascending by `startedAt`. Set only when
47 * {@link ReconstructChatOptions.includeRuns} is `true` and the `runs` store
48 * implements `listByThread`. Each assistant message of a listed run also
49 * gets the timings on `message.metadata.tanstack.run`.
50 */
51 runs?: Array<{
52 runId: string
53 status: TerminalRunStatus
54 startedAt: number
55 finishedAt?: number
56 }>
57}
58
59export interface ReconstructChatOptions {
60 /** Query parameter carrying the thread id. Defaults to `threadId`. */
61 param?: string
62 /**
63 * Add the thread's finished runs, with `startedAt` and `finishedAt`, to the
64 * response as `runs`. Needs a `runs` store that implements `listByThread`.
65 * Default: `false`.
66 */
67 includeRuns?: boolean
68 /**
69 * Authorize access to the requested thread before loading history.
70 *
71 * ⚠️ Without this, any caller who knows or guesses `?threadId=` receives the
72 * full transcript. Multi-user / multi-tenant deployments **must** supply
73 * an authorization check (session → owned threads) or resolve a validated
74 * thread id in the route and pass it via a custom `param` that only your
75 * server sets.
76 *
77 * Return:
78 * - `true` to allow the load
79 * - `false` for a default `403` response
80 * - a `Response` to return as-is (e.g. `401` with a body)
81 */
82 authorize?: (
83 threadId: string,
84 request: Request,
85 ) => boolean | Response | Promise<boolean | Response>
86}
87
88/**
89 * Build the JSON `Response` a server-authoritative client hydrates from on load
90 * (see the client-persistence guide). Reads the thread id from the request query
91 * (`?threadId=` by default) and returns `{ messages, activeRun, interrupts }`
92 * ({@link ReconstructedChat}):
93 *
94 * - `messages` — the stored transcript as UI messages.
95 * - `activeRun` — `{ runId }` if a run is still generating for the thread (so the
96 * client tails it via the durability stream), else `null`. Resolved via the
97 * required `stores.runs.findActiveRun`; `null` when the `runs` store is absent.
98 * - `interrupts` — `{ runId, pending }` if the thread has pending human-in-the-loop
99 * interrupts (a paused approval / wait) and the run they paused, else `null`, so
100 * a reload re-prompts the decision from the server. Resolved via the optional
101 * `stores.interrupts.listPending`; `null` when that store is absent.
102 *
103 * Paging is opt-in. A valid `?limit=` (positive integer, capped at 500) returns
104 * the newest window of UI messages plus `page`. `?before=` walks to an older
105 * window. Invalid `limit` (`0`, negative, NaN) is ignored and the full
106 * transcript is returned. `activeRun` and `interrupts` are never paged.
107 *
108 * Requires `stores.messages`. Returns an empty transcript with no active run
109 * and no interrupts when the thread id is missing or the thread is unknown, so
110 * the caller never has to special-case a first load.
111 *
112 * This helper does **not** enforce tenancy by itself. Pass
113 * {@link ReconstructChatOptions.authorize} (or wrap the call in your own
114 * session gate) before exposing it on a public route.
115 *
116 * ```ts
117 * export async function GET(request: Request) {
118 * return reconstructChat(persistence, request, {
119 * authorize: async (threadId, req) => {
120 * const userId = await getSessionUserId(req)
121 * return userId != null && (await userOwnsThread(userId, threadId))
122 * },
123 * })
124 * }
125 * ```
126 */
127export async function reconstructChat(
128 persistence: AIPersistence<ChatTranscriptStores>,
129 request: Request,
130 options?: ReconstructChatOptions,
131): Promise<Response> {
132 validateReconstructChatStores(persistence)
133 const messageStore = persistence.stores.messages
134 if (!messageStore) {
135 // validateReconstructChatStores already throws; this narrows for TypeScript.
136 throw new Error('reconstructChat requires stores.messages.')
137 }
138
139 const requestUrl = new URL(request.url)
140 const param = options?.param ?? 'threadId'
141 const threadId = requestUrl.searchParams.get(param) ?? ''
142 const pageSize = parsePageSize(requestUrl.searchParams.get('limit'))
143 const before = parseBefore(requestUrl.searchParams.get('before'))
144
145 if (threadId && options?.authorize) {
146 const decision = await options.authorize(threadId, request)
147 if (decision instanceof Response) {
148 return decision
149 }
150 if (!decision) {
151 return new Response(JSON.stringify({ error: 'Forbidden' }), {
152 status: 403,
153 headers: {
154 'content-type': 'application/json',
155 'cache-control': 'no-store',
156 },
157 })
158 }
159 }
160
161 // Resolve the active run BEFORE reading the transcript. `withPersistence`
162 // persists the final transcript BEFORE marking a run complete, so observing
163 // "no active run" here guarantees the transcript read below is the FINAL one.
164 // Reading them in the other order opens a finish-window race: a fast run that
165 // completes between the two reads would return a stale streaming snapshot with
166 // `activeRun: null`, leaving the client stuck on the partial (no run to tail).
167 const active = threadId
168 ? await persistence.stores.runs?.findActiveRun(threadId)
169 : null
170 const stored =
171 threadId === ''
172 ? []
173 : pageSize === undefined
174 ? await messageStore.loadThread(threadId)
175 : await messageStore.loadThread(threadId, {
176 limit: pageSize + 1,
177 ...(before === undefined ? {} : { before }),
178 })
179 // Pending interrupts for the thread, so a reload re-prompts the approval from
180 // the server. Each stored `payload` is the full interrupt descriptor the
181 // client hydrates; they share the run they paused.
182 const pending = threadId
183 ? ((await persistence.stores.interrupts?.listPending(threadId)) ?? [])
184 : []
185 const firstPending = pending[0]
186 const isPaging = pageSize !== undefined && threadId !== ''
187 const transcript = !isPaging
188 ? {
189 messages: modelMessagesToUIMessages(threadMessages(stored)),
190 }
191 : Array.isArray(stored)
192 ? await windowFromArray({
193 stored,
194 messageStore,
195 threadId,
196 pageSize,
197 before,
198 })
199 : windowFromMessagePage(stored, pageSize)
200 const messages = await attachSubagentCards(
201 transcript.messages,
202 persistence.stores.runs,
203 messageStore,
204 threadId,
205 pending,
206 )
207 const runStore = persistence.stores.runs
208 const runs =
209 options?.includeRuns && threadId && runStore?.listByThread
210 ? (await runStore.listByThread(threadId)).flatMap((run) =>
211 isTerminalRunStatus(run.status)
212 ? [
213 {
214 runId: run.runId,
215 status: run.status,
216 startedAt: run.startedAt,
217 ...(run.finishedAt !== undefined && {
218 finishedAt: run.finishedAt,
219 }),
220 },
221 ]
222 : [],
223 )
224 : undefined
225 const body: ReconstructedChat = {
226 messages: runs ? stampRunTimings(messages, runs) : messages,
227 activeRun: active ? { runId: active.runId } : null,
228 interrupts: firstPending
229 ? {
230 runId: firstPending.runId,
231 pending: pending.map((record) => record.payload),
232 }
233 : null,
234 ...('page' in transcript ? { page: transcript.page } : {}),
235 ...(runs ? { runs } : {}),
236 }
237 return new Response(JSON.stringify(body), {
238 headers: {
239 'content-type': 'application/json',
240 'cache-control': 'no-store',
241 },
242 })
243}
244
245function messageRunId(message: UIMessage) {
246 const metadata = message.metadata
247 if (!metadata || typeof metadata !== 'object') return
248 const tanstack = metadata.tanstack
249 if (!tanstack || typeof tanstack !== 'object') return
250 const runId = (tanstack as { runId?: unknown }).runId
251 return typeof runId === 'string' && runId !== '' ? runId : undefined
252}
253
254/**
255 * Write each finished run's timings to `metadata.tanstack.run` on the
256 * assistant messages of that run, so a client reads them from the message.
257 */
258function stampRunTimings(
259 messages: Array<UIMessage>,
260 runs: NonNullable<ReconstructedChat['runs']>,
261): Array<UIMessage> {
262 const byId = new Map(runs.map((run) => [run.runId, run]))
263 return messages.map((message) => {
264 const tanstack = message.metadata?.tanstack
265 const runId: unknown = tanstack?.run?.id
266 const run =
267 message.role === 'assistant' && typeof runId === 'string'
268 ? byId.get(runId)
269 : undefined
270 if (!run) return message
271 return {
272 ...message,
273 metadata: {
274 ...message.metadata,
275 tanstack: {
276 ...tanstack,
277 run: {
278 id: run.runId,
279 startedAt: run.startedAt,
280 ...(run.finishedAt !== undefined && { finishedAt: run.finishedAt }),
281 },
282 },
283 },
284 }
285 })
286}
287
288type Runs = NonNullable<ChatTranscriptStores['runs']>
289
290/** Rebuild one child card from its run record and stored transcript. */
291async function childCard(
292 child: RunRecord,
293 runs: Runs,
294 messageStore: MessageStore,
295 pending: ReadonlyArray<InterruptRecord>,
296 depth: number,
297): Promise<SubagentPart> {
298 const subagentRunId = child.subagentRunId ?? child.runId
299 const stored = await messageStore.loadThread(child.threadId)
300 const info = storedSubagentInfo(stored)
301 const messages = modelMessagesToUIMessages(
302 stored.filter(
303 (message) => storedSubagentInfo([message])?.placeholder !== true,
304 ),
305 )
306 const nested =
307 runs.listByParentRun && depth < 8
308 ? await runs.listByParentRun(subagentRunId)
309 : []
310 if (nested.length > 0) {
311 const cards = await Promise.all(
312 nested.map((run) =>
313 childCard(run, runs, messageStore, pending, depth + 1),
314 ),
315 )
316 const last = messages.findLastIndex((m) => m.role === 'assistant')
317 if (last === -1) {
318 messages.push({
319 id: `child-cards:${subagentRunId}`,
320 role: 'assistant',
321 parts: cards,
322 })
323 } else {
324 const host = messages[last]
325 if (host) messages[last] = { ...host, parts: [...host.parts, ...cards] }
326 }
327 }
328 const failed = child.status === 'failed' || child.status === 'aborted'
329 const interruptIds = pending
330 .filter((record) => record.payload.subagentRunId === subagentRunId)
331 .map((record) => record.interruptId)
332 return {
333 type: 'subagent',
334 subagent: {
335 id: subagentRunId,
336 name: child.name ?? info?.name ?? 'subagent',
337 status: failed
338 ? 'error'
339 : child.status === 'running'
340 ? 'running'
341 : child.status === 'interrupted'
342 ? 'suspended'
343 : 'finished',
344 ...(child.parentRunId !== undefined && {
345 parentRunId: child.parentRunId,
346 }),
347 ...(info?.parentToolCallId !== undefined && {
348 parentToolCallId: info.parentToolCallId,
349 }),
350 ...(interruptIds.length > 0 && { interruptIds }),
351 ...(info?.metadata !== undefined && { metadata: info.metadata }),
352 messages,
353 ...(failed && child.error ? { error: child.error } : {}),
354 },
355 }
356}
357
358/**
359 * Put stored subagent cards back on the transcript. A routed child sits on
360 * the parent assistant message of its run. A child that a tool call started
361 * sits on the message that holds that tool call.
362 */
363async function attachSubagentCards(
364 messages: Array<UIMessage>,
365 runs: ChatTranscriptStores['runs'],
366 messageStore: MessageStore,
367 threadId: string,
368 pending: ReadonlyArray<InterruptRecord>,
369) {
370 if (!runs?.listByParentRun) return messages
371 const parentRunIds = new Set<string>()
372 for (const message of messages) {
373 const runId = messageRunId(message)
374 if (runId) parentRunIds.add(runId)
375 }
376 const hasToolCalls = messages.some((message) =>
377 message.parts.some((part) => part.type === 'tool-call'),
378 )
379 if (hasToolCalls && runs.listByThread && threadId !== '') {
380 for (const run of await runs.listByThread(threadId)) {
381 parentRunIds.add(run.runId)
382 }
383 }
384
385 const cardsByRun = new Map<string, Array<SubagentPart>>()
386 const cardsByToolCall = new Map<string, Array<SubagentPart>>()
387 for (const runId of parentRunIds) {
388 for (const child of await runs.listByParentRun(runId)) {
389 const card = await childCard(child, runs, messageStore, pending, 0)
390 const toolCallId = card.subagent.parentToolCallId
391 const target = toolCallId === undefined ? cardsByRun : cardsByToolCall
392 const key = toolCallId ?? runId
393 target.set(key, [...(target.get(key) ?? []), card])
394 }
395 }
396 if (cardsByRun.size === 0 && cardsByToolCall.size === 0) return messages
397
398 return messages.map((message) => {
399 if (message.role !== 'assistant') return message
400 const runId = messageRunId(message)
401 const routed = runId !== undefined ? cardsByRun.get(runId) : undefined
402 const started = message.parts.flatMap((part) =>
403 part.type === 'tool-call' ? (cardsByToolCall.get(part.id) ?? []) : [],
404 )
405 if (!routed && started.length === 0) return message
406 // A routed parent message holds only the children's text. The cards
407 // replace it.
408 const parts = routed
409 ? message.parts.filter((part) => part.type !== 'text')
410 : message.parts
411 return {
412 ...message,
413 parts: [...(routed ?? []), ...parts, ...started],
414 }
415 })
416}
417
418function parsePageSize(raw: string | null) {
419 if (raw == null) return
420 const pageSize = Number(raw)
421 const isValidPageSize = Number.isInteger(pageSize) && pageSize > 0
422 if (!isValidPageSize) return
423 return Math.min(pageSize, MAX_PAGE_SIZE)
424}
425
426function parseBefore(raw: string | null) {
427 if (raw == null || raw === '') return
428 return raw
429}
430
431function threadMessages(
432 loaded: Array<ModelMessage> | MessagePage,
433): Array<ModelMessage> {
434 return Array.isArray(loaded) ? loaded : loaded.messages
435}
436
437function completePage() {
438 return { truncated: false as const }
439}
440
441function truncatedPage(cursor: string) {
442 return { truncated: true as const, cursor }
443}
444
445function pageFromCursor(cursor: string | undefined) {
446 if (cursor === undefined || cursor === '') {
447 return completePage()
448 }
449 return truncatedPage(cursor)
450}
451
452function newestUiWindow(messages: Array<UIMessage>, pageSize: number) {
453 const truncated = messages.length > pageSize
454 if (!truncated) {
455 return { messages, page: completePage() }
456 }
457 const uiWindow = messages.slice(messages.length - pageSize)
458 return {
459 messages: uiWindow,
460 page: pageFromCursor(uiWindow[0]?.id),
461 }
462}
463
464function uiBeforeCursor(messages: Array<UIMessage>, cursor: string) {
465 const cut = messages.findIndex((message) => message.id === cursor)
466 if (cut === -1) return
467 return messages.slice(0, cut)
468}
469
470function windowFromMessagePage(page: MessagePage, pageSize: number) {
471 const ui = modelMessagesToUIMessages(page.messages)
472 if (ui.length > pageSize) {
473 // Extra slice uses a library-minted cursor. Keeping the adapter cursor
474 // after dropping the oldest row would skip that row on the next GET.
475 return newestUiWindow(ui, pageSize)
476 }
477 if (page.truncated) {
478 return {
479 messages: ui,
480 page: pageFromCursor(page.cursor),
481 }
482 }
483 return { messages: ui, page: completePage() }
484}
485
486async function windowFromArray(input: {
487 stored: Array<ModelMessage>
488 messageStore: MessageStore
489 threadId: string
490 pageSize: number
491 before: string | undefined
492}) {
493 const { stored, messageStore, threadId, pageSize, before } = input
494 if (before === undefined) {
495 return newestUiWindow(modelMessagesToUIMessages(stored), pageSize)
496 }
497 // Array adapters own no cursor. Apply `before` to the full transcript so an
498 // adapter that ignored the hint cannot return the same newest page forever.
499 const full = threadMessages(await messageStore.loadThread(threadId))
500 const older = uiBeforeCursor(modelMessagesToUIMessages(full), before)
501 if (older === undefined) {
502 return { messages: [], page: truncatedPage(before) }
503 }
504 return newestUiWindow(older, pageSize)
505}