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

persistence-durability.spec.ts

335 lines11.6 KB

1import { expect, test } from '@playwright/test'
2import { 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 // Full reload: the conversation must come back from localStorage alone.
63 await page.reload()
64​
65 await expect(page.getByTestId('message-list')).toBeVisible()
66 await expect(page.getByTestId('user-message')).toContainText(
67 'tell me about the lighthouse',
68 )
69 await expect(page.getByTestId('assistant-message')).toContainText(
70 'PERSIST_OK',
71 )
72 // No in-flight run to rejoin after a clean finish — the page settles idle.
73 await expect(page.getByTestId('loading-indicator')).toHaveCount(0)
74 })
75​
76 test('a pending interrupt survives a reload (rehydrated from the resume snapshot)', async ({
77 page,
78 }) => {
79 await page.goto('/persistence-durability?scenario=interrupt')
80​
81 await sendMessage(page, 'ship the order')
82​
83 // The run ends on a bound generic interrupt; the client folds the pending
84 // interrupt into the same combined record.
85 await expect
86 .poll(() => interruptCount(page), { timeout: 15_000 })
87 .toBeGreaterThanOrEqual(1)
88 await expect(page.getByTestId('interrupt-confirm-shipment')).toBeVisible()
89 await expect(page.getByTestId('interrupt-source')).toHaveText('live')
90​
91 // The combined record carries the resume half while the interrupt is pending.
92 const stored = await page.evaluate(() =>
93 window.localStorage.getItem(
94 'tanstack-ai:persistence-durability-interrupt',
95 ),
96 )
97 expect(stored).not.toBeNull()
98 const record = JSON.parse(stored!) as { resume?: unknown }
99 expect(record.resume).toBeTruthy()
100​
101 // Full reload: the interrupt must rehydrate from localStorage, not a refetch.
102 await page.reload()
103​
104 await expect(page.getByTestId('persistence-durability-page')).toBeVisible()
105 await expect
106 .poll(() => interruptCount(page), { timeout: 15_000 })
107 .toBeGreaterThanOrEqual(1)
108 await expect(page.getByTestId('interrupt-confirm-shipment')).toBeVisible()
109 await expect(page.getByTestId('interrupt-kind')).toHaveText('generic')
110 await expect(page.getByTestId('interrupt-source')).toHaveText('hydrate')
111 })
112​
113 test('restores a pending interrupt from the SERVER on a fresh load (persistence: true)', async ({
114 page,
115 }) => {
116 // Server-authoritative: the client caches nothing. On mount it hydrates from
117 // the GET, which returns a pending approval. This is the path that was
118 // broken — a fresh client showed the paused tool call with no way to
119 // approve/reject. Clear localStorage before the asserting load so the
120 // interrupt can ONLY have come from the server.
121 await page.goto('/persistence-durability?scenario=server-interrupt')
122 await page.evaluate(() => window.localStorage.clear())
123 await page.reload()
124​
125 await expect(page.getByTestId('persistence-durability-page')).toBeVisible()
126 // localStorage is empty, so a visible interrupt proves server-side restore.
127 await expect
128 .poll(() => interruptCount(page), { timeout: 15_000 })
129 .toBeGreaterThanOrEqual(1)
130 await expect(page.getByTestId('interrupt-confirm-shipment')).toBeVisible()
131 await expect(page.getByTestId('interrupt-kind')).toHaveText('generic')
132 await expect(page.getByTestId('interrupt-source')).toHaveText('hydrate')
133 // Restored bound and resolvable — the reload can approve/reject, not just
134 // view a dead paused tool call.
135 await expect(page.getByTestId('interrupt-can-resolve')).toHaveText('true')
136​
137 // And the client wrote nothing to localStorage: `persistence: true` keeps no
138 // record at all, so the interrupt could only have come from the server.
139 const stored = await page.evaluate(() =>
140 window.localStorage.getItem(
141 'tanstack-ai:persistence-durability-server-interrupt',
142 ),
143 )
144 expect(stored).toBeNull()
145 })
146})
147​
148test.describe('structured output persistence', () => {
149 test('restores a completed structured-output part from server persistence', async ({
150 request,
151 }) => {
152 const threadId = `structured-output-${crypto.randomUUID()}`
153 const runId = crypto.randomUUID()
154 const run = await request.post(
155 '/api/persistence-durability?scenario=structured-output',
156 { data: { threadId, runId } },
157 )
158 expect(run.ok()).toBe(true)
159​
160 const hydration = await request.get(
161 `/api/persistence-durability?scenario=structured-output&threadId=${threadId}`,
162 )
163 expect(hydration.ok()).toBe(true)
164 const body = (await hydration.json()) as {
165 messages: Array<{
166 role: string
167 parts: Array<Record<string, unknown>>
168 }>
169 }
170 const assistants = body.messages.filter(
171 (message) => message.role === 'assistant',
172 )
173​
174 expect(assistants).toHaveLength(2)
175 expect(assistants[0]?.parts).toEqual([
176 {
177 type: 'text',
178 content: 'PERSIST_OK the lighthouse still turns.',
179 },
180 ])
181 expect(assistants[1]?.parts).toEqual([
182 {
183 type: 'structured-output',
184 status: 'complete',
185 data: { name: 'Ada Lovelace' },
186 partial: { name: 'Ada Lovelace' },
187 raw: '{"name":"Ada Lovelace"}',
188 },
189 ])
190 })
191​
192 test('restores event-sourced harness structured output from server persistence', async ({
193 request,
194 }) => {
195 const threadId = `harness-output-${crypto.randomUUID()}`
196 const runId = crypto.randomUUID()
197 const run = await request.post(
198 '/api/persistence-durability?scenario=harness-output',
199 { data: { threadId, runId } },
200 )
201 expect(run.ok()).toBe(true)
202​
203 const hydration = await request.get(
204 `/api/persistence-durability?scenario=harness-output&threadId=${threadId}`,
205 )
206 expect(hydration.ok()).toBe(true)
207 const body = (await hydration.json()) as {
208 messages: Array<{
209 role: string
210 parts: Array<Record<string, unknown>>
211 }>
212 }
213 const assistants = body.messages.filter(
214 (message) => message.role === 'assistant',
215 )
216​
217 expect(assistants).toHaveLength(2)
218 expect(assistants[0]?.parts).toEqual([
219 {
220 type: 'text',
221 content: 'looking around the repo',
222 },
223 ])
224 expect(assistants[1]?.parts).toEqual([
225 {
226 type: 'structured-output',
227 status: 'complete',
228 data: { name: 'Ada Lovelace' },
229 partial: { name: 'Ada Lovelace' },
230 raw: '{"name":"Ada Lovelace"}',
231 },
232 ])
233 })
234})
235​
236test.describe('server persistence', () => {
237 test('stores cumulative usage across model calls', async ({ request }) => {
238 const run = await request.post(
239 '/api/persistence-durability?scenario=usage',
240 {
241 data: {
242 threadId: `usage-${crypto.randomUUID()}`,
243 runId: crypto.randomUUID(),
244 },
245 },
246 )
247 expect(run.ok()).toBe(true)
248 const body = (await run.json()) as {
249 usage?: {
250 promptTokens: number
251 completionTokens: number
252 totalTokens: number
253 }
254 }
255 expect(body.usage).toEqual({
256 promptTokens: 19,
257 completionTokens: 6,
258 totalTokens: 25,
259 })
260 })
261​
262 test('reconstructChat with includeRuns returns run timings (issue #1061)', async ({
263 request,
264 }) => {
265 const threadId = `run-timings-${crypto.randomUUID()}`
266 const run = await request.post(
267 '/api/persistence-durability?scenario=usage',
268 { data: { threadId, runId: crypto.randomUUID() } },
269 )
270 expect(run.ok()).toBe(true)
271 const { runId } = (await run.json()) as { runId: string }
272​
273 const hydrated = await request.get(
274 `/api/persistence-durability?scenario=usage&threadId=${encodeURIComponent(threadId)}`,
275 )
276 expect(hydrated.ok()).toBe(true)
277 const body = (await hydrated.json()) as {
278 runs?: Array<{
279 runId: string
280 status: string
281 startedAt: number
282 finishedAt?: number
283 }>
284 messages: Array<{
285 role: string
286 metadata?: {
287 tanstack?: {
288 run?: { id: string; startedAt?: number; finishedAt?: number }
289 }
290 }
291 }>
292 }
293​
294 expect(body.runs).toHaveLength(1)
295 const [timing] = body.runs!
296 expect(timing).toMatchObject({ runId, status: 'completed' })
297 expect(timing!.finishedAt).toBeGreaterThanOrEqual(timing!.startedAt)
298 const assistant = body.messages.filter((m) => m.role === 'assistant')
299 expect(assistant.length).toBeGreaterThan(0)
300 for (const message of assistant) {
301 expect(message.metadata?.tanstack?.run).toEqual({
302 id: runId,
303 startedAt: timing!.startedAt,
304 finishedAt: timing!.finishedAt,
305 })
306 }
307 })
308​
309 test('restores a failed server tool call as failed', async ({ request }) => {
310 const threadId = `tool-error-${crypto.randomUUID()}`
311 const run = await request.post(
312 '/api/persistence-durability?scenario=tool-error',
313 { data: { threadId, runId: crypto.randomUUID() } },
314 )
315 expect(run.ok()).toBe(true)
316​
317 const hydration = await request.get(
318 `/api/persistence-durability?scenario=tool-error&threadId=${threadId}`,
319 )
320 expect(hydration.ok()).toBe(true)
321 const body = (await hydration.json()) as {
322 messages: Array<{ parts: Array<Record<string, unknown>> }>
323 }
324 const parts = body.messages.flatMap((message) => message.parts)
325​
326 expect(parts).toContainEqual(
327 expect.objectContaining({
328 type: 'tool-result',
329 toolCallId: 'call-status',
330 state: 'error',
331 error: 'Status service unavailable',
332 }),
333 )
334 })
335})