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

api.middleware-test.ts

788 lines25.4 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 chatParamsFromRequestBody,
5 createCapability,
6 EventType,
7 maxIterations,
8 toServerSentEventsResponse,
9 toolDefinition,
10} from '@tanstack/ai'
11import { otelMiddleware } from '@tanstack/ai/middlewares/otel'
12import { memoryMiddleware } from '@tanstack/ai-memory'
13import type { MemoryAdapter } from '@tanstack/ai-memory'
14import { clientContextToolDefinition } from '@/lib/middleware-test-tools'
15import {
16 getMemoryCapture,
17 recordMemoryConfig,
18 recordMemorySave,
19 resetMemoryCapture,
20} from '@/lib/memory-capture'
21import { SpanStatusCode } from '@opentelemetry/api'
22import { z } from 'zod'
23import type {
24 AnyTextAdapter,
25 ChatMiddleware,
26 StreamChunk,
27 Tool,
28} from '@tanstack/ai'
29import type {
30 AttributeValue,
31 Attributes,
32 Context,
33 Histogram,
34 Meter,
35 MetricOptions,
36 Span,
37 SpanContext,
38 SpanStatus,
39 Tracer,
40} from '@opentelemetry/api'
41import { guitarRecommendationSchema } from '@/lib/schemas'
42import {
43 getPhaseCapture,
44 recordGenericBoundary,
45 recordGenericPolicy,
46 recordGenericResolution,
47 recordGenericToolExecution,
48 recordOnError,
49 recordOnFinish,
50 recordPhase,
51 recordYieldedChunk,
52 resetPhaseCapture,
53} from '@/lib/phase-capture'
54import {
55 boundaryForScenario,
56 deleteReviewTool,
57 inspectReviewTool,
58 isGenericScenario,
59 renderReviewTool,
60 reviewPlan,
61 toolResumeForScenario,
62} from '@/lib/generic-middleware-interrupts'
63import type { GenericScenario } from '@/lib/generic-middleware-interrupts'
64import { createTextAdapter } from '@/lib/providers'
65import {
66 getOtelCapture,
67 recordOtelEvent,
68 recordOtelException,
69 recordOtelHistogram,
70 recordOtelSpan,
71 resetOtelCapture,
72} from '@/lib/otel-capture'
73​
74// The otel capture endpoint is only useful during E2E runs. Gate both the
75// POST 'otel' mode and the GET capture fetch behind this flag so the route
76// cannot be used as an oracle in a production-like build.
77const OTEL_TEST_ENABLED =
78 process.env.E2E_TEST === '1' || process.env.NODE_ENV !== 'production'
79​
80const weatherTool = toolDefinition({
81 name: 'get_weather',
82 description: 'Get weather',
83 inputSchema: z.object({ city: z.string() }),
84}).server(async (args) =>
85 JSON.stringify({ city: args.city, temperature: 72, condition: 'sunny' }),
87​
88function createRunErrorAdapter(): AnyTextAdapter {
89 return {
90 kind: 'text',
91 name: 'run-error-test',
92 model: 'run-error-test',
93 '~types': {
94 providerOptions: {},
95 inputModalities: ['text'],
96 messageMetadataByModality: {},
97 toolCapabilities: [],
98 toolCallMetadata: undefined,
99 systemPromptMetadata: undefined,
100 },
101 async *chatStream(options): AsyncGenerator<StreamChunk> {
102 yield {
103 type: EventType.RUN_STARTED,
104 runId: options.runId ?? 'run-error-test',
105 threadId: options.threadId ?? 'run-error-test',
106 timestamp: Date.now(),
107 }
108 yield {
109 type: EventType.RUN_ERROR,
110 message: 'Provider failed',
111 code: 'provider_error',
112 timestamp: Date.now(),
113 }
114 },
115 structuredOutput: async () => ({ data: {}, rawText: '{}' }),
116 }
118​
119const runErrorBoundaryMiddleware: ChatMiddleware<unknown, typeof reviewPlan> = {
120 name: 'run-error-boundary',
121 onInterruptBoundary(ctx) {
122 if (ctx.phase !== 'afterModel') return
123 return {
124 interrupts: [
125 reviewPlan.interrupt({
126 key: 'run-error-review',
127 reason: 'review_required',
128 message: 'Review the response',
129 payload: { title: 'Run error review', boundary: ctx.phase },
130 }),
131 ],
132 }
133 },
135​
136/** The adapter's accumulated `content`. The AG-UI 1.0 event type omits it. */
137function accumulated(chunk: StreamChunk): string {
138 const content: unknown = Reflect.get(chunk, 'content')
139 return typeof content === 'string' ? content : ''
141​
142const chunkTransformMiddleware: ChatMiddleware = {
143 name: 'chunk-transform',
144 onChunk(_ctx, chunk) {
145 if (chunk.type === 'TEXT_MESSAGE_CONTENT' && chunk.delta) {
146 return {
147 ...chunk,
148 delta: '[MW] ' + chunk.delta,
149 content: '[MW] ' + accumulated(chunk),
150 }
151 }
152 return chunk
153 },
155​
156const toolSkipMiddleware: ChatMiddleware = {
157 name: 'tool-skip',
158 onBeforeToolCall(_ctx, hookCtx) {
159 if (hookCtx.toolName === 'get_weather') {
160 return {
161 type: 'skip' as const,
162 result: JSON.stringify({ skipped: true, reason: 'middleware' }),
163 }
164 }
165 return undefined
166 },
168​
169/**
170 * Capability provide/consume flow (`capability` mode).
171 *
172 * Exercises the server-side middleware capability primitive end-to-end:
173 *
174 * - `prefixCapability` is a typed handle created via `createCapability`. It is
175 * simultaneously a `[get, provide]` tuple and the identity referenced in the
176 * middleware `provides`/`requires` declarations.
177 * - `prefixProviderMiddleware` declares `provides: [prefixCapability]` and calls
178 * `providePrefix(ctx, ...)` in `setup` — the hook that runs first, before any
179 * `onConfig`/`onChunk`.
180 * - `prefixConsumerMiddleware` declares `requires: [prefixCapability]` and reads
181 * the value with `getPrefix(ctx)` inside `onChunk`, using it to prefix every
182 * text delta. The consumed value therefore shows up verbatim in the streamed
183 * assistant text, which the spec asserts against the deterministic fixture.
184 */
185const prefixCapability = createCapability<string>()('capability-prefix')
186const [getPrefix, providePrefix] = prefixCapability
187​
188const prefixProviderMiddleware: ChatMiddleware = {
189 name: 'prefix-provider',
190 provides: [prefixCapability],
191 setup(ctx) {
192 providePrefix(ctx, '[CAP]')
193 },
195​
196const prefixConsumerMiddleware: ChatMiddleware = {
197 name: 'prefix-consumer',
198 requires: [prefixCapability],
199 onChunk(ctx, chunk) {
200 if (chunk.type === 'TEXT_MESSAGE_CONTENT' && chunk.delta) {
201 const prefix = getPrefix(ctx)
202 return {
203 ...chunk,
204 delta: prefix + ' ' + chunk.delta,
205 content: prefix + ' ' + accumulated(chunk),
206 }
207 }
208 return chunk
209 },
211​
212/**
213 * Per-testId recorder used by `phase-recorder` mode.
214 *
215 * Captures every `ctx.phase` observed during `onChunk` and counts `onFinish`
216 * invocations. The capture is stored in a module-global keyed by `testId` so
217 * the page can fetch it via `GET /api/middleware-test?testId=...&kind=phase`
218 * after the run finishes.
219 *
220 * Why a factory: middleware closes over `captureId` so we don't have to thread
221 * a per-request shim through global state.
222 */
223function createPhaseRecorderMiddleware(captureId: string): ChatMiddleware {
224 return {
225 name: 'phase-recorder',
226 onChunk(ctx, chunk) {
227 recordPhase(captureId, ctx.phase)
228 return chunk
229 },
230 onFinish() {
231 recordOnFinish(captureId)
232 },
233 onError() {
234 recordOnError(captureId)
235 },
236 }
238​
239/**
240 * Wraps a chat stream so every chunk that leaves `chat()` (post-middleware)
241 * is recorded into the per-testId phase capture as a yielded chunk. Used by
242 * `phase-recorder` mode to let the spec assert what the consumer actually
243 * sees — distinct from what `onChunk` observes inside the middleware chain.
244 */
245async function* teeForPhaseCapture(
246 source: AsyncIterable<StreamChunk>,
247 captureId: string,
248): AsyncIterable<StreamChunk> {
249 let currentRunId: string | undefined
250 for await (const chunk of source) {
251 if (chunk.type === 'RUN_STARTED' && typeof chunk.runId === 'string') {
252 currentRunId = chunk.runId
253 }
254 const runId =
255 'runId' in chunk && typeof chunk.runId === 'string'
256 ? chunk.runId
257 : currentRunId
258 recordYieldedChunk(captureId, {
259 type: chunk.type,
260 ...(runId !== undefined ? { runId } : {}),
261 ...(chunk.type === 'RUN_FINISHED' && chunk.outcome
262 ? { outcomeType: chunk.outcome.type }
263 : {}),
264 ...(chunk.type === 'RUN_FINISHED' && chunk.outcome?.type === 'interrupt'
265 ? { interruptCount: chunk.outcome.interrupts.length }
266 : {}),
267 })
268 yield chunk
269 }
271​
272function lifecycleMiddlewareStack(
273 existing: Array<ChatMiddleware>,
274 extra: ChatMiddleware<unknown, typeof reviewPlan>,
275): Array<ChatMiddleware<unknown, typeof reviewPlan>> {
276 return [...existing, extra]
278​
279function createGenericLifecycleMiddleware(
280 captureId: string,
281 scenario: GenericScenario,
282): ChatMiddleware<unknown, typeof reviewPlan> {
283 const boundary = boundaryForScenario(scenario)
284 return {
285 name: 'generic-lifecycle',
286 onInterruptBoundary(ctx) {
287 if (ctx.phase !== boundary || ctx.parentRunId) return
288 recordGenericBoundary(captureId, { phase: ctx.phase, runId: ctx.runId })
289 return {
290 interrupts: [
291 reviewPlan.interrupt({
292 key: `${scenario}-review`,
293 reason: 'review_required',
294 message: `Review the plan at ${ctx.phase}`,
295 payload: { title: 'Middleware review plan', boundary: ctx.phase },
296 }),
297 ],
298 }
299 },
300 onInterruptResolution(_ctx, resolutions) {
301 for (const resolution of resolutions.for(reviewPlan)) {
302 recordGenericResolution(captureId, {
303 definitionId: resolution.request.definition.id,
304 status: resolution.status,
305 ...(resolution.status === 'resolved'
306 ? { response: resolution.response }
307 : {}),
308 })
309 }
310 const policy = toolResumeForScenario(scenario)
311 recordGenericPolicy(captureId, policy)
312 return { toolResume: policy }
313 },
314 }
316​
317function genericTools(captureId: string, scenario: GenericScenario) {
318 if (scenario === 'generic-after-tools') {
319 return [
320 inspectReviewTool.server(async ({ reviewId }) => {
321 recordGenericToolExecution(captureId, {
322 name: 'inspect_review',
323 side: 'server',
324 })
325 return { inspected: true, reviewId }
326 }),
327 ]
328 }
329 if (boundaryForScenario(scenario) !== 'beforeTools') return []
330 return [
331 deleteReviewTool.server(async ({ reviewId }) => {
332 recordGenericToolExecution(captureId, {
333 name: 'delete_review',
334 side: 'server',
335 })
336 return { deleted: true, reviewId }
337 }),
338 renderReviewTool.client(),
339 ]
341​
342/**
343 * Fake memory adapter for `memory` mode. `recall` unconditionally returns a
344 * known system-prompt block plus a memory tool (so the spec can assert both the
345 * prompt injection AND tool injection reach the model config), and `save`
346 * records that the deferred write ran. Deterministic — no real vendor, no
347 * cross-request state.
348 */
349const RECALL_MORE_TOOL: Tool = {
350 name: 'recall_more',
351 description: 'Look up additional long-term memory by query.',
352 inputSchema: { type: 'object', properties: {}, additionalProperties: false },
354​
355function createFakeMemoryAdapter(captureId: string): MemoryAdapter {
356 return {
357 id: 'fake-memory',
358 recall: async () => ({
359 systemPrompt: 'MEMORY: the user previously said they love TanStack.',
360 fragments: [{ text: 'the user loves TanStack', source: 'f1' }],
361 tools: [RECALL_MORE_TOOL],
362 toolGuidance: 'Use recall_more to look up additional memory when needed.',
363 }),
364 save: async () => {
365 recordMemorySave(captureId)
366 return [{ ok: true }]
367 },
368 }
370​
371/**
372 * Recorder placed AFTER `memoryMiddleware` so it observes the config the model
373 * actually sees — i.e. WITH the recalled system prompt + tools already merged
374 * in. Records that into the per-testId memory capture.
375 */
376function createMemoryConfigRecorder(captureId: string): ChatMiddleware {
377 return {
378 name: 'memory-config-recorder',
379 onConfig(ctx, config) {
380 if (ctx.phase !== 'init') return
381 recordMemoryConfig(captureId, {
382 systemPrompts: config.systemPrompts.map((p) =>
383 typeof p === 'string' ? p : p.content,
384 ),
385 toolNames: config.tools.map((t) => t.name),
386 })
387 return
388 },
389 }
391​
392// Minimal in-memory tracer/meter. Captures into a per-testId bucket so that
393// the Playwright spec can fetch the recorded state via GET after the stream
394// finishes. Not exported — only used to build otelMiddleware for the test.
395function createCaptureTracer(captureId: string): Tracer {
396 let spanSeq = 0
397 const tracer: Tracer = {
398 startSpan(name, options = {}, _ctx?: Context): Span {
399 const id = `span-${spanSeq++}`
400 const attrs: Record<string, AttributeValue> = {}
401 for (const [k, v] of Object.entries(options.attributes ?? {})) {
402 if (v !== undefined) attrs[k] = v
403 }
404 recordOtelSpan(captureId, {
405 id,
406 name,
407 kind: options.kind,
408 attributes: attrs,
409 status: SpanStatusCode.UNSET,
410 events: [],
411 exceptions: [],
412 ended: false,
413 })
414 const status: SpanStatus = { code: SpanStatusCode.UNSET }
415 let ended = false
416 const span: Span = {
417 spanContext(): SpanContext {
418 return { traceId: 'capture-trace', spanId: id, traceFlags: 1 }
419 },
420 setAttribute(key, value) {
421 attrs[key] = value
422 recordOtelSpan(captureId, { id, patch: { attributes: { ...attrs } } })
423 return span
424 },
425 setAttributes(next) {
426 for (const [k, v] of Object.entries(next)) {
427 attrs[k] = v as AttributeValue
428 }
429 recordOtelSpan(captureId, { id, patch: { attributes: { ...attrs } } })
430 return span
431 },
432 addEvent(eventName, eventAttrs) {
433 recordOtelEvent(captureId, id, {
434 name: eventName,
435 attributes: eventAttrs as Attributes | undefined,
436 })
437 return span
438 },
439 addLink() {
440 return span
441 },
442 addLinks() {
443 return span
444 },
445 setStatus(next) {
446 status.code = next.code
447 status.message = next.message
448 recordOtelSpan(captureId, {
449 id,
450 patch: { status: next.code, statusMessage: next.message },
451 })
452 return span
453 },
454 updateName(next) {
455 recordOtelSpan(captureId, { id, patch: { name: next } })
456 return span
457 },
458 end() {
459 ended = true
460 recordOtelSpan(captureId, { id, patch: { ended: true } })
461 },
462 isRecording() {
463 return !ended
464 },
465 recordException(exception, exceptionAttrs) {
466 recordOtelException(captureId, id, {
467 exception: String(
468 (exception as { message?: string } | undefined)?.message ??
469 exception,
470 ),
471 attributes: exceptionAttrs as Attributes | undefined,
472 })
473 },
474 }
475 return span
476 },
477 // Minimal implementation — our middleware never calls startActiveSpan.
478​
479 startActiveSpan(...args: Array<any>) {
480 const fn = args[args.length - 1] as (span: Span) => unknown
481 const name = args[0] as string
482 const span = tracer.startSpan(name, {})
483 try {
484 return fn(span)
485 } finally {
486 span.end()
487 }
488 },
489 }
490 return tracer
492​
493function createCaptureMeter(captureId: string): Meter {
494 const histogram = (name: string, options?: MetricOptions): Histogram => ({
495 record(value: number, attributes?: Attributes) {
496 recordOtelHistogram(captureId, {
497 name,
498 value,
499 attributes,
500 unit: options?.unit,
501 })
502 },
503 })
504 return {
505 createHistogram: histogram,
506 } as any as Meter
508​
509export const Route = createFileRoute('/api/middleware-test')({
510 server: {
511 handlers: {
512 POST: async ({ request }) => {
513 if (request.signal?.aborted) return new Response(null, { status: 499 })
514 const abortController = new AbortController()
515​
516 let params
517 try {
518 params = await chatParamsFromRequestBody(await request.json())
519 } catch (error) {
520 return new Response(
521 error instanceof Error ? error.message : 'Bad request',
522 { status: 400 },
523 )
524 }
525​
526 const fp = params.forwardedProps
527 const scenario =
528 typeof fp.scenario === 'string' ? fp.scenario : 'basic-text'
529 const middlewareMode =
530 typeof fp.middlewareMode === 'string' ? fp.middlewareMode : 'none'
531 const testId: string | undefined =
532 typeof fp.testId === 'string' ? fp.testId : undefined
533 const aimockPort: number | undefined =
534 fp.aimockPort != null ? Number(fp.aimockPort) : undefined
535 // Provider/model overrides let the middleware E2E exercise both the
536 // native-combined-mode path (modern OpenAI / Claude 4.5+ — no
537 // `structuredOutput` phase, single combined call) and the legacy
538 // finalization path (Claude 3.7, etc. — `structuredOutput` phase
539 // fires). See #605.
540 const provider =
541 typeof fp.provider === 'string' ? fp.provider : 'openai'
542 const modelOverride =
543 typeof fp.model === 'string' ? fp.model : undefined
544​
545 try {
546 const adapterOptions =
547 scenario === 'run-error'
548 ? { adapter: createRunErrorAdapter() }
549 : createTextAdapter(
550 provider as Parameters<typeof createTextAdapter>[0],
551 modelOverride,
552 aimockPort,
553 testId,
554 )
555​
556 const middleware: Array<ChatMiddleware> = []
557 let genericLifecycleMiddleware:
558 | ChatMiddleware<unknown, typeof reviewPlan>
559 | undefined =
560 scenario === 'run-error' ? runErrorBoundaryMiddleware : undefined
561 const genericScenario = isGenericScenario(scenario)
562 ? scenario
563 : undefined
564​
565 if (middlewareMode === 'chunk-transform')
566 middleware.push(chunkTransformMiddleware)
567 if (middlewareMode === 'tool-skip')
568 middleware.push(toolSkipMiddleware)
569 if (middlewareMode === 'capability') {
570 // Order matters: the provider's setup() must run before the
571 // consumer reads the capability. Array order is preserved.
572 middleware.push(prefixProviderMiddleware, prefixConsumerMiddleware)
573 }
574 if (middlewareMode === 'phase-recorder') {
575 if (!testId) {
576 return new Response(
577 JSON.stringify({
578 error: 'phase-recorder mode requires testId',
579 }),
580 {
581 status: 400,
582 headers: { 'Content-Type': 'application/json' },
583 },
584 )
585 }
586 resetPhaseCapture(testId)
587 middleware.push(createPhaseRecorderMiddleware(testId))
588 }
589 if (middlewareMode === 'generic-lifecycle') {
590 if (!testId || !genericScenario) {
591 return new Response(
592 JSON.stringify({
593 error:
594 'generic-lifecycle mode requires testId and a generic scenario',
595 }),
596 {
597 status: 400,
598 headers: { 'Content-Type': 'application/json' },
599 },
600 )
601 }
602 if (!params.parentRunId) resetPhaseCapture(testId)
603 genericLifecycleMiddleware = createGenericLifecycleMiddleware(
604 testId,
605 genericScenario,
606 )
607 }
608 if (middlewareMode === 'memory') {
609 if (!testId) {
610 return new Response(
611 JSON.stringify({ error: 'memory mode requires testId' }),
612 {
613 status: 400,
614 headers: { 'Content-Type': 'application/json' },
615 },
616 )
617 }
618 resetMemoryCapture(testId)
619 middleware.push(
620 memoryMiddleware({
621 adapter: createFakeMemoryAdapter(testId),
622 scope: { threadId: testId },
623 }),
624 createMemoryConfigRecorder(testId),
625 )
626 }
627 if (middlewareMode === 'otel') {
628 if (!OTEL_TEST_ENABLED) {
629 return new Response(null, { status: 404 })
630 }
631 if (!testId) {
632 return new Response(
633 JSON.stringify({ error: 'otel mode requires testId' }),
634 {
635 status: 400,
636 headers: { 'Content-Type': 'application/json' },
637 },
638 )
639 }
640 resetOtelCapture(testId)
641 middleware.push(
642 otelMiddleware({
643 tracer: createCaptureTracer(testId),
644 meter: createCaptureMeter(testId),
645 captureContent: true,
646 }),
647 )
648 }
649​
650 const tools =
651 genericScenario && testId
652 ? genericTools(testId, genericScenario)
653 : scenario === 'with-tool'
654 ? [weatherTool]
655 : scenario === 'structured-client-tool-wait'
656 ? [clientContextToolDefinition]
657 : []
658​
659 // Structured scenarios bind the same guitar schema. The client-tool
660 // variant also passes an isomorphic tool definition so the first
661 // server invocation can stop at the browser-execution boundary.
662 const isStructured =
663 scenario === 'structured-output' ||
664 scenario === 'structured-output-stream' ||
665 scenario === 'structured-client-tool-wait'
666​
667 const rawStream = isStructured
668 ? chat({
669 ...adapterOptions,
670 messages: params.messages,
671 tools,
672 middleware,
673 threadId: params.threadId,
674 runId: params.runId,
675 outputSchema: guitarRecommendationSchema,
676 stream: true,
677 abortController,
678 })
679 : genericLifecycleMiddleware
680 ? chat({
681 ...adapterOptions,
682 messages: params.messages,
683 tools,
684 middleware: lifecycleMiddlewareStack(
685 middleware,
686 genericLifecycleMiddleware,
687 ),
688 threadId: params.threadId,
689 runId: params.runId,
690 parentRunId: params.parentRunId,
691 resume: params.resume,
692 interrupts: [reviewPlan] as const,
693 agentLoopStrategy: maxIterations(10),
694 abortController,
695 })
696 : chat({
697 ...adapterOptions,
698 messages: params.messages,
699 tools,
700 middleware,
701 threadId: params.threadId,
702 runId: params.runId,
703 parentRunId: params.parentRunId,
704 resume: params.resume,
705 interrupts: genericScenario ? [reviewPlan] : undefined,
706 agentLoopStrategy: maxIterations(10),
707 abortController,
708 })
709​
710 // Tee the post-middleware stream when `phase-recorder` is active
711 // so the spec can assert on what the consumer ultimately sees
712 // (e.g. exactly one RUN_STARTED/RUN_FINISHED pair).
713 const stream =
714 (middlewareMode === 'phase-recorder' ||
715 middlewareMode === 'generic-lifecycle') &&
716 testId
717 ? teeForPhaseCapture(rawStream, testId)
718 : rawStream
719​
720 return toServerSentEventsResponse(stream, { abortController })
721 } catch (error: any) {
722 console.error('[api.middleware-test] Error:', error.message)
723 if (error.name === 'AbortError' || abortController.signal.aborted) {
724 return new Response(null, { status: 499 })
725 }
726 return new Response(JSON.stringify({ error: error.message }), {
727 status: 500,
728 headers: { 'Content-Type': 'application/json' },
729 })
730 }
731 },
732 GET: async ({ request }) => {
733 const url = new URL(request.url)
734 const testId = url.searchParams.get('testId')
735 const kind = url.searchParams.get('kind')
736​
737 // Phase capture is independent of OTEL — keep it available without
738 // requiring the OTEL_TEST_ENABLED gate so that the structured-output
739 // middleware spec works under any harness build configuration.
740 if (kind === 'phase') {
741 if (!testId) {
742 return new Response(
743 JSON.stringify({ error: 'testId query param required' }),
744 {
745 status: 400,
746 headers: { 'Content-Type': 'application/json' },
747 },
748 )
749 }
750 return new Response(JSON.stringify(getPhaseCapture(testId)), {
751 headers: { 'Content-Type': 'application/json' },
752 })
753 }
754​
755 // Memory capture — like phase capture, available without the OTEL gate.
756 if (kind === 'memory') {
757 if (!testId) {
758 return new Response(
759 JSON.stringify({ error: 'testId query param required' }),
760 { status: 400, headers: { 'Content-Type': 'application/json' } },
761 )
762 }
763 return new Response(JSON.stringify(getMemoryCapture(testId)), {
764 headers: { 'Content-Type': 'application/json' },
765 })
766 }
767​
768 // OTEL capture remains gated — the GET cannot act as an oracle in a
769 // production-like build.
770 if (!OTEL_TEST_ENABLED) {
771 return new Response(null, { status: 404 })
772 }
773 if (!testId) {
774 return new Response(
775 JSON.stringify({ error: 'testId query param required' }),
776 {
777 status: 400,
778 headers: { 'Content-Type': 'application/json' },
779 },
780 )
781 }
782 return new Response(JSON.stringify(getOtelCapture(testId)), {
783 headers: { 'Content-Type': 'application/json' },
784 })
785 },
786 },
787 },
788})