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 live workloads route fetch churn
rcourtman683334420df8
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.mdindex dcd08d90c1..4a84510b6e 100644--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md@@ -244,6 +244,12 @@ work extends shared components instead of creating new local variants.must stay on the app-shell assistant-availability fact instead ofre-reading raw AI settings just to decide whether assistant affordancesshould render.+17. Keep optional shared selectors honest about data ownership. Reusable+ shells such as `frontend-modern/src/components/shared/InfrastructureSelector.tsx`+ must gate their runtime data hooks on actual surface visibility, passing+ explicit disabled/null inputs to shared data owners when the selector is+ hidden instead of hydrating background summary data for chrome the page is+ not rendering.## Forbidden Pathsdiff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex e0d59ccb29..f1b79f3d70 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -201,6 +201,12 @@ regression protection.30. Keep dashboard summary-chart fetches scope-owned rather than page-churn-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 the compact dashboard overview changes, rather than refetching the infrastructure-summary transport in `frontend-modern/src/components/Infrastructure/useInfrastructureSummaryState.ts`, the dashboard storage-summary trend transport in `frontend-modern/src/utils/storageSummaryTrendCache.ts`, or the storage-page summary transport in `frontend-modern/src/utils/storageSummaryCache.ts` for every top-resource or card reshuffle on the same dashboard load. That dashboard infrastructure path must also request only the metrics it renders through the canonical infrastructure-summary route owned by `internal/api/router_routes_monitoring.go` and `internal/api/router.go`; the dashboard may not pay for disk or network summary series when it only renders CPU and memory. App-shell prewarm in `frontend-modern/src/useAppRuntimeState.ts` must not front-run that dashboard-specific route while the operator is already on the root dashboard route owned by `frontend-modern/src/App.tsx`.31. Keep the dashboard overview hot path compact and route-owned. `frontend-modern/src/pages/Dashboard.tsx`, `frontend-modern/src/api/resources.ts`, and `frontend-modern/src/hooks/useDashboardOverview.ts` must hydrate KPI cards, problem-resource rows, and top-infrastructure identities through the compact dashboard-summary API contract owned by the adjacent `api-contracts` and `unified-resources` surfaces, rather than booting the full unfiltered paginated unified-resource list just to derive summary cards.32. Keep infrastructure summary consumers on the compact dashboard overview rather than reopening the all-resources hook. `frontend-modern/src/hooks/useDashboardTrends.ts`, `frontend-modern/src/components/Infrastructure/useInfrastructureSummaryState.ts`, and adjacent dashboard summary consumers may derive chart identity and storage presence from the overview payload they were already given, but they must not call `useResources()` or mount a second unfiltered unified-resource fetch path inside the dashboard hot path. That rule also applies to globally mounted helpers such as `frontend-modern/src/components/AI/Chat/index.tsx`: closed assistant surfaces must read the live websocket snapshot or existing unified-resource cache rather than forcing the dashboard to pay for `all-resources` just because the shell component is mounted.+33. Keep hidden workload-route selector shells off the hot path. When the+ workloads route keeps `frontend-modern/src/components/shared/InfrastructureSelector.tsx`+ mounted only for layout parity, `frontend-modern/src/components/shared/useInfrastructureSelectorState.ts`+ must not hydrate `all-resources` or recovery rollups behind a hidden node+ summary; selector-owned data hooks must be explicitly visibility-gated so+ `/workloads` only pays for workload-owned transports.## Forbidden Paths@@ -372,7 +378,10 @@ of a raw websocket proxy signal: `frontend-modern/src/components/Dashboard/Dashband `frontend-modern/src/components/Dashboard/useDashboardState.ts` must keepfilters, stats, and table visibility driven by the workload route's ownREST-backed health so websocket churn does not hide already-fetched workloads-or swap the protected hot path into a false disconnected shell.+or swap the protected hot path into a false disconnected shell. The first+websocket connect on that route is not a reconnect and must not trigger an+extra workload REST refetch; only later false-to-true recoveries may pay that+refresh cost.The same performance ownership now applies to the downsampled`pkg/metrics/store.go` batched query path. `QueryAllBatch` may drop the globalSQLite `ORDER BY resource_id, metric_type, bucket_ts` sort from the groupeddiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex cdf7368aaa..a5e1058858 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -86,6 +86,10 @@ querying, and the operator-facing storage health presentation layer.`ResourceType` normalization for route/query filters, so storage subtypessuch as `physical_disk` stay on the same cache-backed snapshot instead ofrelying on storage-local filter aliases.+ Optional selector shells that only surface storage/recovery counts when they+ are visible must now pass an explicit enabled gate into that shared hook and+ any adjacent recovery-rollup query, so hidden workload-route selectors do+ not hydrate storage/recovery transport on the protected hot path.6. Preserve API-owned node identity continuity in shared `internal/api/` helpers so storage and recovery transport attachments do not fork by hostname-versus-IP drift across the same runtime.7. Preserve fail-closed API assignment and lookup behavior in shared `internal/api/` helpers so storage and recovery surfaces do not inherit orphaned profile or resource references from unrelated transport mutations.8. Preserve canonical configured public endpoint selection in shared `internal/api/` helpers so recovery and storage links do not inherit loopback-local scheme drift from admin-originated setup/install flows.diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex dc2b7c131f..911a94b453 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -166,6 +166,11 @@ assembly branch.from the compact dashboard overview or resource snapshot they already own,but they must not reopen `useResources()` or start a second unfilteredunified-resource fetch path under the dashboard summary surface.+12. Keep shared selector hydration visibility-bound. Reusable shells such as+ `frontend-modern/src/components/shared/useInfrastructureSelectorState.ts`+ may consume `frontend-modern/src/hooks/useUnifiedResources.ts`, but hidden+ selectors must pass an explicit `enabled` gate instead of booting the+ `all-resources` transport behind a collapsed or non-rendered summary shell.## Forbidden Pathsdiff --git a/frontend-modern/src/components/Dashboard/__tests__/Dashboard.performance.contract.test.tsx b/frontend-modern/src/components/Dashboard/__tests__/Dashboard.performance.contract.test.tsxindex a92d9b4c85..cabaaa4529 100644--- a/frontend-modern/src/components/Dashboard/__tests__/Dashboard.performance.contract.test.tsx+++ b/frontend-modern/src/components/Dashboard/__tests__/Dashboard.performance.contract.test.tsx@@ -76,17 +76,24 @@ if (typeof globalThis.ResizeObserver === 'undefined') {let mockLocationSearch = '';let mockWorkloads: Array<Record<string, unknown>> = [];let setMockWorkloadsSignal: ((next: Array<Record<string, unknown>>) => void) | null = null;+const workloadsRefetchMock = vi.fn();let guestRowMountCount = 0;let guestRowUnmountCount = 0;let wsConnected = true;let wsInitialDataReceived = true;let wsReconnecting = false;+let setWsConnectedSignal: ((next: boolean) => void) | null = null;const pushMockWorkloads = (next: Array<Record<string, unknown>>) => {mockWorkloads = next;setMockWorkloadsSignal?.(next);};+const pushWsConnected = (next: boolean) => {+ wsConnected = next;+ setWsConnectedSignal?.(next);+};+vi.mock('@solidjs/router', async () => {const actual = await vi.importActual<typeof import('@solidjs/router')>('@solidjs/router');return {@@ -97,39 +104,43 @@ vi.mock('@solidjs/router', async () => {});vi.mock('@/contexts/appRuntime', () => ({- useWebSocket: () => ({- connected: () => wsConnected,- activeAlerts: () => ({}),- initialDataReceived: () => wsInitialDataReceived,- reconnecting: () => wsReconnecting,- reconnect: vi.fn(),- state: {- connectedInfrastructure: [],- metrics: [],- performance: {- apiCallDuration: {},- lastPollDuration: 0,- pollingStartTime: '',- totalApiCalls: 0,- failedApiCalls: 0,- cacheHits: 0,- cacheMisses: 0,- },- connectionHealth: {},- stats: {- startTime: '',- uptime: 0,- pollingCycles: 0,- webSocketClients: 0,- version: 'dev',+ useWebSocket: () => {+ const [connected, setConnected] = createSignal(wsConnected);+ setWsConnectedSignal = setConnected;+ return {+ connected,+ activeAlerts: () => ({}),+ initialDataReceived: () => wsInitialDataReceived,+ reconnecting: () => wsReconnecting,+ reconnect: vi.fn(),+ state: {+ connectedInfrastructure: [],+ metrics: [],+ performance: {+ apiCallDuration: {},+ lastPollDuration: 0,+ pollingStartTime: '',+ totalApiCalls: 0,+ failedApiCalls: 0,+ cacheHits: 0,+ cacheMisses: 0,+ },+ connectionHealth: {},+ stats: {+ startTime: '',+ uptime: 0,+ pollingCycles: 0,+ webSocketClients: 0,+ version: 'dev',+ },+ activeAlerts: [],+ recentlyResolved: [],+ lastUpdate: 0,+ resources: [],+ temperatureMonitoringEnabled: false,},- activeAlerts: [],- recentlyResolved: [],- lastUpdate: 0,- resources: [],- temperatureMonitoringEnabled: false,- },- }),+ };+ },}));vi.mock('@/hooks/useWorkloads', () => ({@@ -138,7 +149,7 @@ vi.mock('@/hooks/useWorkloads', () => ({setMockWorkloadsSignal = (next) => setWorkloads(next as any);return {workloads,- refetch: vi.fn(),+ refetch: (...args: unknown[]) => workloadsRefetchMock(...args),mutate: vi.fn(),loading: () => false,error: () => null,@@ -297,6 +308,11 @@ const expectedTypeDistribution = (count: number) => {const getGuestRowCount = (container: HTMLElement) =>container.querySelectorAll('tr[data-testid^="guest-row-"]').length;+const flushEffects = async () => {+ await Promise.resolve();+ await Promise.resolve();+};+describe('Dashboard performance contract', () => {beforeEach(() => {vi.clearAllMocks();@@ -304,6 +320,8 @@ describe('Dashboard performance contract', () => {mockLocationSearch = '';mockWorkloads = [];setMockWorkloadsSignal = null;+ setWsConnectedSignal = null;+ workloadsRefetchMock.mockReset();guestRowMountCount = 0;guestRowUnmountCount = 0;wsConnected = true;@@ -387,6 +405,48 @@ describe('Dashboard performance contract', () => {expect(getKubernetesContextKey(guest as any)).toBe('cluster-a');});++ it('does not treat the first websocket connection as a workload reconnect', async () => {+ mockLocationSearch = '?type=all';+ wsConnected = false;+ mockWorkloads = [makeGuest(1, { name: 'first-connect-workload' })];++ const { container } = render(() => (+ <Dashboard vms={[]} containers={[]} nodes={[]} useWorkloads />+ ));++ await waitFor(() => {+ expect(container.querySelector('table')).toBeInTheDocument();+ });+ expect(workloadsRefetchMock).not.toHaveBeenCalled();++ pushWsConnected(true);+ await flushEffects();++ expect(workloadsRefetchMock).not.toHaveBeenCalled();+ });++ it('refetches workloads only after a real websocket reconnect', async () => {+ mockLocationSearch = '?type=all';+ mockWorkloads = [makeGuest(1, { name: 'reconnect-workload' })];++ const { container } = render(() => (+ <Dashboard vms={[]} containers={[]} nodes={[]} useWorkloads />+ ));++ await waitFor(() => {+ expect(container.querySelector('table')).toBeInTheDocument();+ });+ workloadsRefetchMock.mockClear();++ pushWsConnected(false);+ await flushEffects();+ pushWsConnected(true);++ await waitFor(() => {+ expect(workloadsRefetchMock).toHaveBeenCalledTimes(1);+ });+ });});describe('Workload windowing contracts', () => {diff --git a/frontend-modern/src/components/Dashboard/useDashboardState.ts b/frontend-modern/src/components/Dashboard/useDashboardState.tsindex 4c6bc814c9..4ae1f2d56c 100644--- a/frontend-modern/src/components/Dashboard/useDashboardState.ts+++ b/frontend-modern/src/components/Dashboard/useDashboardState.ts@@ -165,10 +165,14 @@ export function useDashboardState(props: DashboardProps) {};let lastConnected = connected();+ let hasSeenConnectedState = connected();createEffect(() => {const isConnected = connected();- if (workloadsEnabled() && isConnected && !lastConnected) {- void workloads.refetch();+ if (isConnected) {+ if (workloadsEnabled() && !lastConnected && hasSeenConnectedState) {+ void workloads.refetch();+ }+ hasSeenConnectedState = true;}lastConnected = isConnected;});diff --git a/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts b/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.tsindex 37b67f068a..ec47aa1e6d 100644--- a/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts+++ b/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts@@ -762,7 +762,8 @@ describe('shared primitive guardrails', () => {expect(infrastructureSelectorSource).not.toContain('createSignal');expect(infrastructureSelectorSource).not.toContain("resource.type === 'truenas'");- expect(infrastructureSelectorStateSource).toContain('useResources');+ expect(infrastructureSelectorStateSource).toContain('useUnifiedResources');+ expect(infrastructureSelectorStateSource).toContain('enabled: showNodeSummary');expect(infrastructureSelectorStateSource).toContain('useRecoveryRollups');expect(infrastructureSelectorStateSource).toContain('createSignal');expect(infrastructureSelectorStateSource).toContain('document.addEventListener');diff --git a/frontend-modern/src/components/shared/__tests__/InfrastructureSelector.test.tsx b/frontend-modern/src/components/shared/__tests__/InfrastructureSelector.test.tsxindex cbc6468453..f41a6ec592 100644--- a/frontend-modern/src/components/shared/__tests__/InfrastructureSelector.test.tsx+++ b/frontend-modern/src/components/shared/__tests__/InfrastructureSelector.test.tsx@@ -7,6 +7,52 @@ import { InfrastructureSelector } from '@/components/shared/InfrastructureSelectimport { buildInfrastructureSelectorAgents } from '@/components/shared/infrastructureSelectorModel';import type { Resource } from '@/types/resource';+const useUnifiedResourcesMock = vi.fn(+ (options?: { enabled?: () => boolean }) => ({+ resources: () =>+ options?.enabled?.() === false+ ? []+ : [+ {+ id: 'node-1',+ type: 'agent',+ name: 'pve1',+ status: 'online',+ instance: 'main',+ uptime: 120,+ platformData: {+ type: 'node',+ node: 'pve1',+ instance: 'main',+ pveVersion: '8.0',+ cpu: 0.2,+ memory: { total: 8, used: 4, free: 4, usage: 50 },+ disk: { total: 100, used: 25, free: 75, usage: 25 },+ loadAverage: [0.1, 0.2, 0.3],+ },+ memory: { total: 8, used: 4, free: 4, current: 50 },+ agent: {+ platform: 'linux',+ memory: { total: 8, used: 4, free: 4, usage: 50 },+ disks: [],+ networkInterfaces: [],+ raid: [],+ },+ },+ ],+ refetch: vi.fn(),+ mutate: vi.fn(),+ loading: () => false,+ error: () => null,+ }),+);++const useRecoveryRollupsMock = vi.fn(+ (_query?: (() => unknown) | undefined) => ({+ rollups: () => [],+ }),+);+const infrastructureSummaryTableMock = vi.fn((props: { onNodeClick: (nodeId: string, nodeType: 'pve' | 'pbs') => void; selectedNode: string | null }) => (<button@@ -26,43 +72,12 @@ vi.mock('@/components/shared/InfrastructureSummaryTable', () => ({}) => infrastructureSummaryTableMock(props),}));-vi.mock('@/hooks/useResources', () => ({- useResources: () => ({- resources: () => [- {- id: 'node-1',- type: 'agent',- name: 'pve1',- status: 'online',- instance: 'main',- uptime: 120,- platformData: {- type: 'node',- node: 'pve1',- instance: 'main',- pveVersion: '8.0',- cpu: 0.2,- memory: { total: 8, used: 4, free: 4, usage: 50 },- disk: { total: 100, used: 25, free: 75, usage: 25 },- loadAverage: [0.1, 0.2, 0.3],- },- memory: { total: 8, used: 4, free: 4, current: 50 },- agent: {- platform: 'linux',- memory: { total: 8, used: 4, free: 4, usage: 50 },- disks: [],- networkInterfaces: [],- raid: [],- },- },- ],- }),+vi.mock('@/hooks/useUnifiedResources', () => ({+ useUnifiedResources: (options?: { enabled?: () => boolean }) => useUnifiedResourcesMock(options),}));vi.mock('@/hooks/useRecoveryRollups', () => ({- useRecoveryRollups: () => ({- rollups: () => [],- }),+ useRecoveryRollups: (query?: (() => unknown) | undefined) => useRecoveryRollupsMock(query),}));describe('InfrastructureSelector', () => {@@ -73,7 +88,8 @@ describe('InfrastructureSelector', () => {expect(infrastructureSelectorSource).not.toContain('createSignal');expect(infrastructureSelectorSource).not.toContain("resource.type === 'truenas'");- expect(infrastructureSelectorStateSource).toContain('useResources');+ expect(infrastructureSelectorStateSource).toContain('useUnifiedResources');+ expect(infrastructureSelectorStateSource).toContain('enabled: showNodeSummary');expect(infrastructureSelectorStateSource).toContain('useRecoveryRollups');expect(infrastructureSelectorStateSource).toContain('createSignal');expect(infrastructureSelectorStateSource).toContain('document.addEventListener');@@ -93,6 +109,26 @@ describe('InfrastructureSelector', () => {expect(infrastructureSelectorModelSource).toContain('isAgentFacetInfrastructureResource');});+ it('disables selector data hooks when the node summary is hidden', () => {+ render(() => <InfrastructureSelector currentTab="dashboard" showNodeSummary={false} />);++ expect(screen.queryByTestId('infrastructure-selector-table')).not.toBeInTheDocument();+ expect(useUnifiedResourcesMock).toHaveBeenCalledTimes(1);+ expect(useRecoveryRollupsMock).toHaveBeenCalledTimes(1);++ const unifiedOptions = useUnifiedResourcesMock.mock.calls[0]?.[0] as+ | { enabled?: () => boolean; query?: string; cacheKey?: string }+ | undefined;+ expect(unifiedOptions?.query).toBe('');+ expect(unifiedOptions?.cacheKey).toBe('all-resources');+ expect(unifiedOptions?.enabled?.()).toBe(false);++ const recoveryQuery = useRecoveryRollupsMock.mock.calls[0]?.[0] as+ | (() => unknown)+ | undefined;+ expect(recoveryQuery?.()).toBeNull();+ });+it('toggles node selection and clears it on escape', async () => {const onNodeSelect = vi.fn();diff --git a/frontend-modern/src/components/shared/useInfrastructureSelectorState.ts b/frontend-modern/src/components/shared/useInfrastructureSelectorState.tsindex dad71e362a..e9791fef4a 100644--- a/frontend-modern/src/components/shared/useInfrastructureSelectorState.ts+++ b/frontend-modern/src/components/shared/useInfrastructureSelectorState.ts@@ -1,6 +1,6 @@import { createEffect, createMemo, createSignal, onCleanup } from 'solid-js';import { useRecoveryRollups } from '@/hooks/useRecoveryRollups';-import { useResources } from '@/hooks/useResources';+import { useUnifiedResources } from '@/hooks/useUnifiedResources';import {buildInfrastructureSelectorAgents,buildInfrastructureSelectorBackupCounts,@@ -13,8 +13,14 @@ import {export type { InfrastructureSelectorProps } from './infrastructureSelectorModel';export function useInfrastructureSelectorState(props: InfrastructureSelectorProps) {- const { resources } = useResources();- const recovery = useRecoveryRollups();+ const showNodeSummary = createMemo(() => props.showNodeSummary ?? true);+ const unifiedResources = useUnifiedResources({+ query: '',+ cacheKey: 'all-resources',+ enabled: showNodeSummary,+ });+ const resources = createMemo(() => (showNodeSummary() ? unifiedResources.resources() : []));+ const recovery = useRecoveryRollups(() => (showNodeSummary() ? {} : null));const [selectedNode, setSelectedNode] = createSignal<string | null>(null);const unifiedNodes = createMemo(() => buildInfrastructureSelectorUnifiedNodes(resources()));@@ -70,9 +76,6 @@ export function useInfrastructureSelectorState(props: InfrastructureSelectorPropdocument.addEventListener('keydown', handleKeyDown);onCleanup(() => document.removeEventListener('keydown', handleKeyDown));});-- const showNodeSummary = () => props.showNodeSummary ?? true;-return {agentsForNodeSummary,backupCounts,@@ -82,7 +85,7 @@ export function useInfrastructureSelectorState(props: InfrastructureSelectorPropnodes,pbsInstances,selectedNode,- showNodeSummary,+ showNodeSummary: () => showNodeSummary(),storageCounts,vmCounts,};diff --git a/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.ts b/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.tsindex b54cb3dab0..795b9310b4 100644--- a/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.ts+++ b/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.ts@@ -264,6 +264,32 @@ describe('useUnifiedResources', () => {dispose();});+ it('skips unified resource hydration while disabled and resumes when enabled', async () => {+ let dispose = () => {};+ let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;+ const [enabled, setEnabled] = createSignal(false);++ createRoot((d) => {+ dispose = d;+ result = useUnifiedResources({+ query: '',+ cacheKey: 'all-resources',+ enabled,+ });+ });++ await flushAsync();+ expect(apiFetchMock).not.toHaveBeenCalled();+ expect(result!.loading()).toBe(false);++ setEnabled(true);+ await flushAsync();+ expect(apiFetchMock).toHaveBeenCalledTimes(1);+ await waitForResourceCount(() => result!.resources().length);++ dispose();+ });+it('falls back to REST when websocket initial hydration does not arrive in time', async () => {setWsConnected(false);setWsInitialDataReceived(false);diff --git a/frontend-modern/src/hooks/useUnifiedResources.ts b/frontend-modern/src/hooks/useUnifiedResources.tsindex 92962cef28..0807575a05 100644--- a/frontend-modern/src/hooks/useUnifiedResources.ts+++ b/frontend-modern/src/hooks/useUnifiedResources.ts@@ -1,4 +1,4 @@-import { batch, createEffect, createSignal, onCleanup } from 'solid-js';+import { batch, createEffect, createSignal, onCleanup, type Accessor } from 'solid-js';import { createStore, reconcile } from 'solid-js/store';import { canonicalizeMetricsHistoryTargetType } from '@/api/charts';import { readAPIErrorMessage } from '@/api/responseUtils';@@ -918,12 +918,14 @@ type UseUnifiedResourcesOptions = {query?: string;cacheKey?: string;initialHydration?: 'immediate' | 'prefer-ws';+ enabled?: Accessor<boolean>;};export function useUnifiedResources(options?: UseUnifiedResourcesOptions) {const query = normalizeUnifiedResourcesQuery(options?.query ?? DEFAULT_UNIFIED_RESOURCES_QUERY);const cacheKey = (options?.cacheKey || query || 'all').trim();const initialHydration = options?.initialHydration ?? 'immediate';+ const enabled = options?.enabled ?? (() => true);const typeFilter = parseUnifiedResourcesTypeFilter(query);const supportsCanonicalWsHydration = query === '' || typeFilter !== null;const prefersWsInitialHydration =@@ -966,6 +968,9 @@ export function useUnifiedResources(options?: UseUnifiedResourcesOptions) {force?: boolean;source?: 'initial' | 'ws' | 'manual';}) => {+ if (!enabled()) {+ return resources as unknown as Resource[];+ }if (inFlightRefetch) {return inFlightRefetch;}@@ -1015,7 +1020,12 @@ export function useUnifiedResources(options?: UseUnifiedResourcesOptions) {return request;};- const refetch = async () => runRefetch({ force: true, source: 'manual' });+ const refetch = async () => {+ if (!enabled()) {+ return resources as unknown as Resource[];+ }+ return runRefetch({ force: true, source: 'manual' });+ };const mutate = (value: Resource[] | ((prev: Resource[]) => Resource[])) => {const current = resources as unknown as Resource[];@@ -1031,6 +1041,13 @@ export function useUnifiedResources(options?: UseUnifiedResourcesOptions) {}};+ const clearRefreshTimeout = () => {+ if (refreshHandle !== undefined) {+ clearTimeout(refreshHandle);+ refreshHandle = undefined;+ }+ };+const shouldPreferWsInitialHydration = () =>prefersWsInitialHydration &&!cacheEntry.hasSnapshot &&@@ -1052,21 +1069,8 @@ export function useUnifiedResources(options?: UseUnifiedResourcesOptions) {}, UNIFIED_RESOURCES_WS_INITIAL_HYDRATION_WAIT_MS);};- // If cache is stale, refresh it in the background without blocking initial render.- if (!hasFreshUnifiedResourcesCache(cacheEntry)) {- if (shouldPreferWsInitialHydration()) {- scheduleInitialHydrationFallback();- } else {- void runRefetch({ source: 'initial' }).catch((err) => {- logger.warn('[useUnifiedResources] Failed background refresh for stale cache', err);- });- }- }-const scheduleRefetch = () => {- if (refreshHandle !== undefined) {- clearTimeout(refreshHandle);- }+ clearRefreshTimeout();const elapsedSinceFetch = Date.now() - cacheEntry.lastFetchAt;const minIntervalDelay = Math.max(@@ -1083,8 +1087,36 @@ export function useUnifiedResources(options?: UseUnifiedResourcesOptions) {}, delay);};+ createEffect(() => {+ orgScope();++ if (!enabled()) {+ clearInitialHydrationTimeout();+ clearRefreshTimeout();+ setLoading(false);+ return;+ }++ if (hasFreshUnifiedResourcesCache(cacheEntry)) {+ clearInitialHydrationTimeout();+ return;+ }++ if (shouldPreferWsInitialHydration()) {+ scheduleInitialHydrationFallback();+ return;+ }++ void runRefetch({ source: 'initial' }).catch((err) => {+ logger.warn('[useUnifiedResources] Failed background refresh for stale cache', err);+ });+ });+createEffect(() => {const currentOrgScope = orgScope();+ if (!enabled()) {+ return;+ }if (!supportsCanonicalWsHydration) {return;}@@ -1130,6 +1162,14 @@ export function useUnifiedResources(options?: UseUnifiedResourcesOptions) {createEffect(() => {orgScope();+ if (!enabled()) {+ wsInitialized = false;+ lastWsUpdateToken = '';+ clearInitialHydrationTimeout();+ clearRefreshTimeout();+ return;+ }+if (!wsStore.connected() || !wsStore.initialDataReceived()) {wsInitialized = false;lastWsUpdateToken = '';@@ -1183,10 +1223,10 @@ export function useUnifiedResources(options?: UseUnifiedResourcesOptions) {batch(() => {setError(undefined);setResources(reconcile(scopedResources, { key: 'id' }));- setLoading(!cacheEntry.hasSnapshot);+ setLoading(enabled() && !cacheEntry.hasSnapshot);});- if (!hasFreshUnifiedResourcesCache(cacheEntry)) {+ if (enabled() && !hasFreshUnifiedResourcesCache(cacheEntry)) {if (shouldPreferWsInitialHydration()) {scheduleInitialHydrationFallback();} else {@@ -1198,9 +1238,7 @@ export function useUnifiedResources(options?: UseUnifiedResourcesOptions) {onCleanup(() => {unsubscribeOrgSwitch();clearInitialHydrationTimeout();- if (refreshHandle !== undefined) {- clearTimeout(refreshHandle);- }+ clearRefreshTimeout();});return {diff --git a/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts b/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.tsindex c9e31faa01..4bd7eea813 100644--- a/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts+++ b/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts@@ -284,6 +284,7 @@ import useStoragePageBannerModelSource from '@/components/Storage/useStoragePageimport storagePageBannersSource from '@/components/Storage/StoragePageBanners.tsx?raw';import useStoragePageBannersModelSource from '@/components/Storage/useStoragePageBannersModel.ts?raw';import storageSummarySource from '@/components/Storage/StorageSummary.tsx?raw';+import storageSummaryCacheSource from '@/utils/storageSummaryCache.ts?raw';import storagePageSummarySource from '@/components/Storage/StoragePageSummary.tsx?raw';import storageCephSummaryCardSource from '@/components/Storage/StorageCephSummaryCard.tsx?raw';import useStorageCephSummaryCardModelSource from '@/components/Storage/useStorageCephSummaryCardModel.ts?raw';@@ -980,7 +981,7 @@ describe('frontend resource type boundaries', () => {"isAwaitingFirstSample() ? 'Waiting for first sample' : 'No history yet'",);expect(infrastructureSummaryStateSource).not.toContain("getOrgID() || 'default'");- expect(storageSummarySource).toContain('normalizeOrgScope(getOrgID())');+ expect(storageSummaryCacheSource).toContain('normalizeOrgScope(getOrgID())');expect(storageSummarySource).not.toContain("getOrgID() || 'default'");expect(guestRowSource).toContain('useGuestRowState');expect(guestRowSource).toContain("from './GuestRowCells'");@@ -3131,7 +3132,8 @@ describe('frontend resource type boundaries', () => {expect(infrastructureSelectorSource).not.toContain('useResources');expect(infrastructureSelectorSource).not.toContain('createSignal');expect(infrastructureSelectorSource).not.toContain("resource.type === 'truenas'");- expect(infrastructureSelectorStateSource).toContain('useResources');+ expect(infrastructureSelectorStateSource).toContain('useUnifiedResources');+ expect(infrastructureSelectorStateSource).toContain('enabled: showNodeSummary');expect(infrastructureSelectorStateSource).toContain('useRecoveryRollups');expect(infrastructureSelectorStateSource).toContain('createSignal');expect(infrastructureSelectorStateSource).toContain('document.addEventListener');