Open History to see the last commit
1import { test, expect } from './fixtures'
2
3/**
4 * E2E coverage for the structured-output × middleware interaction
5 * introduced in TanStack/ai#390. Two contracts under test:
6 *
7 * 1. Phase observation: the middleware chain sees chunks tagged with
8 * `ctx.phase === 'structuredOutput'` and `onFinish` is invoked exactly
9 * once. Guards against the pre-fix regression where the structured
10 * finalization adapter call bypassed the middleware chain entirely.
11 *
12 * 2. Streaming lifecycle: the consumer sees exactly one RUN_STARTED and
13 * one RUN_FINISHED chunk pair. Guards against the pre-fix regression
14 * where the streaming structured-output path emitted a synthetic
15 * terminal pair on top of the engine's, producing duplicate run
16 * lifecycle events to the consumer.
17 *
18 * Both tests drive the existing `/middleware-test` harness route with the
19 * new `phase-recorder` middleware mode, which records `ctx.phase` per chunk
20 * + `onFinish` count + post-middleware yielded chunks into a per-testId
21 * server-side store. The page fetches that store in `onFinish` and surfaces
22 * it via DOM elements (`#mw-phases-json`, `#mw-onfinish-count`,
23 * `#mw-yielded-chunks-json`) which the spec reads.
24 *
25 * NOTE on naming: both scenarios below run with `stream: true` against the
26 * harness route — the harness currently hard-codes streaming for both
27 * `structured-output` and `structured-output-stream` modes. The first test
28 * exercises the structured-output phase coverage via the SSE harness; the
29 * true non-streaming `Promise<T>` path is covered by unit tests in
30 * `packages/ai/tests/structured-output-middleware.test.ts`.
31 * Adding a real non-streaming E2E scenario would require page-side rewiring
32 * to await `Promise<T>` instead of iterating SSE and is out of scope here.
33 */
34
35function buildHarnessUrl(
36 testId?: string,
37 aimockPort?: number,
38 provider?: string,
39 model?: string,
40): string {
41 const params = new URLSearchParams()
42 if (testId) params.set('testId', testId)
43 if (aimockPort) params.set('aimockPort', String(aimockPort))
44 if (provider) params.set('provider', provider)
45 if (model) params.set('model', model)
46 const qs = params.toString()
47 return `/middleware-test${qs ? '?' + qs : ''}`
48}
49
50function parseStringArray(raw: string | null): Array<string> {
51 if (!raw) return []
52 let parsed: unknown
53 try {
54 parsed = JSON.parse(raw)
55 } catch {
56 return []
57 }
58 return Array.isArray(parsed) && parsed.every((p) => typeof p === 'string')
59 ? parsed
60 : []
61}
62
63function parseChunkSummaries(raw: string | null): Array<{ type: string }> {
64 if (!raw) return []
65 let parsed: unknown
66 try {
67 parsed = JSON.parse(raw)
68 } catch {
69 return []
70 }
71 if (!Array.isArray(parsed)) return []
72 const result: Array<{ type: string }> = []
73 for (const entry of parsed) {
74 if (!entry || typeof entry !== 'object') continue
75 const inner: Record<string, unknown> = { ...entry }
76 const t = inner.type
77 if (typeof t === 'string') result.push({ type: t })
78 }
79 return result
80}
81
82test.describe('Structured Output × Middleware Coverage', () => {
83 test('legacy finalization path: middleware observes structuredOutput phase chunks (claude-3-7-sonnet)', async ({
84 page,
85 testId,
86 aimockPort,
87 }) => {
88 // Pinned to claude-3-7-sonnet because Claude 4.5+ adapters take the
89 // #605 native-combined-mode path (no separate finalization → no
90 // `structuredOutput` phase). The 3.7-sonnet adapter still uses the
91 // forced-tool finalization workaround, which is what this contract
92 // covers: any non-native-combined adapter must keep firing the
93 // `structuredOutput` phase so middleware can observe it.
94 await page.goto(
95 buildHarnessUrl(testId, aimockPort, 'anthropic', 'claude-3-7-sonnet'),
96 )
97 await page.waitForTimeout(2000)
98
99 await page.locator('#mw-scenario-select').selectOption('structured-output')
100 await page.locator('#mw-mode-select').selectOption('phase-recorder')
101 await page.locator('#mw-run-button').click()
102
103 await page.waitForFunction(
104 () =>
105 document
106 .querySelector('#mw-metadata')
107 ?.getAttribute('data-test-complete') === 'true',
108 { timeout: 15000 },
109 )
110
111 const phasesJson = await page.locator('#mw-phases-json').textContent()
112 const phases = parseStringArray(phasesJson)
113 expect(phases).toContain('structuredOutput')
114
115 const finishCountRaw = await page
116 .locator('#mw-onfinish-count')
117 .textContent()
118 const finishCount = Number(finishCountRaw ?? '0')
119 expect(finishCount).toBe(1)
120 })
121
122 test('native combined mode (#605): structuredOutput phase does NOT fire — single combined call observed via beforeModel only (openai)', async ({
123 page,
124 testId,
125 aimockPort,
126 }) => {
127 // Default openai adapter (gpt-4o) declares supportsCombinedToolsAndSchema,
128 // so the engine forwards outputSchema into the regular chatStream call
129 // and harvests the JSON from accumulated content — no second adapter
130 // request, no `structuredOutput` phase. This pins the new contract
131 // introduced in #605.
132 await page.goto(buildHarnessUrl(testId, aimockPort, 'openai'))
133 await page.waitForTimeout(2000)
134
135 await page.locator('#mw-scenario-select').selectOption('structured-output')
136 await page.locator('#mw-mode-select').selectOption('phase-recorder')
137 await page.locator('#mw-run-button').click()
138
139 await page.waitForFunction(
140 () =>
141 document
142 .querySelector('#mw-metadata')
143 ?.getAttribute('data-test-complete') === 'true',
144 { timeout: 15000 },
145 )
146
147 const phasesJson = await page.locator('#mw-phases-json').textContent()
148 const phases = parseStringArray(phasesJson)
149 // Combined-mode contract: middleware sees the run through the regular
150 // chat phases, not `structuredOutput`. The phase-recorder records
151 // `ctx.phase` per `onChunk`, and the engine tags streaming chunks
152 // with `'modelStream'` (the `'beforeModel'` phase tag is set only for
153 // the `onConfig` hook boundary, not for chunks).
154 expect(phases).not.toContain('structuredOutput')
155 expect(phases).toContain('modelStream')
156
157 const finishCountRaw = await page
158 .locator('#mw-onfinish-count')
159 .textContent()
160 const finishCount = Number(finishCountRaw ?? '0')
161 expect(finishCount).toBe(1)
162 })
163
164 test('streaming structured output: consumer sees exactly one RUN_STARTED/RUN_FINISHED pair', async ({
165 page,
166 testId,
167 aimockPort,
168 }) => {
169 await page.goto(buildHarnessUrl(testId, aimockPort))
170 await page.waitForTimeout(2000)
171
172 await page
173 .locator('#mw-scenario-select')
174 .selectOption('structured-output-stream')
175 await page.locator('#mw-mode-select').selectOption('phase-recorder')
176 await page.locator('#mw-run-button').click()
177
178 await page.waitForFunction(
179 () =>
180 document
181 .querySelector('#mw-metadata')
182 ?.getAttribute('data-test-complete') === 'true',
183 { timeout: 15000 },
184 )
185
186 const yieldedJson = await page
187 .locator('#mw-yielded-chunks-json')
188 .textContent()
189 const yielded = parseChunkSummaries(yieldedJson)
190 expect(yielded.filter((c) => c.type === 'RUN_STARTED')).toHaveLength(1)
191 expect(yielded.filter((c) => c.type === 'RUN_FINISHED')).toHaveLength(1)
192 })
193})