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

middleware.spec.ts

813 lines29.0 KB

1import { SpanKind } from '@opentelemetry/api'
2import { test, expect } from './fixtures'
3​
4async function fetchOtelCapture(
5 page: import('@playwright/test').Page,
6 baseURL: string | undefined,
7 testId: string | undefined,
8) {
9 if (!testId) throw new Error('otel capture test requires a testId fixture')
10 const url = `${baseURL ?? ''}/api/middleware-test?testId=${encodeURIComponent(testId)}`
11 const response = await page.request.get(url)
12 if (!response.ok()) {
13 throw new Error(
14 `GET ${url} failed: ${response.status()} ${await response.text()}`,
15 )
16 }
17 return response.json()
19​
20async function fetchPhaseCapture(
21 page: import('@playwright/test').Page,
22 baseURL: string | undefined,
23 testId: string | undefined,
24) {
25 if (!testId) throw new Error('phase capture test requires a testId fixture')
26 const url = `${baseURL ?? ''}/api/middleware-test?testId=${encodeURIComponent(testId)}&kind=phase`
27 const response = await page.request.get(url)
28 if (!response.ok()) {
29 throw new Error(
30 `GET ${url} failed: ${response.status()} ${await response.text()}`,
31 )
32 }
33 return response.json()
35​
36test.describe('Middleware Lifecycle', () => {
37 test('adapter RUN_ERROR calls onError once', async ({
38 page,
39 testId,
40 baseURL,
41 }) => {
42 const params = new URLSearchParams()
43 if (testId) params.set('testId', testId)
44 const qs = params.toString()
45 await page.goto(`/middleware-test${qs ? '?' + qs : ''}`)
46 await page.waitForTimeout(2000) // hydration
47 await page.locator('#mw-scenario-select').selectOption('run-error')
48 await page.locator('#mw-mode-select').selectOption('phase-recorder')
49 await page.locator('#mw-run-button').click()
50​
51 await expect
52 .poll(async () => {
53 const capture = await fetchPhaseCapture(page, baseURL, testId)
54 return capture.onErrorCount
55 })
56 .toBe(1)
57​
58 const capture = await fetchPhaseCapture(page, baseURL, testId)
59 expect(capture.onFinishCount).toBe(0)
60 expect(capture.yieldedChunks).toContainEqual(
61 expect.objectContaining({ type: 'RUN_ERROR' }),
62 )
63 expect(capture.yieldedChunks).not.toContainEqual(
64 expect.objectContaining({
65 type: 'RUN_FINISHED',
66 outcomeType: 'interrupt',
67 }),
68 )
69 })
70​
71 test('onChunk transforms text content', async ({
72 page,
73 testId,
74 aimockPort,
75 }) => {
76 const params = new URLSearchParams()
77 if (testId) params.set('testId', testId)
78 if (aimockPort) params.set('aimockPort', String(aimockPort))
79 const qs = params.toString()
80 await page.goto(`/middleware-test${qs ? '?' + qs : ''}`)
81 await page.waitForTimeout(2000) // hydration
82 await page.locator('#mw-scenario-select').selectOption('basic-text')
83 await page.locator('#mw-mode-select').selectOption('chunk-transform')
84 await page.locator('#mw-run-button').click()
85​
86 await page.waitForFunction(
87 () =>
88 document
89 .querySelector('#mw-metadata')
90 ?.getAttribute('data-test-complete') === 'true',
91 { timeout: 10000 },
92 )
93​
94 const messagesJson = await page.locator('#mw-messages-json').textContent()
95 const messages = JSON.parse(messagesJson || '[]')
96 const assistantMsg = messages.find((m: any) => m.role === 'assistant')
97 const textPart = assistantMsg?.parts?.find((p: any) => p.type === 'text')
98 expect(textPart?.content).toContain('[MW]')
99 })
100​
101 test('onBeforeToolCall skips tool execution', async ({
102 page,
103 testId,
104 aimockPort,
105 }) => {
106 const params = new URLSearchParams()
107 if (testId) params.set('testId', testId)
108 if (aimockPort) params.set('aimockPort', String(aimockPort))
109 const qs = params.toString()
110 await page.goto(`/middleware-test${qs ? '?' + qs : ''}`)
111 await page.waitForTimeout(2000)
112 await page.locator('#mw-scenario-select').selectOption('with-tool')
113 await page.locator('#mw-mode-select').selectOption('tool-skip')
114 await page.locator('#mw-run-button').click()
115​
116 await page.waitForFunction(
117 () =>
118 document
119 .querySelector('#mw-metadata')
120 ?.getAttribute('data-test-complete') === 'true',
121 { timeout: 10000 },
122 )
123​
124 const messagesJson = await page.locator('#mw-messages-json').textContent()
125 const messages = JSON.parse(messagesJson || '[]')
126​
127 // Find tool result parts
128 const toolResults = messages.flatMap((m: any) =>
129 m.parts.filter((p: any) => p.type === 'tool-result'),
130 )
131 expect(toolResults.length).toBeGreaterThan(0)
132 expect(toolResults[0].content).toContain('skipped')
133 })
134​
135 test('onBeforeToolCall args that fail the inputSchema become a tool error', async ({
136 page,
137 testId,
138 aimockPort,
139 }) => {
140 const params = new URLSearchParams()
141 if (testId) params.set('testId', testId)
142 if (aimockPort) params.set('aimockPort', String(aimockPort))
143 const qs = params.toString()
144 await page.goto(`/middleware-test${qs ? '?' + qs : ''}`)
145 await page.waitForTimeout(2000)
146 await page.locator('#mw-scenario-select').selectOption('with-tool')
147 await page.locator('#mw-mode-select').selectOption('tool-bad-args')
148 await page.locator('#mw-run-button').click()
149​
150 await page.waitForFunction(
151 () =>
152 document
153 .querySelector('#mw-metadata')
154 ?.getAttribute('data-test-complete') === 'true',
155 { timeout: 10000 },
156 )
157​
158 const messagesJson = await page.locator('#mw-messages-json').textContent()
159 const messages = JSON.parse(messagesJson || '[]')
160 const toolResults = messages.flatMap((m: any) =>
161 m.parts.filter((p: any) => p.type === 'tool-result'),
162 )
163 // The middleware rewrote { city: 'NYC' } to { city: { name: 'NYC' } }. The schema
164 // checks the rewritten args, so get_weather never runs.
165 expect(toolResults).toHaveLength(1)
166 expect(toolResults[0].content).toContain('Input validation failed')
167 expect(toolResults[0].content).not.toContain('temperature')
168 })
169​
170 test('the next model call replays the exact tool argument bytes', async ({
171 page,
172 request,
173 testId,
174 aimockPort,
175 }) => {
176 const params = new URLSearchParams()
177 if (testId) params.set('testId', testId)
178 if (aimockPort) params.set('aimockPort', String(aimockPort))
179 const qs = params.toString()
180 await page.goto(`/middleware-test${qs ? '?' + qs : ''}`)
181 await page.waitForTimeout(2000)
182 await page.locator('#mw-scenario-select').selectOption('raw-tool-args')
183 await page.locator('#mw-run-button').click()
184​
185 await page.waitForFunction(
186 () =>
187 document
188 .querySelector('#mw-metadata')
189 ?.getAttribute('data-test-complete') === 'true',
190 { timeout: 10000 },
191 )
192​
193 // The fixture sends spaces and `1.50`. A re-serialized value would be
194 // `{"city":"NYC","days":1.5}`.
195 const raw = '{"city": "NYC", "days": 1.50}'
196 const journal = await request.get(
197 `http://127.0.0.1:${aimockPort}/v1/_requests`,
198 )
199 const entries: Array<{
200 headers?: Record<string, string>
201 body: {
202 messages?: Array<{
203 role: string
204 tool_calls?: Array<{ function: { arguments: string } }>
205 }>
206 } | null
207 }> = await journal.json()
208 const calls = entries.filter(
209 (entry) => entry.headers?.['x-test-id'] === testId,
210 )
211 expect(calls).toHaveLength(2)
212 const replayed = calls[1]?.body?.messages
213 ?.flatMap((message) => message.tool_calls ?? [])
214 .map((call) => call.function.arguments)
215 expect(replayed).toEqual([raw])
216​
217 // The client keeps the same string.
218 const messages = JSON.parse(
219 (await page.locator('#mw-messages-json').textContent()) || '[]',
220 )
221 const toolCall = messages
222 .flatMap((m: any) => m.parts)
223 .find((p: any) => p.type === 'tool-call')
224 expect(toolCall?.arguments).toBe(raw)
225 })
226​
227 test('onAfterToolCall replaceResult changes what the client and the model see', async ({
228 page,
229 request,
230 testId,
231 aimockPort,
232 }) => {
233 const params = new URLSearchParams()
234 if (testId) params.set('testId', testId)
235 if (aimockPort) params.set('aimockPort', String(aimockPort))
236 const qs = params.toString()
237 await page.goto(`/middleware-test${qs ? '?' + qs : ''}`)
238 await page.waitForTimeout(2000)
239 await page.locator('#mw-scenario-select').selectOption('with-tool')
240 await page.locator('#mw-mode-select').selectOption('tool-replace')
241 await page.locator('#mw-run-button').click()
242​
243 await page.waitForFunction(
244 () =>
245 document
246 .querySelector('#mw-metadata')
247 ?.getAttribute('data-test-complete') === 'true',
248 { timeout: 10000 },
249 )
250​
251 // get_weather returns {"city":"NYC","temperature":72,...}. The
252 // tool-replace middleware swaps it for this value after the call.
253 const replaced = '{"replaced":true,"reason":"middleware"}'
254​
255 // The client gets the replaced result in TOOL_CALL_RESULT.
256 const messagesJson = await page.locator('#mw-messages-json').textContent()
257 const messages = JSON.parse(messagesJson || '[]')
258 const toolResults = messages.flatMap((m: any) =>
259 m.parts.filter((p: any) => p.type === 'tool-result'),
260 )
261 expect(toolResults).toHaveLength(1)
262 expect(toolResults[0].content).toBe(replaced)
263​
264 // The model gets the replaced result on the next call. aimock journals
265 // the Responses `function_call_output` as a `role: 'tool'` message.
266 const journal = await request.get(
267 `http://127.0.0.1:${aimockPort}/v1/_requests`,
268 )
269 const entries: Array<{
270 headers?: Record<string, string>
271 body: { messages?: Array<{ role: string; content: unknown }> } | null
272 }> = await journal.json()
273 const calls = entries.filter(
274 (entry) => entry.headers?.['x-test-id'] === testId,
275 )
276 expect(calls).toHaveLength(2)
277 const toolMessage = calls[1]?.body?.messages?.find(
278 (message) => message.role === 'tool',
279 )
280 expect(toolMessage?.content).toBe(replaced)
281 })
282​
283 test('capability provide/consume flow surfaces the consumed value in the stream', async ({
284 page,
285 testId,
286 aimockPort,
287 }) => {
288 const params = new URLSearchParams()
289 if (testId) params.set('testId', testId)
290 if (aimockPort) params.set('aimockPort', String(aimockPort))
291 const qs = params.toString()
292 await page.goto(`/middleware-test${qs ? '?' + qs : ''}`)
293 await page.waitForTimeout(2000) // hydration
294 await page.locator('#mw-scenario-select').selectOption('capability')
295 await page.locator('#mw-mode-select').selectOption('capability')
296 await page.locator('#mw-run-button').click()
297​
298 await page.waitForFunction(
299 () =>
300 document
301 .querySelector('#mw-metadata')
302 ?.getAttribute('data-test-complete') === 'true',
303 { timeout: 10000 },
304 )
305​
306 const messagesJson = await page.locator('#mw-messages-json').textContent()
307 const messages = JSON.parse(messagesJson || '[]')
308 const assistantMsg = messages.find((m: any) => m.role === 'assistant')
309 const textPart = assistantMsg?.parts?.find((p: any) => p.type === 'text')
310 // The provider middleware provides "[CAP]" in setup(); the consumer
311 // middleware reads it via the capability getter in onChunk and prefixes
312 // each text delta. Seeing "[CAP]" in the streamed text proves the provided
313 // capability value flowed across middleware to the consumer.
314 expect(textPart?.content).toContain('[CAP]')
315 expect(textPart?.content).toContain('Hello')
316 })
317​
318 test('otel middleware emits chat span + per-iteration token histograms', async ({
319 page,
320 testId,
321 aimockPort,
322 baseURL,
323 }) => {
324 const params = new URLSearchParams()
325 if (testId) params.set('testId', testId)
326 if (aimockPort) params.set('aimockPort', String(aimockPort))
327 const qs = params.toString()
328 await page.goto(`/middleware-test${qs ? '?' + qs : ''}`)
329 await page.waitForTimeout(2000)
330 await page.locator('#mw-scenario-select').selectOption('basic-text')
331 await page.locator('#mw-mode-select').selectOption('otel')
332 await page.locator('#mw-run-button').click()
333​
334 await page.waitForFunction(
335 () =>
336 document
337 .querySelector('#mw-metadata')
338 ?.getAttribute('data-test-complete') === 'true',
339 { timeout: 10000 },
340 )
341​
342 const capture = await fetchOtelCapture(page, baseURL, testId)
343​
344 // Root span is kind=INTERNAL; iteration spans are kind=CLIENT. This is a
345 // structural discriminator, immune to accidental attribute renames on
346 // either span.
347 const chatSpans = capture.spans.filter(
348 (s: any) => s.kind === SpanKind.INTERNAL,
349 )
350 expect(chatSpans).toHaveLength(1)
351 const chatSpan = chatSpans[0]
352 expect(chatSpan.ended).toBe(true)
353 // `gen_ai.operation.name` is intentionally NOT set on the root span —
354 // only iteration spans carry it (see otel.ts).
355 expect(chatSpan.attributes['gen_ai.operation.name']).toBeUndefined()
356​
357 const iterationSpans = capture.spans.filter(
358 (s: any) => s.kind === SpanKind.CLIENT,
359 )
360 expect(iterationSpans.length).toBeGreaterThanOrEqual(1)
361 for (const iter of iterationSpans) {
362 expect(iter.ended).toBe(true)
363 expect(iter.attributes['gen_ai.operation.name']).toBe('chat')
364 }
365​
366 // Token histogram records show up with correct unit and low-cardinality attrs.
367 const tokenRecords = capture.histograms.filter(
368 (h: any) => h.name === 'gen_ai.client.token.usage',
369 )
370 // Guard against the C1 regression: onUsage used to no-op in production order,
371 // losing every token histogram record. If we ever regress, this assertion fails.
372 expect(tokenRecords.length).toBeGreaterThanOrEqual(2)
373 for (const r of tokenRecords) {
374 expect(r.unit).toBe('{token}')
375 expect(r.attributes['gen_ai.response.id']).toBeUndefined()
376 expect(r.attributes['gen_ai.response.model']).toBeUndefined()
377 }
378​
379 // Duration histogram is per-run.
380 const durationRecords = capture.histograms.filter(
381 (h: any) => h.name === 'gen_ai.client.operation.duration',
382 )
383 expect(durationRecords.length).toBe(1)
384 expect(durationRecords[0].unit).toBe('s')
385 expect(
386 durationRecords[0].attributes['gen_ai.response.model'],
387 ).toBeUndefined()
388 })
389​
390 // #1054 — no-tools + outputSchema skips the agent loop. The only model
391 // call is structured-output finalization (`phase=structuredOutput`).
392 // otelMiddleware must open an iteration (CLIENT) span for that call so
393 // backends that key off generation spans (PostHog $ai_generation) and
394 // captureContent both work. Pin to claude-3-7-sonnet so we take the
395 // legacy finalization path, not native-combined (#605) which already
396 // emits a beforeModel iteration span.
397 test('otel middleware emits iteration span + captureContent for no-tools structured-output finalization', async ({
398 page,
399 testId,
400 aimockPort,
401 baseURL,
402 }) => {
403 const params = new URLSearchParams()
404 if (testId) params.set('testId', testId)
405 if (aimockPort) params.set('aimockPort', String(aimockPort))
406 params.set('provider', 'anthropic')
407 params.set('model', 'claude-3-7-sonnet')
408 const qs = params.toString()
409 await page.goto(`/middleware-test?${qs}`)
410 await page.waitForTimeout(2000)
411 await page.locator('#mw-scenario-select').selectOption('structured-output')
412 await page.locator('#mw-mode-select').selectOption('otel')
413 await page.locator('#mw-run-button').click()
414​
415 await page.waitForFunction(
416 () =>
417 document
418 .querySelector('#mw-metadata')
419 ?.getAttribute('data-test-complete') === 'true',
420 { timeout: 15000 },
421 )
422​
423 const capture = await fetchOtelCapture(page, baseURL, testId)
424​
425 const chatSpans = capture.spans.filter(
426 (s: any) => s.kind === SpanKind.INTERNAL,
427 )
428 expect(chatSpans).toHaveLength(1)
429​
430 const iterationSpans = capture.spans.filter(
431 (s: any) => s.kind === SpanKind.CLIENT,
432 )
433 // Exactly one provider call on the skip-agent-loop path → one generation.
434 expect(iterationSpans).toHaveLength(1)
435 const iter = iterationSpans[0]
436 expect(iter.ended).toBe(true)
437 expect(iter.attributes['gen_ai.operation.name']).toBe('chat')
438 expect(iter.attributes['tanstack.ai.iteration']).toBe(0)
439​
440 // captureContent is enabled on the harness otel middleware — prompt must
441 // land on the iteration span (the pre-fix silent no-op left this empty).
442 const inputMessages = iter.attributes['gen_ai.input.messages']
443 expect(typeof inputMessages).toBe('string')
444 expect(inputMessages.length).toBeGreaterThan(0)
445 })
446​
447 test('otel middleware nests tool spans under the iteration span that triggered them', async ({
448 page,
449 testId,
450 aimockPort,
451 baseURL,
452 }) => {
453 const params = new URLSearchParams()
454 if (testId) params.set('testId', testId)
455 if (aimockPort) params.set('aimockPort', String(aimockPort))
456 const qs = params.toString()
457 await page.goto(`/middleware-test${qs ? '?' + qs : ''}`)
458 await page.waitForTimeout(2000)
459 await page.locator('#mw-scenario-select').selectOption('with-tool')
460 await page.locator('#mw-mode-select').selectOption('otel')
461 await page.locator('#mw-run-button').click()
462​
463 await page.waitForFunction(
464 () =>
465 document
466 .querySelector('#mw-metadata')
467 ?.getAttribute('data-test-complete') === 'true',
468 { timeout: 15000 },
469 )
470​
471 const capture = await fetchOtelCapture(page, baseURL, testId)
472​
473 // Every tool span carries gen_ai.tool.name + ended outcome. This also
474 // guards against the "iteration span closed before onBeforeToolCall"
475 // regression — if it regressed, onBeforeToolCall would skip span creation.
476 const toolSpans = capture.spans.filter(
477 (s: any) => 'gen_ai.tool.name' in s.attributes,
478 )
479 expect(toolSpans.length).toBeGreaterThanOrEqual(1)
480 for (const tool of toolSpans) {
481 expect(tool.ended).toBe(true)
482 expect(tool.attributes['tanstack.ai.tool.outcome']).toBeDefined()
483 }
484 })
485​
486 test('otel middleware rolls up usage across a tool loop', async ({
487 request,
488 testId,
489 }) => {
490 const res = await request.post('/api/otel-usage', {
491 data: { provider: 'tool-loop', testId },
492 })
493 expect(res.ok()).toBe(true)
494 const { ok, error, spans } = await res.json()
495 expect(error ?? null).toBeNull()
496 expect(ok).toBe(true)
497​
498 const iterationSpans = spans.filter(
499 (span: any) => span.kind === SpanKind.CLIENT,
500 )
501 expect(iterationSpans).toHaveLength(2)
502 expect(iterationSpans.every((span: any) => span.ended)).toBe(true)
503​
504 const rootSpans = spans.filter(
505 (span: any) =>
506 span.kind === SpanKind.INTERNAL &&
507 span.attributes['tanstack.ai.iterations'] === 2,
508 )
509 expect(rootSpans).toHaveLength(1)
510 expect(rootSpans[0].ended).toBe(true)
511​
512 for (const key of [
513 'gen_ai.usage.input_tokens',
514 'gen_ai.usage.output_tokens',
515 'gen_ai.usage.total_tokens',
516 ]) {
517 expect(rootSpans[0].attributes[key]).toBe(
518 iterationSpans.reduce(
519 (total: number, span: any) => total + span.attributes[key],
520 0,
521 ),
522 )
523 }
524 })
525​
526 test('otel middleware emits total/cache/reasoning usage details on spans', async ({
527 request,
528 }) => {
529 // `/api/otel-usage` drives the OpenAI adapter against the
530 // `/openai-usage-details` aimock mount (total_tokens + cached_tokens +
531 // reasoning_tokens) with otelMiddleware attached, and returns the
532 // captured spans. End-to-end proof for #721: the full TokenUsage reaches
533 // span attributes, not just input/output tokens.
534 const res = await request.post('/api/otel-usage', {
535 data: { provider: 'openai' },
536 })
537 expect(res.ok()).toBe(true)
538 const { ok, error, spans } = await res.json()
539 expect(error ?? null).toBeNull()
540 expect(ok).toBe(true)
541​
542 const iterationSpans = spans.filter(
543 (s: any) => s.kind === SpanKind.CLIENT && s.ended,
544 )
545 expect(iterationSpans.length).toBeGreaterThanOrEqual(1)
546 expect(iterationSpans[0].attributes).toMatchObject({
547 'gen_ai.usage.input_tokens': 100,
548 'gen_ai.usage.output_tokens': 50,
549 'gen_ai.usage.total_tokens': 150,
550 'gen_ai.usage.cache_read.input_tokens': 80,
551 'gen_ai.usage.reasoning.output_tokens': 30,
552 })
553​
554 // The root span rolls up the final usage on onFinish.
555 const rootSpans = spans.filter((s: any) => s.kind === SpanKind.INTERNAL)
556 expect(rootSpans).toHaveLength(1)
557 expect(rootSpans[0].attributes).toMatchObject({
558 'gen_ai.usage.total_tokens': 150,
559 'gen_ai.usage.cache_read.input_tokens': 80,
560 'gen_ai.usage.reasoning.output_tokens': 30,
561 })
562 })
563​
564 test('otel middleware keeps image parts structured in gen_ai.input.messages', async ({
565 request,
566 }) => {
567 // #1525: captureContent used to flatten image parts to "[image]". The
568 // URL reference must survive as an OTel semconv `uri` part.
569 const res = await request.post('/api/otel-usage', {
570 data: { provider: 'multimodal' },
571 })
572 expect(res.ok()).toBe(true)
573 const { ok, error, spans } = await res.json()
574 expect(error ?? null).toBeNull()
575 expect(ok).toBe(true)
576​
577 const iterationSpan = spans.find((s: any) => s.kind === SpanKind.CLIENT)
578 expect(
579 JSON.parse(iterationSpan.attributes['gen_ai.input.messages']),
580 ).toEqual([
581 {
582 role: 'user',
583 content: [
584 { type: 'text', content: 'describe this' },
585 {
586 type: 'uri',
587 modality: 'image',
588 uri: 'https://example.com/cat.png',
589 mime_type: 'image/png',
590 },
591 ],
592 },
593 ])
594 })
595​
596 test('otel middleware emits provider-reported cost on spans', async ({
597 request,
598 }) => {
599 // OpenRouter adapter against the `/openrouter-cost` mount, whose trailing
600 // usage chunk carries `cost` / `cost_details`. Backends like PostHog read
601 // `gen_ai.usage.cost` directly instead of re-deriving from price tables.
602 const res = await request.post('/api/otel-usage', {
603 data: { provider: 'openrouter' },
604 })
605 expect(res.ok()).toBe(true)
606 const { ok, error, spans } = await res.json()
607 expect(error ?? null).toBeNull()
608 expect(ok).toBe(true)
609​
610 const iterationSpans = spans.filter(
611 (s: any) => s.kind === SpanKind.CLIENT && s.ended,
612 )
613 expect(iterationSpans.length).toBeGreaterThanOrEqual(1)
614 expect(iterationSpans[0].attributes).toMatchObject({
615 'gen_ai.usage.input_tokens': 11,
616 'gen_ai.usage.output_tokens': 3,
617 'gen_ai.usage.total_tokens': 14,
618 'gen_ai.usage.cost': 0.0042,
619 'tanstack.ai.usage.upstream_cost': 0.0038,
620 'tanstack.ai.usage.upstream_input_cost': 0.0012,
621 'tanstack.ai.usage.upstream_output_cost': 0.0026,
622 })
623​
624 const rootSpans = spans.filter((s: any) => s.kind === SpanKind.INTERNAL)
625 expect(rootSpans).toHaveLength(1)
626 expect(rootSpans[0].attributes['gen_ai.usage.cost']).toBe(0.0042)
627 })
628​
629 test('otelMiddleware emits an image_generation span for generateImage', async ({
630 request,
631 testId,
632 aimockPort,
633 }) => {
634 // `/api/otel-media` drives generateImage with otelMiddleware against the
635 // image-gen aimock mount and returns the captured spans. End-to-end proof
636 // that the unified middleware tags a non-chat activity with the right
637 // `gen_ai.operation.name` — the same `otelMiddleware` value used for chat,
638 // passed through the media `middleware` slot.
639 const res = await request.post('/api/otel-media', {
640 data: {
641 prompt: 'a guitar in a music store',
642 provider: 'openai',
643 testId,
644 aimockPort,
645 },
646 })
647 expect(res.ok()).toBe(true)
648 const { ok, error, spans } = await res.json()
649 expect(error ?? null).toBeNull()
650 expect(ok).toBe(true)
651​
652 const mediaSpans = spans.filter(
653 (s: any) => s.attributes['gen_ai.operation.name'] === 'image_generation',
654 )
655 expect(mediaSpans).toHaveLength(1)
656 expect(mediaSpans[0].kind).toBe(SpanKind.CLIENT)
657 expect(mediaSpans[0].ended).toBe(true)
658 expect(mediaSpans[0].attributes).toMatchObject({
659 'gen_ai.system': 'openai',
660 'gen_ai.operation.name': 'image_generation',
661 'gen_ai.request.model': 'gpt-image-1',
662 })
663 // captureContent (#1526): the prompt lands as input. The mock returns a
664 // `data:` URL, so the output is a placeholder, never the bytes.
665 expect(
666 JSON.parse(mediaSpans[0].attributes['gen_ai.input.messages']),
667 ).toEqual([
668 {
669 role: 'user',
670 content: [{ type: 'text', content: 'a guitar in a music store' }],
671 },
672 ])
673 expect(
674 JSON.parse(mediaSpans[0].attributes['gen_ai.output.messages']),
675 ).toEqual([
676 { role: 'assistant', content: [{ type: 'text', content: '[image]' }] },
677 ])
678 })
679​
680 test('otel middleware emits the self-describing billed quantity for a duration-billed activity', async ({
681 request,
682 testId,
683 aimockPort,
684 }) => {
685 // `/api/otel-transcription` drives whisper-1 (duration-billed) against the
686 // transcription aimock fixture, whose response reports `duration: 2.4`.
687 // The adapter surfaces that as `usage.billed = { quantity, unit }`, and the
688 // middleware must emit it as the paired billed_quantity/billed_unit
689 // attributes — the machine-readable unit that #816 adds.
690 const res = await request.post('/api/otel-transcription', {
691 data: {
692 audio: 'data:audio/mpeg;base64,SGVsbG8=',
693 provider: 'openai',
694 testId,
695 aimockPort,
696 },
697 })
698 expect(res.ok()).toBe(true)
699 const { ok, error, spans } = await res.json()
700 expect(error ?? null).toBeNull()
701 expect(ok).toBe(true)
702​
703 const mediaSpans = spans.filter(
704 (s: any) => s.attributes['gen_ai.operation.name'] === 'transcription',
705 )
706 expect(mediaSpans).toHaveLength(1)
707 expect(mediaSpans[0].ended).toBe(true)
708 expect(mediaSpans[0].attributes).toMatchObject({
709 'gen_ai.request.model': 'whisper-1',
710 'tanstack.ai.usage.billed_quantity': 2.4,
711 'tanstack.ai.usage.billed_unit': 'seconds',
712 // Deprecated bare count still emitted for backward compatibility.
713 'tanstack.ai.usage.duration_seconds': 2.4,
714 })
715 // captureContent (#1526): inline source audio is a placeholder; the
716 // transcript is the output.
717 expect(
718 JSON.parse(mediaSpans[0].attributes['gen_ai.input.messages']),
719 ).toEqual([
720 { role: 'user', content: [{ type: 'text', content: '[audio]' }] },
721 ])
722 expect(
723 JSON.parse(mediaSpans[0].attributes['gen_ai.output.messages']),
724 ).toEqual([
725 {
726 role: 'assistant',
727 content: [
728 {
729 type: 'text',
730 content: 'I would like to buy a Fender Stratocaster please',
731 },
732 ],
733 },
734 ])
735 })
736​
737 test('no middleware passes content through unchanged', async ({
738 page,
739 testId,
740 aimockPort,
741 }) => {
742 const params = new URLSearchParams()
743 if (testId) params.set('testId', testId)
744 if (aimockPort) params.set('aimockPort', String(aimockPort))
745 const qs = params.toString()
746 await page.goto(`/middleware-test${qs ? '?' + qs : ''}`)
747 await page.waitForTimeout(2000)
748 await page.locator('#mw-scenario-select').selectOption('basic-text')
749 await page.locator('#mw-mode-select').selectOption('none')
750 await page.locator('#mw-run-button').click()
751​
752 await page.waitForFunction(
753 () =>
754 document
755 .querySelector('#mw-metadata')
756 ?.getAttribute('data-test-complete') === 'true',
757 { timeout: 10000 },
758 )
759​
760 const messagesJson = await page.locator('#mw-messages-json').textContent()
761 const messages = JSON.parse(messagesJson || '[]')
762 const assistantMsg = messages.find((m: any) => m.role === 'assistant')
763 const textPart = assistantMsg?.parts?.find((p: any) => p.type === 'text')
764 expect(textPart?.content).not.toContain('[MW]')
765 expect(textPart?.content).toContain('Hello')
766 })
767​
768 test('memory middleware injects recalled prompt + tools and defers save', async ({
769 page,
770 testId,
771 aimockPort,
772 }) => {
773 const params = new URLSearchParams()
774 if (testId) params.set('testId', testId)
775 if (aimockPort) params.set('aimockPort', String(aimockPort))
776 const qs = params.toString()
777 await page.goto(`/middleware-test${qs ? '?' + qs : ''}`)
778 await page.waitForTimeout(2000) // hydration
779 await page.locator('#mw-scenario-select').selectOption('basic-text')
780 await page.locator('#mw-mode-select').selectOption('memory')
781 await page.locator('#mw-run-button').click()
782​
783 await page.waitForFunction(
784 () =>
785 document
786 .querySelector('#mw-metadata')
787 ?.getAttribute('data-test-complete') === 'true',
788 { timeout: 10000 },
789 )
790​
791 const memoryJson = await page.locator('#mw-memory-json').textContent()
792 const capture = JSON.parse(memoryJson || '{}') as {
793 configs: Array<{ systemPrompts: Array<string>; toolNames: Array<string> }>
794 saveCount: number
795 }
796​
797 // The recorder placed after memoryMiddleware saw the config the model
798 // receives: the recalled system prompt (+ tool guidance) and the injected
799 // tool must both be present.
800 expect(capture.configs.length).toBeGreaterThan(0)
801 const injected = capture.configs.find((c) =>
802 c.systemPrompts.some((p) => p.includes('love TanStack')),
803 )
804 expect(injected).toBeTruthy()
805 expect(injected?.systemPrompts.some((p) => p.includes('recall_more'))).toBe(
806 true,
807 )
808 expect(injected?.toolNames).toContain('recall_more')
809​
810 // The finished turn deferred a save through the adapter.
811 expect(capture.saveCount).toBeGreaterThanOrEqual(1)
812 })
813})