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

reconstruct.test.ts

598 lines19.7 KB

1import { describe, expect, it } from 'vitest'
2import type { ModelMessage } from '@tanstack/ai'
3import { defineMessageStore, memoryPersistence } from '../src'
4import type { MessageStore } from '../src'
5import { reconstructChat } from '../src/reconstruct'
6import { defineAIPersistence } from '../src/types'
7import type { ReconstructedChat } from '../src/reconstruct'
8​
9async function body(response: Response): Promise<ReconstructedChat> {
10 return (await response.json()) as ReconstructedChat
12​
13function textOf(message: ReconstructedChat['messages'][number]): string {
14 const part = message.parts.find((p) => p.type === 'text')
15 return part && 'content' in part ? (part.content ?? '') : ''
17​
18function idsOf(parsed: ReconstructedChat) {
19 return parsed.messages.map((message) => message.id)
21​
22function chatUrl(query = 'threadId=t1') {
23 if (query === '') return 'http://example.test/api/chat'
24 return `http://example.test/api/chat?${query}`
26​
27async function hydrate(
28 persistence: Parameters<typeof reconstructChat>[0],
29 url: string,
30) {
31 return body(await reconstructChat(persistence, new Request(url)))
33​
34async function saveThread(messages: Array<ModelMessage>, threadId = 't1') {
35 const persistence = memoryPersistence()
36 await persistence.stores.messages.saveThread(threadId, messages)
37 return persistence
39​
40const threeTurnThread: Array<ModelMessage> = [
41 { id: '1', role: 'user', content: 'one' },
42 { id: '2', role: 'assistant', content: 'two' },
43 { id: '3', role: 'user', content: 'three' },
45​
46describe('reconstructChat', () => {
47 it('returns the stored transcript (as UI messages) for a known threadId', async () => {
48 const persistence = memoryPersistence()
49 await persistence.stores.messages!.saveThread('t1', [
50 { role: 'user', content: 'hello' },
51 { role: 'assistant', content: 'hi' },
52 ])
53​
54 const response = await reconstructChat(persistence, new Request(chatUrl()))
55 expect(response.status).toBe(200)
56 expect(response.headers.get('cache-control')).toBe('no-store')
57 const parsed = await body(response)
58 expect(parsed.messages).toHaveLength(2)
59 expect(parsed.messages[0]?.role).toBe('user')
60 expect(textOf(parsed.messages[0]!)).toBe('hello')
61 // No run is generating for the thread.
62 expect(parsed.activeRun).toBeNull()
63 })
64​
65 it('restores persisted structured output as a message part', async () => {
66 const persistence = memoryPersistence()
67 const structuredOutput = {
68 type: 'structured-output' as const,
69 status: 'complete' as const,
70 raw: '{"name":"Ada"}',
71 data: { name: 'Ada' },
72 partial: { name: 'Ada' },
73 }
74 await persistence.stores.messages!.saveThread('t1', [
75 {
76 id: 'assistant-1',
77 role: 'assistant',
78 content: structuredOutput.raw,
79 structuredOutput,
80 },
81 ])
82​
83 const parsed = await hydrate(persistence, chatUrl())
84 expect(parsed.messages[0]).toMatchObject({
85 id: 'assistant-1',
86 role: 'assistant',
87 parts: [structuredOutput],
88 })
89 })
90​
91 it('restores persisted ui-resource widgets into parts', async () => {
92 const persistence = memoryPersistence()
93 const uiResource = {
94 type: 'ui-resource' as const,
95 resource: {
96 uri: 'ui://widget/todos',
97 mimeType: 'text/html',
98 text: '<div>todos</div>',
99 },
100 toolCallId: 'tc-1',
101 toolName: 'getTodos',
102 }
103 await persistence.stores.messages!.saveThread('t1', [
104 {
105 id: 'assistant-1',
106 role: 'assistant',
107 content: 'here',
108 name: 'Ada',
109 metadata: { tanstack: { uiResources: [uiResource] } },
110 },
111 ])
112​
113 const parsed = await hydrate(persistence, chatUrl())
114​
115 expect(parsed.messages[0]).toMatchObject({
116 id: 'assistant-1',
117 role: 'assistant',
118 name: 'Ada',
119 parts: [{ type: 'text', content: 'here' }, uiResource],
120 })
121 })
122​
123 it('restores persisted message metadata', async () => {
124 const persistence = memoryPersistence()
125 await persistence.stores.messages!.saveThread('t1', [
126 {
127 id: 'user-1',
128 role: 'user',
129 content: 'hello',
130 metadata: { author: { id: 'user-42' } },
131 },
132 ])
133​
134 const parsed = await hydrate(persistence, chatUrl())
135​
136 expect(parsed.messages[0]).toMatchObject({
137 id: 'user-1',
138 role: 'user',
139 metadata: { author: { id: 'user-42' } },
140 })
141 })
142​
143 it('reports the active run for a thread that is still generating', async () => {
144 const persistence = memoryPersistence()
145 await persistence.stores.messages!.saveThread('t1', [
146 { role: 'user', content: 'write a long story' },
147 ])
148 await persistence.stores.runs!.createOrResume({
149 runId: 'run-live',
150 threadId: 't1',
151 startedAt: 1000,
152 })
153​
154 const parsed = await hydrate(persistence, chatUrl())
155 expect(parsed.activeRun).toEqual({ runId: 'run-live' })
156​
157 // Once the run finishes, no active run is reported.
158 await persistence.stores.runs!.update('run-live', { status: 'completed' })
159 const after = await hydrate(persistence, chatUrl())
160 expect(after.activeRun).toBeNull()
161 })
162​
163 it('lists finished runs with their timings when includeRuns is set (#1061)', async () => {
164 const persistence = memoryPersistence()
165 await persistence.stores.messages.saveThread('t1', [
166 { id: 'u1', role: 'user', content: 'one' },
167 {
168 id: 'a1',
169 role: 'assistant',
170 content: 'two',
171 metadata: { tanstack: { run: { id: 'r1' } } },
172 },
173 { id: 'u2', role: 'user', content: 'three' },
174 ])
175 const runs = persistence.stores.runs
176 await runs.createOrResume({ runId: 'r1', threadId: 't1', startedAt: 1000 })
177 await runs.update('r1', { status: 'completed', finishedAt: 4000 })
178 await runs.createOrResume({ runId: 'r2', threadId: 't1', startedAt: 5000 })
179 await runs.update('r2', { status: 'failed', finishedAt: 6000 })
180 await runs.createOrResume({ runId: 'r3', threadId: 't1', startedAt: 7000 })
181​
182 const withRuns = await body(
183 await reconstructChat(persistence, new Request(chatUrl()), {
184 includeRuns: true,
185 }),
186 )
187 const plain = await hydrate(persistence, chatUrl())
188​
189 expect(withRuns.runs).toEqual([
190 { runId: 'r1', status: 'completed', startedAt: 1000, finishedAt: 4000 },
191 { runId: 'r2', status: 'failed', startedAt: 5000, finishedAt: 6000 },
192 ])
193 expect(withRuns.activeRun).toEqual({ runId: 'r3' })
194 // The assistant message of each run carries that run's timings.
195 expect(withRuns.messages[1]?.metadata?.tanstack).toEqual({
196 run: { id: 'r1', startedAt: 1000, finishedAt: 4000 },
197 })
198 expect(withRuns.messages[0]?.metadata?.tanstack?.run).toBeUndefined()
199 expect('runs' in plain).toBe(false)
200 expect(plain.messages[1]?.metadata?.tanstack?.run).toEqual({ id: 'r1' })
201 })
202​
203 it('returns an empty transcript and no active run when threadId is missing or unknown', async () => {
204 const persistence = memoryPersistence()
205 const missing = await hydrate(persistence, chatUrl(''))
206 expect(missing).toEqual({ messages: [], activeRun: null, interrupts: null })
207​
208 const unknown = await hydrate(persistence, chatUrl('threadId=nope'))
209 expect(unknown).toEqual({ messages: [], activeRun: null, interrupts: null })
210 })
211​
212 it('reports pending interrupts so a reload re-prompts the approval', async () => {
213 const persistence = memoryPersistence()
214 await persistence.stores.messages!.saveThread('t1', [
215 { role: 'user', content: 'send an email' },
216 ])
217 const payload = {
218 id: 'int-1',
219 type: 'tool-approval',
220 toolName: 'sendEmail',
221 toolCallId: 'call-1',
222 }
223 await persistence.stores.interrupts!.create({
224 interruptId: 'int-1',
225 runId: 'run-paused',
226 threadId: 't1',
227 requestedAt: 1000,
228 payload,
229 })
230​
231 const parsed = await hydrate(persistence, chatUrl())
232 expect(parsed.interrupts).toEqual({
233 runId: 'run-paused',
234 pending: [payload],
235 })
236 })
237​
238 it('returns 403 when authorize returns false', async () => {
239 const persistence = memoryPersistence()
240 await persistence.stores.messages!.saveThread('t1', [
241 { role: 'user', content: 'secret' },
242 ])
243​
244 const response = await reconstructChat(
245 persistence,
246 new Request(chatUrl()),
247 { authorize: () => false },
248 )
249 expect(response.status).toBe(403)
250 expect(await response.json()).toEqual({ error: 'Forbidden' })
251 })
252​
253 it('returns a custom Response from authorize', async () => {
254 const persistence = memoryPersistence()
255 const response = await reconstructChat(
256 persistence,
257 new Request(chatUrl()),
258 {
259 authorize: () =>
260 new Response(JSON.stringify({ error: 'login' }), { status: 401 }),
261 },
262 )
263 expect(response.status).toBe(401)
264 })
265​
266 it('honors a custom query param name', async () => {
267 const persistence = memoryPersistence()
268 await persistence.stores.messages!.saveThread('custom-id', [
269 { role: 'user', content: 'via-param' },
270 ])
271 const response = await reconstructChat(
272 persistence,
273 new Request(chatUrl('id=custom-id')),
274 { param: 'id' },
275 )
276 const parsed = await body(response)
277 expect(textOf(parsed.messages[0]!)).toBe('via-param')
278 })
279​
280 it('interleaves stored activity at the saved index', async () => {
281 const persistence = memoryPersistence()
282 await persistence.stores.messages!.saveThread('t1', [
283 { role: 'user', content: 'hi' },
284 { role: 'assistant', content: 'ok' },
285 ])
286 await persistence.stores.activities!.saveActivities('t1', [
287 {
288 id: 'act-1',
289 activityType: 'SEARCH',
290 content: { q: 'x' },
291 index: 1,
292 },
293 ])
294​
295 const parsed = await body(
296 await reconstructChat(
297 persistence,
298 new Request('http://example.test/api/chat?threadId=t1'),
299 ),
300 )
301 expect(parsed.messages.map((message) => message.role)).toEqual([
302 'user',
303 'activity',
304 'assistant',
305 ])
306 expect(parsed.messages[1]).toMatchObject({
307 id: 'act-1',
308 role: 'activity',
309 parts: [
310 { type: 'activity', activityType: 'SEARCH', content: { q: 'x' } },
311 ],
312 })
313 })
314​
315 it('leaves reconstruct unchanged when the activities store is absent', async () => {
316 const memory = memoryPersistence()
317 await memory.stores.messages!.saveThread('t1', [
318 { role: 'user', content: 'hi' },
319 { role: 'assistant', content: 'ok' },
320 ])
321 await memory.stores.activities!.saveActivities('t1', [
322 {
323 id: 'act-1',
324 activityType: 'SEARCH',
325 content: { q: 'x' },
326 index: 1,
327 },
328 ])
329​
330 const parsed = await body(
331 await reconstructChat(
332 defineAIPersistence({ stores: { messages: memory.stores.messages! } }),
333 new Request('http://example.test/api/chat?threadId=t1'),
334 ),
335 )
336 expect(parsed.messages.map((message) => message.role)).toEqual([
337 'user',
338 'assistant',
339 ])
340 })
341})
342​
343describe('reconstructChat paging', () => {
344 it('with limit returns the newest UI window and page.truncated', async () => {
345 const persistence = await saveThread(threeTurnThread)
346 const parsed = await hydrate(persistence, chatUrl('threadId=t1&limit=2'))
347 expect(idsOf(parsed)).toEqual(['2', '3'])
348 expect(parsed.page).toEqual({ truncated: true, cursor: '2' })
349 })
350​
351 it('limit=0 returns the full thread', async () => {
352 const persistence = await saveThread(threeTurnThread)
353 const parsed = await hydrate(persistence, chatUrl('threadId=t1&limit=0'))
354 expect(idsOf(parsed)).toEqual(['1', '2', '3'])
355 expect(parsed.page).toBeUndefined()
356 })
357​
358 it('unknown before returns empty messages and keeps truncated true', async () => {
359 const persistence = await saveThread(threeTurnThread)
360 await persistence.stores.runs.createOrResume({
361 runId: 'run-live',
362 threadId: 't1',
363 startedAt: 1000,
364 })
365 const parsed = await hydrate(
366 persistence,
367 chatUrl('threadId=t1&limit=2&before=no-such-cursor'),
368 )
369 expect(parsed.messages).toEqual([])
370 expect(parsed.page).toEqual({
371 truncated: true,
372 cursor: 'no-such-cursor',
373 })
374 expect(parsed.activeRun).toEqual({ runId: 'run-live' })
375 })
376​
377 it('does not split an assistant from its tool result across a page', async () => {
378 const persistence = await saveThread([
379 { id: 'user-1', role: 'user', content: 'ask' },
380 {
381 id: 'assistant-1',
382 role: 'assistant',
383 content: '',
384 toolCalls: [
385 {
386 id: 'call-1',
387 type: 'function',
388 function: { name: 'lookup', arguments: '{}' },
389 },
390 ],
391 },
392 {
393 id: 'tool-1',
394 role: 'tool',
395 toolCallId: 'call-1',
396 content: 'found it',
397 },
398 { id: 'user-2', role: 'user', content: 'thanks' },
399 ])
400 const parsed = await hydrate(persistence, chatUrl('threadId=t1&limit=2'))
401 expect(idsOf(parsed)).toEqual(['assistant-1', 'user-2'])
402 expect(parsed.messages[0]?.parts).toEqual(
403 expect.arrayContaining([
404 expect.objectContaining({ type: 'tool-call', id: 'call-1' }),
405 expect.objectContaining({
406 type: 'tool-result',
407 toolCallId: 'call-1',
408 content: 'found it',
409 }),
410 ]),
411 )
412 })
413​
414 describe('with stored activity', () => {
415 // Full UI transcript: u1, act-early, a1, u2, a2, u3, act-late, a3.
416 async function activityThread() {
417 const persistence = await saveThread([
418 { id: 'u1', role: 'user', content: 'one' },
419 { id: 'a1', role: 'assistant', content: 'one' },
420 { id: 'u2', role: 'user', content: 'two' },
421 { id: 'a2', role: 'assistant', content: 'two' },
422 { id: 'u3', role: 'user', content: 'three' },
423 { id: 'a3', role: 'assistant', content: 'three' },
424 ])
425 await persistence.stores.activities.saveActivities('t1', [
426 { id: 'act-early', activityType: 'PLAN', content: {}, index: 1 },
427 { id: 'act-late', activityType: 'PLAN', content: {}, index: 6 },
428 ])
429 return persistence
430 }
431​
432 it('puts each activity only on the newest page that holds its index', async () => {
433 const parsed = await hydrate(
434 await activityThread(),
435 chatUrl('threadId=t1&limit=3'),
436 )
437 expect(idsOf(parsed)).toEqual(['u3', 'act-late', 'a3'])
438 expect(parsed.page).toEqual({ truncated: true, cursor: 'u3' })
439 })
440​
441 it('walks older pages without repeating or moving activity', async () => {
442 const persistence = await activityThread()
443 const middle = await hydrate(
444 persistence,
445 chatUrl('threadId=t1&limit=3&before=u3'),
446 )
447 expect(idsOf(middle)).toEqual(['a1', 'u2', 'a2'])
448 expect(middle.page).toEqual({ truncated: true, cursor: 'a1' })
449​
450 const oldest = await hydrate(
451 persistence,
452 chatUrl('threadId=t1&limit=3&before=a1'),
453 )
454 expect(idsOf(oldest)).toEqual(['u1', 'act-early'])
455 expect(oldest.page).toEqual({ truncated: false })
456 })
457 })
458​
459 it('loads an older window from the minted cursor without overlapping ids', async () => {
460 const persistence = await saveThread(threeTurnThread)
461 const older = await hydrate(
462 persistence,
463 chatUrl('threadId=t1&limit=2&before=2'),
464 )
465 expect(idsOf(older)).toEqual(['1'])
466 expect(older.page).toEqual({ truncated: false })
467 })
468​
469 it('mints a library cursor when a MessagePage is longer than pageSize', async () => {
470 const persistence = memoryPersistence()
471 const inner = persistence.stores.messages
472 persistence.stores.messages = defineMessageStore({
473 loadThread(threadId, options) {
474 if (options?.limit === undefined) {
475 return inner.loadThread(threadId)
476 }
477 return Promise.resolve({
478 messages: threeTurnThread,
479 truncated: true as const,
480 cursor: 'before-1',
481 })
482 },
483 saveThread(threadId, messages) {
484 return inner.saveThread(threadId, messages)
485 },
486 } as MessageStore)
487 const parsed = await hydrate(persistence, chatUrl('threadId=t1&limit=2'))
488 expect(idsOf(parsed)).toEqual(['2', '3'])
489 expect(parsed.page).toEqual({ truncated: true, cursor: '2' })
490 })
491​
492 it('keeps a MessagePage adapter cursor when the UI window fits pageSize', async () => {
493 const persistence = memoryPersistence()
494 const inner = persistence.stores.messages
495 persistence.stores.messages = defineMessageStore({
496 loadThread(threadId, options) {
497 if (options?.limit === undefined) {
498 return inner.loadThread(threadId)
499 }
500 return Promise.resolve({
501 messages: [
502 { id: '2', role: 'assistant', content: 'two' },
503 { id: '3', role: 'user', content: 'three' },
504 ],
505 truncated: true as const,
506 cursor: 'adapter-cursor',
507 })
508 },
509 saveThread(threadId, messages) {
510 return inner.saveThread(threadId, messages)
511 },
512 } as MessageStore)
513 const parsed = await hydrate(persistence, chatUrl('threadId=t1&limit=2'))
514 expect(idsOf(parsed)).toEqual(['2', '3'])
515 expect(parsed.page).toEqual({
516 truncated: true,
517 cursor: 'adapter-cursor',
518 })
519 })
520​
521 it('slices an array adapter that honors limit plus one', async () => {
522 const persistence = memoryPersistence()
523 const inner = persistence.stores.messages
524 await inner.saveThread('t1', threeTurnThread)
525 persistence.stores.messages = defineMessageStore({
526 loadThread(threadId, options) {
527 const limit = options?.limit
528 if (limit === undefined) {
529 return inner.loadThread(threadId)
530 }
531 return inner
532 .loadThread(threadId)
533 .then((list) => list.slice(Math.max(0, list.length - limit)))
534 },
535 saveThread(threadId, messages) {
536 return inner.saveThread(threadId, messages)
537 },
538 } as MessageStore)
539 const parsed = await hydrate(persistence, chatUrl('threadId=t1&limit=2'))
540 expect(idsOf(parsed)).toEqual(['2', '3'])
541 expect(parsed.page).toEqual({ truncated: true, cursor: '2' })
542 })
543​
544 it('pages through the store when the cursor predates the first activity', async () => {
545 const persistence = memoryPersistence()
546 const inner = persistence.stores.messages
547 await inner.saveThread('t1', [{ id: '3', role: 'user', content: 'three' }])
548 await persistence.stores.activities.saveActivities('t1', [
549 { id: 'act-1', activityType: 'PLAN', content: {}, index: 1 },
550 ])
551 persistence.stores.messages = defineMessageStore({
552 loadThread(threadId, options) {
553 if (options?.limit === undefined) {
554 return inner.loadThread(threadId)
555 }
556 return Promise.resolve({
557 messages: [{ id: '1', role: 'user', content: 'one' }],
558 truncated: false as const,
559 })
560 },
561 saveThread(threadId, messages) {
562 return inner.saveThread(threadId, messages)
563 },
564 } as MessageStore)
565 const parsed = await hydrate(
566 persistence,
567 chatUrl('threadId=t1&limit=2&before=adapter-cursor'),
568 )
569 expect(idsOf(parsed)).toEqual(['1'])
570 expect(parsed.page).toEqual({ truncated: false })
571 })
572​
573 it('treats a truncated MessagePage without a usable cursor as complete', async () => {
574 const persistence = memoryPersistence()
575 const inner = persistence.stores.messages
576 persistence.stores.messages = defineMessageStore({
577 loadThread(threadId, options) {
578 if (options?.limit === undefined) {
579 return inner.loadThread(threadId)
580 }
581 return Promise.resolve({
582 messages: [
583 { id: '2', role: 'assistant', content: 'two' },
584 { id: '3', role: 'user', content: 'three' },
585 ],
586 truncated: true as const,
587 cursor: '',
588 })
589 },
590 saveThread(threadId, messages) {
591 return inner.saveThread(threadId, messages)
592 },
593 } as MessageStore)
594 const parsed = await hydrate(persistence, chatUrl('threadId=t1&limit=2'))
595 expect(idsOf(parsed)).toEqual(['2', '3'])
596 expect(parsed.page).toEqual({ truncated: false })
597 })
598})