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