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