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

ResourceTelemetryDiagnostics.tsx

1,291 lines48.1 KB

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