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

message-history-paging.spec.ts

297 lines8.8 KB

1import { expect, test } from '@playwright/test'
2import { sendMessage, waitForResponse } from './helpers'
3import type { APIRequestContext, Page } from '@playwright/test'
4​
5/**
6 * Server-authoritative history paging (`persistence: true` + `history.pageSize`).
7 *
8 * Provider-free: `/api/message-history-paging` streams a fixed reply. Exempt
9 * from aimock.
10 */
11​
12const SEED = [
13 { id: 'u1', role: 'user' as const, content: 'one' },
14 { id: 'a1', role: 'assistant' as const, content: 'one-reply' },
15 { id: 'u2', role: 'user' as const, content: 'two' },
16 { id: 'a2', role: 'assistant' as const, content: 'two-reply' },
17 { id: 'u3', role: 'user' as const, content: 'three' },
18 { id: 'a3', role: 'assistant' as const, content: 'three-reply' },
20​
21const SEED_IDS = ['u1', 'a1', 'u2', 'a2', 'u3', 'a3']
22​
23interface InspectBody {
24 stored: Array<{ id?: string; role: string; content: string }>
25 lastIncomingIds: Array<string>
27​
28function isRecord(value: unknown): value is Record<string, unknown> {
29 return typeof value === 'object' && value !== null
31​
32function readHydrate(value: unknown): {
33 messageIds: Array<string>
34 page?: { truncated: boolean; cursor?: string }
35} {
36 if (!isRecord(value) || !Array.isArray(value.messages)) {
37 throw new Error('hydrate body is missing messages')
38 }
39 const messageIds: Array<string> = []
40 for (const entry of value.messages) {
41 if (!isRecord(entry) || typeof entry.id !== 'string') {
42 throw new Error('hydrate message id is missing')
43 }
44 messageIds.push(entry.id)
45 }
46 if (!isRecord(value.page)) {
47 return { messageIds }
48 }
49 if (typeof value.page.truncated !== 'boolean') {
50 throw new Error('hydrate page.truncated is missing')
51 }
52 return {
53 messageIds,
54 page: {
55 truncated: value.page.truncated,
56 cursor:
57 typeof value.page.cursor === 'string' ? value.page.cursor : undefined,
58 },
59 }
61​
62function readInspect(value: unknown): InspectBody {
63 if (!isRecord(value) || !Array.isArray(value.stored)) {
64 throw new Error('inspect body is missing stored')
65 }
66 if (!Array.isArray(value.lastIncomingIds)) {
67 throw new Error('inspect body is missing lastIncomingIds')
68 }
69 const stored: InspectBody['stored'] = []
70 for (const entry of value.stored) {
71 if (!isRecord(entry) || typeof entry.role !== 'string') {
72 throw new Error('inspect stored row is invalid')
73 }
74 stored.push({
75 id: typeof entry.id === 'string' ? entry.id : undefined,
76 role: entry.role,
77 content: typeof entry.content === 'string' ? entry.content : '',
78 })
79 }
80 const lastIncomingIds: Array<string> = []
81 for (const id of value.lastIncomingIds) {
82 if (typeof id !== 'string') {
83 throw new Error('inspect lastIncomingIds must be strings')
84 }
85 lastIncomingIds.push(id)
86 }
87 return { stored, lastIncomingIds }
89​
90function threadId(label: string) {
91 return `hist-${label}-${Date.now()}-${Math.random().toString(16).slice(2)}`
93​
94function apiPath(store: 'array' | 'page', extra = '') {
95 const params = extra === '' ? '' : `&${extra}`
96 return store === 'page'
97 ? `/api/message-history-paging?store=page${params}`
98 : `/api/message-history-paging?${extra}`
100​
101async function seedThread(
102 request: APIRequestContext,
103 store: 'array' | 'page',
104 id: string,
105 messages: typeof SEED,
106) {
107 const response = await request.post(apiPath(store, 'seed=1'), {
108 data: { threadId: id, messages },
109 })
110 expect(response.ok()).toBe(true)
112​
113async function inspectThread(
114 request: APIRequestContext,
115 store: 'array' | 'page',
116 id: string,
117) {
118 const response = await request.get(
119 apiPath(store, `inspect=1&threadId=${encodeURIComponent(id)}`),
120 )
121 expect(response.ok()).toBe(true)
122 return readInspect(await response.json())
124​
125async function paintedIds(page: Page) {
126 const raw = await page.getByTestId('painted-ids').getAttribute('data-ids')
127 return raw === null || raw === '' ? [] : raw.split(',')
129​
130test.describe('message history paging', () => {
131 test('isHydrating stays true until the server transcript is painted', async ({
132 page,
133 request,
134 }) => {
135 const id = threadId('is-hydrating')
136 await seedThread(request, 'array', id, SEED)
137​
138 // Hold the browser's hydrate GET so the loading state is observable.
139 let release!: () => void
140 const gate = new Promise<void>((resolve) => {
141 release = resolve
142 })
143 await page.route(
144 (url) =>
145 url.pathname === '/api/message-history-paging' &&
146 url.searchParams.get('threadId') === id,
147 async (route) => {
148 if (route.request().method() === 'GET') await gate
149 await route.continue()
150 },
151 )
152​
153 await page.goto(
154 `/message-history-paging?threadId=${encodeURIComponent(id)}&store=array&pageSize=2`,
155 )
156 await expect(page.getByTestId('hydration-marker')).toBeAttached()
157 await expect(page.getByTestId('is-hydrating')).toHaveAttribute(
158 'data-is-hydrating',
159 'true',
160 )
161 expect(await paintedIds(page)).toEqual([])
162​
163 release()
164 await expect(page.getByTestId('painted-ids')).toHaveAttribute(
165 'data-ids',
166 'u3,a3',
167 )
168 await expect(page.getByTestId('is-hydrating')).toHaveAttribute(
169 'data-is-hydrating',
170 'false',
171 )
172 })
173​
174 for (const store of ['array', 'page'] as const) {
175 test(`${store} store hydrates the newest window and Load older prepends`, async ({
176 page,
177 request,
178 }) => {
179 const id = threadId(store)
180 await seedThread(request, store, id, SEED)
181​
182 const hydrate = await request.get(
183 apiPath(store, `threadId=${encodeURIComponent(id)}&limit=2`),
184 )
185 expect(hydrate.ok()).toBe(true)
186 const hydrateBody = readHydrate(await hydrate.json())
187 expect(hydrateBody.messageIds).toEqual(['u3', 'a3'])
188 expect(hydrateBody.page).toEqual({ truncated: true, cursor: 'u3' })
189​
190 await page.goto(
191 `/message-history-paging?threadId=${encodeURIComponent(id)}&store=${store}&pageSize=2`,
192 )
193 await expect(page.getByTestId('hydration-marker')).toBeAttached()
194 await expect(page.getByTestId('painted-ids')).toHaveAttribute(
195 'data-ids',
196 'u3,a3',
197 )
198 await expect(page.getByTestId('has-older')).toHaveAttribute(
199 'data-has-older',
200 'true',
201 )
202​
203 await page.getByTestId('load-older').click()
204 await expect(page.getByTestId('painted-ids')).toHaveAttribute(
205 'data-ids',
206 'u2,a2,u3,a3',
207 )
208​
209 await page.getByTestId('load-older').click()
210 await expect(page.getByTestId('painted-ids')).toHaveAttribute(
211 'data-ids',
212 'u1,a1,u2,a2,u3,a3',
213 )
214 await expect(page.getByTestId('has-older')).toHaveAttribute(
215 'data-has-older',
216 'false',
217 )
218 await expect(page.getByTestId('load-older')).toHaveCount(0)
219 expect(await paintedIds(page)).toEqual(SEED_IDS)
220 })
221 }
222​
223 test('a one-message send keeps stored extras (no paging client)', async ({
224 request,
225 }) => {
226 const id = threadId('short-send')
227 await seedThread(request, 'array', id, [
228 { id: 'u1', role: 'user', content: 'one' },
229 { id: 'a1', role: 'assistant', content: 'one-reply' },
230 ])
231​
232 const response = await request.post(apiPath('array', 'run=1'), {
233 data: {
234 threadId: id,
235 messages: [{ id: 'u-new', role: 'user', content: 'next' }],
236 },
237 })
238 expect(response.ok()).toBe(true)
239 const body = readInspect(await response.json())
240​
241 expect(body.lastIncomingIds).toEqual(['u-new'])
242 expect(body.stored.map((message) => message.id)).toEqual([
243 'u1',
244 'a1',
245 'u-new',
246 expect.any(String),
247 ])
248 expect(body.stored.map((message) => message.content)).toEqual([
249 'one',
250 'one-reply',
251 'next',
252 'PAGE_OK',
253 ])
254 })
255​
256 test('a paged client send posts only the new turn and keeps stored extras', async ({
257 page,
258 request,
259 }) => {
260 const id = threadId('paged-send')
261 await seedThread(request, 'array', id, SEED)
262​
263 await page.goto(
264 `/message-history-paging?threadId=${encodeURIComponent(id)}&pageSize=2`,
265 )
266 await expect(page.getByTestId('hydration-marker')).toBeAttached()
267 await expect(page.getByTestId('painted-ids')).toHaveAttribute(
268 'data-ids',
269 'u3,a3',
270 )
271​
272 await sendMessage(page, 'next')
273 await waitForResponse(page)
274 await expect(page.getByTestId('assistant-message').last()).toContainText(
275 'PAGE_OK',
276 )
277​
278 const body = await inspectThread(request, 'array', id)
279 expect(body.lastIncomingIds).toHaveLength(1)
280 expect(SEED_IDS.includes(body.lastIncomingIds[0] ?? '')).toBe(false)
281 expect(body.stored.map((message) => message.id).slice(0, 6)).toEqual(
282 SEED_IDS,
283 )
284 expect(
285 body.stored.some(
286 (message) => message.role === 'user' && message.content === 'next',
287 ),
288 ).toBe(true)
289 expect(
290 body.stored.some(
291 (message) =>
292 message.role === 'assistant' && message.content === 'PAGE_OK',
293 ),
294 ).toBe(true)
295 expect(body.stored).toHaveLength(8)
296 })
297})