Open History to see the last commit
1import { ProcessSignalActions } from "./ProcessSignalActions";
2import { resolveUsageAccess } from "@t3tools/client-runtime/state/usage-access";
3import { environmentSession } from "../../state/session";
4import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
5import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
6import { AuthEnvironmentMaintainScope } from "@t3tools/contracts";
7import { RefreshIcon } from "~/components/ui/refresh-icon";
8import { AlertTriangleIcon, CopyIcon, FolderOpenIcon, InfoIcon } from "lucide-react";
9import { ChevronDown, ChevronRight } from "lucide";
10import {
11 isAtomCommandInterrupted,
12 squashAtomCommandFailure,
13} from "@t3tools/client-runtime/state/runtime";
14import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
15import type {
16 ServerProcessDiagnosticsEntry,
17 ServerProcessResourceHistorySummary,
18 ServerProcessSignal,
19} from "@t3tools/contracts";
20import * as DateTime from "effect/DateTime";
21import * as Option from "effect/Option";
22
23import { cn } from "../../lib/utils";
24import { ensureLocalApi } from "../../localApi";
25import { useOpenInPreferredEditor } from "../../editorPreferences";
26import { formatRelativeTimeLabel, getRelativeTimeState } from "../../timestampFormat";
27import { useEnvironmentQuery } from "../../state/query";
28import { serverEnvironment } from "../../state/server";
29import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
30import { Button } from "../ui/button";
31import { MorphIcon } from "~/components/MorphIcon";
32import { ScrollArea } from "../ui/scroll-area";
33import { Toggle, ToggleGroup } from "../ui/toggle-group";
34import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
35import { toastManager } from "../ui/toast";
36import { ExpandableText } from "./ExpandableText";
37import { ResourceTelemetryDiagnostics } from "./ResourceTelemetryDiagnostics";
38import { SettingsPageContainer, SettingsSection, useRelativeTimeTick } from "./settingsLayout";
39import { useAtomCommand } from "../../state/use-atom-command";
40import { useSettingsScope } from "./SettingsScopeContext";
41import { TelemetryExportSettings } from "./TelemetryExportSettings";
42
43const NUMBER_FORMAT = new Intl.NumberFormat();
44
45function formatCount(value: number): string {
46 return NUMBER_FORMAT.format(value);
47}
48
49function formatDuration(value: number): string {
50 if (value < 1_000) return `${Math.round(value)} ms`;
51 return `${(value / 1_000).toFixed(value >= 10_000 ? 1 : 2)} s`;
52}
53
54function formatBytes(value: number): string {
55 if (value < 1024) return `${value} B`;
56 const units = ["KB", "MB", "GB"] as const;
57 let unitIndex = -1;
58 let next = value;
59 do {
60 next /= 1024;
61 unitIndex += 1;
62 } while (next >= 1024 && unitIndex < units.length - 1);
63 return `${next.toFixed(next >= 10 ? 1 : 2)} ${units[unitIndex]}`;
64}
65
66function formatRelative(value: DateTime.Utc | null): string {
67 if (!value) return "No trace records";
68 return formatRelativeTimeLabel(DateTime.formatIso(value));
69}
70
71function formatRelativeNoWrap(value: DateTime.Utc | null): string {
72 return formatRelative(value).replaceAll(" ", "\u00a0");
73}
74
75function shortenTraceId(traceId: string): string {
76 if (traceId.length <= 32) return traceId;
77 return `${traceId.slice(0, 18)}...${traceId.slice(-10)}`;
78}
79
80function isStaleProcessSignalMessage(message: string | undefined): boolean {
81 return message?.includes("not a live descendant") ?? false;
82}
83
84function StatBlock({
85 label,
86 value,
87 tooltip,
88 tone = "default",
89}: {
90 label: string;
91 value: string;
92 tooltip?: ReactNode;
93 tone?: "default" | "warning" | "danger";
94}) {
95 return (
96 <div className="min-w-0 border-border/60 px-4 py-3 sm:px-5">
97 <div className="flex min-w-0 items-center gap-1.5 text-2xs font-medium uppercase tracking-widest text-muted-foreground/70">
98 <span className="min-w-0 truncate">{label}</span>
99 {tooltip ? (
100 <Tooltip>
101 <TooltipTrigger
102 render={
103 <button
104 type="button"
105 className="cursor-pointer inline-flex size-3.5 shrink-0 items-center justify-center rounded-sm text-muted-foreground/60 hover:text-foreground"
106 aria-label={`${label} details`}
107 >
108 <InfoIcon className="size-3" />
109 </button>
110 }
111 />
112 <TooltipPopup side="top">{tooltip}</TooltipPopup>
113 </Tooltip>
114 ) : null}
115 </div>
116 <div
117 className={cn(
118 "mt-1 truncate font-mono text-lg font-semibold tabular-nums text-foreground",
119 tone === "warning" && "text-warning-foreground",
120 tone === "danger" && "text-destructive",
121 )}
122 >
123 {value}
124 </div>
125 </div>
126 );
127}
128
129function StatsGrid({ children }: { children: ReactNode }) {
130 return (
131 <div className="relative grid grid-cols-2 sm:grid-cols-4">
132 <span
133 className="pointer-events-none absolute inset-y-0 left-1/2 w-px bg-border/60"
134 aria-hidden
135 />
136 <span
137 className="pointer-events-none absolute inset-x-0 top-1/2 h-px bg-border/60 sm:hidden"
138 aria-hidden
139 />
140 <span
141 className="pointer-events-none absolute inset-y-0 left-1/4 hidden w-px bg-border/60 sm:block"
142 aria-hidden
143 />
144 <span
145 className="pointer-events-none absolute inset-y-0 left-3/4 hidden w-px bg-border/60 sm:block"
146 aria-hidden
147 />
148 {children}
149 </div>
150 );
151}
152
153function EmptyRows({ label }: { label: string }) {
154 return <div className="px-4 py-4 text-xs text-muted-foreground sm:px-5">{label}</div>;
155}
156
157function DiagnosticsTable({
158 headers,
159 children,
160 minTableWidth = "min-w-[640px]",
161 columnWidths,
162}: {
163 headers: ReadonlyArray<string>;
164 children: ReactNode;
165 minTableWidth?: string;
166 columnWidths?: ReadonlyArray<string>;
167}) {
168 return (
169 <ScrollArea
170 radius="none"
171 chainVerticalScroll
172 scrollFade
173 hideScrollbars
174 className="w-full max-w-full"
175 >
176 <table
177 className={cn("w-full text-left text-xs", minTableWidth, columnWidths && "table-fixed")}
178 >
179 {columnWidths ? (
180 <colgroup>
181 {headers.map((header, index) => (
182 <col key={header} className={columnWidths[index]} />
183 ))}
184 </colgroup>
185 ) : null}
186 <thead className="border-b border-border/60 text-2xs uppercase tracking-widest text-muted-foreground/70">
187 <tr>
188 {headers.map((header, index) => (
189 <th
190 key={header}
191 className={cn(
192 "whitespace-nowrap px-4 py-2.5 font-semibold first:sm:pl-5 last:sm:pr-5",
193 !columnWidths && index === headers.length - 1 && "w-px",
194 )}
195 >
196 {header.replaceAll(" ", "\u00a0")}
197 </th>
198 ))}
199 </tr>
200 </thead>
201 <tbody className="divide-y divide-border/60">{children}</tbody>
202 </table>
203 </ScrollArea>
204 );
205}
206
207function TraceIdCell({ traceId }: { traceId: string }) {
208 const { copyToClipboard, isCopied: copied } = useCopyToClipboard({
209 target: "trace ID",
210 timeout: 1_200,
211 });
212
213 return (
214 <div className="flex w-full min-w-0 max-w-full items-center gap-2">
215 <Tooltip>
216 <TooltipTrigger
217 render={
218 <span className="min-w-0 flex-1 truncate font-mono text-2xs">
219 {shortenTraceId(traceId)}
220 </span>
221 }
222 />
223 <TooltipPopup side="top" variant="code">
224 {traceId}
225 </TooltipPopup>
226 </Tooltip>
227 <Tooltip>
228 <TooltipTrigger
229 render={
230 <Button
231 size="icon-micro"
232 variant="ghost-muted"
233 aria-label={copied ? "Copied trace ID" : "Copy trace ID"}
234 onClick={() => copyToClipboard(traceId)}
235 >
236 <CopyIcon className="size-3" />
237 </Button>
238 }
239 />
240 <TooltipPopup side="top">{copied ? "Copied" : "Copy full trace ID"}</TooltipPopup>
241 </Tooltip>
242 </div>
243 );
244}
245
246function formatProcessName(command: string): string {
247 const firstToken = command.trim().split(/\s+/)[0];
248 if (!firstToken) return command;
249 const normalized = firstToken.replace(/^['"]|['"]$/g, "");
250 const segments = normalized.split(/[\\/]/).filter(Boolean);
251 return segments.at(-1) ?? normalized;
252}
253
254function formatProcessType(process: ServerProcessDiagnosticsEntry): string {
255 if (process.depth > 0) return "Subprocess";
256 if (/\b(codex|claude|opencode|cursor)\b/i.test(process.command)) return "Agent";
257 return "Process";
258}
259
260function ProcessNameCell({
261 process,
262 isExpanded,
263 onToggle,
264}: {
265 process: ServerProcessDiagnosticsEntry;
266 isExpanded: boolean;
267 onToggle: (pid: number) => void;
268}) {
269 const name = formatProcessName(process.command);
270 const hasChildren = process.childPids.length > 0;
271
272 return (
273 <div
274 className="grid min-w-0 grid-cols-[1.25rem_0.375rem_minmax(0,1fr)] items-center gap-2"
275 style={{ paddingLeft: `${Math.min(process.depth, 6) * 10}px` }}
276 >
277 {hasChildren ? (
278 <Button
279 size="icon-micro"
280 variant="ghost-muted"
281 aria-label={isExpanded ? `Collapse ${name}` : `Expand ${name}`}
282 onClick={() => onToggle(process.pid)}
283 >
284 <MorphIcon className="size-3.5" icon={isExpanded ? ChevronDown : ChevronRight} />
285 </Button>
286 ) : (
287 <span className="size-5 shrink-0" aria-hidden="true" />
288 )}
289 <span className="size-1.5 shrink-0 rounded-full bg-success/80" />
290 <Tooltip>
291 <TooltipTrigger
292 render={<span className="min-w-0 truncate font-medium text-foreground">{name}</span>}
293 />
294 <TooltipPopup side="top" variant="code">
295 {process.command}
296 </TooltipPopup>
297 </Tooltip>
298 </div>
299 );
300}
301
302function ProcessDiagnosticsTable({
303 processes,
304 canMaintainEnvironment,
305 signalingPid,
306 onSignal,
307 emptyLabel,
308}: {
309 processes: ReadonlyArray<ServerProcessDiagnosticsEntry>;
310 canMaintainEnvironment: boolean;
311 signalingPid: number | null;
312 onSignal: (pid: number, signal: ServerProcessSignal) => void;
313 emptyLabel?: string;
314}) {
315 const [collapsedPids, setCollapsedPids] = useState<ReadonlySet<number>>(() => new Set());
316 const visibleProcesses = useMemo(() => {
317 const visible: ServerProcessDiagnosticsEntry[] = [];
318 let hiddenChildDepth: number | null = null;
319
320 for (const process of processes) {
321 if (hiddenChildDepth !== null) {
322 if (process.depth > hiddenChildDepth) continue;
323 hiddenChildDepth = null;
324 }
325
326 visible.push(process);
327 if (collapsedPids.has(process.pid)) {
328 hiddenChildDepth = process.depth;
329 }
330 }
331
332 return visible;
333 }, [collapsedPids, processes]);
334
335 const toggleProcess = useCallback((pid: number) => {
336 setCollapsedPids((previous) => {
337 const next = new Set(previous);
338 if (next.has(pid)) {
339 next.delete(pid);
340 } else {
341 next.add(pid);
342 }
343 return next;
344 });
345 }, []);
346
347 return (
348 <div className="border-t border-border/60">
349 <ScrollArea
350 radius="none"
351 chainVerticalScroll
352 scrollFade
353 hideScrollbars
354 className="max-h-[min(64vh,44rem)] w-full max-w-full"
355 >
356 <table className="w-full min-w-[1040px] table-fixed text-left text-xs">
357 <colgroup>
358 <col className="w-[24%]" />
359 <col className="w-[8%]" />
360 <col className="w-[10%]" />
361 <col className="w-[33%]" />
362 <col className="w-[8%]" />
363 <col className="w-[11%]" />
364 <col className="w-[6%]" />
365 </colgroup>
366 <thead className="sticky top-0 z-10 border-b border-border/60 bg-card text-2xs uppercase tracking-widest text-muted-foreground/70">
367 <tr>
368 <th className="px-4 py-2 font-semibold sm:pl-5">Name</th>
369 <th className="px-3 py-2 text-right font-semibold">CPU</th>
370 <th className="px-3 py-2 text-right font-semibold">Memory</th>
371 <th className="px-3 py-2 font-semibold">Command</th>
372 <th className="px-3 py-2 text-right font-semibold">PID</th>
373 <th className="px-3 py-2 font-semibold">Type</th>
374 <th className="p-2 text-right font-semibold sm:pr-4">Kill</th>
375 </tr>
376 </thead>
377 <tbody className="divide-y divide-border/50">
378 {visibleProcesses.length === 0 ? (
379 <tr>
380 <td colSpan={7} className="px-4 py-4 text-xs text-muted-foreground sm:px-5">
381 {emptyLabel ?? "No live descendant processes found."}
382 </td>
383 </tr>
384 ) : null}
385 {visibleProcesses.map((process) => (
386 <tr key={process.pid} className="hover:bg-muted/20">
387 <td className="px-4 py-2 align-middle sm:pl-5">
388 <ProcessNameCell
389 process={process}
390 isExpanded={!collapsedPids.has(process.pid)}
391 onToggle={toggleProcess}
392 />
393 </td>
394 <td className="px-3 py-2 text-right align-middle font-mono tabular-nums">
395 {process.cpuPercent.toFixed(1)}%
396 </td>
397 <td className="px-3 py-2 text-right align-middle font-mono tabular-nums">
398 {formatBytes(process.rssBytes)}
399 </td>
400 <td className="px-3 py-2 align-middle text-muted-foreground">
401 <Tooltip>
402 <TooltipTrigger
403 render={<span className="block truncate">{process.command}</span>}
404 />
405 <TooltipPopup side="top" variant="code">
406 {process.command}
407 </TooltipPopup>
408 </Tooltip>
409 </td>
410 <td className="px-3 py-2 text-right align-middle font-mono tabular-nums text-muted-foreground">
411 {process.pid}
412 </td>
413 <td className="truncate px-3 py-2 align-middle text-muted-foreground">
414 {formatProcessType(process)}
415 </td>
416 <td className="p-2 align-middle sm:pr-4">
417 <ProcessSignalActions
418 disabled={!canMaintainEnvironment || signalingPid === process.pid}
419 onSignal={(signal) => onSignal(process.pid, signal)}
420 />
421 </td>
422 </tr>
423 ))}
424 </tbody>
425 </table>
426 </ScrollArea>
427 </div>
428 );
429}
430
431const RESOURCE_HISTORY_WINDOWS = [
432 { label: "5m", windowMs: 5 * 60_000, bucketMs: 30_000 },
433 { label: "15m", windowMs: 15 * 60_000, bucketMs: 60_000 },
434 { label: "30m", windowMs: 30 * 60_000, bucketMs: 2 * 60_000 },
435 { label: "1h", windowMs: 60 * 60_000, bucketMs: 5 * 60_000 },
436] as const;
437
438function formatCpuTime(seconds: number): string {
439 if (seconds < 60) return `${seconds.toFixed(seconds >= 10 ? 1 : 2)}s`;
440 const minutes = seconds / 60;
441 if (minutes < 60) return `${minutes.toFixed(minutes >= 10 ? 1 : 2)}m`;
442 return `${(minutes / 60).toFixed(2)}h`;
443}
444
445function formatShortProcessName(command: string): string {
446 const name = formatProcessName(command);
447 return name.length > 42 ? `${name.slice(0, 39)}...` : name;
448}
449
450function ResourceHistoryProcessNameCell({
451 process,
452 visualDepth,
453}: {
454 process: ServerProcessResourceHistorySummary;
455 visualDepth: number;
456}) {
457 const name = formatShortProcessName(process.command);
458
459 return (
460 <div
461 className="grid min-w-0 grid-cols-[1.25rem_0.375rem_minmax(0,1fr)] items-center gap-2"
462 style={{ paddingLeft: `${Math.min(visualDepth, 6) * 10}px` }}
463 aria-label={`${process.isServerRoot ? "Root" : "Child"} process ${name}`}
464 >
465 <span className="size-5 shrink-0" aria-hidden="true" />
466 <span
467 className={cn(
468 "size-1.5 shrink-0 rounded-full",
469 process.isServerRoot ? "bg-warning/90" : "bg-success/80",
470 )}
471 />
472 <Tooltip>
473 <TooltipTrigger
474 render={<span className="min-w-0 truncate font-medium text-foreground">{name}</span>}
475 />
476 <TooltipPopup side="top" variant="code">
477 {process.command}
478 </TooltipPopup>
479 </Tooltip>
480 </div>
481 );
482}
483
484function ProcessResourceHistoryChart({
485 buckets,
486}: {
487 buckets: ReadonlyArray<{
488 readonly startedAt: DateTime.Utc;
489 readonly avgCpuPercent: number;
490 readonly maxCpuPercent: number;
491 }>;
492}) {
493 const maxCpuPercent = Math.max(1, ...buckets.map((bucket) => bucket.maxCpuPercent));
494
495 return (
496 <div className="border-t border-border/60 px-4 py-3 sm:px-5">
497 <div className="flex h-28 items-end gap-1 overflow-hidden rounded-sm bg-muted/10 p-2">
498 {buckets.map((bucket) => {
499 const peakHeight = Math.max(2, (bucket.maxCpuPercent / maxCpuPercent) * 100);
500 const averageHeight = Math.max(2, (bucket.avgCpuPercent / maxCpuPercent) * 100);
501 return (
502 <Tooltip key={DateTime.formatIso(bucket.startedAt)}>
503 <TooltipTrigger
504 render={
505 <div className="flex h-full min-w-1 flex-1 items-end">
506 <div
507 className="relative h-full w-full"
508 aria-label={`Average CPU ${bucket.avgCpuPercent.toFixed(1)}%, peak CPU ${bucket.maxCpuPercent.toFixed(1)}%`}
509 >
510 <div
511 className="absolute inset-x-0 bottom-0 rounded-t-sm bg-foreground/15 transition-colors"
512 style={{ height: `${peakHeight}%` }}
513 />
514 <div
515 className="absolute inset-x-0 bottom-0 rounded-t-sm bg-foreground/60 transition-colors"
516 style={{ height: `${averageHeight}%` }}
517 />
518 </div>
519 </div>
520 }
521 />
522 <TooltipPopup side="top">
523 Avg {bucket.avgCpuPercent.toFixed(1)}%, peak {bucket.maxCpuPercent.toFixed(1)}%
524 </TooltipPopup>
525 </Tooltip>
526 );
527 })}
528 </div>
529 </div>
530 );
531}
532
533function ResourceHistoryWindowSelector({
534 selectedWindowMs,
535 onSelect,
536}: {
537 selectedWindowMs: number;
538 onSelect: (windowMs: number) => void;
539}) {
540 return (
541 <ToggleGroup
542 aria-label="Process history period"
543 variant="segmented"
544 value={[String(selectedWindowMs)]}
545 onValueChange={(next) => {
546 const selected = RESOURCE_HISTORY_WINDOWS.find(
547 (option) => String(option.windowMs) === next[0],
548 );
549 if (selected) onSelect(selected.windowMs);
550 }}
551 >
552 {RESOURCE_HISTORY_WINDOWS.map((option) => (
553 <Toggle key={option.windowMs} value={String(option.windowMs)}>
554 {option.label}
555 </Toggle>
556 ))}
557 </ToggleGroup>
558 );
559}
560
561function ProcessResourceHistoryTable({
562 processes,
563 emptyLabel,
564}: {
565 processes: ReadonlyArray<ServerProcessResourceHistorySummary>;
566 emptyLabel: string;
567}) {
568 const shallowestChildDepth = processes.reduce<number | null>((minDepth, process) => {
569 if (process.isServerRoot) return minDepth;
570 return minDepth === null ? process.depth : Math.min(minDepth, process.depth);
571 }, null);
572
573 return (
574 <div className="border-t border-border/60">
575 <ScrollArea
576 chainVerticalScroll
577 scrollFade
578 hideScrollbars
579 className="max-h-[min(64vh,44rem)] w-full max-w-full"
580 >
581 <table className="w-full min-w-[980px] table-fixed text-left text-xs">
582 <colgroup>
583 <col className="w-[24%]" />
584 <col className="w-[10%]" />
585 <col className="w-[10%]" />
586 <col className="w-[10%]" />
587 <col className="w-[10%]" />
588 <col className="w-[10%]" />
589 <col className="w-[16%]" />
590 <col className="w-[10%]" />
591 </colgroup>
592 <thead className="sticky top-0 z-10 border-b border-border/60 bg-card text-2xs uppercase tracking-widest text-muted-foreground/70">
593 <tr>
594 <th className="px-4 py-2 font-semibold sm:pl-5">Process</th>
595 <th className="px-3 py-2 text-right font-semibold">CPU Time</th>
596 <th className="px-3 py-2 text-right font-semibold">Current</th>
597 <th className="px-3 py-2 text-right font-semibold">Average</th>
598 <th className="px-3 py-2 text-right font-semibold">Peak</th>
599 <th className="px-3 py-2 text-right font-semibold">Max Mem</th>
600 <th className="px-3 py-2 font-semibold">Command</th>
601 <th className="px-3 py-2 text-right font-semibold sm:pr-5">PID</th>
602 </tr>
603 </thead>
604 <tbody className="divide-y divide-border/50">
605 {processes.length === 0 ? (
606 <tr>
607 <td colSpan={8} className="px-4 py-4 text-xs text-muted-foreground sm:px-5">
608 {emptyLabel}
609 </td>
610 </tr>
611 ) : null}
612 {processes.map((process) => (
613 <tr key={process.processKey} className="hover:bg-muted/20">
614 <td className="px-4 py-2 align-middle sm:pl-5">
615 <ResourceHistoryProcessNameCell
616 process={process}
617 visualDepth={
618 process.isServerRoot || shallowestChildDepth === null
619 ? 0
620 : Math.max(1, process.depth - shallowestChildDepth + 1)
621 }
622 />
623 </td>
624 <td className="px-3 py-2 text-right align-middle font-mono tabular-nums">
625 {formatCpuTime(process.cpuSecondsApprox)}
626 </td>
627 <td className="px-3 py-2 text-right align-middle font-mono tabular-nums">
628 {process.currentCpuPercent.toFixed(1)}%
629 </td>
630 <td className="px-3 py-2 text-right align-middle font-mono tabular-nums">
631 {process.avgCpuPercent.toFixed(1)}%
632 </td>
633 <td className="px-3 py-2 text-right align-middle font-mono tabular-nums">
634 {process.maxCpuPercent.toFixed(1)}%
635 </td>
636 <td className="px-3 py-2 text-right align-middle font-mono tabular-nums">
637 {formatBytes(process.maxRssBytes)}
638 </td>
639 <td className="px-3 py-2 align-middle text-muted-foreground">
640 <Tooltip>
641 <TooltipTrigger
642 render={<span className="block truncate">{process.command}</span>}
643 />
644 <TooltipPopup side="top" variant="code">
645 {process.command}
646 </TooltipPopup>
647 </Tooltip>
648 </td>
649 <td className="px-3 py-2 text-right align-middle font-mono tabular-nums text-muted-foreground sm:pr-5">
650 {process.pid}
651 </td>
652 </tr>
653 ))}
654 </tbody>
655 </table>
656 </ScrollArea>
657 </div>
658 );
659}
660
661function DiagnosticsLastChecked({ checkedAt }: { checkedAt: DateTime.Utc | null }) {
662 useRelativeTimeTick();
663 const relative = getRelativeTimeState(checkedAt ? DateTime.formatIso(checkedAt) : null);
664
665 if (relative.status === "missing") {
666 return <span className="text-2xs text-muted-foreground/50">Checking</span>;
667 }
668
669 if (relative.status === "invalid") {
670 return <span className="text-2xs text-muted-foreground/50">Checked unavailable</span>;
671 }
672
673 return (
674 <span className="text-2xs text-muted-foreground/60">
675 {relative.suffix ? (
676 <>
677 Checked <span className="font-mono tabular-nums">{relative.value}</span> {relative.suffix}
678 </>
679 ) : (
680 <>Checked {relative.value}</>
681 )}
682 </span>
683 );
684}
685
686function DiagnosticsRefreshButton({
687 isPending,
688 label,
689 onClick,
690}: {
691 isPending: boolean;
692 label: string;
693 onClick: () => void;
694}) {
695 return (
696 <Tooltip>
697 <TooltipTrigger
698 render={
699 <Button
700 size="icon-xs"
701 variant="ghost-muted"
702 disabled={isPending}
703 onClick={onClick}
704 aria-label={label}
705 >
706 <RefreshIcon refreshing={isPending} />
707 </Button>
708 }
709 />
710 <TooltipPopup side="top">{label}</TooltipPopup>
711 </Tooltip>
712 );
713}
714
715export function DiagnosticsSettingsPanel() {
716 const { environment } = useSettingsScope();
717 const environmentId = environment?.environmentId ?? null;
718 const canMaintainEnvironment = useEnvironmentScope(environmentId, AuthEnvironmentMaintainScope);
719 const observability = environment?.serverConfig?.observability;
720 const availableEditors = environment?.serverConfig?.availableEditors;
721 const canOpenHostEditor = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
722 const session = useEnvironmentQuery(
723 environmentId === null ? null : environmentSession.sessionStateAtom(environmentId),
724 );
725 const diagnosticsAccess = resolveUsageAccess({
726 connectionPhase: environment?.connection.phase ?? "available",
727 session: session.data,
728 hasSessionError: session.error !== null,
729 });
730 const canReadDiagnostics = diagnosticsAccess.canReadDiagnostics;
731 const signalServerProcess = useAtomCommand(serverEnvironment.signalProcess, {
732 reportFailure: false,
733 });
734 const openInEditor = useOpenInPreferredEditor(environmentId, availableEditors ?? []);
735 const [resourceWindowMs, setResourceWindowMs] = useState(15 * 60_000);
736 const selectedResourceWindow =
737 RESOURCE_HISTORY_WINDOWS.find((option) => option.windowMs === resourceWindowMs) ??
738 RESOURCE_HISTORY_WINDOWS[1];
739 const { data, error, isPending, refresh } = useEnvironmentQuery(
740 environmentId === null || !canReadDiagnostics
741 ? null
742 : serverEnvironment.traceDiagnostics({ environmentId, input: {} }),
743 );
744 const {
745 data: processData,
746 error: processError,
747 isPending: isProcessPending,
748 refresh: refreshProcesses,
749 } = useEnvironmentQuery(
750 environmentId === null || !canReadDiagnostics
751 ? null
752 : serverEnvironment.processDiagnostics({ environmentId, input: {} }),
753 );
754 const {
755 data: resourceData,
756 error: resourceError,
757 isPending: isResourcePending,
758 refresh: refreshResources,
759 } = useEnvironmentQuery(
760 environmentId === null || !canReadDiagnostics
761 ? null
762 : serverEnvironment.processResourceHistory({
763 environmentId,
764 input: {
765 windowMs: selectedResourceWindow.windowMs,
766 bucketMs: selectedResourceWindow.bucketMs,
767 },
768 }),
769 );
770 const [isOpeningLogsDirectory, setIsOpeningLogsDirectory] = useState(false);
771 const [openLogsDirectoryError, setOpenLogsDirectoryError] = useState<string | null>(null);
772 const [signalingPid, setSignalingPid] = useState<number | null>(null);
773 const signalingPidRef = useRef<number | null>(null);
774 const environmentIdRef = useRef(environmentId);
775 const processDataRef = useRef(processData);
776 useEffect(() => {
777 processDataRef.current = processData;
778 }, [processData]);
779 useEffect(() => {
780 environmentIdRef.current = environmentId;
781 return () => {
782 environmentIdRef.current = null;
783 };
784 }, [environmentId]);
785
786 const openLogsDirectory = useCallback(() => {
787 const logsDirectoryPath = observability?.logsDirectoryPath ?? null;
788 if (!logsDirectoryPath) return;
789
790 if (
791 environmentId === null ||
792 !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
793 ) {
794 return;
795 }
796
797 setIsOpeningLogsDirectory(true);
798 setOpenLogsDirectoryError(null);
799 void (async () => {
800 const result = await openInEditor(logsDirectoryPath);
801 setIsOpeningLogsDirectory(false);
802 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
803 const error = squashAtomCommandFailure(result);
804 setOpenLogsDirectoryError(
805 error instanceof Error ? error.message : "Unable to open logs folder.",
806 );
807 }
808 })();
809 }, [environmentId, observability?.logsDirectoryPath, openInEditor]);
810
811 const isInitialLoading = isPending && data === null;
812 const isProcessInitialLoading = isProcessPending && processData === null;
813 const isResourceInitialLoading = isResourcePending && resourceData === null;
814 // The export form waits for each environment's first tables so a search target below them
815 // stays in view. Later loads, such as a new resource window, must not remount it and drop drafts.
816 const [exportFormEnvironmentId, setExportFormEnvironmentId] =
817 useState<typeof environmentId>(null);
818 if (
819 exportFormEnvironmentId !== environmentId &&
820 canReadDiagnostics &&
821 !isInitialLoading &&
822 !isProcessInitialLoading &&
823 !isResourceInitialLoading
824 ) {
825 setExportFormEnvironmentId(environmentId);
826 }
827 const signalProcess = useCallback(
828 async (pid: number, signal: ServerProcessSignal) => {
829 const targetEnvironmentId = environmentIdRef.current;
830 const process = processDataRef.current?.processes.find((entry) => entry.pid === pid);
831 if (
832 targetEnvironmentId === null ||
833 process === undefined ||
834 !readEnvironmentScope(targetEnvironmentId, AuthEnvironmentMaintainScope)
835 )
836 return;
837 if (signalingPidRef.current !== null) return;
838 signalingPidRef.current = pid;
839 setSignalingPid(pid);
840 const clearSignaling = () => {
841 signalingPidRef.current = null;
842 setSignalingPid(null);
843 };
844 if (signal === "SIGKILL") {
845 let confirmed = false;
846 try {
847 confirmed = await ensureLocalApi().dialogs.confirm(
848 `Send SIGKILL to process ${pid}? This cannot be handled by the process.`,
849 { variant: "destructive" },
850 );
851 } catch (error) {
852 clearSignaling();
853 toastManager.add({
854 type: "error",
855 title: "Could not confirm signal",
856 description: error instanceof Error ? error.message : `Failed to send ${signal}.`,
857 });
858 return;
859 }
860 if (!confirmed) {
861 clearSignaling();
862 return;
863 }
864 }
865 const currentEnvironmentId = environmentIdRef.current;
866 if (
867 currentEnvironmentId === null ||
868 currentEnvironmentId !== targetEnvironmentId ||
869 !readEnvironmentScope(currentEnvironmentId, AuthEnvironmentMaintainScope)
870 ) {
871 clearSignaling();
872 return;
873 }
874 if (
875 processDataRef.current?.processes.find((entry) => entry.pid === pid)?.startTimeMs !==
876 process.startTimeMs
877 ) {
878 clearSignaling();
879 return;
880 }
881
882 try {
883 const result = await signalServerProcess({
884 environmentId: targetEnvironmentId,
885 input: { pid, startTimeMs: process.startTimeMs, signal },
886 });
887 if (result._tag === "Failure") {
888 if (!isAtomCommandInterrupted(result)) {
889 const error = squashAtomCommandFailure(result);
890 toastManager.add({
891 type: "error",
892 title: `Could not send ${signal}`,
893 description: error instanceof Error ? error.message : `Failed to send ${signal}.`,
894 });
895 }
896 return;
897 }
898 if (!result.value.signaled) {
899 const message = Option.getOrUndefined(result.value.message);
900 refreshProcesses();
901 if (isStaleProcessSignalMessage(message)) {
902 toastManager.add({
903 type: "info",
904 title: "Process already exited",
905 description:
906 "The process is not a child of the T3 Server. It might already have exited.",
907 });
908 return;
909 }
910
911 toastManager.add({
912 type: "error",
913 title: `Could not send ${signal}`,
914 description: message ?? `Failed to send ${signal}.`,
915 });
916 return;
917 }
918 refreshProcesses();
919 } finally {
920 clearSignaling();
921 }
922 },
923 [refreshProcesses, signalServerProcess],
924 );
925
926 const processDiagnosticsError = processData ? Option.getOrNull(processData.error) : null;
927 const processResourceError = resourceData ? Option.getOrNull(resourceData.error) : null;
928 const traceDiagnosticsError = data ? Option.getOrNull(data.error) : null;
929 const traceDiagnosticsPartialFailure = data
930 ? Option.getOrElse(data.partialFailure, () => false)
931 : false;
932
933 if (!canReadDiagnostics) {
934 return (
935 <SettingsPageContainer>
936 <p className="text-sm text-muted-foreground">
937 {environmentId === null
938 ? "Connect an environment to see diagnostics."
939 : diagnosticsAccess.isPending
940 ? "Checking diagnostics access…"
941 : diagnosticsAccess.error}
942 </p>
943 </SettingsPageContainer>
944 );
945 }
946
947 return (
948 <SettingsPageContainer width="expanded" className="gap-10">
949 <ResourceTelemetryDiagnostics environmentId={environmentId} />
950
951 <SettingsSection
952 title="Live Processes"
953 headerAction={
954 <div className="flex items-center gap-1.5">
955 <DiagnosticsLastChecked checkedAt={processData?.readAt ?? null} />
956 <DiagnosticsRefreshButton
957 isPending={isProcessPending}
958 label="Refresh process diagnostics"
959 onClick={refreshProcesses}
960 />
961 </div>
962 }
963 >
964 <StatsGrid>
965 <StatBlock
966 label="Child Processes"
967 value={processData ? formatCount(processData.processCount) : "..."}
968 />
969 <StatBlock
970 label="CPU"
971 value={processData ? `${processData.totalCpuPercent.toFixed(1)}%` : "..."}
972 tooltip="Total CPU across live child processes of the current server process. The desktop shell and other parent processes are not included."
973 />
974 <StatBlock
975 label="Memory"
976 value={processData ? formatBytes(processData.totalRssBytes) : "..."}
977 tooltip="Total resident memory across live child processes of the current server process. The desktop shell and other parent processes are not included."
978 />
979 <StatBlock
980 label="Server PID"
981 value={processData ? String(processData.serverPid) : "..."}
982 />
983 </StatsGrid>
984 {processDiagnosticsError || processError ? (
985 <div className="space-y-2 border-t border-border/60 px-4 py-3 text-xs text-muted-foreground sm:px-5">
986 {processDiagnosticsError ? (
987 <div className="flex items-start gap-2 text-destructive">
988 <AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
989 <span>{processDiagnosticsError.message}</span>
990 </div>
991 ) : null}
992 {processError ? (
993 <div className="flex items-start gap-2 text-destructive">
994 <AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
995 <span>{processError}</span>
996 </div>
997 ) : null}
998 </div>
999 ) : null}
1000 <ProcessDiagnosticsTable
1001 processes={processData?.processes ?? []}
1002 canMaintainEnvironment={canMaintainEnvironment}
1003 signalingPid={signalingPid}
1004 onSignal={signalProcess}
1005 emptyLabel={
1006 isProcessInitialLoading
1007 ? "Loading live processes..."
1008 : "No live descendant processes found."
1009 }
1010 />
1011 </SettingsSection>
1012
1013 <SettingsSection
1014 title="Resource History"
1015 headerAction={
1016 <div className="flex items-center gap-1.5">
1017 <ResourceHistoryWindowSelector
1018 selectedWindowMs={resourceWindowMs}
1019 onSelect={setResourceWindowMs}
1020 />
1021 <DiagnosticsLastChecked checkedAt={resourceData?.readAt ?? null} />
1022 <DiagnosticsRefreshButton
1023 isPending={isResourcePending}
1024 label="Refresh resource history"
1025 onClick={refreshResources}
1026 />
1027 </div>
1028 }
1029 >
1030 <StatsGrid>
1031 <StatBlock
1032 label="CPU Time"
1033 value={resourceData ? formatCpuTime(resourceData.totalCpuSecondsApprox) : "..."}
1034 tooltip="Approximate active CPU time for the T3 server root process and its descendants during the selected window. It grows only while sampled processes use CPU and older samples leave as the window moves."
1035 />
1036 <StatBlock
1037 label="Samples"
1038 value={resourceData ? formatCount(resourceData.retainedSampleCount) : "..."}
1039 tooltip="In-memory process samples retained by the server. The server samples only while diagnostics is open, and this resets when the server restarts."
1040 />
1041 <StatBlock
1042 label="Interval"
1043 value={
1044 resourceData
1045 ? resourceData.sampleIntervalMs === 0
1046 ? "On demand"
1047 : formatDuration(resourceData.sampleIntervalMs)
1048 : "..."
1049 }
1050 />
1051 <StatBlock
1052 label="Processes"
1053 value={resourceData ? formatCount(resourceData.topProcesses.length) : "..."}
1054 />
1055 </StatsGrid>
1056 {processResourceError || resourceError ? (
1057 <div className="space-y-2 border-t border-border/60 px-4 py-3 text-xs text-muted-foreground sm:px-5">
1058 {processResourceError ? (
1059 <div className="flex items-start gap-2 text-destructive">
1060 <AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
1061 <span>{processResourceError.message}</span>
1062 </div>
1063 ) : null}
1064 {resourceError ? (
1065 <div className="flex items-start gap-2 text-destructive">
1066 <AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
1067 <span>{resourceError}</span>
1068 </div>
1069 ) : null}
1070 </div>
1071 ) : null}
1072 <ProcessResourceHistoryChart buckets={resourceData?.buckets ?? []} />
1073 <ProcessResourceHistoryTable
1074 processes={resourceData?.topProcesses ?? []}
1075 emptyLabel={
1076 isResourceInitialLoading
1077 ? "Collecting process resource samples..."
1078 : "No process resource samples found for this window."
1079 }
1080 />
1081 </SettingsSection>
1082
1083 <SettingsSection
1084 title="Trace Diagnostics"
1085 headerAction={
1086 <div className="flex items-center gap-1.5">
1087 <DiagnosticsLastChecked checkedAt={data?.readAt ?? null} />
1088 <Tooltip>
1089 <TooltipTrigger
1090 render={
1091 <Button
1092 size="icon-xs"
1093 variant="ghost-muted"
1094 disabled={
1095 !canOpenHostEditor ||
1096 !observability?.logsDirectoryPath ||
1097 isOpeningLogsDirectory
1098 }
1099 onClick={openLogsDirectory}
1100 aria-label="Open logs folder"
1101 >
1102 <FolderOpenIcon />
1103 </Button>
1104 }
1105 />
1106 <TooltipPopup side="top">Open logs folder</TooltipPopup>
1107 </Tooltip>
1108 <DiagnosticsRefreshButton
1109 isPending={isPending}
1110 label="Refresh trace diagnostics"
1111 onClick={refresh}
1112 />
1113 </div>
1114 }
1115 >
1116 <StatsGrid>
1117 <StatBlock label="Spans" value={data ? formatCount(data.recordCount) : "..."} />
1118 <StatBlock
1119 label="Failures"
1120 value={data ? formatCount(data.failureCount) : "..."}
1121 tone={data && data.failureCount > 0 ? "danger" : "default"}
1122 />
1123 <StatBlock
1124 label="Slow Spans"
1125 value={data ? formatCount(data.slowSpanCount) : "..."}
1126 tooltip={
1127 data
1128 ? `Spans with a duration of ${formatDuration(data.slowSpanThresholdMs)} or longer.`
1129 : "Spans at or above the configured slow-span threshold."
1130 }
1131 tone={data && data.slowSpanCount > 0 ? "warning" : "default"}
1132 />
1133 <StatBlock
1134 label="Parse Errors"
1135 value={data ? formatCount(data.parseErrorCount) : "..."}
1136 tone={data && data.parseErrorCount > 0 ? "warning" : "default"}
1137 />
1138 </StatsGrid>
1139 {openLogsDirectoryError || traceDiagnosticsError || error ? (
1140 <div className="space-y-2 border-t border-border/60 px-4 py-3 text-xs text-muted-foreground sm:px-5">
1141 {openLogsDirectoryError ? (
1142 <div className="flex items-start gap-2 text-destructive">
1143 <AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
1144 <span>{openLogsDirectoryError}</span>
1145 </div>
1146 ) : null}
1147 {traceDiagnosticsError ? (
1148 <div
1149 className={cn(
1150 "flex items-start gap-2",
1151 traceDiagnosticsPartialFailure ? "text-warning-foreground" : "text-destructive",
1152 )}
1153 >
1154 <AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
1155 <span>
1156 {traceDiagnosticsPartialFailure
1157 ? `Some trace files could not be read, so diagnostics may be incomplete. ${traceDiagnosticsError.message}`
1158 : traceDiagnosticsError.message}
1159 </span>
1160 </div>
1161 ) : null}
1162 {error ? (
1163 <div className="flex items-start gap-2 text-destructive">
1164 <AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
1165 <span>{error}</span>
1166 </div>
1167 ) : null}
1168 </div>
1169 ) : null}
1170 </SettingsSection>
1171
1172 <SettingsSection title="Latest Failures">
1173 {data && data.latestFailures.length > 0 ? (
1174 <DiagnosticsTable headers={["Span", "Cause", "Duration", "Ended"]}>
1175 {data.latestFailures.map((failure) => (
1176 <tr key={`${failure.traceId}:${failure.spanId}`}>
1177 <td className="px-4 py-3 align-top text-xs font-medium text-foreground first:sm:pl-5">
1178 {failure.name}
1179 </td>
1180 <td className="max-w-[360px] px-4 py-3 align-top text-muted-foreground">
1181 <ExpandableText text={failure.cause} />
1182 </td>
1183 <td className="px-4 py-3 align-top font-mono tabular-nums">
1184 {formatDuration(failure.durationMs)}
1185 </td>
1186 <td className="whitespace-nowrap px-4 py-3 align-top font-mono tabular-nums text-muted-foreground last:sm:pr-5">
1187 {formatRelativeNoWrap(failure.endedAt)}
1188 </td>
1189 </tr>
1190 ))}
1191 </DiagnosticsTable>
1192 ) : (
1193 <EmptyRows label={isInitialLoading ? "Loading failures..." : "No failed spans found."} />
1194 )}
1195 </SettingsSection>
1196
1197 <SettingsSection title="Most Common Failures">
1198 {data && data.commonFailures.length > 0 ? (
1199 <DiagnosticsTable
1200 headers={["Span", "Count", "Cause", "Last Seen"]}
1201 minTableWidth="min-w-[760px]"
1202 >
1203 {data.commonFailures.map((failure) => (
1204 <tr key={`${failure.name}:${failure.cause}`}>
1205 <td className="px-4 py-3 align-top text-xs font-medium text-foreground first:sm:pl-5">
1206 {failure.name}
1207 </td>
1208 <td className="px-4 py-3 align-top font-mono tabular-nums">
1209 {formatCount(failure.count)}
1210 </td>
1211 <td className="max-w-[360px] px-4 py-3 align-top text-muted-foreground">
1212 <ExpandableText text={failure.cause} />
1213 </td>
1214 <td className="w-px whitespace-nowrap px-4 py-3 align-top font-mono tabular-nums text-muted-foreground last:sm:pr-5">
1215 {formatRelativeNoWrap(failure.lastSeenAt)}
1216 </td>
1217 </tr>
1218 ))}
1219 </DiagnosticsTable>
1220 ) : (
1221 <EmptyRows
1222 label={isInitialLoading ? "Loading failure groups..." : "No repeated failures found."}
1223 />
1224 )}
1225 </SettingsSection>
1226
1227 <SettingsSection title="Slowest Spans">
1228 {data && data.slowestSpans.length > 0 ? (
1229 <DiagnosticsTable
1230 headers={["Span", "Duration", "Ended", "Trace"]}
1231 minTableWidth="min-w-[900px]"
1232 columnWidths={["w-[44%]", "w-[14%]", "w-[12%]", "w-[30%]"]}
1233 >
1234 {data.slowestSpans.map((span) => (
1235 <tr key={`${span.traceId}:${span.spanId}`}>
1236 <td className="px-4 py-3 align-top text-xs font-medium text-foreground first:sm:pl-5">
1237 {span.name}
1238 </td>
1239 <td className="px-4 py-3 align-top font-mono tabular-nums">
1240 {formatDuration(span.durationMs)}
1241 </td>
1242 <td className="w-px whitespace-nowrap px-4 py-3 align-top font-mono tabular-nums text-muted-foreground">
1243 {formatRelativeNoWrap(span.endedAt)}
1244 </td>
1245 <td className="min-w-0 whitespace-nowrap px-4 py-3 align-top text-muted-foreground last:sm:pr-5">
1246 <TraceIdCell traceId={span.traceId} />
1247 </td>
1248 </tr>
1249 ))}
1250 </DiagnosticsTable>
1251 ) : (
1252 <EmptyRows label={isInitialLoading ? "Loading slow spans..." : "No spans found."} />
1253 )}
1254 </SettingsSection>
1255
1256 <SettingsSection title="Span Logs">
1257 {data && data.latestWarningAndErrorLogs.length > 0 ? (
1258 <ScrollArea
1259 radius="none"
1260 chainVerticalScroll
1261 scrollFade
1262 hideScrollbars
1263 className="w-full max-w-full"
1264 >
1265 <table className="w-full min-w-[920px] table-fixed text-left text-xs">
1266 <colgroup>
1267 <col className="w-[11%]" />
1268 <col className="w-[9%]" />
1269 <col className="w-[24%]" />
1270 <col className="w-[26%]" />
1271 <col className="w-[30%]" />
1272 </colgroup>
1273 <thead className="border-b border-border/60 text-2xs uppercase tracking-widest text-muted-foreground/70">
1274 <tr>
1275 <th className="whitespace-nowrap px-4 py-2.5 font-semibold sm:pl-5">Time</th>
1276 <th className="whitespace-nowrap px-4 py-2.5 font-semibold">Level</th>
1277 <th className="whitespace-nowrap px-4 py-2.5 font-semibold">Span</th>
1278 <th className="whitespace-nowrap px-4 py-2.5 font-semibold">Message</th>
1279 <th className="whitespace-nowrap px-4 py-2.5 font-semibold sm:pr-5">Trace</th>
1280 </tr>
1281 </thead>
1282 <tbody className="divide-y divide-border/60">
1283 {data.latestWarningAndErrorLogs.map((event) => (
1284 <tr
1285 key={`${event.traceId}:${event.spanId}:${DateTime.formatIso(event.seenAt)}:${event.message}`}
1286 className="hover:bg-muted/15"
1287 >
1288 <td className="whitespace-nowrap px-4 py-3 align-top font-mono tabular-nums text-muted-foreground sm:pl-5">
1289 {formatRelativeNoWrap(event.seenAt)}
1290 </td>
1291 <td className="px-4 py-3 align-top">
1292 <span className="inline-flex rounded bg-muted px-1.5 py-0.5 font-mono text-2xs font-medium uppercase text-foreground/80">
1293 {event.level}
1294 </span>
1295 </td>
1296 <td className="px-4 py-3 align-top">
1297 <div className="truncate font-medium text-foreground">{event.spanName}</div>
1298 </td>
1299 <td className="px-4 py-3 align-top text-muted-foreground">
1300 <ExpandableText
1301 collapsedClassName="line-clamp-2"
1302 expandLabel="Show full message"
1303 text={event.message}
1304 />
1305 </td>
1306 <td className="min-w-0 whitespace-nowrap px-4 py-3 align-top text-muted-foreground sm:pr-5">
1307 <TraceIdCell traceId={event.traceId} />
1308 </td>
1309 </tr>
1310 ))}
1311 </tbody>
1312 </table>
1313 </ScrollArea>
1314 ) : (
1315 <EmptyRows
1316 label={isInitialLoading ? "Loading recent logs..." : "No warnings or errors found."}
1317 />
1318 )}
1319 </SettingsSection>
1320
1321 <SettingsSection title="Top Span Names">
1322 {data && data.topSpansByCount.length > 0 ? (
1323 <DiagnosticsTable
1324 headers={["Span", "Count", "Failures", "Average", "Max"]}
1325 minTableWidth="min-w-[760px]"
1326 columnWidths={["w-[48%]", "w-[13%]", "w-[13%]", "w-[13%]", "w-[13%]"]}
1327 >
1328 {data.topSpansByCount.map((span) => (
1329 <tr key={span.name}>
1330 <td className="px-4 py-3 align-top text-xs font-medium text-foreground first:sm:pl-5">
1331 {span.name}
1332 </td>
1333 <td className="whitespace-nowrap px-4 py-3 align-top font-mono tabular-nums">
1334 {formatCount(span.count)}
1335 </td>
1336 <td className="whitespace-nowrap px-4 py-3 align-top font-mono tabular-nums">
1337 {formatCount(span.failureCount)}
1338 </td>
1339 <td className="whitespace-nowrap px-4 py-3 align-top font-mono tabular-nums">
1340 {formatDuration(span.averageDurationMs)}
1341 </td>
1342 <td className="whitespace-nowrap px-4 py-3 align-top font-mono tabular-nums last:sm:pr-5">
1343 {formatDuration(span.maxDurationMs)}
1344 </td>
1345 </tr>
1346 ))}
1347 </DiagnosticsTable>
1348 ) : (
1349 <EmptyRows label={isInitialLoading ? "Loading span names..." : "No spans found."} />
1350 )}
1351 </SettingsSection>
1352 {exportFormEnvironmentId === environmentId && <TelemetryExportSettings />}
1353 </SettingsPageContainer>
1354 );
1355}