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