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

helpers.ts

310 lines10.8 KB

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