feat: add native resource telemetry

Replace scheduled process shell probes with a persistent native collector, Electron power/process telemetry, Effect services, diagnostics UI, attribution, and release packaging.

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-06-17 13:34:50 -07:00
1 parent 79ad071184
commit dbd8a8e09c
62 files changed
+7749 -1965

No files matched your search

@@ -1,18 +1,5 @@
import {
AlertTriangleIcon,
ChevronDownIcon,
ChevronRightIcon,
CopyIcon,
FolderOpenIcon,
InfoIcon,
RefreshCwIcon,
} from "lucide-react";
import { useCallback, useMemo, useState, type ReactNode } from "react";
import type {
ServerProcessDiagnosticsEntry,
ServerProcessResourceHistorySummary,
ServerProcessSignal,
} from "@t3tools/contracts";
import { AlertTriangleIcon, CopyIcon, FolderOpenIcon, InfoIcon, RefreshCwIcon } from "lucide-react";
import { useCallback, useState, type ReactNode } from "react";
import * as DateTime from "effect/DateTime";
import * as Option from "effect/Option";
@@ -21,15 +8,11 @@ import { cn } from "../../lib/utils";
import { resolveAndPersistPreferredEditor } from "../../editorPreferences";
import { formatRelativeTime } from "../../timestampFormat";
import { useServerAvailableEditors, useServerObservability } from "../../rpc/serverState";
import {
useProcessDiagnostics,
useProcessResourceHistory,
} from "../../lib/processDiagnosticsState";
import { useTraceDiagnostics } from "../../lib/traceDiagnosticsState";
import { Button } from "../ui/button";
import { ScrollArea } from "../ui/scroll-area";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { toastManager } from "../ui/toast";
import { ResourceTelemetryDiagnostics } from "./ResourceTelemetryDiagnostics";
import { SettingsPageContainer, SettingsSection, useRelativeTimeTick } from "./settingsLayout";
const NUMBER_FORMAT = new Intl.NumberFormat();
@@ -43,18 +26,6 @@ function formatDuration(value: number): string {
return `${(value / 1_000).toFixed(value >= 10_000 ? 1 : 2)} s`;
}
function formatBytes(value: number): string {
if (value < 1024) return `${value} B`;
const units = ["KB", "MB", "GB"] as const;
let unitIndex = -1;
let next = value;
do {
next /= 1024;
unitIndex += 1;
} while (next >= 1024 && unitIndex < units.length - 1);
return `${next.toFixed(next >= 10 ? 1 : 2)} ${units[unitIndex]}`;
}
function formatRelative(value: DateTime.Utc | null): string {
if (!value) return "No trace records";
const relative = formatRelativeTime(DateTime.formatIso(value));
@@ -70,10 +41,6 @@ function shortenTraceId(traceId: string): string {
return `${traceId.slice(0, 18)}...${traceId.slice(-10)}`;
}
function isStaleProcessSignalMessage(message: string | undefined): boolean {
return message?.includes("not a live descendant") ?? false;
}
function StatBlock({
label,
value,
@@ -286,471 +253,6 @@ function TraceIdCell({ traceId }: { traceId: string }) {
);
}
function formatProcessName(command: string): string {
const firstToken = command.trim().split(/\s+/)[0];
if (!firstToken) return command;
const normalized = firstToken.replace(/^['"]|['"]$/g, "");
const segments = normalized.split(/[\\/]/).filter(Boolean);
return segments.at(-1) ?? normalized;
}
function formatProcessType(process: ServerProcessDiagnosticsEntry): string {
if (process.depth > 0) return "Subprocess";
if (/\b(codex|claude|opencode|cursor)\b/i.test(process.command)) return "Agent";
return "Process";
}
function ProcessNameCell({
process,
isExpanded,
onToggle,
}: {
process: ServerProcessDiagnosticsEntry;
isExpanded: boolean;
onToggle: (pid: number) => void;
}) {
const name = formatProcessName(process.command);
const hasChildren = process.childPids.length > 0;
const ChevronIcon = isExpanded ? ChevronDownIcon : ChevronRightIcon;
return (
<div
className="grid min-w-0 grid-cols-[1.25rem_0.375rem_minmax(0,1fr)] items-center gap-2"
style={{ paddingLeft: `${Math.min(process.depth, 6) * 10}px` }}
>
{hasChildren ? (
<button
type="button"
className="inline-flex size-5 items-center justify-center rounded-sm text-muted-foreground hover:bg-accent hover:text-foreground"
aria-label={isExpanded ? `Collapse ${name}` : `Expand ${name}`}
onClick={() => onToggle(process.pid)}
>
<ChevronIcon className="size-3.5" />
</button>
) : (
<span className="size-5 shrink-0" aria-hidden="true" />
)}
<span className="size-1.5 shrink-0 rounded-full bg-emerald-500/80" />
<Tooltip>
<TooltipTrigger
render={<span className="min-w-0 truncate font-medium text-foreground">{name}</span>}
/>
<TooltipPopup
side="top"
className="max-w-[min(440px,calc(100vw-2rem))] whitespace-normal break-words text-left font-mono text-[11px] leading-relaxed text-wrap"
>
{process.command}
</TooltipPopup>
</Tooltip>
</div>
);
}
function ProcessSignalActions({
process,
isSignaling,
onSignal,
}: {
process: ServerProcessDiagnosticsEntry;
isSignaling: boolean;
onSignal: (pid: number, signal: ServerProcessSignal) => void;
}) {
return (
<div className="flex items-center justify-end gap-1.5">
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
disabled={isSignaling}
className="text-[11px] font-medium text-muted-foreground underline-offset-2 hover:text-foreground hover:underline disabled:pointer-events-none disabled:opacity-50"
onClick={() => onSignal(process.pid, "SIGINT")}
>
INT
</button>
}
/>
<TooltipPopup side="top">Send SIGINT</TooltipPopup>
</Tooltip>
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
disabled={isSignaling}
className="text-[11px] font-medium text-destructive underline-offset-2 hover:underline disabled:pointer-events-none disabled:opacity-50"
onClick={() => onSignal(process.pid, "SIGKILL")}
>
KILL
</button>
}
/>
<TooltipPopup side="top">Send SIGKILL</TooltipPopup>
</Tooltip>
</div>
);
}
function ProcessDiagnosticsTable({
processes,
signalingPid,
onSignal,
emptyLabel,
}: {
processes: ReadonlyArray<ServerProcessDiagnosticsEntry>;
signalingPid: number | null;
onSignal: (pid: number, signal: ServerProcessSignal) => void;
emptyLabel?: string;
}) {
const [collapsedPids, setCollapsedPids] = useState<ReadonlySet<number>>(() => new Set());
const visibleProcesses = useMemo(() => {
const visible: ServerProcessDiagnosticsEntry[] = [];
let hiddenChildDepth: number | null = null;
for (const process of processes) {
if (hiddenChildDepth !== null) {
if (process.depth > hiddenChildDepth) continue;
hiddenChildDepth = null;
}
visible.push(process);
if (collapsedPids.has(process.pid)) {
hiddenChildDepth = process.depth;
}
}
return visible;
}, [collapsedPids, processes]);
const toggleProcess = useCallback((pid: number) => {
setCollapsedPids((previous) => {
const next = new Set(previous);
if (next.has(pid)) {
next.delete(pid);
} else {
next.add(pid);
}
return next;
});
}, []);
return (
<ScrollArea
chainVerticalScroll
scrollFade
hideScrollbars
className="max-h-[min(64vh,44rem)] w-full max-w-full rounded-none border-t border-border/60"
>
<table className="w-full min-w-[1040px] table-fixed text-left text-xs">
<colgroup>
<col className="w-[24%]" />
<col className="w-[8%]" />
<col className="w-[10%]" />
<col className="w-[33%]" />
<col className="w-[8%]" />
<col className="w-[11%]" />
<col className="w-[6%]" />
</colgroup>
<thead className="sticky top-0 z-10 border-b border-border/60 bg-card text-[11px] uppercase tracking-[0.08em] text-muted-foreground/70">
<tr>
<th className="px-4 py-2 font-semibold sm:pl-5">Name</th>
<th className="px-3 py-2 text-right font-semibold">CPU</th>
<th className="px-3 py-2 text-right font-semibold">Memory</th>
<th className="px-3 py-2 font-semibold">Command</th>
<th className="px-3 py-2 text-right font-semibold">PID</th>
<th className="px-3 py-2 font-semibold">Type</th>
<th className="p-2 text-right font-semibold sm:pr-4">Kill</th>
</tr>
</thead>
<tbody className="divide-y divide-border/50">
{visibleProcesses.length === 0 ? (
<tr>
<td colSpan={7} className="px-4 py-4 text-xs text-muted-foreground sm:px-5">
{emptyLabel ?? "No live descendant processes found."}
</td>
</tr>
) : null}
{visibleProcesses.map((process) => (
<tr key={process.pid} className="hover:bg-muted/20">
<td className="px-4 py-2 align-middle sm:pl-5">
<ProcessNameCell
process={process}
isExpanded={!collapsedPids.has(process.pid)}
onToggle={toggleProcess}
/>
</td>
<td className="px-3 py-2 text-right align-middle font-mono tabular-nums">
{process.cpuPercent.toFixed(1)}%
</td>
<td className="px-3 py-2 text-right align-middle font-mono tabular-nums">
{formatBytes(process.rssBytes)}
</td>
<td className="px-3 py-2 align-middle text-muted-foreground">
<Tooltip>
<TooltipTrigger
render={<span className="block truncate">{process.command}</span>}
/>
<TooltipPopup
side="top"
className="max-w-[min(440px,calc(100vw-2rem))] whitespace-normal break-words text-left font-mono text-[11px] leading-relaxed text-wrap"
>
{process.command}
</TooltipPopup>
</Tooltip>
</td>
<td className="px-3 py-2 text-right align-middle font-mono tabular-nums text-muted-foreground">
{process.pid}
</td>
<td className="truncate px-3 py-2 align-middle text-muted-foreground">
{formatProcessType(process)}
</td>
<td className="p-2 align-middle sm:pr-4">
<ProcessSignalActions
process={process}
isSignaling={signalingPid === process.pid}
onSignal={onSignal}
/>
</td>
</tr>
))}
</tbody>
</table>
</ScrollArea>
);
}
const RESOURCE_HISTORY_WINDOWS = [
{ label: "5m", windowMs: 5 * 60_000, bucketMs: 30_000 },
{ label: "15m", windowMs: 15 * 60_000, bucketMs: 60_000 },
{ label: "30m", windowMs: 30 * 60_000, bucketMs: 2 * 60_000 },
{ label: "1h", windowMs: 60 * 60_000, bucketMs: 5 * 60_000 },
] as const;
function formatCpuTime(seconds: number): string {
if (seconds < 60) return `${seconds.toFixed(seconds >= 10 ? 1 : 2)}s`;
const minutes = seconds / 60;
if (minutes < 60) return `${minutes.toFixed(minutes >= 10 ? 1 : 2)}m`;
return `${(minutes / 60).toFixed(2)}h`;
}
function formatShortProcessName(command: string): string {
const name = formatProcessName(command);
return name.length > 42 ? `${name.slice(0, 39)}...` : name;
}
function ResourceHistoryProcessNameCell({
process,
visualDepth,
}: {
process: ServerProcessResourceHistorySummary;
visualDepth: number;
}) {
const name = formatShortProcessName(process.command);
return (
<div
className="grid min-w-0 grid-cols-[1.25rem_0.375rem_minmax(0,1fr)] items-center gap-2"
style={{ paddingLeft: `${Math.min(visualDepth, 6) * 10}px` }}
aria-label={`${process.isServerRoot ? "Root" : "Child"} process ${name}`}
>
<span className="size-5 shrink-0" aria-hidden="true" />
<span
className={cn(
"size-1.5 shrink-0 rounded-full",
process.isServerRoot ? "bg-amber-500/90" : "bg-emerald-500/80",
)}
/>
<Tooltip>
<TooltipTrigger
render={<span className="min-w-0 truncate font-medium text-foreground">{name}</span>}
/>
<TooltipPopup
side="top"
className="max-w-[min(440px,calc(100vw-2rem))] whitespace-normal break-words text-left font-mono text-[11px] leading-relaxed text-wrap"
>
{process.command}
</TooltipPopup>
</Tooltip>
</div>
);
}
function ProcessResourceHistoryChart({
buckets,
}: {
buckets: ReadonlyArray<{
readonly startedAt: DateTime.Utc;
readonly avgCpuPercent: number;
readonly maxCpuPercent: number;
}>;
}) {
const maxCpuPercent = Math.max(1, ...buckets.map((bucket) => bucket.maxCpuPercent));
return (
<div className="border-t border-border/60 px-4 py-3 sm:px-5">
<div className="flex h-28 items-end gap-1 overflow-hidden rounded-sm bg-muted/10 p-2">
{buckets.map((bucket) => {
const peakHeight = Math.max(2, (bucket.maxCpuPercent / maxCpuPercent) * 100);
const averageHeight = Math.max(2, (bucket.avgCpuPercent / maxCpuPercent) * 100);
return (
<Tooltip key={DateTime.formatIso(bucket.startedAt)}>
<TooltipTrigger
render={
<div className="flex h-full min-w-1 flex-1 items-end">
<div
className="relative h-full w-full"
aria-label={`Average CPU ${bucket.avgCpuPercent.toFixed(1)}%, peak CPU ${bucket.maxCpuPercent.toFixed(1)}%`}
>
<div
className="absolute inset-x-0 bottom-0 rounded-t-sm bg-foreground/15 transition-colors"
style={{ height: `${peakHeight}%` }}
/>
<div
className="absolute inset-x-0 bottom-0 rounded-t-sm bg-foreground/60 transition-colors"
style={{ height: `${averageHeight}%` }}
/>
</div>
</div>
}
/>
<TooltipPopup side="top">
Avg {bucket.avgCpuPercent.toFixed(1)}%, peak {bucket.maxCpuPercent.toFixed(1)}%
</TooltipPopup>
</Tooltip>
);
})}
</div>
</div>
);
}
function ResourceHistoryWindowSelector({
selectedWindowMs,
onSelect,
}: {
selectedWindowMs: number;
onSelect: (windowMs: number) => void;
}) {
return (
<div className="flex items-center rounded-md border border-border/60 p-0.5">
{RESOURCE_HISTORY_WINDOWS.map((option) => (
<button
key={option.windowMs}
type="button"
className={cn(
"h-6 rounded-sm px-2 text-[11px] font-medium text-muted-foreground hover:text-foreground",
selectedWindowMs === option.windowMs && "bg-muted text-foreground",
)}
onClick={() => onSelect(option.windowMs)}
>
{option.label}
</button>
))}
</div>
);
}
function ProcessResourceHistoryTable({
processes,
emptyLabel,
}: {
processes: ReadonlyArray<ServerProcessResourceHistorySummary>;
emptyLabel: string;
}) {
const shallowestChildDepth = processes.reduce<number | null>((minDepth, process) => {
if (process.isServerRoot) return minDepth;
return minDepth === null ? process.depth : Math.min(minDepth, process.depth);
}, null);
return (
<ScrollArea
chainVerticalScroll
scrollFade
hideScrollbars
className="max-h-[min(64vh,44rem)] w-full max-w-full border-t border-border/60"
>
<table className="w-full min-w-[980px] table-fixed text-left text-xs">
<colgroup>
<col className="w-[24%]" />
<col className="w-[10%]" />
<col className="w-[10%]" />
<col className="w-[10%]" />
<col className="w-[10%]" />
<col className="w-[10%]" />
<col className="w-[16%]" />
<col className="w-[10%]" />
</colgroup>
<thead className="sticky top-0 z-10 border-b border-border/60 bg-card text-[11px] uppercase tracking-[0.08em] text-muted-foreground/70">
<tr>
<th className="px-4 py-2 font-semibold sm:pl-5">Process</th>
<th className="px-3 py-2 text-right font-semibold">CPU Time</th>
<th className="px-3 py-2 text-right font-semibold">Current</th>
<th className="px-3 py-2 text-right font-semibold">Average</th>
<th className="px-3 py-2 text-right font-semibold">Peak</th>
<th className="px-3 py-2 text-right font-semibold">Max Mem</th>
<th className="px-3 py-2 font-semibold">Command</th>
<th className="px-3 py-2 text-right font-semibold sm:pr-5">PID</th>
</tr>
</thead>
<tbody className="divide-y divide-border/50">
{processes.length === 0 ? (
<tr>
<td colSpan={8} className="px-4 py-4 text-xs text-muted-foreground sm:px-5">
{emptyLabel}
</td>
</tr>
) : null}
{processes.map((process) => (
<tr key={process.processKey} className="hover:bg-muted/20">
<td className="px-4 py-2 align-middle sm:pl-5">
<ResourceHistoryProcessNameCell
process={process}
visualDepth={
process.isServerRoot || shallowestChildDepth === null
? 0
: Math.max(1, process.depth - shallowestChildDepth + 1)
}
/>
</td>
<td className="px-3 py-2 text-right align-middle font-mono tabular-nums">
{formatCpuTime(process.cpuSecondsApprox)}
</td>
<td className="px-3 py-2 text-right align-middle font-mono tabular-nums">
{process.currentCpuPercent.toFixed(1)}%
</td>
<td className="px-3 py-2 text-right align-middle font-mono tabular-nums">
{process.avgCpuPercent.toFixed(1)}%
</td>
<td className="px-3 py-2 text-right align-middle font-mono tabular-nums">
{process.maxCpuPercent.toFixed(1)}%
</td>
<td className="px-3 py-2 text-right align-middle font-mono tabular-nums">
{formatBytes(process.maxRssBytes)}
</td>
<td className="px-3 py-2 align-middle text-muted-foreground">
<Tooltip>
<TooltipTrigger
render={<span className="block truncate">{process.command}</span>}
/>
<TooltipPopup
side="top"
className="max-w-[min(440px,calc(100vw-2rem))] whitespace-normal break-words text-left font-mono text-[11px] leading-relaxed text-wrap"
>
{process.command}
</TooltipPopup>
</Tooltip>
</td>
<td className="px-3 py-2 text-right align-middle font-mono tabular-nums text-muted-foreground sm:pr-5">
{process.pid}
</td>
</tr>
))}
</tbody>
</table>
</ScrollArea>
);
}
function DiagnosticsLastChecked({ checkedAt }: { checkedAt: DateTime.Utc | null }) {
useRelativeTimeTick();
const relative = checkedAt ? formatRelativeTime(DateTime.formatIso(checkedAt)) : null;
@@ -805,29 +307,9 @@ function DiagnosticsRefreshButton({
export function DiagnosticsSettingsPanel() {
const observability = useServerObservability();
const availableEditors = useServerAvailableEditors();
const [resourceWindowMs, setResourceWindowMs] = useState(15 * 60_000);
const selectedResourceWindow =
RESOURCE_HISTORY_WINDOWS.find((option) => option.windowMs === resourceWindowMs) ??
RESOURCE_HISTORY_WINDOWS[1];
const { data, error, isPending, refresh } = useTraceDiagnostics();
const {
data: processData,
error: processError,
isPending: isProcessPending,
refresh: refreshProcesses,
} = useProcessDiagnostics();
const {
data: resourceData,
error: resourceError,
isPending: isResourcePending,
refresh: refreshResources,
} = useProcessResourceHistory({
windowMs: selectedResourceWindow.windowMs,
bucketMs: selectedResourceWindow.bucketMs,
});
const [isOpeningLogsDirectory, setIsOpeningLogsDirectory] = useState(false);
const [openLogsDirectoryError, setOpenLogsDirectoryError] = useState<string | null>(null);
const [signalingPid, setSignalingPid] = useState<number | null>(null);
const openLogsDirectory = useCallback(() => {
const logsDirectoryPath = observability?.logsDirectoryPath ?? null;
@@ -854,58 +336,7 @@ export function DiagnosticsSettingsPanel() {
}, [availableEditors, observability?.logsDirectoryPath]);
const isInitialLoading = isPending && data === null;
const isProcessInitialLoading = isProcessPending && processData === null;
const signalProcess = useCallback(
(pid: number, signal: ServerProcessSignal) => {
if (
signal === "SIGKILL" &&
!window.confirm(`Send SIGKILL to process ${pid}? This cannot be handled by the process.`)
) {
return;
}
setSignalingPid(pid);
void ensureLocalApi()
.server.signalProcess({ pid, signal })
.then((result) => {
if (!result.signaled) {
const message = Option.getOrUndefined(result.message);
refreshProcesses();
if (isStaleProcessSignalMessage(message)) {
toastManager.add({
type: "info",
title: "Process already exited",
description:
"The process is not a child of the T3 Server. It might already have exited.",
});
return;
}
toastManager.add({
type: "error",
title: `Could not send ${signal}`,
description: message ?? `Failed to send ${signal}.`,
});
return;
}
refreshProcesses();
})
.catch((error: unknown) => {
toastManager.add({
type: "error",
title: `Could not send ${signal}`,
description: error instanceof Error ? error.message : `Failed to send ${signal}.`,
});
})
.finally(() => {
setSignalingPid(null);
});
},
[refreshProcesses],
);
const processDiagnosticsError = processData ? Option.getOrNull(processData.error) : null;
const processResourceError = resourceData ? Option.getOrNull(resourceData.error) : null;
const traceDiagnosticsError = data ? Option.getOrNull(data.error) : null;
const traceDiagnosticsPartialFailure = data
? Option.getOrElse(data.partialFailure, () => false)
@@ -913,130 +344,7 @@ export function DiagnosticsSettingsPanel() {
return (
<SettingsPageContainer>
<SettingsSection
title="Live Processes"
headerAction={
<div className="flex items-center gap-1.5">
<DiagnosticsLastChecked checkedAt={processData?.readAt ?? null} />
<DiagnosticsRefreshButton
isPending={isProcessPending}
label="Refresh process diagnostics"
onClick={refreshProcesses}
/>
</div>
}
>
<StatsGrid>
<StatBlock
label="Child Processes"
value={processData ? formatCount(processData.processCount) : "..."}
/>
<StatBlock
label="CPU"
value={processData ? `${processData.totalCpuPercent.toFixed(1)}%` : "..."}
tooltip="Total CPU across live child processes of the current server process. The desktop shell and other parent processes are not included."
/>
<StatBlock
label="Memory"
value={processData ? formatBytes(processData.totalRssBytes) : "..."}
tooltip="Total resident memory across live child processes of the current server process. The desktop shell and other parent processes are not included."
/>
<StatBlock
label="Server PID"
value={processData ? String(processData.serverPid) : "..."}
/>
</StatsGrid>
{processDiagnosticsError || processError ? (
<div className="space-y-2 border-t border-border/60 px-4 py-3 text-xs text-muted-foreground sm:px-5">
{processDiagnosticsError ? (
<div className="flex items-start gap-2 text-destructive">
<AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
<span>{processDiagnosticsError.message}</span>
</div>
) : null}
{processError ? (
<div className="flex items-start gap-2 text-destructive">
<AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
<span>{processError}</span>
</div>
) : null}
</div>
) : null}
<ProcessDiagnosticsTable
processes={processData?.processes ?? []}
signalingPid={signalingPid}
onSignal={signalProcess}
emptyLabel={
isProcessInitialLoading
? "Loading live processes..."
: "No live descendant processes found."
}
/>
</SettingsSection>
<SettingsSection
title="Resource History"
headerAction={
<div className="flex items-center gap-1.5">
<ResourceHistoryWindowSelector
selectedWindowMs={resourceWindowMs}
onSelect={setResourceWindowMs}
/>
<DiagnosticsLastChecked checkedAt={resourceData?.readAt ?? null} />
<DiagnosticsRefreshButton
isPending={isResourcePending}
label="Refresh resource history"
onClick={refreshResources}
/>
</div>
}
>
<StatsGrid>
<StatBlock
label="CPU Time"
value={resourceData ? formatCpuTime(resourceData.totalCpuSecondsApprox) : "..."}
tooltip="Approximate active CPU time for the T3 server root process and its descendants during the selected window. It grows only while sampled processes use CPU and older samples leave as the window moves."
/>
<StatBlock
label="Samples"
value={resourceData ? formatCount(resourceData.retainedSampleCount) : "..."}
tooltip="In-memory process samples retained by the server. This resets when the server restarts."
/>
<StatBlock
label="Interval"
value={resourceData ? formatDuration(resourceData.sampleIntervalMs) : "..."}
/>
<StatBlock
label="Processes"
value={resourceData ? formatCount(resourceData.topProcesses.length) : "..."}
/>
</StatsGrid>
{processResourceError || resourceError ? (
<div className="space-y-2 border-t border-border/60 px-4 py-3 text-xs text-muted-foreground sm:px-5">
{processResourceError ? (
<div className="flex items-start gap-2 text-destructive">
<AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
<span>{processResourceError.message}</span>
</div>
) : null}
{resourceError ? (
<div className="flex items-start gap-2 text-destructive">
<AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
<span>{resourceError}</span>
</div>
) : null}
</div>
) : null}
<ProcessResourceHistoryChart buckets={resourceData?.buckets ?? []} />
<ProcessResourceHistoryTable
processes={resourceData?.topProcesses ?? []}
emptyLabel={
isResourcePending && resourceData === null
? "Collecting process resource samples..."
: "No process resource samples found for this window."
}
/>
</SettingsSection>
<ResourceTelemetryDiagnostics />
<SettingsSection
title="Trace Diagnostics"
File diff suppressed because it is too large. Load diff
@@ -172,11 +172,15 @@ vi.mock("@t3tools/client-runtime", async (importOriginal) => {
getTraceDiagnostics: vi.fn(),
getProcessDiagnostics: vi.fn(),
getProcessResourceHistory: vi.fn(),
getResourceTelemetry: vi.fn(),
getResourceTelemetryHistory: vi.fn(),
retryResourceTelemetry: vi.fn(),
signalProcess: vi.fn(),
reportClientActivity: vi.fn(),
reportHostPowerState: vi.fn(),
getBackgroundPolicy: vi.fn(),
subscribeBackgroundPolicy: vi.fn(() => () => undefined),
subscribeResourceTelemetry: vi.fn(() => () => undefined),
},
};
return {
+228
View File
@@ -0,0 +1,228 @@
import { useAtomValue } from "@effect/atom-react";
import type {
ResourceTelemetryHistory,
ResourceTelemetryHistoryInput,
ResourceTelemetrySnapshot,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useCallback, useEffect } from "react";
import {
getPrimaryEnvironmentConnection,
subscribeEnvironmentConnections,
} from "../environments/runtime";
import { ensureLocalApi } from "../localApi";
import { appAtomRegistry } from "../rpc/atomRegistry";
const RESOURCE_TELEMETRY_HISTORY_STALE_TIME_MS = 5_000;
const RESOURCE_TELEMETRY_IDLE_TTL_MS = 5 * 60_000;
const RESOURCE_TELEMETRY_HISTORY_INPUT_SEPARATOR = ":";
interface ResourceTelemetryLiveState {
readonly data: ResourceTelemetrySnapshot | null;
readonly error: string | null;
readonly isPending: boolean;
}
const resourceTelemetryLiveAtom = Atom.make<ResourceTelemetryLiveState>({
data: null,
error: null,
isPending: true,
}).pipe(Atom.keepAlive, Atom.withLabel("resource-telemetry-live"));
function formatResourceTelemetryError(error: unknown): string {
return error instanceof Error ? error.message : "Failed to load resource telemetry.";
}
function updateLiveState(
update: (current: ResourceTelemetryLiveState) => ResourceTelemetryLiveState,
): void {
appAtomRegistry.set(
resourceTelemetryLiveAtom,
update(appAtomRegistry.get(resourceTelemetryLiveAtom)),
);
}
let retainCount = 0;
let requestGeneration = 0;
let activeClient: object | null = null;
let unsubscribeTelemetry: () => void = () => undefined;
let unsubscribeConnections: () => void = () => undefined;
function applySnapshot(snapshot: ResourceTelemetrySnapshot): void {
updateLiveState(() => ({
data: snapshot,
error: null,
isPending: false,
}));
}
function refreshFromCurrentClient(): void {
const generation = ++requestGeneration;
updateLiveState((current) => ({
...current,
error: null,
isPending: true,
}));
let server: ReturnType<typeof getPrimaryEnvironmentConnection>["client"]["server"];
try {
server = getPrimaryEnvironmentConnection().client.server;
} catch (error) {
if (generation !== requestGeneration) return;
updateLiveState((current) => ({
...current,
error: formatResourceTelemetryError(error),
isPending: false,
}));
return;
}
void server.getResourceTelemetry().then(
(snapshot) => {
if (generation !== requestGeneration) return;
applySnapshot(snapshot);
},
(error: unknown) => {
if (generation !== requestGeneration) return;
updateLiveState((current) => ({
...current,
error: formatResourceTelemetryError(error),
isPending: false,
}));
},
);
}
function attachResourceTelemetry(): void {
let client: ReturnType<typeof getPrimaryEnvironmentConnection>["client"];
try {
client = getPrimaryEnvironmentConnection().client;
} catch (error) {
activeClient = null;
unsubscribeTelemetry();
unsubscribeTelemetry = () => undefined;
updateLiveState((current) => ({
...current,
error: formatResourceTelemetryError(error),
isPending: false,
}));
return;
}
if (client === activeClient) {
return;
}
activeClient = client;
unsubscribeTelemetry();
refreshFromCurrentClient();
unsubscribeTelemetry = client.server.subscribeResourceTelemetry(applySnapshot, {
onResubscribe: refreshFromCurrentClient,
});
}
function retainResourceTelemetry(): () => void {
retainCount += 1;
if (retainCount === 1) {
unsubscribeConnections = subscribeEnvironmentConnections(() => {
activeClient = null;
attachResourceTelemetry();
});
attachResourceTelemetry();
}
return () => {
retainCount = Math.max(0, retainCount - 1);
if (retainCount !== 0) return;
requestGeneration += 1;
activeClient = null;
unsubscribeTelemetry();
unsubscribeTelemetry = () => undefined;
unsubscribeConnections();
unsubscribeConnections = () => undefined;
};
}
function formatHistoryKey(input: ResourceTelemetryHistoryInput): string {
return `${input.windowMs}${RESOURCE_TELEMETRY_HISTORY_INPUT_SEPARATOR}${input.bucketMs}`;
}
function parseHistoryKey(key: string): ResourceTelemetryHistoryInput {
const [windowMs = "0", bucketMs = "0"] = key.split(RESOURCE_TELEMETRY_HISTORY_INPUT_SEPARATOR);
return {
windowMs: Number(windowMs),
bucketMs: Number(bucketMs),
};
}
const resourceTelemetryHistoryAtom = Atom.family((key: string) => {
const input = parseHistoryKey(key);
return Atom.make(
Effect.promise(() => ensureLocalApi().server.getResourceTelemetryHistory(input)),
).pipe(
Atom.swr({
staleTime: RESOURCE_TELEMETRY_HISTORY_STALE_TIME_MS,
revalidateOnMount: true,
}),
Atom.setIdleTTL(RESOURCE_TELEMETRY_IDLE_TTL_MS),
Atom.withLabel(`resource-telemetry-history:${key}`),
);
});
export interface ResourceTelemetryState extends ResourceTelemetryLiveState {
readonly refresh: () => void;
readonly retry: () => Promise<ResourceTelemetrySnapshot>;
}
export interface ResourceTelemetryHistoryState {
readonly data: ResourceTelemetryHistory | null;
readonly error: string | null;
readonly isPending: boolean;
readonly refresh: () => void;
}
export function refreshResourceTelemetry(): void {
refreshFromCurrentClient();
}
export async function retryResourceTelemetry(): Promise<ResourceTelemetrySnapshot> {
const result = await ensureLocalApi().server.retryResourceTelemetry();
applySnapshot(result.snapshot);
return result.snapshot;
}
export function useResourceTelemetry(): ResourceTelemetryState {
useEffect(retainResourceTelemetry, []);
const state = useAtomValue(resourceTelemetryLiveAtom);
const refresh = useCallback(refreshResourceTelemetry, []);
const retry = useCallback(() => retryResourceTelemetry(), []);
return {
...state,
refresh,
retry,
};
}
export function useResourceTelemetryHistory(
input: ResourceTelemetryHistoryInput,
): ResourceTelemetryHistoryState {
const atom = resourceTelemetryHistoryAtom(formatHistoryKey(input));
const result = useAtomValue(atom);
const data = Option.getOrNull(AsyncResult.value(result));
const refresh = useCallback(() => {
appAtomRegistry.refresh(atom);
}, [atom]);
return {
data,
error:
result._tag === "Failure" ? formatResourceTelemetryError(Cause.squash(result.cause)) : null,
isPending: result.waiting,
refresh,
};
}
+12
View File
@@ -159,6 +159,18 @@ function createBrowserLocalApi(rpcClient?: WsRpcClient): LocalApi {
rpcClient
? rpcClient.server.getProcessResourceHistory(input)
: Promise.reject(unavailableLocalBackendError()),
getResourceTelemetry: () =>
rpcClient
? rpcClient.server.getResourceTelemetry()
: Promise.reject(unavailableLocalBackendError()),
getResourceTelemetryHistory: (input) =>
rpcClient
? rpcClient.server.getResourceTelemetryHistory(input)
: Promise.reject(unavailableLocalBackendError()),
retryResourceTelemetry: () =>
rpcClient
? rpcClient.server.retryResourceTelemetry()
: Promise.reject(unavailableLocalBackendError()),
signalProcess: (input) =>
rpcClient
? rpcClient.server.signalProcess(input)