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

ResourceTelemetryDiagnostics.tsx

1,281 lines47.5 KB

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