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

middleware-test.tsx

434 lines14.2 KB

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 }>
37​
38const EMPTY_PHASE_CAPTURE: PhaseCaptureSnapshot = {
39 phases: [],
40 onFinishCount: 0,
41 yieldedChunks: [],
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 }
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 body: { scenario, middlewareMode, testId, aimockPort, provider, model },
153 tools: clientToolList,
154 interrupts: [reviewPlan],
155 persistence:
156 middlewareMode === 'generic-lifecycle' ? genericPersistence : undefined,
157 onFinish: () => {
158 // For phase-recorder mode the spec reads `#mw-phases-json` /
159 // `#mw-onfinish-count` / `#mw-yielded-chunks-json` AFTER
160 // `data-test-complete=true`. Pull the server-side capture before
161 // flipping the completion flag so the DOM is consistent when the
162 // spec's `waitForFunction` returns.
163 if (middlewareMode === 'phase-recorder' && testId) {
164 void fetch(
165 `/api/middleware-test?testId=${encodeURIComponent(testId)}&kind=phase`,
166 )
167 .then((res) => (res.ok ? res.json() : EMPTY_PHASE_CAPTURE))
168 .then((data) => {
169 setPhaseCapture(toPhaseCapture(data))
170 setTestComplete(true)
171 })
172 .catch(() => {
173 setPhaseCapture(EMPTY_PHASE_CAPTURE)
174 setTestComplete(true)
175 })
176 return
177 }
178 if (middlewareMode === 'memory' && testId) {
179 void fetch(
180 `/api/middleware-test?testId=${encodeURIComponent(testId)}&kind=memory`,
181 )
182 .then((res) => (res.ok ? res.json() : { configs: [], saveCount: 0 }))
183 .then((data) => {
184 setMemoryCapture(data)
185 setTestComplete(true)
186 })
187 .catch(() => {
188 setMemoryCapture({ configs: [], saveCount: 0 })
189 setTestComplete(true)
190 })
191 return
192 }
193 setTestComplete(true)
194 },
195 })
196​
197 const handleRun = () => {
198 setTestComplete(false)
199 setPhaseCapture(EMPTY_PHASE_CAPTURE)
200 setClientToolExecutions(0)
201 setClientToolWaiting(false)
202 clientToolResolver.current = null
203 sendMessage(`[${scenario}] run test`)
204 }
205​
206 const handleResolveClientTool = () => {
207 const resolve = clientToolResolver.current
208 if (!resolve) return
209 clientToolResolver.current = null
210 setClientToolWaiting(false)
211 resolve({ context: 'client-result' })
212 }
213​
214 type ActiveInterrupt = (typeof interrupts)[number]
215 const reviewInterrupts = interrupts.filter(
216 (
217 interrupt,
218 ): interrupt is Extract<ActiveInterrupt, { definitionId: 'review-plan' }> =>
219 interrupt.kind === 'generic' &&
220 'definitionId' in interrupt &&
221 interrupt.definitionId === reviewPlan.id,
222 )
223 const approvalInterrupts = interrupts.filter(
224 (
225 interrupt,
226 ): interrupt is Extract<ActiveInterrupt, { kind: 'tool-approval' }> =>
227 interrupt.kind === 'tool-approval',
228 )
229​
230 return (
231 <div
232 style={{
233 padding: '20px',
234 fontFamily: 'system-ui',
235 color: '#e2e8f0',
236 }}
237 >
238 <h1>Middleware Test</h1>
239​
240 <div style={{ marginBottom: '10px' }}>
241 <label>Scenario: </label>
242 <select
243 id="mw-scenario-select"
244 value={scenario}
245 onChange={(e) => setScenario(e.target.value)}
246 style={{
247 backgroundColor: '#1e293b',
248 color: '#e2e8f0',
249 border: '1px solid #475569',
250 borderRadius: '4px',
251 padding: '6px',
252 }}
253 >
254 <option value="basic-text">Basic Text</option>
255 <option value="capability">Capability</option>
256 <option value="with-tool">With Tool</option>
257 <option value="raw-tool-args">Raw Tool Args</option>
258 <option value="run-error">Run Error</option>
259 <option value="structured-output">Structured Output</option>
260 <option value="structured-output-stream">
261 Structured Output (Stream)
262 </option>
263 <option value="structured-client-tool-wait">
264 Structured Output + Client Tool Wait
265 </option>
266 <option value="generic-before-model">Generic Before Model</option>
267 <option value="generic-after-model">Generic After Model</option>
268 <option value="generic-before-tools-continue">
269 Generic Before Tools Continue
270 </option>
271 <option value="generic-before-tools-cancel">
272 Generic Before Tools Cancel
273 </option>
274 <option value="generic-before-tools-stop">
275 Generic Before Tools Stop
276 </option>
277 <option value="generic-after-tools">Generic After Tools</option>
278 </select>
279 </div>
280​
281 <div style={{ marginBottom: '10px' }}>
282 <label>Middleware: </label>
283 <select
284 id="mw-mode-select"
285 value={middlewareMode}
286 onChange={(e) => setMiddlewareMode(e.target.value)}
287 style={{
288 backgroundColor: '#1e293b',
289 color: '#e2e8f0',
290 border: '1px solid #475569',
291 borderRadius: '4px',
292 padding: '6px',
293 }}
294 >
295 {MIDDLEWARE_MODES.map((m) => (
296 <option key={m.id} value={m.id}>
297 {m.label}
298 </option>
299 ))}
300 </select>
301 </div>
302​
303 <button
304 id="mw-run-button"
305 onClick={handleRun}
306 disabled={isLoading}
307 style={{
308 padding: '10px 20px',
309 fontSize: '14px',
310 backgroundColor: '#007bff',
311 color: 'white',
312 border: 'none',
313 borderRadius: '4px',
314 cursor: isLoading ? 'not-allowed' : 'pointer',
315 opacity: isLoading ? 0.7 : 1,
316 }}
317 >
318 Run Test
319 </button>
320​
321 <button
322 id="mw-client-tool-resolve"
323 onClick={handleResolveClientTool}
324 disabled={!clientToolWaiting}
325 style={{
326 marginLeft: '10px',
327 padding: '10px 20px',
328 fontSize: '14px',
329 backgroundColor: '#16a34a',
330 color: 'white',
331 border: 'none',
332 borderRadius: '4px',
333 cursor: clientToolWaiting ? 'pointer' : 'not-allowed',
334 opacity: clientToolWaiting ? 1 : 0.7,
335 }}
336 >
337 Resolve Client Tool
338 </button>
339​
340 {reviewInterrupts.map((interrupt) => (
341 <div
342 key={interrupt.id}
343 data-testid="generic-review-plan"
344 data-definition-id={interrupt.definitionId}
345 data-payload={JSON.stringify(interrupt.payload)}
346 >
347 <span>{interrupt.message}</span>
348 <button
349 data-testid="resolve-review-plan"
350 onClick={() =>
351 interrupt.resolveInterrupt({
352 approved: true,
353 note: 'approved in middleware e2e',
354 })
355 }
356 >
357 Resolve review
358 </button>
359 <button
360 data-testid="cancel-review-plan"
361 onClick={() => interrupt.cancel()}
362 >
363 Cancel review
364 </button>
365 </div>
366 ))}
367​
368 {approvalInterrupts.map((interrupt) => (
369 <div key={interrupt.id} data-testid="delete-review-approval">
370 <button
371 data-testid="approve-delete-review"
372 onClick={() => interrupt.resolveInterrupt(true)}
373 >
374 Approve tool
375 </button>
376 <button
377 data-testid="reject-delete-review"
378 onClick={() => interrupt.resolveInterrupt(false)}
379 >
380 Reject tool
381 </button>
382 </div>
383 ))}
384​
385 <pre
386 id="mw-messages-json"
387 style={{
388 marginTop: '20px',
389 background: 'rgba(15, 23, 42, 0.6)',
390 border: '1px solid rgba(100, 116, 139, 0.3)',
391 borderRadius: '4px',
392 color: '#94a3b8',
393 padding: '10px',
394 maxHeight: '400px',
395 overflow: 'auto',
396 }}
397 >
398 {JSON.stringify(messages, null, 2)}
399 </pre>
400​
401 {/*
402 Phase-recorder surfaces. These are always rendered so the Playwright
403 spec can do a flat `.textContent()` read without conditional waits;
404 they're empty/zeroed for runs that don't use `phase-recorder` mode.
405 */}
406 <pre id="mw-error" style={{ display: 'none' }}>
407 {error?.message ?? ''}
408 </pre>
409 <pre id="mw-phases-json" style={{ display: 'none' }}>
410 {JSON.stringify(phaseCapture.phases)}
411 </pre>
412 <span id="mw-onfinish-count" style={{ display: 'none' }}>
413 {phaseCapture.onFinishCount}
414 </span>
415 <pre id="mw-yielded-chunks-json" style={{ display: 'none' }}>
416 {JSON.stringify(phaseCapture.yieldedChunks)}
417 </pre>
418 <pre id="mw-memory-json" style={{ display: 'none' }}>
419 {JSON.stringify(memoryCapture)}
420 </pre>
421​
422 <div
423 id="mw-metadata"
424 style={{ display: 'none' }}
425 data-is-loading={isLoading.toString()}
426 data-test-complete={testComplete.toString()}
427 data-client-tool-waiting={clientToolWaiting.toString()}
428 data-message-count={messages.length}
429 data-interrupt-count={interrupts.length}
430 data-client-tool-executions={clientToolExecutions}
431 />
432 </div>
433 )