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

api.persistence-durability.ts

542 lines16.5 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 INTERRUPT_BINDING_METADATA_KEY,
4 INTERRUPT_BINDING_VERSION,
5 canonicalInterruptJson,
6 chat,
7 digestInterruptJson,
8 memoryStream,
9 resumeServerSentEventsResponse,
10 toolDefinition,
11 toServerSentEventsResponse,
12} from '@tanstack/ai'
13import {
14 memoryPersistence,
15 reconstructChat,
16 withPersistence,
17} from '@tanstack/ai-persistence'
18import { z } from 'zod'
19import type {
20 AnyTextAdapter,
21 StreamChunk,
22 TokenUsage,
23 Tool,
24} from '@tanstack/ai'
25​
26/**
27 * Provider-free harness route for the browser-refresh persistence story. It
28 * mirrors the production wiring of `examples/.../api.persistent-chat.ts` — a
29 * `memoryStream(request)` delivery sink plus a GET resume handler that makes the
30 * connection resumable — but uses fixed AG-UI sequences and a fixed adapter
31 * instead of calling an LLM, so the e2e is deterministic with nothing to mock.
32 *
33 * Five scenarios (`?scenario=`):
34 *
35 * - `text` (default) — a run that streams one assistant text message and
36 * finishes cleanly (`outcome: success`). The client persists the transcript
37 * to its `localStoragePersistence` combined record; the resume half is
38 * cleared on the successful terminal. A reload restores the messages.
39 * - `interrupt` — a run that ends on a single BOUND generic interrupt
40 * (carrying a resume binding, exactly like `api.foreign-interrupt`). The
41 * client folds the pending-interrupt resume snapshot into the SAME combined
42 * record, so a reload rehydrates the interrupt from `localStorage` alone
43 * (no server round-trip).
44 * - `server-interrupt` — the SERVER-authoritative counterpart. The client runs
45 * `persistence: true` (caches nothing), so on mount it hydrates from the
46 * GET below, which returns a `reconstructChat`-shaped JSON carrying a pending
47 * interrupt. Proves a fresh client (empty `localStorage`) re-prompts the
48 * approval from the server alone — the path that was previously broken.
49 * - `structured-output` — runs separate structured-output finalization through
50 * `withPersistence`, then hydrates the completed structured-output part from
51 * the server through `reconstructChat`.
52 * - `harness-output` — emits event-sourced structured output (the harness
53 * adapter path) through `withPersistence`, then hydrates the prose message
54 * and the structured-output message from `reconstructChat`.
55 * - `usage` — runs two provider calls through server persistence and returns
56 * their stored cumulative usage.
57 * - `tool-error` — runs a server tool that throws through `withPersistence`,
58 * then hydrates the failed tool call from `reconstructChat`.
59 *
60 * Exempt from the aimock policy: this route never reaches an LLM provider's HTTP
61 * layer, so there is nothing to mock.
62 */
63​
64const REPLY_TEXT = 'PERSIST_OK the lighthouse still turns.'
65​
66const structuredOutputPersistence = memoryPersistence()
67const structuredOutputSchema = z.object({ name: z.string() })
68const structuredOutputTool = toolDefinition({
69 name: 'lookup_programmer',
70 description: 'Look up a programmer',
71 inputSchema: z.object({}),
72}).server(() => ({ found: true }))
73const structuredOutputAdapter: AnyTextAdapter = {
74 kind: 'text',
75 name: 'fixed',
76 model: 'test-model',
77 '~types': {},
78 chatStream: ({ threadId, runId }: { threadId: string; runId: string }) =>
79 textRun(threadId, runId),
80 structuredOutput: () =>
81 Promise.resolve({
82 data: { name: 'Ada Lovelace' },
83 rawText: '{"name":"Ada Lovelace"}',
84 }),
85} as unknown as AnyTextAdapter
86​
87const harnessOutputPersistence = memoryPersistence()
88const HARNESS_PROSE = 'looking around the repo'
89const HARNESS_RAW = '{"name":"Ada Lovelace"}'
90​
91function harnessOutputRun(
92 threadId: string,
93 runId: string,
94): AsyncIterable<StreamChunk> {
95 return (async function* () {
96 yield {
97 type: 'RUN_STARTED',
98 threadId,
99 runId,
100 timestamp: Date.now(),
101 } as StreamChunk
102 yield {
103 type: 'TEXT_MESSAGE_START',
104 messageId: 'harness-prose',
105 role: 'assistant',
106 timestamp: Date.now(),
107 } as StreamChunk
108 yield {
109 type: 'TEXT_MESSAGE_CONTENT',
110 messageId: 'harness-prose',
111 delta: HARNESS_PROSE,
112 content: HARNESS_PROSE,
113 timestamp: Date.now(),
114 } as StreamChunk
115 yield {
116 type: 'TEXT_MESSAGE_END',
117 messageId: 'harness-prose',
118 timestamp: Date.now(),
119 } as StreamChunk
120 yield {
121 type: 'CUSTOM',
122 name: 'structured-output.start',
123 value: { messageId: 'harness-so' },
124 timestamp: Date.now(),
125 } as StreamChunk
126 yield {
127 type: 'CUSTOM',
128 name: 'structured-output.complete',
129 value: {
130 messageId: 'harness-so',
131 object: { name: 'Ada Lovelace' },
132 raw: HARNESS_RAW,
133 },
134 timestamp: Date.now(),
135 } as StreamChunk
136 yield {
137 type: 'RUN_FINISHED',
138 threadId,
139 runId,
140 timestamp: Date.now(),
141 outcome: { type: 'success' },
142 } as StreamChunk
143 })()
145​
146const harnessOutputAdapter: AnyTextAdapter = {
147 kind: 'text',
148 name: 'fixed',
149 model: 'test-model',
150 '~types': {},
151 supportsCombinedToolsAndSchema: () => true,
152 combinedStructuredOutputSource: () => 'event',
153 chatStream: ({ threadId, runId }: { threadId: string; runId: string }) =>
154 harnessOutputRun(threadId, runId),
155} as unknown as AnyTextAdapter
156​
157const toolErrorPersistence = memoryPersistence()
158const failingTool = toolDefinition({
159 name: 'check_status',
160 description: 'Check the service status',
161 inputSchema: z.object({}),
162}).server(() => {
163 throw new Error('Status service unavailable')
164})
165​
166function toolErrorRun(
167 threadId: string,
168 runId: string,
169 messages: ReadonlyArray<{ role: string }>,
170): AsyncIterable<StreamChunk> {
171 if (messages.some((message) => message.role === 'tool')) {
172 return textRun(threadId, runId)
173 }
174 return (async function* () {
175 yield {
176 type: 'RUN_STARTED',
177 threadId,
178 runId,
179 timestamp: Date.now(),
180 } as StreamChunk
181 yield {
182 type: 'TOOL_CALL_START',
183 toolCallId: 'call-status',
184 toolCallName: 'check_status',
185 toolName: 'check_status',
186 timestamp: Date.now(),
187 } as StreamChunk
188 yield {
189 type: 'TOOL_CALL_ARGS',
190 toolCallId: 'call-status',
191 delta: '{}',
192 timestamp: Date.now(),
193 } as StreamChunk
194 yield {
195 type: 'TOOL_CALL_END',
196 toolCallId: 'call-status',
197 timestamp: Date.now(),
198 } as StreamChunk
199 yield {
200 type: 'RUN_FINISHED',
201 threadId,
202 runId,
203 finishReason: 'tool_calls',
204 timestamp: Date.now(),
205 } as StreamChunk
206 })()
208​
209const toolErrorAdapter: AnyTextAdapter = {
210 kind: 'text',
211 name: 'fixed',
212 model: 'test-model',
213 '~types': {},
214 chatStream: ({
215 threadId,
216 runId,
217 messages,
218 }: {
219 threadId: string
220 runId: string
221 messages: ReadonlyArray<{ role: string }>
222 }) => toolErrorRun(threadId, runId, messages),
223} as unknown as AnyTextAdapter
224​
225const confirmSchema = {
226 type: 'object',
227 properties: { confirmed: { type: 'boolean' } },
228 required: ['confirmed'],
230​
231function textRun(
232 threadId: string,
233 runId: string,
234 usage?: TokenUsage,
235): AsyncIterable<StreamChunk> {
236 return (async function* () {
237 yield {
238 type: 'RUN_STARTED',
239 threadId,
240 runId,
241 timestamp: Date.now(),
242 } as StreamChunk
243 yield {
244 type: 'TEXT_MESSAGE_START',
245 messageId: 'assistant-1',
246 role: 'assistant',
247 timestamp: Date.now(),
248 } as StreamChunk
249 yield {
250 type: 'TEXT_MESSAGE_CONTENT',
251 messageId: 'assistant-1',
252 delta: REPLY_TEXT,
253 content: REPLY_TEXT,
254 timestamp: Date.now(),
255 } as StreamChunk
256 yield {
257 type: 'TEXT_MESSAGE_END',
258 messageId: 'assistant-1',
259 timestamp: Date.now(),
260 } as StreamChunk
261 yield {
262 type: 'RUN_FINISHED',
263 threadId,
264 runId,
265 timestamp: Date.now(),
266 outcome: { type: 'success' },
267 ...(usage ? { usage } : {}),
268 } as StreamChunk
269 })()
271​
272const usagePersistence = memoryPersistence()
273const usageTool: Tool = {
274 name: 'search',
275 description: 'Search',
276 execute: () => ({ hits: [] }),
278const usageAdapter = {
279 kind: 'text',
280 name: 'fixed',
281 model: 'test-model',
282 '~types': {},
283 chatStream: ({ threadId, runId }: { threadId: string; runId: string }) =>
284 textRun(threadId, runId, {
285 promptTokens: 12,
286 completionTokens: 4,
287 totalTokens: 16,
288 }),
289 structuredOutput: () =>
290 Promise.resolve({
291 data: { name: 'Ada Lovelace' },
292 rawText: '{"name":"Ada Lovelace"}',
293 usage: {
294 promptTokens: 7,
295 completionTokens: 2,
296 totalTokens: 9,
297 },
298 }),
299} as unknown as AnyTextAdapter
300​
301async function cumulativeUsage(threadId: string, runId: string) {
302 const stream = chat({
303 adapter: usageAdapter,
304 messages: [{ role: 'user', content: 'Name the programmer' }],
305 tools: [usageTool],
306 outputSchema: {
307 type: 'object',
308 properties: { name: { type: 'string' } },
309 },
310 stream: true,
311 threadId,
312 runId,
313 middleware: [withPersistence(usagePersistence)],
314 })
315 for await (const _ of stream) void _
316 return usagePersistence.stores.runs?.get(runId)
318​
319function interruptRun(
320 threadId: string,
321 runId: string,
322): AsyncIterable<StreamChunk> {
323 return (async function* () {
324 yield {
325 type: 'RUN_STARTED',
326 threadId,
327 runId,
328 timestamp: Date.now(),
329 } as StreamChunk
330 yield {
331 type: 'RUN_FINISHED',
332 threadId,
333 runId,
334 timestamp: Date.now(),
335 outcome: {
336 type: 'interrupt',
337 interrupts: [
338 {
339 id: 'confirm-shipment',
340 reason: 'confirmation',
341 message: 'Confirm the shipment?',
342 responseSchema: confirmSchema,
343 metadata: {
344 [INTERRUPT_BINDING_METADATA_KEY]: {
345 v: INTERRUPT_BINDING_VERSION,
346 kind: 'generic',
347 interruptId: 'confirm-shipment',
348 interruptedRunId: runId,
349 generation: 0,
350 responseSchemaHash: digestInterruptJson(
351 canonicalInterruptJson(confirmSchema),
352 ),
353 },
354 },
355 },
356 ],
357 },
358 } as StreamChunk
359 })()
361​
362function stringField(body: unknown, key: string): string | undefined {
363 if (typeof body !== 'object' || body === null || !(key in body)) {
364 return undefined
365 }
366 const value: unknown = (body as Record<string, unknown>)[key]
367 return typeof value === 'string' ? value : undefined
369​
370function scenarioOf(
371 request: Request,
372):
373 | 'text'
374 | 'interrupt'
375 | 'server-interrupt'
376 | 'structured-output'
377 | 'harness-output'
378 | 'usage'
379 | 'tool-error' {
380 try {
381 const value = new URL(request.url).searchParams.get('scenario')
382 if (value === 'interrupt') return 'interrupt'
383 if (value === 'server-interrupt') return 'server-interrupt'
384 if (value === 'structured-output') return 'structured-output'
385 if (value === 'harness-output') return 'harness-output'
386 if (value === 'usage') return 'usage'
387 if (value === 'tool-error') return 'tool-error'
388 return 'text'
389 } catch {
390 return 'text'
391 }
393​
394// The pending interrupt a server-authoritative client rehydrates from the GET
395// below. It is the same BOUND generic interrupt shape the `interrupt` run ends
396// on, but delivered as `reconstructChat`'s `interrupts.pending[]` payload rather
397// than a live terminal — so the client restores it from the server on mount.
398const SERVER_INTERRUPT_RUN_ID = 'server-interrupt-run'
399​
400function serverInterruptReconstruction(): {
401 messages: []
402 activeRun: null
403 interrupts: { runId: string; pending: Array<Record<string, unknown>> }
404} {
405 return {
406 messages: [],
407 activeRun: null,
408 interrupts: {
409 runId: SERVER_INTERRUPT_RUN_ID,
410 pending: [
411 {
412 id: 'confirm-shipment',
413 reason: 'confirmation',
414 message: 'Confirm the shipment?',
415 responseSchema: confirmSchema,
416 metadata: {
417 [INTERRUPT_BINDING_METADATA_KEY]: {
418 v: INTERRUPT_BINDING_VERSION,
419 kind: 'generic',
420 interruptId: 'confirm-shipment',
421 interruptedRunId: SERVER_INTERRUPT_RUN_ID,
422 generation: 0,
423 responseSchemaHash: digestInterruptJson(
424 canonicalInterruptJson(confirmSchema),
425 ),
426 },
427 },
428 },
429 ],
430 },
431 }
433​
434export const Route = createFileRoute('/api/persistence-durability')({
435 server: {
436 handlers: {
437 POST: async ({ request }) => {
438 const body: unknown = await request.json()
439 const threadId = stringField(body, 'threadId') ?? 'persistence-thread'
440 const runId = stringField(body, 'runId') ?? crypto.randomUUID()
441 const scenario = scenarioOf(request)
442 if (scenario === 'structured-output') {
443 const stream = chat({
444 adapter: structuredOutputAdapter,
445 messages: [{ role: 'user', content: 'Name the programmer' }],
446 tools: [structuredOutputTool],
447 outputSchema: structuredOutputSchema,
448 stream: true,
449 threadId,
450 runId,
451 middleware: [withPersistence(structuredOutputPersistence)],
452 })
453 for await (const _ of stream) void _
454 return Response.json({ runId, threadId })
455 }
456 if (scenario === 'harness-output') {
457 const stream = chat({
458 adapter: harnessOutputAdapter,
459 messages: [{ role: 'user', content: 'Name the programmer' }],
460 outputSchema: structuredOutputSchema,
461 stream: true,
462 threadId,
463 runId,
464 middleware: [withPersistence(harnessOutputPersistence)],
465 })
466 for await (const _ of stream) void _
467 return Response.json({ runId, threadId })
468 }
469 if (scenario === 'tool-error') {
470 const stream = chat({
471 adapter: toolErrorAdapter,
472 messages: [{ role: 'user', content: 'Is the service up?' }],
473 tools: [failingTool],
474 threadId,
475 runId,
476 middleware: [withPersistence(toolErrorPersistence)],
477 })
478 for await (const _ of stream) void _
479 return Response.json({ runId, threadId })
480 }
481 if (scenario === 'usage') {
482 const run = await cumulativeUsage(threadId, runId)
483 return Response.json({ runId, threadId, usage: run?.usage })
484 }
485 const stream =
486 scenario === 'interrupt'
487 ? interruptRun(threadId, runId)
488 : textRun(threadId, runId)
489 return toServerSentEventsResponse(stream, {
490 durability: { adapter: memoryStream(request) },
491 })
492 },
493​
494 // GET serves two jobs off one route, mirroring the production wiring:
495 //
496 // 1. Delivery replay — re-attach to an in-flight run by id
497 // (`?offset=-1&runId=…`). Detected via the durability adapter's
498 // `resumeFrom()`. Read-only: no producer stream is built.
499 // 2. Server-authoritative hydration — the `persistence: true` client's mount
500 // probe (a plain `?threadId=` GET, no resume cursor). Returns a
501 // `reconstructChat`-shaped JSON; the `server-interrupt` scenario carries
502 // a pending approval so a fresh client re-prompts it from the server.
503 GET: ({ request }) => {
504 if (scenarioOf(request) === 'structured-output') {
505 return reconstructChat(structuredOutputPersistence, request, {
506 authorize: (threadId) => threadId.length > 0,
507 })
508 }
509 if (scenarioOf(request) === 'harness-output') {
510 return reconstructChat(harnessOutputPersistence, request, {
511 authorize: (threadId) => threadId.length > 0,
512 })
513 }
514 if (scenarioOf(request) === 'tool-error') {
515 return reconstructChat(toolErrorPersistence, request, {
516 authorize: (threadId) => threadId.length > 0,
517 })
518 }
519 if (scenarioOf(request) === 'usage') {
520 return reconstructChat(usagePersistence, request, {
521 authorize: (threadId) => threadId.length > 0,
522 includeRuns: true,
523 })
524 }
525 const durability = memoryStream(request)
526 if (durability.resumeFrom() !== null) {
527 return resumeServerSentEventsResponse({ adapter: durability })
528 }
529 const body =
530 scenarioOf(request) === 'server-interrupt'
531 ? serverInterruptReconstruction()
532 : { messages: [], activeRun: null, interrupts: null }
533 return new Response(JSON.stringify(body), {
534 headers: {
535 'content-type': 'application/json',
536 'cache-control': 'no-store',
537 },
538 })
539 },
540 },
541 },
542})