Open History to see the last commit
1import { useMemo, useRef, useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import {
4 useChat,
5 fetchServerSentEvents,
6 localStoragePersistence,
7} from '@tanstack/ai-react'
8import { clientTools } from '@tanstack/ai-client'
9import { parseAimockPort } from '@/lib/devtools-test'
10import {
11 deleteReviewTool,
12 renderReviewTool,
13 reviewPlan,
14} from '@/lib/generic-middleware-interrupts'
15import { clientContextToolDefinition } from '@/lib/middleware-test-tools'
16
17const MIDDLEWARE_MODES = [
18 { id: 'none', label: 'No Middleware' },
19 { id: 'chunk-transform', label: 'Chunk Transform (prefix text)' },
20 { id: 'tool-skip', label: 'Tool Skip (skip with custom result)' },
21 { id: 'capability', label: 'Capability (provide/consume prefix)' },
22 { id: 'phase-recorder', label: 'Phase Recorder (capture phase + chunks)' },
23 { id: 'otel', label: 'OpenTelemetry (capture spans/metrics)' },
24 { id: 'memory', label: 'Memory (recall/save)' },
25 { id: 'generic-lifecycle', label: 'Generic Interrupt Lifecycle' },
26] as const
27
28const genericPersistence = localStoragePersistence()
29
30interface PhaseCaptureSnapshot {
31 phases: Array<string>
32 onFinishCount: number
33 yieldedChunks: Array<{ type: string }>
34}
35
36const EMPTY_PHASE_CAPTURE: PhaseCaptureSnapshot = {
37 phases: [],
38 onFinishCount: 0,
39 yieldedChunks: [],
40}
41
42/**
43 * Defensively coerce the `/api/middleware-test?kind=phase` response into a
44 * `PhaseCaptureSnapshot`. The server returns a well-typed object, but this
45 * page can't import server-only types and we want zero `as` casts on the
46 * untrusted parse, so we validate each field shape before reading it.
47 */
48function toPhaseCapture(raw: unknown): PhaseCaptureSnapshot {
49 if (!raw || typeof raw !== 'object') return EMPTY_PHASE_CAPTURE
50 const obj: Record<string, unknown> = { ...raw }
51 const phasesRaw = obj.phases
52 const onFinishRaw = obj.onFinishCount
53 const yieldedRaw = obj.yieldedChunks
54 const phases =
55 Array.isArray(phasesRaw) && phasesRaw.every((p) => typeof p === 'string')
56 ? phasesRaw
57 : []
58 const onFinishCount =
59 typeof onFinishRaw === 'number' && Number.isFinite(onFinishRaw)
60 ? onFinishRaw
61 : 0
62 const yieldedChunks = Array.isArray(yieldedRaw)
63 ? yieldedRaw
64 .map((c) => {
65 if (!c || typeof c !== 'object') return null
66 const inner: Record<string, unknown> = { ...c }
67 const t = inner.type
68 return typeof t === 'string' ? { type: t } : null
69 })
70 .filter((c): c is { type: string } => c !== null)
71 : []
72 return { phases, onFinishCount, yieldedChunks }
73}
74
75export const Route = createFileRoute('/middleware-test')({
76 component: MiddlewareTestPage,
77 validateSearch: (search: Record<string, unknown>) => {
78 return {
79 testId: typeof search.testId === 'string' ? search.testId : undefined,
80 aimockPort: parseAimockPort(search.aimockPort),
81 // `provider` / `model` are forwarded to the server route so the
82 // structured-output × middleware spec can exercise both the
83 // native-combined-mode path (modern openai / claude 4.5+) and the
84 // legacy finalization path (claude 3.7, etc.) — see #605.
85 provider:
86 typeof search.provider === 'string' ? search.provider : undefined,
87 model: typeof search.model === 'string' ? search.model : undefined,
88 scenario:
89 typeof search.scenario === 'string' ? search.scenario : undefined,
90 middlewareMode:
91 typeof search.middlewareMode === 'string'
92 ? search.middlewareMode
93 : undefined,
94 }
95 },
96})
97
98function MiddlewareTestPage() {
99 const { testId, aimockPort, provider, model, ...searchSelection } =
100 Route.useSearch()
101 const [scenario, setScenario] = useState(
102 searchSelection.scenario ?? 'basic-text',
103 )
104 const [middlewareMode, setMiddlewareMode] = useState(
105 searchSelection.middlewareMode ?? 'none',
106 )
107 const [testComplete, setTestComplete] = useState(false)
108 const [phaseCapture, setPhaseCapture] =
109 useState<PhaseCaptureSnapshot>(EMPTY_PHASE_CAPTURE)
110 const [memoryCapture, setMemoryCapture] = useState<{
111 configs: Array<{ systemPrompts: Array<string>; toolNames: Array<string> }>
112 saveCount: number
113 }>({ configs: [], saveCount: 0 })
114 const [clientToolExecutions, setClientToolExecutions] = useState(0)
115 const [clientToolWaiting, setClientToolWaiting] = useState(false)
116 const clientToolResolver = useRef<
117 ((value: { context: string }) => void) | null
118 >(null)
119 const [clientContextTool] = useState(() =>
120 clientContextToolDefinition.client(
121 () =>
122 new Promise<{ context: string }>((resolve) => {
123 clientToolResolver.current = resolve
124 setClientToolWaiting(true)
125 }),
126 ),
127 )
128
129 const clientToolList = useMemo(
130 () =>
131 clientTools(
132 deleteReviewTool.client(),
133 renderReviewTool.client(async ({ reviewId }) => {
134 setClientToolExecutions((count) => count + 1)
135 return { rendered: true, reviewId }
136 }),
137 clientContextTool,
138 ),
139 [clientContextTool],
140 )
141
142 const { messages, sendMessage, isLoading, error, interrupts } = useChat<
143 typeof clientToolList,
144 undefined,
145 unknown,
146 readonly [typeof reviewPlan]
147 >({
148 threadId: `mw-test-${testId ?? 'manual'}-${scenario}-${middlewareMode}-${provider ?? 'openai'}-${model ?? 'default'}`,
149 connection: fetchServerSentEvents('/api/middleware-test'),
150 body: { scenario, middlewareMode, testId, aimockPort, provider, model },
151 tools: clientToolList,
152 interrupts: [reviewPlan],
153 persistence:
154 middlewareMode === 'generic-lifecycle' ? genericPersistence : undefined,
155 onFinish: () => {
156 // For phase-recorder mode the spec reads `#mw-phases-json` /
157 // `#mw-onfinish-count` / `#mw-yielded-chunks-json` AFTER
158 // `data-test-complete=true`. Pull the server-side capture before
159 // flipping the completion flag so the DOM is consistent when the
160 // spec's `waitForFunction` returns.
161 if (middlewareMode === 'phase-recorder' && testId) {
162 void fetch(
163 `/api/middleware-test?testId=${encodeURIComponent(testId)}&kind=phase`,
164 )
165 .then((res) => (res.ok ? res.json() : EMPTY_PHASE_CAPTURE))
166 .then((data) => {
167 setPhaseCapture(toPhaseCapture(data))
168 setTestComplete(true)
169 })
170 .catch(() => {
171 setPhaseCapture(EMPTY_PHASE_CAPTURE)
172 setTestComplete(true)
173 })
174 return
175 }
176 if (middlewareMode === 'memory' && testId) {
177 void fetch(
178 `/api/middleware-test?testId=${encodeURIComponent(testId)}&kind=memory`,
179 )
180 .then((res) => (res.ok ? res.json() : { configs: [], saveCount: 0 }))
181 .then((data) => {
182 setMemoryCapture(data)
183 setTestComplete(true)
184 })
185 .catch(() => {
186 setMemoryCapture({ configs: [], saveCount: 0 })
187 setTestComplete(true)
188 })
189 return
190 }
191 setTestComplete(true)
192 },
193 })
194
195 const handleRun = () => {
196 setTestComplete(false)
197 setPhaseCapture(EMPTY_PHASE_CAPTURE)
198 setClientToolExecutions(0)
199 setClientToolWaiting(false)
200 clientToolResolver.current = null
201 sendMessage(`[${scenario}] run test`)
202 }
203
204 const handleResolveClientTool = () => {
205 const resolve = clientToolResolver.current
206 if (!resolve) return
207 clientToolResolver.current = null
208 setClientToolWaiting(false)
209 resolve({ context: 'client-result' })
210 }
211
212 type ActiveInterrupt = (typeof interrupts)[number]
213 const reviewInterrupts = interrupts.filter(
214 (
215 interrupt,
216 ): interrupt is Extract<ActiveInterrupt, { definitionId: 'review-plan' }> =>
217 interrupt.kind === 'generic' &&
218 'definitionId' in interrupt &&
219 interrupt.definitionId === reviewPlan.id,
220 )
221 const approvalInterrupts = interrupts.filter(
222 (
223 interrupt,
224 ): interrupt is Extract<ActiveInterrupt, { kind: 'tool-approval' }> =>
225 interrupt.kind === 'tool-approval',
226 )
227
228 return (
229 <div
230 style={{
231 padding: '20px',
232 fontFamily: 'system-ui',
233 color: '#e2e8f0',
234 }}
235 >
236 <h1>Middleware Test</h1>
237
238 <div style={{ marginBottom: '10px' }}>
239 <label>Scenario: </label>
240 <select
241 id="mw-scenario-select"
242 value={scenario}
243 onChange={(e) => setScenario(e.target.value)}
244 style={{
245 backgroundColor: '#1e293b',
246 color: '#e2e8f0',
247 border: '1px solid #475569',
248 borderRadius: '4px',
249 padding: '6px',
250 }}
251 >
252 <option value="basic-text">Basic Text</option>
253 <option value="capability">Capability</option>
254 <option value="with-tool">With Tool</option>
255 <option value="run-error">Run Error</option>
256 <option value="structured-output">Structured Output</option>
257 <option value="structured-output-stream">
258 Structured Output (Stream)
259 </option>
260 <option value="structured-client-tool-wait">
261 Structured Output + Client Tool Wait
262 </option>
263 <option value="generic-before-model">Generic Before Model</option>
264 <option value="generic-after-model">Generic After Model</option>
265 <option value="generic-before-tools-continue">
266 Generic Before Tools Continue
267 </option>
268 <option value="generic-before-tools-cancel">
269 Generic Before Tools Cancel
270 </option>
271 <option value="generic-before-tools-stop">
272 Generic Before Tools Stop
273 </option>
274 <option value="generic-after-tools">Generic After Tools</option>
275 </select>
276 </div>
277
278 <div style={{ marginBottom: '10px' }}>
279 <label>Middleware: </label>
280 <select
281 id="mw-mode-select"
282 value={middlewareMode}
283 onChange={(e) => setMiddlewareMode(e.target.value)}
284 style={{
285 backgroundColor: '#1e293b',
286 color: '#e2e8f0',
287 border: '1px solid #475569',
288 borderRadius: '4px',
289 padding: '6px',
290 }}
291 >
292 {MIDDLEWARE_MODES.map((m) => (
293 <option key={m.id} value={m.id}>
294 {m.label}
295 </option>
296 ))}
297 </select>
298 </div>
299
300 <button
301 id="mw-run-button"
302 onClick={handleRun}
303 disabled={isLoading}
304 style={{
305 padding: '10px 20px',
306 fontSize: '14px',
307 backgroundColor: '#007bff',
308 color: 'white',
309 border: 'none',
310 borderRadius: '4px',
311 cursor: isLoading ? 'not-allowed' : 'pointer',
312 opacity: isLoading ? 0.7 : 1,
313 }}
314 >
315 Run Test
316 </button>
317
318 <button
319 id="mw-client-tool-resolve"
320 onClick={handleResolveClientTool}
321 disabled={!clientToolWaiting}
322 style={{
323 marginLeft: '10px',
324 padding: '10px 20px',
325 fontSize: '14px',
326 backgroundColor: '#16a34a',
327 color: 'white',
328 border: 'none',
329 borderRadius: '4px',
330 cursor: clientToolWaiting ? 'pointer' : 'not-allowed',
331 opacity: clientToolWaiting ? 1 : 0.7,
332 }}
333 >
334 Resolve Client Tool
335 </button>
336
337 {reviewInterrupts.map((interrupt) => (
338 <div
339 key={interrupt.id}
340 data-testid="generic-review-plan"
341 data-definition-id={interrupt.definitionId}
342 data-payload={JSON.stringify(interrupt.payload)}
343 >
344 <span>{interrupt.message}</span>
345 <button
346 data-testid="resolve-review-plan"
347 onClick={() =>
348 interrupt.resolveInterrupt({
349 approved: true,
350 note: 'approved in middleware e2e',
351 })
352 }
353 >
354 Resolve review
355 </button>
356 <button
357 data-testid="cancel-review-plan"
358 onClick={() => interrupt.cancel()}
359 >
360 Cancel review
361 </button>
362 </div>
363 ))}
364
365 {approvalInterrupts.map((interrupt) => (
366 <div key={interrupt.id} data-testid="delete-review-approval">
367 <button
368 data-testid="approve-delete-review"
369 onClick={() => interrupt.resolveInterrupt(true)}
370 >
371 Approve tool
372 </button>
373 <button
374 data-testid="reject-delete-review"
375 onClick={() => interrupt.resolveInterrupt(false)}
376 >
377 Reject tool
378 </button>
379 </div>
380 ))}
381
382 <pre
383 id="mw-messages-json"
384 style={{
385 marginTop: '20px',
386 background: 'rgba(15, 23, 42, 0.6)',
387 border: '1px solid rgba(100, 116, 139, 0.3)',
388 borderRadius: '4px',
389 color: '#94a3b8',
390 padding: '10px',
391 maxHeight: '400px',
392 overflow: 'auto',
393 }}
394 >
395 {JSON.stringify(messages, null, 2)}
396 </pre>
397
398 {/*
399 Phase-recorder surfaces. These are always rendered so the Playwright
400 spec can do a flat `.textContent()` read without conditional waits;
401 they're empty/zeroed for runs that don't use `phase-recorder` mode.
402 */}
403 <pre id="mw-error" style={{ display: 'none' }}>
404 {error?.message ?? ''}
405 </pre>
406 <pre id="mw-phases-json" style={{ display: 'none' }}>
407 {JSON.stringify(phaseCapture.phases)}
408 </pre>
409 <span id="mw-onfinish-count" style={{ display: 'none' }}>
410 {phaseCapture.onFinishCount}
411 </span>
412 <pre id="mw-yielded-chunks-json" style={{ display: 'none' }}>
413 {JSON.stringify(phaseCapture.yieldedChunks)}
414 </pre>
415 <pre id="mw-memory-json" style={{ display: 'none' }}>
416 {JSON.stringify(memoryCapture)}
417 </pre>
418
419 <div
420 id="mw-metadata"
421 style={{ display: 'none' }}
422 data-is-loading={isLoading.toString()}
423 data-test-complete={testComplete.toString()}
424 data-client-tool-waiting={clientToolWaiting.toString()}
425 data-message-count={messages.length}
426 data-interrupt-count={interrupts.length}
427 data-client-tool-executions={clientToolExecutions}
428 />
429 </div>
430 )
431}