Open History to see the last commit
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()
18}
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()
34}
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('capability provide/consume flow surfaces the consumed value in the stream', 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) // hydration
146 await page.locator('#mw-scenario-select').selectOption('capability')
147 await page.locator('#mw-mode-select').selectOption('capability')
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 assistantMsg = messages.find((m: any) => m.role === 'assistant')
161 const textPart = assistantMsg?.parts?.find((p: any) => p.type === 'text')
162 // The provider middleware provides "[CAP]" in setup(); the consumer
163 // middleware reads it via the capability getter in onChunk and prefixes
164 // each text delta. Seeing "[CAP]" in the streamed text proves the provided
165 // capability value flowed across middleware to the consumer.
166 expect(textPart?.content).toContain('[CAP]')
167 expect(textPart?.content).toContain('Hello')
168 })
169
170 test('otel middleware emits chat span + per-iteration token histograms', async ({
171 page,
172 testId,
173 aimockPort,
174 baseURL,
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('basic-text')
183 await page.locator('#mw-mode-select').selectOption('otel')
184 await page.locator('#mw-run-button').click()
185
186 await page.waitForFunction(
187 () =>
188 document
189 .querySelector('#mw-metadata')
190 ?.getAttribute('data-test-complete') === 'true',
191 { timeout: 10000 },
192 )
193
194 const capture = await fetchOtelCapture(page, baseURL, testId)
195
196 // Root span is kind=INTERNAL; iteration spans are kind=CLIENT. This is a
197 // structural discriminator, immune to accidental attribute renames on
198 // either span.
199 const chatSpans = capture.spans.filter(
200 (s: any) => s.kind === SpanKind.INTERNAL,
201 )
202 expect(chatSpans).toHaveLength(1)
203 const chatSpan = chatSpans[0]
204 expect(chatSpan.ended).toBe(true)
205 // `gen_ai.operation.name` is intentionally NOT set on the root span —
206 // only iteration spans carry it (see otel.ts).
207 expect(chatSpan.attributes['gen_ai.operation.name']).toBeUndefined()
208
209 const iterationSpans = capture.spans.filter(
210 (s: any) => s.kind === SpanKind.CLIENT,
211 )
212 expect(iterationSpans.length).toBeGreaterThanOrEqual(1)
213 for (const iter of iterationSpans) {
214 expect(iter.ended).toBe(true)
215 expect(iter.attributes['gen_ai.operation.name']).toBe('chat')
216 }
217
218 // Token histogram records show up with correct unit and low-cardinality attrs.
219 const tokenRecords = capture.histograms.filter(
220 (h: any) => h.name === 'gen_ai.client.token.usage',
221 )
222 // Guard against the C1 regression: onUsage used to no-op in production order,
223 // losing every token histogram record. If we ever regress, this assertion fails.
224 expect(tokenRecords.length).toBeGreaterThanOrEqual(2)
225 for (const r of tokenRecords) {
226 expect(r.unit).toBe('{token}')
227 expect(r.attributes['gen_ai.response.id']).toBeUndefined()
228 expect(r.attributes['gen_ai.response.model']).toBeUndefined()
229 }
230
231 // Duration histogram is per-run.
232 const durationRecords = capture.histograms.filter(
233 (h: any) => h.name === 'gen_ai.client.operation.duration',
234 )
235 expect(durationRecords.length).toBe(1)
236 expect(durationRecords[0].unit).toBe('s')
237 expect(
238 durationRecords[0].attributes['gen_ai.response.model'],
239 ).toBeUndefined()
240 })
241
242 // #1054 — no-tools + outputSchema skips the agent loop. The only model
243 // call is structured-output finalization (`phase=structuredOutput`).
244 // otelMiddleware must open an iteration (CLIENT) span for that call so
245 // backends that key off generation spans (PostHog $ai_generation) and
246 // captureContent both work. Pin to claude-3-7-sonnet so we take the
247 // legacy finalization path, not native-combined (#605) which already
248 // emits a beforeModel iteration span.
249 test('otel middleware emits iteration span + captureContent for no-tools structured-output finalization', async ({
250 page,
251 testId,
252 aimockPort,
253 baseURL,
254 }) => {
255 const params = new URLSearchParams()
256 if (testId) params.set('testId', testId)
257 if (aimockPort) params.set('aimockPort', String(aimockPort))
258 params.set('provider', 'anthropic')
259 params.set('model', 'claude-3-7-sonnet')
260 const qs = params.toString()
261 await page.goto(`/middleware-test?${qs}`)
262 await page.waitForTimeout(2000)
263 await page.locator('#mw-scenario-select').selectOption('structured-output')
264 await page.locator('#mw-mode-select').selectOption('otel')
265 await page.locator('#mw-run-button').click()
266
267 await page.waitForFunction(
268 () =>
269 document
270 .querySelector('#mw-metadata')
271 ?.getAttribute('data-test-complete') === 'true',
272 { timeout: 15000 },
273 )
274
275 const capture = await fetchOtelCapture(page, baseURL, testId)
276
277 const chatSpans = capture.spans.filter(
278 (s: any) => s.kind === SpanKind.INTERNAL,
279 )
280 expect(chatSpans).toHaveLength(1)
281
282 const iterationSpans = capture.spans.filter(
283 (s: any) => s.kind === SpanKind.CLIENT,
284 )
285 // Exactly one provider call on the skip-agent-loop path → one generation.
286 expect(iterationSpans).toHaveLength(1)
287 const iter = iterationSpans[0]
288 expect(iter.ended).toBe(true)
289 expect(iter.attributes['gen_ai.operation.name']).toBe('chat')
290 expect(iter.attributes['tanstack.ai.iteration']).toBe(0)
291
292 // captureContent is enabled on the harness otel middleware — prompt must
293 // land on the iteration span (the pre-fix silent no-op left this empty).
294 const inputMessages = iter.attributes['gen_ai.input.messages']
295 expect(typeof inputMessages).toBe('string')
296 expect(inputMessages.length).toBeGreaterThan(0)
297 })
298
299 test('otel middleware nests tool spans under the iteration span that triggered them', async ({
300 page,
301 testId,
302 aimockPort,
303 baseURL,
304 }) => {
305 const params = new URLSearchParams()
306 if (testId) params.set('testId', testId)
307 if (aimockPort) params.set('aimockPort', String(aimockPort))
308 const qs = params.toString()
309 await page.goto(`/middleware-test${qs ? '?' + qs : ''}`)
310 await page.waitForTimeout(2000)
311 await page.locator('#mw-scenario-select').selectOption('with-tool')
312 await page.locator('#mw-mode-select').selectOption('otel')
313 await page.locator('#mw-run-button').click()
314
315 await page.waitForFunction(
316 () =>
317 document
318 .querySelector('#mw-metadata')
319 ?.getAttribute('data-test-complete') === 'true',
320 { timeout: 15000 },
321 )
322
323 const capture = await fetchOtelCapture(page, baseURL, testId)
324
325 // Every tool span carries gen_ai.tool.name + ended outcome. This also
326 // guards against the "iteration span closed before onBeforeToolCall"
327 // regression — if it regressed, onBeforeToolCall would skip span creation.
328 const toolSpans = capture.spans.filter(
329 (s: any) => 'gen_ai.tool.name' in s.attributes,
330 )
331 expect(toolSpans.length).toBeGreaterThanOrEqual(1)
332 for (const tool of toolSpans) {
333 expect(tool.ended).toBe(true)
334 expect(tool.attributes['tanstack.ai.tool.outcome']).toBeDefined()
335 }
336 })
337
338 test('otel middleware rolls up usage across a tool loop', async ({
339 request,
340 testId,
341 }) => {
342 const res = await request.post('/api/otel-usage', {
343 data: { provider: 'tool-loop', testId },
344 })
345 expect(res.ok()).toBe(true)
346 const { ok, error, spans } = await res.json()
347 expect(error ?? null).toBeNull()
348 expect(ok).toBe(true)
349
350 const iterationSpans = spans.filter(
351 (span: any) => span.kind === SpanKind.CLIENT,
352 )
353 expect(iterationSpans).toHaveLength(2)
354 expect(iterationSpans.every((span: any) => span.ended)).toBe(true)
355
356 const rootSpans = spans.filter(
357 (span: any) =>
358 span.kind === SpanKind.INTERNAL &&
359 span.attributes['tanstack.ai.iterations'] === 2,
360 )
361 expect(rootSpans).toHaveLength(1)
362 expect(rootSpans[0].ended).toBe(true)
363
364 for (const key of [
365 'gen_ai.usage.input_tokens',
366 'gen_ai.usage.output_tokens',
367 'gen_ai.usage.total_tokens',
368 ]) {
369 expect(rootSpans[0].attributes[key]).toBe(
370 iterationSpans.reduce(
371 (total: number, span: any) => total + span.attributes[key],
372 0,
373 ),
374 )
375 }
376 })
377
378 test('otel middleware emits total/cache/reasoning usage details on spans', async ({
379 request,
380 }) => {
381 // `/api/otel-usage` drives the OpenAI adapter against the
382 // `/openai-usage-details` aimock mount (total_tokens + cached_tokens +
383 // reasoning_tokens) with otelMiddleware attached, and returns the
384 // captured spans. End-to-end proof for #721: the full TokenUsage reaches
385 // span attributes, not just input/output tokens.
386 const res = await request.post('/api/otel-usage', {
387 data: { provider: 'openai' },
388 })
389 expect(res.ok()).toBe(true)
390 const { ok, error, spans } = await res.json()
391 expect(error ?? null).toBeNull()
392 expect(ok).toBe(true)
393
394 const iterationSpans = spans.filter(
395 (s: any) => s.kind === SpanKind.CLIENT && s.ended,
396 )
397 expect(iterationSpans.length).toBeGreaterThanOrEqual(1)
398 expect(iterationSpans[0].attributes).toMatchObject({
399 'gen_ai.usage.input_tokens': 100,
400 'gen_ai.usage.output_tokens': 50,
401 'gen_ai.usage.total_tokens': 150,
402 'gen_ai.usage.cache_read.input_tokens': 80,
403 'gen_ai.usage.reasoning.output_tokens': 30,
404 })
405
406 // The root span rolls up the final usage on onFinish.
407 const rootSpans = spans.filter((s: any) => s.kind === SpanKind.INTERNAL)
408 expect(rootSpans).toHaveLength(1)
409 expect(rootSpans[0].attributes).toMatchObject({
410 'gen_ai.usage.total_tokens': 150,
411 'gen_ai.usage.cache_read.input_tokens': 80,
412 'gen_ai.usage.reasoning.output_tokens': 30,
413 })
414 })
415
416 test('otel middleware keeps image parts structured in gen_ai.input.messages', async ({
417 request,
418 }) => {
419 // #1525: captureContent used to flatten image parts to "[image]". The
420 // URL reference must survive as an OTel semconv `uri` part.
421 const res = await request.post('/api/otel-usage', {
422 data: { provider: 'multimodal' },
423 })
424 expect(res.ok()).toBe(true)
425 const { ok, error, spans } = await res.json()
426 expect(error ?? null).toBeNull()
427 expect(ok).toBe(true)
428
429 const iterationSpan = spans.find((s: any) => s.kind === SpanKind.CLIENT)
430 expect(
431 JSON.parse(iterationSpan.attributes['gen_ai.input.messages']),
432 ).toEqual([
433 {
434 role: 'user',
435 content: [
436 { type: 'text', content: 'describe this' },
437 {
438 type: 'uri',
439 modality: 'image',
440 uri: 'https://example.com/cat.png',
441 mime_type: 'image/png',
442 },
443 ],
444 },
445 ])
446 })
447
448 test('otel middleware emits provider-reported cost on spans', async ({
449 request,
450 }) => {
451 // OpenRouter adapter against the `/openrouter-cost` mount, whose trailing
452 // usage chunk carries `cost` / `cost_details`. Backends like PostHog read
453 // `gen_ai.usage.cost` directly instead of re-deriving from price tables.
454 const res = await request.post('/api/otel-usage', {
455 data: { provider: 'openrouter' },
456 })
457 expect(res.ok()).toBe(true)
458 const { ok, error, spans } = await res.json()
459 expect(error ?? null).toBeNull()
460 expect(ok).toBe(true)
461
462 const iterationSpans = spans.filter(
463 (s: any) => s.kind === SpanKind.CLIENT && s.ended,
464 )
465 expect(iterationSpans.length).toBeGreaterThanOrEqual(1)
466 expect(iterationSpans[0].attributes).toMatchObject({
467 'gen_ai.usage.input_tokens': 11,
468 'gen_ai.usage.output_tokens': 3,
469 'gen_ai.usage.total_tokens': 14,
470 'gen_ai.usage.cost': 0.0042,
471 'tanstack.ai.usage.upstream_cost': 0.0038,
472 'tanstack.ai.usage.upstream_input_cost': 0.0012,
473 'tanstack.ai.usage.upstream_output_cost': 0.0026,
474 })
475
476 const rootSpans = spans.filter((s: any) => s.kind === SpanKind.INTERNAL)
477 expect(rootSpans).toHaveLength(1)
478 expect(rootSpans[0].attributes['gen_ai.usage.cost']).toBe(0.0042)
479 })
480
481 test('otelMiddleware emits an image_generation span for generateImage', async ({
482 request,
483 testId,
484 aimockPort,
485 }) => {
486 // `/api/otel-media` drives generateImage with otelMiddleware against the
487 // image-gen aimock mount and returns the captured spans. End-to-end proof
488 // that the unified middleware tags a non-chat activity with the right
489 // `gen_ai.operation.name` — the same `otelMiddleware` value used for chat,
490 // passed through the media `middleware` slot.
491 const res = await request.post('/api/otel-media', {
492 data: {
493 prompt: 'a guitar in a music store',
494 provider: 'openai',
495 testId,
496 aimockPort,
497 },
498 })
499 expect(res.ok()).toBe(true)
500 const { ok, error, spans } = await res.json()
501 expect(error ?? null).toBeNull()
502 expect(ok).toBe(true)
503
504 const mediaSpans = spans.filter(
505 (s: any) => s.attributes['gen_ai.operation.name'] === 'image_generation',
506 )
507 expect(mediaSpans).toHaveLength(1)
508 expect(mediaSpans[0].kind).toBe(SpanKind.CLIENT)
509 expect(mediaSpans[0].ended).toBe(true)
510 expect(mediaSpans[0].attributes).toMatchObject({
511 'gen_ai.system': 'openai',
512 'gen_ai.operation.name': 'image_generation',
513 'gen_ai.request.model': 'gpt-image-1',
514 })
515 // captureContent (#1526): the prompt lands as input. The mock returns a
516 // `data:` URL, so the output is a placeholder, never the bytes.
517 expect(
518 JSON.parse(mediaSpans[0].attributes['gen_ai.input.messages']),
519 ).toEqual([
520 {
521 role: 'user',
522 content: [{ type: 'text', content: 'a guitar in a music store' }],
523 },
524 ])
525 expect(
526 JSON.parse(mediaSpans[0].attributes['gen_ai.output.messages']),
527 ).toEqual([
528 { role: 'assistant', content: [{ type: 'text', content: '[image]' }] },
529 ])
530 })
531
532 test('otel middleware emits the self-describing billed quantity for a duration-billed activity', async ({
533 request,
534 testId,
535 aimockPort,
536 }) => {
537 // `/api/otel-transcription` drives whisper-1 (duration-billed) against the
538 // transcription aimock fixture, whose response reports `duration: 2.4`.
539 // The adapter surfaces that as `usage.billed = { quantity, unit }`, and the
540 // middleware must emit it as the paired billed_quantity/billed_unit
541 // attributes — the machine-readable unit that #816 adds.
542 const res = await request.post('/api/otel-transcription', {
543 data: {
544 audio: 'data:audio/mpeg;base64,SGVsbG8=',
545 provider: 'openai',
546 testId,
547 aimockPort,
548 },
549 })
550 expect(res.ok()).toBe(true)
551 const { ok, error, spans } = await res.json()
552 expect(error ?? null).toBeNull()
553 expect(ok).toBe(true)
554
555 const mediaSpans = spans.filter(
556 (s: any) => s.attributes['gen_ai.operation.name'] === 'transcription',
557 )
558 expect(mediaSpans).toHaveLength(1)
559 expect(mediaSpans[0].ended).toBe(true)
560 expect(mediaSpans[0].attributes).toMatchObject({
561 'gen_ai.request.model': 'whisper-1',
562 'tanstack.ai.usage.billed_quantity': 2.4,
563 'tanstack.ai.usage.billed_unit': 'seconds',
564 // Deprecated bare count still emitted for backward compatibility.
565 'tanstack.ai.usage.duration_seconds': 2.4,
566 })
567 // captureContent (#1526): inline source audio is a placeholder; the
568 // transcript is the output.
569 expect(
570 JSON.parse(mediaSpans[0].attributes['gen_ai.input.messages']),
571 ).toEqual([
572 { role: 'user', content: [{ type: 'text', content: '[audio]' }] },
573 ])
574 expect(
575 JSON.parse(mediaSpans[0].attributes['gen_ai.output.messages']),
576 ).toEqual([
577 {
578 role: 'assistant',
579 content: [
580 {
581 type: 'text',
582 content: 'I would like to buy a Fender Stratocaster please',
583 },
584 ],
585 },
586 ])
587 })
588
589 test('no middleware passes content through unchanged', async ({
590 page,
591 testId,
592 aimockPort,
593 }) => {
594 const params = new URLSearchParams()
595 if (testId) params.set('testId', testId)
596 if (aimockPort) params.set('aimockPort', String(aimockPort))
597 const qs = params.toString()
598 await page.goto(`/middleware-test${qs ? '?' + qs : ''}`)
599 await page.waitForTimeout(2000)
600 await page.locator('#mw-scenario-select').selectOption('basic-text')
601 await page.locator('#mw-mode-select').selectOption('none')
602 await page.locator('#mw-run-button').click()
603
604 await page.waitForFunction(
605 () =>
606 document
607 .querySelector('#mw-metadata')
608 ?.getAttribute('data-test-complete') === 'true',
609 { timeout: 10000 },
610 )
611
612 const messagesJson = await page.locator('#mw-messages-json').textContent()
613 const messages = JSON.parse(messagesJson || '[]')
614 const assistantMsg = messages.find((m: any) => m.role === 'assistant')
615 const textPart = assistantMsg?.parts?.find((p: any) => p.type === 'text')
616 expect(textPart?.content).not.toContain('[MW]')
617 expect(textPart?.content).toContain('Hello')
618 })
619
620 test('memory middleware injects recalled prompt + tools and defers save', async ({
621 page,
622 testId,
623 aimockPort,
624 }) => {
625 const params = new URLSearchParams()
626 if (testId) params.set('testId', testId)
627 if (aimockPort) params.set('aimockPort', String(aimockPort))
628 const qs = params.toString()
629 await page.goto(`/middleware-test${qs ? '?' + qs : ''}`)
630 await page.waitForTimeout(2000) // hydration
631 await page.locator('#mw-scenario-select').selectOption('basic-text')
632 await page.locator('#mw-mode-select').selectOption('memory')
633 await page.locator('#mw-run-button').click()
634
635 await page.waitForFunction(
636 () =>
637 document
638 .querySelector('#mw-metadata')
639 ?.getAttribute('data-test-complete') === 'true',
640 { timeout: 10000 },
641 )
642
643 const memoryJson = await page.locator('#mw-memory-json').textContent()
644 const capture = JSON.parse(memoryJson || '{}') as {
645 configs: Array<{ systemPrompts: Array<string>; toolNames: Array<string> }>
646 saveCount: number
647 }
648
649 // The recorder placed after memoryMiddleware saw the config the model
650 // receives: the recalled system prompt (+ tool guidance) and the injected
651 // tool must both be present.
652 expect(capture.configs.length).toBeGreaterThan(0)
653 const injected = capture.configs.find((c) =>
654 c.systemPrompts.some((p) => p.includes('love TanStack')),
655 )
656 expect(injected).toBeTruthy()
657 expect(injected?.systemPrompts.some((p) => p.includes('recall_more'))).toBe(
658 true,
659 )
660 expect(injected?.toolNames).toContain('recall_more')
661
662 // The finished turn deferred a save through the adapter.
663 expect(capture.saveCount).toBeGreaterThanOrEqual(1)
664 })
665})