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

middleware.spec.ts

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