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

middleware-test.tsx

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