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