Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 chatParamsFromRequestBody,
5 memoryStream,
6 resumeServerSentEventsResponse,
7 toServerSentEventsResponse,
8} from '@tanstack/ai'
9import { openaiText } from '@tanstack/ai-openai'
10import {
11 memoryPersistence,
12 reconstructChat,
13 withPersistence,
14} from '@tanstack/ai-persistence'
15import type { StreamChunk } from '@tanstack/ai'
16
17// In memory, so this page never touches the SQLite threads of /persistent-chat.
18// A server restart clears it.
19const persistence = memoryPersistence()
20
21// "Slow model" on the page puts 30ms between text chunks, like a slower model,
22// so the batching is easy to see by eye.
23async function* slowText(
24 stream: AsyncIterable<StreamChunk>,
25): AsyncIterable<StreamChunk> {
26 for await (const chunk of stream) {
27 if (chunk.type === 'TEXT_MESSAGE_CONTENT') {
28 await new Promise((resolve) => setTimeout(resolve, 30))
29 }
30 yield chunk
31 }
32}
33
34/**
35 * Server-authoritative persistence with a resumable POST: the persistence
36 * guide's POST plus `durability`. A reload mid-answer rejoins the run from the
37 * memoryStream log, because the GET reports the thread's active run.
38 */
39export const Route = createFileRoute('/api/durable-persistence')({
40 server: {
41 handlers: {
42 POST: async ({ request }) => {
43 const params = await chatParamsFromRequestBody(await request.json())
44 const stream = chat({
45 adapter: openaiText('gpt-5.5'),
46 messages: params.messages,
47 threadId: params.threadId,
48 runId: params.runId,
49 ...(params.resume ? { resume: params.resume } : {}),
50 middleware: [withPersistence(persistence)],
51 })
52 // "Old batching" on the page turns the batch wait off. A chunk then
53 // waits until 32 chunks or the run end, which is how durable batching
54 // worked before `batchWaitMs`.
55 const oldBatching = params.forwardedProps.oldBatching === true
56 const slowModel = params.forwardedProps.slowModel === true
57 return toServerSentEventsResponse(
58 slowModel ? slowText(stream) : stream,
59 {
60 durability: {
61 adapter: memoryStream(request),
62 ...(oldBatching ? { batchWaitMs: 2_147_483_647 } : {}),
63 },
64 },
65 )
66 },
67
68 GET: ({ request }) => {
69 // A rejoin (`?offset` / `Last-Event-ID`) replays the run's log.
70 const durability = memoryStream(request)
71 if (durability.resumeFrom() !== null) {
72 return resumeServerSentEventsResponse({ adapter: durability })
73 }
74 // Otherwise return the stored thread plus a cursor to any active run.
75 // Demo only: a real app checks that the session owns the thread.
76 return reconstructChat(persistence, request, {
77 authorize: async (threadId) => threadId.length > 0,
78 })
79 },
80 },
81 },
82})