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

helpers.ts

237 lines8.3 KB

1import { expect, type Page } from '@playwright/test'
2​
3export function featureUrl(
4 provider: string,
5 feature: string,
6 testId: string,
7 aimockPort: number,
8 mode?: string,
9): string {
10 let url = `/${provider}/${feature}?testId=${encodeURIComponent(testId)}&aimockPort=${aimockPort}`
11 if (mode) url += `&mode=${mode}`
12 return url
14​
15export async function sendMessage(page: Page, text: string) {
16 const input = page.getByTestId('chat-input')
17 await input.click()
18 await input.fill(text)
19 // Dispatch an input event to trigger React's onChange for controlled inputs
20 await input.dispatchEvent('input', { bubbles: true })
21 await page
22 .getByTestId('send-button')
23 .click({ timeout: 5000 })
24 .catch(async (err) => {
25 // Only retry if button was disabled (fill() didn't trigger React onChange)
26 const isDisabled = await page.getByTestId('send-button').isDisabled()
27 if (!isDisabled) throw err
28 await input.clear()
29 await input.pressSequentially(text, { delay: 30 })
30 await page.getByTestId('send-button').click()
31 })
33​
34/** Types a prompt and attaches an image; attaching auto-sends. Retries until
35 * the user bubble renders — the inline comment below explains why. */
36export async function sendMessageWithImage(
37 page: Page,
38 text: string,
39 imagePath: string,
40) {
41 const input = page.getByTestId('chat-input')
42 const fileInput = page.getByTestId('image-attachment-input')
43 const userMessages = page.getByTestId('user-message')
44​
45 // Attaching the image auto-sends, using the prompt currently in the chat
46 // input, and the matched aimock fixture keys on the exact user text. A
47 // *controlled* React input is fragile here under CPU load (CI, parallel
48 // workers) in two ways: typing char-by-char can drop characters, leaving a
49 // truncated value like "cribe this image" (which 404s as "No fixture
50 // matched" → empty `chatStream fatal`); and the attach's onChange can land
51 // before the typed value is committed, dispatching nothing at all. So drive
52 // the interaction to its observable outcome — the user bubble rendering —
53 // retrying both the typing and the attach until the send actually fires with
54 // the full prompt. A redundant re-attach is harmless: the client ignores a
55 // second send while the first is still streaming.
56 await expect(async () => {
57 await input.click()
58 await input.fill('')
59 await input.pressSequentially(text, { delay: 15 })
60 // Confirm the full prompt is committed before attaching.
61 expect(await input.inputValue()).toBe(text)
62 // Reset the selection so re-attaching the same path re-fires onChange.
63 await fileInput.setInputFiles([])
64 await fileInput.setInputFiles(imagePath)
65 await expect(userMessages.first()).toBeVisible({ timeout: 2_000 })
66 }).toPass({ timeout: 15_000, intervals: [250, 500, 1000] })
68​
69/** Types a prompt and attaches a PDF; attaching auto-sends. Retries until the
70 * user bubble renders (same fragile-controlled-input problem as
71 * sendMessageWithImage — see the comment there). */
72export async function sendMessageWithDocument(
73 page: Page,
74 text: string,
75 documentPath: string,
76) {
77 const input = page.getByTestId('chat-input')
78 const fileInput = page.getByTestId('document-attachment-input')
79 const userMessages = page.getByTestId('user-message')
80​
81 // Same retry-to-observable-outcome pattern as sendMessageWithImage above.
82 await expect(async () => {
83 await input.click()
84 await input.fill('')
85 await input.pressSequentially(text, { delay: 15 })
86 expect(await input.inputValue()).toBe(text)
87 await fileInput.setInputFiles([])
88 await fileInput.setInputFiles(documentPath)
89 await expect(userMessages.first()).toBeVisible({ timeout: 2_000 })
90 }).toPass({ timeout: 15_000, intervals: [250, 500, 1000] })
92​
93export async function waitForResponse(page: Page, timeout = 15_000) {
94 try {
95 await page
96 .getByTestId('loading-indicator')
97 .waitFor({ state: 'visible', timeout: 5_000 })
98 } catch {
99 // Loading may have already finished
100 }
101 await page
102 .getByTestId('loading-indicator')
103 .waitFor({ state: 'hidden', timeout })
105​
106export async function getLastAssistantMessage(page: Page): Promise<string> {
107 const messages = page.getByTestId('assistant-message')
108 const count = await messages.count()
109 if (count === 0) return ''
110 return messages.nth(count - 1).innerText()
112​
113/** Wait for an assistant message containing specific text (useful for tool-calling where
114 * the agentic loop produces multiple responses and waitForResponse returns too early) */
115export async function waitForAssistantText(
116 page: Page,
117 text: string,
118 timeout = 15_000,
119) {
120 await page
121 .getByTestId('assistant-message')
122 .filter({ hasText: text })
123 .first()
124 .waitFor({ state: 'visible', timeout })
126​
127export async function getToolCalls(
128 page: Page,
129): Promise<Array<{ name: string }>> {
130 const toolCalls: Array<{ name: string }> = []
131 const elements = page.locator('[data-testid^="tool-call-"]').filter({
132 hasNot: page.locator('[data-testid^="tool-call-result-"]'),
133 })
134 const count = await elements.count()
135 for (let i = 0; i < count; i++) {
136 const testId = await elements.nth(i).getAttribute('data-testid')
137 if (testId && testId.startsWith('tool-call-')) {
138 toolCalls.push({ name: testId.replace('tool-call-', '') })
139 }
140 }
141 return toolCalls
143​
144export async function getStructuredOutput(page: Page): Promise<string> {
145 return page.getByTestId('structured-output').innerText()
147​
148export async function approveToolCall(page: Page, toolName: string) {
149 await page.getByTestId(`approve-button-${toolName}`).click()
151​
152export async function denyToolCall(page: Page, toolName: string) {
153 await page.getByTestId(`deny-button-${toolName}`).click()
155​
156export async function isNotSupported(page: Page): Promise<boolean> {
157 return page
158 .getByTestId('not-supported')
159 .isVisible({ timeout: 2_000 })
160 .catch(() => false)
162​
163export async function submitSummarization(page: Page, text: string) {
164 const input = page.getByTestId('summarize-input')
165 await input.click()
166 await input.pressSequentially(text, { delay: 10 })
167 await page.getByTestId('summarize-button').click()
169​
170export async function getSummarizationResult(page: Page): Promise<string> {
171 await page
172 .getByTestId('summarize-result')
173 .waitFor({ state: 'visible', timeout: 15_000 })
174 return page.getByTestId('summarize-result').innerText()
176​
177export async function getAudioPlayer(page: Page) {
178 return page.getByTestId('audio-player')
180​
181export async function getTranscriptionResult(page: Page): Promise<string> {
182 await page
183 .getByTestId('transcription-result')
184 .waitFor({ state: 'visible', timeout: 15_000 })
185 return page.getByTestId('transcription-result').innerText()
187​
188async function fillControlledGenerateInput(
189 page: Page,
190 testId: 'prompt-input' | 'text-input',
191 text: string,
192) {
193 // Hydrate first. Waiting for networkidle after fill used to remount the
194 // controlled input empty, so generate-button stayed disabled for 30s.
195 await page.waitForLoadState('networkidle')
196 const input = page.getByTestId(testId)
197 const btn = page.getByTestId('generate-button')
198 await expect(async () => {
199 await input.click()
200 await input.fill(text)
201 await input.dispatchEvent('input', { bubbles: true })
202 if (await btn.isDisabled()) {
203 await input.clear()
204 await input.pressSequentially(text, { delay: 20 })
205 }
206 await expect(btn).toBeEnabled({ timeout: 2_000 })
207 }).toPass({ timeout: 15_000, intervals: [250, 500, 1000] })
209​
210export async function fillPrompt(page: Page, text: string) {
211 await fillControlledGenerateInput(page, 'prompt-input', text)
213​
214export async function fillTextInput(page: Page, text: string) {
215 await fillControlledGenerateInput(page, 'text-input', text)
217​
218export async function clickGenerate(page: Page, testId = 'generate-button') {
219 const btn = page.getByTestId(testId)
220 await expect(btn).toBeEnabled()
221 await btn.click()
222 // Verify the click actually triggered React — status should leave 'idle'
223 // If still idle after a short wait, the click missed hydration; retry
224 try {
225 await expect(page.getByTestId('generation-status')).not.toHaveText('idle', {
226 timeout: 3_000,
227 })
228 } catch {
229 await btn.click()
230 }
232​
233export async function waitForGenerationComplete(page: Page, timeout = 30_000) {
234 await expect(page.getByTestId('generation-status')).toHaveText('complete', {
235 timeout,
236 })