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

ResourceTelemetryDiagnostics.tsx

1,280 lines47.6 KB

1import { ProcessSignalActions } from "./ProcessSignalActions";
2import { RefreshIcon } from "~/components/ui/refresh-icon";
3import {
4 ActivityIcon,
5 AlertTriangleIcon,
6 BatteryIcon,
7 CpuIcon,
8 DatabaseIcon,
9 GaugeIcon,
10 HardDriveIcon,
11 MemoryStickIcon,
12} from "lucide-react";
13import { ChevronDown, ChevronRight } from "lucide";
14import type {
15 BackgroundBooleanState,
16 EnvironmentId,
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, useEffect, useMemo, useRef, 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 { ensureLocalApi } from "../../localApi";
42import { serverEnvironment } from "../../state/server";
43import { useAtomCommand } from "../../state/use-atom-command";
44import { formatRelativeTime } from "../../timestampFormat";
45import { Button } from "../ui/button";
46import { MorphIcon } from "~/components/MorphIcon";
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-warning";
146 if (category.startsWith("electron-")) return "bg-info";
147 if (category === "server") return "bg-violet-500";
148 return "bg-success";
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-3xs font-semibold uppercase tracking-widest",
198 tone === "neutral" && "border-border/70 bg-muted/45 text-muted-foreground",
199 tone === "default" && "border-success/25 bg-success/10 text-success-foreground",
200 tone === "warning" && "border-warning/30 bg-warning/10 text-warning-foreground",
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-success",
209 tone === "warning" && "bg-warning",
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-2xs text-muted-foreground/55">Waiting for sample</span>;
222 }
223 const relative = formatRelativeTime(DateTime.formatIso(sampledAt));
224 if (!relative) {
225 return <span className="text-2xs text-muted-foreground/55">Waiting for sample</span>;
226 }
227 return (
228 <span className="text-2xs 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-3xs font-semibold uppercase tracking-widest 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-tighter tabular-nums text-foreground",
259 tone === "warning" && "text-warning-foreground",
260 tone === "danger" && "text-destructive",
261 )}
262 >
263 {value}
264 </div>
265 {detail ? (
266 <div className="mt-1.5 truncate text-3xs 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-3xs font-semibold uppercase tracking-widest 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-3xs 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-3xs font-semibold uppercase tracking-widest 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-sm font-medium text-foreground">{label}</div>
323 <div className="mt-1 text-2xs 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-2xs text-muted-foreground/75">{label}</span>
360 <span
361 className={cn(
362 "min-w-0 truncate text-right font-mono text-2xs 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 <ToggleGroup
381 aria-label="Resource history period"
382 variant="segmented"
383 value={[String(selectedWindowMs)]}
384 onValueChange={(next) => {
385 const selected = HISTORY_WINDOWS.find((option) => String(option.windowMs) === next[0]);
386 if (selected) onSelect(selected.windowMs);
387 }}
388 >
389 {HISTORY_WINDOWS.map((option) => (
390 <Toggle key={option.windowMs} value={String(option.windowMs)}>
391 {option.label}
392 </Toggle>
393 ))}
394 </ToggleGroup>
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-3xs 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-info/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-warning/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-info/70"
447 style={{ height: `${readHeight}%` }}
448 />
449 <span
450 className="block rounded-t-sm bg-warning/80"
451 style={{ height: `${writeHeight}%` }}
452 />
453 </div>
454 }
455 />
456 <TooltipPopup side="top" className="text-left">
457 <div className="space-y-0.5">
458 <div>CPU avg {bucket.avgCpuPercent.toFixed(1)}%</div>
459 <div>CPU peak {bucket.maxCpuPercent.toFixed(1)}%</div>
460 <div>Read {formatBytes(bucket.ioReadBytes)}</div>
461 <div>Write {formatBytes(bucket.ioWriteBytes)}</div>
462 </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 return (
484 <div
485 className="grid min-w-0 grid-cols-[1.25rem_0.375rem_minmax(0,1fr)] items-center gap-2"
486 style={{ paddingLeft: `${Math.min(process.depth, 7) * 10}px` }}
487 >
488 {hasChildren ? (
489 <Button
490 size="icon-micro"
491 variant="ghost-muted"
492 onClick={() => onToggle(process)}
493 aria-label={collapsed ? `Expand ${name}` : `Collapse ${name}`}
494 >
495 <MorphIcon className="size-3.5" icon={collapsed ? ChevronRight : ChevronDown} />
496 </Button>
497 ) : (
498 <span className="size-5" aria-hidden />
499 )}
500 <span className={cn("size-1.5 rounded-full", categoryDotClass(process.category))} />
501 <Tooltip>
502 <TooltipTrigger
503 render={<span className="min-w-0 truncate font-medium text-foreground">{name}</span>}
504 />
505 <TooltipPopup side="top" variant="code">
506 {process.command || process.name}
507 </TooltipPopup>
508 </Tooltip>
509 </div>
510 );
512​
513function canSignalProcess(process: ResourceTelemetryProcess): boolean {
514 return (
515 process.category === "server-child" ||
516 process.category === "provider-root" ||
517 process.category === "terminal-root"
518 );
520​
521function ProcessActions({
522 process,
523 signalingKeys,
524 onSignal,
525}: {
526 process: ResourceTelemetryProcess;
527 signalingKeys: ReadonlySet<string>;
528 onSignal: (process: ResourceTelemetryProcess, signal: ServerProcessSignal) => void;
529}) {
530 if (!canSignalProcess(process)) {
531 return <span className="text-3xs text-muted-foreground/35">—</span>;
532 }
533 const isSignaling = signalingKeys.has(processIdentityKey(process));
534 return (
535 <ProcessSignalActions disabled={isSignaling} onSignal={(signal) => onSignal(process, signal)} />
536 );
538​
539function ProcessTable({
540 processes,
541 signalingKeys,
542 onSignal,
543}: {
544 processes: ReadonlyArray<ResourceTelemetryProcess>;
545 signalingKeys: ReadonlySet<string>;
546 onSignal: (process: ResourceTelemetryProcess, signal: ServerProcessSignal) => void;
547}) {
548 const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => new Set());
549 const visible = useMemo(
550 () => visibleResourceTelemetryProcesses(processes, collapsed),
551 [collapsed, processes],
552 );
553 const toggle = useCallback((process: ResourceTelemetryProcess) => {
554 const identityKey = processIdentityKey(process);
555 setCollapsed((current) => {
556 const next = new Set(current);
557 if (next.has(identityKey)) {
558 next.delete(identityKey);
559 } else {
560 next.add(identityKey);
561 }
562 return next;
563 });
564 }, []);
565​
566 return (
567 <div className="border-t border-border/60">
568 <ScrollArea
569 chainVerticalScroll
570 scrollFade
571 hideScrollbars
572 className="max-h-[min(68vh,48rem)] w-full max-w-full"
573 >
574 <table className="w-full min-w-[1320px] table-fixed text-left text-xs">
575 <colgroup>
576 <col className="w-[20%]" />
577 <col className="w-[10%]" />
578 <col className="w-[7%]" />
579 <col className="w-[8%]" />
580 <col className="w-[9%]" />
581 <col className="w-[9%]" />
582 <col className="w-[9%]" />
583 <col className="w-[10%]" />
584 <col className="w-[8%]" />
585 <col className="w-[6%]" />
586 <col className="w-[4%]" />
587 </colgroup>
588 <thead className="sticky top-0 z-10 border-b border-border/60 bg-card text-3xs uppercase tracking-widest text-muted-foreground/65">
589 <tr>
590 <th className="px-4 py-2 font-semibold sm:pl-5">Process</th>
591 <th className="px-3 py-2 font-semibold">Category</th>
592 <th className="px-3 py-2 text-right font-semibold">CPU</th>
593 <th className="px-3 py-2 text-right font-semibold">CPU Time</th>
594 <th className="px-3 py-2 text-right font-semibold">Memory</th>
595 <th className="px-3 py-2 text-right font-semibold">Read/s</th>
596 <th className="px-3 py-2 text-right font-semibold">Write/s</th>
597 <th className="px-3 py-2 text-right font-semibold">Read Total</th>
598 <th className="px-3 py-2 text-right font-semibold">Write Total</th>
599 <th className="px-3 py-2 text-right font-semibold">PID</th>
600 <th className="px-2 py-2 text-right font-semibold sm:pr-4">Kill</th>
601 </tr>
602 </thead>
603 <tbody className="divide-y divide-border/50">
604 {visible.length === 0 ? (
605 <tr>
606 <td colSpan={11} className="px-4 py-5 text-xs text-muted-foreground sm:px-5">
607 Waiting for the native process monitor.
608 </td>
609 </tr>
610 ) : null}
611 {visible.map((process) => (
612 <tr key={processIdentityKey(process)} className="hover:bg-muted/20">
613 <td className="px-4 py-2 sm:pl-5">
614 <ProcessTreeName
615 process={process}
616 collapsed={collapsed.has(processIdentityKey(process))}
617 onToggle={toggle}
618 />
619 </td>
620 <td className="truncate px-3 py-2 text-2xs text-muted-foreground">
621 {categoryLabel(process.category)}
622 </td>
623 <td className="px-3 py-2 text-right font-mono tabular-nums">
624 {process.cpuPercent.toFixed(1)}%
625 </td>
626 <td className="px-3 py-2 text-right font-mono tabular-nums">
627 {formatCpuTime(process.cpuTimeMs)}
628 </td>
629 <td className="px-3 py-2 text-right font-mono tabular-nums">
630 {formatBytes(process.residentBytes)}
631 </td>
632 <td className="px-3 py-2 text-right font-mono tabular-nums text-info-foreground">
633 {formatRate(process.ioReadBytesPerSecond)}
634 </td>
635 <td className="px-3 py-2 text-right font-mono tabular-nums text-warning-foreground">
636 {formatRate(process.ioWriteBytesPerSecond)}
637 </td>
638 <td className="px-3 py-2 text-right font-mono tabular-nums text-muted-foreground">
639 {formatBytes(process.ioReadBytes)}
640 </td>
641 <td className="px-3 py-2 text-right font-mono tabular-nums text-muted-foreground">
642 <Tooltip>
643 <TooltipTrigger render={<span>{formatBytes(process.ioWriteBytes)}</span>} />
644 <TooltipPopup side="top">{ioSemanticsLabel(process.ioSemantics)}</TooltipPopup>
645 </Tooltip>
646 </td>
647 <td className="px-3 py-2 text-right font-mono tabular-nums text-muted-foreground">
648 {process.identity.pid}
649 </td>
650 <td className="px-2 py-2 text-right sm:pr-4">
651 <ProcessActions
652 process={process}
653 signalingKeys={signalingKeys}
654 onSignal={onSignal}
655 />
656 </td>
657 </tr>
658 ))}
659 </tbody>
660 </table>
661 </ScrollArea>
662 </div>
663 );
665​
666function HistoryProcessTable({
667 processes,
668}: {
669 processes: ReadonlyArray<ResourceTelemetryProcessSummary>;
670}) {
671 return (
672 <div className="border-t border-border/60">
673 <ScrollArea
674 chainVerticalScroll
675 scrollFade
676 hideScrollbars
677 className="max-h-[28rem] w-full max-w-full"
678 >
679 <table className="w-full min-w-[1020px] table-fixed text-left text-xs">
680 <colgroup>
681 <col className="w-[24%]" />
682 <col className="w-[11%]" />
683 <col className="w-[10%]" />
684 <col className="w-[10%]" />
685 <col className="w-[11%]" />
686 <col className="w-[11%]" />
687 <col className="w-[11%]" />
688 <col className="w-[7%]" />
689 <col className="w-[5%]" />
690 </colgroup>
691 <thead className="sticky top-0 z-10 border-b border-border/60 bg-card text-3xs uppercase tracking-widest text-muted-foreground/65">
692 <tr>
693 <th className="px-4 py-2 font-semibold sm:pl-5">Process</th>
694 <th className="px-3 py-2 font-semibold">Category</th>
695 <th className="px-3 py-2 text-right font-semibold">CPU Time</th>
696 <th className="px-3 py-2 text-right font-semibold">Peak CPU</th>
697 <th className="px-3 py-2 text-right font-semibold">Peak Mem</th>
698 <th className="px-3 py-2 text-right font-semibold">Read</th>
699 <th className="px-3 py-2 text-right font-semibold">Write</th>
700 <th className="px-3 py-2 text-right font-semibold">Samples</th>
701 <th className="px-3 py-2 text-right font-semibold sm:pr-5">PID</th>
702 </tr>
703 </thead>
704 <tbody className="divide-y divide-border/50">
705 {processes.length === 0 ? (
706 <tr>
707 <td colSpan={9} className="px-4 py-5 text-xs text-muted-foreground sm:px-5">
708 No retained process samples in this window.
709 </td>
710 </tr>
711 ) : null}
712 {processes.map((process) => (
713 <tr key={processSummaryIdentityKey(process)} className="hover:bg-muted/20">
714 <td className="px-4 py-2 sm:pl-5">
715 <Tooltip>
716 <TooltipTrigger
717 render={
718 <span className="block truncate font-medium text-foreground">
719 {process.name || process.command}
720 </span>
721 }
722 />
723 <TooltipPopup side="top" variant="code">
724 {process.command || process.name}
725 </TooltipPopup>
726 </Tooltip>
727 </td>
728 <td className="truncate px-3 py-2 text-2xs text-muted-foreground">
729 {categoryLabel(process.category)}
730 </td>
731 <td className="px-3 py-2 text-right font-mono tabular-nums">
732 {formatCpuTime(process.cpuTimeMs)}
733 </td>
734 <td className="px-3 py-2 text-right font-mono tabular-nums">
735 {process.maxCpuPercent.toFixed(1)}%
736 </td>
737 <td className="px-3 py-2 text-right font-mono tabular-nums">
738 {formatBytes(process.peakRssBytes)}
739 </td>
740 <td className="px-3 py-2 text-right font-mono tabular-nums text-info-foreground">
741 {formatBytes(process.ioReadBytes)}
742 </td>
743 <td className="px-3 py-2 text-right font-mono tabular-nums text-warning-foreground">
744 {formatBytes(process.ioWriteBytes)}
745 </td>
746 <td className="px-3 py-2 text-right font-mono tabular-nums text-muted-foreground">
747 {process.sampleCount}
748 </td>
749 <td className="px-3 py-2 text-right font-mono tabular-nums text-muted-foreground sm:pr-5">
750 {process.identity.pid}
751 </td>
752 </tr>
753 ))}
754 </tbody>
755 </table>
756 </ScrollArea>
757 </div>
758 );
760​
761function AttributionTable({ entries }: { entries: ReadonlyArray<ResourceAttributionEntry> }) {
762 return (
763 <div className="overflow-x-auto border-t border-border/60">
764 <table className="w-full min-w-[720px] table-fixed text-left text-xs">
765 <colgroup>
766 <col className="w-[22%]" />
767 <col className="w-[28%]" />
768 <col className="w-[14%]" />
769 <col className="w-[14%]" />
770 <col className="w-[10%]" />
771 <col className="w-[12%]" />
772 </colgroup>
773 <thead className="border-b border-border/60 text-3xs uppercase tracking-widest text-muted-foreground/65">
774 <tr>
775 <th className="px-4 py-2 font-semibold sm:pl-5">Component</th>
776 <th className="px-3 py-2 font-semibold">Operation</th>
777 <th className="px-3 py-2 text-right font-semibold">Logical Read</th>
778 <th className="px-3 py-2 text-right font-semibold">Logical Write</th>
779 <th className="px-3 py-2 text-right font-semibold">Count</th>
780 <th className="px-3 py-2 text-right font-semibold sm:pr-5">Time</th>
781 </tr>
782 </thead>
783 <tbody className="divide-y divide-border/50">
784 {entries.length === 0 ? (
785 <tr>
786 <td colSpan={6} className="px-4 py-5 text-xs text-muted-foreground sm:px-5">
787 No instrumented application I/O has been recorded yet.
788 </td>
789 </tr>
790 ) : null}
791 {entries.map((entry) => (
792 <tr key={`${entry.component}:${entry.operation}`} className="hover:bg-muted/20">
793 <td className="truncate px-4 py-2 font-medium text-foreground sm:pl-5">
794 {entry.component}
795 </td>
796 <td className="truncate px-3 py-2 text-muted-foreground">{entry.operation}</td>
797 <td className="px-3 py-2 text-right font-mono tabular-nums text-info-foreground">
798 {formatBytes(entry.logicalReadBytes)}
799 </td>
800 <td className="px-3 py-2 text-right font-mono tabular-nums text-warning-foreground">
801 {formatBytes(entry.logicalWriteBytes)}
802 </td>
803 <td className="px-3 py-2 text-right font-mono tabular-nums">{entry.count}</td>
804 <td className="px-3 py-2 text-right font-mono tabular-nums text-muted-foreground sm:pr-5">
805 {(entry.durationMs / 1_000).toFixed(2)}s
806 </td>
807 </tr>
808 ))}
809 </tbody>
810 </table>
811 </div>
812 );
814​
815export function ResourceTelemetryDiagnostics({
816 environmentId,
817}: {
818 environmentId: EnvironmentId | null;
819}) {
820 const [windowMs, setWindowMs] = useState(15 * 60_000);
821 const selectedWindow =
822 HISTORY_WINDOWS.find((option) => option.windowMs === windowMs) ?? HISTORY_WINDOWS[1];
823 const telemetry = useResourceTelemetry(environmentId);
824 const retryTelemetry = telemetry.retry;
825 const history = useResourceTelemetryHistory(
826 {
827 windowMs: selectedWindow.windowMs,
828 bucketMs: selectedWindow.bucketMs,
829 },
830 environmentId,
831 );
832 const signalServerProcess = useAtomCommand(serverEnvironment.signalProcess, {
833 reportFailure: false,
834 });
835 const [signalingKeys, setSignalingKeys] = useState<ReadonlySet<string>>(() => new Set());
836 const signalingKeysRef = useRef<ReadonlySet<string>>(new Set());
837 const environmentIdRef = useRef(environmentId);
838 useEffect(() => {
839 environmentIdRef.current = environmentId;
840 return () => {
841 environmentIdRef.current = null;
842 };
843 }, [environmentId]);
844 const [isRetrying, setIsRetrying] = useState(false);
845 const snapshot = telemetry.data;
846 const allT3 = snapshot?.groups.allT3;
847​
848 const signalProcess = useCallback(
849 async (process: ResourceTelemetryProcess, signal: ServerProcessSignal) => {
850 const targetEnvironmentId = environmentIdRef.current;
851 if (targetEnvironmentId === null) return;
852 const identityKey = processIdentityKey(process);
853 if (signalingKeysRef.current.has(identityKey)) return;
854 const nextSignalingKeys = new Set(signalingKeysRef.current).add(identityKey);
855 signalingKeysRef.current = nextSignalingKeys;
856 setSignalingKeys(nextSignalingKeys);
857 const clearSignaling = () => {
858 const next = new Set(signalingKeysRef.current);
859 next.delete(identityKey);
860 signalingKeysRef.current = next;
861 setSignalingKeys(next);
862 };
863​
864 if (signal === "SIGKILL") {
865 let confirmed = false;
866 try {
867 confirmed = await ensureLocalApi().dialogs.confirm(
868 `Send SIGKILL to process ${process.identity.pid}? This cannot be handled by the process.`,
869 { variant: "destructive" },
870 );
871 } catch (error) {
872 clearSignaling();
873 toastManager.add({
874 type: "error",
875 title: "Could not confirm signal",
876 description: error instanceof Error ? error.message : `Failed to send ${signal}.`,
877 });
878 return;
879 }
880 if (!confirmed) {
881 clearSignaling();
882 return;
883 }
884 }
885 if (environmentIdRef.current !== targetEnvironmentId) {
886 clearSignaling();
887 return;
888 }
889 void signalServerProcess({
890 environmentId: targetEnvironmentId,
891 input: {
892 pid: process.identity.pid,
893 startTimeMs: process.identity.startTimeMs,
894 signal,
895 },
896 })
897 .then((result) => {
898 if (result._tag === "Failure") {
899 if (isAtomCommandInterrupted(result)) return;
900 throw squashAtomCommandFailure(result);
901 }
902 if (result.value.signaled) return;
903 toastManager.add({
904 type: "error",
905 title: `Could not send ${signal}`,
906 description: Option.getOrElse(
907 result.value.message,
908 () => `Failed to send ${signal} to process ${process.identity.pid}.`,
909 ),
910 });
911 })
912 .catch((error: unknown) => {
913 toastManager.add({
914 type: "error",
915 title: `Could not send ${signal}`,
916 description: error instanceof Error ? error.message : `Failed to send ${signal}.`,
917 });
918 })
919 .finally(() => {
920 clearSignaling();
921 });
922 },
923 [signalServerProcess],
924 );
925​
926 const retryCollector = useCallback(() => {
927 setIsRetrying(true);
928 void retryTelemetry()
929 .catch((error: unknown) => {
930 toastManager.add({
931 type: "error",
932 title: "Could not restart resource monitor",
933 description:
934 error instanceof Error ? error.message : "The resource monitor retry failed.",
935 });
936 })
937 .finally(() => {
938 setIsRetrying(false);
939 });
940 }, [retryTelemetry]);
941​
942 const speedLimit = snapshot ? Option.getOrNull(snapshot.speedLimitPercent) : null;
943 const collectorNeedsRetry = shouldShowResourceMonitorRetry({
944 nativeStatus: snapshot?.health.native.status ?? null,
945 error: telemetry.error,
946 });
947 const hasHostPowerSignal =
948 snapshot !== null &&
949 (snapshot.power.onBattery !== "unknown" ||
950 snapshot.power.lowPowerMode !== "unknown" ||
951 snapshot.power.idle !== "unknown" ||
952 snapshot.power.locked !== "unknown" ||
953 snapshot.power.thermalState !== "unknown");
954​
955 return (
956 <>
957 <SettingsSection
958 title="Resource monitor"
959 icon={<ActivityIcon className="size-4 text-muted-foreground" />}
960 headerAction={
961 <div className="flex items-center gap-2">
962 {snapshot ? (
963 <SourceStatusBadge label="Native" status={snapshot.health.native.status} />
964 ) : null}
965 <LastSampleLabel sampledAt={snapshot?.readAt ?? null} />
966 <Tooltip>
967 <TooltipTrigger
968 render={
969 <Button
970 size="icon-micro"
971 variant="ghost"
972 disabled={telemetry.isPending}
973 onClick={telemetry.refresh}
974 aria-label="Refresh resource telemetry"
975 >
976 <RefreshIcon size="xs" refreshing={telemetry.isPending} />
977 </Button>
978 }
979 />
980 <TooltipPopup side="top">Refresh telemetry snapshot</TooltipPopup>
981 </Tooltip>
982 </div>
983 }
984 >
985 <div className="overflow-hidden rounded-2xl border border-border/70 bg-card shadow-sm/5">
986 <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">
987 <div>
988 <div className="text-3xs font-semibold uppercase tracking-widest text-muted-foreground/70">
989 T3 system footprint
990 </div>
991 <p className="mt-1 max-w-xl text-xs leading-relaxed text-muted-foreground">
992 Live native counters for the server, providers, terminals, desktop processes, and
993 the monitor itself.
994 </p>
995 </div>
996 <div className="flex items-center gap-2 text-3xs text-muted-foreground/65">
997 <span className="size-1.5 rounded-full bg-success" />
998 Sampling every {snapshot ? formatSampleInterval(snapshot.sampleIntervalMs) : "..."}
999 </div>
1000 </div>
1001 <div className="grid grid-cols-2 divide-x divide-y divide-border/55 md:grid-cols-3">
1002 <IconStat
1003 icon={<CpuIcon className="size-3.5" />}
1004 label="Current CPU"
1005 value={allT3 ? `${allT3.currentCpuPercent.toFixed(1)}%` : "..."}
1006 detail={allT3 ? `${formatCpuTime(allT3.cpuTimeMs)} observed CPU time` : undefined}
1007 />
1008 <IconStat
1009 icon={<MemoryStickIcon className="size-3.5" />}
1010 label="Resident memory"
1011 value={allT3 ? formatBytes(allT3.currentRssBytes) : "..."}
1012 detail={
1013 allT3 ? `${formatBytes(allT3.peakRssBytes)} combined process peaks` : undefined
1015 />
1016 <IconStat
1017 icon={<ActivityIcon className="size-3.5" />}
1018 label="Process count"
1019 value={allT3 ? String(allT3.processCount) : "..."}
1020 detail={
1021 allT3 ? `${allT3.processStarts} starts · ${allT3.processExits} exits` : undefined
1023 />
1024 <IconStat
1025 icon={<HardDriveIcon className="size-3.5" />}
1026 label="Read throughput"
1027 value={allT3 ? formatRate(allT3.ioReadBytesPerSecond) : "..."}
1028 detail={allT3 ? `${formatBytes(allT3.ioReadBytes)} observed` : undefined}
1029 />
1030 <IconStat
1031 icon={<DatabaseIcon className="size-3.5" />}
1032 label="Write throughput"
1033 value={allT3 ? formatRate(allT3.ioWriteBytesPerSecond) : "..."}
1034 detail={allT3 ? `${formatBytes(allT3.ioWriteBytes)} observed` : undefined}
1035 tone={
1036 allT3 && allT3.ioWriteBytesPerSecond >= 10 * 1_024 * 1_024
1037 ? "danger"
1038 : allT3 && allT3.ioWriteBytesPerSecond >= 1_024 * 1_024
1039 ? "warning"
1040 : "default"
1042 />
1043 <IconStat
1044 icon={<GaugeIcon className="size-3.5" />}
1045 label="CPU speed limit"
1046 value={
1047 snapshot ? (speedLimit === null ? "Unknown" : `${speedLimit.toFixed(0)}%`) : "..."
1049 detail={snapshot ? `${snapshot.power.thermalState} thermal state` : undefined}
1050 tone={speedLimit !== null && speedLimit < 80 ? "warning" : "default"}
1051 />
1052 </div>
1053 {telemetry.error ? (
1054 <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">
1055 <AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
1056 <span>{telemetry.error}</span>
1057 </div>
1058 ) : null}
1059 {snapshot ? (
1060 <div className="grid border-t border-border/60 bg-muted/10 md:grid-cols-3">
1061 <AggregateCard
1062 label="Backend + agents"
1063 accentClass="bg-success/80"
1064 aggregate={snapshot.groups.backend}
1065 />
1066 <AggregateCard
1067 label="Desktop"
1068 accentClass="bg-info/80"
1069 aggregate={snapshot.groups.electron}
1070 />
1071 <AggregateCard
1072 label="Monitor overhead"
1073 accentClass="bg-warning/80"
1074 aggregate={snapshot.groups.monitor}
1075 />
1076 </div>
1077 ) : null}
1078 </div>
1079 </SettingsSection>
1080​
1081 <SettingsSection
1082 title="Host & collection"
1083 icon={<GaugeIcon className="size-4 text-muted-foreground" />}
1084 headerAction={
1085 collectorNeedsRetry ? (
1086 <Button size="xs" variant="outline" disabled={isRetrying} onClick={retryCollector}>
1087 <RefreshIcon size="xs" refreshing={isRetrying} />
1088 Retry monitor
1089 </Button>
1090 ) : null
1093 <div className="grid overflow-hidden rounded-2xl border border-border/70 bg-card shadow-xs/5 md:grid-cols-2 md:divide-x md:divide-border/60">
1094 <div className="px-4 py-4 sm:px-5">
1095 <div className="mb-3 flex items-center gap-2 text-3xs font-semibold uppercase tracking-widest text-muted-foreground/70">
1096 <span className="flex size-6 items-center justify-center rounded-md bg-muted/60">
1097 <BatteryIcon className="size-3.5" />
1098 </span>
1099 Host state
1100 </div>
1101 {hasHostPowerSignal && snapshot ? (
1102 <>
1103 <DetailRow
1104 label="Power source"
1105 value={booleanStateLabel(snapshot.power.onBattery, {
1106 true: "Battery",
1107 false: "External power",
1108 })}
1109 />
1110 <DetailRow
1111 label="Low power mode"
1112 value={booleanStateLabel(snapshot.power.lowPowerMode, {
1113 true: "Enabled",
1114 false: "Disabled",
1115 })}
1116 />
1117 <DetailRow
1118 label="Idle"
1119 value={`${booleanStateLabel(snapshot.power.idle, {
1120 true: "Idle",
1121 false: "Active",
1122 })}${
1123 snapshot.power.idleSeconds === null
1124 ? ""
1125 : ` · ${Math.round(snapshot.power.idleSeconds)}s`
1126 }`}
1127 />
1128 <DetailRow
1129 label="Session"
1130 value={
1131 snapshot.power.suspended
1132 ? "Suspended"
1133 : booleanStateLabel(snapshot.power.locked, {
1134 true: "Locked",
1135 false: "Unlocked",
1136 })
1138 />
1139 <DetailRow
1140 label="Thermal"
1141 value={snapshot.power.thermalState}
1142 valueClassName={
1143 snapshot.power.thermalState === "serious" ||
1144 snapshot.power.thermalState === "critical"
1145 ? "text-destructive"
1146 : undefined
1148 />
1149 </>
1150 ) : (
1151 <div className="rounded-xl border border-dashed border-border/70 bg-muted/20 px-4 py-5">
1152 <div className="text-sm font-medium text-foreground">
1153 Desktop host signals not connected
1154 </div>
1155 <p className="mt-1.5 max-w-sm text-2xs leading-relaxed text-muted-foreground/70">
1156 Power, idle, lock, and thermal state are supplied by the desktop host. Process
1157 telemetry remains fully active in this browser session.
1158 </p>
1159 </div>
1160 )}
1161 </div>
1162 <div className="border-t border-border/60 px-4 py-4 md:border-t-0 sm:px-5">
1163 <div className="mb-3 flex items-center gap-2 text-3xs font-semibold uppercase tracking-widest text-muted-foreground/70">
1164 <span className="flex size-6 items-center justify-center rounded-md bg-muted/60">
1165 <GaugeIcon className="size-3.5" />
1166 </span>
1167 Collection health
1168 </div>
1169 {snapshot ? (
1170 <>
1171 <HealthSource label="Native process monitor" health={snapshot.health.native} />
1172 <HealthSource label="Electron main process" health={snapshot.health.desktop} />
1173 <DetailRow
1174 label="Collection time"
1175 value={formatDurationMicros(snapshot.health.collectionDurationMicros)}
1176 />
1177 <DetailRow
1178 label="Process scan"
1179 value={`${snapshot.health.retainedProcessCount}/${snapshot.health.scannedProcessCount} retained`}
1180 />
1181 <DetailRow
1182 label="Inaccessible"
1183 value={String(snapshot.health.inaccessibleProcessCount)}
1184 valueClassName={
1185 snapshot.health.inaccessibleProcessCount > 0
1186 ? "text-warning-foreground"
1187 : undefined
1189 />
1190 <DetailRow
1191 label="Sidecar"
1192 value={Option.match(snapshot.health.sidecarVersion, {
1193 onNone: () => "Unavailable",
1194 onSome: (version) =>
1195 `${version}${Option.match(snapshot.health.sidecarPid, {
1196 onNone: () => "",
1197 onSome: (pid) => ` · PID ${pid}`,
1198 })}`,
1199 })}
1200 />
1201 <DetailRow label="Restarts" value={String(snapshot.health.restartCount)} />
1202 </>
1203 ) : (
1204 <div className="py-4 text-xs text-muted-foreground">
1205 Waiting for collector health.
1206 </div>
1207 )}
1208 </div>
1209 </div>
1210 </SettingsSection>
1211​
1212 <SettingsSection
1213 title="Resource timeline"
1214 icon={<HardDriveIcon className="size-4 text-muted-foreground" />}
1215 headerAction={
1216 <div className="flex items-center gap-2">
1217 <HistoryWindowSelector selectedWindowMs={windowMs} onSelect={setWindowMs} />
1218 <Button
1219 size="icon-micro"
1220 variant="ghost"
1221 disabled={history.isPending}
1222 onClick={history.refresh}
1223 aria-label="Refresh resource history"
1225 <RefreshIcon size="xs" refreshing={history.isPending} />
1226 </Button>
1227 </div>
1230 <div className="overflow-hidden rounded-2xl border border-border/70 bg-card shadow-xs/5">
1231 {history.error ? (
1232 <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">
1233 <AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
1234 <span>{history.error}</span>
1235 </div>
1236 ) : null}
1237 <ResourceHistoryChart buckets={history.data?.buckets ?? []} />
1238 <HistoryProcessTable processes={history.data?.topProcesses ?? []} />
1239 </div>
1240 </SettingsSection>
1241​
1242 <SettingsSection
1243 title="Live process tree"
1244 icon={<CpuIcon className="size-4 text-muted-foreground" />}
1245 headerAction={
1246 snapshot ? (
1247 <span className="text-3xs text-muted-foreground/55">
1248 Identity: <span className="font-mono">PID + start time</span>
1249 </span>
1250 ) : null
1253 <div className="overflow-hidden rounded-2xl border border-border/70 bg-card shadow-xs/5">
1254 <ProcessTable
1255 processes={snapshot?.processes ?? []}
1256 signalingKeys={signalingKeys}
1257 onSignal={signalProcess}
1258 />
1259 </div>
1260 </SettingsSection>
1261​
1262 <SettingsSection
1263 title="Instrumented application I/O"
1264 icon={<DatabaseIcon className="size-4 text-muted-foreground" />}
1265 headerAction={
1266 <span className="text-3xs text-muted-foreground/55">Logical bytes by operation</span>
1269 <div className="overflow-hidden rounded-2xl border border-border/70 bg-card shadow-xs/5">
1270 <div className="bg-muted/15 px-4 py-3 text-2xs leading-relaxed text-muted-foreground sm:px-5">
1271 Native counters identify which process is reading or writing. These application-level
1272 counters identify known T3 operations so process spikes can be correlated with specific
1273 persistence and logging paths.
1274 </div>
1275 <AttributionTable entries={snapshot?.attribution.entries ?? []} />
1276 </div>
1277 </SettingsSection>
1278 </>
1279 );