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

helpers.ts

352 lines11.0 KB

1import type { Page } from '@playwright/test'
2import type { UIMessage } from '@tanstack/ai-client'
3​
4/**
5 * Shared helpers for tools-test spec files.
6 *
7 * These helpers interact with the /tools-test page and the selectors it
8 * exposes:
9 *
10 * #scenario-select — dropdown for choosing a test scenario
11 * #run-test-button — button that starts the test
12 * #approval-section — container shown when approvals are pending
13 * .approve-button — class selector for approve buttons
14 * .deny-button — class selector for deny buttons
15 * #approve-{id} — specific approve button for a tool call
16 * #deny-{id} — specific deny button for a tool call
17 * #test-metadata — hidden div with data-* attributes used for assertions
18 * #event-log-json — <script type="application/json"> with event array
19 * #tool-calls-json — <script type="application/json"> with tool-call array
20 * #messages-json-content — <pre> with full messages JSON
21 */
22​
23/**
24 * Navigate to /tools-test and select a scenario reliably (handles React
25 * hydration delays).
26 */
27export async function selectScenario(
28 page: Page,
29 scenario: string,
30 testId?: string,
31 aimockPort?: number,
32): Promise<void> {
33 const params = new URLSearchParams()
34 if (testId) params.set('testId', testId)
35 if (aimockPort) params.set('aimockPort', String(aimockPort))
36 params.set('scenario', scenario)
37 const qs = params.toString()
38 await page.goto(`/tools-test${qs ? '?' + qs : ''}`)
39 await page.waitForSelector('#run-test-button')
40​
41 // Give React time to attach delegated event handlers before clicking.
42 await page.waitForTimeout(500)
43​
44 const isScenarioSelected = async (timeout: number) =>
45 page
46 .waitForFunction(
47 (expected) => {
48 const metadata = document.getElementById('test-metadata')
49 return metadata?.getAttribute('data-scenario') === expected
50 },
51 scenario,
52 { timeout },
53 )
54 .then(() => true)
55 .catch(() => false)
56​
57 if (await isScenarioSelected(5000)) {
58 return
59 }
60​
61 // Try selecting multiple times
62 for (let attempt = 0; attempt < 3; attempt++) {
63 await page.focus('#scenario-select')
64 await page.selectOption('#scenario-select', scenario)
65 await page.waitForTimeout(200)
66​
67 const currentScenario = await page.evaluate(() =>
68 document.getElementById('test-metadata')?.getAttribute('data-scenario'),
69 )
70 if (currentScenario === scenario) break
71 }
72​
73 // Verify scenario is selected
74 await page.waitForFunction(
75 (expected) => {
76 const metadata = document.getElementById('test-metadata')
77 return metadata?.getAttribute('data-scenario') === expected
78 },
79 scenario,
80 { timeout: 10000 },
81 )
82​
83 // Wait for new client to initialize
84 await page.waitForTimeout(300)
86​
87/**
88 * Click #run-test-button and wait for loading to start.
89 *
90 * Uses the pre-click message count as a baseline so that a fixture which is
91 * already populated (non-empty messages JSON) does not register as a started
92 * run on its own. A run is considered started when either:
93 * 1. data-is-loading === "true", OR
94 * 2. the parsed message count has grown beyond the pre-click baseline.
95 */
96export async function runTest(page: Page): Promise<void> {
97 const readMessageCount = () =>
98 page.evaluate(() => {
99 const text =
100 document.getElementById('messages-json-content')?.textContent || '[]'
101 try {
102 const parsed = JSON.parse(text)
103 return Array.isArray(parsed) ? parsed.length : 0
104 } catch {
105 return 0
106 }
107 })
108​
109 for (let attempt = 0; attempt < 5; attempt++) {
110 const baselineMessageCount = await readMessageCount()
111 await page.click('#run-test-button')
112​
113 // A run "starts" only when real stream activity appears — not when the
114 // optimistic user message lands. Clicking adds one user message
115 // synchronously (baseline + 1); that alone must NOT count as started, or a
116 // stalled run (the click registered but the stream produced nothing) would
117 // be reported as started and the test would later time out waiting for an
118 // approval / completion that never comes. Real activity is: loading turned
119 // on, a tool call appeared, the test completed, or a *second* message (the
120 // assistant response) was added beyond the optimistic user message. Poll
121 // briefly so a slow-but-real run under CI load isn't mistaken for a stall.
122 const started = await page
123 .waitForFunction(
124 (baseline) => {
125 const metadata = document.getElementById('test-metadata')
126 if (metadata?.getAttribute('data-is-loading') === 'true') return true
127 if (
128 parseInt(
129 metadata?.getAttribute('data-tool-call-count') || '0',
130 10,
131 ) > 0
132 )
133 return true
134 if (metadata?.getAttribute('data-test-complete') === 'true')
135 return true
136 const text =
137 document.getElementById('messages-json-content')?.textContent ||
138 '[]'
139 try {
140 const parsed = JSON.parse(text)
141 // > baseline + 1: the assistant message arrived (a real response),
142 // not just the optimistic user message.
143 return Array.isArray(parsed) && parsed.length > baseline + 1
144 } catch {
145 return false
146 }
147 },
148 baselineMessageCount,
149 { timeout: 2000 },
150 )
151 .then(() => true)
152 .catch(() => false)
153​
154 if (started) {
155 return
156 }
157 }
158​
159 throw new Error('Run test button did not start a chat run')
161​
162/**
163 * Wait for the test to complete.
164 *
165 * Considers the test complete when either:
166 * 1. data-test-complete === "true", OR
167 * 2. data-is-loading === "false" AND data-complete-tool-count >= expectedToolCount
168 */
169export async function waitForTestComplete(
170 page: Page,
171 timeout = 15000,
172 expectedToolCount = 1,
173): Promise<void> {
174 await page.waitForFunction(
175 ({ minTools }) => {
176 const metadata = document.getElementById('test-metadata')
177 const testComplete =
178 metadata?.getAttribute('data-test-complete') === 'true'
179 const isLoading = metadata?.getAttribute('data-is-loading') === 'true'
180 const completeToolCount = parseInt(
181 metadata?.getAttribute('data-complete-tool-count') || '0',
182 10,
183 )
184​
185 // Consider complete if:
186 // 1. testComplete flag is true, OR
187 // 2. Not loading and we have at least the expected number of complete tools
188 return testComplete || (!isLoading && completeToolCount >= minTools)
189 },
190 { minTools: expectedToolCount },
191 { timeout },
192 )
193​
194 // Give a little extra time for final state updates
195 await page.waitForTimeout(200)
197​
198/**
199 * Wait for client-side execution events to be reflected in the event log.
200 *
201 * Tool call completion can be visible in message state before React has flushed
202 * the separate event-log state update used by these assertions.
203 */
204export async function waitForExecutionComplete(
205 page: Page,
206 toolName: string,
207 timeout = 10000,
208): Promise<void> {
209 await page.waitForFunction(
210 (expectedToolName) => {
211 const el = document.getElementById('event-log-json')
212 if (!el) return false
213​
214 try {
215 const events = JSON.parse(el.textContent || '[]') as Array<{
216 type?: string
217 toolName?: string
218 }>
219 return events.some(
220 (event) =>
221 event.type === 'execution-complete' &&
222 event.toolName === expectedToolName,
223 )
224 } catch {
225 return false
226 }
227 },
228 toolName,
229 { timeout },
230 )
232​
233/**
234 * Wait for the #approval-section element to become visible.
235 */
236export async function waitForApproval(
237 page: Page,
238 timeout = 10000,
239): Promise<void> {
240 await page.waitForSelector('#approval-section', { timeout })
242​
243/**
244 * Read all data-* attributes from #test-metadata.
245 */
246export async function getMetadata(page: Page): Promise<Record<string, string>> {
247 return page.evaluate((): Record<string, string> => {
248 const el = document.getElementById('test-metadata')
249 if (!el) return {}
250 return {
251 scenario: el.getAttribute('data-scenario') || '',
252 isLoading: el.getAttribute('data-is-loading') || '',
253 testComplete: el.getAttribute('data-test-complete') || '',
254 toolCallCount: el.getAttribute('data-tool-call-count') || '',
255 pendingApprovalCount:
256 el.getAttribute('data-pending-approval-count') || '',
257 completeToolCount: el.getAttribute('data-complete-tool-count') || '',
258 eventCount: el.getAttribute('data-event-count') || '',
259 executionStartCount: el.getAttribute('data-execution-start-count') || '',
260 executionCompleteCount:
261 el.getAttribute('data-execution-complete-count') || '',
262 approvalGrantedCount:
263 el.getAttribute('data-approval-granted-count') || '',
264 approvalDeniedCount: el.getAttribute('data-approval-denied-count') || '',
265 hasError: el.getAttribute('data-has-error') || '',
266 errorMessage: el.getAttribute('data-error-message') || '',
267 errorRawEvent: el.getAttribute('data-error-raw-event') || '',
268 }
269 })
271​
272/**
273 * Parse the JSON event log from #event-log-json.
274 */
275export async function getEventLog(
276 page: Page,
277): Promise<Array<{ type: string; toolName: string; timestamp: number }>> {
278 return page.evaluate(() => {
279 const el = document.getElementById('event-log-json')
280 if (!el) return []
281 try {
282 return JSON.parse(el.textContent || '[]')
283 } catch {
284 return []
285 }
286 })
288​
289/**
290 * Parse the JSON tool-calls list from #tool-calls-json.
291 */
292export async function getToolCalls(
293 page: Page,
294): Promise<Array<{ id: string; name: string; state: string }>> {
295 return page.evaluate(() => {
296 const el = document.getElementById('tool-calls-json')
297 if (!el) return []
298 try {
299 return JSON.parse(el.textContent || '[]')
300 } catch {
301 return []
302 }
303 })
305​
306/**
307 * Parse the full UIMessage array from #messages-json-content.
308 */
309export async function getMessages(page: Page): Promise<Array<UIMessage>> {
310 return page.evaluate(() => {
311 const el = document.getElementById('messages-json-content')
312 if (!el) return []
313 try {
314 return JSON.parse(el.textContent || '[]')
315 } catch {
316 return []
317 }
318 })
320​
321/**
322 * Extract tool-call parts with parsed arguments from #messages-json-content.
323 */
324export async function getToolCallParts(
325 page: Page,
326): Promise<Array<{ name: string; arguments: Record<string, unknown> }>> {
327 return page.evaluate(() => {
328 const el = document.getElementById('messages-json-content')
329 if (!el) return []
330 try {
331 const messages = JSON.parse(el.textContent || '[]')
332 const parts: Array<{ name: string; arguments: Record<string, unknown> }> =
333 []
334 for (const msg of messages) {
335 for (const part of msg.parts || []) {
336 if (part.type === 'tool-call') {
337 parts.push({
338 name: part.name,
339 arguments:
340 typeof part.arguments === 'string'
341 ? JSON.parse(part.arguments)
342 : part.arguments,
343 })
344 }
345 }
346 }
347 return parts
348 } catch {
349 return []
350 }
351 })