Open History to see the last commit
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' },
19]
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>
26}
27
28function isRecord(value: unknown): value is Record<string, unknown> {
29 return typeof value === 'object' && value !== null
30}
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 }
60}
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 }
88}
89
90function threadId(label: string) {
91 return `hist-${label}-${Date.now()}-${Math.random().toString(16).slice(2)}`
92}
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}`
99}
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)
111}
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())
123}
124
125async function paintedIds(page: Page) {
126 const raw = await page.getByTestId('painted-ids').getAttribute('data-ids')
127 return raw === null || raw === '' ? [] : raw.split(',')
128}
129
130test.describe('message history paging', () => {
131 for (const store of ['array', 'page'] as const) {
132 test(`${store} store hydrates the newest window and Load older prepends`, async ({
133 page,
134 request,
135 }) => {
136 const id = threadId(store)
137 await seedThread(request, store, id, SEED)
138
139 const hydrate = await request.get(
140 apiPath(store, `threadId=${encodeURIComponent(id)}&limit=2`),
141 )
142 expect(hydrate.ok()).toBe(true)
143 const hydrateBody = readHydrate(await hydrate.json())
144 expect(hydrateBody.messageIds).toEqual(['u3', 'a3'])
145 expect(hydrateBody.page).toEqual({ truncated: true, cursor: 'u3' })
146
147 await page.goto(
148 `/message-history-paging?threadId=${encodeURIComponent(id)}&store=${store}&pageSize=2`,
149 )
150 await expect(page.getByTestId('hydration-marker')).toBeAttached()
151 await expect(page.getByTestId('painted-ids')).toHaveAttribute(
152 'data-ids',
153 'u3,a3',
154 )
155 await expect(page.getByTestId('has-older')).toHaveAttribute(
156 'data-has-older',
157 'true',
158 )
159
160 await page.getByTestId('load-older').click()
161 await expect(page.getByTestId('painted-ids')).toHaveAttribute(
162 'data-ids',
163 'u2,a2,u3,a3',
164 )
165
166 await page.getByTestId('load-older').click()
167 await expect(page.getByTestId('painted-ids')).toHaveAttribute(
168 'data-ids',
169 'u1,a1,u2,a2,u3,a3',
170 )
171 await expect(page.getByTestId('has-older')).toHaveAttribute(
172 'data-has-older',
173 'false',
174 )
175 await expect(page.getByTestId('load-older')).toHaveCount(0)
176 expect(await paintedIds(page)).toEqual(SEED_IDS)
177 })
178 }
179
180 test('a one-message send keeps stored extras (no paging client)', async ({
181 request,
182 }) => {
183 const id = threadId('short-send')
184 await seedThread(request, 'array', id, [
185 { id: 'u1', role: 'user', content: 'one' },
186 { id: 'a1', role: 'assistant', content: 'one-reply' },
187 ])
188
189 const response = await request.post(apiPath('array', 'run=1'), {
190 data: {
191 threadId: id,
192 messages: [{ id: 'u-new', role: 'user', content: 'next' }],
193 },
194 })
195 expect(response.ok()).toBe(true)
196 const body = readInspect(await response.json())
197
198 expect(body.lastIncomingIds).toEqual(['u-new'])
199 expect(body.stored.map((message) => message.id)).toEqual([
200 'u1',
201 'a1',
202 'u-new',
203 expect.any(String),
204 ])
205 expect(body.stored.map((message) => message.content)).toEqual([
206 'one',
207 'one-reply',
208 'next',
209 'PAGE_OK',
210 ])
211 })
212
213 test('a paged client send posts only the new turn and keeps stored extras', async ({
214 page,
215 request,
216 }) => {
217 const id = threadId('paged-send')
218 await seedThread(request, 'array', id, SEED)
219
220 await page.goto(
221 `/message-history-paging?threadId=${encodeURIComponent(id)}&pageSize=2`,
222 )
223 await expect(page.getByTestId('hydration-marker')).toBeAttached()
224 await expect(page.getByTestId('painted-ids')).toHaveAttribute(
225 'data-ids',
226 'u3,a3',
227 )
228
229 await sendMessage(page, 'next')
230 await waitForResponse(page)
231 await expect(page.getByTestId('assistant-message').last()).toContainText(
232 'PAGE_OK',
233 )
234
235 const body = await inspectThread(request, 'array', id)
236 expect(body.lastIncomingIds).toHaveLength(1)
237 expect(SEED_IDS.includes(body.lastIncomingIds[0] ?? '')).toBe(false)
238 expect(body.stored.map((message) => message.id).slice(0, 6)).toEqual(
239 SEED_IDS,
240 )
241 expect(
242 body.stored.some(
243 (message) => message.role === 'user' && message.content === 'next',
244 ),
245 ).toBe(true)
246 expect(
247 body.stored.some(
248 (message) =>
249 message.role === 'assistant' && message.content === 'PAGE_OK',
250 ),
251 ).toBe(true)
252 expect(body.stored).toHaveLength(8)
253 })
254})