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

ResourceTelemetryDiagnostics.tsx

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