Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
feat(charts): add downsampling and smoother rendering
rcourtmancfd9648d2d6b
diff --git a/frontend-modern/src/components/shared/HistoryChart.tsx b/frontend-modern/src/components/shared/HistoryChart.tsxindex 8c872c07e9..3f9e2822b1 100644--- a/frontend-modern/src/components/shared/HistoryChart.tsx+++ b/frontend-modern/src/components/shared/HistoryChart.tsx@@ -10,6 +10,8 @@ import { ChartsAPI, type ResourceType, type HistoryTimeRange, type AggregatedMetimport { hasFeature, loadLicenseStatus } from '@/stores/license';import { Portal } from 'solid-js/web';import { formatBytes } from '@/utils/format';+import { calculateOptimalPoints } from '@/utils/downsample';+interface HistoryChartProps {resourceType: ResourceType;@@ -22,6 +24,10 @@ interface HistoryChartProps {range?: HistoryTimeRange;onRangeChange?: (range: HistoryTimeRange) => void;hideSelector?: boolean;+ /** Strip outer card chrome (border/padding/shadow) and reduce min-height for inline embedding. */+ compact?: boolean;+ /** Suppress the built-in Pro lock overlay (caller handles it externally). */+ hideLock?: boolean;}export const HistoryChart: Component<HistoryChartProps> = (props) => {@@ -35,6 +41,10 @@ export const HistoryChart: Component<HistoryChartProps> = (props) => {const [source, setSource] = createSignal<'store' | 'memory' | 'live' | null>(null);const [maxPoints, setMaxPoints] = createSignal<number | null>(null);const [refreshTick, setRefreshTick] = createSignal(0);+ // Track if we have ever loaded data successfully - used to determine if we show loading spinner+ const [hasLoadedOnce, setHasLoadedOnce] = createSignal(false);+ // Track cursor X position for crosshair line (null when not hovering)+ const [cursorX, setCursorX] = createSignal<number | null>(null);const refreshIntervalMs = createMemo(() => {const r = range();@@ -92,28 +102,17 @@ export const HistoryChart: Component<HistoryChartProps> = (props) => {y: number;} | null>(null);- // Fetch data when range or resource changes- createEffect(async () => {- const r = range();- const type = props.resourceType;- const id = props.resourceId;- const metric = props.metric;- const locked = isLocked();- const pointsCap = maxPoints();- refreshTick();-- if (!id || !type) return;-- if (locked) {- setLoading(false);- setError(null);- setSource(null);- return;+ // Helper function to load data+ const loadData = async (r: HistoryTimeRange, type: ResourceType, id: string, metric: string, pointsCap: number | null, isBackgroundRefresh: boolean) => {+ // Only show loading spinner if this is NOT a background refresh and we haven't loaded once yet+ if (!isBackgroundRefresh && !hasLoadedOnce()) {+ setLoading(true);}-- setLoading(true);setError(null);- setSource(null);+ // Don't clear source during background refresh to avoid flashing UI changes+ if (!isBackgroundRefresh) {+ setSource(null);+ }try {const result = await ChartsAPI.getMetricsHistory({resourceType: type,@@ -131,13 +130,63 @@ export const HistoryChart: Component<HistoryChartProps> = (props) => {setData([]);setSource(result.source ?? 'store');}+ // Mark that we've successfully loaded data at least once+ if (!hasLoadedOnce()) {+ setHasLoadedOnce(true);+ }} catch (err) {console.error('Failed to fetch metrics history:', err);- setError('Failed to load history data');+ // Only show error if we don't have data already+ if (!hasLoadedOnce()) {+ setError('Failed to load history data');+ }setSource(null);} finally {setLoading(false);}+ };++ // Main data loading effect - responds to resource/range changes+ // This is NOT a background refresh, so show loading spinner on first load+ createEffect(async () => {+ const r = range();+ const type = props.resourceType;+ const id = props.resourceId;+ const metric = props.metric;+ const locked = isLocked();+ const pointsCap = maxPoints();++ if (!id || !type) return;++ if (locked) {+ setLoading(false);+ setError(null);+ setSource(null);+ return;+ }++ // Initial or user-triggered load (not background refresh)+ loadData(r, type, id, metric, pointsCap, false);+ });++ // Separate effect for background refresh - uses refreshTick only+ // This ensures background refreshes are silent (no loading spinner)+ createEffect(() => {+ const tick = refreshTick();+ // Only trigger background refresh after at least one tick (initial is 0)+ if (tick === 0) return;++ const r = range();+ const type = props.resourceType;+ const id = props.resourceId;+ const metric = props.metric;+ const locked = isLocked();+ const pointsCap = maxPoints();++ if (!id || !type || locked) return;++ // Background refresh - pass true to prevent loading spinner+ loadData(r, type, id, metric, pointsCap, true);});createEffect(() => {@@ -149,6 +198,7 @@ export const HistoryChart: Component<HistoryChartProps> = (props) => {onCleanup(() => window.clearInterval(timer));});+// Draw chartconst drawChart = () => {if (!canvasRef) return;@@ -160,16 +210,29 @@ export const HistoryChart: Component<HistoryChartProps> = (props) => {const w = canvas.parentElement?.clientWidth || 300;const h = props.height || 200;- // Handle device pixel ratio+ // Set canvas size ONLY if dimensions have changed+ // Resizing canvas clears its content and resets transforms, which causes flickeringconst dpr = window.devicePixelRatio || 1;- canvas.width = w * dpr;- canvas.height = h * dpr;- canvas.style.width = `${w}px`;- canvas.style.height = `${h}px`;- ctx.scale(dpr, dpr);+ const targetWidth = Math.round(w * dpr);+ const targetHeight = Math.round(h * dpr);++ const needsResize = canvas.width !== targetWidth || canvas.height !== targetHeight;++ if (needsResize) {+ canvas.width = targetWidth;+ canvas.height = targetHeight;+ canvas.style.width = `${w}px`;+ canvas.style.height = `${h}px`;+ }++ // Reset transform and apply DPR scale before drawing+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);++ // Clear canvas (if not already cleared by resize)+ if (!needsResize) {+ ctx.clearRect(0, 0, w, h);+ }- // Clear- ctx.clearRect(0, 0, w, h);// Colorsconst isDark = document.documentElement.classList.contains('dark');@@ -276,34 +339,85 @@ export const HistoryChart: Component<HistoryChartProps> = (props) => {ctx.fillText(formatTimeLabel(t), x, h - 2);}+ // Draw crosshair vertical line and point circle if cursor is hovering+ const cursor = cursorX();+ if (cursor !== null && cursor >= 40 && points.length > 0) {+ // Draw the vertical dashed line+ ctx.save();+ ctx.strokeStyle = isDark ? 'rgba(255, 255, 255, 0.4)' : 'rgba(0, 0, 0, 0.3)';+ ctx.lineWidth = 1;+ ctx.setLineDash([4, 4]); // Dotted line pattern+ ctx.beginPath();+ ctx.moveTo(cursor, 0);+ ctx.lineTo(cursor, h - 20); // Stop at x-axis labels area+ ctx.stroke();+ ctx.restore();++ // Calculate which point is nearest to the cursor X position+ const ratio = (cursor - 40) / (w - 40);+ const hoverTs = startTime + ratio * timeSpan;++ // Find the nearest point+ let closest = points[0];+ let minDiff = Math.abs(points[0].timestamp - hoverTs);+ for (const p of points) {+ const diff = Math.abs(p.timestamp - hoverTs);+ if (diff < minDiff) {+ minDiff = diff;+ closest = p;+ }+ }++ // Calculate the exact position+ const pointX = getX(closest.timestamp);+ const pointY = getY(closest.value);++ // Draw outer ring (white/dark background for contrast)+ ctx.beginPath();+ ctx.arc(pointX, pointY, 5, 0, Math.PI * 2);+ ctx.fillStyle = isDark ? '#1f2937' : '#ffffff';+ ctx.fill();++ // Draw colored circle+ ctx.beginPath();+ ctx.arc(pointX, pointY, 4, 0, Math.PI * 2);+ ctx.fillStyle = mainColor;+ ctx.fill();++ // Draw inner highlight+ ctx.beginPath();+ ctx.arc(pointX, pointY, 2, 0, Math.PI * 2);+ ctx.fillStyle = isDark ? 'rgba(255, 255, 255, 0.6)' : 'rgba(255, 255, 255, 0.8)';+ ctx.fill();+ }++// Min/Max envelope (optional, for pro feel?)// Let's keep it clean for now, maybe add later.};// ReactivitycreateEffect(() => {+ cursorX(); // Track cursor position for crosshair redrawdrawChart();});+// Resize observercreateEffect(() => {if (!containerRef) return;- const computeMaxPoints = (width: number) => {- const safeWidth = Math.max(120, Math.floor(width));- const dpr = window.devicePixelRatio || 1;- const points = Math.round(safeWidth * dpr);- return Math.min(1200, Math.max(180, points));- };const updateMaxPoints = () => {const width = containerRef?.clientWidth || 0;if (width <= 0) return;- const next = computeMaxPoints(width);+ // Use optimized point calculation: ~1 point per 2 pixels+ const next = calculateOptimalPoints(width, 'history');if (next !== maxPoints()) {setMaxPoints(next);}};+const resizeObserver = new ResizeObserver(() => {updateMaxPoints();drawChart();@@ -328,7 +442,15 @@ export const HistoryChart: Component<HistoryChartProps> = (props) => {// Inverse getX: x = 40 + ratio * (w-40)// ratio = (x - 40) / (w - 40)- if (x < 40) return;+ if (x < 40) {+ setCursorX(null);+ setHoveredPoint(null);+ return;+ }++ // Update cursor position for crosshair line+ setCursorX(x);+const ratio = (x - 40) / (w - 40);const hoverTs = startTime + ratio * timeSpan;@@ -358,13 +480,17 @@ export const HistoryChart: Component<HistoryChartProps> = (props) => {});};- const handleMouseLeave = () => setHoveredPoint(null);+ const handleMouseLeave = () => {+ setHoveredPoint(null);+ setCursorX(null);+ };+const ranges: HistoryTimeRange[] = ['24h', '7d', '30d', '90d'];return (- <div class="flex flex-col h-full bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-4">- <div class="flex items-center justify-between mb-4">+ <div class={`flex flex-col h-full ${props.compact ? '' : 'bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-4'}`}>+ <div class={`flex items-center justify-between ${props.compact ? 'mb-2' : 'mb-4'}`}><div class="flex items-center gap-2"><span class="text-sm font-medium text-gray-700 dark:text-gray-200">{props.label || 'History'}</span><Show when={props.unit}>@@ -372,11 +498,10 @@ export const HistoryChart: Component<HistoryChartProps> = (props) => {</Show><Show when={source() && source() !== 'store'}><span- class={`text-[10px] font-semibold px-2 py-0.5 rounded-full uppercase tracking-wide ${- source() === 'live'- ? 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300'- : 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300'- }`}+ class={`text-[10px] font-semibold px-2 py-0.5 rounded-full uppercase tracking-wide ${source() === 'live'+ ? 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300'+ : 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300'+ }`}title={source() === 'live' ? 'Live sample shown because history is not available yet.' : 'In-memory buffer shown while history is warming up.'}>{source() === 'live' ? 'Live' : 'Memory'}@@ -402,7 +527,7 @@ export const HistoryChart: Component<HistoryChartProps> = (props) => {</Show></div>- <div class="relative flex-1 min-h-[200px] w-full" ref={containerRef}>+ <div class={`relative flex-1 w-full ${props.compact ? 'min-h-[120px]' : 'min-h-[200px]'}`} ref={containerRef}><canvasref={canvasRef}class="block w-full h-full cursor-crosshair"@@ -443,7 +568,7 @@ export const HistoryChart: Component<HistoryChartProps> = (props) => {</Show>{/* Pro Lock Overlay */}- <Show when={isLocked()}>+ <Show when={isLocked() && !props.hideLock}><div class="absolute inset-0 z-10 flex flex-col items-center justify-center backdrop-blur-sm bg-white/60 dark:bg-gray-900/60 rounded-lg"><div class="bg-gradient-to-br from-indigo-500 to-purple-600 rounded-full p-3 shadow-lg mb-3"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">diff --git a/frontend-modern/src/components/shared/Sparkline.tsx b/frontend-modern/src/components/shared/Sparkline.tsxindex 6fc33948b4..61ba1958cd 100644--- a/frontend-modern/src/components/shared/Sparkline.tsx+++ b/frontend-modern/src/components/shared/Sparkline.tsx@@ -5,10 +5,12 @@* Optimized for rendering many sparklines simultaneously in tables.*/-import { onCleanup, createEffect, createSignal, Component, Show } from 'solid-js';+import { onCleanup, createEffect, createSignal, Component, Show, createMemo } from 'solid-js';import { Portal } from 'solid-js/web';import type { MetricSnapshot } from '@/stores/metricsHistory';import { scheduleSparkline } from '@/utils/canvasRenderQueue';+import { downsampleMetricSnapshots, calculateOptimalPoints } from '@/utils/downsample';+interface SparklineProps {data: MetricSnapshot[];@@ -43,6 +45,23 @@ export const Sparkline: Component<SparklineProps> = (props) => {};const height = () => props.height || 16;+ // Downsample data using LTTB algorithm for optimal rendering+ // This reduces ~2880 points to ~60-80 points (1 per 1.5 pixels)+ const downsampledData = createMemo(() => {+ const data = props.data;+ if (!data || data.length === 0) return data;++ const w = width();+ const optimalPoints = calculateOptimalPoints(w, 'sparkline');++ // Only downsample if we have significantly more points than needed+ if (data.length <= optimalPoints * 1.5) {+ return data;+ }++ return downsampleMetricSnapshots(data, props.metric, optimalPoints);+ });+// Default thresholds based on metric typeconst getDefaultThresholds = () => {switch (props.metric) {@@ -59,6 +78,7 @@ export const Sparkline: Component<SparklineProps> = (props) => {const thresholds = () => props.thresholds || getDefaultThresholds();+// Get color based on latest value and thresholdsconst getColor = (value: number): string => {if (props.color) return props.color;@@ -86,23 +106,38 @@ export const Sparkline: Component<SparklineProps> = (props) => {const ctx = canvas.getContext('2d');if (!ctx) return;- const data = props.data;+ // Use downsampled data for efficient rendering+ const data = downsampledData();const w = width();const h = height();const metric = props.metric;- // Set canvas size (accounting for device pixel ratio for sharp rendering)++ // Set canvas size ONLY if dimensions have changed+ // Resizing canvas clears its content and resets transforms, which causes flickeringconst dpr = window.devicePixelRatio || 1;- canvas.width = w * dpr;- canvas.height = h * dpr;- // Always set explicit width style to prevent canvas from expanding beyond container- // When width=0, we use the calculated container width- canvas.style.width = `${w}px`;- canvas.style.height = `${h}px`;- ctx.scale(dpr, dpr);+ const targetWidth = Math.round(w * dpr);+ const targetHeight = Math.round(h * dpr);++ const needsResize = canvas.width !== targetWidth || canvas.height !== targetHeight;++ if (needsResize) {+ // Resize clears canvas and resets transform automatically+ canvas.width = targetWidth;+ canvas.height = targetHeight;+ canvas.style.width = `${w}px`;+ canvas.style.height = `${h}px`;+ }++ // Reset transform and apply DPR scale before drawing+ // This must be done on every draw since transforms can compound+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);++ // Clear canvas (if not already cleared by resize)+ if (!needsResize) {+ ctx.clearRect(0, 0, w, h);+ }- // Clear canvas- ctx.clearRect(0, 0, w, h);// Detect dark mode for reference line colorconst isDark = document.documentElement.classList.contains('dark');@@ -187,11 +222,13 @@ export const Sparkline: Component<SparklineProps> = (props) => {// Redraw when data or dimensions changecreateEffect(() => {- void props.data;+ // Track downsampled data for efficient re-rendering+ void downsampledData();void props.metric;void width();void height();+// Unregister previous draw callback if it existsif (unregister) {unregister();@@ -209,13 +246,13 @@ export const Sparkline: Component<SparklineProps> = (props) => {// Handle mouse move to find nearest pointconst handleMouseMove = (e: MouseEvent) => {- if (!canvasRef || !props.data || props.data.length === 0) return;+ const data = downsampledData();+ if (!canvasRef || !data || data.length === 0) return;const rect = canvasRef.getBoundingClientRect();const mouseX = e.clientX - rect.left;const w = width();- const data = props.data;const values = data.map(d => d[props.metric]);const xStep = w / Math.max(values.length - 1, 1);@@ -235,6 +272,7 @@ export const Sparkline: Component<SparklineProps> = (props) => {});};+const handleMouseLeave = () => {setHoveredPoint(null);};diff --git a/frontend-modern/src/components/shared/UnifiedHistoryChart.tsx b/frontend-modern/src/components/shared/UnifiedHistoryChart.tsxindex b83462cc0c..17bb07741a 100644--- a/frontend-modern/src/components/shared/UnifiedHistoryChart.tsx+++ b/frontend-modern/src/components/shared/UnifiedHistoryChart.tsx@@ -4,6 +4,8 @@ import { AggregatedMetricPoint, ChartsAPI, HistoryTimeRange, ResourceType } fromimport { formatBytes } from '@/utils/format';import { hasFeature, loadLicenseStatus } from '@/stores/license';import { logger } from '@/utils/logger';+import { calculateOptimalPoints } from '@/utils/downsample';+interface UnifiedHistoryChartProps {resourceType: ResourceType;@@ -35,6 +37,13 @@ export const UnifiedHistoryChart: Component<UnifiedHistoryChartProps> = (props)const [maxPoints, setMaxPoints] = createSignal<number | null>(null);const [group, setGroup] = createSignal<'utilization' | 'io'>('utilization');const [refreshTick, setRefreshTick] = createSignal(0);+ // Track if we have ever loaded data successfully - used to determine if we show loading spinner+ const [hasLoadedOnce, setHasLoadedOnce] = createSignal(false);+ // Track cursor X position for crosshair line (null when not hovering)+ const [cursorX, setCursorX] = createSignal<number | null>(null);+ // Track the last successfully fetched params to avoid redundant fetches on prop reference changes+ let lastFetchParams: { resourceType: string; resourceId: string; range: string; maxPoints: number | null } | null = null;+const metricGroups: Record<'utilization' | 'io', Record<string, { label: string; color: string; unit: string }>> = {utilization: {@@ -66,10 +75,17 @@ export const UnifiedHistoryChart: Component<UnifiedHistoryChartProps> = (props)}});- const loadData = async (resourceType: ResourceType, resourceId: string, rangeValue: HistoryTimeRange, pointsCap?: number | null) => {- setLoading(true);+ const loadData = async (resourceType: ResourceType, resourceId: string, rangeValue: HistoryTimeRange, pointsCap?: number | null, isBackgroundRefresh = false) => {+ // Only show loading spinner if this is NOT a background refresh and we haven't loaded once yet+ // This prevents flickering when data refreshes in the background+ if (!isBackgroundRefresh && !hasLoadedOnce()) {+ setLoading(true);+ }setError(null);- setSource(null);+ // Don't clear source during background refresh to avoid flashing UI changes+ if (!isBackgroundRefresh) {+ setSource(null);+ }try {// Fetch all metrics for the resourceconst response = await ChartsAPI.getMetricsHistory({@@ -87,15 +103,25 @@ export const UnifiedHistoryChart: Component<UnifiedHistoryChartProps> = (props)setMetricsData({ [response.metric]: response.points });setSource(response.source ?? 'store');}+ // Mark that we've successfully loaded data at least once+ if (!hasLoadedOnce()) {+ setHasLoadedOnce(true);+ }+ // Update the last fetch params+ lastFetchParams = { resourceType, resourceId, range: rangeValue, maxPoints: pointsCap ?? null };} catch (err: any) {console.error('[UnifiedHistoryChart] Failed to load history:', err);- setError('Failed to load history data');+ // Only show error if we don't have data already+ if (!hasLoadedOnce()) {+ setError('Failed to load history data');+ }setSource(null);} finally {setLoading(false);}};+onMount(() => {loadLicenseStatus();});@@ -104,13 +130,14 @@ export const UnifiedHistoryChart: Component<UnifiedHistoryChartProps> = (props)if (props.range) setRange(props.range);});+ // Main data loading effect - responds to resource/range changes+ // This is NOT a background refresh, so show loading spinner on first loadcreateEffect(() => {const resourceType = props.resourceType;const resourceId = props.resourceId;const rangeValue = props.range ?? range();const locked = isLocked();const pointsCap = maxPoints();- refreshTick();if (!resourceType || !resourceId) return;if (locked) {@@ -118,7 +145,38 @@ export const UnifiedHistoryChart: Component<UnifiedHistoryChartProps> = (props)setError(null);return;}- loadData(resourceType, resourceId, rangeValue, pointsCap);++ // Check if we need to fetch - skip if params haven't actually changed+ // This prevents redundant fetches when props change reference but not value+ const paramsChanged = !lastFetchParams ||+ lastFetchParams.resourceType !== resourceType ||+ lastFetchParams.resourceId !== resourceId ||+ lastFetchParams.range !== rangeValue ||+ lastFetchParams.maxPoints !== pointsCap;++ if (paramsChanged) {+ // This is an initial or user-triggered load (not background refresh)+ loadData(resourceType, resourceId, rangeValue, pointsCap, false);+ }+ });++ // Separate effect for background refresh - uses refreshTick only+ // This ensures background refreshes are silent (no loading spinner)+ createEffect(() => {+ const tick = refreshTick();+ // Only trigger background refresh after at least one tick (initial is 0)+ if (tick === 0) return;++ const resourceType = props.resourceType;+ const resourceId = props.resourceId;+ const rangeValue = props.range ?? range();+ const locked = isLocked();+ const pointsCap = maxPoints();++ if (!resourceType || !resourceId || locked) return;++ // Background refresh - pass true to prevent loading spinner+ loadData(resourceType, resourceId, rangeValue, pointsCap, true);});createEffect(() => {@@ -130,6 +188,7 @@ export const UnifiedHistoryChart: Component<UnifiedHistoryChartProps> = (props)onCleanup(() => window.clearInterval(timer));});+const drawChart = () => {if (!canvasRef) return;const ctx = canvasRef.getContext('2d');@@ -140,14 +199,29 @@ export const UnifiedHistoryChart: Component<UnifiedHistoryChartProps> = (props)const activeGroup = group();const metricConfigs = metricGroups[activeGroup];+ // Set canvas size ONLY if dimensions have changed+ // Resizing canvas clears its content and resets transforms, which causes flickeringconst dpr = window.devicePixelRatio || 1;- canvasRef.width = w * dpr;- canvasRef.height = h * dpr;- canvasRef.style.width = `${w}px`;- canvasRef.style.height = `${h}px`;- ctx.scale(dpr, dpr);+ const targetWidth = Math.round(w * dpr);+ const targetHeight = Math.round(h * dpr);++ const needsResize = canvasRef.width !== targetWidth || canvasRef.height !== targetHeight;++ if (needsResize) {+ canvasRef.width = targetWidth;+ canvasRef.height = targetHeight;+ canvasRef.style.width = `${w}px`;+ canvasRef.style.height = `${h}px`;+ }++ // Reset transform and apply DPR scale before drawing+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);++ // Clear canvas (if not already cleared by resize)+ if (!needsResize) {+ ctx.clearRect(0, 0, w, h);+ }- ctx.clearRect(0, 0, w, h);const isDark = document.documentElement.classList.contains('dark');const gridColor = isDark ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.05)';@@ -272,31 +346,99 @@ export const UnifiedHistoryChart: Component<UnifiedHistoryChartProps> = (props)ctx.fillText(`${formatBytes(value)}/s`, 35, y);});}++ // Draw crosshair vertical line and point circles if cursor is hovering+ const cursor = cursorX();+ if (cursor !== null && cursor >= 40) {+ // Draw the vertical dashed line+ ctx.save();+ ctx.strokeStyle = isDark ? 'rgba(255, 255, 255, 0.4)' : 'rgba(0, 0, 0, 0.3)';+ ctx.lineWidth = 1;+ ctx.setLineDash([4, 4]); // Dotted line pattern+ ctx.beginPath();+ ctx.moveTo(cursor, 0);+ ctx.lineTo(cursor, h - 20); // Stop at x-axis labels area+ ctx.stroke();+ ctx.restore();++ // Draw point circles at each metric's intersection with the crosshair+ Object.entries(metricConfigs).forEach(([metricId, config]) => {+ const points = dataMap[metricId];+ if (!points || points.length === 0) return;++ const startTime = points[0].timestamp;+ const endTime = points[points.length - 1].timestamp;+ const timeSpan = endTime - startTime || 1;++ // Calculate which point is nearest to the cursor X position+ const ratio = (cursor - 40) / (w - 40);+ const hoverTs = startTime + ratio * timeSpan;++ // Find the nearest point+ let closest = points[0];+ let minDiff = Math.abs(points[0].timestamp - hoverTs);+ for (const p of points) {+ const diff = Math.abs(p.timestamp - hoverTs);+ if (diff < minDiff) {+ minDiff = diff;+ closest = p;+ }+ }++ // Calculate the exact position+ const getX = (ts: number) => 40 + ((ts - startTime) / timeSpan) * (w - 40);+ const getY = (val: number) => {+ const clamped = Math.max(0, Math.min(val, maxAxisValue));+ return h - 20 - (clamped / maxAxisValue) * (h - 40);+ };++ const pointX = getX(closest.timestamp);+ const pointY = getY(closest.value);++ // Draw outer ring (white/dark background for contrast)+ ctx.beginPath();+ ctx.arc(pointX, pointY, 5, 0, Math.PI * 2);+ ctx.fillStyle = isDark ? '#1f2937' : '#ffffff';+ ctx.fill();++ // Draw colored circle+ ctx.beginPath();+ ctx.arc(pointX, pointY, 4, 0, Math.PI * 2);+ ctx.fillStyle = config.color;+ ctx.fill();++ // Draw inner highlight+ ctx.beginPath();+ ctx.arc(pointX, pointY, 2, 0, Math.PI * 2);+ ctx.fillStyle = isDark ? 'rgba(255, 255, 255, 0.6)' : 'rgba(255, 255, 255, 0.8)';+ ctx.fill();+ });+ }};++createEffect(() => {metricsData();+ cursorX(); // Track cursor position for crosshair redrawdrawChart();});+createEffect(() => {if (!containerRef) return;- const computeMaxPoints = (width: number) => {- const safeWidth = Math.max(120, Math.floor(width));- const dpr = window.devicePixelRatio || 1;- const points = Math.round(safeWidth * dpr);- return Math.min(1200, Math.max(180, points));- };const updateMaxPoints = () => {const width = containerRef?.clientWidth || 0;if (width <= 0) return;- const next = computeMaxPoints(width);+ // Use optimized point calculation: ~1 point per 2 pixels+ const next = calculateOptimalPoints(width, 'history');if (next !== maxPoints()) {setMaxPoints(next);}};+const ro = new ResizeObserver(() => {updateMaxPoints();drawChart();@@ -312,9 +454,13 @@ export const UnifiedHistoryChart: Component<UnifiedHistoryChartProps> = (props)const x = e.clientX - rect.left;if (x < 40) {setHoveredPoint(null);+ setCursorX(null);return;}+ // Update cursor position for crosshair line+ setCursorX(x);+const dataMap = metricsData();const activeGroup = group();const metricConfigs = metricGroups[activeGroup];@@ -364,6 +510,12 @@ export const UnifiedHistoryChart: Component<UnifiedHistoryChartProps> = (props)setHoveredPoint(hoverInfo);};+ const handleMouseLeave = () => {+ setHoveredPoint(null);+ setCursorX(null);+ };++const updateRange = (r: HistoryTimeRange) => {setRange(r);if (props.onRangeChange) props.onRangeChange(r);@@ -376,11 +528,10 @@ export const UnifiedHistoryChart: Component<UnifiedHistoryChartProps> = (props)<span class="text-sm font-bold text-gray-700 dark:text-gray-200">{props.label || 'Unified History'}</span><Show when={source() && source() !== 'store'}><span- class={`text-[10px] font-semibold px-2 py-0.5 rounded-full uppercase tracking-wide ${- source() === 'live'- ? 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300'- : 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300'- }`}+ class={`text-[10px] font-semibold px-2 py-0.5 rounded-full uppercase tracking-wide ${source() === 'live'+ ? 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300'+ : 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300'+ }`}title={source() === 'live' ? 'Live sample shown because history is not available yet.' : 'In-memory buffer shown while history is warming up.'}>{source() === 'live' ? 'Live' : 'Memory'}@@ -436,7 +587,8 @@ export const UnifiedHistoryChart: Component<UnifiedHistoryChartProps> = (props)ref={canvasRef}class="block w-full h-full cursor-crosshair"onMouseMove={handleMouseMove}- onMouseLeave={() => setHoveredPoint(null)}+ onMouseLeave={handleMouseLeave}+/><Show when={loading()}>diff --git a/frontend-modern/src/utils/__tests__/downsample.test.ts b/frontend-modern/src/utils/__tests__/downsample.test.tsnew file mode 100644index 0000000000..7d56b25ac1--- /dev/null+++ b/frontend-modern/src/utils/__tests__/downsample.test.ts@@ -0,0 +1,144 @@+import { describe, it, expect } from 'vitest';+import {+ downsampleLTTB,+ downsampleMetricSnapshots,+ calculateOptimalPoints,+ TimeSeriesPoint+} from '../downsample';++describe('downsampleLTTB', () => {+ it('returns original data when length is less than or equal to target', () => {+ const data: TimeSeriesPoint[] = [+ { timestamp: 1, value: 10 },+ { timestamp: 2, value: 20 },+ { timestamp: 3, value: 30 },+ ];++ const result = downsampleLTTB(data, 5);+ expect(result).toEqual(data);+ });++ it('returns original data when target is less than 3', () => {+ const data: TimeSeriesPoint[] = [+ { timestamp: 1, value: 10 },+ { timestamp: 2, value: 20 },+ { timestamp: 3, value: 30 },+ { timestamp: 4, value: 40 },+ ];++ const result = downsampleLTTB(data, 2);+ expect(result).toEqual(data);+ });++ it('always keeps first and last points', () => {+ const data: TimeSeriesPoint[] = [];+ for (let i = 0; i < 100; i++) {+ data.push({ timestamp: i, value: Math.random() * 100 });+ }++ const result = downsampleLTTB(data, 10);++ expect(result[0]).toEqual(data[0]);+ expect(result[result.length - 1]).toEqual(data[data.length - 1]);+ });++ it('returns the correct number of points', () => {+ const data: TimeSeriesPoint[] = [];+ for (let i = 0; i < 1000; i++) {+ data.push({ timestamp: i * 1000, value: Math.sin(i / 10) * 50 + 50 });+ }++ const result = downsampleLTTB(data, 100);++ expect(result.length).toBe(100);+ });++ it('preserves peaks and valleys', () => {+ // Create data with a clear peak at index 50+ const data: TimeSeriesPoint[] = [];+ for (let i = 0; i < 100; i++) {+ const value = i === 50 ? 100 : 10; // spike at index 50+ data.push({ timestamp: i * 1000, value });+ }++ const result = downsampleLTTB(data, 10);++ // The peak should be preserved+ const hasPeak = result.some(p => p.value === 100);+ expect(hasPeak).toBe(true);+ });+});++describe('downsampleMetricSnapshots', () => {+ it('downsamples based on selected metric', () => {+ const data = [];+ for (let i = 0; i < 100; i++) {+ data.push({+ timestamp: i * 1000,+ cpu: i % 2 === 0 ? 80 : 20, // oscillating+ memory: 50,+ disk: 30,+ });+ }++ const result = downsampleMetricSnapshots(data, 'cpu', 20);++ expect(result.length).toBe(20);+ // All points should be valid metric snapshots+ result.forEach(p => {+ expect(p).toHaveProperty('timestamp');+ expect(p).toHaveProperty('cpu');+ expect(p).toHaveProperty('memory');+ expect(p).toHaveProperty('disk');+ });+ });++ it('returns original data when length is less than target', () => {+ const data = [+ { timestamp: 1, cpu: 10, memory: 20, disk: 30 },+ { timestamp: 2, cpu: 20, memory: 25, disk: 35 },+ ];++ const result = downsampleMetricSnapshots(data, 'cpu', 10);++ expect(result).toEqual(data);+ });+});++describe('calculateOptimalPoints', () => {+ describe('sparkline mode', () => {+ it('returns ~1 point per 1.5 pixels', () => {+ const result = calculateOptimalPoints(120, 'sparkline');+ // 120px / 1.5 = 80 points+ expect(result).toBe(80);+ });++ it('clamps to minimum of 20 points', () => {+ const result = calculateOptimalPoints(10, 'sparkline');+ expect(result).toBe(20);+ });++ it('clamps to maximum of 100 points', () => {+ const result = calculateOptimalPoints(500, 'sparkline');+ expect(result).toBe(100);+ });+ });++ describe('history mode', () => {+ it('returns ~1 point per 2 pixels', () => {+ const result = calculateOptimalPoints(400, 'history');+ // 400px / 2 = 200 points+ expect(result).toBe(200);+ });++ it('clamps to minimum of 60 points', () => {+ const result = calculateOptimalPoints(50, 'history');+ expect(result).toBe(60);+ });++ it('clamps to maximum of 600 points', () => {+ const result = calculateOptimalPoints(2000, 'history');+ expect(result).toBe(600);+ });+ });+});diff --git a/frontend-modern/src/utils/downsample.ts b/frontend-modern/src/utils/downsample.tsnew file mode 100644index 0000000000..e1632feef7--- /dev/null+++ b/frontend-modern/src/utils/downsample.ts@@ -0,0 +1,174 @@+/**+ * LTTB (Largest Triangle Three Buckets) Downsampling Algorithm+ *+ * This algorithm reduces the number of data points while preserving the visual+ * characteristics of the time-series data. It's the gold standard for chart+ * downsampling because it keeps peaks, valleys, and significant changes.+ *+ * Reference: Sveinn Steinarsson's 2013 thesis+ * "Downsampling Time Series for Visual Representation"+ */++export interface TimeSeriesPoint {+ timestamp: number;+ value: number;+ // Optional: preserve additional data+ min?: number;+ max?: number;+}++/**+ * Downsample time-series data using the LTTB algorithm+ *+ * @param data - Array of data points with timestamp and value+ * @param targetPoints - Desired number of output points+ * @returns Downsampled array preserving visual characteristics+ */+export function downsampleLTTB<T extends TimeSeriesPoint>(+ data: T[],+ targetPoints: number+): T[] {+ // If data is already small enough, return as-is+ if (data.length <= targetPoints || targetPoints < 3) {+ return data;+ }++ const result: T[] = [];++ // Always keep the first point+ result.push(data[0]);++ // Calculate bucket size (excluding first and last points)+ const bucketSize = (data.length - 2) / (targetPoints - 2);++ let lastSelectedIndex = 0;++ for (let i = 0; i < targetPoints - 2; i++) {+ // Calculate bucket boundaries+ const bucketStart = Math.floor((i + 0) * bucketSize) + 1;+ const bucketEnd = Math.floor((i + 1) * bucketSize) + 1;++ // Calculate the average point of the next bucket (for triangle calculation)+ const nextBucketStart = Math.floor((i + 1) * bucketSize) + 1;+ const nextBucketEnd = Math.min(+ Math.floor((i + 2) * bucketSize) + 1,+ data.length - 1+ );++ let avgX = 0;+ let avgY = 0;+ let avgCount = 0;++ for (let j = nextBucketStart; j < nextBucketEnd; j++) {+ avgX += data[j].timestamp;+ avgY += data[j].value;+ avgCount++;+ }++ if (avgCount > 0) {+ avgX /= avgCount;+ avgY /= avgCount;+ }++ // Find the point in the current bucket that creates the largest triangle+ const pointA = data[lastSelectedIndex];+ let maxArea = -1;+ let maxAreaIndex = bucketStart;++ for (let j = bucketStart; j < bucketEnd && j < data.length - 1; j++) {+ const pointB = data[j];++ // Calculate triangle area using the cross product formula+ // Area = 0.5 * |x1(y2 - y3) + x2(y3 - y1) + x3(y1 - y2)|+ const area = Math.abs(+ (pointA.timestamp - avgX) * (pointB.value - pointA.value) -+ (pointA.timestamp - pointB.timestamp) * (avgY - pointA.value)+ );++ if (area > maxArea) {+ maxArea = area;+ maxAreaIndex = j;+ }+ }++ result.push(data[maxAreaIndex]);+ lastSelectedIndex = maxAreaIndex;+ }++ // Always keep the last point+ result.push(data[data.length - 1]);++ return result;+}++/**+ * Downsample metric snapshots (for Sparkline component)+ * Works with the MetricSnapshot interface from metricsHistory+ */+export interface MetricSnapshotLike {+ timestamp: number;+ cpu: number;+ memory: number;+ disk: number;+}++/**+ * Downsample metric snapshots for a specific metric+ *+ * @param data - Array of MetricSnapshot data+ * @param metric - Which metric to use for LTTB selection ('cpu', 'memory', 'disk')+ * @param targetPoints - Desired number of output points+ * @returns Downsampled array+ */+export function downsampleMetricSnapshots<T extends MetricSnapshotLike>(+ data: T[],+ metric: 'cpu' | 'memory' | 'disk',+ targetPoints: number+): T[] {+ if (data.length <= targetPoints || targetPoints < 3) {+ return data;+ }++ // Convert to TimeSeriesPoint format for LTTB+ const points: (TimeSeriesPoint & { originalIndex: number })[] = data.map((d, i) => ({+ timestamp: d.timestamp,+ value: d[metric],+ originalIndex: i+ }));++ // Run LTTB+ const downsampled = downsampleLTTB(points, targetPoints);++ // Return original data at selected indices+ return downsampled.map(p => data[p.originalIndex]);+}++/**+ * Calculate optimal number of points for a given pixel width+ *+ * Best practices:+ * - For sparklines: ~1 point per 2 pixels (max ~80 points for small sparklines)+ * - For larger charts: ~1 point per 2-3 pixels+ * - Never more than width/2 points (overplotting provides no visual benefit)+ *+ * @param widthPx - Width of the chart in CSS pixels+ * @param chartType - Type of chart ('sparkline' | 'history')+ * @returns Optimal number of data points+ */+export function calculateOptimalPoints(+ widthPx: number,+ chartType: 'sparkline' | 'history' = 'history'+): number {+ if (chartType === 'sparkline') {+ // Sparklines are tiny - 1 point per 1.5-2 pixels is plenty+ // Min 20 points to show a trend, max 100 for small sparklines+ const points = Math.floor(widthPx / 1.5);+ return Math.min(100, Math.max(20, points));+ }++ // History charts - 1 point per 2 pixels is optimal+ // This provides smooth curves without overplotting+ // Min 60 points for basic trends, max 600 for very wide screens+ const points = Math.floor(widthPx / 2);+ return Math.min(600, Math.max(60, points));+}