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

DiagnosticsSettings.tsx

1,304 lines47.0 KB

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