Open History to see the last commit
1import { modelMessagesToUIMessages } from '@tanstack/ai'
2import type { UIMessage } from '@tanstack/ai'
3import { validateReconstructChatStores } from './types'
4import type { AIPersistence, ChatTranscriptStores } from './types'
5
6/**
7 * The JSON body `reconstructChat` returns and a server-authoritative client
8 * hydrates from on mount.
9 *
10 * `messages` is the stored transcript as UI messages (ready to paint).
11 * `activeRun` is a cursor to a run still generating for the thread, or `null` —
12 * resolved from the STABLE thread id via `stores.runs.findActiveRun`, so the
13 * client learns "there is a live run to tail" without ever handling a run id.
14 * `interrupts` is the thread's pending human-in-the-loop interrupts (tool
15 * approvals, client-tool/generic waits) and the run they paused, or `null` —
16 * so a reload (or another device) re-prompts the approval from the SERVER, not
17 * from client storage. Resolved via `stores.interrupts.listPending`.
18 */
19export interface ReconstructedChat {
20 messages: Array<UIMessage>
21 activeRun: { runId: string } | null
22 interrupts: {
23 runId: string
24 pending: Array<Record<string, unknown>>
25 } | null
26}
27
28export interface ReconstructChatOptions {
29 /** Query parameter carrying the thread id. Defaults to `threadId`. */
30 param?: string
31 /**
32 * Authorize access to the requested thread before loading history.
33 *
34 * ⚠️ Without this, any caller who knows or guesses `?threadId=` receives the
35 * full transcript. Multi-user / multi-tenant deployments **must** supply
36 * an authorization check (session → owned threads) or resolve a validated
37 * thread id in the route and pass it via a custom `param` that only your
38 * server sets.
39 *
40 * Return:
41 * - `true` to allow the load
42 * - `false` for a default `403` response
43 * - a `Response` to return as-is (e.g. `401` with a body)
44 */
45 authorize?: (
46 threadId: string,
47 request: Request,
48 ) => boolean | Response | Promise<boolean | Response>
49}
50
51/**
52 * Build the JSON `Response` a server-authoritative client hydrates from on load
53 * (see the client-persistence guide). Reads the thread id from the request query
54 * (`?threadId=` by default) and returns `{ messages, activeRun, interrupts }`
55 * ({@link ReconstructedChat}):
56 *
57 * - `messages` — the stored transcript as UI messages.
58 * - `activeRun` — `{ runId }` if a run is still generating for the thread (so the
59 * client tails it via the durability stream), else `null`. Resolved via the
60 * required `stores.runs.findActiveRun`; `null` when the `runs` store is absent.
61 * - `interrupts` — `{ runId, pending }` if the thread has pending human-in-the-loop
62 * interrupts (a paused approval / wait) and the run they paused, else `null`, so
63 * a reload re-prompts the decision from the server. Resolved via the optional
64 * `stores.interrupts.listPending`; `null` when that store is absent.
65 *
66 * Requires `stores.messages`. Returns an empty transcript with no active run
67 * and no interrupts when the thread id is missing or the thread is unknown, so
68 * the caller never has to special-case a first load.
69 *
70 * This helper does **not** enforce tenancy by itself. Pass
71 * {@link ReconstructChatOptions.authorize} (or wrap the call in your own
72 * session gate) before exposing it on a public route.
73 *
74 * ```ts
75 * export async function GET(request: Request) {
76 * return reconstructChat(persistence, request, {
77 * authorize: async (threadId, req) => {
78 * const userId = await getSessionUserId(req)
79 * return userId != null && (await userOwnsThread(userId, threadId))
80 * },
81 * })
82 * }
83 * ```
84 */
85export async function reconstructChat(
86 persistence: AIPersistence<ChatTranscriptStores>,
87 request: Request,
88 options?: ReconstructChatOptions,
89): Promise<Response> {
90 validateReconstructChatStores(persistence)
91 const messageStore = persistence.stores.messages
92 if (!messageStore) {
93 // validateReconstructChatStores already throws; this narrows for TypeScript.
94 throw new Error('reconstructChat requires stores.messages.')
95 }
96
97 const param = options?.param ?? 'threadId'
98 const threadId = new URL(request.url).searchParams.get(param) ?? ''
99
100 if (threadId && options?.authorize) {
101 const decision = await options.authorize(threadId, request)
102 if (decision instanceof Response) {
103 return decision
104 }
105 if (!decision) {
106 return new Response(JSON.stringify({ error: 'Forbidden' }), {
107 status: 403,
108 headers: {
109 'content-type': 'application/json',
110 'cache-control': 'no-store',
111 },
112 })
113 }
114 }
115
116 // Resolve the active run BEFORE reading the transcript. `withPersistence`
117 // persists the final transcript BEFORE marking a run complete, so observing
118 // "no active run" here guarantees the transcript read below is the FINAL one.
119 // Reading them in the other order opens a finish-window race: a fast run that
120 // completes between the two reads would return a stale streaming snapshot with
121 // `activeRun: null`, leaving the client stuck on the partial (no run to tail).
122 const active = threadId
123 ? await persistence.stores.runs?.findActiveRun(threadId)
124 : null
125 const stored = threadId ? await messageStore.loadThread(threadId) : []
126 // Pending interrupts for the thread, so a reload re-prompts the approval from
127 // the server. Each stored `payload` is the full interrupt descriptor the
128 // client hydrates; they share the run they paused.
129 const pending = threadId
130 ? ((await persistence.stores.interrupts?.listPending(threadId)) ?? [])
131 : []
132 const firstPending = pending[0]
133 const body: ReconstructedChat = {
134 messages: modelMessagesToUIMessages(stored),
135 activeRun: active ? { runId: active.runId } : null,
136 interrupts: firstPending
137 ? {
138 runId: firstPending.runId,
139 pending: pending.map((record) => record.payload),
140 }
141 : null,
142 }
143 return new Response(JSON.stringify(body), {
144 headers: {
145 'content-type': 'application/json',
146 'cache-control': 'no-store',
147 },
148 })
149}