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

api.persistence-durability.ts

652 lines20.5 KB

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