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