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

helpers.ts

221 lines7.0 KB

1import type { Page } from '@playwright/test'
2​
3/**
4 * Helpers for the /interrupts-test playground. Selectors mirror /tools-test:
5 *
6 * #scenario-select — scenario dropdown
7 * #run-test-button — starts a run
8 * #approval-section — tool-approval interrupts container
9 * #generic-section — generic interrupts container
10 * .approve-button / .deny-button / .cancel-button — per-item controls
11 * #resolve-all-approve / #resolve-all-deny / #cancel-all / #resolve-all-mixed
12 * .resolve-generic-button / .cancel-generic-button
13 * #test-metadata — hidden div with data-* attributes
14 * #event-log-json — <script> with the event array
15 * #messages-json-content — <pre> with full messages JSON
16 */
17​
18export async function selectScenario(
19 page: Page,
20 scenario: string,
21 testId?: string,
22 aimockPort?: number,
23): Promise<void> {
24 const params = new URLSearchParams()
25 if (testId) params.set('testId', testId)
26 if (aimockPort) params.set('aimockPort', String(aimockPort))
27 params.set('scenario', scenario)
28 await page.goto(`/interrupts-test?${params.toString()}`)
29 await page.waitForSelector('#run-test-button')
30 await page.waitForFunction(
31 (expected) =>
32 document
33 .getElementById('test-metadata')
34 ?.getAttribute('data-scenario') === expected,
35 scenario,
36 { timeout: 10000 },
37 )
38 // Let React attach delegated handlers before interaction.
39 await page.waitForTimeout(300)
41​
42export async function runTest(page: Page): Promise<void> {
43 const readCount = () =>
44 page.evaluate(() => {
45 const text =
46 document.getElementById('messages-json-content')?.textContent || '[]'
47 try {
48 const parsed = JSON.parse(text)
49 return Array.isArray(parsed) ? parsed.length : 0
50 } catch {
51 return 0
52 }
53 })
54​
55 for (let attempt = 0; attempt < 5; attempt++) {
56 const baseline = await readCount()
57 await page.click('#run-test-button')
58 const started = await page
59 .waitForFunction(
60 (base) => {
61 const meta = document.getElementById('test-metadata')
62 if (meta?.getAttribute('data-is-loading') === 'true') return true
63 if (
64 parseInt(meta?.getAttribute('data-tool-call-count') || '0', 10) > 0
65 )
66 return true
67 if (
68 parseInt(meta?.getAttribute('data-interrupt-count') || '0', 10) > 0
69 )
70 return true
71 if (meta?.getAttribute('data-test-complete') === 'true') return true
72 const text =
73 document.getElementById('messages-json-content')?.textContent ||
74 '[]'
75 try {
76 const parsed = JSON.parse(text)
77 return Array.isArray(parsed) && parsed.length > base + 1
78 } catch {
79 return false
80 }
81 },
82 baseline,
83 { timeout: 2000 },
84 )
85 .then(() => true)
86 .catch(() => false)
87 if (started) return
88 }
89 throw new Error('Run test button did not start a chat run')
91​
92export async function waitForApproval(page: Page, timeout = 10000) {
93 await page.waitForSelector('#approval-section', { timeout })
95​
96/** Wait until exactly `n` tool-approval interrupts are pending. */
97export async function waitForPendingApprovals(
98 page: Page,
99 n: number,
100 timeout = 10000,
101) {
102 await page.waitForFunction(
103 (expected) =>
104 document
105 .getElementById('test-metadata')
106 ?.getAttribute('data-pending-approval-count') === String(expected),
107 n,
108 { timeout },
109 )
111​
112export async function waitForGeneric(page: Page, timeout = 10000) {
113 await page.waitForSelector('#generic-section', { timeout })
115​
116export async function waitForTestComplete(page: Page, timeout = 15000) {
117 await page.waitForFunction(
118 () => {
119 const meta = document.getElementById('test-metadata')
120 return (
121 meta?.getAttribute('data-test-complete') === 'true' ||
122 (meta?.getAttribute('data-is-loading') === 'false' &&
123 meta?.getAttribute('data-interrupt-count') === '0')
124 )
125 },
126 undefined,
127 { timeout },
128 )
129 await page.waitForTimeout(200)
131​
132/** Read every data-* attribute off #test-metadata as a flat string map. */
133export async function getMetadata(page: Page): Promise<Record<string, string>> {
134 return page.evaluate(() => {
135 const el = document.getElementById('test-metadata')
136 const out: Record<string, string> = {}
137 if (!el) return out
138 for (const attr of Array.from(el.attributes)) {
139 if (attr.name.startsWith('data-')) {
140 // data-approval-granted-count → approvalGrantedCount
141 const key = attr.name
142 .slice(5)
143 .replace(/-([a-z])/g, (_, c: string) => c.toUpperCase())
144 out[key] = attr.value
145 }
146 }
147 return out
148 })
150​
151export async function getEventLog(
152 page: Page,
153): Promise<Array<{ type: string; toolName: string; details?: string }>> {
154 return page.evaluate(() => {
155 const el = document.getElementById('event-log-json')
156 if (!el) return []
157 try {
158 return JSON.parse(el.textContent || '[]')
159 } catch {
160 return []
161 }
162 })
164​
165export async function getToolCalls(
166 page: Page,
167): Promise<
168 Array<{ id: string; name: string; state: string; output?: unknown }>
169> {
170 return page.evaluate(() => {
171 const el = document.getElementById('tool-calls-json')
172 if (!el) return []
173 try {
174 return JSON.parse(el.textContent || '[]')
175 } catch {
176 return []
177 }
178 })
180​
181/** Collect the ids of every rendered per-item button of a given class. */
182async function itemButtonIds(page: Page, cls: string): Promise<Array<string>> {
183 return page.evaluate((selector) => {
184 return Array.from(document.querySelectorAll(selector))
185 .map((el) => el.id)
186 .filter(Boolean)
187 }, `.${cls}`)
189​
190/** Click every currently-rendered per-item button of a class, in sequence. */
191async function clickAllItems(page: Page, cls: string): Promise<number> {
192 const ids = await itemButtonIds(page, cls)
193 let clicked = 0
194 for (const id of ids) {
195 // Use an attribute selector so ids with hyphens (`approve-fc-…`) need no
196 // escaping. The list re-renders as items resolve; guard each click.
197 const locator = page.locator(`[id="${id}"]`)
198 if (await locator.count()) {
199 await locator.click()
200 clicked++
201 await page.waitForTimeout(50)
202 }
203 }
204 return clicked
206​
207export const approveEachItem = (page: Page) =>
208 clickAllItems(page, 'approve-button')
209export const denyEachItem = (page: Page) => clickAllItems(page, 'deny-button')
210export const cancelEachItem = (page: Page) =>
211 clickAllItems(page, 'cancel-button')
212​
213export const approveAll = (page: Page) => page.click('#resolve-all-approve')
214export const denyAll = (page: Page) => page.click('#resolve-all-deny')
215export const cancelAll = (page: Page) => page.click('#cancel-all')
216export const resolveAllMixed = (page: Page) => page.click('#resolve-all-mixed')
217​
218export const resolveGeneric = (page: Page) =>
219 page.click('.resolve-generic-button')
220export const cancelGeneric = (page: Page) =>
221 page.click('.cancel-generic-button')