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

stream-debugger.tsx

759 lines23.3 KB

1import { createFileRoute, useSearch } from '@tanstack/react-router'
2import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
3import {
4 Check,
5 Copy,
6 FastForward,
7 RefreshCw,
8 RotateCcw,
9 SkipBack,
10 SkipForward,
11 Upload,
12} from 'lucide-react'
13import {
14 EventType,
15 StreamProcessor,
16 uiMessageToModelMessages,
17} from '@tanstack/ai'
18​
19import type {
20 AdapterYieldChunk,
21 ChunkRecording,
22 ProcessorResult,
23 UIMessage,
24} from '@tanstack/ai'
25​
26// Import sample traces
27import * as sampleTraces from '@/traces'
28​
29export const Route = createFileRoute('/stream-debugger')({
30 component: TestPanel,
31 validateSearch: (search: Record<string, unknown>) => {
32 return {
33 trace: (search.trace as string) || undefined,
34 }
35 },
36})
37​
38interface RecordedTrace {
39 id: string
40 filename: string
41 timestamp: string
42 provider: string
43 model: string
44 size: number
45 chunkCount: number
47​
48function TestPanel() {
49 const searchParams = useSearch({ from: '/stream-debugger' })
50 const [recording, setRecording] = useState<ChunkRecording | null>(null)
51 const [currentChunkIndex, setCurrentChunkIndex] = useState(-1)
52 const [uiMessage, setUIMessage] = useState<UIMessage | null>(null)
53 const [result, setResult] = useState<ProcessorResult | null>(null)
54 const [isDragging, setIsDragging] = useState(false)
55 const [selectedSample, setSelectedSample] = useState<string>('')
56 const [copied, setCopied] = useState(false)
57 const [recordedTraces, setRecordedTraces] = useState<Array<RecordedTrace>>([])
58 const fileInputRef = useRef<HTMLInputElement>(null)
59​
60 // Processor ref for step-through mode
61 const processorRef = useRef<StreamProcessor | null>(null)
62​
63 const sampleOptions = useMemo(() => Object.keys(sampleTraces), [])
64​
65 // Function to fetch recorded traces
66 const fetchRecordedTraces = useCallback(() => {
67 fetch('/api/list-traces')
68 .then((res) => res.json())
69 .then((data) => {
70 if (data.traces) {
71 setRecordedTraces(data.traces)
72 }
73 })
74 .catch((error) => {
75 console.error('[TestPanel] Failed to load trace list:', error)
76 })
77 }, [])
78​
79 // Fetch recorded traces on mount
80 useEffect(() => {
81 fetchRecordedTraces()
82 }, [fetchRecordedTraces])
83​
84 const resetState = useCallback(() => {
85 setCurrentChunkIndex(-1)
86 setUIMessage(null)
87 setResult(null)
88 processorRef.current = null
89 }, [])
90​
91 const createProcessor = useCallback(() => {
92 const processor = new StreamProcessor({
93 events: {
94 onMessagesChange: (messages: Array<UIMessage>) => {
95 // Get the assistant message (should be the last one)
96 const assistantMessage = messages.find((m) => m.role === 'assistant')
97 if (assistantMessage) {
98 setUIMessage(assistantMessage)
99 }
100 },
101 onStreamEnd: (message: UIMessage) => {
102 // Get text content from parts
103 const textParts = message.parts.filter((p) => p.type === 'text')
104 const content = textParts.map((p) => (p as any).content).join('')
105​
106 // Get tool calls from parts
107 const toolCallParts = message.parts.filter(
108 (p) => p.type === 'tool-call',
109 )
110 const toolCalls =
111 toolCallParts.length > 0
112 ? toolCallParts.map((p: any) => ({
113 id: p.id,
114 type: 'function' as const,
115 function: {
116 name: p.name,
117 arguments: p.arguments,
118 },
119 }))
120 : undefined
121​
122 setResult({
123 content,
124 toolCalls,
125 finishReason: null,
126 })
127 },
128 },
129 })
130​
131 // Start an assistant message using the new API
132 processor.startAssistantMessage()
133​
134 processorRef.current = processor
135 return processor
136 }, [])
137​
138 const loadRecording = useCallback(
139 (rec: ChunkRecording) => {
140 setRecording(rec)
141 resetState()
142 },
143 [resetState],
144 )
145​
146 const handleFileUpload = useCallback(
147 (file: File) => {
148 const reader = new FileReader()
149 reader.onload = (e) => {
150 try {
151 const data = JSON.parse(e.target?.result as string) as ChunkRecording
152 loadRecording(data)
153 setSelectedSample('')
154 } catch (err) {
155 console.error('Failed to parse JSON:', err)
156 alert('Invalid JSON file')
157 }
158 }
159 reader.readAsText(file)
160 },
161 [loadRecording],
162 )
163​
164 const handleDrop = useCallback(
165 (e: React.DragEvent) => {
166 e.preventDefault()
167 setIsDragging(false)
168 const file = e.dataTransfer.files[0]
169 if (file && file.type === 'application/json') {
170 handleFileUpload(file)
171 }
172 },
173 [handleFileUpload],
174 )
175​
176 const handleSampleSelect = useCallback(
177 (value: string) => {
178 setSelectedSample(value)
179​
180 if (!value) return
181​
182 // Check if it's a recorded trace (trace:id) or sample trace (sample:name)
183 if (value.startsWith('trace:')) {
184 const traceId = value.substring(6) // Remove "trace:" prefix
185​
186 // Load the trace from API
187 fetch(`/api/load-trace?id=${traceId}`)
188 .then((res) => {
189 if (!res.ok) {
190 throw new Error(`Failed to load trace: ${res.statusText}`)
191 }
192 return res.json()
193 })
194 .then((traceData) => {
195 const chunkRecording: ChunkRecording = {
196 version: '1.0',
197 timestamp: traceData.timestamp,
198 model: traceData.model,
199 provider: traceData.provider,
200 chunks: traceData.chunks,
201 }
202 loadRecording(chunkRecording)
203 })
204 .catch((error) => {
205 console.error('[TestPanel] Failed to load trace:', error)
206 alert(`Failed to load trace: ${error.message}`)
207 })
208 } else if (value.startsWith('sample:')) {
209 const sampleName = value.substring(7) // Remove "sample:" prefix
210 if (sampleTraces[sampleName as keyof typeof sampleTraces]) {
211 loadRecording(
212 sampleTraces[
213 sampleName as keyof typeof sampleTraces
214 ] as ChunkRecording,
215 )
216 }
217 }
218 },
219 [loadRecording],
220 )
221​
222 const stepForward = useCallback(() => {
223 if (!recording) return
224​
225 const nextIndex = currentChunkIndex + 1
226 if (nextIndex >= recording.chunks.length) return
227​
228 const processor = processorRef.current ?? createProcessor()
229​
230 const chunk = recording.chunks[nextIndex]?.chunk
231 if (chunk) {
232 processor.processChunk(chunk)
233 setCurrentChunkIndex(nextIndex)
234​
235 // Update result with current processor state
236 const state = processor.getState()
237​
238 // Convert toolCalls Map to array
239 const toolCallsArray = Array.from(state.toolCalls.values()).map((tc) => ({
240 id: tc.id,
241 type: 'function' as const,
242 function: {
243 name: tc.name,
244 arguments: tc.arguments,
245 },
246 }))
247​
248 setResult({
249 content: state.content,
250 toolCalls: toolCallsArray.length > 0 ? toolCallsArray : undefined,
251 finishReason: null,
252 })
253 }
254 }, [recording, currentChunkIndex, createProcessor])
255​
256 const stepBackward = useCallback(() => {
257 if (!recording || currentChunkIndex < 0) return
258​
259 // Replay from start to currentChunkIndex - 1
260 const targetIndex = currentChunkIndex - 1
261 resetState()
262​
263 if (targetIndex < 0) return
264​
265 const processor = createProcessor()
266 for (let i = 0; i <= targetIndex; i++) {
267 const chunk = recording.chunks[i]?.chunk
268 if (chunk) {
269 processor.processChunk(chunk)
270 }
271 }
272 setCurrentChunkIndex(targetIndex)
273​
274 // Update result with current processor state
275 const state = processor.getState()
276​
277 // Convert toolCalls Map to array
278 const toolCallsArray = Array.from(state.toolCalls.values()).map((tc) => ({
279 id: tc.id,
280 type: 'function' as const,
281 function: {
282 name: tc.name,
283 arguments: tc.arguments,
284 },
285 }))
286​
287 setResult({
288 content: state.content,
289 toolCalls: toolCallsArray.length > 0 ? toolCallsArray : undefined,
290 finishReason: null,
291 })
292 }, [recording, currentChunkIndex, createProcessor, resetState])
293​
294 const runAll = useCallback(async () => {
295 if (!recording) return
296​
297 resetState()
298 const processor = createProcessor()
299​
300 for (let i = 0; i < recording.chunks.length; i++) {
301 const chunk = recording.chunks[i]?.chunk
302 if (chunk) {
303 processor.processChunk(chunk)
304 setCurrentChunkIndex(i)
305​
306 // Update result with current processor state
307 const state = processor.getState()
308​
309 // Convert toolCalls Map to array
310 const toolCallsArray = Array.from(state.toolCalls.values()).map(
311 (tc) => ({
312 id: tc.id,
313 type: 'function' as const,
314 function: {
315 name: tc.name,
316 arguments: tc.arguments,
317 },
318 }),
319 )
320​
321 setResult({
322 content: state.content,
323 toolCalls: toolCallsArray.length > 0 ? toolCallsArray : undefined,
324 finishReason: null,
325 })
326​
327 // Small delay for visual effect
328 await new Promise((resolve) => setTimeout(resolve, 50))
329 }
330 }
331 }, [recording, createProcessor, resetState])
332​
333 const reset = useCallback(() => {
334 resetState()
335 }, [resetState])
336​
337 const copyForIDE = useCallback(() => {
338 if (!recording) return
339​
340 const report = {
341 sample: selectedSample || 'custom',
342 currentChunkIndex,
343 totalChunks: recording.chunks.length,
344 chunks: recording.chunks
345 .slice(0, currentChunkIndex + 1)
346 .map(({ chunk, index }) => ({
347 index,
348 type: chunk.type,
349 chunk,
350 })),
351 uiMessage,
352 modelMessage: uiMessage ? convertToModelMessage(uiMessage) : null,
353 processorState: processorRef.current?.getState(),
354 }
355​
356 const formatted = `## Stream Processing Debug Report
357​
358**Sample:** ${report.sample}
359**Progress:** ${currentChunkIndex + 1}/${report.totalChunks} chunks processed
360​
361### Chunks Processed
362\`\`\`json
363${JSON.stringify(report.chunks, null, 2)}
364\`\`\`
365​
366### UIMessage (Parsed)
367\`\`\`json
368${JSON.stringify(report.uiMessage, null, 2)}
369\`\`\`
370​
371### ModelMessage (for server)
372\`\`\`json
373${JSON.stringify(report.modelMessage, null, 2)}
374\`\`\`
375​
376### Raw Processor State
377\`\`\`json
378${JSON.stringify(report.processorState, null, 2)}
379\`\`\`
381​
382 navigator.clipboard.writeText(formatted).then(() => {
383 setCopied(true)
384 setTimeout(() => setCopied(false), 2000)
385 })
386 }, [recording, selectedSample, currentChunkIndex, uiMessage, result])
387​
388 // Load trace from query param
389 useEffect(() => {
390 if (searchParams.trace) {
391 // Reset state first
392 setCurrentChunkIndex(-1)
393 setUIMessage(null)
394 setResult(null)
395 processorRef.current = null
396​
397 // Set the dropdown to show this trace
398 setSelectedSample(`trace:${searchParams.trace}`)
399​
400 // Then load the trace
401 fetch(`/api/load-trace?id=${searchParams.trace}`)
402 .then((res) => {
403 if (!res.ok) {
404 throw new Error(`Failed to load trace: ${res.statusText}`)
405 }
406 return res.json()
407 })
408 .then((traceData) => {
409 // Convert trace data to ChunkRecording format
410 const chunkRecording: ChunkRecording = {
411 version: '1.0',
412 timestamp: traceData.timestamp,
413 model: traceData.model,
414 provider: traceData.provider,
415 chunks: traceData.chunks,
416 }
417 setRecording(chunkRecording)
418 })
419 .catch((error) => {
420 console.error('[TestPanel] Failed to load trace:', error)
421 alert(`Failed to load trace: ${error.message}`)
422 })
423 }
424 }, [searchParams.trace])
425​
426 return (
427 <div className="p-6 flex flex-col gap-6 h-[calc(100vh-88px)] bg-gray-900">
428 {/* Controls Row */}
429 <div className="flex gap-4 items-center">
430 {/* File Upload / Drop Zone */}
431 <div
432 className={`flex-1 border-2 border-dashed rounded-lg p-4 transition-all cursor-pointer
433 ${
434 isDragging
435 ? 'border-orange-500 bg-orange-500/20'
436 : 'border-gray-700 hover:border-gray-500'
437 }`}
438 onDragOver={(e) => {
439 e.preventDefault()
440 setIsDragging(true)
441 }}
442 onDragLeave={() => setIsDragging(false)}
443 onDrop={handleDrop}
444 onClick={() => fileInputRef.current?.click()}
445 >
446 <div className="flex items-center gap-3 text-gray-400">
447 <Upload className="w-5 h-5" />
448 <span>Drop trace JSON file or click to upload</span>
449 </div>
450 <input
451 ref={fileInputRef}
452 type="file"
453 accept=".json"
454 className="hidden"
455 onChange={(e) =>
456 e.target.files?.[0] && handleFileUpload(e.target.files[0])
457 }
458 />
459 </div>
460​
461 {/* Sample Selector */}
462 <div className="flex items-center gap-2">
463 <label className="text-sm text-gray-400">Load Trace:</label>
464 <select
465 value={selectedSample}
466 onChange={(e) => handleSampleSelect(e.target.value)}
467 className="bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm text-white min-w-[280px] focus:outline-none focus:ring-2 focus:ring-orange-500/50 hover:border-gray-600 transition-colors"
468 >
469 <option value="">Select a trace...</option>
470 {recordedTraces.length > 0 && (
471 <optgroup label="Recorded Traces">
472 {recordedTraces.map((trace) => (
473 <option key={trace.id} value={`trace:${trace.id}`}>
474 {trace.id} - {trace.provider}/{trace.model} (
475 {trace.chunkCount} chunks)
476 </option>
477 ))}
478 </optgroup>
479 )}
480 {sampleOptions.length > 0 && (
481 <optgroup label="Sample Traces">
482 {sampleOptions.map((name) => (
483 <option key={name} value={`sample:${name}`}>
484 {name}
485 </option>
486 ))}
487 </optgroup>
488 )}
489 </select>
490 <button
491 onClick={fetchRecordedTraces}
492 className="p-2 bg-gray-800 hover:bg-gray-700 border border-gray-700 rounded-lg text-white transition-colors"
493 title="Refresh trace list"
494 >
495 <RefreshCw className="w-4 h-4" />
496 </button>
497 </div>
498​
499 {/* Copy For IDE Button */}
500 <button
501 onClick={copyForIDE}
502 disabled={!recording || currentChunkIndex < 0}
503 className="flex items-center gap-2 px-4 py-2 bg-orange-600 hover:bg-orange-700 text-white rounded-lg disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
504 >
505 {copied ? (
506 <>
507 <Check className="w-4 h-4" />
508 <span>Copied!</span>
509 </>
510 ) : (
511 <>
512 <Copy className="w-4 h-4" />
513 <span>Copy For IDE</span>
514 </>
515 )}
516 </button>
517 </div>
518​
519 {/* Main Content */}
520 <div className="flex-1 grid grid-cols-2 gap-6 min-h-0">
521 {/* Left Panel - Raw Chunks */}
522 <div className="flex flex-col bg-gray-800 rounded-lg border border-gray-700 overflow-hidden">
523 <div className="px-4 py-3 border-b border-gray-700 flex items-center justify-between">
524 <h2 className="font-semibold text-white">
525 Raw Chunks {recording && `(${recording.chunks.length})`}
526 </h2>
527 <div className="flex items-center gap-1">
528 <button
529 onClick={stepBackward}
530 disabled={!recording || currentChunkIndex < 0}
531 className="p-2 rounded-lg hover:bg-gray-700 disabled:opacity-30 disabled:cursor-not-allowed text-gray-300 hover:text-white transition-colors"
532 title="Step Back"
533 >
534 <SkipBack className="w-4 h-4" />
535 </button>
536 <button
537 onClick={stepForward}
538 disabled={
539 !recording ||
540 currentChunkIndex >= (recording?.chunks.length ?? 0) - 1
541 }
542 className="p-2 rounded-lg hover:bg-gray-700 disabled:opacity-30 disabled:cursor-not-allowed text-gray-300 hover:text-white transition-colors"
543 title="Step Forward"
544 >
545 <SkipForward className="w-4 h-4" />
546 </button>
547 <button
548 onClick={runAll}
549 disabled={!recording}
550 className="p-2 rounded-lg hover:bg-gray-700 disabled:opacity-30 disabled:cursor-not-allowed text-gray-300 hover:text-white transition-colors"
551 title="Run All"
552 >
553 <FastForward className="w-4 h-4" />
554 </button>
555 <button
556 onClick={reset}
557 disabled={!recording}
558 className="p-2 rounded-lg hover:bg-gray-700 disabled:opacity-30 disabled:cursor-not-allowed text-gray-300 hover:text-white transition-colors"
559 title="Reset"
560 >
561 <RotateCcw className="w-4 h-4" />
562 </button>
563 </div>
564 </div>
565 <div className="flex-1 overflow-auto p-4 scrollbar-thin">
566 {recording ? (
567 <div className="space-y-2">
568 {recording.chunks.map(({ chunk }, arrayIndex) => (
569 <ChunkItem
570 key={arrayIndex}
571 chunk={chunk}
572 index={arrayIndex}
573 isActive={arrayIndex === currentChunkIndex}
574 isProcessed={arrayIndex <= currentChunkIndex}
575 />
576 ))}
577 </div>
578 ) : (
579 <div className="text-center text-gray-500 py-12">
580 Load a trace file to see chunks
581 </div>
582 )}
583 </div>
584 </div>
585​
586 {/* Right Panel - Parsed Output */}
587 <div className="flex flex-col gap-4 min-h-0">
588 {/* UIMessage */}
589 <div className="flex-1 bg-gray-800 rounded-lg border border-gray-700 overflow-hidden flex flex-col">
590 <div className="px-4 py-3 border-b border-gray-700">
591 <h2 className="font-semibold text-white">UIMessage (Parsed)</h2>
592 </div>
593 <div className="flex-1 overflow-auto p-4 scrollbar-thin">
594 {uiMessage ? (
595 <JsonView data={uiMessage} />
596 ) : (
597 <div className="text-center text-gray-500 py-12">
598 Process chunks to see UIMessage
599 </div>
600 )}
601 </div>
602 </div>
603​
604 {/* ModelMessage */}
605 <div className="flex-1 bg-gray-800 rounded-lg border border-gray-700 overflow-hidden flex flex-col">
606 <div className="px-4 py-3 border-b border-gray-700">
607 <h2 className="font-semibold text-white">
608 ModelMessage (for server)
609 </h2>
610 </div>
611 <div className="flex-1 overflow-auto p-4 scrollbar-thin">
612 {uiMessage ? (
613 <JsonView data={convertToModelMessage(uiMessage)} />
614 ) : (
615 <div className="text-center text-gray-500 py-12">
616 Process chunks to see ModelMessage
617 </div>
618 )}
619 </div>
620 </div>
621 </div>
622 </div>
623 </div>
624 )
626​
627function ChunkItem({
628 chunk,
629 index,
630 isActive,
631 isProcessed,
632}: {
633 chunk: AdapterYieldChunk
634 index: number
635 isActive: boolean
636 isProcessed: boolean
637}) {
638 const typeColors: Record<string, string> = {
639 [EventType.TEXT_MESSAGE_CONTENT]: 'text-green-400',
640 [EventType.TOOL_CALL_START]: 'text-blue-400',
641 [EventType.TOOL_CALL_ARGS]: 'text-blue-400',
642 [EventType.TOOL_CALL_END]: 'text-blue-400',
643 [EventType.TOOL_CALL_RESULT]: 'text-purple-400',
644 [EventType.RUN_FINISHED]: 'text-yellow-400',
645 [EventType.RUN_ERROR]: 'text-red-400',
646 [EventType.REASONING_MESSAGE_CONTENT]: 'text-cyan-400',
647 [EventType.CUSTOM]: 'text-orange-400',
648 }
649​
650 const getSummary = (chunk: AdapterYieldChunk): string => {
651 switch (chunk.type) {
652 case EventType.TEXT_MESSAGE_CONTENT:
653 return `δ="${chunk.delta?.slice(0, 30) ?? ''}${(chunk.delta?.length ?? 0) > 30 ? '...' : ''}"`
654 case EventType.TOOL_CALL_START:
655 return `${chunk.toolCallName}[${chunk.index ?? 0}]`
656 case EventType.TOOL_CALL_ARGS:
657 return `δ="${chunk.delta?.slice(0, 30) ?? ''}..."`
658 case EventType.TOOL_CALL_RESULT:
659 return `${chunk.toolCallId}`
660 case EventType.RUN_FINISHED:
661 return `${chunk.finishReason ?? ''}`
662 case EventType.REASONING_MESSAGE_CONTENT:
663 return `δ="${chunk.delta?.slice(0, 20) ?? ''}..."`
664 case EventType.RUN_ERROR:
665 return chunk.message?.slice(0, 30) ?? ''
666 default:
667 return ''
668 }
669 }
670​
671 return (
672 <div
673 className={`p-2 rounded-lg text-sm font-mono transition-all ${
674 isActive
675 ? 'bg-orange-500/20 border border-orange-500'
676 : isProcessed
677 ? 'bg-gray-700 opacity-60'
678 : 'bg-gray-900'
679 }`}
680 >
681 <div className="flex items-center gap-2">
682 <span className="text-gray-500 w-6">{index}</span>
683 <span className={typeColors[chunk.type] || 'text-gray-400'}>
684 {chunk.type}
685 </span>
686 <span className="text-gray-400 truncate">{getSummary(chunk)}</span>
687 </div>
688 </div>
689 )
691​
692function JsonView({ data }: { data: any }) {
693 const formatValue = (value: any, indent: number = 0): React.ReactNode => {
694 const spaces = ' '.repeat(indent)
695​
696 if (value === null) {
697 return <span className="json-null">null</span>
698 }
699 if (typeof value === 'boolean') {
700 return <span className="json-boolean">{String(value)}</span>
701 }
702 if (typeof value === 'number') {
703 return <span className="json-number">{value}</span>
704 }
705 if (typeof value === 'string') {
706 const escaped = value.replace(/"/g, '\\"').replace(/\n/g, '\\n')
707 return <span className="json-string">"{escaped}"</span>
708 }
709 if (Array.isArray(value)) {
710 if (value.length === 0) return '[]'
711 return (
712 <>
713 {'[\n'}
714 {value.map((item, i) => (
715 <span key={i}>
716 {spaces} {formatValue(item, indent + 1)}
717 {i < value.length - 1 ? ',' : ''}
718 {'\n'}
719 </span>
720 ))}
721 {spaces}]
722 </>
723 )
724 }
725 if (typeof value === 'object') {
726 const keys = Object.keys(value)
727 if (keys.length === 0) return '{}'
728 return (
729 <>
730 {'{\n'}
731 {keys.map((key, i) => (
732 <span key={key}>
733 {spaces} <span className="json-key">"{key}"</span>:{' '}
734 {formatValue(value[key], indent + 1)}
735 {i < keys.length - 1 ? ',' : ''}
736 {'\n'}
737 </span>
738 ))}
739 {spaces}
740 {'}'}
741 </>
742 )
743 }
744 return String(value)
745 }
746​
747 return (
748 <pre className="text-sm whitespace-pre-wrap break-all text-gray-100 font-mono">
749 {formatValue(data)}
750 </pre>
751 )
753​
754function convertToModelMessage(uiMessage: UIMessage): any {
755 // Use the actual uiMessageToModelMessages utility from @tanstack/ai-client
756 const modelMessages = uiMessageToModelMessages(uiMessage)
757 // Return the first message (the assistant message)
758 return modelMessages[0] || null