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