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

structured-output-stream.spec.ts

216 lines7.7 KB

1import { test, expect } from './fixtures'
2import {
3 sendMessage,
4 waitForResponse,
5 getLastAssistantMessage,
6 featureUrl,
7} from './helpers'
8import { providersFor } from './test-matrix'
9​
10test('OpenAI Responses structured output reports EOF without response.completed', async ({
11 request,
12}) => {
13 const response = await request.post(
14 '/api/openai-completed-response-text?scenario=structured-missing-terminal',
15 )
16​
17 expect(response.ok()).toBe(true)
18 const result = await response.json()
19 expect(result.text).toBe('{"answer":"partial"}')
20 expect(result.events).toContain('TEXT_MESSAGE_CONTENT')
21 expect(result.events.at(-1)).toBe('RUN_ERROR')
22 expect(result.errorCode).toBe('incomplete-stream')
23 expect(result.completed).toBe(false)
24 expect(result.events).not.toContain('RUN_FINISHED')
25})
26​
27for (const provider of providersFor('structured-output-stream')) {
28 test.describe(`${provider} — structured-output-stream`, () => {
29 test('streams structured JSON deltas in a single request', async ({
30 page,
31 testId,
32 aimockPort,
33 }) => {
34 await page.goto(
35 featureUrl(provider, 'structured-output-stream', testId, aimockPort),
36 )
37​
38 await sendMessage(page, '[structured-stream] recommend a guitar as json')
39 await waitForResponse(page)
40​
41 const response = await getLastAssistantMessage(page)
42 expect(response).toContain('Fender Stratocaster')
43 expect(response).toContain('1299')
44​
45 // Routing assertion: per `docs/structured-outputs/streaming.md`, when
46 // `outputSchema` is set, `TEXT_MESSAGE_CONTENT` deltas accumulate into
47 // a `structured-output` part — NOT into a `text` part with raw JSON
48 // bytes. The harness `ChatUI` renders both part types with distinct
49 // testids, so the assistant message must have exactly one
50 // `structured-output-part` and zero `text-part`s.
51 const assistantMessage = page.getByTestId('assistant-message').last()
52 await expect(
53 assistantMessage.getByTestId('structured-output-part'),
54 ).toHaveCount(1)
55 await expect(assistantMessage.getByTestId('text-part')).toHaveCount(0)
56​
57 // Verify the terminal `structured-output.complete` CUSTOM event
58 // reached the client and carries the parsed object — protects against
59 // a regression where the event is dropped but the JSON text still
60 // happens to render.
61 const completeEl = page.getByTestId('structured-output-complete')
62 await expect(completeEl).toBeAttached()
63 const structuredAttr = await completeEl.getAttribute(
64 'data-structured-output',
65 )
66 expect(structuredAttr).toBeTruthy()
67 const parsed = JSON.parse(structuredAttr!)
68 expect(parsed.name).toContain('Fender Stratocaster')
69 expect(parsed.price).toBe(1299)
70​
71 // `condition` is `.optional()`, so strict-mode widening made the provider
72 // return `null` for it (see the fixture). The engine must un-widen that
73 // synthesized null before the streamed `structured-output.complete` event
74 // reaches the consumer, so the field reads back as ABSENT — not `null`.
75 // Pre-fix, null-preserving adapters (e.g. openrouter) leaked the `null`
76 // straight through on the streaming path.
77 expect('condition' in parsed).toBe(false)
78​
79 // Verify the response actually streamed (more than one content delta).
80 // A regression that silently fell back to the synthetic single-delta
81 // path would still pass the substring assertion above but fail here.
82 const countAttr = await page
83 .getByTestId('content-delta-count')
84 .getAttribute('data-count')
85 expect(Number(countAttr)).toBeGreaterThan(1)
86 })
87​
88 test('reasoning before the JSON does not add a text part', async ({
89 page,
90 testId,
91 aimockPort,
92 }) => {
93 test.skip(
94 provider !== 'openai',
95 'Pins the Responses path that streams reasoning under its own message id (#1632)',
96 )
97 await page.goto(
98 featureUrl(provider, 'structured-output-stream', testId, aimockPort),
99 )
100​
101 await sendMessage(
102 page,
103 '[structured-stream-reasoning] recommend a guitar as json',
104 )
105 await waitForResponse(page)
106​
107 const assistantMessage = page.getByTestId('assistant-message').last()
108 await expect(assistantMessage.getByTestId('thinking-block')).toHaveCount(
109 1,
110 )
111 await expect(
112 assistantMessage.getByTestId('structured-output-part'),
113 ).toHaveCount(1)
114 await expect(assistantMessage.getByTestId('text-part')).toHaveCount(0)
115 })
116​
117 test('aborting mid-stream stops the run cleanly', async ({
118 page,
119 testId,
120 aimockPort,
121 }) => {
122 await page.goto(
123 featureUrl(provider, 'structured-output-stream', testId, aimockPort),
124 )
125​
126 // Uses the slow-streaming fixture (tokensPerSecond + small chunkSize)
127 // so the stop button is reliably visible mid-stream.
128 await sendMessage(
129 page,
130 '[structured-stream-abort] recommend a guitar slowly',
131 )
132​
133 await expect(page.getByTestId('loading-indicator')).toBeVisible({
134 timeout: 10_000,
135 })
136​
137 const stopButton = page.getByTestId('stop-button')
138 await expect(stopButton).toBeVisible({ timeout: 5_000 })
139 await stopButton.click()
140​
141 await expect(page.getByTestId('loading-indicator')).not.toBeVisible({
142 timeout: 10_000,
143 })
144​
145 // The structured-output.complete event must not have reached the
146 // client — aborting before the JSON finished streaming should leave
147 // the run terminated, not "completed with empty result".
148 await expect(page.getByTestId('structured-output-complete')).toHaveCount(
149 0,
150 )
151 })
152​
153 test('invalid JSON does not emit structured-output.complete', async ({
154 page,
155 testId,
156 aimockPort,
157 }) => {
158 test.skip(
159 provider !== 'gemini',
160 'Pins the Gemini native parse-error path added with structuredOutputStream',
161 )
162 await page.goto(
163 featureUrl(provider, 'structured-output-stream', testId, aimockPort),
164 )
165​
166 await sendMessage(
167 page,
168 '[structured-stream-invalid] recommend a guitar as json',
169 )
170​
171 await expect(page.getByTestId('loading-indicator')).not.toBeVisible({
172 timeout: 15_000,
173 })
174 await expect(page.getByTestId('structured-output-complete')).toHaveCount(
175 0,
176 )
177 })
178 })
180​
181for (const malformed of [false, true]) {
182 for (const reasoning of ['positive', 'zero', 'missing']) {
183 test(`OpenRouter structured usage: malformed=${malformed}, reasoning=${reasoning}`, async ({
184 request,
185 }) => {
186 const response = await request.post(
187 `/api/openrouter-structured-usage?malformed=${malformed}&reasoning=${reasoning}`,
188 )
189 expect(response.ok()).toBe(true)
190 const { result, events, usageReports, requests } = await response.json()
191 expect(requests).toBe(1)
192 const terminal = events.at(-1)
193 expect(terminal.type).toBe(malformed ? 'RUN_ERROR' : 'RUN_FINISHED')
194 expect(
195 events.filter((event: { usage?: unknown }) => event.usage),
196 ).toHaveLength(1)
197 expect(terminal.usage).toMatchObject({
198 promptTokens: 10,
199 completionTokens: 50,
200 totalTokens: 60,
201 cost: 0.002,
202 })
203 expect(terminal.usage.completionTokensDetails?.reasoningTokens).toBe(
204 reasoning === 'missing' ? undefined : reasoning === 'zero' ? 0 : 42,
205 )
206 expect(usageReports).toHaveLength(malformed ? 0 : 1)
207 if (malformed) {
208 expect(terminal.code).toBe('parse-error')
209 expect(result.error).toContain('Failed to parse structured output')
210 } else {
211 expect(result.value).toEqual({ answer: 'ok' })
212 expect(usageReports[0]).toEqual(terminal.usage)
213 }
214 })
215 }