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

ResourceTelemetryDiagnostics.tsx

1,283 lines47.8 KB

1import { ProcessSignalActions } from "./ProcessSignalActions";
2import { RefreshIcon } from "~/components/ui/refresh-icon";
3import {
4 ActivityIcon,
5 AlertTriangleIcon,
6 BatteryIcon,
7 ChevronDownIcon,
8 ChevronRightIcon,
9 CpuIcon,
10 DatabaseIcon,
11 GaugeIcon,
12 HardDriveIcon,
13 MemoryStickIcon,
14} from "lucide-react";
15import type {
16 BackgroundBooleanState,
17 EnvironmentId,
18 ResourceAttributionEntry,
19 ResourceTelemetryAggregate,
20 ResourceTelemetryHistoryBucket,
21 ResourceTelemetryIoSemantics,
22 ResourceTelemetryProcess,
23 ResourceTelemetryProcessCategory,
24 ResourceTelemetryProcessSummary,
25 ResourceTelemetrySourceHealth,
26 ResourceTelemetrySourceStatus,
27 ServerProcessSignal,
28} from "@t3tools/contracts";
29import * as DateTime from "effect/DateTime";
30import * as Option from "effect/Option";
31import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
32import {
33 isAtomCommandInterrupted,
34 squashAtomCommandFailure,
35} from "@t3tools/client-runtime/state/runtime";
36​
37import {
38 useResourceTelemetry,
39 useResourceTelemetryHistory,
40} from "../../lib/resourceTelemetryState";
41import { cn } from "../../lib/utils";
42import { ensureLocalApi } from "../../localApi";
43import { serverEnvironment } from "../../state/server";
44import { useAtomCommand } from "../../state/use-atom-command";
45import { formatRelativeTime } from "../../timestampFormat";
46import { Button } from "../ui/button";
47import { ScrollArea } from "../ui/scroll-area";
48import { Toggle, ToggleGroup } from "../ui/toggle-group";
49import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
50import { toastManager } from "../ui/toast";
51import {
52 resourceHistoryBarHeight,
53 resourceHistoryCpuScaleMax,
54 shouldShowResourceMonitorRetry,
55 visibleResourceTelemetryProcesses,
56} from "./ResourceTelemetryDiagnostics.logic";
57import { SettingsSection, useRelativeTimeTick } from "./settingsLayout";
58​
59const HISTORY_WINDOWS = [
60 { label: "5m", windowMs: 5 * 60_000, bucketMs: 15_000 },
61 { label: "15m", windowMs: 15 * 60_000, bucketMs: 30_000 },
62 { label: "30m", windowMs: 30 * 60_000, bucketMs: 60_000 },
63 { label: "1h", windowMs: 60 * 60_000, bucketMs: 2 * 60_000 },
64] as const;
65​
66function formatBytes(value: number): string {
67 if (value < 1_024) return `${Math.round(value)} B`;
68 const units = ["KB", "MB", "GB", "TB"] as const;
69 let next = value;
70 let unitIndex = -1;
71 do {
72 next /= 1_024;
73 unitIndex += 1;
74 } while (next >= 1_024 && unitIndex < units.length - 1);
75 return `${next.toFixed(next >= 100 ? 0 : next >= 10 ? 1 : 2)} ${units[unitIndex]}`;
77​
78function formatRate(value: number): string {
79 return `${formatBytes(value)}/s`;
81​
82function formatCpuTime(valueMs: number): string {
83 const seconds = valueMs / 1_000;
84 if (seconds < 60) return `${seconds.toFixed(seconds >= 10 ? 1 : 2)}s`;
85 const minutes = seconds / 60;
86 if (minutes < 60) return `${minutes.toFixed(minutes >= 10 ? 1 : 2)}m`;
87 return `${(minutes / 60).toFixed(2)}h`;
89​
90function formatDurationMicros(value: number): string {
91 if (value < 1_000) return `${Math.round(value)} µs`;
92 if (value < 1_000_000) return `${(value / 1_000).toFixed(2)} ms`;
93 return `${(value / 1_000_000).toFixed(2)} s`;
95​
96function formatSampleInterval(valueMs: number): string {
97 if (valueMs < 1_000) return `${Math.max(0, Math.round(valueMs))} ms`;
98 const seconds = valueMs / 1_000;
99 return `${seconds.toLocaleString(undefined, { maximumFractionDigits: 1 })} ${
100 seconds === 1 ? "second" : "seconds"
101 }`;
103​
104function processIdentityKey(process: ResourceTelemetryProcess): string {
105 return `${process.identity.pid}:${process.identity.startTimeMs}`;
107​
108function processSummaryIdentityKey(process: ResourceTelemetryProcessSummary): string {
109 return `${process.identity.pid}:${process.identity.startTimeMs}`;
111​
112function formatProcessName(process: Pick<ResourceTelemetryProcess, "command" | "name">): string {
113 if (process.name.trim()) return process.name;
114 const firstToken = process.command.trim().split(/\s+/)[0] ?? process.command;
115 const normalized = firstToken.replace(/^['"]|['"]$/g, "");
116 return normalized.split(/[\\/]/).findLast((segment) => segment.length > 0) ?? normalized;
118​
119function categoryLabel(category: ResourceTelemetryProcessCategory): string {
120 switch (category) {
121 case "server":
122 return "Server";
123 case "server-child":
124 return "Backend child";
125 case "provider-root":
126 return "Provider";
127 case "terminal-root":
128 return "Terminal";
129 case "electron-main":
130 return "Electron main";
131 case "electron-renderer":
132 return "Renderer";
133 case "electron-gpu":
134 return "GPU";
135 case "electron-utility":
136 return "Electron utility";
137 case "resource-monitor":
138 return "Monitor";
139 case "unknown-t3":
140 return "T3 process";
141 }
143​
144function categoryDotClass(category: ResourceTelemetryProcessCategory): string {
145 if (category === "resource-monitor") return "bg-amber-500";
146 if (category.startsWith("electron-")) return "bg-sky-500";
147 if (category === "server") return "bg-violet-500";
148 return "bg-emerald-500";
150​
151function ioSemanticsLabel(semantics: ResourceTelemetryIoSemantics): string {
152 switch (semantics) {
153 case "storage":
154 return "Storage bytes";
155 case "logical":
156 return "Logical bytes";
157 case "all-io":
158 return "All I/O bytes";
159 case "unavailable":
160 return "Unavailable";
161 }
163​
164function booleanStateLabel(
165 value: BackgroundBooleanState,
166 labels: { readonly true: string; readonly false: string },
167): string {
168 if (value === "true") return labels.true;
169 if (value === "false") return labels.false;
170 return "Unknown";
172​
173function sourceStatusTone(status: ResourceTelemetrySourceStatus): "default" | "warning" | "danger" {
174 if (status === "healthy") return "default";
175 if (status === "starting" || status === "degraded") return "warning";
176 return "danger";
178​
179function SourceStatusBadge({
180 label,
181 status,
182 presentation,
183}: {
184 label: string;
185 status: ResourceTelemetrySourceStatus;
186 presentation?:
187 | {
188 readonly label: string;
189 readonly tone: "neutral";
190 }
191 | undefined;
192}) {
193 const tone = presentation?.tone ?? sourceStatusTone(status);
194 return (
195 <span
196 className={cn(
197 "inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.08em]",
198 tone === "neutral" && "border-border/70 bg-muted/45 text-muted-foreground",
199 tone === "default" &&
200 "border-emerald-500/25 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300",
201 tone === "warning" &&
202 "border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-300",
203 tone === "danger" && "border-destructive/30 bg-destructive/10 text-destructive",
204 )}
205 >
206 <span
207 className={cn(
208 "size-1.5 rounded-full",
209 tone === "neutral" && "bg-muted-foreground/55",
210 tone === "default" && "bg-emerald-500",
211 tone === "warning" && "bg-amber-500",
212 tone === "danger" && "bg-destructive",
213 )}
214 />
215 {label} {presentation?.label ?? status}
216 </span>
217 );
219​
220function LastSampleLabel({ sampledAt }: { sampledAt: DateTime.Utc | null }) {
221 useRelativeTimeTick();
222 if (!sampledAt) {
223 return <span className="text-[11px] text-muted-foreground/55">Waiting for sample</span>;
224 }
225 const relative = formatRelativeTime(DateTime.formatIso(sampledAt));
226 if (!relative) {
227 return <span className="text-[11px] text-muted-foreground/55">Waiting for sample</span>;
228 }
229 return (
230 <span className="text-[11px] text-muted-foreground/60">
231 Updated <span className="font-mono tabular-nums">{relative.value}</span>
232 {relative.suffix ? ` ${relative.suffix}` : ""}
233 </span>
234 );
236​
237function IconStat({
238 icon,
239 label,
240 value,
241 detail,
242 tone = "default",
243}: {
244 icon: ReactNode;
245 label: string;
246 value: string;
247 detail?: string | undefined;
248 tone?: "default" | "warning" | "danger";
249}) {
250 return (
251 <div className="group min-w-0 px-4 py-4 sm:px-5">
252 <div className="flex items-center gap-2 text-[10px] font-semibold uppercase tracking-[0.11em] text-muted-foreground/70">
253 <span className="text-muted-foreground/55 transition-colors group-hover:text-foreground/65">
254 {icon}
255 </span>
256 <span className="truncate">{label}</span>
257 </div>
258 <div
259 className={cn(
260 "mt-2.5 truncate font-mono text-2xl font-semibold tracking-[-0.05em] tabular-nums text-foreground",
261 tone === "warning" && "text-amber-600 dark:text-amber-300",
262 tone === "danger" && "text-destructive",
263 )}
264 >
265 {value}
266 </div>
267 {detail ? (
268 <div className="mt-1.5 truncate text-[10px] text-muted-foreground/60">{detail}</div>
269 ) : null}
270 </div>
271 );
273​
274function AggregateCard({
275 label,
276 accentClass,
277 aggregate,
278}: {
279 label: string;
280 accentClass: string;
281 aggregate: ResourceTelemetryAggregate;
282}) {
283 return (
284 <div className="relative overflow-hidden border-t border-border/60 px-4 py-4 first:border-t-0 md:border-t-0 md:border-l md:first:border-l-0 sm:px-5">
285 <span className={cn("absolute inset-x-5 top-0 h-0.5 rounded-full opacity-75", accentClass)} />
286 <div className="flex items-center justify-between gap-3">
287 <div className="text-[10px] font-semibold uppercase tracking-[0.11em] text-muted-foreground/75">
288 {label}
289 </div>
290 <div className="rounded-md bg-muted/55 px-1.5 py-0.5 font-mono text-[9px] tabular-nums text-muted-foreground/70">
291 {aggregate.processCount} {aggregate.processCount === 1 ? "process" : "processes"}
292 </div>
293 </div>
294 <div className="mt-3.5 grid grid-cols-2 gap-x-4 gap-y-2.5">
295 <MetricPair label="CPU" value={`${aggregate.currentCpuPercent.toFixed(1)}%`} />
296 <MetricPair label="Memory" value={formatBytes(aggregate.currentRssBytes)} />
297 <MetricPair label="Read" value={formatRate(aggregate.ioReadBytesPerSecond)} />
298 <MetricPair label="Write" value={formatRate(aggregate.ioWriteBytesPerSecond)} />
299 </div>
300 </div>
301 );
303​
304function MetricPair({ label, value }: { label: string; value: string }) {
305 return (
306 <div className="min-w-0">
307 <div className="text-[9px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/45">
308 {label}
309 </div>
310 <div className="truncate font-mono text-xs font-medium tabular-nums text-foreground/90">
311 {value}
312 </div>
313 </div>
314 );
316​
317function HealthSource({ label, health }: { label: string; health: ResourceTelemetrySourceHealth }) {
318 const expectedInBrowser =
319 health.status === "unavailable" &&
320 Option.exists(health.lastError, (error) => error.includes("'web' mode"));
321 return (
322 <div className="flex items-start justify-between gap-4 border-t border-border/50 py-3 first:border-t-0">
323 <div className="min-w-0">
324 <div className="text-[13px] font-medium text-foreground">{label}</div>
325 <div className="mt-1 text-[11px] leading-relaxed text-muted-foreground/65">
326 {expectedInBrowser
327 ? "Available when this page runs inside the desktop app."
328 : Option.match(health.lastError, {
329 onNone: () => "No reported errors",
330 onSome: (error) => error,
331 })}
332 </div>
333 </div>
334 <SourceStatusBadge
335 label=""
336 status={health.status}
337 presentation={
338 expectedInBrowser
339 ? {
340 label: "Desktop only",
341 tone: "neutral",
342 }
343 : undefined
344 }
345 />
346 </div>
347 );
349​
350function DetailRow({
351 label,
352 value,
353 valueClassName,
354}: {
355 label: string;
356 value: ReactNode;
357 valueClassName?: string | undefined;
358}) {
359 return (
360 <div className="flex items-center justify-between gap-4 border-t border-border/50 py-2.5 first:border-t-0">
361 <span className="text-[11px] text-muted-foreground/75">{label}</span>
362 <span
363 className={cn(
364 "min-w-0 truncate text-right font-mono text-[11px] tabular-nums text-foreground/85",
365 valueClassName,
366 )}
367 >
368 {value}
369 </span>
370 </div>
371 );
373​
374function HistoryWindowSelector({
375 selectedWindowMs,
376 onSelect,
377}: {
378 selectedWindowMs: number;
379 onSelect: (windowMs: number) => void;
380}) {
381 return (
382 <ToggleGroup
383 aria-label="Resource history period"
384 variant="segmented"
385 value={[String(selectedWindowMs)]}
386 onValueChange={(next) => {
387 const selected = HISTORY_WINDOWS.find((option) => String(option.windowMs) === next[0]);
388 if (selected) onSelect(selected.windowMs);
389 }}
390 >
391 {HISTORY_WINDOWS.map((option) => (
392 <Toggle key={option.windowMs} value={String(option.windowMs)}>
393 {option.label}
394 </Toggle>
395 ))}
396 </ToggleGroup>
397 );
399​
400function ResourceHistoryChart({
401 buckets,
402}: {
403 buckets: ReadonlyArray<ResourceTelemetryHistoryBucket>;
404}) {
405 const maxCpu = resourceHistoryCpuScaleMax(buckets);
406 const maxIo = Math.max(1, ...buckets.map((bucket) => bucket.ioReadBytes + bucket.ioWriteBytes));
407​
408 return (
409 <div className="border-t border-border/60 px-4 py-4 sm:px-5">
410 <div className="mb-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-[10px] text-muted-foreground/65">
411 <span className="inline-flex items-center gap-1.5">
412 <span className="h-1.5 w-3 rounded-full bg-foreground/70" /> CPU average
413 </span>
414 <span className="inline-flex items-center gap-1.5">
415 <span className="h-1.5 w-3 rounded-full bg-sky-500/70" /> I/O reads
416 </span>
417 <span className="inline-flex items-center gap-1.5">
418 <span className="h-1.5 w-3 rounded-full bg-amber-500/80" /> I/O writes
419 </span>
420 </div>
421 <div className="flex h-32 items-end gap-1 overflow-hidden rounded-lg border border-border/40 bg-muted/8 px-2 pt-3 pb-2">
422 {buckets.map((bucket) => {
423 const cpuHeight = resourceHistoryBarHeight({
424 value: bucket.avgCpuPercent,
425 max: maxCpu,
426 minimumVisiblePercent: 2,
427 });
428 const readHeight = resourceHistoryBarHeight({
429 value: bucket.ioReadBytes,
430 max: maxIo,
431 minimumVisiblePercent: 1,
432 });
433 const writeHeight = resourceHistoryBarHeight({
434 value: bucket.ioWriteBytes,
435 max: maxIo,
436 minimumVisiblePercent: 1,
437 });
438 return (
439 <Tooltip key={DateTime.formatIso(bucket.startedAt)}>
440 <TooltipTrigger
441 render={
442 <div className="grid h-full min-w-1 flex-1 grid-cols-3 items-end gap-px">
443 <span
444 className="block rounded-t-sm bg-foreground/65"
445 style={{ height: `${cpuHeight}%` }}
446 />
447 <span
448 className="block rounded-t-sm bg-sky-500/70"
449 style={{ height: `${readHeight}%` }}
450 />
451 <span
452 className="block rounded-t-sm bg-amber-500/80"
453 style={{ height: `${writeHeight}%` }}
454 />
455 </div>
456 }
457 />
458 <TooltipPopup side="top" className="space-y-0.5 text-left">
459 <div>CPU avg {bucket.avgCpuPercent.toFixed(1)}%</div>
460 <div>CPU peak {bucket.maxCpuPercent.toFixed(1)}%</div>
461 <div>Read {formatBytes(bucket.ioReadBytes)}</div>
462 <div>Write {formatBytes(bucket.ioWriteBytes)}</div>
463 </TooltipPopup>
464 </Tooltip>
465 );
466 })}
467 </div>
468 </div>
469 );
471​
472function ProcessTreeName({
473 process,
474 collapsed,
475 onToggle,
476}: {
477 process: ResourceTelemetryProcess;
478 collapsed: boolean;
479 onToggle: (process: ResourceTelemetryProcess) => void;
480}) {
481 const name = formatProcessName(process);
482 const hasChildren = process.childPids.length > 0;
483 const ChevronIcon = collapsed ? ChevronRightIcon : ChevronDownIcon;
484 return (
485 <div
486 className="grid min-w-0 grid-cols-[1.25rem_0.375rem_minmax(0,1fr)] items-center gap-2"
487 style={{ paddingLeft: `${Math.min(process.depth, 7) * 10}px` }}
488 >
489 {hasChildren ? (
490 <Button
491 size="icon-micro"
492 variant="ghost-muted"
493 onClick={() => onToggle(process)}
494 aria-label={collapsed ? `Expand ${name}` : `Collapse ${name}`}
495 >
496 <ChevronIcon className="size-3.5" />
497 </Button>
498 ) : (
499 <span className="size-5" aria-hidden />
500 )}
501 <span className={cn("size-1.5 rounded-full", categoryDotClass(process.category))} />
502 <Tooltip>
503 <TooltipTrigger
504 render={<span className="min-w-0 truncate font-medium text-foreground">{name}</span>}
505 />
506 <TooltipPopup
507 side="top"
508 className="max-w-[min(520px,calc(100vw-2rem))] whitespace-normal break-words text-left font-mono text-[11px]"
509 >
510 {process.command || process.name}
511 </TooltipPopup>
512 </Tooltip>
513 </div>
514 );
516​
517function canSignalProcess(process: ResourceTelemetryProcess): boolean {
518 return (
519 process.category === "server-child" ||
520 process.category === "provider-root" ||
521 process.category === "terminal-root"
522 );
524​
525function ProcessActions({
526 process,
527 signalingKeys,
528 onSignal,
529}: {
530 process: ResourceTelemetryProcess;
531 signalingKeys: ReadonlySet<string>;
532 onSignal: (process: ResourceTelemetryProcess, signal: ServerProcessSignal) => void;
533}) {
534 if (!canSignalProcess(process)) {
535 return <span className="text-[10px] text-muted-foreground/35">—</span>;
536 }
537 const isSignaling = signalingKeys.has(processIdentityKey(process));
538 return (
539 <ProcessSignalActions disabled={isSignaling} onSignal={(signal) => onSignal(process, signal)} />
540 );
542​
543function ProcessTable({
544 processes,
545 signalingKeys,
546 onSignal,
547}: {
548 processes: ReadonlyArray<ResourceTelemetryProcess>;
549 signalingKeys: ReadonlySet<string>;
550 onSignal: (process: ResourceTelemetryProcess, signal: ServerProcessSignal) => void;
551}) {
552 const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => new Set());
553 const visible = useMemo(
554 () => visibleResourceTelemetryProcesses(processes, collapsed),
555 [collapsed, processes],
556 );
557 const toggle = useCallback((process: ResourceTelemetryProcess) => {
558 const identityKey = processIdentityKey(process);
559 setCollapsed((current) => {
560 const next = new Set(current);
561 if (next.has(identityKey)) {
562 next.delete(identityKey);
563 } else {
564 next.add(identityKey);
565 }
566 return next;
567 });
568 }, []);
569​
570 return (
571 <ScrollArea
572 chainVerticalScroll
573 scrollFade
574 hideScrollbars
575 className="max-h-[min(68vh,48rem)] w-full max-w-full border-t border-border/60"
576 >
577 <table className="w-full min-w-[1320px] table-fixed text-left text-xs">
578 <colgroup>
579 <col className="w-[20%]" />
580 <col className="w-[10%]" />
581 <col className="w-[7%]" />
582 <col className="w-[8%]" />
583 <col className="w-[9%]" />
584 <col className="w-[9%]" />
585 <col className="w-[9%]" />
586 <col className="w-[10%]" />
587 <col className="w-[8%]" />
588 <col className="w-[6%]" />
589 <col className="w-[4%]" />
590 </colgroup>
591 <thead className="sticky top-0 z-10 border-b border-border/60 bg-card text-[10px] uppercase tracking-[0.08em] text-muted-foreground/65">
592 <tr>
593 <th className="px-4 py-2 font-semibold sm:pl-5">Process</th>
594 <th className="px-3 py-2 font-semibold">Category</th>
595 <th className="px-3 py-2 text-right font-semibold">CPU</th>
596 <th className="px-3 py-2 text-right font-semibold">CPU Time</th>
597 <th className="px-3 py-2 text-right font-semibold">Memory</th>
598 <th className="px-3 py-2 text-right font-semibold">Read/s</th>
599 <th className="px-3 py-2 text-right font-semibold">Write/s</th>
600 <th className="px-3 py-2 text-right font-semibold">Read Total</th>
601 <th className="px-3 py-2 text-right font-semibold">Write Total</th>
602 <th className="px-3 py-2 text-right font-semibold">PID</th>
603 <th className="px-2 py-2 text-right font-semibold sm:pr-4">Kill</th>
604 </tr>
605 </thead>
606 <tbody className="divide-y divide-border/50">
607 {visible.length === 0 ? (
608 <tr>
609 <td colSpan={11} className="px-4 py-5 text-xs text-muted-foreground sm:px-5">
610 Waiting for the native process monitor.
611 </td>
612 </tr>
613 ) : null}
614 {visible.map((process) => (
615 <tr key={processIdentityKey(process)} className="hover:bg-muted/20">
616 <td className="px-4 py-2 sm:pl-5">
617 <ProcessTreeName
618 process={process}
619 collapsed={collapsed.has(processIdentityKey(process))}
620 onToggle={toggle}
621 />
622 </td>
623 <td className="truncate px-3 py-2 text-[11px] text-muted-foreground">
624 {categoryLabel(process.category)}
625 </td>
626 <td className="px-3 py-2 text-right font-mono tabular-nums">
627 {process.cpuPercent.toFixed(1)}%
628 </td>
629 <td className="px-3 py-2 text-right font-mono tabular-nums">
630 {formatCpuTime(process.cpuTimeMs)}
631 </td>
632 <td className="px-3 py-2 text-right font-mono tabular-nums">
633 {formatBytes(process.residentBytes)}
634 </td>
635 <td className="px-3 py-2 text-right font-mono tabular-nums text-sky-700 dark:text-sky-300">
636 {formatRate(process.ioReadBytesPerSecond)}
637 </td>
638 <td className="px-3 py-2 text-right font-mono tabular-nums text-amber-700 dark:text-amber-300">
639 {formatRate(process.ioWriteBytesPerSecond)}
640 </td>
641 <td className="px-3 py-2 text-right font-mono tabular-nums text-muted-foreground">
642 {formatBytes(process.ioReadBytes)}
643 </td>
644 <td className="px-3 py-2 text-right font-mono tabular-nums text-muted-foreground">
645 <Tooltip>
646 <TooltipTrigger render={<span>{formatBytes(process.ioWriteBytes)}</span>} />
647 <TooltipPopup side="top">{ioSemanticsLabel(process.ioSemantics)}</TooltipPopup>
648 </Tooltip>
649 </td>
650 <td className="px-3 py-2 text-right font-mono tabular-nums text-muted-foreground">
651 {process.identity.pid}
652 </td>
653 <td className="px-2 py-2 text-right sm:pr-4">
654 <ProcessActions
655 process={process}
656 signalingKeys={signalingKeys}
657 onSignal={onSignal}
658 />
659 </td>
660 </tr>
661 ))}
662 </tbody>
663 </table>
664 </ScrollArea>
665 );
667​
668function HistoryProcessTable({
669 processes,
670}: {
671 processes: ReadonlyArray<ResourceTelemetryProcessSummary>;
672}) {
673 return (
674 <ScrollArea
675 chainVerticalScroll
676 scrollFade
677 hideScrollbars
678 className="max-h-[28rem] w-full max-w-full border-t border-border/60"
679 >
680 <table className="w-full min-w-[1020px] table-fixed text-left text-xs">
681 <colgroup>
682 <col className="w-[24%]" />
683 <col className="w-[11%]" />
684 <col className="w-[10%]" />
685 <col className="w-[10%]" />
686 <col className="w-[11%]" />
687 <col className="w-[11%]" />
688 <col className="w-[11%]" />
689 <col className="w-[7%]" />
690 <col className="w-[5%]" />
691 </colgroup>
692 <thead className="sticky top-0 z-10 border-b border-border/60 bg-card text-[10px] uppercase tracking-[0.08em] text-muted-foreground/65">
693 <tr>
694 <th className="px-4 py-2 font-semibold sm:pl-5">Process</th>
695 <th className="px-3 py-2 font-semibold">Category</th>
696 <th className="px-3 py-2 text-right font-semibold">CPU Time</th>
697 <th className="px-3 py-2 text-right font-semibold">Peak CPU</th>
698 <th className="px-3 py-2 text-right font-semibold">Peak Mem</th>
699 <th className="px-3 py-2 text-right font-semibold">Read</th>
700 <th className="px-3 py-2 text-right font-semibold">Write</th>
701 <th className="px-3 py-2 text-right font-semibold">Samples</th>
702 <th className="px-3 py-2 text-right font-semibold sm:pr-5">PID</th>
703 </tr>
704 </thead>
705 <tbody className="divide-y divide-border/50">
706 {processes.length === 0 ? (
707 <tr>
708 <td colSpan={9} className="px-4 py-5 text-xs text-muted-foreground sm:px-5">
709 No retained process samples in this window.
710 </td>
711 </tr>
712 ) : null}
713 {processes.map((process) => (
714 <tr key={processSummaryIdentityKey(process)} className="hover:bg-muted/20">
715 <td className="px-4 py-2 sm:pl-5">
716 <Tooltip>
717 <TooltipTrigger
718 render={
719 <span className="block truncate font-medium text-foreground">
720 {process.name || process.command}
721 </span>
722 }
723 />
724 <TooltipPopup
725 side="top"
726 className="max-w-[min(520px,calc(100vw-2rem))] whitespace-normal break-words text-left font-mono text-[11px]"
727 >
728 {process.command || process.name}
729 </TooltipPopup>
730 </Tooltip>
731 </td>
732 <td className="truncate px-3 py-2 text-[11px] text-muted-foreground">
733 {categoryLabel(process.category)}
734 </td>
735 <td className="px-3 py-2 text-right font-mono tabular-nums">
736 {formatCpuTime(process.cpuTimeMs)}
737 </td>
738 <td className="px-3 py-2 text-right font-mono tabular-nums">
739 {process.maxCpuPercent.toFixed(1)}%
740 </td>
741 <td className="px-3 py-2 text-right font-mono tabular-nums">
742 {formatBytes(process.peakRssBytes)}
743 </td>
744 <td className="px-3 py-2 text-right font-mono tabular-nums text-sky-700 dark:text-sky-300">
745 {formatBytes(process.ioReadBytes)}
746 </td>
747 <td className="px-3 py-2 text-right font-mono tabular-nums text-amber-700 dark:text-amber-300">
748 {formatBytes(process.ioWriteBytes)}
749 </td>
750 <td className="px-3 py-2 text-right font-mono tabular-nums text-muted-foreground">
751 {process.sampleCount}
752 </td>
753 <td className="px-3 py-2 text-right font-mono tabular-nums text-muted-foreground sm:pr-5">
754 {process.identity.pid}
755 </td>
756 </tr>
757 ))}
758 </tbody>
759 </table>
760 </ScrollArea>
761 );
763​
764function AttributionTable({ entries }: { entries: ReadonlyArray<ResourceAttributionEntry> }) {
765 return (
766 <div className="overflow-x-auto border-t border-border/60">
767 <table className="w-full min-w-[720px] table-fixed text-left text-xs">
768 <colgroup>
769 <col className="w-[22%]" />
770 <col className="w-[28%]" />
771 <col className="w-[14%]" />
772 <col className="w-[14%]" />
773 <col className="w-[10%]" />
774 <col className="w-[12%]" />
775 </colgroup>
776 <thead className="border-b border-border/60 text-[10px] uppercase tracking-[0.08em] text-muted-foreground/65">
777 <tr>
778 <th className="px-4 py-2 font-semibold sm:pl-5">Component</th>
779 <th className="px-3 py-2 font-semibold">Operation</th>
780 <th className="px-3 py-2 text-right font-semibold">Logical Read</th>
781 <th className="px-3 py-2 text-right font-semibold">Logical Write</th>
782 <th className="px-3 py-2 text-right font-semibold">Count</th>
783 <th className="px-3 py-2 text-right font-semibold sm:pr-5">Time</th>
784 </tr>
785 </thead>
786 <tbody className="divide-y divide-border/50">
787 {entries.length === 0 ? (
788 <tr>
789 <td colSpan={6} className="px-4 py-5 text-xs text-muted-foreground sm:px-5">
790 No instrumented application I/O has been recorded yet.
791 </td>
792 </tr>
793 ) : null}
794 {entries.map((entry) => (
795 <tr key={`${entry.component}:${entry.operation}`} className="hover:bg-muted/20">
796 <td className="truncate px-4 py-2 font-medium text-foreground sm:pl-5">
797 {entry.component}
798 </td>
799 <td className="truncate px-3 py-2 text-muted-foreground">{entry.operation}</td>
800 <td className="px-3 py-2 text-right font-mono tabular-nums text-sky-700 dark:text-sky-300">
801 {formatBytes(entry.logicalReadBytes)}
802 </td>
803 <td className="px-3 py-2 text-right font-mono tabular-nums text-amber-700 dark:text-amber-300">
804 {formatBytes(entry.logicalWriteBytes)}
805 </td>
806 <td className="px-3 py-2 text-right font-mono tabular-nums">{entry.count}</td>
807 <td className="px-3 py-2 text-right font-mono tabular-nums text-muted-foreground sm:pr-5">
808 {(entry.durationMs / 1_000).toFixed(2)}s
809 </td>
810 </tr>
811 ))}
812 </tbody>
813 </table>
814 </div>
815 );
817​
818export function ResourceTelemetryDiagnostics({
819 environmentId,
820}: {
821 environmentId: EnvironmentId | null;
822}) {
823 const [windowMs, setWindowMs] = useState(15 * 60_000);
824 const selectedWindow =
825 HISTORY_WINDOWS.find((option) => option.windowMs === windowMs) ?? HISTORY_WINDOWS[1];
826 const telemetry = useResourceTelemetry(environmentId);
827 const retryTelemetry = telemetry.retry;
828 const history = useResourceTelemetryHistory(
829 {
830 windowMs: selectedWindow.windowMs,
831 bucketMs: selectedWindow.bucketMs,
832 },
833 environmentId,
834 );
835 const signalServerProcess = useAtomCommand(serverEnvironment.signalProcess, {
836 reportFailure: false,
837 });
838 const [signalingKeys, setSignalingKeys] = useState<ReadonlySet<string>>(() => new Set());
839 const signalingKeysRef = useRef<ReadonlySet<string>>(new Set());
840 const environmentIdRef = useRef(environmentId);
841 useEffect(() => {
842 environmentIdRef.current = environmentId;
843 return () => {
844 environmentIdRef.current = null;
845 };
846 }, [environmentId]);
847 const [isRetrying, setIsRetrying] = useState(false);
848 const snapshot = telemetry.data;
849 const allT3 = snapshot?.groups.allT3;
850​
851 const signalProcess = useCallback(
852 async (process: ResourceTelemetryProcess, signal: ServerProcessSignal) => {
853 const targetEnvironmentId = environmentIdRef.current;
854 if (targetEnvironmentId === null) return;
855 const identityKey = processIdentityKey(process);
856 if (signalingKeysRef.current.has(identityKey)) return;
857 const nextSignalingKeys = new Set(signalingKeysRef.current).add(identityKey);
858 signalingKeysRef.current = nextSignalingKeys;
859 setSignalingKeys(nextSignalingKeys);
860 const clearSignaling = () => {
861 const next = new Set(signalingKeysRef.current);
862 next.delete(identityKey);
863 signalingKeysRef.current = next;
864 setSignalingKeys(next);
865 };
866​
867 if (signal === "SIGKILL") {
868 let confirmed = false;
869 try {
870 confirmed = await ensureLocalApi().dialogs.confirm(
871 `Send SIGKILL to process ${process.identity.pid}? This cannot be handled by the process.`,
872 { variant: "destructive" },
873 );
874 } catch (error) {
875 clearSignaling();
876 toastManager.add({
877 type: "error",
878 title: "Could not confirm signal",
879 description: error instanceof Error ? error.message : `Failed to send ${signal}.`,
880 });
881 return;
882 }
883 if (!confirmed) {
884 clearSignaling();
885 return;
886 }
887 }
888 if (environmentIdRef.current !== targetEnvironmentId) {
889 clearSignaling();
890 return;
891 }
892 void signalServerProcess({
893 environmentId: targetEnvironmentId,
894 input: {
895 pid: process.identity.pid,
896 startTimeMs: process.identity.startTimeMs,
897 signal,
898 },
899 })
900 .then((result) => {
901 if (result._tag === "Failure") {
902 if (isAtomCommandInterrupted(result)) return;
903 throw squashAtomCommandFailure(result);
904 }
905 if (result.value.signaled) return;
906 toastManager.add({
907 type: "error",
908 title: `Could not send ${signal}`,
909 description: Option.getOrElse(
910 result.value.message,
911 () => `Failed to send ${signal} to process ${process.identity.pid}.`,
912 ),
913 });
914 })
915 .catch((error: unknown) => {
916 toastManager.add({
917 type: "error",
918 title: `Could not send ${signal}`,
919 description: error instanceof Error ? error.message : `Failed to send ${signal}.`,
920 });
921 })
922 .finally(() => {
923 clearSignaling();
924 });
925 },
926 [signalServerProcess],
927 );
928​
929 const retryCollector = useCallback(() => {
930 setIsRetrying(true);
931 void retryTelemetry()
932 .catch((error: unknown) => {
933 toastManager.add({
934 type: "error",
935 title: "Could not restart resource monitor",
936 description:
937 error instanceof Error ? error.message : "The resource monitor retry failed.",
938 });
939 })
940 .finally(() => {
941 setIsRetrying(false);
942 });
943 }, [retryTelemetry]);
944​
945 const speedLimit = snapshot ? Option.getOrNull(snapshot.speedLimitPercent) : null;
946 const collectorNeedsRetry = shouldShowResourceMonitorRetry({
947 nativeStatus: snapshot?.health.native.status ?? null,
948 error: telemetry.error,
949 });
950 const hasHostPowerSignal =
951 snapshot !== null &&
952 (snapshot.power.onBattery !== "unknown" ||
953 snapshot.power.lowPowerMode !== "unknown" ||
954 snapshot.power.idle !== "unknown" ||
955 snapshot.power.locked !== "unknown" ||
956 snapshot.power.thermalState !== "unknown");
957​
958 return (
959 <>
960 <SettingsSection
961 title="Resource monitor"
962 icon={<ActivityIcon className="size-4 text-muted-foreground" />}
963 headerAction={
964 <div className="flex items-center gap-2">
965 {snapshot ? (
966 <SourceStatusBadge label="Native" status={snapshot.health.native.status} />
967 ) : null}
968 <LastSampleLabel sampledAt={snapshot?.readAt ?? null} />
969 <Tooltip>
970 <TooltipTrigger
971 render={
972 <Button
973 size="icon-micro"
974 variant="ghost"
975 disabled={telemetry.isPending}
976 onClick={telemetry.refresh}
977 aria-label="Refresh resource telemetry"
978 >
979 <RefreshIcon className="size-3" refreshing={telemetry.isPending} />
980 </Button>
981 }
982 />
983 <TooltipPopup side="top">Refresh telemetry snapshot</TooltipPopup>
984 </Tooltip>
985 </div>
986 }
987 >
988 <div className="overflow-hidden rounded-2xl border border-border/70 bg-card shadow-[0_1px_1px_rgb(0_0_0/0.03),0_8px_30px_rgb(0_0_0/0.035)]">
989 <div className="flex flex-col gap-3 border-b border-border/60 bg-linear-to-r from-muted/45 via-muted/20 to-transparent px-4 py-4 sm:flex-row sm:items-center sm:justify-between sm:px-5">
990 <div>
991 <div className="text-[10px] font-semibold uppercase tracking-[0.14em] text-muted-foreground/70">
992 T3 system footprint
993 </div>
994 <p className="mt-1 max-w-xl text-xs leading-relaxed text-muted-foreground">
995 Live native counters for the server, providers, terminals, desktop processes, and
996 the monitor itself.
997 </p>
998 </div>
999 <div className="flex items-center gap-2 text-[10px] text-muted-foreground/65">
1000 <span className="size-1.5 rounded-full bg-emerald-500" />
1001 Sampling every {snapshot ? formatSampleInterval(snapshot.sampleIntervalMs) : "..."}
1002 </div>
1003 </div>
1004 <div className="grid grid-cols-2 divide-x divide-y divide-border/55 md:grid-cols-3">
1005 <IconStat
1006 icon={<CpuIcon className="size-3.5" />}
1007 label="Current CPU"
1008 value={allT3 ? `${allT3.currentCpuPercent.toFixed(1)}%` : "..."}
1009 detail={allT3 ? `${formatCpuTime(allT3.cpuTimeMs)} observed CPU time` : undefined}
1010 />
1011 <IconStat
1012 icon={<MemoryStickIcon className="size-3.5" />}
1013 label="Resident memory"
1014 value={allT3 ? formatBytes(allT3.currentRssBytes) : "..."}
1015 detail={
1016 allT3 ? `${formatBytes(allT3.peakRssBytes)} combined process peaks` : undefined
1018 />
1019 <IconStat
1020 icon={<ActivityIcon className="size-3.5" />}
1021 label="Process count"
1022 value={allT3 ? String(allT3.processCount) : "..."}
1023 detail={
1024 allT3 ? `${allT3.processStarts} starts · ${allT3.processExits} exits` : undefined
1026 />
1027 <IconStat
1028 icon={<HardDriveIcon className="size-3.5" />}
1029 label="Read throughput"
1030 value={allT3 ? formatRate(allT3.ioReadBytesPerSecond) : "..."}
1031 detail={allT3 ? `${formatBytes(allT3.ioReadBytes)} observed` : undefined}
1032 />
1033 <IconStat
1034 icon={<DatabaseIcon className="size-3.5" />}
1035 label="Write throughput"
1036 value={allT3 ? formatRate(allT3.ioWriteBytesPerSecond) : "..."}
1037 detail={allT3 ? `${formatBytes(allT3.ioWriteBytes)} observed` : undefined}
1038 tone={
1039 allT3 && allT3.ioWriteBytesPerSecond >= 10 * 1_024 * 1_024
1040 ? "danger"
1041 : allT3 && allT3.ioWriteBytesPerSecond >= 1_024 * 1_024
1042 ? "warning"
1043 : "default"
1045 />
1046 <IconStat
1047 icon={<GaugeIcon className="size-3.5" />}
1048 label="CPU speed limit"
1049 value={
1050 snapshot ? (speedLimit === null ? "Unknown" : `${speedLimit.toFixed(0)}%`) : "..."
1052 detail={snapshot ? `${snapshot.power.thermalState} thermal state` : undefined}
1053 tone={speedLimit !== null && speedLimit < 80 ? "warning" : "default"}
1054 />
1055 </div>
1056 {telemetry.error ? (
1057 <div className="flex items-start gap-2 border-t border-destructive/20 bg-destructive/5 px-4 py-3 text-xs text-destructive sm:px-5">
1058 <AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
1059 <span>{telemetry.error}</span>
1060 </div>
1061 ) : null}
1062 {snapshot ? (
1063 <div className="grid border-t border-border/60 bg-muted/10 md:grid-cols-3">
1064 <AggregateCard
1065 label="Backend + agents"
1066 accentClass="bg-emerald-500/80"
1067 aggregate={snapshot.groups.backend}
1068 />
1069 <AggregateCard
1070 label="Desktop"
1071 accentClass="bg-sky-500/80"
1072 aggregate={snapshot.groups.electron}
1073 />
1074 <AggregateCard
1075 label="Monitor overhead"
1076 accentClass="bg-amber-500/80"
1077 aggregate={snapshot.groups.monitor}
1078 />
1079 </div>
1080 ) : null}
1081 </div>
1082 </SettingsSection>
1083​
1084 <SettingsSection
1085 title="Host & collection"
1086 icon={<GaugeIcon className="size-4 text-muted-foreground" />}
1087 headerAction={
1088 collectorNeedsRetry ? (
1089 <Button size="xs" variant="outline" disabled={isRetrying} onClick={retryCollector}>
1090 <RefreshIcon className="size-3" refreshing={isRetrying} />
1091 Retry monitor
1092 </Button>
1093 ) : null
1096 <div className="grid overflow-hidden rounded-2xl border border-border/70 bg-card shadow-[0_1px_1px_rgb(0_0_0/0.03)] md:grid-cols-2 md:divide-x md:divide-border/60">
1097 <div className="px-4 py-4 sm:px-5">
1098 <div className="mb-3 flex items-center gap-2 text-[10px] font-semibold uppercase tracking-[0.12em] text-muted-foreground/70">
1099 <span className="flex size-6 items-center justify-center rounded-md bg-muted/60">
1100 <BatteryIcon className="size-3.5" />
1101 </span>
1102 Host state
1103 </div>
1104 {hasHostPowerSignal && snapshot ? (
1105 <>
1106 <DetailRow
1107 label="Power source"
1108 value={booleanStateLabel(snapshot.power.onBattery, {
1109 true: "Battery",
1110 false: "External power",
1111 })}
1112 />
1113 <DetailRow
1114 label="Low power mode"
1115 value={booleanStateLabel(snapshot.power.lowPowerMode, {
1116 true: "Enabled",
1117 false: "Disabled",
1118 })}
1119 />
1120 <DetailRow
1121 label="Idle"
1122 value={`${booleanStateLabel(snapshot.power.idle, {
1123 true: "Idle",
1124 false: "Active",
1125 })}${
1126 snapshot.power.idleSeconds === null
1127 ? ""
1128 : ` · ${Math.round(snapshot.power.idleSeconds)}s`
1129 }`}
1130 />
1131 <DetailRow
1132 label="Session"
1133 value={
1134 snapshot.power.suspended
1135 ? "Suspended"
1136 : booleanStateLabel(snapshot.power.locked, {
1137 true: "Locked",
1138 false: "Unlocked",
1139 })
1141 />
1142 <DetailRow
1143 label="Thermal"
1144 value={snapshot.power.thermalState}
1145 valueClassName={
1146 snapshot.power.thermalState === "serious" ||
1147 snapshot.power.thermalState === "critical"
1148 ? "text-destructive"
1149 : undefined
1151 />
1152 </>
1153 ) : (
1154 <div className="rounded-xl border border-dashed border-border/70 bg-muted/20 px-4 py-5">
1155 <div className="text-[13px] font-medium text-foreground">
1156 Desktop host signals not connected
1157 </div>
1158 <p className="mt-1.5 max-w-sm text-[11px] leading-relaxed text-muted-foreground/70">
1159 Power, idle, lock, and thermal state are supplied by the desktop host. Process
1160 telemetry remains fully active in this browser session.
1161 </p>
1162 </div>
1163 )}
1164 </div>
1165 <div className="border-t border-border/60 px-4 py-4 md:border-t-0 sm:px-5">
1166 <div className="mb-3 flex items-center gap-2 text-[10px] font-semibold uppercase tracking-[0.12em] text-muted-foreground/70">
1167 <span className="flex size-6 items-center justify-center rounded-md bg-muted/60">
1168 <GaugeIcon className="size-3.5" />
1169 </span>
1170 Collection health
1171 </div>
1172 {snapshot ? (
1173 <>
1174 <HealthSource label="Native process monitor" health={snapshot.health.native} />
1175 <HealthSource label="Electron main process" health={snapshot.health.desktop} />
1176 <DetailRow
1177 label="Collection time"
1178 value={formatDurationMicros(snapshot.health.collectionDurationMicros)}
1179 />
1180 <DetailRow
1181 label="Process scan"
1182 value={`${snapshot.health.retainedProcessCount}/${snapshot.health.scannedProcessCount} retained`}
1183 />
1184 <DetailRow
1185 label="Inaccessible"
1186 value={String(snapshot.health.inaccessibleProcessCount)}
1187 valueClassName={
1188 snapshot.health.inaccessibleProcessCount > 0
1189 ? "text-amber-600 dark:text-amber-300"
1190 : undefined
1192 />
1193 <DetailRow
1194 label="Sidecar"
1195 value={Option.match(snapshot.health.sidecarVersion, {
1196 onNone: () => "Unavailable",
1197 onSome: (version) =>
1198 `${version}${Option.match(snapshot.health.sidecarPid, {
1199 onNone: () => "",
1200 onSome: (pid) => ` · PID ${pid}`,
1201 })}`,
1202 })}
1203 />
1204 <DetailRow label="Restarts" value={String(snapshot.health.restartCount)} />
1205 </>
1206 ) : (
1207 <div className="py-4 text-xs text-muted-foreground">
1208 Waiting for collector health.
1209 </div>
1210 )}
1211 </div>
1212 </div>
1213 </SettingsSection>
1214​
1215 <SettingsSection
1216 title="Resource timeline"
1217 icon={<HardDriveIcon className="size-4 text-muted-foreground" />}
1218 headerAction={
1219 <div className="flex items-center gap-2">
1220 <HistoryWindowSelector selectedWindowMs={windowMs} onSelect={setWindowMs} />
1221 <Button
1222 size="icon-micro"
1223 variant="ghost"
1224 disabled={history.isPending}
1225 onClick={history.refresh}
1226 aria-label="Refresh resource history"
1228 <RefreshIcon className="size-3" refreshing={history.isPending} />
1229 </Button>
1230 </div>
1233 <div className="overflow-hidden rounded-2xl border border-border/70 bg-card shadow-[0_1px_1px_rgb(0_0_0/0.03)]">
1234 {history.error ? (
1235 <div className="flex items-start gap-2 border-b border-destructive/20 bg-destructive/5 px-4 py-3 text-xs text-destructive sm:px-5">
1236 <AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
1237 <span>{history.error}</span>
1238 </div>
1239 ) : null}
1240 <ResourceHistoryChart buckets={history.data?.buckets ?? []} />
1241 <HistoryProcessTable processes={history.data?.topProcesses ?? []} />
1242 </div>
1243 </SettingsSection>
1244​
1245 <SettingsSection
1246 title="Live process tree"
1247 icon={<CpuIcon className="size-4 text-muted-foreground" />}
1248 headerAction={
1249 snapshot ? (
1250 <span className="text-[10px] text-muted-foreground/55">
1251 Identity: <span className="font-mono">PID + start time</span>
1252 </span>
1253 ) : null
1256 <div className="overflow-hidden rounded-2xl border border-border/70 bg-card shadow-[0_1px_1px_rgb(0_0_0/0.03)]">
1257 <ProcessTable
1258 processes={snapshot?.processes ?? []}
1259 signalingKeys={signalingKeys}
1260 onSignal={signalProcess}
1261 />
1262 </div>
1263 </SettingsSection>
1264​
1265 <SettingsSection
1266 title="Instrumented application I/O"
1267 icon={<DatabaseIcon className="size-4 text-muted-foreground" />}
1268 headerAction={
1269 <span className="text-[10px] text-muted-foreground/55">Logical bytes by operation</span>
1272 <div className="overflow-hidden rounded-2xl border border-border/70 bg-card shadow-[0_1px_1px_rgb(0_0_0/0.03)]">
1273 <div className="bg-muted/15 px-4 py-3 text-[11px] leading-relaxed text-muted-foreground sm:px-5">
1274 Native counters identify which process is reading or writing. These application-level
1275 counters identify known T3 operations so process spikes can be correlated with specific
1276 persistence and logging paths.
1277 </div>
1278 <AttributionTable entries={snapshot?.attribution.entries ?? []} />
1279 </div>
1280 </SettingsSection>
1281 </>
1282 );