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

generic-middleware-interrupts.spec.ts

337 lines9.6 KB

1import type { Page } from '@playwright/test'
2import type { PhaseCapture } from '../src/lib/phase-capture'
3import { expect, test } from './fixtures'
4import { collectHydrationErrors } from './helpers'
5​
6const genericMode = 'generic-lifecycle'
7​
8function middlewareUrl(testId: string, aimockPort: number, scenario: string) {
9 const query = new URLSearchParams({
10 testId,
11 aimockPort: String(aimockPort),
12 scenario,
13 middlewareMode: genericMode,
14 })
15 return `/middleware-test?${query}`
17​
18async function startScenario(
19 page: Page,
20 testId: string,
21 aimockPort: number,
22 scenario: string,
23) {
24 await page.goto(middlewareUrl(testId, aimockPort, scenario))
25 await page.waitForSelector('#mw-run-button')
26 await page.waitForFunction(
27 () =>
28 document
29 .getElementById('mw-metadata')
30 ?.getAttribute('data-is-loading') === 'false',
31 )
32 // Let React attach delegated handlers before interaction.
33 await page.waitForTimeout(300)
34​
35 const readCount = () =>
36 page.evaluate(() =>
37 parseInt(
38 document
39 .getElementById('mw-metadata')
40 ?.getAttribute('data-message-count') || '0',
41 10,
42 ),
43 )
44​
45 for (let attempt = 0; attempt < 5; attempt++) {
46 const baseline = await readCount()
47 await page.locator('#mw-run-button').click()
48 const started = await page
49 .waitForFunction(
50 (base) => {
51 const meta = document.getElementById('mw-metadata')
52 if (meta?.getAttribute('data-is-loading') === 'true') return true
53 if (
54 parseInt(meta?.getAttribute('data-interrupt-count') || '0', 10) > 0
55 )
56 return true
57 if (
58 parseInt(meta?.getAttribute('data-message-count') || '0', 10) > base
59 )
60 return true
61 return false
62 },
63 baseline,
64 { timeout: 2000 },
65 )
66 .then(() => true)
67 .catch(() => false)
68 if (started) {
69 await expect(page.getByTestId('generic-review-plan')).toBeVisible()
70 return
71 }
72 }
73​
74 throw new Error('Run test button did not start a chat run')
76​
77async function resolveReview(page: Page) {
78 await page.getByTestId('resolve-review-plan').click()
80​
81async function resolveMixedBatch(page: Page) {
82 await resolveReview(page)
83 await page.getByTestId('approve-delete-review').click()
85​
86async function waitForFinished(page: Page) {
87 await expect(page.locator('#mw-metadata')).toHaveAttribute(
88 'data-interrupt-count',
89 '0',
90 )
91 await expect(page.locator('#mw-metadata')).toHaveAttribute(
92 'data-is-loading',
93 'false',
94 )
96​
97async function fetchCapture(page: Page, testId: string): Promise<PhaseCapture> {
98 const response = await page.request.get(
99 `/api/middleware-test?testId=${encodeURIComponent(testId)}&kind=phase`,
100 )
101 expect(response.ok()).toBe(true)
102 return response.json()
104​
105async function expectAssistantText(page: Page, text: string) {
106 await expect(page.locator('#mw-messages-json')).toContainText(text)
108​
109function expectOneInterruptTerminalForEachBoundary(capture: PhaseCapture) {
110 const interruptedRunIds = Array.from(
111 new Set(capture.boundaries.map((boundary) => boundary.runId)),
112 )
113​
114 expect(interruptedRunIds).not.toHaveLength(0)
115​
116 for (const runId of interruptedRunIds) {
117 const chunks = capture.yieldedChunks.filter(
118 (chunk) => chunk.runId === runId,
119 )
120 const startedIndexes = chunks.flatMap((chunk, index) =>
121 chunk.type === 'RUN_STARTED' ? [index] : [],
122 )
123 const terminalIndexes = chunks.flatMap((chunk, index) =>
124 chunk.type === 'RUN_FINISHED' ? [index] : [],
125 )
126​
127 expect(startedIndexes).toHaveLength(1)
128 expect(terminalIndexes).toHaveLength(1)
129 const startedIndex = startedIndexes[0]
130 const terminalIndex = terminalIndexes[0]
131 expect(startedIndex).toBeLessThan(terminalIndex)
132 expect(chunks[terminalIndex]?.outcomeType).toBe('interrupt')
133 expect(terminalIndex).toBe(chunks.length - 1)
134 expect(chunks[terminalIndex - 1]?.type).toBe('MESSAGES_SNAPSHOT')
135 }
137​
138const boundaryCases = [
139 {
140 scenario: 'generic-before-model',
141 boundary: 'beforeModel',
142 result: 'BEFORE_MODEL_RESOLVED',
143 },
144 {
145 scenario: 'generic-after-model',
146 boundary: 'afterModel',
147 result: 'AFTER_MODEL_CONTENT',
148 },
149 {
150 scenario: 'generic-before-tools-continue',
151 boundary: 'beforeTools',
152 result: 'TOOLS_CONTINUED',
153 mixed: true,
154 },
155 {
156 scenario: 'generic-after-tools',
157 boundary: 'afterTools',
158 result: 'AFTER_TOOLS_RESOLVED',
159 },
160] as const
161​
162for (const boundaryCase of boundaryCases) {
163 test(`resolves a typed generic interrupt at ${boundaryCase.boundary}`, async ({
164 page,
165 testId,
166 aimockPort,
167 }) => {
168 await startScenario(page, testId, aimockPort, boundaryCase.scenario)
169 await expect(page.getByTestId('generic-review-plan')).toHaveAttribute(
170 'data-definition-id',
171 'review-plan',
172 )
173 await expect(page.getByTestId('generic-review-plan')).toHaveAttribute(
174 'data-payload',
175 new RegExp(`"boundary":"${boundaryCase.boundary}"`),
176 )
177​
178 if (boundaryCase.mixed) await resolveMixedBatch(page)
179 else await resolveReview(page)
180 await waitForFinished(page)
181 await expectAssistantText(page, boundaryCase.result)
182​
183 const capture = await fetchCapture(page, testId)
184 expect(capture.boundaries).toEqual([
185 expect.objectContaining({ phase: boundaryCase.boundary }),
186 ])
187 expect(capture.resolutions).toEqual([
188 expect.objectContaining({
189 definitionId: 'review-plan',
190 status: 'resolved',
191 response: {
192 approved: true,
193 note: 'approved in middleware e2e',
194 },
195 }),
196 ])
197 })
199​
200test('keeps the afterModel turn thinking in the interrupt snapshot', async ({
201 page,
202 testId,
203 aimockPort,
204}) => {
205 await startScenario(page, testId, aimockPort, 'generic-after-model')
206 // The client loads the interrupt's MESSAGES_SNAPSHOT. It must still hold
207 // the thinking of the turn that the interrupt paused.
208 await expect(page.locator('#mw-messages-json')).toContainText(
209 'AFTER_MODEL_REASONING',
210 )
211})
212​
213test('cancels a typed generic interrupt and records the cancellation', async ({
214 page,
215 testId,
216 aimockPort,
217}) => {
218 await startScenario(page, testId, aimockPort, 'generic-before-model')
219 await page.getByTestId('cancel-review-plan').click()
220 await waitForFinished(page)
221​
222 const capture = await fetchCapture(page, testId)
223 expect(capture.resolutions).toEqual([
224 expect.objectContaining({
225 definitionId: 'review-plan',
226 status: 'cancelled',
227 }),
228 ])
229})
230​
231test('keeps generic, approval, and client-tool waits in one terminal batch', async ({
232 page,
233 testId,
234 aimockPort,
235}) => {
236 await startScenario(page, testId, aimockPort, 'generic-before-tools-continue')
237 await expect(page.getByTestId('generic-review-plan')).toHaveCount(1)
238 await expect(page.getByTestId('delete-review-approval')).toHaveCount(1)
239 await expect(page.locator('#mw-metadata')).toHaveAttribute(
240 'data-interrupt-count',
241 '2',
242 )
243​
244 await resolveMixedBatch(page)
245 await waitForFinished(page)
246 await expect(page.locator('#mw-metadata')).toHaveAttribute(
247 'data-client-tool-executions',
248 '1',
249 )
250​
251 const capture = await fetchCapture(page, testId)
252 const firstTerminal = capture.yieldedChunks.find(
253 (chunk) =>
254 chunk.type === 'RUN_FINISHED' && chunk.interruptCount !== undefined,
255 )
256 expect(firstTerminal?.interruptCount).toBe(3)
257 expect(capture.toolExecutions).toEqual([
258 { name: 'delete_review', side: 'server' },
259 ])
260 expect(capture.policies).toEqual(['continue'])
261})
262​
263for (const policyCase of [
264 {
265 scenario: 'generic-before-tools-cancel',
266 policy: 'cancel',
267 result: 'TOOLS_CANCELLED',
268 },
269 {
270 scenario: 'generic-before-tools-stop',
271 policy: 'stop',
272 result: undefined,
273 },
274] as const) {
275 test(`${policyCase.policy} policy prevents pending tool execution`, async ({
276 page,
277 testId,
278 aimockPort,
279 }) => {
280 await startScenario(page, testId, aimockPort, policyCase.scenario)
281 await resolveMixedBatch(page)
282 await waitForFinished(page)
283​
284 const capture = await fetchCapture(page, testId)
285 expect(capture.policies).toEqual([policyCase.policy])
286 expect(capture.toolExecutions).toEqual([])
287 await expect(page.locator('#mw-metadata')).toHaveAttribute(
288 'data-client-tool-executions',
289 '0',
290 )
291 if (policyCase.result) await expectAssistantText(page, policyCase.result)
292 else
293 await expect(page.locator('#mw-messages-json')).not.toContainText(
294 'TOOLS_',
295 )
296 })
298​
299for (const scenario of [
300 'generic-before-model',
301 'generic-after-model',
302 'generic-before-tools-continue',
303 'generic-before-tools-cancel',
304 'generic-before-tools-stop',
305 'generic-after-tools',
306] as const) {
307 test(`emits one final interrupt terminal for ${scenario}`, async ({
308 page,
309 testId,
310 aimockPort,
311 }) => {
312 await startScenario(page, testId, aimockPort, scenario)
313 const capture = await fetchCapture(page, testId)
314 expectOneInterruptTerminalForEachBoundary(capture)
315 })
317​
318test('restores a pending generic interrupt after reload and resumes it', async ({
319 page,
320 testId,
321 aimockPort,
322}) => {
323 await startScenario(page, testId, aimockPort, 'generic-before-model')
324 const hydrationErrors = collectHydrationErrors(page)
325 await page.reload()
326 await expect(page.getByTestId('generic-review-plan')).toBeVisible()
327 await resolveReview(page)
328 await waitForFinished(page)
329 await expectAssistantText(page, 'BEFORE_MODEL_RESOLVED')
330​
331 const capture = await fetchCapture(page, testId)
332 expect(capture.boundaries).toHaveLength(1)
333 expect(capture.resolutions).toEqual([
334 expect.objectContaining({ status: 'resolved' }),
335 ])
336 expect(hydrationErrors).toEqual([])
337})