Open History to see the last commit
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 * - `subagent-stopped` — reconstructs a stopped child. Its run record has no
60 * error, so the card error comes from the stored child metadata.
61 *
62 * Exempt from the aimock policy: this route never reaches an LLM provider's HTTP
63 * layer, so there is nothing to mock.
64 */
65
66const REPLY_TEXT = 'PERSIST_OK the lighthouse still turns.'
67
68const structuredOutputPersistence = memoryPersistence()
69const structuredOutputSchema = z.object({ name: z.string() })
70const structuredOutputTool = toolDefinition({
71 name: 'lookup_programmer',
72 description: 'Look up a programmer',
73 inputSchema: z.object({}),
74}).server(() => ({ found: true }))
75const structuredOutputAdapter: AnyTextAdapter = {
76 kind: 'text',
77 name: 'fixed',
78 model: 'test-model',
79 '~types': {},
80 chatStream: ({ threadId, runId }: { threadId: string; runId: string }) =>
81 textRun(threadId, runId),
82 structuredOutput: () =>
83 Promise.resolve({
84 data: { name: 'Ada Lovelace' },
85 rawText: '{"name":"Ada Lovelace"}',
86 }),
87} as unknown as AnyTextAdapter
88
89const harnessOutputPersistence = memoryPersistence()
90const HARNESS_PROSE = 'looking around the repo'
91const HARNESS_RAW = '{"name":"Ada Lovelace"}'
92
93function harnessOutputRun(
94 threadId: string,
95 runId: string,
96): AsyncIterable<StreamChunk> {
97 return (async function* () {
98 yield {
99 type: 'RUN_STARTED',
100 threadId,
101 runId,
102 timestamp: Date.now(),
103 } as StreamChunk
104 yield {
105 type: 'TEXT_MESSAGE_START',
106 messageId: 'harness-prose',
107 role: 'assistant',
108 timestamp: Date.now(),
109 } as StreamChunk
110 yield {
111 type: 'TEXT_MESSAGE_CONTENT',
112 messageId: 'harness-prose',
113 delta: HARNESS_PROSE,
114 content: HARNESS_PROSE,
115 timestamp: Date.now(),
116 } as StreamChunk
117 yield {
118 type: 'TEXT_MESSAGE_END',
119 messageId: 'harness-prose',
120 timestamp: Date.now(),
121 } as StreamChunk
122 yield {
123 type: 'CUSTOM',
124 name: 'structured-output.start',
125 value: { messageId: 'harness-so' },
126 timestamp: Date.now(),
127 } as StreamChunk
128 yield {
129 type: 'CUSTOM',
130 name: 'structured-output.complete',
131 value: {
132 messageId: 'harness-so',
133 object: { name: 'Ada Lovelace' },
134 raw: HARNESS_RAW,
135 },
136 timestamp: Date.now(),
137 } as StreamChunk
138 yield {
139 type: 'RUN_FINISHED',
140 threadId,
141 runId,
142 timestamp: Date.now(),
143 outcome: { type: 'success' },
144 } as StreamChunk
145 })()
146}
147
148const harnessOutputAdapter: AnyTextAdapter = {
149 kind: 'text',
150 name: 'fixed',
151 model: 'test-model',
152 '~types': {},
153 supportsCombinedToolsAndSchema: () => true,
154 combinedStructuredOutputSource: () => 'event',
155 chatStream: ({ threadId, runId }: { threadId: string; runId: string }) =>
156 harnessOutputRun(threadId, runId),
157} as unknown as AnyTextAdapter
158
159const toolErrorPersistence = memoryPersistence()
160const subagentStoppedPersistence = memoryPersistence()
161const failingTool = toolDefinition({
162 name: 'check_status',
163 description: 'Check the service status',
164 inputSchema: z.object({}),
165}).server(() => {
166 throw new Error('Status service unavailable')
167})
168
169function toolErrorRun(
170 threadId: string,
171 runId: string,
172 messages: ReadonlyArray<{ role: string }>,
173): AsyncIterable<StreamChunk> {
174 if (messages.some((message) => message.role === 'tool')) {
175 return textRun(threadId, runId)
176 }
177 return (async function* () {
178 yield {
179 type: 'RUN_STARTED',
180 threadId,
181 runId,
182 timestamp: Date.now(),
183 } as StreamChunk
184 yield {
185 type: 'TOOL_CALL_START',
186 toolCallId: 'call-status',
187 toolCallName: 'check_status',
188 toolName: 'check_status',
189 timestamp: Date.now(),
190 } as StreamChunk
191 yield {
192 type: 'TOOL_CALL_ARGS',
193 toolCallId: 'call-status',
194 delta: '{}',
195 timestamp: Date.now(),
196 } as StreamChunk
197 yield {
198 type: 'TOOL_CALL_END',
199 toolCallId: 'call-status',
200 timestamp: Date.now(),
201 } as StreamChunk
202 yield {
203 type: 'RUN_FINISHED',
204 threadId,
205 runId,
206 finishReason: 'tool_calls',
207 timestamp: Date.now(),
208 } as StreamChunk
209 })()
210}
211
212const toolErrorAdapter: AnyTextAdapter = {
213 kind: 'text',
214 name: 'fixed',
215 model: 'test-model',
216 '~types': {},
217 chatStream: ({
218 threadId,
219 runId,
220 messages,
221 }: {
222 threadId: string
223 runId: string
224 messages: ReadonlyArray<{ role: string }>
225 }) => toolErrorRun(threadId, runId, messages),
226} as unknown as AnyTextAdapter
227
228const confirmSchema = {
229 type: 'object',
230 properties: { confirmed: { type: 'boolean' } },
231 required: ['confirmed'],
232}
233
234function textRun(
235 threadId: string,
236 runId: string,
237 usage?: TokenUsage,
238): AsyncIterable<StreamChunk> {
239 return (async function* () {
240 yield {
241 type: 'RUN_STARTED',
242 threadId,
243 runId,
244 timestamp: Date.now(),
245 } as StreamChunk
246 yield {
247 type: 'TEXT_MESSAGE_START',
248 messageId: 'assistant-1',
249 role: 'assistant',
250 timestamp: Date.now(),
251 } as StreamChunk
252 yield {
253 type: 'TEXT_MESSAGE_CONTENT',
254 messageId: 'assistant-1',
255 delta: REPLY_TEXT,
256 content: REPLY_TEXT,
257 timestamp: Date.now(),
258 } as StreamChunk
259 yield {
260 type: 'TEXT_MESSAGE_END',
261 messageId: 'assistant-1',
262 timestamp: Date.now(),
263 } as StreamChunk
264 yield {
265 type: 'RUN_FINISHED',
266 threadId,
267 runId,
268 timestamp: Date.now(),
269 outcome: { type: 'success' },
270 ...(usage ? { usage } : {}),
271 } as StreamChunk
272 })()
273}
274
275const usagePersistence = memoryPersistence()
276const usageTool: Tool = {
277 name: 'search',
278 description: 'Search',
279 execute: () => ({ hits: [] }),
280}
281const usageAdapter = {
282 kind: 'text',
283 name: 'fixed',
284 model: 'test-model',
285 '~types': {},
286 chatStream: ({ threadId, runId }: { threadId: string; runId: string }) =>
287 textRun(threadId, runId, {
288 promptTokens: 12,
289 completionTokens: 4,
290 totalTokens: 16,
291 }),
292 structuredOutput: () =>
293 Promise.resolve({
294 data: { name: 'Ada Lovelace' },
295 rawText: '{"name":"Ada Lovelace"}',
296 usage: {
297 promptTokens: 7,
298 completionTokens: 2,
299 totalTokens: 9,
300 },
301 }),
302} as unknown as AnyTextAdapter
303
304async function cumulativeUsage(threadId: string, runId: string) {
305 const stream = chat({
306 adapter: usageAdapter,
307 messages: [{ role: 'user', content: 'Name the programmer' }],
308 tools: [usageTool],
309 outputSchema: {
310 type: 'object',
311 properties: { name: { type: 'string' } },
312 },
313 stream: true,
314 threadId,
315 runId,
316 middleware: [withPersistence(usagePersistence)],
317 })
318 for await (const _ of stream) void _
319 return usagePersistence.stores.runs?.get(runId)
320}
321
322function interruptRun(
323 threadId: string,
324 runId: string,
325): AsyncIterable<StreamChunk> {
326 return (async function* () {
327 yield {
328 type: 'RUN_STARTED',
329 threadId,
330 runId,
331 timestamp: Date.now(),
332 } as StreamChunk
333 yield {
334 type: 'RUN_FINISHED',
335 threadId,
336 runId,
337 timestamp: Date.now(),
338 outcome: {
339 type: 'interrupt',
340 interrupts: [
341 {
342 id: 'confirm-shipment',
343 reason: 'confirmation',
344 message: 'Confirm the shipment?',
345 responseSchema: confirmSchema,
346 metadata: {
347 [INTERRUPT_BINDING_METADATA_KEY]: {
348 v: INTERRUPT_BINDING_VERSION,
349 kind: 'generic',
350 interruptId: 'confirm-shipment',
351 interruptedRunId: runId,
352 generation: 0,
353 responseSchemaHash: digestInterruptJson(
354 canonicalInterruptJson(confirmSchema),
355 ),
356 },
357 },
358 },
359 ],
360 },
361 } as StreamChunk
362 })()
363}
364
365function stringField(body: unknown, key: string): string | undefined {
366 if (typeof body !== 'object' || body === null || !(key in body)) {
367 return undefined
368 }
369 const value: unknown = (body as Record<string, unknown>)[key]
370 return typeof value === 'string' ? value : undefined
371}
372
373function scenarioOf(
374 request: Request,
375):
376 | 'text'
377 | 'interrupt'
378 | 'server-interrupt'
379 | 'structured-output'
380 | 'harness-output'
381 | 'usage'
382 | 'tool-error'
383 | 'subagent-stopped' {
384 try {
385 const value = new URL(request.url).searchParams.get('scenario')
386 if (value === 'interrupt') return 'interrupt'
387 if (value === 'server-interrupt') return 'server-interrupt'
388 if (value === 'structured-output') return 'structured-output'
389 if (value === 'harness-output') return 'harness-output'
390 if (value === 'usage') return 'usage'
391 if (value === 'tool-error') return 'tool-error'
392 if (value === 'subagent-stopped') return 'subagent-stopped'
393 return 'text'
394 } catch {
395 return 'text'
396 }
397}
398
399// The pending interrupt a server-authoritative client rehydrates from the GET
400// below. It is the same BOUND generic interrupt shape the `interrupt` run ends
401// on, but delivered as `reconstructChat`'s `interrupts.pending[]` payload rather
402// than a live terminal — so the client restores it from the server on mount.
403const SERVER_INTERRUPT_RUN_ID = 'server-interrupt-run'
404
405function serverInterruptReconstruction(): {
406 messages: []
407 activeRun: null
408 interrupts: { runId: string; pending: Array<Record<string, unknown>> }
409} {
410 return {
411 messages: [],
412 activeRun: null,
413 interrupts: {
414 runId: SERVER_INTERRUPT_RUN_ID,
415 pending: [
416 {
417 id: 'confirm-shipment',
418 reason: 'confirmation',
419 message: 'Confirm the shipment?',
420 responseSchema: confirmSchema,
421 metadata: {
422 [INTERRUPT_BINDING_METADATA_KEY]: {
423 v: INTERRUPT_BINDING_VERSION,
424 kind: 'generic',
425 interruptId: 'confirm-shipment',
426 interruptedRunId: SERVER_INTERRUPT_RUN_ID,
427 generation: 0,
428 responseSchemaHash: digestInterruptJson(
429 canonicalInterruptJson(confirmSchema),
430 ),
431 },
432 },
433 },
434 ],
435 },
436 }
437}
438
439export const Route = createFileRoute('/api/persistence-durability')({
440 server: {
441 handlers: {
442 POST: async ({ request }) => {
443 const body: unknown = await request.json()
444 const threadId = stringField(body, 'threadId') ?? 'persistence-thread'
445 const runId = stringField(body, 'runId') ?? crypto.randomUUID()
446 const scenario = scenarioOf(request)
447 if (scenario === 'structured-output') {
448 const stream = chat({
449 adapter: structuredOutputAdapter,
450 messages: [{ role: 'user', content: 'Name the programmer' }],
451 tools: [structuredOutputTool],
452 outputSchema: structuredOutputSchema,
453 stream: true,
454 threadId,
455 runId,
456 middleware: [withPersistence(structuredOutputPersistence)],
457 })
458 for await (const _ of stream) void _
459 return Response.json({ runId, threadId })
460 }
461 if (scenario === 'harness-output') {
462 const stream = chat({
463 adapter: harnessOutputAdapter,
464 messages: [{ role: 'user', content: 'Name the programmer' }],
465 outputSchema: structuredOutputSchema,
466 stream: true,
467 threadId,
468 runId,
469 middleware: [withPersistence(harnessOutputPersistence)],
470 })
471 for await (const _ of stream) void _
472 return Response.json({ runId, threadId })
473 }
474 if (scenario === 'tool-error') {
475 const stream = chat({
476 adapter: toolErrorAdapter,
477 messages: [{ role: 'user', content: 'Is the service up?' }],
478 tools: [failingTool],
479 threadId,
480 runId,
481 middleware: [withPersistence(toolErrorPersistence)],
482 })
483 for await (const _ of stream) void _
484 return Response.json({ runId, threadId })
485 }
486 if (scenario === 'subagent-stopped') {
487 const { stores } = subagentStoppedPersistence
488 if (!stores.messages || !stores.runs) {
489 throw new Error('memory persistence has message and run stores')
490 }
491 const startedAt = Date.now()
492 const childRunId = `${runId}-child`
493 await stores.runs.createOrResume({
494 runId,
495 threadId,
496 status: 'completed',
497 startedAt,
498 })
499 await stores.messages.saveThread(threadId, [
500 {
501 id: `assistant:${runId}`,
502 role: 'assistant',
503 content: '',
504 metadata: { tanstack: { runId } },
505 },
506 ])
507 await stores.runs.createOrResume({
508 runId: childRunId,
509 threadId: `subagent:${childRunId}`,
510 parentRunId: runId,
511 subagentRunId: childRunId,
512 name: 'researcher',
513 status: 'aborted',
514 startedAt,
515 })
516 // A stopped child has no error on its run record.
517 await stores.runs.update(childRunId, { finishedAt: startedAt })
518 await stores.messages.saveThread(`subagent:${childRunId}`, [
519 {
520 id: `child:${childRunId}`,
521 role: 'assistant',
522 content: '',
523 metadata: {
524 tanstack: {
525 subagent: {
526 name: 'researcher',
527 status: 'error',
528 error: { message: 'Stopped' },
529 placeholder: true,
530 },
531 },
532 },
533 },
534 ])
535 return Response.json({ runId, threadId })
536 }
537 if (scenario === 'usage') {
538 const run = await cumulativeUsage(threadId, runId)
539 return Response.json({ runId, threadId, usage: run?.usage })
540 }
541 const stream =
542 scenario === 'interrupt'
543 ? interruptRun(threadId, runId)
544 : textRun(threadId, runId)
545 return toServerSentEventsResponse(stream, {
546 durability: { adapter: memoryStream(request) },
547 })
548 },
549
550 // GET serves two jobs off one route, mirroring the production wiring:
551 //
552 // 1. Delivery replay — re-attach to an in-flight run by id
553 // (`?offset=-1&runId=…`). Detected via the durability adapter's
554 // `resumeFrom()`. Read-only: no producer stream is built.
555 // 2. Server-authoritative hydration — the `persistence: true` client's mount
556 // probe (a plain `?threadId=` GET, no resume cursor). Returns a
557 // `reconstructChat`-shaped JSON; the `server-interrupt` scenario carries
558 // a pending approval so a fresh client re-prompts it from the server.
559 GET: ({ request }) => {
560 if (scenarioOf(request) === 'structured-output') {
561 return reconstructChat(structuredOutputPersistence, request, {
562 authorize: (threadId) => threadId.length > 0,
563 })
564 }
565 if (scenarioOf(request) === 'harness-output') {
566 return reconstructChat(harnessOutputPersistence, request, {
567 authorize: (threadId) => threadId.length > 0,
568 })
569 }
570 if (scenarioOf(request) === 'tool-error') {
571 return reconstructChat(toolErrorPersistence, request, {
572 authorize: (threadId) => threadId.length > 0,
573 })
574 }
575 if (scenarioOf(request) === 'subagent-stopped') {
576 return reconstructChat(subagentStoppedPersistence, request, {
577 authorize: (threadId) => threadId.length > 0,
578 })
579 }
580 if (scenarioOf(request) === 'usage') {
581 return reconstructChat(usagePersistence, request, {
582 authorize: (threadId) => threadId.length > 0,
583 includeRuns: true,
584 })
585 }
586 const durability = memoryStream(request)
587 if (durability.resumeFrom() !== null) {
588 return resumeServerSentEventsResponse({ adapter: durability })
589 }
590 const body =
591 scenarioOf(request) === 'server-interrupt'
592 ? serverInterruptReconstruction()
593 : { messages: [], activeRun: null, interrupts: null }
594 return new Response(JSON.stringify(body), {
595 headers: {
596 'content-type': 'application/json',
597 'cache-control': 'no-store',
598 },
599 })
600 },
601 },
602 },
603})