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
Reduce demo dashboard chart churn
rcourtmand0648b07ae87
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex 29f30e389b..55c2732f8b 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -9,7 +9,7 @@"contract_file": "docs/release-control/v6/internal/subsystems/performance-and-scalability.md","status_file": "docs/release-control/v6/internal/status.json","registry_file": "docs/release-control/v6/internal/subsystems/registry.json",- "dependency_subsystem_ids": ["api-contracts", "frontend-primitives"]+ "dependency_subsystem_ids": ["api-contracts", "frontend-primitives", "unified-resources"]}```@@ -119,6 +119,11 @@ regression protection.97. `frontend-modern/src/components/Infrastructure/InfrastructureSummary.tsx`98. `frontend-modern/src/components/Infrastructure/useInfrastructureSummaryState.ts`99. `frontend-modern/src/components/Infrastructure/infrastructureSummaryModel.ts`+100. `frontend-modern/src/hooks/useDashboardTrends.ts`+101. `frontend-modern/src/hooks/__tests__/useDashboardTrends.test.ts`+102. `frontend-modern/src/components/Storage/DashboardStoragePanel.tsx`+103. `frontend-modern/src/components/Storage/StorageSummary.tsx`+104. `frontend-modern/src/utils/storageSummaryCache.ts`## Shared Boundaries@@ -193,6 +198,7 @@ regression protection.chart-transport hot paths, fold summary-card caching into commercialcallback behavior, or reuse those public auth endpoints as a justificationfor relaxing the protected history payload budgets that belong elsewhere.+30. Keep dashboard summary-chart fetches scope-owned rather than pagination-owned: `frontend-modern/src/hooks/useDashboardTrends.ts` must hydrate infrastructure and storage summaries once per org/range scope from the canonical summary caches and recompute card presentation locally as additional resource pages arrive, rather than refetching the infrastructure-summary transport in `frontend-modern/src/components/Infrastructure/useInfrastructureSummaryState.ts` or the storage-summary transport in `frontend-modern/src/utils/storageSummaryCache.ts` for every resource-id expansion on the same dashboard load.## Forbidden Paths@@ -258,6 +264,14 @@ chart.Infrastructure cluster-header hover now belongs to that same bounded hot path:hovering a grouped infrastructure header must scope the top cards to thatcluster's unified-resource members through the shared group/entity interaction+That same hot path now also owns dashboard freshness discipline. Supported+unified-resource dashboard reads may hydrate from REST for first paint, but+once websocket `state.resources` is available they must consume that canonical+live snapshot directly instead of turning each websocket update into a second+REST fetch. Dashboard trend loading must also key off stable target identity+and selected range only; reconciled resource snapshots that do not change the+effective target set must not trigger duplicate infrastructure or storage+chart requests.contract instead of inventing an infrastructure-local summary filter branch.For shared line charts on that hot path, the shared sparkline primitive mayisolate the selected series inside the existing render budget, but thatdiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex a27aaf35b1..a1b0c98967 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -55,6 +55,8 @@ querying, and the operator-facing storage health presentation layer.28. `frontend-modern/src/utils/recoverySummaryPresentation.ts`29. `frontend-modern/src/utils/recoveryTablePresentation.ts`30. `frontend-modern/src/utils/textPresentation.ts`+31. `frontend-modern/src/components/Storage/StorageSummary.tsx`+32. `frontend-modern/src/utils/storageSummaryCache.ts`## Shared Boundaries@@ -204,6 +206,14 @@ querying, and the operator-facing storage health presentation layer.runtime as populated mock inventory, but they must not expose`demo_fixtures`, billing identity, or alternate entitlement semantics asrecovery-local transport or operator-facing storage metadata.+37. Keep dashboard storage summary fetches scope-owned on the shared storage+ summary cache. `frontend-modern/src/components/Storage/StorageSummary.tsx`,+ `frontend-modern/src/utils/storageSummaryCache.ts`, and+ `frontend-modern/src/pages/Dashboard.tsx` may reuse cached org/range+ storage summaries for first paint, but they must not refetch+ `/api/storage-charts` once per additional dashboard resource page or invent+ a dashboard-only storage summary transport path outside the canonical cache+ owner.## Forbidden Pathsdiff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex 015dd727cb..ecdaa15a4d 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -146,6 +146,12 @@ assembly branch.6. Add canonical governed name-resolution or policy-aware resource lookup behavior through `internal/unifiedresources/resolve.go` and `internal/unifiedresources/resolve_context.go`7. Add or change resource drawer timeline/facet presentation through `frontend-modern/src/components/Infrastructure/ResourceDetailDrawer.tsx`, `frontend-modern/src/components/Infrastructure/ResourceDetailDrawerOverviewTab.tsx`, `frontend-modern/src/components/Infrastructure/ResourceDetailDrawerDebugTab.tsx`, `frontend-modern/src/components/Infrastructure/useResourceDetailDrawerState.ts`, `frontend-modern/src/components/Infrastructure/ResourceFacetSummary.tsx`, `frontend-modern/src/components/Infrastructure/resourceDetailMappers.ts`, and the governed `internal/api/resources.go` facet/timeline contract together8. Add or change discovery-support runtime under the resource drawer through `frontend-modern/src/components/Discovery/DiscoveryTab.tsx` for shell/presentation ownership and `frontend-modern/src/components/Discovery/useDiscoveryTabState.ts` for fetch, websocket-progress, and notes-mutation ownership+9. Keep dashboard and infrastructure freshness on the canonical unified-resource+ ownership path. `frontend-modern/src/hooks/useUnifiedResources.ts` may use+ REST for initial hydration and unsupported filtered queries, but supported+ snapshot freshness must come from websocket `state.resources` instead of+ layering confirmatory dashboard/infrastructure REST refetch loops over+ already-owned resource updates.## Forbidden Paths@@ -1669,8 +1675,11 @@ rebuilding resource-change labels locally.That frontend consumer rule now applies on the canonical decode path too:`frontend-modern/src/hooks/useUnifiedResources.ts` must preserve backend-ownedpolicy metadata, AI-safe summaries, recent changes, and facet counts as-first-class `Resource` fields, and it must treat the backend refresh path as-the source of truth instead of re-normalizing those values locally.+first-class `Resource` fields. It may use the backend refresh path for initial+hydration and unsupported filtered queries, but canonical live freshness for+supported resource snapshots must flow from websocket `state.resources`+instead of layering confirmatory REST refresh loops on top of already-owned+resource updates.Shared infrastructure consumers such as the unified resource table and detaildrawer must present that owned metadata through shared helpers instead ofreconstructing privacy posture from display names, source types, or otherdiff --git a/frontend-modern/src/components/Storage/StorageSummary.tsx b/frontend-modern/src/components/Storage/StorageSummary.tsxindex 72c3d047a2..f1a73e8d0b 100644--- a/frontend-modern/src/components/Storage/StorageSummary.tsx+++ b/frontend-modern/src/components/Storage/StorageSummary.tsx@@ -12,7 +12,6 @@ import { SummaryMetricCard } from '@/components/shared/SummaryMetricCard';import { SummarySynchronizedReadout } from '@/components/shared/SummarySynchronizedReadout';import { buildInteractiveSparklineSynchronizedReadout } from '@/components/shared/interactiveSparklineModel';import {- ChartsAPI,type MetricPoint,type TimeRange,type StorageSummaryChartsResponse,@@ -22,33 +21,14 @@ import {type SummaryTimeRange,} from '@/components/shared/summaryTimeRange';import { formatBytes } from '@/utils/format';-import { getOrgID } from '@/utils/apiClient';-import { normalizeOrgScope } from '@/utils/orgScope';import { eventBus } from '@/stores/events';import { getChartSeriesColor } from '@/utils/chartSeriesPresentation';--// ----------------------------------------------------------------------------// Cache (org-scoped to prevent cross-tenant data leakage)-// ---------------------------------------------------------------------------+import {+ fetchStorageSummaryAndCache,+ readStorageSummaryCache,+} from '@/utils/storageSummaryCache';const POLL_INTERVAL_MS = 30_000;-const STORAGE_SUMMARY_IN_MEMORY_CACHE_VERSION = 1;-const inMemoryCache = new Map<string, StorageSummaryChartsResponse>();--function inMemoryCacheKey(range: TimeRange, nodeId?: string): string {- return `${STORAGE_SUMMARY_IN_MEMORY_CACHE_VERSION}::${normalizeOrgScope(getOrgID())}::${range}::${nodeId || '__all__'}`;-}--// Clear in-memory cache on org switch to prevent cross-org data leakage.-const unsubscribeStorageOrgSwitch = eventBus.on('org_switched', () => {- inMemoryCache.clear();-});--if (import.meta.hot) {- import.meta.hot.dispose(() => {- unsubscribeStorageOrgSwitch();- });-}// ---------------------------------------------------------------------------// Props@@ -105,6 +85,26 @@ const StorageSummary: Component<StorageSummaryProps> = (props) => {return id && id !== 'all' ? id : undefined;});+ const awaitAbortable = <T,>(promise: Promise<T>, signal: AbortSignal): Promise<T> => {+ if (signal.aborted) {+ return Promise.reject(new DOMException('Aborted', 'AbortError'));+ }+ return new Promise<T>((resolve, reject) => {+ const onAbort = () => reject(new DOMException('Aborted', 'AbortError'));+ signal.addEventListener('abort', onAbort, { once: true });+ promise.then(+ (value) => {+ signal.removeEventListener('abort', onAbort);+ resolve(value);+ },+ (error) => {+ signal.removeEventListener('abort', onAbort);+ reject(error);+ },+ );+ });+ };+// Fetch data with race-condition prevention via request IDconst fetchData = async (options?: { prioritize?: boolean }) => {const prioritize = options?.prioritize === true;@@ -115,18 +115,19 @@ const StorageSummary: Component<StorageSummaryProps> = (props) => {const requestedRange = selectedRange();const requestedNodeId = selectedNodeId();- // Capture scope before async gap to prevent cross-org/scope cache writes- const capturedCacheKey = inMemoryCacheKey(requestedRange, requestedNodeId);const controller = new AbortController();const requestId = ++activeFetchRequest;activeFetchController = controller;try {- const response = await ChartsAPI.getStorageSummaryCharts(requestedRange, controller.signal, {- nodeId: requestedNodeId,- });+ const response = await awaitAbortable(+ fetchStorageSummaryAndCache(requestedRange, {+ caller: 'StorageSummary',+ nodeId: requestedNodeId,+ }),+ controller.signal,+ );if (requestId !== activeFetchRequest) return; // stale response- inMemoryCache.set(capturedCacheKey, response);setData(response);setFetchFailed(false);} catch (err: unknown) {@@ -134,7 +135,7 @@ const StorageSummary: Component<StorageSummaryProps> = (props) => {if (requestId !== activeFetchRequest) return; // stale errorsetFetchFailed(true);// Fall back to cache- const cached = inMemoryCache.get(capturedCacheKey);+ const cached = readStorageSummaryCache(requestedRange, requestedNodeId);if (cached) setData(cached);} finally {if (activeFetchController === controller) {@@ -160,7 +161,7 @@ const StorageSummary: Component<StorageSummaryProps> = (props) => {}// Try cache first for instant display- const cached = inMemoryCache.get(inMemoryCacheKey(range, nodeId));+ const cached = readStorageSummaryCache(range, nodeId);if (cached) {setData(cached);setLoaded(true);diff --git a/frontend-modern/src/components/Storage/__tests__/Storage.test.tsx b/frontend-modern/src/components/Storage/__tests__/Storage.test.tsxindex 4f9ce2c753..8923e7e927 100644--- a/frontend-modern/src/components/Storage/__tests__/Storage.test.tsx+++ b/frontend-modern/src/components/Storage/__tests__/Storage.test.tsx@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { ChartsAPI } from '@/api/charts';import StorageSummary from '@/components/Storage/StorageSummary';import storageSummarySource from '@/components/Storage/StorageSummary.tsx?raw';+import storageSummaryCacheSource from '@/utils/storageSummaryCache.ts?raw';import type { Alert } from '@/types/api';import type { Resource, ResourceType } from '@/types/resource';import Storage from '@/components/Storage/Storage';@@ -1715,10 +1716,13 @@ describe('Storage', () => {expect(params.get('status')).toBe('warning');});- it('versions same-tab storage summary cache keys with the summary contract', () => {- expect(storageSummarySource).toContain('const STORAGE_SUMMARY_IN_MEMORY_CACHE_VERSION = 1;');- expect(storageSummarySource).toContain(- "return `${STORAGE_SUMMARY_IN_MEMORY_CACHE_VERSION}::${normalizeOrgScope(getOrgID())}::${range}::${nodeId || '__all__'}`;",+ it('routes storage summary fetches through the shared storage summary cache owner', () => {+ expect(storageSummarySource).toContain('readStorageSummaryCache(range, nodeId)');+ expect(storageSummarySource).toContain('fetchStorageSummaryAndCache(requestedRange, {');+ expect(storageSummarySource).not.toContain('ChartsAPI.getStorageSummaryCharts(');+ expect(storageSummaryCacheSource).toContain('const STORAGE_SUMMARY_CACHE_VERSION = 1;');+ expect(storageSummaryCacheSource).toContain(+ "return `${STORAGE_SUMMARY_CACHE_VERSION}::${orgScope}::${range}::${nodeId || '__all__'}`;",);});});diff --git a/frontend-modern/src/hooks/__tests__/useDashboardTrends.test.ts b/frontend-modern/src/hooks/__tests__/useDashboardTrends.test.tsindex 4531f81693..f06c250337 100644--- a/frontend-modern/src/hooks/__tests__/useDashboardTrends.test.ts+++ b/frontend-modern/src/hooks/__tests__/useDashboardTrends.test.ts@@ -1,11 +1,79 @@-import { describe, expect, it } from 'vitest';+import { createRoot, createSignal } from 'solid-js';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { Resource } from '@/types/resource';++vi.mock('@/utils/apiClient', () => ({+ getOrgID: () => 'test-org',+}));++vi.mock('@/stores/events', () => ({+ eventBus: {+ on: vi.fn(() => () => {}),+ },+}));++vi.mock('@/utils/infrastructureSummaryCache', () => ({+ fetchInfrastructureSummaryAndCache: vi.fn(),+ readInfrastructureSummaryCache: vi.fn(),+}));++vi.mock('@/utils/storageSummaryCache', () => ({+ fetchStorageSummaryAndCache: vi.fn(),+ readStorageSummaryCache: vi.fn(),+}));++vi.mock('@/components/Infrastructure/infrastructureSummaryModel', () => ({+ buildInfrastructureEmptyHistoryLabel: vi.fn(() => null),+ buildInfrastructureSummarySeries: vi.fn((resources: Resource[]) =>+ resources+ .filter((resource) =>+ ['agent', 'docker-host', 'k8s-cluster', 'k8s-node'].includes(resource.type),+ )+ .map((resource) => ({+ id: resource.id,+ cpu: [+ { timestamp: 1_700_000_000_000, value: 20 },+ { timestamp: 1_700_000_060_000, value: 30 },+ ],+ memory: [+ { timestamp: 1_700_000_000_000, value: 40 },+ { timestamp: 1_700_000_060_000, value: 50 },+ ],+ })),+ ),+}));+import useDashboardTrendsSource from '@/hooks/useDashboardTrends.ts?raw';import {buildStorageCapacityTrendPoints,computeTrendDelta,extractTrendData,+ useDashboardTrends,type TrendPoint,} from '@/hooks/useDashboardTrends';+import {+ fetchInfrastructureSummaryAndCache,+ readInfrastructureSummaryCache,+} from '@/utils/infrastructureSummaryCache';+import {+ fetchStorageSummaryAndCache,+ readStorageSummaryCache,+} from '@/utils/storageSummaryCache';++function createResource(partial: Partial<Resource> & Pick<Resource, 'id' | 'type'>): Resource {+ return {+ ...partial,+ id: partial.id,+ type: partial.type,+ name: partial.name ?? partial.id,+ displayName: partial.displayName ?? partial.name ?? partial.id,+ platformId: partial.platformId ?? 'platform-1',+ platformType: partial.platformType ?? 'proxmox',+ sourceType: partial.sourceType ?? 'proxmox',+ status: partial.status ?? 'online',+ lastSeen: partial.lastSeen ?? 1_700_000_000_000,+ } as Resource;+}function createPoints(values: number[]): TrendPoint[] {const start = 1_700_000_000_000;@@ -122,16 +190,139 @@ describe('buildStorageCapacityTrendPoints', () => {});});+describe('useDashboardTrends fetch scoping', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(readInfrastructureSummaryCache).mockReturnValue(null);+ vi.mocked(fetchInfrastructureSummaryAndCache).mockResolvedValue({+ map: new Map(),+ oldestDataTimestamp: null,+ });+ vi.mocked(readStorageSummaryCache).mockReturnValue(null);+ vi.mocked(fetchStorageSummaryAndCache).mockResolvedValue({+ pools: {+ 'pool-a': {+ name: 'Pool A',+ usage: [],+ used: createPoints([400, 500]),+ avail: createPoints([600, 500]),+ },+ },+ disks: {},+ stats: {} as never,+ });+ });++ it('does not refetch dashboard summary charts as paginated resources expand within the same scope', async () => {+ const infrastructureA = createResource({ id: 'infra-a', type: 'agent' });+ const infrastructureB = createResource({ id: 'infra-b', type: 'agent' });+ const storageA = createResource({ id: 'storage-a', type: 'storage' });+ const storageB = createResource({ id: 'storage-b', type: 'storage' });++ let dispose!: () => void;+ let trends!: ReturnType<typeof useDashboardTrends>;+ let setResources!: (value: Resource[]) => void;++ createRoot((d) => {+ dispose = d;+ const [resources, setResourcesSignal] = createSignal<Resource[]>([infrastructureA, storageA]);+ setResources = setResourcesSignal;+ const [range] = createSignal<'1h'>('1h');+ trends = useDashboardTrends(resources, range);+ });++ await vi.waitFor(() => {+ expect(vi.mocked(fetchInfrastructureSummaryAndCache)).toHaveBeenCalledTimes(1);+ expect(vi.mocked(fetchStorageSummaryAndCache)).toHaveBeenCalledTimes(1);+ });++ setResources([infrastructureA, infrastructureB, storageA, storageB]);++ await Promise.resolve();+ await Promise.resolve();++ expect(vi.mocked(fetchInfrastructureSummaryAndCache)).toHaveBeenCalledTimes(1);+ expect(vi.mocked(fetchStorageSummaryAndCache)).toHaveBeenCalledTimes(1);+ expect(Array.from(trends().infrastructure.cpu.keys())).toEqual(['infra-a', 'infra-b']);++ dispose();+ });++ it('refetches infrastructure charts when the dashboard trend range changes without refetching storage charts', async () => {+ const infrastructureA = createResource({ id: 'infra-a', type: 'agent' });+ const storageA = createResource({ id: 'storage-a', type: 'storage' });++ let dispose!: () => void;+ let setRange!: (value: '1h' | '12h') => void;++ createRoot((d) => {+ dispose = d;+ const [resources] = createSignal<Resource[]>([infrastructureA, storageA]);+ const [range, setRangeSignal] = createSignal<'1h' | '12h'>('1h');+ setRange = setRangeSignal;+ useDashboardTrends(resources, range);+ });++ await vi.waitFor(() => {+ expect(vi.mocked(fetchInfrastructureSummaryAndCache)).toHaveBeenCalledTimes(1);+ expect(vi.mocked(fetchStorageSummaryAndCache)).toHaveBeenCalledTimes(1);+ });++ setRange('12h');++ await vi.waitFor(() => {+ expect(vi.mocked(fetchInfrastructureSummaryAndCache)).toHaveBeenCalledTimes(2);+ });++ expect(vi.mocked(fetchStorageSummaryAndCache)).toHaveBeenCalledTimes(1);++ dispose();+ });++ it('reuses a fresh infrastructure summary cache instead of immediately refetching the same scope', async () => {+ const infrastructureA = createResource({ id: 'infra-a', type: 'agent' });+ const storageA = createResource({ id: 'storage-a', type: 'storage' });++ vi.mocked(readInfrastructureSummaryCache).mockReturnValue({+ map: new Map(),+ oldestDataTimestamp: null,+ cachedAt: Date.now(),+ });++ let dispose!: () => void;++ createRoot((d) => {+ dispose = d;+ const [resources] = createSignal<Resource[]>([infrastructureA, storageA]);+ const [range] = createSignal<'1h'>('1h');+ useDashboardTrends(resources, range);+ });++ await Promise.resolve();+ await Promise.resolve();++ expect(vi.mocked(fetchInfrastructureSummaryAndCache)).not.toHaveBeenCalled();+ expect(vi.mocked(fetchStorageSummaryAndCache)).toHaveBeenCalledTimes(1);++ dispose();+ });+});+describe('useDashboardTrends infrastructure routing', () => {it('routes dashboard infrastructure sparklines through the infrastructure summary chart cache', () => {+ expect(useDashboardTrendsSource).toContain('readInfrastructureSummaryCache');expect(useDashboardTrendsSource).toContain('fetchInfrastructureSummaryAndCache');expect(useDashboardTrendsSource).toContain("caller: 'useDashboardTrends'");+ expect(useDashboardTrendsSource).toContain('const infrastructureScopeKey');+ expect(useDashboardTrendsSource).toContain('const hasInfrastructureResources');expect(useDashboardTrendsSource).not.toContain('request.cpu.map(async');expect(useDashboardTrendsSource).not.toContain('request.memory.map(async');});it('routes storage trends through the storage summary charts endpoint', () => {- expect(useDashboardTrendsSource).toContain('ChartService.getStorageSummaryCharts(STORAGE_RANGE)');+ expect(useDashboardTrendsSource).toContain('readStorageSummaryCache');+ expect(useDashboardTrendsSource).toContain('fetchStorageSummaryAndCache(STORAGE_RANGE');+ expect(useDashboardTrendsSource).toContain('const storageScopeKey');expect(useDashboardTrendsSource).toContain('buildStorageCapacityTrendPoints(storageSummary.pools)');expect(useDashboardTrendsSource).not.toContain('metrics-store/history');expect(useDashboardTrendsSource).not.toContain('request.storage.map(async');diff --git a/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.ts b/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.tsindex 67e91eca72..af83ce0c91 100644--- a/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.ts+++ b/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.ts@@ -1,7 +1,8 @@-import { batch, createEffect, createRoot, createSignal } from 'solid-js';+import { batch, createRoot, createSignal } from 'solid-js';import { createStore, reconcile, type SetStoreFunction } from 'solid-js/store';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { State } from '@/types/api';+import type { Resource } from '@/types/resource';import useUnifiedResourcesSource from '../useUnifiedResources.ts?raw';import stringUtilsSource from '@/utils/stringUtils.ts?raw';@@ -32,8 +33,39 @@ const v2Resource = {},};-const asWsResource = <T extends object>(resource: T): State['resources'][number] =>- resource as unknown as State['resources'][number];+const wsResource: Resource = {+ id: 'node-1',+ type: 'agent',+ name: 'node-1',+ displayName: 'node-1',+ platformId: 'node-1',+ platformType: 'agent',+ sourceType: 'agent',+ status: 'online',+ lastSeen: Date.parse('2026-02-06T12:00:00Z'),+ cpu: { current: 15 },+ memory: { current: 50, used: 4 * 1024 * 1024, total: 8 * 1024 * 1024, free: 4 * 1024 * 1024 },+ disk: {+ current: 30,+ used: 30 * 1024 * 1024,+ total: 100 * 1024 * 1024,+ free: 70 * 1024 * 1024,+ },+ discoveryTarget: {+ resourceType: 'agent',+ agentId: 'host-1',+ resourceId: 'host-1',+ hostname: 'pve1',+ },+ facetCounts: {+ recentChanges: 1,+ },+};++const createWsResource = (overrides: Partial<Resource> = {}): Resource => ({+ ...wsResource,+ ...overrides,+});const flushAsync = async () => {await Promise.resolve();@@ -101,7 +133,7 @@ describe('useUnifiedResources', () => {},activeAlerts: [],recentlyResolved: [],- resources: [asWsResource(v2Resource)],+ resources: [wsResource],lastUpdate: 0,});setWsState = _setWsState;@@ -131,19 +163,12 @@ describe('useUnifiedResources', () => {vi.resetModules();});- it('refetches when lastUpdate changes even if resources are reconciled in place', async () => {+ it('uses canonical websocket resource updates without a REST refetch for supported queries', async () => {let dispose = () => {};let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;- let firstResourceEffectRuns = 0;createRoot((d) => {dispose = d;result = useUnifiedResources();- createEffect(() => {- const first = result!.resources()[0];- if (first) {- firstResourceEffectRuns += 1;- }- });});await flushAsync();@@ -154,12 +179,8 @@ describe('useUnifiedResources', () => {'/api/resources?type=agent%2Cdocker-host%2Cpbs%2Cpmg%2Ck8s-cluster%2Ck8s-node&page=1&limit=100',{ cache: 'no-store' },);- const originalResourceRef = result!.resources()[0];- const effectsAfterInitialFetch = firstResourceEffectRuns;-- vi.advanceTimersByTime(800);await flushAsync();- expect(apiFetchMock).toHaveBeenCalledTimes(1);+ await flushAsync();// Simulate a metric update where reconcile keeps array identity stable.batch(() => {@@ -167,12 +188,8 @@ describe('useUnifiedResources', () => {'resources',reconcile([- asWsResource({- ...v2Resource,- metrics: {- ...v2Resource.metrics,- cpu: { percent: 42 },- },+ createWsResource({+ cpu: { current: 42 },}),],{ key: 'id' },@@ -181,15 +198,9 @@ describe('useUnifiedResources', () => {setWsState('lastUpdate', 1738843201000);});- vi.advanceTimersByTime(799);await flushAsync();expect(apiFetchMock).toHaveBeenCalledTimes(1);-- vi.advanceTimersByTime(2000);- await flushAsync();- expect(apiFetchMock).toHaveBeenCalledTimes(2);- expect(result!.resources()[0]).toBe(originalResourceRef);- expect(firstResourceEffectRuns).toBe(effectsAfterInitialFetch);+ expect(result!.resources()[0]?.cpu?.current).toBe(42);expect(result!.resources()[0].discoveryTarget).toEqual({resourceType: 'agent',agentId: 'host-1',@@ -204,7 +215,7 @@ describe('useUnifiedResources', () => {});it('projects kubernetes clusterId from the canonical context prefix', async () => {- apiFetchMock.mockResolvedValueOnce({+ apiFetchMock.mockResolvedValue({ok: true,json: async () => ({data: [@@ -226,11 +237,10 @@ describe('useUnifiedResources', () => {let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;createRoot((d) => {dispose = d;- result = useUnifiedResources();+ result = useUnifiedResources({ query: 'type=pod', cacheKey: 'pods' });});- await flushAsync();- await waitForResourceCount(() => result!.resources().length);+ await result!.refetch();expect(result!.resources()[0]?.clusterId).toBe('cluster-a');@@ -258,11 +268,10 @@ describe('useUnifiedResources', () => {let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;createRoot((d) => {dispose = d;- result = useUnifiedResources();+ result = useUnifiedResources({ query: 'type=vm', cacheKey: 'vms' });});- await flushAsync();- await waitForResourceCount(() => result!.resources().length);+ await result!.refetch();expect(result!.resources()[0]?.clusterId).toBe('cluster-b');@@ -452,10 +461,10 @@ describe('useUnifiedResources', () => {let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;createRoot((d) => {dispose = d;- result = useUnifiedResources();+ result = useUnifiedResources({ query: 'type=pod', cacheKey: 'pods' });});- await waitForResourceCount(() => result!.resources().length);+ await result!.refetch();expect(result!.resources()[0].discoveryTarget).toEqual({resourceType: 'pod',agentId: 'cluster-agent-1',@@ -704,12 +713,14 @@ describe('useUnifiedResources', () => {let first: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;createRoot((d) => {disposeFirst = d;- first = useUnifiedResources();+ first = useUnifiedResources({ query: '', cacheKey: 'all-resources' });});await flushAsync();await waitForResourceCount(() => first!.resources().length);expect(apiFetchMock).toHaveBeenCalledTimes(1);+ await flushAsync();+ await flushAsync();disposeFirst();@@ -717,10 +728,10 @@ describe('useUnifiedResources', () => {let second: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;createRoot((d) => {disposeSecond = d;- second = useUnifiedResources();+ second = useUnifiedResources({ query: '', cacheKey: 'all-resources' });});- await flushAsync();+ await waitForResourceCount(() => second!.resources().length);expect(apiFetchMock).toHaveBeenCalledTimes(1);expect(second!.resources().length).toBeGreaterThan(0);@@ -753,6 +764,20 @@ describe('useUnifiedResources', () => {await flushAsync();await waitForResourceCount(() => allResources!.resources().length, 2);expect(apiFetchMock).toHaveBeenCalledTimes(1);+ batch(() => {+ setWsState('resources', [+ wsResource,+ createWsResource({+ id: 'disk-1',+ type: 'physical_disk',+ name: 'nvme0n1',+ displayName: 'nvme0n1',+ platformId: 'disk-1',+ }),+ ]);+ setWsState('lastUpdate', 1738843202500);+ });+ await flushAsync();disposeAll();@@ -797,6 +822,21 @@ describe('useUnifiedResources', () => {await flushAsync();await waitForResourceCount(() => allResources!.resources().length, 2);expect(apiFetchMock).toHaveBeenCalledTimes(1);+ batch(() => {+ setWsState('resources', [+ wsResource,+ createWsResource({+ id: 'disk-1',+ type: 'physical_disk',+ name: 'nvme0n1',+ displayName: 'nvme0n1',+ platformId: 'disk-1',+ }),+ ]);+ setWsState('lastUpdate', 1738843202501);+ });+ await flushAsync();+ await flushAsync();disposeAll();@@ -807,7 +847,7 @@ describe('useUnifiedResources', () => {filtered = useUnifiedResources({ query: 'type=physical_disk' });});- await flushAsync();+ await waitForValue(() => filtered!.resources().length, 1);expect(apiFetchMock).toHaveBeenCalledTimes(1);expect(filtered!.loading()).toBe(false);expect(filtered!.resources().map((resource) => resource.id)).toEqual(['disk-1']);@@ -820,6 +860,10 @@ describe('useUnifiedResources', () => {ok: true,json: async () => ({ data: [] }),});+ batch(() => {+ setWsState('resources', []);+ setWsState('lastUpdate', 1738843202600);+ });let disposeFirst = () => {};let first: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;@@ -850,11 +894,11 @@ describe('useUnifiedResources', () => {disposeSecond();});- it('coalesces burst websocket updates into a single delayed refetch', async () => {+ it('coalesces burst websocket updates into a single delayed refetch for unsupported queries', async () => {let dispose = () => {};createRoot((d) => {dispose = d;- useUnifiedResources();+ useUnifiedResources({ query: 'status=online', cacheKey: 'status-online' });});await flushAsync();@@ -882,7 +926,7 @@ describe('useUnifiedResources', () => {dispose();});- it('replaces stale canonical resources when websocket lastUpdate triggers a refetch', async () => {+ it('replaces stale canonical resources through fallback refetches for unsupported queries', async () => {apiFetchMock.mockResolvedValueOnce({ok: true,@@ -914,7 +958,7 @@ describe('useUnifiedResources', () => {let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;createRoot((d) => {dispose = d;- result = useUnifiedResources();+ result = useUnifiedResources({ query: 'status=online', cacheKey: 'status-online' });});await flushAsync();@@ -980,8 +1024,7 @@ describe('useUnifiedResources', () => {result = useUnifiedResources();});- await flushAsync();- await waitForResourceCount(() => result!.resources().length);+ await waitForValue(() => result!.resources()[0]?.platformType, 'truenas');expect(result!.resources()[0]?.type).toBe('agent');expect(result!.resources()[0]?.platformType).toBe('truenas');@@ -1046,8 +1089,7 @@ describe('useUnifiedResources', () => {result = useUnifiedResources();});- await flushAsync();- await waitForResourceCount(() => result!.resources().length);+ await waitForValue(() => result!.resources()[0]?.recentChanges?.[0]?.id, 'change-1');expect(result!.resources()[0]?.recentChanges).toEqual([{@@ -1089,8 +1131,7 @@ describe('useUnifiedResources', () => {result = useUnifiedResources();});- await flushAsync();- await waitForResourceCount(() => result!.resources().length);+ await waitForValue(() => result!.resources()[0]?.platformType, 'proxmox-pve');expect(apiFetchMock).toHaveBeenCalledTimes(1);expect(result!.resources()[0]?.id).toBe('node-1');expect(result!.resources()[0]?.platformType).toBe('proxmox-pve');@@ -1109,8 +1150,7 @@ describe('useUnifiedResources', () => {});eventBus.emit('org_switched', 'tenant-b');- await flushAsync();- await waitForResourceCount(() => result!.resources().length);+ await waitForValue(() => result!.resources()[0]?.id, 'node-2');expect(apiFetchMock).toHaveBeenCalledTimes(2);expect(result!.resources()[0]?.id).toBe('node-2');@@ -1156,6 +1196,8 @@ describe('useUnifiedResources', () => {it('uses the shared org scope helper for cache and fetch state', () => {expect(useUnifiedResourcesSource).toContain('normalizeOrgScope(getOrgID())');+ expect(useUnifiedResourcesSource).toContain('supportsCanonicalWsHydration');+ expect(useUnifiedResourcesSource).toContain('wsStore.state.resources');expect(useUnifiedResourcesSource).not.toContain('const DEFAULT_ORG_SCOPE = \'default\'');expect(useUnifiedResourcesSource).not.toContain('const normalizeOrgScope =');expect(useUnifiedResourcesSource).toContain('asTrimmedString');diff --git a/frontend-modern/src/hooks/useDashboardTrends.ts b/frontend-modern/src/hooks/useDashboardTrends.tsindex 6ffa3fd794..7798c24ea3 100644--- a/frontend-modern/src/hooks/useDashboardTrends.ts+++ b/frontend-modern/src/hooks/useDashboardTrends.ts@@ -1,6 +1,6 @@-import { createEffect, createMemo, createSignal, type Accessor } from 'solid-js';+import { createEffect, createMemo, createSignal, onCleanup, type Accessor } from 'solid-js';import {- ChartsAPI as ChartService,+ type ChartData,type HistoryTimeRange,type StorageSummaryChartsResponse,type TimeRange,@@ -9,9 +9,18 @@ import {buildInfrastructureEmptyHistoryLabel,buildInfrastructureSummarySeries,} from '@/components/Infrastructure/infrastructureSummaryModel';-import type { DashboardOverview } from '@/hooks/useDashboardOverview';+import { eventBus } from '@/stores/events';import { isAgentFacetInfrastructureResource } from '@/utils/agentResources';-import { fetchInfrastructureSummaryAndCache } from '@/utils/infrastructureSummaryCache';+import { getOrgID } from '@/utils/apiClient';+import {+ fetchInfrastructureSummaryAndCache,+ readInfrastructureSummaryCache,+} from '@/utils/infrastructureSummaryCache';+import { normalizeOrgScope } from '@/utils/orgScope';+import {+ fetchStorageSummaryAndCache,+ readStorageSummaryCache,+} from '@/utils/storageSummaryCache';import { isInfrastructure, isStorage, type Resource } from '@/types/resource';export type TrendPoint = {@@ -38,18 +47,6 @@ export interface DashboardTrends {error: string | null;}-interface DashboardTrendRequest {- infrastructure: string[];- storage: string[];- infrastructureRange: HistoryTimeRange;-}--interface DashboardTrendSnapshot {- infrastructure: DashboardTrends['infrastructure'];- storage: DashboardTrends['storage'];- error: string | null;-}-const INFRASTRUCTURE_RANGE: HistoryTimeRange = '1h';const STORAGE_RANGE: TimeRange = '24h';@@ -61,17 +58,17 @@ function createEmptyTrendData(): TrendData {};}-function createEmptyTrendSnapshot(): DashboardTrendSnapshot {+function createEmptyInfrastructureTrends(): DashboardTrends['infrastructure'] {return {- infrastructure: {- cpu: new Map<string, TrendData>(),- memory: new Map<string, TrendData>(),- emptyMessage: null,- },- storage: {- capacity: null,- },- error: null,+ cpu: new Map<string, TrendData>(),+ memory: new Map<string, TrendData>(),+ emptyMessage: null,+ };+}++function createEmptyStorageTrends(): DashboardTrends['storage'] {+ return {+ capacity: null,};}@@ -95,10 +92,6 @@ function averagePoints(points: TrendPoint[]): number {return points.reduce((sum, point) => sum + point.value, 0) / points.length;}-function dedupeValues(values: string[]): string[] {- return Array.from(new Set(values));-}-function toInfrastructureSummaryRange(range: HistoryTimeRange): TimeRange {switch (range) {case '1h':@@ -118,27 +111,19 @@ function toInfrastructureSummaryRange(range: HistoryTimeRange): TimeRange {}}-async function fetchInfrastructureTrendSnapshot(+function buildInfrastructureTrendSnapshot(resources: Resource[],- range: HistoryTimeRange,-): Promise<DashboardTrends['infrastructure']> {+ map: Map<string, ChartData>,+ oldestDataTimestamp: number | null,+): DashboardTrends['infrastructure'] {const infrastructureResources = resources.filter((resource) => isInfrastructure(resource));if (infrastructureResources.length === 0) {- return {- cpu: new Map<string, TrendData>(),- memory: new Map<string, TrendData>(),- emptyMessage: null,- };+ return createEmptyInfrastructureTrends();}const agentFacetResources = resources.filter((resource) =>isAgentFacetInfrastructureResource(resource),);-- const { map, oldestDataTimestamp } = await fetchInfrastructureSummaryAndCache(- toInfrastructureSummaryRange(range),- { caller: 'useDashboardTrends' },- );const summarySeries = buildInfrastructureSummarySeries(infrastructureResources,map,@@ -257,140 +242,171 @@ export function extractTrendData(points: Array<{ timestamp: number; value: numbe};}-async function fetchDashboardTrendSnapshot(- request: DashboardTrendRequest,- resources: Resource[],-): Promise<DashboardTrendSnapshot> {- let firstError: string | null = null;- const captureError = (error: unknown) => {- if (firstError === null) {- firstError = toErrorMessage(error);- }- };-- const [infrastructure, storageCapacity] = await Promise.all([- (async () => {- try {- return await fetchInfrastructureTrendSnapshot(resources, request.infrastructureRange);- } catch (error) {- captureError(error);- return createEmptyTrendSnapshot().infrastructure;- }- })(),- (async () => {- if (request.storage.length === 0) {- return null;- }- try {- const storageSummary = await ChartService.getStorageSummaryCharts(STORAGE_RANGE);- return extractTrendData(buildStorageCapacityTrendPoints(storageSummary.pools));- } catch (error) {- captureError(error);- return null;- }- })(),- ]);-+function buildStorageTrendSnapshot(+ storageSummary: StorageSummaryChartsResponse | null,+): DashboardTrends['storage'] {+ if (!storageSummary) {+ return createEmptyStorageTrends();+ }return {- infrastructure,- storage: {- capacity: storageCapacity,- },- error: firstError,+ capacity: extractTrendData(buildStorageCapacityTrendPoints(storageSummary.pools)),};}export function useDashboardTrends(- overview: Accessor<DashboardOverview>,resources: Accessor<Resource[]>,infrastructureRange?: Accessor<HistoryTimeRange>,): Accessor<DashboardTrends> {- const [error, setError] = createSignal<string | null>(null);-- const trendRequest = createMemo<DashboardTrendRequest>(() => {- const currentOverview = overview();- const currentResources = resources();- const infrastructureTargets = dedupeValues([- ...currentOverview.infrastructure.topCPU.map((item) => item.id),- ...currentOverview.infrastructure.topMemory.map((item) => item.id),- ]).sort();- const storageTargets = dedupeValues(- currentResources- .filter((resource) => isStorage(resource))- .map((resource) => {- const mt = resource.metricsTarget;- return mt ? mt.resourceId : resource.id;- }),- ).sort();+ const [infrastructureError, setInfrastructureError] = createSignal<string | null>(null);+ const [storageError, setStorageError] = createSignal<string | null>(null);+ const [infrastructureCharts, setInfrastructureCharts] = createSignal<Map<string, ChartData>>(+ new Map(),+ );+ const [oldestDataTimestamp, setOldestDataTimestamp] = createSignal<number | null>(null);+ const [storageSummary, setStorageSummary] = createSignal<StorageSummaryChartsResponse | null>(+ null,+ );+ const [infrastructureLoading, setInfrastructureLoading] = createSignal(false);+ const [storageLoading, setStorageLoading] = createSignal(false);+ const [orgVersion, setOrgVersion] = createSignal(0);- return {- infrastructure: infrastructureTargets,- storage: storageTargets,- infrastructureRange: infrastructureRange ? infrastructureRange() : INFRASTRUCTURE_RANGE,- };+ const unsubscribeOrgSwitch = eventBus.on('org_switched', () => {+ setOrgVersion((value) => value + 1);});- // Stabilize the request key: sort targets by ID so that metric-value- // fluctuations don't shuffle the ordering and trigger unnecessary refetches.- const requestKey = createMemo(() => {- const req = trendRequest();- const stableReq = {- infrastructure: [...req.infrastructure].sort(),- storage: [...req.storage].sort(),- infrastructureRange: req.infrastructureRange,- };- return JSON.stringify(stableReq);+ onCleanup(() => {+ unsubscribeOrgSwitch();+ });++ const hasInfrastructureResources = createMemo(() =>+ resources().some((resource) => isInfrastructure(resource)),+ );+ const hasStorageResources = createMemo(() => resources().some((resource) => isStorage(resource)));++ const infrastructureScopeKey = createMemo(() => {+ const version = orgVersion();+ const orgScope = normalizeOrgScope(getOrgID());+ const range = infrastructureRange ? infrastructureRange() : INFRASTRUCTURE_RANGE;+ return JSON.stringify({+ orgScope,+ version,+ hasInfrastructure: hasInfrastructureResources(),+ infrastructureRange: range,+ });});- const initialSnapshot = createEmptyTrendSnapshot();- const [snapshot, setSnapshot] = createSignal<DashboardTrendSnapshot>(initialSnapshot);- const [trendLoading, setTrendLoading] = createSignal(false);+ const storageScopeKey = createMemo(() => {+ const version = orgVersion();+ const orgScope = normalizeOrgScope(getOrgID());+ return JSON.stringify({+ orgScope,+ version,+ hasStorage: hasStorageResources(),+ storageRange: STORAGE_RANGE,+ });+ });- // Track the latest request to discard stale responses.- let latestRequestId = 0;+ let latestInfrastructureRequestId = 0;+ let latestStorageRequestId = 0;- // Use manual async fetching instead of createResource so that refetches- // never trigger the app-level <Suspense> boundary (which would unmount- // the entire page and reset scroll position).createEffect(() => {- requestKey(); // track dependency — re-run effect when key changes- const request = trendRequest();- const currentResources = resources();+ infrastructureScopeKey();+ const range = infrastructureRange ? infrastructureRange() : INFRASTRUCTURE_RANGE;+ const summaryRange = toInfrastructureSummaryRange(range);++ if (!hasInfrastructureResources()) {+ setInfrastructureCharts(new Map());+ setOldestDataTimestamp(null);+ setInfrastructureError(null);+ setInfrastructureLoading(false);+ return;+ }- // Skip empty requests (no targets yet).- if (request.infrastructure.length === 0 && request.storage.length === 0) return;+ const cached = readInfrastructureSummaryCache(summaryRange);+ if (cached) {+ setInfrastructureCharts(cached.map);+ setOldestDataTimestamp(cached.oldestDataTimestamp);+ setInfrastructureError(null);+ setInfrastructureLoading(false);+ return;+ }- const requestId = ++latestRequestId;- setTrendLoading(true);+ const requestId = ++latestInfrastructureRequestId;+ setInfrastructureLoading(true);- fetchDashboardTrendSnapshot(request, currentResources)+ fetchInfrastructureSummaryAndCache(summaryRange, {+ caller: 'useDashboardTrends',+ }).then((result) => {- if (requestId !== latestRequestId) return; // stale- setSnapshot(result);- if (result.error) {- setError(result.error);- } else {- setError(null);+ if (requestId !== latestInfrastructureRequestId) return;+ setInfrastructureCharts(result.map);+ setOldestDataTimestamp(result.oldestDataTimestamp);+ setInfrastructureError(null);+ })+ .catch((err) => {+ if (requestId !== latestInfrastructureRequestId) return;+ if (!cached) {+ setInfrastructureCharts(new Map());+ setOldestDataTimestamp(null);}+ setInfrastructureError(toErrorMessage(err));+ })+ .finally(() => {+ if (requestId === latestInfrastructureRequestId) {+ setInfrastructureLoading(false);+ }+ });+ });++ createEffect(() => {+ storageScopeKey();++ if (!hasStorageResources()) {+ setStorageSummary(null);+ setStorageError(null);+ setStorageLoading(false);+ return;+ }++ const cached = readStorageSummaryCache(STORAGE_RANGE);+ if (cached) {+ setStorageSummary(cached);+ }++ const requestId = ++latestStorageRequestId;+ setStorageLoading(true);++ fetchStorageSummaryAndCache(STORAGE_RANGE, { caller: 'useDashboardTrends' })+ .then((result) => {+ if (requestId !== latestStorageRequestId) return;+ setStorageSummary(result);+ setStorageError(null);}).catch((err) => {- if (requestId !== latestRequestId) return;- setError(toErrorMessage(err));+ if (requestId !== latestStorageRequestId) return;+ if (!cached) {+ setStorageSummary(null);+ }+ setStorageError(toErrorMessage(err));}).finally(() => {- if (requestId === latestRequestId) {- setTrendLoading(false);+ if (requestId === latestStorageRequestId) {+ setStorageLoading(false);}});});+ const infrastructureSnapshot = createMemo(() =>+ buildInfrastructureTrendSnapshot(resources(), infrastructureCharts(), oldestDataTimestamp()),+ );+ const storageSnapshot = createMemo(() => buildStorageTrendSnapshot(storageSummary()));+return createMemo<DashboardTrends>(() => {- const current = snapshot();return {- infrastructure: current.infrastructure,- storage: current.storage,- loading: trendLoading(),- error: error(),+ infrastructure: infrastructureSnapshot(),+ storage: storageSnapshot(),+ loading: infrastructureLoading() || storageLoading(),+ error: infrastructureError() ?? storageError(),};});}diff --git a/frontend-modern/src/hooks/useUnifiedResources.ts b/frontend-modern/src/hooks/useUnifiedResources.tsindex a90315dca0..d9cd05f282 100644--- a/frontend-modern/src/hooks/useUnifiedResources.ts+++ b/frontend-modern/src/hooks/useUnifiedResources.ts@@ -789,6 +789,21 @@ const parseUnifiedResourcesTypeFilter = (query: string): Set<ResourceType> | nulreturn types.size > 0 ? types : null;};+const filterCanonicalUnifiedResources = (+ resources: Resource[],+ query: string,+ typeFilter: Set<ResourceType> | null,+): Resource[] | null => {+ const normalizedQuery = normalizeUnifiedResourcesQuery(query);+ if (normalizedQuery === '') {+ return resources;+ }+ if (!typeFilter) {+ return null;+ }+ return resources.filter((resource) => typeFilter.has(resolveType(resource.type)));+};+const seedUnifiedResourcesCacheFromAllResources = (entry: UnifiedResourcesCacheEntry,cacheKey: string,@@ -906,6 +921,8 @@ type UseUnifiedResourcesOptions = {export function useUnifiedResources(options?: UseUnifiedResourcesOptions) {const query = normalizeUnifiedResourcesQuery(options?.query ?? DEFAULT_UNIFIED_RESOURCES_QUERY);const cacheKey = (options?.cacheKey || query || 'all').trim();+ const typeFilter = parseUnifiedResourcesTypeFilter(query);+ const supportsCanonicalWsHydration = query === '' || typeFilter !== null;const [orgScope, setOrgScope] = createSignal(normalizeOrgScope(getOrgID()));const resolveScopedCacheKey = () => buildScopedUnifiedResourcesCacheKey(cacheKey, orgScope());let cacheEntry = seedUnifiedResourcesCacheFromAllResources(@@ -925,6 +942,7 @@ export function useUnifiedResources(options?: UseUnifiedResourcesOptions) {let inFlightRefetch: Promise<Resource[]> | null = null;let wsInitialized = false;let lastWsUpdateToken = '';+ let blockedWsHydrationToken: string | null = null;let scopeVersion = 0;const applyResources = (@@ -1027,6 +1045,49 @@ export function useUnifiedResources(options?: UseUnifiedResourcesOptions) {}, delay);};+ createEffect(() => {+ const currentOrgScope = orgScope();+ if (!supportsCanonicalWsHydration) {+ return;+ }+ if (!wsStore.connected() || !wsStore.initialDataReceived()) {+ return;+ }++ const lastUpdateToken = String(wsStore.state.lastUpdate ?? '');+ if (blockedWsHydrationToken !== null) {+ if (+ lastUpdateToken.length === 0 ||+ lastUpdateToken === '0' ||+ lastUpdateToken === blockedWsHydrationToken+ ) {+ return;+ }+ blockedWsHydrationToken = null;+ }++ const wsResources = Array.isArray(wsStore.state.resources) ? wsStore.state.resources : [];+ const projectedResources = filterCanonicalUnifiedResources(wsResources, query, typeFilter);+ const now = Date.now();+ const allResourcesEntry = getUnifiedResourcesCacheEntry(+ buildScopedUnifiedResourcesCacheKey(ALL_RESOURCES_CACHE_KEY, currentOrgScope),+ );+ setUnifiedResourcesCache(allResourcesEntry, wsResources, now);+ allResourcesEntry.lastFetchAt = now;++ if (projectedResources === null) {+ return;+ }++ setUnifiedResourcesCache(cacheEntry, projectedResources, now);+ cacheEntry.lastFetchAt = now;+ batch(() => {+ setResources(reconcile(projectedResources, { key: 'id' }));+ setError(undefined);+ setLoading(false);+ });+ });+createEffect(() => {orgScope();@@ -1041,7 +1102,9 @@ export function useUnifiedResources(options?: UseUnifiedResourcesOptions) {if (!wsInitialized) {wsInitialized = true;lastWsUpdateToken = lastUpdateToken;- scheduleRefetch();+ if (!supportsCanonicalWsHydration) {+ scheduleRefetch();+ }return;}@@ -1050,7 +1113,9 @@ export function useUnifiedResources(options?: UseUnifiedResourcesOptions) {}lastWsUpdateToken = lastUpdateToken;- scheduleRefetch();+ if (!supportsCanonicalWsHydration) {+ scheduleRefetch();+ }});const unsubscribeOrgSwitch = eventBus.on('org_switched', (nextOrgID?: string) => {@@ -1060,6 +1125,9 @@ export function useUnifiedResources(options?: UseUnifiedResourcesOptions) {}scopeVersion += 1;+ blockedWsHydrationToken = supportsCanonicalWsHydration+ ? String(wsStore.state.lastUpdate ?? '')+ : null;setOrgScope(nextOrgScope);cacheEntry = seedUnifiedResourcesCacheFromAllResources(getUnifiedResourcesCacheEntry(resolveScopedCacheKey()),diff --git a/frontend-modern/src/pages/Dashboard.tsx b/frontend-modern/src/pages/Dashboard.tsxindex 649c7d0688..ea93ef11cd 100644--- a/frontend-modern/src/pages/Dashboard.tsx+++ b/frontend-modern/src/pages/Dashboard.tsx@@ -51,7 +51,7 @@ export default function Dashboard() {const overview = useDashboardOverview(resources, alertsList);const [trendRange, setTrendRange] = createSignal<HistoryTimeRange>('1h');- const trends = useDashboardTrends(overview, resources, trendRange);+ const trends = useDashboardTrends(resources, trendRange);const layout = useDashboardLayout();const actions = useDashboardActions(alertsList);const recoverySummary = useDashboardRecovery();diff --git a/frontend-modern/src/pages/__tests__/DashboardPage.test.tsx b/frontend-modern/src/pages/__tests__/DashboardPage.test.tsxindex 374a118327..b8c019a097 100644--- a/frontend-modern/src/pages/__tests__/DashboardPage.test.tsx+++ b/frontend-modern/src/pages/__tests__/DashboardPage.test.tsx@@ -158,6 +158,11 @@ describe('Dashboard page module contract', () => {expect(dashboardPageSource).toContain("cacheKey: 'all-resources'");});+ it('routes dashboard trend hydration through the shared dashboard resources snapshot', () => {+ expect(dashboardPageSource).toContain('const trends = useDashboardTrends(resources, trendRange);');+ expect(dashboardPageSource).not.toContain('useDashboardTrends(overview, resources, trendRange)');+ });+it('renders loading skeleton blocks when resources are loading', () => {unifiedLoading = true;diff --git a/frontend-modern/src/utils/storageSummaryCache.ts b/frontend-modern/src/utils/storageSummaryCache.tsnew file mode 100644index 0000000000..305ddeca57--- /dev/null+++ b/frontend-modern/src/utils/storageSummaryCache.ts@@ -0,0 +1,65 @@+import { ChartsAPI, type StorageSummaryChartsResponse, type TimeRange } from '@/api/charts';+import { eventBus } from '@/stores/events';+import { getOrgID } from '@/utils/apiClient';+import { normalizeOrgScope } from '@/utils/orgScope';++const STORAGE_SUMMARY_CACHE_VERSION = 1;++function cacheKeyFor(+ range: TimeRange,+ nodeId?: string,+ orgScope: string = normalizeOrgScope(getOrgID()),+): string {+ return `${STORAGE_SUMMARY_CACHE_VERSION}::${orgScope}::${range}::${nodeId || '__all__'}`;+}++const inMemoryCache = new Map<string, StorageSummaryChartsResponse>();+const inFlightFetches = new Map<string, Promise<StorageSummaryChartsResponse>>();++export function readStorageSummaryCache(+ range: TimeRange,+ nodeId?: string,+): StorageSummaryChartsResponse | null {+ return inMemoryCache.get(cacheKeyFor(range, nodeId)) ?? null;+}++export function fetchStorageSummaryAndCache(+ range: TimeRange,+ options?: { caller?: string; nodeId?: string },+): Promise<StorageSummaryChartsResponse> {+ const inFlightKey = cacheKeyFor(range, options?.nodeId);+ const existing = inFlightFetches.get(inFlightKey);+ if (existing) {+ return existing;+ }++ const request = ChartsAPI.getStorageSummaryCharts(range, undefined, {+ nodeId: options?.nodeId,+ })+ .then((response) => {+ inMemoryCache.set(inFlightKey, response);+ return response;+ })+ .finally(() => {+ inFlightFetches.delete(inFlightKey);+ });++ inFlightFetches.set(inFlightKey, request);+ return request;+}++export function __resetStorageSummaryCacheForTests(): void {+ inMemoryCache.clear();+ inFlightFetches.clear();+}++const unsubscribeStorageOrgSwitch = eventBus.on('org_switched', () => {+ inMemoryCache.clear();+ inFlightFetches.clear();+});++if (import.meta.hot) {+ import.meta.hot.dispose(() => {+ unsubscribeStorageOrgSwitch();+ });+}