Open History to see the last commit
1import {
2 AlertTriangleIcon,
3 ChevronDownIcon,
4 ChevronRightIcon,
5 CopyIcon,
6 FolderOpenIcon,
7 InfoIcon,
8 RefreshCwIcon,
9} from "lucide-react";
10import { useCallback, useMemo, useState, type ReactNode } from "react";
11import type { ServerProcessDiagnosticsEntry, ServerProcessSignal } from "@t3tools/contracts";
12import { DateTime, Option } from "effect";
13
14import { ensureLocalApi } from "../../localApi";
15import { cn } from "../../lib/utils";
16import { resolveAndPersistPreferredEditor } from "../../editorPreferences";
17import { formatRelativeTime } from "../../timestampFormat";
18import { useServerAvailableEditors, useServerObservability } from "../../rpc/serverState";
19import { useProcessDiagnostics } from "../../lib/processDiagnosticsState";
20import { useTraceDiagnostics } from "../../lib/traceDiagnosticsState";
21import { Button } from "../ui/button";
22import { ScrollArea } from "../ui/scroll-area";
23import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
24import { toastManager } from "../ui/toast";
25import { SettingsPageContainer, SettingsSection, useRelativeTimeTick } from "./settingsLayout";
26
27const NUMBER_FORMAT = new Intl.NumberFormat();
28
29function formatCount(value: number): string {
30 return NUMBER_FORMAT.format(value);
31}
32
33function formatDuration(value: number): string {
34 if (value < 1_000) return `${Math.round(value)} ms`;
35 return `${(value / 1_000).toFixed(value >= 10_000 ? 1 : 2)} s`;
36}
37
38function formatBytes(value: number): string {
39 if (value < 1024) return `${value} B`;
40 const units = ["KB", "MB", "GB"] as const;
41 let unitIndex = -1;
42 let next = value;
43 do {
44 next /= 1024;
45 unitIndex += 1;
46 } while (next >= 1024 && unitIndex < units.length - 1);
47 return `${next.toFixed(next >= 10 ? 1 : 2)} ${units[unitIndex]}`;
48}
49
50function formatRelative(value: DateTime.Utc | null): string {
51 if (!value) return "No trace records";
52 const relative = formatRelativeTime(DateTime.formatIso(value));
53 return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
54}
55
56function formatRelativeNoWrap(value: DateTime.Utc | null): string {
57 return formatRelative(value).replaceAll(" ", "\u00a0");
58}
59
60function shortenTraceId(traceId: string): string {
61 if (traceId.length <= 32) return traceId;
62 return `${traceId.slice(0, 18)}...${traceId.slice(-10)}`;
63}
64
65function isStaleProcessSignalMessage(message: string | undefined): boolean {
66 return message?.includes("not a live descendant") ?? false;
67}
68
69function StatBlock({
70 label,
71 value,
72 tooltip,
73 tone = "default",
74}: {
75 label: string;
76 value: string;
77 tooltip?: ReactNode;
78 tone?: "default" | "warning" | "danger";
79}) {
80 return (
81 <div className="min-w-0 border-border/60 px-4 py-3 sm:px-5">
82 <div className="flex min-w-0 items-center gap-1.5 text-[11px] font-medium uppercase tracking-[0.08em] text-muted-foreground/70">
83 <span className="min-w-0 truncate">{label}</span>
84 {tooltip ? (
85 <Tooltip>
86 <TooltipTrigger
87 render={
88 <button
89 type="button"
90 className="inline-flex size-3.5 shrink-0 items-center justify-center rounded-sm text-muted-foreground/60 hover:text-foreground"
91 aria-label={`${label} details`}
92 >
93 <InfoIcon className="size-3" />
94 </button>
95 }
96 />
97 <TooltipPopup
98 side="top"
99 className="max-w-[min(300px,calc(100vw-2rem))] whitespace-normal text-left text-[11px] leading-relaxed text-wrap"
100 >
101 {tooltip}
102 </TooltipPopup>
103 </Tooltip>
104 ) : null}
105 </div>
106 <div
107 className={cn(
108 "mt-1 truncate font-mono text-lg font-semibold tabular-nums text-foreground",
109 tone === "warning" && "text-amber-600 dark:text-amber-400",
110 tone === "danger" && "text-destructive",
111 )}
112 >
113 {value}
114 </div>
115 </div>
116 );
117}
118
119function StatsGrid({ children }: { children: ReactNode }) {
120 return (
121 <div className="relative grid grid-cols-2 sm:grid-cols-4">
122 <span
123 className="pointer-events-none absolute inset-y-0 left-1/2 w-px bg-border/60"
124 aria-hidden
125 />
126 <span
127 className="pointer-events-none absolute inset-x-0 top-1/2 h-px bg-border/60 sm:hidden"
128 aria-hidden
129 />
130 <span
131 className="pointer-events-none absolute inset-y-0 left-1/4 hidden w-px bg-border/60 sm:block"
132 aria-hidden
133 />
134 <span
135 className="pointer-events-none absolute inset-y-0 left-3/4 hidden w-px bg-border/60 sm:block"
136 aria-hidden
137 />
138 {children}
139 </div>
140 );
141}
142
143function EmptyRows({ label }: { label: string }) {
144 return <div className="px-4 py-4 text-xs text-muted-foreground sm:px-5">{label}</div>;
145}
146
147function ExpandableText({
148 text,
149 className,
150 collapsedClassName = "line-clamp-3",
151 expandLabel = "Show full error",
152}: {
153 text: string;
154 className?: string;
155 collapsedClassName?: string;
156 expandLabel?: string;
157}) {
158 const [expanded, setExpanded] = useState(false);
159 const canExpand = text.length > 180 || text.includes("\n");
160
161 return (
162 <div className={cn("min-w-0", className)}>
163 <div
164 className={cn(
165 "whitespace-pre-wrap break-words",
166 !expanded && canExpand ? collapsedClassName : null,
167 )}
168 >
169 {text}
170 </div>
171 {canExpand ? (
172 <button
173 type="button"
174 className="mt-1 text-[11px] font-medium text-foreground/70 underline-offset-2 hover:text-foreground hover:underline"
175 onClick={() => setExpanded((value) => !value)}
176 >
177 {expanded ? "Show less" : expandLabel}
178 </button>
179 ) : null}
180 </div>
181 );
182}
183
184function DiagnosticsTable({
185 headers,
186 children,
187 minTableWidth = "min-w-[640px]",
188 columnWidths,
189}: {
190 headers: ReadonlyArray<string>;
191 children: ReactNode;
192 minTableWidth?: string;
193 columnWidths?: ReadonlyArray<string>;
194}) {
195 return (
196 <ScrollArea
197 chainVerticalScroll
198 scrollFade
199 hideScrollbars
200 className="w-full max-w-full rounded-none"
201 >
202 <table
203 className={cn("w-full text-left text-xs", minTableWidth, columnWidths && "table-fixed")}
204 >
205 {columnWidths ? (
206 <colgroup>
207 {headers.map((header, index) => (
208 <col key={header} className={columnWidths[index]} />
209 ))}
210 </colgroup>
211 ) : null}
212 <thead className="border-b border-border/60 text-[11px] uppercase tracking-[0.08em] text-muted-foreground/70">
213 <tr>
214 {headers.map((header, index) => (
215 <th
216 key={header}
217 className={cn(
218 "whitespace-nowrap px-4 py-2.5 font-semibold first:sm:pl-5 last:sm:pr-5",
219 !columnWidths && index === headers.length - 1 && "w-px",
220 )}
221 >
222 {header.replaceAll(" ", "\u00a0")}
223 </th>
224 ))}
225 </tr>
226 </thead>
227 <tbody className="divide-y divide-border/60">{children}</tbody>
228 </table>
229 </ScrollArea>
230 );
231}
232
233function TraceIdCell({ traceId }: { traceId: string }) {
234 const [copied, setCopied] = useState(false);
235 const copyTraceId = useCallback(() => {
236 void navigator.clipboard
237 ?.writeText(traceId)
238 .then(() => {
239 setCopied(true);
240 window.setTimeout(() => setCopied(false), 1_200);
241 })
242 .catch(() => undefined);
243 }, [traceId]);
244
245 return (
246 <div className="flex w-full min-w-0 max-w-full items-center gap-2">
247 <Tooltip>
248 <TooltipTrigger
249 render={
250 <span className="min-w-0 flex-1 truncate font-mono text-[11px]">
251 {shortenTraceId(traceId)}
252 </span>
253 }
254 />
255 <TooltipPopup
256 side="top"
257 className="max-w-[min(520px,calc(100vw-2rem))] break-all font-mono text-[11px]"
258 >
259 {traceId}
260 </TooltipPopup>
261 </Tooltip>
262 <Tooltip>
263 <TooltipTrigger
264 render={
265 <button
266 type="button"
267 className="inline-flex size-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-accent hover:text-foreground"
268 aria-label={copied ? "Copied trace ID" : "Copy trace ID"}
269 onClick={copyTraceId}
270 >
271 <CopyIcon className="size-3" />
272 </button>
273 }
274 />
275 <TooltipPopup side="top">{copied ? "Copied" : "Copy full trace ID"}</TooltipPopup>
276 </Tooltip>
277 </div>
278 );
279}
280
281function formatProcessName(command: string): string {
282 const firstToken = command.trim().split(/\s+/)[0];
283 if (!firstToken) return command;
284 const normalized = firstToken.replace(/^['"]|['"]$/g, "");
285 const segments = normalized.split(/[\\/]/).filter(Boolean);
286 return segments.at(-1) ?? normalized;
287}
288
289function formatProcessType(process: ServerProcessDiagnosticsEntry): string {
290 if (process.depth > 0) return "Subprocess";
291 if (/\b(codex|claude|opencode|cursor)\b/i.test(process.command)) return "Agent";
292 return "Process";
293}
294
295function ProcessNameCell({
296 process,
297 isExpanded,
298 onToggle,
299}: {
300 process: ServerProcessDiagnosticsEntry;
301 isExpanded: boolean;
302 onToggle: (pid: number) => void;
303}) {
304 const name = formatProcessName(process.command);
305 const hasChildren = process.childPids.length > 0;
306 const ChevronIcon = isExpanded ? ChevronDownIcon : ChevronRightIcon;
307
308 return (
309 <div
310 className="grid min-w-0 grid-cols-[1.25rem_0.375rem_minmax(0,1fr)] items-center gap-2"
311 style={{ paddingLeft: `${Math.min(process.depth, 8) * 16}px` }}
312 >
313 {hasChildren ? (
314 <button
315 type="button"
316 className="inline-flex size-5 items-center justify-center rounded-sm text-muted-foreground hover:bg-accent hover:text-foreground"
317 aria-label={isExpanded ? `Collapse ${name}` : `Expand ${name}`}
318 onClick={() => onToggle(process.pid)}
319 >
320 <ChevronIcon className="size-3.5" />
321 </button>
322 ) : (
323 <span className="size-5 shrink-0" aria-hidden="true" />
324 )}
325 <span className="size-1.5 shrink-0 rounded-full bg-emerald-500/80" />
326 <span className="min-w-0 truncate font-medium text-foreground">{name}</span>
327 </div>
328 );
329}
330
331function ProcessSignalActions({
332 process,
333 isSignaling,
334 onSignal,
335}: {
336 process: ServerProcessDiagnosticsEntry;
337 isSignaling: boolean;
338 onSignal: (pid: number, signal: ServerProcessSignal) => void;
339}) {
340 return (
341 <div className="flex items-center justify-end gap-1.5">
342 <Tooltip>
343 <TooltipTrigger
344 render={
345 <button
346 type="button"
347 disabled={isSignaling}
348 className="text-[11px] font-medium text-muted-foreground underline-offset-2 hover:text-foreground hover:underline disabled:pointer-events-none disabled:opacity-50"
349 onClick={() => onSignal(process.pid, "SIGINT")}
350 >
351 INT
352 </button>
353 }
354 />
355 <TooltipPopup side="top">Send SIGINT</TooltipPopup>
356 </Tooltip>
357 <Tooltip>
358 <TooltipTrigger
359 render={
360 <button
361 type="button"
362 disabled={isSignaling}
363 className="text-[11px] font-medium text-destructive underline-offset-2 hover:underline disabled:pointer-events-none disabled:opacity-50"
364 onClick={() => onSignal(process.pid, "SIGKILL")}
365 >
366 KILL
367 </button>
368 }
369 />
370 <TooltipPopup side="top">Send SIGKILL</TooltipPopup>
371 </Tooltip>
372 </div>
373 );
374}
375
376function ProcessDiagnosticsTable({
377 processes,
378 signalingPid,
379 onSignal,
380 emptyLabel,
381}: {
382 processes: ReadonlyArray<ServerProcessDiagnosticsEntry>;
383 signalingPid: number | null;
384 onSignal: (pid: number, signal: ServerProcessSignal) => void;
385 emptyLabel?: string;
386}) {
387 const [collapsedPids, setCollapsedPids] = useState<ReadonlySet<number>>(() => new Set());
388 const visibleProcesses = useMemo(() => {
389 const visible: ServerProcessDiagnosticsEntry[] = [];
390 let hiddenChildDepth: number | null = null;
391
392 for (const process of processes) {
393 if (hiddenChildDepth !== null) {
394 if (process.depth > hiddenChildDepth) continue;
395 hiddenChildDepth = null;
396 }
397
398 visible.push(process);
399 if (collapsedPids.has(process.pid)) {
400 hiddenChildDepth = process.depth;
401 }
402 }
403
404 return visible;
405 }, [collapsedPids, processes]);
406
407 const toggleProcess = useCallback((pid: number) => {
408 setCollapsedPids((previous) => {
409 const next = new Set(previous);
410 if (next.has(pid)) {
411 next.delete(pid);
412 } else {
413 next.add(pid);
414 }
415 return next;
416 });
417 }, []);
418
419 return (
420 <ScrollArea
421 chainVerticalScroll
422 scrollFade
423 hideScrollbars
424 className="w-full max-w-full rounded-none border-t border-border/60"
425 >
426 <table className="w-full min-w-[1040px] table-fixed text-left text-xs">
427 <colgroup>
428 <col className="w-[24%]" />
429 <col className="w-[8%]" />
430 <col className="w-[10%]" />
431 <col className="w-[33%]" />
432 <col className="w-[8%]" />
433 <col className="w-[11%]" />
434 <col className="w-[6%]" />
435 </colgroup>
436 <thead className="border-b border-border/60 bg-muted/15 text-[11px] uppercase tracking-[0.08em] text-muted-foreground/70">
437 <tr>
438 <th className="px-4 py-2 font-semibold sm:pl-5">Name</th>
439 <th className="px-3 py-2 text-right font-semibold">CPU</th>
440 <th className="px-3 py-2 text-right font-semibold">Memory</th>
441 <th className="px-3 py-2 font-semibold">Command</th>
442 <th className="px-3 py-2 text-right font-semibold">PID</th>
443 <th className="px-3 py-2 font-semibold">Type</th>
444 <th className="px-2 py-2 text-right font-semibold sm:pr-4">Kill</th>
445 </tr>
446 </thead>
447 <tbody className="divide-y divide-border/50">
448 {visibleProcesses.length === 0 ? (
449 <tr>
450 <td colSpan={7} className="px-4 py-4 text-xs text-muted-foreground sm:px-5">
451 {emptyLabel ?? "No live descendant processes found."}
452 </td>
453 </tr>
454 ) : null}
455 {visibleProcesses.map((process) => (
456 <tr key={process.pid} className="hover:bg-muted/20">
457 <td className="px-4 py-2 align-middle sm:pl-5">
458 <ProcessNameCell
459 process={process}
460 isExpanded={!collapsedPids.has(process.pid)}
461 onToggle={toggleProcess}
462 />
463 </td>
464 <td className="px-3 py-2 text-right align-middle font-mono tabular-nums">
465 {process.cpuPercent.toFixed(1)}%
466 </td>
467 <td className="px-3 py-2 text-right align-middle font-mono tabular-nums">
468 {formatBytes(process.rssBytes)}
469 </td>
470 <td className="px-3 py-2 align-middle text-muted-foreground">
471 <Tooltip>
472 <TooltipTrigger
473 render={<span className="block truncate">{process.command}</span>}
474 />
475 <TooltipPopup
476 side="top"
477 className="max-w-[min(440px,calc(100vw-2rem))] whitespace-normal break-words text-left font-mono text-[11px] leading-relaxed text-wrap"
478 >
479 {process.command}
480 </TooltipPopup>
481 </Tooltip>
482 </td>
483 <td className="px-3 py-2 text-right align-middle font-mono tabular-nums text-muted-foreground">
484 {process.pid}
485 </td>
486 <td className="truncate px-3 py-2 align-middle text-muted-foreground">
487 {formatProcessType(process)}
488 </td>
489 <td className="px-2 py-2 align-middle sm:pr-4">
490 <ProcessSignalActions
491 process={process}
492 isSignaling={signalingPid === process.pid}
493 onSignal={onSignal}
494 />
495 </td>
496 </tr>
497 ))}
498 </tbody>
499 </table>
500 </ScrollArea>
501 );
502}
503
504function DiagnosticsLastChecked({ checkedAt }: { checkedAt: DateTime.Utc | null }) {
505 useRelativeTimeTick();
506 const relative = checkedAt ? formatRelativeTime(DateTime.formatIso(checkedAt)) : null;
507
508 if (!relative) {
509 return <span className="text-[11px] text-muted-foreground/50">Checking</span>;
510 }
511
512 return (
513 <span className="text-[11px] text-muted-foreground/60">
514 {relative.suffix ? (
515 <>
516 Checked <span className="font-mono tabular-nums">{relative.value}</span> {relative.suffix}
517 </>
518 ) : (
519 <>Checked {relative.value}</>
520 )}
521 </span>
522 );
523}
524
525function DiagnosticsRefreshButton({
526 isPending,
527 label,
528 onClick,
529}: {
530 isPending: boolean;
531 label: string;
532 onClick: () => void;
533}) {
534 return (
535 <Tooltip>
536 <TooltipTrigger
537 render={
538 <Button
539 size="icon-xs"
540 variant="ghost"
541 className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
542 disabled={isPending}
543 onClick={onClick}
544 aria-label={label}
545 >
546 <RefreshCwIcon className={cn("size-3", isPending && "animate-spin")} />
547 </Button>
548 }
549 />
550 <TooltipPopup side="top">{label}</TooltipPopup>
551 </Tooltip>
552 );
553}
554
555export function DiagnosticsSettingsPanel() {
556 const observability = useServerObservability();
557 const availableEditors = useServerAvailableEditors();
558 const { data, error, isPending, refresh } = useTraceDiagnostics();
559 const {
560 data: processData,
561 error: processError,
562 isPending: isProcessPending,
563 refresh: refreshProcesses,
564 } = useProcessDiagnostics();
565 const [isOpeningLogsDirectory, setIsOpeningLogsDirectory] = useState(false);
566 const [openLogsDirectoryError, setOpenLogsDirectoryError] = useState<string | null>(null);
567 const [signalingPid, setSignalingPid] = useState<number | null>(null);
568
569 const openLogsDirectory = useCallback(() => {
570 const logsDirectoryPath = observability?.logsDirectoryPath ?? null;
571 if (!logsDirectoryPath) return;
572
573 const editor = resolveAndPersistPreferredEditor(availableEditors ?? []);
574 if (!editor) {
575 setOpenLogsDirectoryError("No available editors found.");
576 return;
577 }
578
579 setIsOpeningLogsDirectory(true);
580 setOpenLogsDirectoryError(null);
581 void ensureLocalApi()
582 .shell.openInEditor(logsDirectoryPath, editor)
583 .catch((error: unknown) => {
584 setOpenLogsDirectoryError(
585 error instanceof Error ? error.message : "Unable to open logs folder.",
586 );
587 })
588 .finally(() => {
589 setIsOpeningLogsDirectory(false);
590 });
591 }, [availableEditors, observability?.logsDirectoryPath]);
592
593 const isInitialLoading = isPending && data === null;
594 const isProcessInitialLoading = isProcessPending && processData === null;
595 const signalProcess = useCallback(
596 (pid: number, signal: ServerProcessSignal) => {
597 if (
598 signal === "SIGKILL" &&
599 !window.confirm(`Send SIGKILL to process ${pid}? This cannot be handled by the process.`)
600 ) {
601 return;
602 }
603
604 setSignalingPid(pid);
605 void ensureLocalApi()
606 .server.signalProcess({ pid, signal })
607 .then((result) => {
608 if (!result.signaled) {
609 const message = Option.getOrUndefined(result.message);
610 refreshProcesses();
611 if (isStaleProcessSignalMessage(message)) {
612 toastManager.add({
613 type: "info",
614 title: "Process already exited",
615 description:
616 "The process is not a child of the T3 Server. It might already have exited.",
617 });
618 return;
619 }
620
621 toastManager.add({
622 type: "error",
623 title: `Could not send ${signal}`,
624 description: message ?? `Failed to send ${signal}.`,
625 });
626 return;
627 }
628 refreshProcesses();
629 })
630 .catch((error: unknown) => {
631 toastManager.add({
632 type: "error",
633 title: `Could not send ${signal}`,
634 description: error instanceof Error ? error.message : `Failed to send ${signal}.`,
635 });
636 })
637 .finally(() => {
638 setSignalingPid(null);
639 });
640 },
641 [refreshProcesses],
642 );
643
644 const processDiagnosticsError = processData ? Option.getOrNull(processData.error) : null;
645 const traceDiagnosticsError = data ? Option.getOrNull(data.error) : null;
646 const traceDiagnosticsPartialFailure = data
647 ? Option.getOrElse(data.partialFailure, () => false)
648 : false;
649
650 return (
651 <SettingsPageContainer>
652 <SettingsSection
653 title="Live Processes"
654 headerAction={
655 <div className="flex items-center gap-1.5">
656 <DiagnosticsLastChecked checkedAt={processData?.readAt ?? null} />
657 <DiagnosticsRefreshButton
658 isPending={isProcessPending}
659 label="Refresh process diagnostics"
660 onClick={refreshProcesses}
661 />
662 </div>
663 }
664 >
665 <StatsGrid>
666 <StatBlock
667 label="Child Processes"
668 value={processData ? formatCount(processData.processCount) : "..."}
669 />
670 <StatBlock
671 label="CPU"
672 value={processData ? `${processData.totalCpuPercent.toFixed(1)}%` : "..."}
673 tooltip="Total CPU across live child processes of the current server process. The desktop shell and other parent processes are not included."
674 />
675 <StatBlock
676 label="Memory"
677 value={processData ? formatBytes(processData.totalRssBytes) : "..."}
678 tooltip="Total resident memory across live child processes of the current server process. The desktop shell and other parent processes are not included."
679 />
680 <StatBlock
681 label="Server PID"
682 value={processData ? String(processData.serverPid) : "..."}
683 />
684 </StatsGrid>
685 {processDiagnosticsError || processError ? (
686 <div className="space-y-2 border-t border-border/60 px-4 py-3 text-xs text-muted-foreground sm:px-5">
687 {processDiagnosticsError ? (
688 <div className="flex items-start gap-2 text-destructive">
689 <AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
690 <span>{processDiagnosticsError.message}</span>
691 </div>
692 ) : null}
693 {processError ? (
694 <div className="flex items-start gap-2 text-destructive">
695 <AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
696 <span>{processError}</span>
697 </div>
698 ) : null}
699 </div>
700 ) : null}
701 <ProcessDiagnosticsTable
702 processes={processData?.processes ?? []}
703 signalingPid={signalingPid}
704 onSignal={signalProcess}
705 emptyLabel={
706 isProcessInitialLoading
707 ? "Loading live processes..."
708 : "No live descendant processes found."
709 }
710 />
711 </SettingsSection>
712
713 <SettingsSection
714 title="Trace Diagnostics"
715 headerAction={
716 <div className="flex items-center gap-1.5">
717 <DiagnosticsLastChecked checkedAt={data?.readAt ?? null} />
718 <Tooltip>
719 <TooltipTrigger
720 render={
721 <Button
722 size="icon-xs"
723 variant="ghost"
724 className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
725 disabled={!observability?.logsDirectoryPath || isOpeningLogsDirectory}
726 onClick={openLogsDirectory}
727 aria-label="Open logs folder"
728 >
729 <FolderOpenIcon className="size-3" />
730 </Button>
731 }
732 />
733 <TooltipPopup side="top">Open logs folder</TooltipPopup>
734 </Tooltip>
735 <DiagnosticsRefreshButton
736 isPending={isPending}
737 label="Refresh trace diagnostics"
738 onClick={refresh}
739 />
740 </div>
741 }
742 >
743 <StatsGrid>
744 <StatBlock label="Spans" value={data ? formatCount(data.recordCount) : "..."} />
745 <StatBlock
746 label="Failures"
747 value={data ? formatCount(data.failureCount) : "..."}
748 tone={data && data.failureCount > 0 ? "danger" : "default"}
749 />
750 <StatBlock
751 label="Slow Spans"
752 value={data ? formatCount(data.slowSpanCount) : "..."}
753 tooltip={
754 data
755 ? `Spans with a duration of ${formatDuration(data.slowSpanThresholdMs)} or longer.`
756 : "Spans at or above the configured slow-span threshold."
757 }
758 tone={data && data.slowSpanCount > 0 ? "warning" : "default"}
759 />
760 <StatBlock
761 label="Parse Errors"
762 value={data ? formatCount(data.parseErrorCount) : "..."}
763 tone={data && data.parseErrorCount > 0 ? "warning" : "default"}
764 />
765 </StatsGrid>
766 {openLogsDirectoryError || traceDiagnosticsError || error ? (
767 <div className="space-y-2 border-t border-border/60 px-4 py-3 text-xs text-muted-foreground sm:px-5">
768 {openLogsDirectoryError ? (
769 <div className="flex items-start gap-2 text-destructive">
770 <AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
771 <span>{openLogsDirectoryError}</span>
772 </div>
773 ) : null}
774 {traceDiagnosticsError ? (
775 <div
776 className={cn(
777 "flex items-start gap-2",
778 traceDiagnosticsPartialFailure
779 ? "text-amber-600 dark:text-amber-400"
780 : "text-destructive",
781 )}
782 >
783 <AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
784 <span>
785 {traceDiagnosticsPartialFailure
786 ? `Some trace files could not be read, so diagnostics may be incomplete. ${traceDiagnosticsError.message}`
787 : traceDiagnosticsError.message}
788 </span>
789 </div>
790 ) : null}
791 {error ? (
792 <div className="flex items-start gap-2 text-destructive">
793 <AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
794 <span>{error}</span>
795 </div>
796 ) : null}
797 </div>
798 ) : null}
799 </SettingsSection>
800
801 <SettingsSection title="Latest Failures">
802 {data && data.latestFailures.length > 0 ? (
803 <DiagnosticsTable headers={["Span", "Cause", "Duration", "Ended"]}>
804 {data.latestFailures.map((failure) => (
805 <tr key={`${failure.traceId}:${failure.spanId}`}>
806 <td className="px-4 py-3 align-top text-xs font-medium text-foreground first:sm:pl-5">
807 {failure.name}
808 </td>
809 <td className="max-w-[360px] px-4 py-3 align-top text-muted-foreground">
810 <ExpandableText text={failure.cause} />
811 </td>
812 <td className="px-4 py-3 align-top font-mono tabular-nums">
813 {formatDuration(failure.durationMs)}
814 </td>
815 <td className="whitespace-nowrap px-4 py-3 align-top font-mono tabular-nums text-muted-foreground last:sm:pr-5">
816 {formatRelativeNoWrap(failure.endedAt)}
817 </td>
818 </tr>
819 ))}
820 </DiagnosticsTable>
821 ) : (
822 <EmptyRows label={isInitialLoading ? "Loading failures..." : "No failed spans found."} />
823 )}
824 </SettingsSection>
825
826 <SettingsSection title="Most Common Failures">
827 {data && data.commonFailures.length > 0 ? (
828 <DiagnosticsTable
829 headers={["Span", "Count", "Cause", "Last Seen"]}
830 minTableWidth="min-w-[760px]"
831 >
832 {data.commonFailures.map((failure) => (
833 <tr key={`${failure.name}:${failure.cause}`}>
834 <td className="px-4 py-3 align-top text-xs font-medium text-foreground first:sm:pl-5">
835 {failure.name}
836 </td>
837 <td className="px-4 py-3 align-top font-mono tabular-nums">
838 {formatCount(failure.count)}
839 </td>
840 <td className="max-w-[360px] px-4 py-3 align-top text-muted-foreground">
841 <ExpandableText text={failure.cause} />
842 </td>
843 <td className="w-px whitespace-nowrap px-4 py-3 align-top font-mono tabular-nums text-muted-foreground last:sm:pr-5">
844 {formatRelativeNoWrap(failure.lastSeenAt)}
845 </td>
846 </tr>
847 ))}
848 </DiagnosticsTable>
849 ) : (
850 <EmptyRows
851 label={isInitialLoading ? "Loading failure groups..." : "No repeated failures found."}
852 />
853 )}
854 </SettingsSection>
855
856 <SettingsSection title="Slowest Spans">
857 {data && data.slowestSpans.length > 0 ? (
858 <DiagnosticsTable
859 headers={["Span", "Duration", "Ended", "Trace"]}
860 minTableWidth="min-w-[900px]"
861 columnWidths={["w-[44%]", "w-[14%]", "w-[12%]", "w-[30%]"]}
862 >
863 {data.slowestSpans.map((span) => (
864 <tr key={`${span.traceId}:${span.spanId}`}>
865 <td className="px-4 py-3 align-top text-xs font-medium text-foreground first:sm:pl-5">
866 {span.name}
867 </td>
868 <td className="px-4 py-3 align-top font-mono tabular-nums">
869 {formatDuration(span.durationMs)}
870 </td>
871 <td className="w-px whitespace-nowrap px-4 py-3 align-top font-mono tabular-nums text-muted-foreground">
872 {formatRelativeNoWrap(span.endedAt)}
873 </td>
874 <td className="min-w-0 whitespace-nowrap px-4 py-3 align-top text-muted-foreground last:sm:pr-5">
875 <TraceIdCell traceId={span.traceId} />
876 </td>
877 </tr>
878 ))}
879 </DiagnosticsTable>
880 ) : (
881 <EmptyRows label={isInitialLoading ? "Loading slow spans..." : "No spans found."} />
882 )}
883 </SettingsSection>
884
885 <SettingsSection title="Span Logs">
886 {data && data.latestWarningAndErrorLogs.length > 0 ? (
887 <ScrollArea
888 chainVerticalScroll
889 scrollFade
890 hideScrollbars
891 className="w-full max-w-full rounded-none"
892 >
893 <table className="w-full min-w-[920px] table-fixed text-left text-xs">
894 <colgroup>
895 <col className="w-[11%]" />
896 <col className="w-[9%]" />
897 <col className="w-[24%]" />
898 <col className="w-[26%]" />
899 <col className="w-[30%]" />
900 </colgroup>
901 <thead className="border-b border-border/60 text-[11px] uppercase tracking-[0.08em] text-muted-foreground/70">
902 <tr>
903 <th className="whitespace-nowrap px-4 py-2.5 font-semibold sm:pl-5">Time</th>
904 <th className="whitespace-nowrap px-4 py-2.5 font-semibold">Level</th>
905 <th className="whitespace-nowrap px-4 py-2.5 font-semibold">Span</th>
906 <th className="whitespace-nowrap px-4 py-2.5 font-semibold">Message</th>
907 <th className="whitespace-nowrap px-4 py-2.5 font-semibold sm:pr-5">Trace</th>
908 </tr>
909 </thead>
910 <tbody className="divide-y divide-border/60">
911 {data.latestWarningAndErrorLogs.map((event) => (
912 <tr
913 key={`${event.traceId}:${event.spanId}:${DateTime.formatIso(event.seenAt)}:${event.message}`}
914 className="hover:bg-muted/15"
915 >
916 <td className="whitespace-nowrap px-4 py-3 align-top font-mono tabular-nums text-muted-foreground sm:pl-5">
917 {formatRelativeNoWrap(event.seenAt)}
918 </td>
919 <td className="px-4 py-3 align-top">
920 <span className="inline-flex rounded bg-muted px-1.5 py-0.5 font-mono text-[11px] font-medium uppercase text-foreground/80">
921 {event.level}
922 </span>
923 </td>
924 <td className="px-4 py-3 align-top">
925 <div className="truncate font-medium text-foreground">{event.spanName}</div>
926 </td>
927 <td className="px-4 py-3 align-top text-muted-foreground">
928 <ExpandableText
929 collapsedClassName="line-clamp-2"
930 expandLabel="Show full message"
931 text={event.message}
932 />
933 </td>
934 <td className="min-w-0 whitespace-nowrap px-4 py-3 align-top text-muted-foreground sm:pr-5">
935 <TraceIdCell traceId={event.traceId} />
936 </td>
937 </tr>
938 ))}
939 </tbody>
940 </table>
941 </ScrollArea>
942 ) : (
943 <EmptyRows
944 label={isInitialLoading ? "Loading recent logs..." : "No warnings or errors found."}
945 />
946 )}
947 </SettingsSection>
948
949 <SettingsSection title="Top Span Names">
950 {data && data.topSpansByCount.length > 0 ? (
951 <DiagnosticsTable
952 headers={["Span", "Count", "Failures", "Average", "Max"]}
953 minTableWidth="min-w-[760px]"
954 columnWidths={["w-[48%]", "w-[13%]", "w-[13%]", "w-[13%]", "w-[13%]"]}
955 >
956 {data.topSpansByCount.map((span) => (
957 <tr key={span.name}>
958 <td className="px-4 py-3 align-top text-xs font-medium text-foreground first:sm:pl-5">
959 {span.name}
960 </td>
961 <td className="whitespace-nowrap px-4 py-3 align-top font-mono tabular-nums">
962 {formatCount(span.count)}
963 </td>
964 <td className="whitespace-nowrap px-4 py-3 align-top font-mono tabular-nums">
965 {formatCount(span.failureCount)}
966 </td>
967 <td className="whitespace-nowrap px-4 py-3 align-top font-mono tabular-nums">
968 {formatDuration(span.averageDurationMs)}
969 </td>
970 <td className="whitespace-nowrap px-4 py-3 align-top font-mono tabular-nums last:sm:pr-5">
971 {formatDuration(span.maxDurationMs)}
972 </td>
973 </tr>
974 ))}
975 </DiagnosticsTable>
976 ) : (
977 <EmptyRows label={isInitialLoading ? "Loading span names..." : "No spans found."} />
978 )}
979 </SettingsSection>
980 </SettingsPageContainer>
981 );
982}