Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DiagnosticsSettings.tsx

1,300 lines47.3 KB

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