-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathDebug.tsx
More file actions
666 lines (629 loc) · 23.9 KB
/
Copy pathDebug.tsx
File metadata and controls
666 lines (629 loc) · 23.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { api } from '../lib/api';
import Editor from '@monaco-editor/react';
import {
RefreshCw,
Clock,
Database,
ChevronDown,
ChevronRight,
Copy,
Check,
Trash2,
Download,
Filter,
X,
Minimize2,
Maximize2,
} from 'lucide-react';
import { clsx } from 'clsx';
import { Button } from '../components/ui/Button';
import { Modal } from '../components/ui/Modal';
import { PageHeader } from '../components/layout/PageHeader';
import { useLocation } from 'react-router-dom';
import type { Provider } from '../lib/api';
import { isClipboardAvailable, copyToClipboard } from '../lib/clipboard';
import { useAuth } from '../contexts/AuthContext';
interface DebugLogMeta {
requestId: string;
createdAt: number;
}
interface DebugLogDetail extends DebugLogMeta {
rawRequest: string | object;
transformedRequest: string | object;
rawResponse: string | object;
transformedResponse: string | object;
rawResponseSnapshot?: string | object;
transformedResponseSnapshot?: string | object;
responseHeaders?: string | object;
}
export const Debug: React.FC = () => {
const location = useLocation();
const { isAdmin, principal } = useAuth();
const [logs, setLogs] = useState<DebugLogMeta[]>([]);
const [selectedId, setSelectedId] = useState<string | null>(null);
const [detail, setDetail] = useState<DebugLogDetail | null>(null);
const [loading, setLoading] = useState(false);
const [loadingDetail, setLoadingDetail] = useState(false);
const [copiedAll, setCopiedAll] = useState(false);
// Provider filter state
const [providers, setProviders] = useState<Provider[]>([]);
const [debugEnabled, setDebugEnabled] = useState(false);
const [selectedProviders, setSelectedProviders] = useState<string[]>([]);
const [isFilterOpen, setIsFilterOpen] = useState(false);
// Delete Modal State
const [isDeleteAllModalOpen, setIsDeleteAllModalOpen] = useState(false);
const [isSingleDeleteModalOpen, setIsSingleDeleteModalOpen] = useState(false);
const [selectedLogIdForDelete, setSelectedLogIdForDelete] = useState<string | null>(null);
const [isDeleting, setIsDeleting] = useState(false);
useEffect(() => {
if (location.state?.requestId) {
setSelectedId(location.state.requestId);
// clear state so it doesn't persist on refresh if we wanted, but standard behavior is fine
}
}, [location.state]);
const fetchLogs = async () => {
setLoading(true);
try {
const data = await api.getDebugLogs(50);
setLogs(data);
if (data.length > 0 && !selectedId && !location.state?.requestId) {
// Optionally select first? No, let user choose.
}
} finally {
setLoading(false);
}
};
const handleDeleteAll = () => {
setIsDeleteAllModalOpen(true);
};
const confirmDeleteAll = async () => {
setIsDeleting(true);
try {
await api.deleteAllDebugLogs();
await fetchLogs();
setSelectedId(null);
setDetail(null);
setIsDeleteAllModalOpen(false);
} finally {
setIsDeleting(false);
}
};
const handleDelete = (e: React.MouseEvent, requestId: string) => {
e.stopPropagation();
setSelectedLogIdForDelete(requestId);
setIsSingleDeleteModalOpen(true);
};
const confirmDeleteSingle = async () => {
if (!selectedLogIdForDelete) return;
setIsDeleting(true);
try {
await api.deleteDebugLog(selectedLogIdForDelete);
setLogs(logs.filter((l) => l.requestId !== selectedLogIdForDelete));
if (selectedId === selectedLogIdForDelete) {
setSelectedId(null);
setDetail(null);
}
setIsSingleDeleteModalOpen(false);
setSelectedLogIdForDelete(null);
} catch (e) {
console.error('Failed to delete log', e);
} finally {
setIsDeleting(false);
}
};
useEffect(() => {
fetchLogs();
const interval = setInterval(fetchLogs, 10000); // Auto-refresh list
return () => clearInterval(interval);
}, []);
useEffect(() => {
if (selectedId) {
setLoadingDetail(true);
api.getDebugLogDetail(selectedId).then((data) => {
setDetail(data);
setLoadingDetail(false);
});
} else {
setDetail(null);
}
}, [selectedId]);
useEffect(() => {
setCopiedAll(false);
}, [detail?.requestId]);
// Fetch providers and debug status
useEffect(() => {
const fetchProvidersAndStatus = async () => {
try {
const [providersData, debugStatus] = await Promise.all([
api.getProviders(),
api.getDebugMode(),
]);
setProviders(providersData);
setDebugEnabled(debugStatus.enabled);
setSelectedProviders(debugStatus.providers || []);
} catch (e) {
console.error('Failed to fetch providers or debug status', e);
}
};
fetchProvidersAndStatus();
}, []);
// Close filter dropdown when clicking outside
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
const target = event.target as HTMLElement;
if (!target.closest('.provider-filter-dropdown')) {
setIsFilterOpen(false);
}
};
if (isFilterOpen) {
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}
}, [isFilterOpen]);
const handleProviderToggle = (providerId: string) => {
setSelectedProviders((prev) => {
const newSelection = prev.includes(providerId)
? prev.filter((id) => id !== providerId)
: [...prev, providerId];
return newSelection;
});
};
const applyProviderFilter = async () => {
try {
await api.setDebugMode(debugEnabled, selectedProviders.length > 0 ? selectedProviders : null);
setIsFilterOpen(false);
} catch (e) {
console.error('Failed to apply provider filter', e);
}
};
const clearProviderFilter = async () => {
setSelectedProviders([]);
try {
await api.setDebugMode(debugEnabled, null);
} catch (e) {
console.error('Failed to clear provider filter', e);
}
};
const formatContent = (content: any) => {
if (!content) return '';
if (typeof content === 'string') {
try {
return JSON.stringify(JSON.parse(content), null, 2);
} catch {
return content;
}
}
return JSON.stringify(content, null, 2);
};
const normalizeExportContent = (content: string | object | null | undefined) => {
if (content === undefined) return undefined;
if (content === null) return null;
if (typeof content === 'string') {
try {
return JSON.parse(content);
} catch {
return content;
}
}
return content;
};
const exportContent = useMemo(() => {
if (!detail) return '';
const payload = {
requestId: detail.requestId,
createdAt: detail.createdAt,
rawRequest: normalizeExportContent(detail.rawRequest),
transformedRequest: normalizeExportContent(detail.transformedRequest),
rawResponse: normalizeExportContent(detail.rawResponse),
rawResponseSnapshot: normalizeExportContent(detail.rawResponseSnapshot),
transformedResponse: normalizeExportContent(detail.transformedResponse),
transformedResponseSnapshot: normalizeExportContent(detail.transformedResponseSnapshot),
responseHeaders: normalizeExportContent(detail.responseHeaders),
};
return JSON.stringify(payload, null, 2);
}, [detail]);
const handleCopyAll = async () => {
if (!exportContent || !isClipboardAvailable()) return;
const success = await copyToClipboard(exportContent);
if (success) {
setCopiedAll(true);
setTimeout(() => setCopiedAll(false), 2000);
}
};
const handleDownloadAll = () => {
if (!detail || !exportContent) return;
const blob = new Blob([exportContent], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
const timestamp = new Date(detail.createdAt).toISOString().replace(/[:.]/g, '-');
link.href = url;
link.download = `debug-trace-${detail.requestId}-${timestamp}.json`;
link.click();
URL.revokeObjectURL(url);
};
return (
<div className="flex flex-col min-h-[calc(100vh-3rem)]">
<div className="shrink-0">
<PageHeader
title="Traces"
subtitle={
principal?.role === 'limited' && principal.keyName
? `Traces for key "${principal.keyName}" only. Toggle capture in My Key.`
: 'Distributed spans · OTLP'
}
actions={
<>
{/* Provider Filter — admin-only: the global filter affects all users. */}
{isAdmin && (
<div className="relative provider-filter-dropdown">
<Button
variant="secondary"
className={clsx(
'flex items-center gap-2',
selectedProviders.length > 0 && 'border-primary'
)}
onClick={() => setIsFilterOpen(!isFilterOpen)}
leftIcon={<Filter size={14} />}
>
Filter
{selectedProviders.length > 0 && (
<span className="ml-1 px-1.5 py-0.5 text-xs bg-primary text-white rounded-full">
{selectedProviders.length}
</span>
)}
</Button>
{isFilterOpen && (
<div className="absolute left-0 top-full z-50 mt-2 w-[calc(100vw-2rem)] max-w-72 rounded-lg border border-border-glass bg-bg-surface p-4 shadow-lg sm:left-auto sm:right-0">
<div className="flex items-center justify-between mb-3">
<span className="text-sm font-medium text-text">Provider Filter</span>
{selectedProviders.length > 0 && (
<button
onClick={clearProviderFilter}
className="text-xs text-text-muted hover:text-text transition-colors flex items-center gap-1"
>
<X size={12} />
Clear
</button>
)}
</div>
<p className="text-xs text-text-muted mb-3">
Only log requests for selected providers
</p>
<div className="max-h-64 overflow-y-auto space-y-1">
{providers.map((provider) => (
<label
key={provider.id}
className="flex items-center gap-2 p-2 rounded hover:bg-bg-hover cursor-pointer"
>
<input
type="checkbox"
checked={selectedProviders.includes(provider.id)}
onChange={() => handleProviderToggle(provider.id)}
className="rounded border-border-glass text-primary focus:ring-primary"
/>
<span className="text-sm text-text">
{provider.name || provider.id}
</span>
</label>
))}
</div>
<div className="flex gap-2 mt-4 pt-3 border-t border-border-glass">
<Button
variant="secondary"
className="flex-1 text-xs"
onClick={() => setIsFilterOpen(false)}
>
Cancel
</Button>
<Button
variant="primary"
className="flex-1 text-xs"
onClick={applyProviderFilter}
>
Apply
</Button>
</div>
</div>
)}
</div>
)}
{detail && (
<>
<Button
variant="secondary"
className="flex items-center gap-2"
onClick={handleCopyAll}
leftIcon={
copiedAll ? (
<Check size={14} className="text-green-500" />
) : (
<Copy size={14} />
)
}
>
{copiedAll ? 'Copied' : 'Copy All'}
</Button>
<Button
variant="secondary"
className="flex items-center gap-2"
onClick={handleDownloadAll}
leftIcon={<Download size={14} />}
>
Download
</Button>
</>
)}
{isAdmin && (
<Button
onClick={handleDeleteAll}
variant="danger"
className="flex items-center gap-2"
disabled={logs.length === 0}
>
<Trash2 size={16} />
Delete All
</Button>
)}
<Button
onClick={fetchLogs}
variant="secondary"
leftIcon={<RefreshCw size={16} className={clsx(loading && 'animate-spin')} />}
>
Refresh
</Button>
</>
}
/>
</div>
<div className="flex min-h-0 flex-1 flex-col overflow-hidden border-t border-border-glass md:flex-row">
{/* Left Pane: Request List */}
<div className="flex max-h-[34vh] w-full shrink-0 flex-col border-b border-border-glass bg-bg-surface md:max-h-none md:w-[320px] md:border-b-0 md:border-r">
<div className="border-b border-border-glass p-3 sm:p-4">
<span className="text-xs font-bold text-text-muted uppercase tracking-wider">
Recent Requests
</span>
</div>
<div className="flex-1 overflow-y-auto p-2 flex flex-col gap-2">
{logs.map((log) => (
<div
key={log.requestId}
onClick={() => setSelectedId(log.requestId)}
className={clsx(
'p-3 rounded-md cursor-pointer transition-all duration-200 border border-transparent hover:bg-bg-hover group',
selectedId === log.requestId && 'bg-bg-glass border-border-glass shadow-sm'
)}
>
<div className="w-full">
<div className="flex items-center gap-2 mb-1 justify-between items-center">
<div className="flex items-center gap-2">
<Clock size={14} className="text-[var(--color-text-muted)]" />
<span className="text-xs font-mono text-text-muted">
{new Date(log.createdAt).toLocaleTimeString()}
</span>
</div>
<button
onClick={(e) => handleDelete(e, log.requestId)}
className="bg-transparent border-0 text-text-muted p-1 rounded cursor-pointer transition-all duration-200 flex items-center justify-center hover:bg-red-600/10 hover:text-danger opacity-100 md:opacity-0 md:group-hover:opacity-100"
title="Delete log"
>
<Trash2 size={12} />
</button>
</div>
<div className="text-[13px] font-mono text-primary whitespace-nowrap overflow-hidden text-ellipsis mt-1">
{log.requestId?.substring(0, 8) ?? '-'}...
</div>
</div>
</div>
))}
{logs.length === 0 && (
<div className="text-center p-8 text-[var(--color-text-muted)] italic text-sm">
No debug logs found. Ensure Debug Mode is enabled.
</div>
)}
</div>
</div>
{/* Right Pane: Details */}
<div className="relative flex min-h-0 flex-1 flex-col overflow-y-auto bg-bg-deep">
{selectedId && detail ? (
<div className="flex flex-col">
<div className="sticky top-0 z-10 flex flex-col gap-2 border-b border-border-glass bg-bg-surface px-3 py-3 sm:px-4">
<div className="flex min-w-0 flex-col gap-1">
<span className="text-xs font-bold uppercase tracking-wider text-text-muted">
Selected Trace
</span>
<span className="break-all text-xs font-mono text-text-secondary">
{detail.requestId}
</span>
</div>
</div>
<AccordionPanel
title="Raw Request"
content={formatContent(detail.rawRequest)}
color="text-blue-400"
defaultOpen={true}
/>
<AccordionPanel
title="Transformed Request"
content={formatContent(detail.transformedRequest)}
color="text-purple-400"
/>
<AccordionPanel
title="Raw Response"
content={formatContent(detail.rawResponse)}
color="text-orange-400"
/>
{detail.rawResponseSnapshot && (
<AccordionPanel
title="Raw Response (Reconstructed)"
content={formatContent(detail.rawResponseSnapshot)}
color="text-orange-400"
/>
)}
<AccordionPanel
title="Transformed Response"
content={formatContent(detail.transformedResponse)}
color="text-green-400"
defaultOpen={true}
/>
{detail.transformedResponseSnapshot && (
<AccordionPanel
title="Transformed Response (Reconstructed)"
content={formatContent(detail.transformedResponseSnapshot)}
color="text-green-400"
/>
)}
{detail.responseHeaders && (
<AccordionPanel
title="Response Headers"
content={formatContent(detail.responseHeaders)}
color="text-yellow-400"
/>
)}
</div>
) : (
<div className="flex flex-col items-center justify-center h-full text-text-muted gap-4">
<Database size={48} opacity={0.2} />
<p>Select a request trace to inspect details</p>
</div>
)}
{loadingDetail && (
<div className="absolute inset-0 bg-[rgba(15,23,42,0.5)] backdrop-blur-sm flex items-center justify-center z-10">
<RefreshCw className="animate-spin text-[var(--color-primary)]" size={32} />
</div>
)}
</div>
</div>
<Modal
isOpen={isDeleteAllModalOpen}
onClose={() => setIsDeleteAllModalOpen(false)}
title="Confirm Deletion"
footer={
<>
<Button variant="secondary" onClick={() => setIsDeleteAllModalOpen(false)}>
Cancel
</Button>
<Button variant="danger" onClick={confirmDeleteAll} disabled={isDeleting}>
{isDeleting ? 'Deleting...' : 'Delete All Logs'}
</Button>
</>
}
>
<p>Are you sure you want to delete ALL debug logs? This action cannot be undone.</p>
</Modal>
<Modal
isOpen={isSingleDeleteModalOpen}
onClose={() => setIsSingleDeleteModalOpen(false)}
title="Confirm Deletion"
footer={
<>
<Button variant="secondary" onClick={() => setIsSingleDeleteModalOpen(false)}>
Cancel
</Button>
<Button variant="danger" onClick={confirmDeleteSingle} disabled={isDeleting}>
{isDeleting ? 'Deleting...' : 'Delete Log'}
</Button>
</>
}
>
<p>Are you sure you want to delete this debug log? This action cannot be undone.</p>
</Modal>
</div>
);
};
const AccordionPanel: React.FC<{
title: string;
content: string;
color: string;
defaultOpen?: boolean;
}> = ({ title, content, color, defaultOpen = false }) => {
const [isOpen, setIsOpen] = useState(defaultOpen);
const [copied, setCopied] = useState(false);
const [folded, setFolded] = useState(false);
const editorRef = useRef<any>(null);
const handleCopy = async (e: React.MouseEvent) => {
e.stopPropagation();
if (!isClipboardAvailable()) return;
const success = await copyToClipboard(content);
if (success) {
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}
};
const handleToggleFold = (e: React.MouseEvent) => {
e.stopPropagation();
const editor = editorRef.current;
if (!editor) return;
if (folded) {
editor.trigger('unfoldAll', 'editor.unfoldAll', null);
} else {
// Fold everything first
editor.trigger('foldAll', 'editor.foldAll', null);
// Then unfold the outermost object (line 1) to keep it visible
setTimeout(() => {
editor.setSelection({ startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 });
editor.trigger('unfold', 'editor.unfold', null);
editor.setSelection({ startLineNumber: 0, startColumn: 0, endLineNumber: 0, endColumn: 0 });
}, 50);
}
setFolded(!folded);
};
return (
<div className="border-b border-border-glass bg-bg-surface">
<div
className="flex cursor-pointer items-center justify-between gap-3 bg-bg-hover px-3 py-3 transition-colors duration-200 select-none hover:bg-bg-glass sm:px-4"
onClick={() => setIsOpen(!isOpen)}
>
<div className="flex min-w-0 items-center gap-2">
{isOpen ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
<span className={clsx('truncate text-[11px] font-bold uppercase tracking-wider', color)}>
{title}
</span>
<button
className="bg-transparent border-0 text-text-muted p-0.5 rounded cursor-pointer transition-all duration-200 flex items-center justify-center hover:bg-white/10 hover:text-text"
onClick={handleToggleFold}
title={folded ? 'Unfold all' : 'Fold all'}
>
{folded ? <Maximize2 size={12} /> : <Minimize2 size={12} />}
</button>
</div>
<button
className="bg-transparent border-0 text-text-muted p-1 rounded cursor-pointer transition-all duration-200 flex items-center justify-center hover:bg-white/10 hover:text-text"
onClick={handleCopy}
title="Copy to clipboard"
>
{copied ? <Check size={14} className="text-green-500" /> : <Copy size={14} />}
</button>
</div>
<div
className={clsx(
'overflow-hidden transition-[max-height] duration-300 ease-in-out',
isOpen ? 'max-h-[500px]' : 'max-h-0'
)}
>
<div className="h-[280px] bg-[#1e1e1e] sm:h-[400px]">
<Editor
height="100%"
defaultLanguage="json"
theme="vs-dark"
value={content}
onMount={(editor) => {
editorRef.current = editor;
}}
options={{
readOnly: true,
minimap: { enabled: false },
scrollBeyondLastLine: false,
fontSize: 12,
fontFamily: "'JetBrains Mono', 'Fira Code', monospace",
lineNumbers: 'on',
folding: true,
wordWrap: 'on',
padding: { top: 10, bottom: 10 },
}}
/>
</div>
</div>
</div>
);
};