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

api.message-history-paging.ts

265 lines8.3 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 EventType,
4 chat,
5 chatParamsFromRequestBody,
6 toServerSentEventsResponse,
7} from '@tanstack/ai'
8import {
9 defineAIPersistence,
10 defineMessageStore,
11 memoryPersistence,
12 reconstructChat,
13 withPersistence,
14} from '@tanstack/ai-persistence'
15import type { AnyTextAdapter, ModelMessage, StreamChunk } from '@tanstack/ai'
16import type { MessagePage, MessageStore } from '@tanstack/ai-persistence'
17​
18/**
19 * Provider-free harness for server-authoritative history paging.
20 *
21 * GET hydrates through `reconstructChat` (the `persistence: true` mount probe).
22 * POST runs `chat()` through `withPersistence`. `?store=page` uses a
23 * MessagePage adapter; the default store returns the full array and lets
24 * reconstructChat slice.
25 *
26 * Exempt from aimock: the adapter streams a fixed AG-UI sequence.
27 */
28​
29const PAGING_REPLY = 'PAGE_OK'
30​
31const lastIncomingIds = new Map<string, Array<string>>()
32​
33const arrayPersistence = memoryPersistence()
34const pagedInner = memoryPersistence()
35const pagedPersistence = defineAIPersistence({
36 stores: {
37 messages: defineMessageStore({
38 // One implementation covers both overloads: no options → full array,
39 // paging hint → MessagePage. TypeScript cannot express that as both
40 // call signatures without this assertion.
41 loadThread(
42 threadId: string,
43 options?: { limit?: number; before?: string },
44 ) {
45 return loadPaged(pagedInner.stores.messages, threadId, options)
46 },
47 saveThread(threadId, messages) {
48 return pagedInner.stores.messages.saveThread(threadId, messages)
49 },
50 } as MessageStore),
51 runs: pagedInner.stores.runs,
52 interrupts: pagedInner.stores.interrupts,
53 metadata: pagedInner.stores.metadata,
54 },
55})
56​
57async function loadPaged(
58 inner: MessageStore,
59 threadId: string,
60 options?: { limit?: number; before?: string },
61): Promise<Array<ModelMessage> | MessagePage> {
62 const all = await inner.loadThread(threadId)
63 if (options?.limit === undefined) return all
64 let slice = all
65 const before = options.before
66 if (before !== undefined) {
67 const cut = all.findIndex((message) => message.id === before)
68 if (cut === -1) return { messages: [], truncated: false }
69 slice = all.slice(0, cut)
70 }
71 if (slice.length <= options.limit) {
72 return { messages: slice, truncated: false }
73 }
74 const window = slice.slice(slice.length - options.limit)
75 const cursor = window[0]?.id
76 if (cursor === undefined || cursor === '') {
77 return { messages: window, truncated: false }
78 }
79 return { messages: window, truncated: true, cursor }
81​
82function persistenceFor(request: Request) {
83 const store = new URL(request.url).searchParams.get('store')
84 return store === 'page' ? pagedPersistence : arrayPersistence
86​
87function replyRun(threadId: string, runId: string): AsyncIterable<StreamChunk> {
88 const messageId = `assistant-${runId}`
89 return (async function* () {
90 yield {
91 type: EventType.RUN_STARTED,
92 threadId,
93 runId,
94 timestamp: Date.now(),
95 } satisfies StreamChunk
96 yield {
97 type: EventType.TEXT_MESSAGE_START,
98 messageId,
99 role: 'assistant',
100 timestamp: Date.now(),
101 } satisfies StreamChunk
102 yield {
103 type: EventType.TEXT_MESSAGE_CONTENT,
104 messageId,
105 delta: PAGING_REPLY,
106 timestamp: Date.now(),
107 } satisfies StreamChunk
108 yield {
109 type: EventType.TEXT_MESSAGE_END,
110 messageId,
111 timestamp: Date.now(),
112 } satisfies StreamChunk
113 yield {
114 type: EventType.RUN_FINISHED,
115 threadId,
116 runId,
117 timestamp: Date.now(),
118 outcome: { type: 'success' },
119 } satisfies StreamChunk
120 })()
122​
123const adapter = {
124 kind: 'text' as const,
125 name: 'fixed',
126 model: 'test-model',
127 '~types': {},
128 chatStream: ({ threadId, runId }: { threadId: string; runId: string }) =>
129 replyRun(threadId, runId),
130 structuredOutput: () => Promise.resolve({ data: {}, rawText: '{}' }),
131 // Fixed-sequence harness adapters in this package cannot satisfy the
132 // generic `~types` bag without a double assertion.
133} as unknown as AnyTextAdapter
134​
135function isRecord(value: unknown): value is Record<string, unknown> {
136 return typeof value === 'object' && value !== null
138​
139function stringField(body: unknown, key: string): string | undefined {
140 if (!isRecord(body) || !(key in body)) return undefined
141 const value = body[key]
142 return typeof value === 'string' ? value : undefined
144​
145function seedMessages(value: unknown): Array<ModelMessage> {
146 if (!Array.isArray(value)) {
147 throw new Error('seed messages must be an array')
148 }
149 const messages: Array<ModelMessage> = []
150 for (const entry of value) {
151 if (!isRecord(entry)) {
152 throw new Error('seed message must be an object')
153 }
154 if (entry.role !== 'user' && entry.role !== 'assistant') {
155 throw new Error('seed message role must be user or assistant')
156 }
157 if (typeof entry.content !== 'string') {
158 throw new Error('seed message content must be a string')
159 }
160 if (typeof entry.id !== 'string' || entry.id === '') {
161 throw new Error('seed message id must be a string')
162 }
163 messages.push({
164 id: entry.id,
165 role: entry.role,
166 content: entry.content,
167 })
168 }
169 return messages
171​
172function incomingIds(messages: ReadonlyArray<{ id?: string }>): Array<string> {
173 const ids: Array<string> = []
174 for (const message of messages) {
175 if (typeof message.id === 'string' && message.id !== '') {
176 ids.push(message.id)
177 }
178 }
179 return ids
181​
182async function inspectBody(request: Request, threadId: string) {
183 const persistence = persistenceFor(request)
184 const stored = await persistence.stores.messages.loadThread(threadId)
185 return {
186 stored: stored.map((message) => ({
187 id: message.id,
188 role: message.role,
189 content: typeof message.content === 'string' ? message.content : '',
190 })),
191 lastIncomingIds: lastIncomingIds.get(threadId) ?? [],
192 }
194​
195export const Route = createFileRoute('/api/message-history-paging')({
196 server: {
197 handlers: {
198 POST: async ({ request }) => {
199 const url = new URL(request.url)
200 const persistence = persistenceFor(request)
201 const body: unknown = await request.json()
202​
203 if (url.searchParams.get('seed') === '1') {
204 const threadId = stringField(body, 'threadId')
205 if (threadId === undefined || threadId === '') {
206 return new Response('threadId required', { status: 400 })
207 }
208 if (!isRecord(body)) {
209 return new Response('invalid seed body', { status: 400 })
210 }
211 await persistence.stores.messages.saveThread(
212 threadId,
213 seedMessages(body.messages),
214 )
215 return Response.json({ threadId })
216 }
217​
218 if (url.searchParams.get('run') === '1') {
219 const threadId = stringField(body, 'threadId')
220 if (threadId === undefined || threadId === '') {
221 return new Response('threadId required', { status: 400 })
222 }
223 if (!isRecord(body)) {
224 return new Response('invalid run body', { status: 400 })
225 }
226 const messages = seedMessages(body.messages)
227 lastIncomingIds.set(threadId, incomingIds(messages))
228 const stream = chat({
229 adapter,
230 messages,
231 threadId,
232 runId: stringField(body, 'runId') ?? crypto.randomUUID(),
233 middleware: [withPersistence(persistence)],
234 })
235 for await (const _ of stream) void _
236 return Response.json(await inspectBody(request, threadId))
237 }
238​
239 const params = await chatParamsFromRequestBody(body)
240 lastIncomingIds.set(params.threadId, incomingIds(params.messages))
241 return toServerSentEventsResponse(
242 chat({
243 adapter,
244 messages: params.messages,
245 threadId: params.threadId,
246 runId: params.runId,
247 middleware: [withPersistence(persistence)],
248 }),
249 )
250 },
251​
252 GET: async ({ request }) => {
253 const url = new URL(request.url)
254 if (url.searchParams.get('inspect') === '1') {
255 return Response.json(
256 await inspectBody(request, url.searchParams.get('threadId') ?? ''),
257 )
258 }
259 return reconstructChat(persistenceFor(request), request, {
260 authorize: (threadId) => threadId.length > 0,
261 })
262 },
263 },
264 },
265})