Open History to see the last commit
1import { expect, type Page } from '@playwright/test'
2
3declare global {
4 interface Window {
5 __e2eLoadingSeen?: boolean
6 __e2eLoadingObserver?: MutationObserver
7 }
8}
9
10/** Call right before an action that starts a run. Records in the page whether
11 * the loading indicator showed after this call, so `waitForResponse` also
12 * sees a run that started and ended before Playwright looked. */
13async function markRunStart(page: Page) {
14 await page.evaluate(() => {
15 window.__e2eLoadingSeen = false
16 if (window.__e2eLoadingObserver) return
17 window.__e2eLoadingObserver = new MutationObserver(() => {
18 if (
19 !window.__e2eLoadingSeen &&
20 document.querySelector('[data-testid="loading-indicator"]')
21 ) {
22 window.__e2eLoadingSeen = true
23 }
24 })
25 window.__e2eLoadingObserver.observe(document.body, {
26 childList: true,
27 subtree: true,
28 })
29 })
30}
31
32const HYDRATION_ERROR = /hydration failed|hydrated but|server rendered html/i
33
34/** Collect React hydration errors from page errors and console errors. Call
35 * before the reload you want to check, then assert the list stays empty. */
36export function collectHydrationErrors(page: Page): Array<string> {
37 const errors: Array<string> = []
38 page.on('pageerror', (error) => {
39 if (HYDRATION_ERROR.test(error.message)) errors.push(error.message)
40 })
41 page.on('console', (message) => {
42 const text = message.text()
43 if (message.type() === 'error' && HYDRATION_ERROR.test(text)) {
44 errors.push(text)
45 }
46 })
47 return errors
48}
49
50export function featureUrl(
51 provider: string,
52 feature: string,
53 testId: string,
54 aimockPort: number,
55 mode?: string,
56): string {
57 let url = `/${provider}/${feature}?testId=${encodeURIComponent(testId)}&aimockPort=${aimockPort}`
58 if (mode) url += `&mode=${mode}`
59 return url
60}
61
62export async function sendMessage(page: Page, text: string) {
63 const input = page.getByTestId('chat-input')
64 const button = page.getByTestId('send-button')
65 // A fill that lands before hydration never reaches React state, so the send
66 // button stays disabled. Clear and refill until the button turns on. Do not
67 // wait on one long click timeout: that cost ~5s on the first send of almost
68 // every test in CI.
69 await expect(async () => {
70 await input.fill('')
71 await input.fill(text)
72 await expect(button).toBeEnabled({ timeout: 500 })
73 }).toPass({ timeout: 15_000 })
74 await markRunStart(page)
75 await button.click()
76}
77
78/** Types a prompt and attaches an image; attaching auto-sends. Retries until
79 * the user bubble renders — the inline comment below explains why. */
80export async function sendMessageWithImage(
81 page: Page,
82 text: string,
83 imagePath: string,
84) {
85 const input = page.getByTestId('chat-input')
86 const fileInput = page.getByTestId('image-attachment-input')
87 const userMessages = page.getByTestId('user-message')
88
89 // Attaching the image auto-sends, using the prompt currently in the chat
90 // input, and the matched aimock fixture keys on the exact user text. A
91 // *controlled* React input is fragile here under CPU load (CI, parallel
92 // workers) in two ways: typing char-by-char can drop characters, leaving a
93 // truncated value like "cribe this image" (which 404s as "No fixture
94 // matched" → empty `chatStream fatal`); and the attach's onChange can land
95 // before the typed value is committed, dispatching nothing at all. So drive
96 // the interaction to its observable outcome — the user bubble rendering —
97 // retrying both the typing and the attach until the send actually fires with
98 // the full prompt. A redundant re-attach is harmless: the client ignores a
99 // second send while the first is still streaming.
100 await markRunStart(page)
101 await expect(async () => {
102 await input.click()
103 await input.fill('')
104 await input.pressSequentially(text, { delay: 15 })
105 // Confirm the full prompt is committed before attaching.
106 expect(await input.inputValue()).toBe(text)
107 // Reset the selection so re-attaching the same path re-fires onChange.
108 await fileInput.setInputFiles([])
109 await fileInput.setInputFiles(imagePath)
110 await expect(userMessages.first()).toBeVisible({ timeout: 2_000 })
111 }).toPass({ timeout: 15_000, intervals: [250, 500, 1000] })
112}
113
114/** Types a prompt and attaches a PDF; attaching auto-sends. Retries until the
115 * user bubble renders (same fragile-controlled-input problem as
116 * sendMessageWithImage — see the comment there). */
117export async function sendMessageWithDocument(
118 page: Page,
119 text: string,
120 documentPath: string,
121) {
122 const input = page.getByTestId('chat-input')
123 const fileInput = page.getByTestId('document-attachment-input')
124 const userMessages = page.getByTestId('user-message')
125
126 // Same retry-to-observable-outcome pattern as sendMessageWithImage above.
127 await markRunStart(page)
128 await expect(async () => {
129 await input.click()
130 await input.fill('')
131 await input.pressSequentially(text, { delay: 15 })
132 expect(await input.inputValue()).toBe(text)
133 await fileInput.setInputFiles([])
134 await fileInput.setInputFiles(documentPath)
135 await expect(userMessages.first()).toBeVisible({ timeout: 2_000 })
136 }).toPass({ timeout: 15_000, intervals: [250, 500, 1000] })
137}
138
139export async function waitForResponse(page: Page, timeout = 15_000) {
140 // Wait for the run to start. A fast mocked run can start and end before
141 // Playwright looks, so also accept the markRunStart record. Without that
142 // record (for example after a reload), this waits up to 5s as before.
143 await page
144 .waitForFunction(
145 () =>
146 window.__e2eLoadingSeen === true ||
147 document.querySelector('[data-testid="loading-indicator"]') !== null,
148 undefined,
149 { timeout: 5_000 },
150 )
151 .catch(() => {
152 // Loading may have already finished
153 })
154 await page
155 .getByTestId('loading-indicator')
156 .waitFor({ state: 'hidden', timeout })
157}
158
159export async function getLastAssistantMessage(page: Page): Promise<string> {
160 const messages = page.getByTestId('assistant-message')
161 const count = await messages.count()
162 if (count === 0) return ''
163 return messages.nth(count - 1).innerText()
164}
165
166/** Wait for an assistant message containing specific text (useful for tool-calling where
167 * the agentic loop produces multiple responses and waitForResponse returns too early) */
168export async function waitForAssistantText(
169 page: Page,
170 text: string,
171 timeout = 15_000,
172) {
173 await page
174 .getByTestId('assistant-message')
175 .filter({ hasText: text })
176 .first()
177 .waitFor({ state: 'visible', timeout })
178}
179
180export async function getToolCalls(
181 page: Page,
182): Promise<Array<{ name: string }>> {
183 const toolCalls: Array<{ name: string }> = []
184 const elements = page.locator('[data-testid^="tool-call-"]').filter({
185 hasNot: page.locator('[data-testid^="tool-call-result-"]'),
186 })
187 const count = await elements.count()
188 for (let i = 0; i < count; i++) {
189 const testId = await elements.nth(i).getAttribute('data-testid')
190 if (testId && testId.startsWith('tool-call-')) {
191 toolCalls.push({ name: testId.replace('tool-call-', '') })
192 }
193 }
194 return toolCalls
195}
196
197export async function getStructuredOutput(page: Page): Promise<string> {
198 return page.getByTestId('structured-output').innerText()
199}
200
201export async function approveToolCall(page: Page, toolName: string) {
202 await markRunStart(page)
203 await page.getByTestId(`approve-button-${toolName}`).click()
204}
205
206export async function denyToolCall(page: Page, toolName: string) {
207 await markRunStart(page)
208 await page.getByTestId(`deny-button-${toolName}`).click()
209}
210
211export async function isNotSupported(page: Page): Promise<boolean> {
212 return page
213 .getByTestId('not-supported')
214 .isVisible({ timeout: 2_000 })
215 .catch(() => false)
216}
217
218export async function submitSummarization(page: Page, text: string) {
219 const input = page.getByTestId('summarize-input')
220 await input.click()
221 await input.pressSequentially(text, { delay: 10 })
222 await page.getByTestId('summarize-button').click()
223}
224
225export async function getSummarizationResult(page: Page): Promise<string> {
226 await page
227 .getByTestId('summarize-result')
228 .waitFor({ state: 'visible', timeout: 15_000 })
229 return page.getByTestId('summarize-result').innerText()
230}
231
232export async function getAudioPlayer(page: Page) {
233 return page.getByTestId('audio-player')
234}
235
236export async function getTranscriptionResult(page: Page): Promise<string> {
237 await page
238 .getByTestId('transcription-result')
239 .waitFor({ state: 'visible', timeout: 15_000 })
240 return page.getByTestId('transcription-result').innerText()
241}
242
243async function fillControlledGenerateInput(
244 page: Page,
245 testId: 'prompt-input' | 'text-input',
246 text: string,
247) {
248 // Hydrate first. Waiting for networkidle after fill used to remount the
249 // controlled input empty, so generate-button stayed disabled for 30s.
250 await page.waitForLoadState('networkidle')
251 const input = page.getByTestId(testId)
252 const btn = page.getByTestId('generate-button')
253 await expect(async () => {
254 await input.click()
255 await input.fill(text)
256 await input.dispatchEvent('input', { bubbles: true })
257 if (await btn.isDisabled()) {
258 await input.clear()
259 await input.pressSequentially(text, { delay: 20 })
260 }
261 await expect(btn).toBeEnabled({ timeout: 2_000 })
262 }).toPass({ timeout: 15_000, intervals: [250, 500, 1000] })
263}
264
265export async function fillPrompt(page: Page, text: string) {
266 await fillControlledGenerateInput(page, 'prompt-input', text)
267}
268
269export async function fillTextInput(page: Page, text: string) {
270 await fillControlledGenerateInput(page, 'text-input', text)
271}
272
273export async function clickGenerate(page: Page, testId = 'generate-button') {
274 const btn = page.getByTestId(testId)
275 await expect(btn).toBeEnabled()
276 await btn.click()
277 // Verify the click actually triggered React — status should leave 'idle'
278 // If still idle after a short wait, the click missed hydration; retry
279 try {
280 await expect(page.getByTestId('generation-status')).not.toHaveText('idle', {
281 timeout: 3_000,
282 })
283 } catch {
284 await btn.click()
285 }
286}
287
288export async function waitForGenerationComplete(page: Page, timeout = 30_000) {
289 await expect(page.getByTestId('generation-status')).toHaveText('complete', {
290 timeout,
291 })
292}