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

persistence-durability.spec.ts

400 lines13.8 KB

1import { expect, test } from '@playwright/test'
2import { collectHydrationErrors, sendMessage, waitForResponse } from './helpers'
3import type { Page } from '@playwright/test'
4​
5/**
6 * Client browser-refresh durability (persistence layer).
7 *
8 * Proves the story wired by `localStoragePersistence` + `useChat({ persistence,
9 * id, threadId })`: a single combined `{ messages, resume }` record per chat id
10 * survives a full `page.reload()`, so the conversation — and any pending
11 * interrupt — is restored from `localStorage` with no server round-trip.
12 *
13 * Provider-free: the `/api/persistence-durability` harness route streams a fixed
14 * AG-UI sequence through a `memoryStream` delivery sink, so there is no LLM in
15 * the loop and nothing to mock (exempt from the aimock policy).
16 *
17 * The mid-stream "rejoin an in-flight run via joinRun after reload" path is NOT
18 * covered here: the harness stream completes in a single tick, so there is no
19 * deterministic window to reload while a run is still producing. That resume
20 * cursor is covered at the transport layer by `delivery-durability.spec.ts`.
21 * A client-tool replay that must drain after `joinRun` (issue #1058) is in
22 * `join-run-client-tool.spec.ts`.
23 */
24​
25async function interruptCount(page: Page): Promise<number> {
26 const raw = await page
27 .getByTestId('interrupt-count')
28 .getAttribute('data-count')
29 return raw ? Number(raw) : 0
31​
32test.describe('persistence durability (browser refresh)', () => {
33 test('restores the conversation from the combined localStorage record after reload', async ({
34 page,
35 }) => {
36 await page.goto('/persistence-durability')
37​
38 await sendMessage(page, 'tell me about the lighthouse')
39 await waitForResponse(page)
40​
41 await expect(page.getByTestId('user-message')).toContainText(
42 'tell me about the lighthouse',
43 )
44 await expect(page.getByTestId('assistant-message')).toContainText(
45 'PERSIST_OK',
46 )
47​
48 // The adapter writes ONE combined record (messages + optional resume) under
49 // one namespaced key. After a clean finish the resume half is dropped, so
50 // the persisted record is messages-only.
51 const stored = await page.evaluate(() =>
52 window.localStorage.getItem('tanstack-ai:persistence-durability-text'),
53 )
54 expect(stored).not.toBeNull()
55 const record = JSON.parse(stored!) as {
56 messages: Array<unknown>
57 resume?: unknown
58 }
59 expect(Array.isArray(record.messages)).toBe(true)
60 expect(record.messages.length).toBeGreaterThanOrEqual(2)
61​
62 const hydrationErrors = collectHydrationErrors(page)
63​
64 // Full reload: the conversation must come back from localStorage alone.
65 await page.reload()
66​
67 await expect(page.getByTestId('message-list')).toBeVisible()
68 await expect(page.getByTestId('user-message')).toContainText(
69 'tell me about the lighthouse',
70 )
71 await expect(page.getByTestId('assistant-message')).toContainText(
72 'PERSIST_OK',
73 )
74 // No in-flight run to rejoin after a clean finish — the page settles idle.
75 await expect(page.getByTestId('loading-indicator')).toHaveCount(0)
76 expect(hydrationErrors).toEqual([])
77 })
78​
79 test('a pending interrupt survives a reload (rehydrated from the resume snapshot)', async ({
80 page,
81 }) => {
82 await page.goto('/persistence-durability?scenario=interrupt')
83​
84 await sendMessage(page, 'ship the order')
85​
86 // The run ends on a bound generic interrupt; the client folds the pending
87 // interrupt into the same combined record.
88 await expect
89 .poll(() => interruptCount(page), { timeout: 15_000 })
90 .toBeGreaterThanOrEqual(1)
91 await expect(page.getByTestId('interrupt-confirm-shipment')).toBeVisible()
92 await expect(page.getByTestId('interrupt-source')).toHaveText('live')
93​
94 // The combined record carries the resume half while the interrupt is pending.
95 const stored = await page.evaluate(() =>
96 window.localStorage.getItem(
97 'tanstack-ai:persistence-durability-interrupt',
98 ),
99 )
100 expect(stored).not.toBeNull()
101 const record = JSON.parse(stored!) as { resume?: unknown }
102 expect(record.resume).toBeTruthy()
103​
104 const hydrationErrors = collectHydrationErrors(page)
105​
106 // Full reload: the interrupt must rehydrate from localStorage, not a refetch.
107 await page.reload()
108​
109 await expect(page.getByTestId('persistence-durability-page')).toBeVisible()
110 await expect
111 .poll(() => interruptCount(page), { timeout: 15_000 })
112 .toBeGreaterThanOrEqual(1)
113 await expect(page.getByTestId('interrupt-confirm-shipment')).toBeVisible()
114 await expect(page.getByTestId('interrupt-kind')).toHaveText('generic')
115 await expect(page.getByTestId('interrupt-source')).toHaveText('hydrate')
116 expect(hydrationErrors).toEqual([])
117 })
118​
119 test('restores a pending interrupt from the SERVER on a fresh load (persistence: true)', async ({
120 page,
121 }) => {
122 // Server-authoritative: the client caches nothing. On mount it hydrates from
123 // the GET, which returns a pending approval. This is the path that was
124 // broken — a fresh client showed the paused tool call with no way to
125 // approve/reject. Clear localStorage before the asserting load so the
126 // interrupt can ONLY have come from the server.
127 await page.goto('/persistence-durability?scenario=server-interrupt')
128 await page.evaluate(() => window.localStorage.clear())
129 await page.reload()
130​
131 await expect(page.getByTestId('persistence-durability-page')).toBeVisible()
132 // localStorage is empty, so a visible interrupt proves server-side restore.
133 await expect
134 .poll(() => interruptCount(page), { timeout: 15_000 })
135 .toBeGreaterThanOrEqual(1)
136 await expect(page.getByTestId('interrupt-confirm-shipment')).toBeVisible()
137 await expect(page.getByTestId('interrupt-kind')).toHaveText('generic')
138 await expect(page.getByTestId('interrupt-source')).toHaveText('hydrate')
139 // Restored bound and resolvable — the reload can approve/reject, not just
140 // view a dead paused tool call.
141 await expect(page.getByTestId('interrupt-can-resolve')).toHaveText('true')
142​
143 // And the client wrote nothing to localStorage: `persistence: true` keeps no
144 // record at all, so the interrupt could only have come from the server.
145 const stored = await page.evaluate(() =>
146 window.localStorage.getItem(
147 'tanstack-ai:persistence-durability-server-interrupt',
148 ),
149 )
150 expect(stored).toBeNull()
151 })
152​
153 test('sends one hydrate GET when a chat mounts under React Strict Mode (persistence: true)', async ({
154 page,
155 }) => {
156 // The dev server replays a client mount's effects (attach, detach, attach)
157 // before the first GET returns. Each attach used to send its own hydrate
158 // GET. The page mounts the chat after hydration, because a hydrated mount
159 // gets no replay.
160 const hydrateGets: Array<string> = []
161 page.on('request', (req) => {
162 const url = new URL(req.url())
163 if (
164 req.method() === 'GET' &&
165 url.pathname === '/api/persistence-durability' &&
166 url.searchParams.has('threadId')
167 ) {
168 hydrateGets.push(req.url())
169 }
170 })
171​
172 await page.goto('/client-mount-hydrate')
173​
174 // The interrupt comes from the hydrate response, so every hydrate GET of
175 // this mount was already sent when it shows.
176 await expect
177 .poll(() => interruptCount(page), { timeout: 15_000 })
178 .toBeGreaterThanOrEqual(1)
179 expect(hydrateGets).toHaveLength(1)
180 })
181})
182​
183test.describe('structured output persistence', () => {
184 test('restores a completed structured-output part from server persistence', async ({
185 request,
186 }) => {
187 const threadId = `structured-output-${crypto.randomUUID()}`
188 const runId = crypto.randomUUID()
189 const run = await request.post(
190 '/api/persistence-durability?scenario=structured-output',
191 { data: { threadId, runId } },
192 )
193 expect(run.ok()).toBe(true)
194​
195 const hydration = await request.get(
196 `/api/persistence-durability?scenario=structured-output&threadId=${threadId}`,
197 )
198 expect(hydration.ok()).toBe(true)
199 const body = (await hydration.json()) as {
200 messages: Array<{
201 role: string
202 parts: Array<Record<string, unknown>>
203 }>
204 }
205 const assistants = body.messages.filter(
206 (message) => message.role === 'assistant',
207 )
208​
209 expect(assistants).toHaveLength(2)
210 expect(assistants[0]?.parts).toEqual([
211 {
212 type: 'text',
213 content: 'PERSIST_OK the lighthouse still turns.',
214 },
215 ])
216 expect(assistants[1]?.parts).toEqual([
217 {
218 type: 'structured-output',
219 status: 'complete',
220 data: { name: 'Ada Lovelace' },
221 partial: { name: 'Ada Lovelace' },
222 raw: '{"name":"Ada Lovelace"}',
223 },
224 ])
225 })
226​
227 test('restores event-sourced harness structured output from server persistence', async ({
228 request,
229 }) => {
230 const threadId = `harness-output-${crypto.randomUUID()}`
231 const runId = crypto.randomUUID()
232 const run = await request.post(
233 '/api/persistence-durability?scenario=harness-output',
234 { data: { threadId, runId } },
235 )
236 expect(run.ok()).toBe(true)
237​
238 const hydration = await request.get(
239 `/api/persistence-durability?scenario=harness-output&threadId=${threadId}`,
240 )
241 expect(hydration.ok()).toBe(true)
242 const body = (await hydration.json()) as {
243 messages: Array<{
244 role: string
245 parts: Array<Record<string, unknown>>
246 }>
247 }
248 const assistants = body.messages.filter(
249 (message) => message.role === 'assistant',
250 )
251​
252 expect(assistants).toHaveLength(2)
253 expect(assistants[0]?.parts).toEqual([
254 {
255 type: 'text',
256 content: 'looking around the repo',
257 },
258 ])
259 expect(assistants[1]?.parts).toEqual([
260 {
261 type: 'structured-output',
262 status: 'complete',
263 data: { name: 'Ada Lovelace' },
264 partial: { name: 'Ada Lovelace' },
265 raw: '{"name":"Ada Lovelace"}',
266 },
267 ])
268 })
269})
270​
271test.describe('server persistence', () => {
272 test('stores cumulative usage across model calls', async ({ request }) => {
273 const run = await request.post(
274 '/api/persistence-durability?scenario=usage',
275 {
276 data: {
277 threadId: `usage-${crypto.randomUUID()}`,
278 runId: crypto.randomUUID(),
279 },
280 },
281 )
282 expect(run.ok()).toBe(true)
283 const body = (await run.json()) as {
284 usage?: {
285 promptTokens: number
286 completionTokens: number
287 totalTokens: number
288 }
289 }
290 expect(body.usage).toEqual({
291 promptTokens: 19,
292 completionTokens: 6,
293 totalTokens: 25,
294 })
295 })
296​
297 test('reconstructChat with includeRuns returns run timings (issue #1061)', async ({
298 request,
299 }) => {
300 const threadId = `run-timings-${crypto.randomUUID()}`
301 const run = await request.post(
302 '/api/persistence-durability?scenario=usage',
303 { data: { threadId, runId: crypto.randomUUID() } },
304 )
305 expect(run.ok()).toBe(true)
306 const { runId } = (await run.json()) as { runId: string }
307​
308 const hydrated = await request.get(
309 `/api/persistence-durability?scenario=usage&threadId=${encodeURIComponent(threadId)}`,
310 )
311 expect(hydrated.ok()).toBe(true)
312 const body = (await hydrated.json()) as {
313 runs?: Array<{
314 runId: string
315 status: string
316 startedAt: number
317 finishedAt?: number
318 }>
319 messages: Array<{
320 role: string
321 metadata?: {
322 tanstack?: {
323 run?: { id: string; startedAt?: number; finishedAt?: number }
324 }
325 }
326 }>
327 }
328​
329 expect(body.runs).toHaveLength(1)
330 const [timing] = body.runs!
331 expect(timing).toMatchObject({ runId, status: 'completed' })
332 expect(timing!.finishedAt).toBeGreaterThanOrEqual(timing!.startedAt)
333 const assistant = body.messages.filter((m) => m.role === 'assistant')
334 expect(assistant.length).toBeGreaterThan(0)
335 for (const message of assistant) {
336 expect(message.metadata?.tanstack?.run).toEqual({
337 id: runId,
338 startedAt: timing!.startedAt,
339 finishedAt: timing!.finishedAt,
340 })
341 }
342 })
343​
344 test('restores a failed server tool call as failed', async ({ request }) => {
345 const threadId = `tool-error-${crypto.randomUUID()}`
346 const run = await request.post(
347 '/api/persistence-durability?scenario=tool-error',
348 { data: { threadId, runId: crypto.randomUUID() } },
349 )
350 expect(run.ok()).toBe(true)
351​
352 const hydration = await request.get(
353 `/api/persistence-durability?scenario=tool-error&threadId=${threadId}`,
354 )
355 expect(hydration.ok()).toBe(true)
356 const body = (await hydration.json()) as {
357 messages: Array<{ parts: Array<Record<string, unknown>> }>
358 }
359 const parts = body.messages.flatMap((message) => message.parts)
360​
361 expect(parts).toContainEqual(
362 expect.objectContaining({
363 type: 'tool-result',
364 toolCallId: 'call-status',
365 state: 'error',
366 error: 'Status service unavailable',
367 }),
368 )
369 })
370​
371 test('restores the error of a stopped child', async ({ request }) => {
372 const threadId = `subagent-stopped-${crypto.randomUUID()}`
373 const runId = crypto.randomUUID()
374 const seed = await request.post(
375 '/api/persistence-durability?scenario=subagent-stopped',
376 { data: { threadId, runId } },
377 )
378 expect(seed.ok()).toBe(true)
379​
380 const hydration = await request.get(
381 `/api/persistence-durability?scenario=subagent-stopped&threadId=${encodeURIComponent(threadId)}`,
382 )
383 expect(hydration.ok()).toBe(true)
384 const body = (await hydration.json()) as {
385 messages: Array<{ parts: Array<Record<string, unknown>> }>
386 }
387 const parts = body.messages.flatMap((message) => message.parts)
388​
389 expect(parts).toContainEqual(
390 expect.objectContaining({
391 type: 'subagent',
392 subagent: expect.objectContaining({
393 name: 'researcher',
394 status: 'error',
395 error: { message: 'Stopped' },
396 }),
397 }),
398 )
399 })
400})