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