Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

reconstruct.ts

550 lines18.7 KB

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