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

ResourceTelemetryDiagnostics.tsx

1,268 lines47.4 KB

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