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

ResourceTelemetryDiagnostics.tsx

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