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