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
Extract dashboard state owner
rcourtmand94d4b8b9749
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex 6f1124290a..dfeebcb5e4 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -26,13 +26,14 @@ regression protection.4. `internal/api/slo.go`5. `internal/api/slo_bench_test.go`6. `frontend-modern/src/components/Dashboard/Dashboard.tsx`-7. `frontend-modern/src/components/Dashboard/workloadSelectors.ts`-8. `frontend-modern/src/components/Infrastructure/UnifiedResourceTable.tsx`-9. `frontend-modern/src/components/Infrastructure/useUnifiedResourceTableState.ts`-10. `frontend-modern/src/components/Infrastructure/infrastructureSelectors.ts`-11. `frontend-modern/src/components/Infrastructure/resourceDetailMappers.ts`-12. `frontend-modern/src/components/Dashboard/__tests__/Dashboard.performance.contract.test.tsx`-13. `frontend-modern/src/components/Infrastructure/__tests__/UnifiedResourceTable.performance.contract.test.tsx`+7. `frontend-modern/src/components/Dashboard/useDashboardState.ts`+8. `frontend-modern/src/components/Dashboard/workloadSelectors.ts`+9. `frontend-modern/src/components/Infrastructure/UnifiedResourceTable.tsx`+10. `frontend-modern/src/components/Infrastructure/useUnifiedResourceTableState.ts`+11. `frontend-modern/src/components/Infrastructure/infrastructureSelectors.ts`+12. `frontend-modern/src/components/Infrastructure/resourceDetailMappers.ts`+13. `frontend-modern/src/components/Dashboard/__tests__/Dashboard.performance.contract.test.tsx`+14. `frontend-modern/src/components/Infrastructure/__tests__/UnifiedResourceTable.performance.contract.test.tsx`## Shared Boundaries@@ -79,6 +80,11 @@ The dashboard workload selector path and the dashboard runtime that consumes itare now part of the protected performance surface rather than proof-onlycontext. Future hot-path filter/group/sort/windowing changes must route throughthe explicit dashboard performance proof policy in the subsystem registry.+That runtime state owner now lives in+`frontend-modern/src/components/Dashboard/useDashboardState.ts`, so guest+metadata persistence, workload-route synchronization, grouping/windowing, and+filter/sort state must extend through that owner instead of accreting back into+`frontend-modern/src/components/Dashboard/Dashboard.tsx`.The unified resource table hot path is now also governed as explicitperformance-owned runtime, with shared ownership against the unified-resourcediff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.jsonindex 72a58ac87a..7d0521fc84 100644--- a/docs/release-control/v6/internal/subsystems/registry.json+++ b/docs/release-control/v6/internal/subsystems/registry.json@@ -2166,6 +2166,7 @@],"owned_files": ["frontend-modern/src/components/Dashboard/Dashboard.tsx",+ "frontend-modern/src/components/Dashboard/useDashboardState.ts","frontend-modern/src/components/Dashboard/workloadSelectors.ts","frontend-modern/src/components/Infrastructure/infrastructureSelectors.ts","frontend-modern/src/components/Infrastructure/resourceDetailMappers.ts",@@ -2210,6 +2211,7 @@"match_prefixes": [],"match_files": ["frontend-modern/src/components/Dashboard/Dashboard.tsx",+ "frontend-modern/src/components/Dashboard/useDashboardState.ts","frontend-modern/src/components/Dashboard/workloadSelectors.ts","frontend-modern/src/components/Infrastructure/infrastructureSelectors.ts","frontend-modern/src/components/Infrastructure/resourceDetailMappers.ts",diff --git a/frontend-modern/src/components/Dashboard/Dashboard.tsx b/frontend-modern/src/components/Dashboard/Dashboard.tsxindex 9d796352ea..23e120ecff 100644--- a/frontend-modern/src/components/Dashboard/Dashboard.tsx+++ b/frontend-modern/src/components/Dashboard/Dashboard.tsx@@ -1,27 +1,10 @@-import {- createSignal,- createMemo,- createEffect,- For,- Index,- Show,- onMount,- onCleanup,- untrack,-} from 'solid-js';-import { useLocation, useNavigate } from '@solidjs/router';-import type { VM, Container, Node } from '@/types/api';-import type { WorkloadGuest, ViewMode } from '@/types/workloads';-import { GuestRow, GUEST_COLUMNS, VIEW_MODE_COLUMNS } from './GuestRow';+import { createMemo, For, Index, Show } from 'solid-js';+import { GuestRow } from './GuestRow';import { GuestDrawer } from './GuestDrawer';-import { useWebSocket } from '@/App';import { getAlertStyles } from '@/utils/alerts';-import { useAlertsActivation } from '@/stores/alertsActivation';import { ComponentErrorBoundary } from '@/components/ErrorBoundary';import { InfrastructureSelector } from '@/components/shared/InfrastructureSelector';import { DashboardFilter } from './DashboardFilter';-import { GuestMetadataAPI } from '@/api/guestMetadata';-import type { GuestMetadata } from '@/api/guestMetadata';import { Card } from '@/components/shared/Card';import {Table,@@ -34,1317 +17,90 @@ import {import { EmptyState } from '@/components/shared/EmptyState';import { NodeGroupHeader } from '@/components/shared/NodeGroupHeader';import { isNodeOnline } from '@/utils/status';-import { getNodeDisplayName } from '@/utils/nodes';-import { logger } from '@/utils/logger';-import { usePersistentSignal } from '@/hooks/usePersistentSignal';-import { useColumnVisibility } from '@/hooks/useColumnVisibility';-import { useBreakpoint } from '@/hooks/useBreakpoint';-import { blurFocusedTypeToSearch } from '@/hooks/useTypeToSearch';-import { useWorkloads } from '@/hooks/useWorkloads';-import { STORAGE_KEYS } from '@/utils/localStorage';-import { getOrgID } from '@/utils/apiClient';-import { normalizeOrgScope } from '@/utils/orgScope';-import { aiChatStore } from '@/stores/aiChat';-import { eventBus } from '@/stores/events';-import { useKioskMode } from '@/hooks/useKioskMode';-import {- getDashboardDisconnectedState,- getDashboardGuestsEmptyState,- getDashboardInfrastructureEmptyState,- getDashboardLoadingState,-} from '@/utils/dashboardEmptyStatePresentation';-import {- getCanonicalWorkloadId,- normalizeWorkloadViewModeParam,- resolveWorkloadType,-} from '@/utils/workloads';-import {- WorkloadsSummary,- type WorkloadSummarySnapshot,-} from '@/components/Workloads/WorkloadsSummary';-import { isSummaryTimeRange } from '@/components/shared/summaryTimeRange';-import {- buildWorkloadsPath,- parseWorkloadsLinkSearch,- WORKLOADS_PATH,- WORKLOADS_QUERY_PARAMS,-} from '@/routing/resourceLinks';-import { areSearchParamsEquivalent } from '@/utils/searchParams';+import { getCanonicalWorkloadId } from '@/utils/workloads';+import { WorkloadsSummary } from '@/components/Workloads/WorkloadsSummary';import { ScrollToTopButton } from '@/components/shared/ScrollToTopButton';-import {- workloadNodeScopeId,- getKubernetesContextKey,- filterWorkloads,- getDiskUsagePercent,- createWorkloadSortComparator,- getWorkloadGroupKey,- groupWorkloads,- computeWorkloadStats,- computeWorkloadIOEmphasis,- buildNodeByInstance,- buildGuestParentNodeMap,- type FilterWorkloadsParams,- type WorkloadStats,-} from './workloadSelectors';-import { useGroupedTableWindowing } from './useGroupedTableWindowing';--type GuestMetadataRecord = Record<string, GuestMetadata>;-type IdleCallbackHandle = number;-type IdleCallback = (deadline?: { didTimeout: boolean; timeRemaining: () => number }) => void;-type IdleCapableWindow = Window & {- requestIdleCallback?: (- callback: IdleCallback,- options?: { timeout?: number },- ) => IdleCallbackHandle;- cancelIdleCallback?: (handle: IdleCallbackHandle) => void;-};--let cachedGuestMetadata: GuestMetadataRecord | null = null;-let cachedGuestMetadataStorageKey: string | null = null;-let lastPersistedGuestMetadataJSON: string | null = null;-let lastPersistedGuestMetadataStorageKey: string | null = null;-let pendingPersistMetadata: GuestMetadataRecord | null = null;-let pendingPersistStorageKey: string | null = null;-let persistHandle: number | null = null;-let persistHandleType: 'idle' | 'timeout' | null = null;--const guestMetadataStorageKeyForOrg = (orgScope: string): string =>- `${STORAGE_KEYS.GUEST_METADATA}.${encodeURIComponent(orgScope)}`;--const instrumentationEnabled = import.meta.env.DEV && typeof performance !== 'undefined';-const DASHBOARD_TABLE_ESTIMATED_ROW_HEIGHT = 32;--const workloadMetricPercent = (value: number | null | undefined): number => {- if (typeof value !== 'number' || !Number.isFinite(value)) return 0;- if (value <= 1) return Math.max(0, value * 100);- return Math.max(0, value);-};--const readGuestMetadataCache = (storageKey: string): GuestMetadataRecord => {- if (cachedGuestMetadata && cachedGuestMetadataStorageKey === storageKey) {- return cachedGuestMetadata;- }-- if (typeof window === 'undefined') {- cachedGuestMetadata = {};- cachedGuestMetadataStorageKey = storageKey;- return cachedGuestMetadata;- }-- try {- const raw = window.localStorage.getItem(storageKey);- if (!raw) {- cachedGuestMetadata = {};- cachedGuestMetadataStorageKey = storageKey;- lastPersistedGuestMetadataJSON = null;- lastPersistedGuestMetadataStorageKey = storageKey;- return cachedGuestMetadata;- }- const parsed = JSON.parse(raw);- if (parsed && typeof parsed === 'object') {- cachedGuestMetadata = parsed as GuestMetadataRecord;- cachedGuestMetadataStorageKey = storageKey;- lastPersistedGuestMetadataJSON = raw;- lastPersistedGuestMetadataStorageKey = storageKey;- return cachedGuestMetadata;- }- } catch (err) {- logger.warn('Failed to parse cached guest metadata', err);- }-- cachedGuestMetadata = {};- cachedGuestMetadataStorageKey = storageKey;- lastPersistedGuestMetadataJSON = null;- lastPersistedGuestMetadataStorageKey = storageKey;- return cachedGuestMetadata;-};--const clearPendingPersistHandle = (idleWindow: IdleCapableWindow) => {- if (persistHandle === null || persistHandleType === null) {- return;- }-- if (persistHandleType === 'idle' && idleWindow.cancelIdleCallback) {- idleWindow.cancelIdleCallback(persistHandle);- } else if (persistHandleType === 'timeout') {- window.clearTimeout(persistHandle);- }-- persistHandle = null;- persistHandleType = null;-};--const runGuestMetadataPersist = () => {- if (typeof window === 'undefined' || !pendingPersistMetadata || !pendingPersistStorageKey) {- pendingPersistMetadata = null;- pendingPersistStorageKey = null;- return;- }-- const metadata = pendingPersistMetadata;- const storageKey = pendingPersistStorageKey;- pendingPersistMetadata = null;- pendingPersistStorageKey = null;-- const markBase = instrumentationEnabled ? `guest-metadata:persist:${Date.now()}` : null;- if (markBase) {- performance.mark(`${markBase}:start`);- }-- let serialized: string;- try {- serialized = JSON.stringify(metadata);- } catch (err) {- if (markBase) {- performance.mark(`${markBase}:end`);- performance.measure(markBase, `${markBase}:start`, `${markBase}:end`);- performance.clearMarks(`${markBase}:start`);- performance.clearMarks(`${markBase}:end`);- performance.clearMeasures(markBase);- }- logger.warn('Failed to serialize guest metadata cache', err);- return;- }+import { useDashboardState, type DashboardProps, type WorkloadSortKey } from './useDashboardState';- if (- serialized === lastPersistedGuestMetadataJSON &&- storageKey === lastPersistedGuestMetadataStorageKey- ) {- if (markBase) {- performance.mark(`${markBase}:end`);- performance.measure(markBase, `${markBase}:start`, `${markBase}:end`);- const entries = performance.getEntriesByName(markBase);- const entry = entries[entries.length - 1];- if (entry) {- logger.debug('[guestMetadataCache] skipped persist (unchanged)', {- durationMs: entry.duration,- });- }- performance.clearMarks(`${markBase}:start`);- performance.clearMarks(`${markBase}:end`);- performance.clearMeasures(markBase);- }- return;- }-- try {- window.localStorage.setItem(storageKey, serialized);- lastPersistedGuestMetadataJSON = serialized;- lastPersistedGuestMetadataStorageKey = storageKey;- if (markBase) {- performance.mark(`${markBase}:end`);- performance.measure(markBase, `${markBase}:start`, `${markBase}:end`);- const entries = performance.getEntriesByName(markBase);- const entry = entries[entries.length - 1];- if (entry) {- logger.debug('[guestMetadataCache] persisted entries', {- count: Object.keys(metadata).length,- durationMs: entry.duration,- });- }- performance.clearMarks(`${markBase}:start`);- performance.clearMarks(`${markBase}:end`);- performance.clearMeasures(markBase);- }- } catch (err) {- if (markBase) {- performance.mark(`${markBase}:end`);- performance.measure(markBase, `${markBase}:start`, `${markBase}:end`);- performance.clearMarks(`${markBase}:start`);- performance.clearMarks(`${markBase}:end`);- performance.clearMeasures(markBase);- }- logger.warn('Failed to persist guest metadata cache', err);- }-};--const queueGuestMetadataPersist = (storageKey: string, metadata: GuestMetadataRecord) => {- cachedGuestMetadata = metadata;- cachedGuestMetadataStorageKey = storageKey;-- if (typeof window === 'undefined') {- return;- }-- pendingPersistMetadata = metadata;- pendingPersistStorageKey = storageKey;- const idleWindow = window as IdleCapableWindow;-- clearPendingPersistHandle(idleWindow);-- const schedule: IdleCallback = () => {- persistHandle = null;- persistHandleType = null;- runGuestMetadataPersist();- };-- if (idleWindow.requestIdleCallback) {- persistHandleType = 'idle';- persistHandle = idleWindow.requestIdleCallback(schedule, { timeout: 750 });- } else {- persistHandleType = 'timeout';- persistHandle = window.setTimeout(schedule, 0);- }-};--interface DashboardProps {- vms: VM[];- containers: Container[];- nodes: Node[];- useWorkloads?: boolean;-}--type StatusMode = 'all' | 'running' | 'degraded' | 'stopped';-type GroupingMode = 'grouped' | 'flat';-type WorkloadSortKey = keyof WorkloadGuest | 'diskIo' | 'netIo';export function Dashboard(props: DashboardProps) {- const navigate = useNavigate();- const location = useLocation();- const ws = useWebSocket();- const { connected, activeAlerts, initialDataReceived, reconnecting, reconnect } = ws;- const { isMobile } = useBreakpoint();- const alertsActivation = useAlertsActivation();- const alertsEnabled = createMemo(() => alertsActivation.activationState() === 'active');- const isWorkloadsRoute = () => location.pathname === WORKLOADS_PATH;- const [search, setSearch] = createSignal('');-- const kioskMode = useKioskMode();- const dashboardInfrastructureEmptyState = createMemo(() => getDashboardInfrastructureEmptyState());- const dashboardGuestsEmptyState = createMemo(() =>- getDashboardGuestsEmptyState(search()),- );- const dashboardLoadingState = createMemo(() => getDashboardLoadingState(reconnecting()));- const dashboardDisconnectedState = createMemo(() => getDashboardDisconnectedState(reconnecting()));-- const [isSearchLocked, setIsSearchLocked] = createSignal(false);- const [selectedNode, setSelectedNode] = createSignal<string | null>(null);- const [selectedKubernetesContext, setSelectedKubernetesContext] = createSignal<string | null>(- null,- );- const [selectedKubernetesNamespace, setSelectedKubernetesNamespace] = createSignal<string | null>(- null,- );- const [selectedGuestId, setSelectedGuestIdRaw] = createSignal<string | null>(null);- const [hoveredWorkloadId, setHoveredWorkloadId] = createSignal<string | null>(null);- const [handledResourceId, setHandledResourceId] = createSignal<string | null>(null);- const [handledTypeParam, setHandledTypeParam] = createSignal<string>('');- const [handledRuntimeParam, setHandledRuntimeParam] = createSignal<string>('');- const [handledContextParam, setHandledContextParam] = createSignal('');- const [handledNamespaceParam, setHandledNamespaceParam] = createSignal('');- const [handledAgentParam, setHandledAgentParam] = createSignal('');- const [selectedHostHint, setSelectedHostHint] = createSignal<string | null>(null);-- // URL-sync can legitimately require multiple reactive updates (e.g. normalizing- // type aliases, dropping irrelevant params). If we- // call navigate() synchronously for each intermediate state, Solid Router will- // treat it as a redirect chain and can throw "Too many redirects".- //- // Coalesce URL sync into a single replace-navigation per tick.- let pendingUrlSyncHandle: number | null = null;- let pendingUrlSyncPath: string | null = null;- const scheduleUrlSyncNavigate = (nextPath: string) => {- pendingUrlSyncPath = nextPath;- if (pendingUrlSyncHandle !== null) return;- pendingUrlSyncHandle = window.setTimeout(() => {- pendingUrlSyncHandle = null;- const target = pendingUrlSyncPath;- pendingUrlSyncPath = null;- if (!target) return;- const current = `${untrack(() => location.pathname)}${untrack(() => location.search)}`;- if (current === target) return;- navigate(target, { replace: true });- }, 0);- };- onCleanup(() => {- if (pendingUrlSyncHandle !== null) {- window.clearTimeout(pendingUrlSyncHandle);- pendingUrlSyncHandle = null;- pendingUrlSyncPath = null;- }- });-- createEffect(() => {- const { resource: resourceId } = parseWorkloadsLinkSearch(location.search);- if (!resourceId || resourceId === handledResourceId()) return;- setSelectedGuestId(resourceId);- const [instance, node, vmid] = resourceId.split(':');- if (instance && node && vmid) {- setSelectedNode(`${instance}-${node}`);- }- setHandledResourceId(resourceId);- });-- // Wrap setSelectedGuestId to preserve scroll position. Opening/closing the- // drawer mounts/unmounts GuestDrawer (which contains DiscoveryTab). The- // DiscoveryTab initialization triggers SolidJS to recreate the <For> row,- // which detaches/reattaches DOM and resets the scroll container's scrollTop.- // We find the scroll container, save its position, and restore it after.- let tableRef: HTMLDivElement | undefined;- const [tableBodyRef, setTableBodyRef] = createSignal<HTMLTableSectionElement | null>(null);- const setSelectedGuestId = (id: string | null) => {- // Find the nearest ancestor scroll container from the table- let scroller: HTMLElement | null = tableRef ?? null;- while (scroller) {- const { overflowY } = getComputedStyle(scroller);- if (- (overflowY === 'auto' || overflowY === 'scroll') &&- scroller.scrollHeight > scroller.clientHeight- ) {- break;- }- scroller = scroller.parentElement;- }- const scrollTop = scroller?.scrollTop ?? 0;- setSelectedGuestIdRaw(id);- // Restore scroll position — opening the drawer can cause layout changes- if (scroller) scroller.scrollTop = scrollTop;- requestAnimationFrame(() => {- if (scroller) scroller.scrollTop = scrollTop;- });- };- const [orgScope, setOrgScope] = createSignal(normalizeOrgScope(getOrgID()));- const guestMetadataStorageKey = createMemo(() => guestMetadataStorageKeyForOrg(orgScope()));- const [guestMetadata, setGuestMetadata] = createSignal<GuestMetadataRecord>(- readGuestMetadataCache(guestMetadataStorageKey()),- );-- createEffect(() => {- const storageKey = guestMetadataStorageKey();- setGuestMetadata(readGuestMetadataCache(storageKey));- });-- const updateGuestMetadataState = (updater: (prev: GuestMetadataRecord) => GuestMetadataRecord) =>- setGuestMetadata((prev) => {- const next = updater(prev);- if (next === prev) {- return prev;- }- queueGuestMetadataPersist(guestMetadataStorageKey(), next);- return next;- });-- const workloadsEnabled = createMemo(() => props.useWorkloads === true);- const workloads = useWorkloads(workloadsEnabled);-- // Keep workload identities stable across polling updates.- const dedupeGuests = (guests: WorkloadGuest[]): WorkloadGuest[] => {- const seen = new Set<string>();- const deduped: WorkloadGuest[] = [];- for (const guest of guests) {- const canonicalId = getCanonicalWorkloadId(guest);- if (seen.has(canonicalId)) continue;- seen.add(canonicalId);- deduped.push(guest);- }- return deduped;- };-- const allGuests = createMemo<WorkloadGuest[]>(() =>- workloadsEnabled() ? dedupeGuests(workloads.workloads()) : [],- );-- const workloadNodeOptions = createMemo(() => {- const labelsByScope = new Map<string, string>();- const nodeNameCounts = new Map<string, number>();-- for (const guest of allGuests()) {- const type = resolveWorkloadType(guest);- if (type === 'pod') continue;- const scope = workloadNodeScopeId(guest);- if (!scope || scope === '-') continue;- const nodeName = (guest.node || '').trim();- if (!nodeName) continue;- nodeNameCounts.set(nodeName, (nodeNameCounts.get(nodeName) || 0) + 1);- }-- for (const guest of allGuests()) {- const type = resolveWorkloadType(guest);- if (type === 'pod') continue;- const scope = workloadNodeScopeId(guest);- if (!scope || scope === '-' || labelsByScope.has(scope)) continue;- const nodeName = (guest.node || '').trim();- const instance = (guest.instance || '').trim();- if (!nodeName) continue;- const hasDuplicateNodeName = (nodeNameCounts.get(nodeName) || 0) > 1;- const label = hasDuplicateNodeName && instance ? `${nodeName} (${instance})` : nodeName;- labelsByScope.set(scope, label);- }-- return Array.from(labelsByScope.entries())- .map(([value, label]) => ({ value, label }))- .sort((a, b) => a.label.localeCompare(b.label));- });-- createEffect(() => {- if (viewMode() === 'pod') return;- const hostHint = selectedHostHint();- if (!hostHint || selectedNode() !== null) return;- const normalizedHint = hostHint.trim().toLowerCase();- if (!normalizedHint) return;- const option = workloadNodeOptions().find((candidate) => {- const label = candidate.label.toLowerCase();- const value = candidate.value.toLowerCase();- return label === normalizedHint || value === normalizedHint || label.includes(normalizedHint);- });- if (!option) return;- setSelectedNode(option.value);- setSelectedHostHint(null);- });-- const kubernetesContextOptions = createMemo(() => {- const contexts = new Set<string>();- for (const guest of allGuests()) {- if (resolveWorkloadType(guest) !== 'pod') continue;- const context = getKubernetesContextKey(guest);- if (context) {- contexts.add(context);- }- }- return Array.from(contexts).sort((a, b) => a.localeCompare(b));- });-- const kubernetesNamespaceOptions = createMemo(() => {- const namespaces = new Set<string>();- const contextFilter = (selectedKubernetesContext() || '').trim();- for (const guest of allGuests()) {- if (resolveWorkloadType(guest) !== 'pod') continue;- if (contextFilter && getKubernetesContextKey(guest) !== contextFilter) continue;- const ns = (guest.namespace || '').trim();- if (ns) namespaces.add(ns);- }- return Array.from(namespaces).sort((a, b) => a.localeCompare(b));- });-- createEffect(() => {- if (!isWorkloadsRoute()) return;- if (viewMode() !== 'pod') return;- const selected = (selectedKubernetesNamespace() || '').trim();- if (!selected) return;- const normalized = selected.toLowerCase();- const exists = kubernetesNamespaceOptions().some((value) => value.toLowerCase() === normalized);- if (!exists) {- setSelectedKubernetesNamespace(null);- }- });-- const containerRuntimeOptions = createMemo(() => {- const runtimes = new Set<string>();- for (const guest of allGuests()) {- if (resolveWorkloadType(guest) !== 'app-container') continue;- const runtime = (guest.containerRuntime || '').trim();- if (runtime) {- runtimes.add(runtime);- }- }- return Array.from(runtimes).sort((a, b) => a.localeCompare(b));- });-- // Initialize from localStorage with proper type checking- const [viewMode, setViewMode] = usePersistentSignal<ViewMode>('dashboardViewMode', 'all', {- deserialize: (raw) => normalizeWorkloadViewModeParam(raw) ?? 'all',- });-- const [containerRuntime, setContainerRuntime] = usePersistentSignal<string>(- 'dashboardContainerRuntime',- '',- {- deserialize: (raw) => (typeof raw === 'string' ? raw : ''),- serialize: (value) => value,- },- );-- createEffect(() => {- if (!isWorkloadsRoute()) return;- if (viewMode() !== 'app-container') return;- const selected = containerRuntime().trim();- if (!selected) return;- const normalized = selected.toLowerCase();- const exists = containerRuntimeOptions().some((value) => value.toLowerCase() === normalized);- if (!exists) {- setContainerRuntime('');- }- });-- createEffect(() => {- if (!isWorkloadsRoute()) return;- if (viewMode() === 'pod') {- if (selectedNode() !== null) {- setSelectedNode(null);- }- if (selectedHostHint() !== null) {- setSelectedHostHint(null);- }- return;- }- if (selectedKubernetesContext() !== null) {- setSelectedKubernetesContext(null);- }- if (selectedKubernetesNamespace() !== null) {- setSelectedKubernetesNamespace(null);- }- });-- createEffect(() => {- if (!isWorkloadsRoute()) return;- if (viewMode() !== 'app-container' && containerRuntime().trim() !== '') {- setContainerRuntime('');- }- });-- createEffect(() => {- const parsed = parseWorkloadsLinkSearch(location.search);- const typeParam = parsed.type;- const normalizedType = typeParam ?? '';- if (normalizedType === handledTypeParam()) return;-- if (!normalizedType) {- setHandledTypeParam('');- return;- }-- // Context/namespace implies pod view; ignore conflicting type params.- const hasK8sScope =- Boolean((parsed.context ?? '').trim()) || Boolean((parsed.namespace ?? '').trim());- const nextMode = normalizeWorkloadViewModeParam(normalizedType);- if (!nextMode) {- setHandledTypeParam(normalizedType);- return;- }- if (hasK8sScope && nextMode !== 'pod') {- setHandledTypeParam(normalizedType);- return;- }-- setViewMode(nextMode);- setHandledTypeParam(normalizedType);- });-- createEffect(() => {- const { context: contextParam } = parseWorkloadsLinkSearch(location.search);- const normalized = contextParam ?? '';- if (normalized === handledContextParam()) return;-- if (normalized) {- if (viewMode() !== 'pod') {- setViewMode('pod');- }- setSelectedKubernetesContext(normalized);- if (!showFilters()) {- setShowFilters(true);- }- setHandledContextParam(normalized);- return;- }-- setSelectedKubernetesContext(null);- setHandledContextParam('');- });-- createEffect(() => {- const { namespace: namespaceParam } = parseWorkloadsLinkSearch(location.search);- const normalized = namespaceParam ?? '';- if (normalized === handledNamespaceParam()) return;-- if (normalized) {- if (viewMode() !== 'pod') {- setViewMode('pod');- }- setSelectedKubernetesNamespace(normalized);- if (!showFilters()) {- setShowFilters(true);- }- setHandledNamespaceParam(normalized);- return;- }-- setSelectedKubernetesNamespace(null);- setHandledNamespaceParam('');- });-- createEffect(() => {- const { agent: agentParam } = parseWorkloadsLinkSearch(location.search);- const normalized = agentParam ?? '';- if (normalized === handledAgentParam()) return;-- if (normalized) {- setSelectedHostHint(normalized);- if (!showFilters()) {- setShowFilters(true);- }- setHandledAgentParam(normalized);- return;- }-- setSelectedHostHint(null);- if (selectedNode() !== null) {- setSelectedNode(null);- }- setHandledAgentParam('');- });-- createEffect(() => {- const parsed = parseWorkloadsLinkSearch(location.search);- const urlRuntime = parsed.runtime ?? '';- if (urlRuntime === handledRuntimeParam()) return;-- const urlContext = parsed.context ?? '';- const hasContext = Boolean(urlContext.trim());- const hasNamespace = Boolean((parsed.namespace ?? '').trim());- const urlType = parsed.type ?? '';- const nextMode = normalizeWorkloadViewModeParam(urlType);- const runtimeRelevant =- !hasContext && !hasNamespace && (nextMode === 'app-container' || !urlType.trim());-- // Ignore runtime param outside of container views, but still mark it handled so URL-sync can clean it up.- if (!runtimeRelevant) {- setHandledRuntimeParam(urlRuntime);- return;- }-- if (!urlRuntime.trim()) {- setContainerRuntime('');- setHandledRuntimeParam('');- return;- }-- if (viewMode() !== 'app-container') {- setViewMode('app-container');- }- setContainerRuntime(urlRuntime);- if (!showFilters()) {- setShowFilters(true);- }- setHandledRuntimeParam(urlRuntime);- });-- createEffect(() => {- if (!isWorkloadsRoute()) return;-- const parsed = parseWorkloadsLinkSearch(location.search);- const urlType = parsed.type ?? '';- const urlRuntime = parsed.runtime ?? '';- const urlContext = parsed.context ?? '';- const urlNamespace = parsed.namespace ?? '';- const urlAgent = parsed.agent ?? '';- const urlResource = parsed.resource ?? '';-- // Avoid oscillation: only write managed params after we've processed the current URL.- if (handledTypeParam() !== urlType) return;- if (handledRuntimeParam() !== urlRuntime) return;- if (handledContextParam() !== urlContext) return;- if (handledNamespaceParam() !== urlNamespace) return;- if (handledAgentParam() !== urlAgent) return;- if (urlResource && handledResourceId() !== urlResource) return;-- const currentParams = new URLSearchParams(location.search);- const nextParams = new URLSearchParams(location.search);- const nextType = viewMode() === 'all' ? '' : viewMode();- const nextRuntime = viewMode() === 'app-container' ? containerRuntime().trim() : '';- const nextContext = viewMode() === 'pod' ? (selectedKubernetesContext() ?? '') : '';- const nextNamespace = viewMode() === 'pod' ? (selectedKubernetesNamespace() ?? '') : '';- const nextAgent = viewMode() === 'pod' ? '' : (selectedNode() ?? selectedHostHint() ?? '');-- const managedPath = buildWorkloadsPath({- type: nextType || null,- runtime: nextRuntime || null,- context: nextContext || null,- namespace: nextNamespace || null,- agent: nextAgent || null,- });- const managedUrl = new URL(managedPath, 'http://pulse.local');- nextParams.delete(WORKLOADS_QUERY_PARAMS.type);- nextParams.delete(WORKLOADS_QUERY_PARAMS.runtime);- nextParams.delete(WORKLOADS_QUERY_PARAMS.context);- nextParams.delete(WORKLOADS_QUERY_PARAMS.namespace);- nextParams.delete(WORKLOADS_QUERY_PARAMS.agent);- managedUrl.searchParams.forEach((value, key) => {- nextParams.set(key, value);- });-- if (!areSearchParamsEquivalent(currentParams, nextParams)) {- const nextSearch = nextParams.toString();- const nextPath = nextSearch ? `${WORKLOADS_PATH}?${nextSearch}` : WORKLOADS_PATH;- scheduleUrlSyncNavigate(nextPath);- }- });-- const [statusMode, setStatusMode] = usePersistentSignal<StatusMode>(- 'dashboardStatusMode',- 'all',- {- deserialize: (raw) =>- raw === 'all' || raw === 'running' || raw === 'degraded' || raw === 'stopped'- ? (raw as StatusMode)- : 'all',- },- );-- // Grouping mode - grouped by node or flat list- const [groupingMode, setGroupingMode] = usePersistentSignal<GroupingMode>(- 'dashboardGroupingMode',- 'grouped',- {- deserialize: (raw) => (raw === 'grouped' || raw === 'flat' ? raw : 'grouped'),- },- );-- const [showFilters, setShowFilters] = usePersistentSignal<boolean>(- 'dashboardShowFilters',- false,- {- deserialize: (raw) => raw === 'true',- serialize: (value) => String(value),- },- );- const [workloadsSummaryRange, setWorkloadsSummaryRange] = usePersistentSignal(- STORAGE_KEYS.WORKLOADS_SUMMARY_RANGE,- '1h',- {- deserialize: (raw) => (isSummaryTimeRange(raw) ? raw : '1h'),- },- );- const [workloadsSummaryCollapsed, setWorkloadsSummaryCollapsed] = usePersistentSignal<boolean>(- STORAGE_KEYS.WORKLOADS_SUMMARY_COLLAPSED,- false,- { deserialize: (raw) => raw === 'true' },- );-- // Sorting state - default to type ascending so VMs/LXCs/Docker/K8s cluster together- const [sortKey, setSortKey] = createSignal<WorkloadSortKey | null>('type');- const [sortDirection, setSortDirection] = createSignal<'asc' | 'desc'>('asc');-- // Column visibility management- // OS and IP columns are hidden by default since they require guest agent and may show dashes- const relevantColumns = createMemo(() => {- const base = VIEW_MODE_COLUMNS[viewMode()];- if (!base) return null;- // Hide the node column when grouped by node — it's already shown in the group header- if (groupingMode() === 'grouped' && base.has('node')) {- const filtered = new Set(base);- filtered.delete('node');- return filtered;- }- return base;- });- const columnVisibility = useColumnVisibility(- STORAGE_KEYS.DASHBOARD_HIDDEN_COLUMNS,- GUEST_COLUMNS,- ['os', 'ip'], // Default hidden columns for cleaner first-run experience- relevantColumns,- );- const visibleColumns = columnVisibility.visibleColumns;- const visibleColumnIds = createMemo(() => visibleColumns().map((c) => c.id));- // Mobile: restrict to the essential columns only so the table fits without horizontal scroll.- // Secondary data (uptime, IP, node, I/O, etc.) is accessible via the row detail drawer.- const MOBILE_ESSENTIAL_COLS = new Set(['name', 'cpu', 'memory', 'disk', 'link']);- const mobileVisibleColumns = createMemo(() =>- isMobile() ? visibleColumns().filter((c) => MOBILE_ESSENTIAL_COLS.has(c.id)) : visibleColumns(),- );- const mobileVisibleColumnIds = createMemo(() =>- isMobile() ? mobileVisibleColumns().map((c) => c.id) : visibleColumnIds(),- );-- // Total columns for colspan calculations- const totalColumns = createMemo(() => mobileVisibleColumns().length);-- // Helper function to refresh guest metadata from server- const refreshGuestMetadata = async () => {- try {- const metadata = await GuestMetadataAPI.getAllMetadata();- updateGuestMetadataState(() => metadata || {});- logger.debug('Guest metadata refreshed');- } catch (err) {- logger.debug('Failed to refresh guest metadata', err);- }- };-- // Load all guest metadata on mount (single API call for all guests)- onMount(() => {- void refreshGuestMetadata();-- // Listen for metadata changes from AI or other sources- const handleMetadataChanged = (event: Event) => {- const customEvent = event as CustomEvent;- logger.debug('[Dashboard] Metadata changed event received', customEvent.detail);-- // Handle optimistic update if payload is present - this fixes the "guest url not appearing straight away" issue- if (customEvent.detail?.payload) {- let { guestId, url } = customEvent.detail.payload;- if (guestId) {- // Normalize guestId if it's in the canonical AI format (instance:node:vmid)- // Frontend uses 'instance-vmid' (e.g., 'pve-node-101') but AI sends 'homelab:pve-node:101'- if (guestId.includes(':')) {- const parts = guestId.split(':');- if (parts.length === 3) {- const [instance, _node, vmid] = parts;- // Construct frontend ID format- guestId = `${instance}-${vmid}`;- logger.debug('[Dashboard] Normalized optimistic guestId', {- original: customEvent.detail.payload.guestId,- normalized: guestId,- });- }- }-- logger.debug('[Dashboard] Applying optimistic metadata update', { guestId, url });- // Ensure url is a string (handle null/undefined for removal)- handleCustomUrlUpdate(guestId, url || '');- // Skip immediate refresh to prevent race condition with backend consistency- // The optimistic update is authoritative for this action- return;- }- }-- logger.debug('Metadata changed event received, refreshing...');- refreshGuestMetadata();- };-- logger.debug('[Dashboard] Adding pulse:metadata-changed listener');- window.addEventListener('pulse:metadata-changed', handleMetadataChanged);- const unsubscribeOrgSwitched = eventBus.on('org_switched', (nextOrgID) => {- setOrgScope(normalizeOrgScope(nextOrgID));- void refreshGuestMetadata();- });-- onCleanup(() => {- window.removeEventListener('pulse:metadata-changed', handleMetadataChanged);- unsubscribeOrgSwitched();- });- });-- let lastConnected = connected();- createEffect(() => {- const isConnected = connected();- if (workloadsEnabled() && isConnected && !lastConnected) {- void workloads.refetch();- }- lastConnected = isConnected;- });-- // Callback to update a guest's custom URL in metadata- const handleCustomUrlUpdate = (guestId: string, url: string) => {- const trimmedUrl = url.trim();- const nextUrl = trimmedUrl === '' ? undefined : trimmedUrl;- const currentUrl = guestMetadata()[guestId]?.customUrl;- if (currentUrl === nextUrl) {- return;- }-- updateGuestMetadataState((prev) => {- const previousEntry = prev[guestId];-- if (nextUrl === undefined) {- if (!previousEntry || typeof previousEntry.customUrl === 'undefined') {- return prev;- }- const { customUrl: _removed, ...restEntry } = previousEntry;- const hasAdditionalMetadata = Object.entries(restEntry).some(- ([key, value]) => key !== 'id' && value !== undefined,- );-- if (!hasAdditionalMetadata) {- const { [guestId]: _omit, ...rest } = prev;- return rest;- }-- return {- ...prev,- [guestId]: {- ...restEntry,- id: restEntry.id ?? guestId,- },- };- }-- if (previousEntry && previousEntry.customUrl === nextUrl) {- return prev;- }-- const nextEntry: GuestMetadata = {- ...(previousEntry || { id: guestId }),- customUrl: nextUrl,- };-- return {- ...prev,- [guestId]: nextEntry,- };- });- };-- // Create a mapping from node ID to node object- // Also maps by instance-nodeName for guest grouping compatibility- const nodeByInstance = createMemo(() => buildNodeByInstance(props.nodes));-- // PERFORMANCE: Pre-compute guest- mapping for faster lookups- // This avoids repeated node lookups for each guest during render- const guestParentNodeMap = createMemo(() =>- buildGuestParentNodeMap(allGuests(), nodeByInstance()),- );-- // Sort handler- const handleSort = (key: WorkloadSortKey) => {- if (sortKey() === key) {- // Toggle direction for the same column- setSortDirection(sortDirection() === 'asc' ? 'desc' : 'asc');- } else {- // New column - set key and default direction- setSortKey(key);- // Set default sort direction based on column type- if (- key === 'cpu' ||- key === 'memory' ||- key === 'disk' ||- key === 'diskIo' ||- key === 'netIo' ||- key === 'uptime'- ) {- setSortDirection('desc');- } else {- setSortDirection('asc');- }- }- };-- // PERFORMANCE: Memoized sort comparator to avoid duplicating sorting logic- // This comparator is reused by both flat and grouped modes in groupedGuests- const guestSortComparator = createMemo(() =>- createWorkloadSortComparator(sortKey() || '', sortDirection()),- );-- createEffect(() => {- const handleKeyDown = (e: KeyboardEvent) => {- // Escape key behavior- if (e.key === 'Escape') {- // First check if we have search/filters to clear (including tag filters and node selection)- const hasActiveFilters =- search().trim() ||- sortKey() !== 'type' ||- sortDirection() !== 'asc' ||- selectedNode() !== null ||- selectedHostHint() !== null ||- selectedKubernetesContext() !== null ||- selectedKubernetesNamespace() !== null ||- containerRuntime().trim() !== '' ||- viewMode() !== 'all' ||- statusMode() !== 'all';-- if (hasActiveFilters) {- // Clear ALL filters including search text, tag filters, node selection, and view modes- setSearch('');- setIsSearchLocked(false);- setSortKey('type');- setSortDirection('asc');- setSelectedNode(null);- setSelectedHostHint(null);- setSelectedKubernetesContext(null);- setSelectedKubernetesNamespace(null);- setContainerRuntime('');- setViewMode('all');- setStatusMode('all');-- blurFocusedTypeToSearch();- } else {- // No active filters, toggle the filters section visibility- setShowFilters(!showFilters());- }- }- };-- document.addEventListener('keydown', handleKeyDown);- return () => document.removeEventListener('keydown', handleKeyDown);- });-- // Filter guests based on current settings- const filteredGuests = createMemo(() => {- const params: FilterWorkloadsParams = {- guests: allGuests(),- viewMode: viewMode(),- statusMode: statusMode(),- searchTerm: search().trim(),- selectedNode: selectedNode(),- selectedHostHint: selectedHostHint(),- selectedKubernetesContext: selectedKubernetesContext(),- selectedKubernetesNamespace: selectedKubernetesNamespace(),- containerRuntime: containerRuntime().trim() || null,- };- return filterWorkloads(params);- });-- const workloadsSummaryVisibleIds = createMemo<string[]>(() =>- filteredGuests().map((guest) => getCanonicalWorkloadId(guest)),- );-- const workloadsSummaryFallbackCounts = createMemo(() => {- const guests = filteredGuests();- const running = guests.filter(- (guest) => guest.status === 'running' || guest.status === 'online',- ).length;- return {- total: guests.length,- running,- stopped: Math.max(0, guests.length - running),- };- });-- const workloadsSummaryFallbackSnapshots = createMemo<WorkloadSummarySnapshot[]>(() =>- filteredGuests().map((guest) => {- const guestId = getCanonicalWorkloadId(guest);- const memoryUsage = workloadMetricPercent(guest.memory?.usage);- let diskUsage = workloadMetricPercent(guest.disk?.usage);- if (- (!diskUsage || diskUsage <= 0) &&- typeof guest.disk?.used === 'number' &&- typeof guest.disk?.total === 'number' &&- Number.isFinite(guest.disk.used) &&- Number.isFinite(guest.disk.total) &&- guest.disk.total > 0- ) {- const selectorDiskUsage = getDiskUsagePercent(guest);- const rawDiskUsage = (guest.disk.used / guest.disk.total) * 100;- // Preserve fallback behavior for anomalous >100% values.- diskUsage = rawDiskUsage > 100 ? rawDiskUsage : (selectorDiskUsage ?? rawDiskUsage);- }-- return {- id: guestId,- name: guest.name || guestId,- cpu: workloadMetricPercent(guest.cpu),- memory: memoryUsage,- disk: Math.max(0, diskUsage),- network: Math.max(0, guest.networkIn || 0) + Math.max(0, guest.networkOut || 0),- };- }),- );-- createEffect(() => {- const hoveredId = hoveredWorkloadId();- if (!hoveredId) return;- const exists = filteredGuests().some((guest) => getCanonicalWorkloadId(guest) === hoveredId);- if (!exists) {- setHoveredWorkloadId(null);- }- });-- const getGroupLabel = (- groupKey: string,- guests: WorkloadGuest[],- ): { type: string; name: string } => {- const node = nodeByInstance()[groupKey];- if (node) return { type: '', name: getNodeDisplayName(node) };- const normalizedGroupKey = guests.length > 0 ? getWorkloadGroupKey(guests[0]) : groupKey;- const [prefix, ...rest] = normalizedGroupKey.split(':');- const context = rest.length > 0 ? rest.join(':') : normalizedGroupKey;- if (prefix === 'app-container') return { type: 'App Containers', name: context };- if (prefix === 'pod') return { type: 'Pods', name: context };- if (prefix === 'vm') return { type: 'VM', name: context };- if (prefix === 'system-container') return { type: 'Container', name: context };- // For PVE workload groups (instance-node key), show node name + cluster badge- const first = guests[0];- if (first) {- const cluster = (first.clusterName || '').trim();- const nodeName = (first.node || '').trim();- if (nodeName && cluster) return { type: cluster, name: nodeName };- if (nodeName) return { type: '', name: nodeName };- }- return { type: '', name: context };- };-- // Group by node or return flat list based on grouping mode- const groupedGuests = createMemo(() =>- groupWorkloads(filteredGuests(), groupingMode(), guestSortComparator()),- );-- // Stable sorted group keys for <For> — strings compare by value so DOM stays stable across data updates- const sortedGroupKeys = createMemo(() => {- const groups = groupedGuests();- const nodes = nodeByInstance();- return Object.keys(groups).sort((a, b) => {- const nodeA = nodes[a];- const nodeB = nodes[b];- const labelA = nodeA ? getNodeDisplayName(nodeA) : getGroupLabel(a, groups[a]).name;- const labelB = nodeB ? getNodeDisplayName(nodeB) : getGroupLabel(b, groups[b]).name;- return labelA.localeCompare(labelB) || a.localeCompare(b);- });- });-- const guestGlobalIndexById = createMemo(() => {- const indexById = new Map<string, number>();- const groups = groupedGuests();- let globalIndex = 0;-- for (const groupKey of sortedGroupKeys()) {- const guests = groups[groupKey] || [];- for (const guest of guests) {- indexById.set(getCanonicalWorkloadId(guest), globalIndex);- globalIndex += 1;- }- }-- return indexById;- });-- const revealGuestIndex = createMemo<number | null>(() => {- const selectedId = selectedGuestId();- if (!selectedId) return null;- return guestGlobalIndexById().get(selectedId) ?? null;- });-- const groupedWindowing = useGroupedTableWindowing({- totalRowCount: () => filteredGuests().length,- revealIndex: revealGuestIndex,- });-- const groupStartIndexByKey = createMemo(() => {- const starts = new Map<string, number>();- const groups = groupedGuests();- let globalIndex = 0;-- for (const groupKey of sortedGroupKeys()) {- starts.set(groupKey, globalIndex);- globalIndex += (groups[groupKey] || []).length;- }-- return starts;- });-- const windowedGroupedGuests = createMemo<Record<string, WorkloadGuest[]>>(() => {- const groups = groupedGuests();- if (!groupedWindowing.isWindowed()) {- return groups;- }-- const starts = groupStartIndexByKey();- const result: Record<string, WorkloadGuest[]> = {};- for (const groupKey of sortedGroupKeys()) {- const guests = groups[groupKey] || [];- const groupStart = starts.get(groupKey) ?? 0;- const visible = groupedWindowing.getVisibleSlice(groupKey, guests, groupStart);- if (visible.length > 0) {- result[groupKey] = visible;- }- }-- return result;- });-- const visibleGroupKeys = createMemo(() => {- const keys = sortedGroupKeys();- if (!groupedWindowing.isWindowed()) return keys;- const groups = windowedGroupedGuests();- return keys.filter((groupKey) => (groups[groupKey] || []).length > 0);- });-- const topSpacerHeight = createMemo(() =>- groupedWindowing.isWindowed()- ? groupedWindowing.startIndex() * DASHBOARD_TABLE_ESTIMATED_ROW_HEIGHT- : 0,- );-- const bottomSpacerHeight = createMemo(() =>- groupedWindowing.isWindowed()- ? Math.max(- 0,- (filteredGuests().length - groupedWindowing.endIndex()) *- DASHBOARD_TABLE_ESTIMATED_ROW_HEIGHT,- )- : 0,- );-- const syncGuestWindowToViewport = () => {- if (!groupedWindowing.isWindowed() || typeof window === 'undefined') return;- const body = tableBodyRef();- if (!body) return;- const rect = body.getBoundingClientRect();- const scrollTop = Math.max(0, -rect.top);- groupedWindowing.onScroll(scrollTop, window.innerHeight, DASHBOARD_TABLE_ESTIMATED_ROW_HEIGHT);- };-- createEffect(() => {- if (typeof window === 'undefined') return;- filteredGuests().length;- if (!groupedWindowing.isWindowed()) return;- if (!tableBodyRef()) return;-- const handleViewportChange = () => {- syncGuestWindowToViewport();- };-- handleViewportChange();- window.addEventListener('scroll', handleViewportChange, { passive: true });- window.addEventListener('resize', handleViewportChange);- onCleanup(() => {- window.removeEventListener('scroll', handleViewportChange);- window.removeEventListener('resize', handleViewportChange);- });- });-- const totalStats = createMemo<WorkloadStats>(() => computeWorkloadStats(filteredGuests()));-- const workloadIOEmphasis = createMemo(() => computeWorkloadIOEmphasis(filteredGuests()));-- const handleNodeSelect = (nodeId: string | null, nodeType: 'pve' | 'pbs' | 'pmg' | null) => {- logger.debug('handleNodeSelect called', { nodeId, nodeType });-- // Track selected node for filtering (independent of search)- if (nodeType === 'pve' || nodeType === null) {- setSelectedHostHint(null);- setSelectedNode(nodeId);- logger.debug('Set selected node', { nodeId });- // Show filters if a node is selected- if (nodeId && !showFilters()) {- setShowFilters(true);- }- }- };-- const handleTagClick = (tag: string) => {- const currentSearch = search().trim();- const tagFilter = `tags:${tag}`;-- // Check if this tag filter already exists- if (currentSearch.includes(tagFilter)) {- // Remove the tag filter- let newSearch = currentSearch;-- // Handle different cases of where the tag filter might be- if (currentSearch === tagFilter) {- // It's the only filter- newSearch = '';- } else if (currentSearch.startsWith(tagFilter + ',')) {- // It's at the beginning- newSearch = currentSearch.replace(tagFilter + ',', '').trim();- } else if (currentSearch.endsWith(', ' + tagFilter)) {- // It's at the end- newSearch = currentSearch.replace(', ' + tagFilter, '').trim();- } else if (currentSearch.includes(', ' + tagFilter + ',')) {- // It's in the middle- newSearch = currentSearch.replace(', ' + tagFilter + ',', ',').trim();- } else if (currentSearch.includes(tagFilter + ', ')) {- // It's at the beginning with space after comma- newSearch = currentSearch.replace(tagFilter + ', ', '').trim();- }-- setSearch(newSearch);- if (!newSearch) {- setIsSearchLocked(false);- }- } else {- // Add the tag filter- if (!currentSearch || isSearchLocked()) {- setSearch(tagFilter);- setIsSearchLocked(false);- } else {- // Add tag filter to existing search with comma separator- setSearch(`${currentSearch}, ${tagFilter}`);- }-- // Make sure filters are visible- if (!showFilters()) {- setShowFilters(true);- }- }- };+ const {+ activeAlerts,+ alertsEnabled,+ allGuests,+ bottomSpacerHeight,+ columnVisibility,+ connected,+ containerRuntime,+ containerRuntimeOptions,+ dashboardDisconnectedState,+ dashboardGuestsEmptyState,+ dashboardInfrastructureEmptyState,+ dashboardLoadingState,+ filteredGuests,+ getGroupLabel,+ groupedGuests,+ groupedWindowing,+ guestMetadata,+ guestParentNodeMap,+ handleBeforeAutoFocus,+ handleCustomUrlUpdate,+ handleNodeSelect,+ handleSort,+ handleTagClick,+ hoveredWorkloadId,+ initialDataReceived,+ isMobile,+ isSearchLocked,+ isWorkloadsRoute,+ kioskMode,+ kubernetesContextOptions,+ kubernetesNamespaceOptions,+ mobileVisibleColumnIds,+ mobileVisibleColumns,+ navigate,+ nodeByInstance,+ reconnect,+ search,+ selectedGuestId,+ selectedKubernetesContext,+ selectedKubernetesNamespace,+ selectedNode,+ setContainerRuntime,+ setGroupingMode,+ setHoveredWorkloadId,+ setSearch,+ setSelectedGuestId,+ setSelectedKubernetesContext,+ setSelectedKubernetesNamespace,+ setSortDirection,+ setSortKey,+ setStatusMode,+ setTableBodyRef,+ setTableWrapperRef,+ setViewMode,+ setWorkloadsSummaryCollapsed,+ setWorkloadsSummaryRange,+ sortDirection,+ sortKey,+ statusMode,+ topSpacerHeight,+ totalColumns,+ totalStats,+ viewMode,+ visibleColumns,+ visibleGroupKeys,+ windowedGroupedGuests,+ workloadIOEmphasis,+ workloadNodeOptions,+ workloads,+ workloadsSummaryCollapsed,+ workloadsSummaryFallbackCounts,+ workloadsSummaryFallbackSnapshots,+ workloadsSummaryRange,+ workloadsSummaryVisibleIds,+ ws,+ groupingMode,+ } = useDashboardState(props);return (<div class="space-y-3">@@ -1498,11 +254,7 @@ export function Dashboard(props: DashboardProps) {setGroupingMode={setGroupingMode}setSortKey={setSortKey}setSortDirection={setSortDirection}- onBeforeAutoFocus={() => {- if (aiChatStore.focusInput()) return true;- if (!showFilters()) setShowFilters(true);- return false;- }}+ onBeforeAutoFocus={handleBeforeAutoFocus}availableColumns={columnVisibility.availableToggles()}isColumnHidden={columnVisibility.isHiddenByUser}onColumnToggle={columnVisibility.toggle}@@ -1550,7 +302,6 @@ export function Dashboard(props: DashboardProps) {value: selectedNode() ?? '',options: [{ value: '', label: 'All nodes' }, ...workloadNodeOptions()],onChange: (value: string) => {- setSelectedHostHint(null);handleNodeSelect(value || null, value ? 'pve' : null);},};@@ -1583,7 +334,7 @@ export function Dashboard(props: DashboardProps) {</div><div class="overflow-x-auto"><Table- wrapperRef={(el) => (tableRef = el)}+ wrapperRef={setTableWrapperRef}class="whitespace-nowrap min-w-[max-content]"style={{'table-layout': 'fixed',diff --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 b57be00ea4..a056ba29c4 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@@ -4,6 +4,7 @@ import { createSignal, onCleanup, onMount } from 'solid-js';import type { Resource } from '@/types/resource';import { Dashboard } from '../Dashboard';import dashboardSource from '../Dashboard.tsx?raw';+import dashboardStateSource from '../useDashboardState.ts?raw';import {filterWorkloads,createWorkloadSortComparator,@@ -449,9 +450,19 @@ describe('Dashboard performance contract', () => {});it('routes org scope normalization through the shared helper', () => {- expect(dashboardSource).toContain('normalizeOrgScope(getOrgID())');- expect(dashboardSource).not.toContain("const DEFAULT_ORG_SCOPE = 'default'");- expect(dashboardSource).not.toContain('const normalizeOrgScope =');+ expect(dashboardSource).toContain('useDashboardState');+ expect(dashboardStateSource).toContain('normalizeOrgScope(getOrgID())');+ expect(dashboardStateSource).not.toContain("const DEFAULT_ORG_SCOPE = 'default'");+ expect(dashboardStateSource).not.toContain('const normalizeOrgScope =');+ });++ it('keeps hot-path dashboard state in the shared dashboard state owner', () => {+ expect(dashboardSource).toContain('useDashboardState');+ expect(dashboardSource).not.toContain('const [search, setSearch] = createSignal(');+ expect(dashboardStateSource).toContain('useGroupedTableWindowing');+ expect(dashboardStateSource).toContain('createWorkloadSortComparator');+ expect(dashboardSource).toContain('createMemo(() => getCanonicalWorkloadId(guest()))');+ expect(dashboardStateSource).not.toContain('const guestId = () => {');});it('filterWorkloads returns all guests when no filters active', () => {diff --git a/frontend-modern/src/components/Dashboard/useDashboardState.ts b/frontend-modern/src/components/Dashboard/useDashboardState.tsnew file mode 100644index 0000000000..d2a09f6f70--- /dev/null+++ b/frontend-modern/src/components/Dashboard/useDashboardState.ts@@ -0,0 +1,1334 @@+import { createEffect, createMemo, createSignal, onCleanup, onMount, untrack } from 'solid-js';+import { useLocation, useNavigate } from '@solidjs/router';+import type { VM, Container, Node } from '@/types/api';+import type { WorkloadGuest, ViewMode } from '@/types/workloads';+import { GUEST_COLUMNS, VIEW_MODE_COLUMNS } from './GuestRow';+import { useWebSocket } from '@/App';+import { useAlertsActivation } from '@/stores/alertsActivation';+import { GuestMetadataAPI } from '@/api/guestMetadata';+import type { GuestMetadata } from '@/api/guestMetadata';+import { getNodeDisplayName } from '@/utils/nodes';+import { logger } from '@/utils/logger';+import { usePersistentSignal } from '@/hooks/usePersistentSignal';+import { useColumnVisibility } from '@/hooks/useColumnVisibility';+import { useBreakpoint } from '@/hooks/useBreakpoint';+import { blurFocusedTypeToSearch } from '@/hooks/useTypeToSearch';+import { useWorkloads } from '@/hooks/useWorkloads';+import { STORAGE_KEYS } from '@/utils/localStorage';+import { getOrgID } from '@/utils/apiClient';+import { normalizeOrgScope } from '@/utils/orgScope';+import { aiChatStore } from '@/stores/aiChat';+import { eventBus } from '@/stores/events';+import { useKioskMode } from '@/hooks/useKioskMode';+import {+ getDashboardDisconnectedState,+ getDashboardGuestsEmptyState,+ getDashboardInfrastructureEmptyState,+ getDashboardLoadingState,+} from '@/utils/dashboardEmptyStatePresentation';+import {+ getCanonicalWorkloadId,+ normalizeWorkloadViewModeParam,+ resolveWorkloadType,+} from '@/utils/workloads';+import { isSummaryTimeRange } from '@/components/shared/summaryTimeRange';+import {+ buildWorkloadsPath,+ parseWorkloadsLinkSearch,+ WORKLOADS_PATH,+ WORKLOADS_QUERY_PARAMS,+} from '@/routing/resourceLinks';+import { areSearchParamsEquivalent } from '@/utils/searchParams';+import {+ workloadNodeScopeId,+ getKubernetesContextKey,+ filterWorkloads,+ getDiskUsagePercent,+ createWorkloadSortComparator,+ getWorkloadGroupKey,+ groupWorkloads,+ computeWorkloadStats,+ computeWorkloadIOEmphasis,+ buildNodeByInstance,+ buildGuestParentNodeMap,+ type FilterWorkloadsParams,+ type WorkloadStats,+} from './workloadSelectors';+import { useGroupedTableWindowing } from './useGroupedTableWindowing';+import type { WorkloadSummarySnapshot } from '@/components/Workloads/WorkloadsSummary';++export interface DashboardProps {+ vms: VM[];+ containers: Container[];+ nodes: Node[];+ useWorkloads?: boolean;+}++type StatusMode = 'all' | 'running' | 'degraded' | 'stopped';+type GroupingMode = 'grouped' | 'flat';+export type WorkloadSortKey = keyof WorkloadGuest | 'diskIo' | 'netIo';++type GuestMetadataRecord = Record<string, GuestMetadata>;+type IdleCallbackHandle = number;+type IdleCallback = (deadline?: { didTimeout: boolean; timeRemaining: () => number }) => void;+type IdleCapableWindow = Window & {+ requestIdleCallback?: (+ callback: IdleCallback,+ options?: { timeout?: number },+ ) => IdleCallbackHandle;+ cancelIdleCallback?: (handle: IdleCallbackHandle) => void;+};++let cachedGuestMetadata: GuestMetadataRecord | null = null;+let cachedGuestMetadataStorageKey: string | null = null;+let lastPersistedGuestMetadataJSON: string | null = null;+let lastPersistedGuestMetadataStorageKey: string | null = null;+let pendingPersistMetadata: GuestMetadataRecord | null = null;+let pendingPersistStorageKey: string | null = null;+let persistHandle: number | null = null;+let persistHandleType: 'idle' | 'timeout' | null = null;++const guestMetadataStorageKeyForOrg = (orgScope: string): string =>+ `${STORAGE_KEYS.GUEST_METADATA}.${encodeURIComponent(orgScope)}`;++const instrumentationEnabled = import.meta.env.DEV && typeof performance !== 'undefined';+const DASHBOARD_TABLE_ESTIMATED_ROW_HEIGHT = 32;++const workloadMetricPercent = (value: number | null | undefined): number => {+ if (typeof value !== 'number' || !Number.isFinite(value)) return 0;+ if (value <= 1) return Math.max(0, value * 100);+ return Math.max(0, value);+};++const readGuestMetadataCache = (storageKey: string): GuestMetadataRecord => {+ if (cachedGuestMetadata && cachedGuestMetadataStorageKey === storageKey) {+ return cachedGuestMetadata;+ }++ if (typeof window === 'undefined') {+ cachedGuestMetadata = {};+ cachedGuestMetadataStorageKey = storageKey;+ return cachedGuestMetadata;+ }++ try {+ const raw = window.localStorage.getItem(storageKey);+ if (!raw) {+ cachedGuestMetadata = {};+ cachedGuestMetadataStorageKey = storageKey;+ lastPersistedGuestMetadataJSON = null;+ lastPersistedGuestMetadataStorageKey = storageKey;+ return cachedGuestMetadata;+ }+ const parsed = JSON.parse(raw);+ if (parsed && typeof parsed === 'object') {+ cachedGuestMetadata = parsed as GuestMetadataRecord;+ cachedGuestMetadataStorageKey = storageKey;+ lastPersistedGuestMetadataJSON = raw;+ lastPersistedGuestMetadataStorageKey = storageKey;+ return cachedGuestMetadata;+ }+ } catch (err) {+ logger.warn('Failed to parse cached guest metadata', err);+ }++ cachedGuestMetadata = {};+ cachedGuestMetadataStorageKey = storageKey;+ lastPersistedGuestMetadataJSON = null;+ lastPersistedGuestMetadataStorageKey = storageKey;+ return cachedGuestMetadata;+};++const clearPendingPersistHandle = (idleWindow: IdleCapableWindow) => {+ if (persistHandle === null || persistHandleType === null) {+ return;+ }++ if (persistHandleType === 'idle' && idleWindow.cancelIdleCallback) {+ idleWindow.cancelIdleCallback(persistHandle);+ } else if (persistHandleType === 'timeout') {+ window.clearTimeout(persistHandle);+ }++ persistHandle = null;+ persistHandleType = null;+};++const runGuestMetadataPersist = () => {+ if (typeof window === 'undefined' || !pendingPersistMetadata || !pendingPersistStorageKey) {+ pendingPersistMetadata = null;+ pendingPersistStorageKey = null;+ return;+ }++ const metadata = pendingPersistMetadata;+ const storageKey = pendingPersistStorageKey;+ pendingPersistMetadata = null;+ pendingPersistStorageKey = null;++ const markBase = instrumentationEnabled ? `guest-metadata:persist:${Date.now()}` : null;+ if (markBase) {+ performance.mark(`${markBase}:start`);+ }++ let serialized: string;+ try {+ serialized = JSON.stringify(metadata);+ } catch (err) {+ if (markBase) {+ performance.mark(`${markBase}:end`);+ performance.measure(markBase, `${markBase}:start`, `${markBase}:end`);+ performance.clearMarks(`${markBase}:start`);+ performance.clearMarks(`${markBase}:end`);+ performance.clearMeasures(markBase);+ }+ logger.warn('Failed to serialize guest metadata cache', err);+ return;+ }++ if (+ serialized === lastPersistedGuestMetadataJSON &&+ storageKey === lastPersistedGuestMetadataStorageKey+ ) {+ if (markBase) {+ performance.mark(`${markBase}:end`);+ performance.measure(markBase, `${markBase}:start`, `${markBase}:end`);+ const entries = performance.getEntriesByName(markBase);+ const entry = entries[entries.length - 1];+ if (entry) {+ logger.debug('[guestMetadataCache] skipped persist (unchanged)', {+ durationMs: entry.duration,+ });+ }+ performance.clearMarks(`${markBase}:start`);+ performance.clearMarks(`${markBase}:end`);+ performance.clearMeasures(markBase);+ }+ return;+ }++ try {+ window.localStorage.setItem(storageKey, serialized);+ lastPersistedGuestMetadataJSON = serialized;+ lastPersistedGuestMetadataStorageKey = storageKey;+ if (markBase) {+ performance.mark(`${markBase}:end`);+ performance.measure(markBase, `${markBase}:start`, `${markBase}:end`);+ const entries = performance.getEntriesByName(markBase);+ const entry = entries[entries.length - 1];+ if (entry) {+ logger.debug('[guestMetadataCache] persisted entries', {+ count: Object.keys(metadata).length,+ durationMs: entry.duration,+ });+ }+ performance.clearMarks(`${markBase}:start`);+ performance.clearMarks(`${markBase}:end`);+ performance.clearMeasures(markBase);+ }+ } catch (err) {+ if (markBase) {+ performance.mark(`${markBase}:end`);+ performance.measure(markBase, `${markBase}:start`, `${markBase}:end`);+ performance.clearMarks(`${markBase}:start`);+ performance.clearMarks(`${markBase}:end`);+ performance.clearMeasures(markBase);+ }+ logger.warn('Failed to persist guest metadata cache', err);+ }+};++const queueGuestMetadataPersist = (storageKey: string, metadata: GuestMetadataRecord) => {+ cachedGuestMetadata = metadata;+ cachedGuestMetadataStorageKey = storageKey;++ if (typeof window === 'undefined') {+ return;+ }++ pendingPersistMetadata = metadata;+ pendingPersistStorageKey = storageKey;+ const idleWindow = window as IdleCapableWindow;++ clearPendingPersistHandle(idleWindow);++ const schedule: IdleCallback = () => {+ persistHandle = null;+ persistHandleType = null;+ runGuestMetadataPersist();+ };++ if (idleWindow.requestIdleCallback) {+ persistHandleType = 'idle';+ persistHandle = idleWindow.requestIdleCallback(schedule, { timeout: 750 });+ } else {+ persistHandleType = 'timeout';+ persistHandle = window.setTimeout(schedule, 0);+ }+};++export function useDashboardState(props: DashboardProps) {+ const navigate = useNavigate();+ const location = useLocation();+ const ws = useWebSocket();+ const { connected, activeAlerts, initialDataReceived, reconnecting, reconnect } = ws;+ const { isMobile } = useBreakpoint();+ const alertsActivation = useAlertsActivation();+ const alertsEnabled = createMemo(() => alertsActivation.activationState() === 'active');+ const isWorkloadsRoute = () => location.pathname === WORKLOADS_PATH;+ const [search, setSearch] = createSignal('');++ const kioskMode = useKioskMode();+ const dashboardInfrastructureEmptyState = createMemo(() => getDashboardInfrastructureEmptyState());+ const dashboardGuestsEmptyState = createMemo(() => getDashboardGuestsEmptyState(search()));+ const dashboardLoadingState = createMemo(() => getDashboardLoadingState(reconnecting()));+ const dashboardDisconnectedState = createMemo(() => getDashboardDisconnectedState(reconnecting()));++ const [isSearchLocked, setIsSearchLocked] = createSignal(false);+ const [selectedNode, setSelectedNode] = createSignal<string | null>(null);+ const [selectedKubernetesContext, setSelectedKubernetesContext] = createSignal<string | null>(+ null,+ );+ const [selectedKubernetesNamespace, setSelectedKubernetesNamespace] = createSignal<+ string | null+ >(null);+ const [selectedGuestId, setSelectedGuestIdRaw] = createSignal<string | null>(null);+ const [hoveredWorkloadId, setHoveredWorkloadId] = createSignal<string | null>(null);+ const [handledResourceId, setHandledResourceId] = createSignal<string | null>(null);+ const [handledTypeParam, setHandledTypeParam] = createSignal<string>('');+ const [handledRuntimeParam, setHandledRuntimeParam] = createSignal<string>('');+ const [handledContextParam, setHandledContextParam] = createSignal('');+ const [handledNamespaceParam, setHandledNamespaceParam] = createSignal('');+ const [handledAgentParam, setHandledAgentParam] = createSignal('');+ const [selectedHostHint, setSelectedHostHint] = createSignal<string | null>(null);++ let pendingUrlSyncHandle: number | null = null;+ let pendingUrlSyncPath: string | null = null;+ const scheduleUrlSyncNavigate = (nextPath: string) => {+ pendingUrlSyncPath = nextPath;+ if (pendingUrlSyncHandle !== null) return;+ pendingUrlSyncHandle = window.setTimeout(() => {+ pendingUrlSyncHandle = null;+ const target = pendingUrlSyncPath;+ pendingUrlSyncPath = null;+ if (!target) return;+ const current = `${untrack(() => location.pathname)}${untrack(() => location.search)}`;+ if (current === target) return;+ navigate(target, { replace: true });+ }, 0);+ };+ onCleanup(() => {+ if (pendingUrlSyncHandle !== null) {+ window.clearTimeout(pendingUrlSyncHandle);+ pendingUrlSyncHandle = null;+ pendingUrlSyncPath = null;+ }+ });++ let tableRef: HTMLDivElement | undefined;+ const [tableBodyRef, setTableBodyRef] = createSignal<HTMLTableSectionElement | null>(null);+ const setTableWrapperRef = (element: HTMLDivElement | undefined) => {+ tableRef = element;+ };++ const setSelectedGuestId = (id: string | null) => {+ let scroller: HTMLElement | null = tableRef ?? null;+ while (scroller) {+ const { overflowY } = getComputedStyle(scroller);+ if (+ (overflowY === 'auto' || overflowY === 'scroll') &&+ scroller.scrollHeight > scroller.clientHeight+ ) {+ break;+ }+ scroller = scroller.parentElement;+ }+ const scrollTop = scroller?.scrollTop ?? 0;+ setSelectedGuestIdRaw(id);+ if (scroller) scroller.scrollTop = scrollTop;+ requestAnimationFrame(() => {+ if (scroller) scroller.scrollTop = scrollTop;+ });+ };++ createEffect(() => {+ const { resource: resourceId } = parseWorkloadsLinkSearch(location.search);+ if (!resourceId || resourceId === handledResourceId()) return;+ setSelectedGuestId(resourceId);+ const [instance, node, vmid] = resourceId.split(':');+ if (instance && node && vmid) {+ setSelectedNode(`${instance}-${node}`);+ }+ setHandledResourceId(resourceId);+ });++ const [orgScope, setOrgScope] = createSignal(normalizeOrgScope(getOrgID()));+ const guestMetadataStorageKey = createMemo(() => guestMetadataStorageKeyForOrg(orgScope()));+ const [guestMetadata, setGuestMetadata] = createSignal<GuestMetadataRecord>(+ readGuestMetadataCache(guestMetadataStorageKey()),+ );++ createEffect(() => {+ const storageKey = guestMetadataStorageKey();+ setGuestMetadata(readGuestMetadataCache(storageKey));+ });++ const updateGuestMetadataState = (updater: (prev: GuestMetadataRecord) => GuestMetadataRecord) =>+ setGuestMetadata((prev) => {+ const next = updater(prev);+ if (next === prev) {+ return prev;+ }+ queueGuestMetadataPersist(guestMetadataStorageKey(), next);+ return next;+ });++ const workloadsEnabled = createMemo(() => props.useWorkloads === true);+ const workloads = useWorkloads(workloadsEnabled);++ const dedupeGuests = (guests: WorkloadGuest[]): WorkloadGuest[] => {+ const seen = new Set<string>();+ const deduped: WorkloadGuest[] = [];+ for (const guest of guests) {+ const canonicalId = getCanonicalWorkloadId(guest);+ if (seen.has(canonicalId)) continue;+ seen.add(canonicalId);+ deduped.push(guest);+ }+ return deduped;+ };++ const allGuests = createMemo<WorkloadGuest[]>(() =>+ workloadsEnabled() ? dedupeGuests(workloads.workloads()) : [],+ );++ const [viewMode, setViewMode] = usePersistentSignal<ViewMode>('dashboardViewMode', 'all', {+ deserialize: (raw) => normalizeWorkloadViewModeParam(raw) ?? 'all',+ });++ const [containerRuntime, setContainerRuntime] = usePersistentSignal<string>(+ 'dashboardContainerRuntime',+ '',+ {+ deserialize: (raw) => (typeof raw === 'string' ? raw : ''),+ serialize: (value) => value,+ },+ );++ const [statusMode, setStatusMode] = usePersistentSignal<StatusMode>(+ 'dashboardStatusMode',+ 'all',+ {+ deserialize: (raw) =>+ raw === 'all' || raw === 'running' || raw === 'degraded' || raw === 'stopped'+ ? (raw as StatusMode)+ : 'all',+ },+ );++ const [groupingMode, setGroupingMode] = usePersistentSignal<GroupingMode>(+ 'dashboardGroupingMode',+ 'grouped',+ {+ deserialize: (raw) => (raw === 'grouped' || raw === 'flat' ? raw : 'grouped'),+ },+ );++ const [showFilters, setShowFilters] = usePersistentSignal<boolean>(+ 'dashboardShowFilters',+ false,+ {+ deserialize: (raw) => raw === 'true',+ serialize: (value) => String(value),+ },+ );+ const [workloadsSummaryRange, setWorkloadsSummaryRange] = usePersistentSignal(+ STORAGE_KEYS.WORKLOADS_SUMMARY_RANGE,+ '1h',+ {+ deserialize: (raw) => (isSummaryTimeRange(raw) ? raw : '1h'),+ },+ );+ const [workloadsSummaryCollapsed, setWorkloadsSummaryCollapsed] = usePersistentSignal<boolean>(+ STORAGE_KEYS.WORKLOADS_SUMMARY_COLLAPSED,+ false,+ { deserialize: (raw) => raw === 'true' },+ );++ const [sortKey, setSortKey] = createSignal<WorkloadSortKey | null>('type');+ const [sortDirection, setSortDirection] = createSignal<'asc' | 'desc'>('asc');++ const workloadNodeOptions = createMemo(() => {+ const labelsByScope = new Map<string, string>();+ const nodeNameCounts = new Map<string, number>();++ for (const guest of allGuests()) {+ const type = resolveWorkloadType(guest);+ if (type === 'pod') continue;+ const scope = workloadNodeScopeId(guest);+ if (!scope || scope === '-') continue;+ const nodeName = (guest.node || '').trim();+ if (!nodeName) continue;+ nodeNameCounts.set(nodeName, (nodeNameCounts.get(nodeName) || 0) + 1);+ }++ for (const guest of allGuests()) {+ const type = resolveWorkloadType(guest);+ if (type === 'pod') continue;+ const scope = workloadNodeScopeId(guest);+ if (!scope || scope === '-' || labelsByScope.has(scope)) continue;+ const nodeName = (guest.node || '').trim();+ const instance = (guest.instance || '').trim();+ if (!nodeName) continue;+ const hasDuplicateNodeName = (nodeNameCounts.get(nodeName) || 0) > 1;+ const label = hasDuplicateNodeName && instance ? `${nodeName} (${instance})` : nodeName;+ labelsByScope.set(scope, label);+ }++ return Array.from(labelsByScope.entries())+ .map(([value, label]) => ({ value, label }))+ .sort((a, b) => a.label.localeCompare(b.label));+ });++ createEffect(() => {+ if (viewMode() === 'pod') return;+ const hostHint = selectedHostHint();+ if (!hostHint || selectedNode() !== null) return;+ const normalizedHint = hostHint.trim().toLowerCase();+ if (!normalizedHint) return;+ const option = workloadNodeOptions().find((candidate) => {+ const label = candidate.label.toLowerCase();+ const value = candidate.value.toLowerCase();+ return label === normalizedHint || value === normalizedHint || label.includes(normalizedHint);+ });+ if (!option) return;+ setSelectedNode(option.value);+ setSelectedHostHint(null);+ });++ const kubernetesContextOptions = createMemo(() => {+ const contexts = new Set<string>();+ for (const guest of allGuests()) {+ if (resolveWorkloadType(guest) !== 'pod') continue;+ const context = getKubernetesContextKey(guest);+ if (context) {+ contexts.add(context);+ }+ }+ return Array.from(contexts).sort((a, b) => a.localeCompare(b));+ });++ const kubernetesNamespaceOptions = createMemo(() => {+ const namespaces = new Set<string>();+ const contextFilter = (selectedKubernetesContext() || '').trim();+ for (const guest of allGuests()) {+ if (resolveWorkloadType(guest) !== 'pod') continue;+ if (contextFilter && getKubernetesContextKey(guest) !== contextFilter) continue;+ const ns = (guest.namespace || '').trim();+ if (ns) namespaces.add(ns);+ }+ return Array.from(namespaces).sort((a, b) => a.localeCompare(b));+ });++ createEffect(() => {+ if (!isWorkloadsRoute()) return;+ if (viewMode() !== 'pod') return;+ const selected = (selectedKubernetesNamespace() || '').trim();+ if (!selected) return;+ const normalized = selected.toLowerCase();+ const exists = kubernetesNamespaceOptions().some((value) => value.toLowerCase() === normalized);+ if (!exists) {+ setSelectedKubernetesNamespace(null);+ }+ });++ const containerRuntimeOptions = createMemo(() => {+ const runtimes = new Set<string>();+ for (const guest of allGuests()) {+ if (resolveWorkloadType(guest) !== 'app-container') continue;+ const runtime = (guest.containerRuntime || '').trim();+ if (runtime) {+ runtimes.add(runtime);+ }+ }+ return Array.from(runtimes).sort((a, b) => a.localeCompare(b));+ });++ createEffect(() => {+ if (!isWorkloadsRoute()) return;+ if (viewMode() !== 'app-container') return;+ const selected = containerRuntime().trim();+ if (!selected) return;+ const normalized = selected.toLowerCase();+ const exists = containerRuntimeOptions().some((value) => value.toLowerCase() === normalized);+ if (!exists) {+ setContainerRuntime('');+ }+ });++ createEffect(() => {+ if (!isWorkloadsRoute()) return;+ if (viewMode() === 'pod') {+ if (selectedNode() !== null) {+ setSelectedNode(null);+ }+ if (selectedHostHint() !== null) {+ setSelectedHostHint(null);+ }+ return;+ }+ if (selectedKubernetesContext() !== null) {+ setSelectedKubernetesContext(null);+ }+ if (selectedKubernetesNamespace() !== null) {+ setSelectedKubernetesNamespace(null);+ }+ });++ createEffect(() => {+ if (!isWorkloadsRoute()) return;+ if (viewMode() !== 'app-container' && containerRuntime().trim() !== '') {+ setContainerRuntime('');+ }+ });++ createEffect(() => {+ const parsed = parseWorkloadsLinkSearch(location.search);+ const typeParam = parsed.type;+ const normalizedType = typeParam ?? '';+ if (normalizedType === handledTypeParam()) return;++ if (!normalizedType) {+ setHandledTypeParam('');+ return;+ }++ const hasK8sScope =+ Boolean((parsed.context ?? '').trim()) || Boolean((parsed.namespace ?? '').trim());+ const nextMode = normalizeWorkloadViewModeParam(normalizedType);+ if (!nextMode) {+ setHandledTypeParam(normalizedType);+ return;+ }+ if (hasK8sScope && nextMode !== 'pod') {+ setHandledTypeParam(normalizedType);+ return;+ }++ setViewMode(nextMode);+ setHandledTypeParam(normalizedType);+ });++ createEffect(() => {+ const { context: contextParam } = parseWorkloadsLinkSearch(location.search);+ const normalized = contextParam ?? '';+ if (normalized === handledContextParam()) return;++ if (normalized) {+ if (viewMode() !== 'pod') {+ setViewMode('pod');+ }+ setSelectedKubernetesContext(normalized);+ if (!showFilters()) {+ setShowFilters(true);+ }+ setHandledContextParam(normalized);+ return;+ }++ setSelectedKubernetesContext(null);+ setHandledContextParam('');+ });++ createEffect(() => {+ const { namespace: namespaceParam } = parseWorkloadsLinkSearch(location.search);+ const normalized = namespaceParam ?? '';+ if (normalized === handledNamespaceParam()) return;++ if (normalized) {+ if (viewMode() !== 'pod') {+ setViewMode('pod');+ }+ setSelectedKubernetesNamespace(normalized);+ if (!showFilters()) {+ setShowFilters(true);+ }+ setHandledNamespaceParam(normalized);+ return;+ }++ setSelectedKubernetesNamespace(null);+ setHandledNamespaceParam('');+ });++ createEffect(() => {+ const { agent: agentParam } = parseWorkloadsLinkSearch(location.search);+ const normalized = agentParam ?? '';+ if (normalized === handledAgentParam()) return;++ if (normalized) {+ setSelectedHostHint(normalized);+ if (!showFilters()) {+ setShowFilters(true);+ }+ setHandledAgentParam(normalized);+ return;+ }++ setSelectedHostHint(null);+ if (selectedNode() !== null) {+ setSelectedNode(null);+ }+ setHandledAgentParam('');+ });++ createEffect(() => {+ const parsed = parseWorkloadsLinkSearch(location.search);+ const urlRuntime = parsed.runtime ?? '';+ if (urlRuntime === handledRuntimeParam()) return;++ const urlContext = parsed.context ?? '';+ const hasContext = Boolean(urlContext.trim());+ const hasNamespace = Boolean((parsed.namespace ?? '').trim());+ const urlType = parsed.type ?? '';+ const nextMode = normalizeWorkloadViewModeParam(urlType);+ const runtimeRelevant =+ !hasContext && !hasNamespace && (nextMode === 'app-container' || !urlType.trim());++ if (!runtimeRelevant) {+ setHandledRuntimeParam(urlRuntime);+ return;+ }++ if (!urlRuntime.trim()) {+ setContainerRuntime('');+ setHandledRuntimeParam('');+ return;+ }++ if (viewMode() !== 'app-container') {+ setViewMode('app-container');+ }+ setContainerRuntime(urlRuntime);+ if (!showFilters()) {+ setShowFilters(true);+ }+ setHandledRuntimeParam(urlRuntime);+ });++ createEffect(() => {+ if (!isWorkloadsRoute()) return;++ const parsed = parseWorkloadsLinkSearch(location.search);+ const urlType = parsed.type ?? '';+ const urlRuntime = parsed.runtime ?? '';+ const urlContext = parsed.context ?? '';+ const urlNamespace = parsed.namespace ?? '';+ const urlAgent = parsed.agent ?? '';+ const urlResource = parsed.resource ?? '';++ if (handledTypeParam() !== urlType) return;+ if (handledRuntimeParam() !== urlRuntime) return;+ if (handledContextParam() !== urlContext) return;+ if (handledNamespaceParam() !== urlNamespace) return;+ if (handledAgentParam() !== urlAgent) return;+ if (urlResource && handledResourceId() !== urlResource) return;++ const currentParams = new URLSearchParams(location.search);+ const nextParams = new URLSearchParams(location.search);+ const nextType = viewMode() === 'all' ? '' : viewMode();+ const nextRuntime = viewMode() === 'app-container' ? containerRuntime().trim() : '';+ const nextContext = viewMode() === 'pod' ? (selectedKubernetesContext() ?? '') : '';+ const nextNamespace = viewMode() === 'pod' ? (selectedKubernetesNamespace() ?? '') : '';+ const nextAgent = viewMode() === 'pod' ? '' : (selectedNode() ?? selectedHostHint() ?? '');++ const managedPath = buildWorkloadsPath({+ type: nextType || null,+ runtime: nextRuntime || null,+ context: nextContext || null,+ namespace: nextNamespace || null,+ agent: nextAgent || null,+ });+ const managedUrl = new URL(managedPath, 'http://pulse.local');+ nextParams.delete(WORKLOADS_QUERY_PARAMS.type);+ nextParams.delete(WORKLOADS_QUERY_PARAMS.runtime);+ nextParams.delete(WORKLOADS_QUERY_PARAMS.context);+ nextParams.delete(WORKLOADS_QUERY_PARAMS.namespace);+ nextParams.delete(WORKLOADS_QUERY_PARAMS.agent);+ managedUrl.searchParams.forEach((value, key) => {+ nextParams.set(key, value);+ });++ if (!areSearchParamsEquivalent(currentParams, nextParams)) {+ const nextSearch = nextParams.toString();+ const nextPath = nextSearch ? `${WORKLOADS_PATH}?${nextSearch}` : WORKLOADS_PATH;+ scheduleUrlSyncNavigate(nextPath);+ }+ });++ const relevantColumns = createMemo(() => {+ const base = VIEW_MODE_COLUMNS[viewMode()];+ if (!base) return null;+ if (groupingMode() === 'grouped' && base.has('node')) {+ const filtered = new Set(base);+ filtered.delete('node');+ return filtered;+ }+ return base;+ });+ const columnVisibility = useColumnVisibility(+ STORAGE_KEYS.DASHBOARD_HIDDEN_COLUMNS,+ GUEST_COLUMNS,+ ['os', 'ip'],+ relevantColumns,+ );+ const visibleColumns = columnVisibility.visibleColumns;+ const visibleColumnIds = createMemo(() => visibleColumns().map((column) => column.id));+ const mobileEssentialColumns = new Set(['name', 'cpu', 'memory', 'disk', 'link']);+ const mobileVisibleColumns = createMemo(() =>+ isMobile() ? visibleColumns().filter((column) => mobileEssentialColumns.has(column.id)) : visibleColumns(),+ );+ const mobileVisibleColumnIds = createMemo(() =>+ isMobile() ? mobileVisibleColumns().map((column) => column.id) : visibleColumnIds(),+ );+ const totalColumns = createMemo(() => mobileVisibleColumns().length);++ const refreshGuestMetadata = async () => {+ try {+ const metadata = await GuestMetadataAPI.getAllMetadata();+ updateGuestMetadataState(() => metadata || {});+ logger.debug('Guest metadata refreshed');+ } catch (err) {+ logger.debug('Failed to refresh guest metadata', err);+ }+ };++ onMount(() => {+ void refreshGuestMetadata();++ const handleMetadataChanged = (event: Event) => {+ const customEvent = event as CustomEvent;+ logger.debug('[Dashboard] Metadata changed event received', customEvent.detail);++ if (customEvent.detail?.payload) {+ let { guestId, url } = customEvent.detail.payload;+ if (guestId) {+ if (guestId.includes(':')) {+ const parts = guestId.split(':');+ if (parts.length === 3) {+ const [instance, _node, vmid] = parts;+ guestId = `${instance}-${vmid}`;+ logger.debug('[Dashboard] Normalized optimistic guestId', {+ original: customEvent.detail.payload.guestId,+ normalized: guestId,+ });+ }+ }++ logger.debug('[Dashboard] Applying optimistic metadata update', { guestId, url });+ handleCustomUrlUpdate(guestId, url || '');+ return;+ }+ }++ logger.debug('Metadata changed event received, refreshing...');+ void refreshGuestMetadata();+ };++ logger.debug('[Dashboard] Adding pulse:metadata-changed listener');+ window.addEventListener('pulse:metadata-changed', handleMetadataChanged);+ const unsubscribeOrgSwitched = eventBus.on('org_switched', (nextOrgID) => {+ setOrgScope(normalizeOrgScope(nextOrgID));+ void refreshGuestMetadata();+ });++ onCleanup(() => {+ window.removeEventListener('pulse:metadata-changed', handleMetadataChanged);+ unsubscribeOrgSwitched();+ });+ });++ let lastConnected = connected();+ createEffect(() => {+ const isConnected = connected();+ if (workloadsEnabled() && isConnected && !lastConnected) {+ void workloads.refetch();+ }+ lastConnected = isConnected;+ });++ const handleCustomUrlUpdate = (guestId: string, url: string) => {+ const trimmedUrl = url.trim();+ const nextUrl = trimmedUrl === '' ? undefined : trimmedUrl;+ const currentUrl = guestMetadata()[guestId]?.customUrl;+ if (currentUrl === nextUrl) {+ return;+ }++ updateGuestMetadataState((prev) => {+ const previousEntry = prev[guestId];++ if (nextUrl === undefined) {+ if (!previousEntry || typeof previousEntry.customUrl === 'undefined') {+ return prev;+ }+ const { customUrl: _removed, ...restEntry } = previousEntry;+ const hasAdditionalMetadata = Object.entries(restEntry).some(+ ([key, value]) => key !== 'id' && value !== undefined,+ );++ if (!hasAdditionalMetadata) {+ const { [guestId]: _omit, ...rest } = prev;+ return rest;+ }++ return {+ ...prev,+ [guestId]: {+ ...restEntry,+ id: restEntry.id ?? guestId,+ },+ };+ }++ if (previousEntry && previousEntry.customUrl === nextUrl) {+ return prev;+ }++ const nextEntry: GuestMetadata = {+ ...(previousEntry || { id: guestId }),+ customUrl: nextUrl,+ };++ return {+ ...prev,+ [guestId]: nextEntry,+ };+ });+ };++ const nodeByInstance = createMemo(() => buildNodeByInstance(props.nodes));+ const guestParentNodeMap = createMemo(() =>+ buildGuestParentNodeMap(allGuests(), nodeByInstance()),+ );++ const handleSort = (key: WorkloadSortKey) => {+ if (sortKey() === key) {+ setSortDirection(sortDirection() === 'asc' ? 'desc' : 'asc');+ } else {+ setSortKey(key);+ if (+ key === 'cpu' ||+ key === 'memory' ||+ key === 'disk' ||+ key === 'diskIo' ||+ key === 'netIo' ||+ key === 'uptime'+ ) {+ setSortDirection('desc');+ } else {+ setSortDirection('asc');+ }+ }+ };++ const guestSortComparator = createMemo(() =>+ createWorkloadSortComparator(sortKey() || '', sortDirection()),+ );++ createEffect(() => {+ const handleKeyDown = (event: KeyboardEvent) => {+ if (event.key === 'Escape') {+ const hasActiveFilters =+ search().trim() ||+ sortKey() !== 'type' ||+ sortDirection() !== 'asc' ||+ selectedNode() !== null ||+ selectedHostHint() !== null ||+ selectedKubernetesContext() !== null ||+ selectedKubernetesNamespace() !== null ||+ containerRuntime().trim() !== '' ||+ viewMode() !== 'all' ||+ statusMode() !== 'all';++ if (hasActiveFilters) {+ setSearch('');+ setIsSearchLocked(false);+ setSortKey('type');+ setSortDirection('asc');+ setSelectedNode(null);+ setSelectedHostHint(null);+ setSelectedKubernetesContext(null);+ setSelectedKubernetesNamespace(null);+ setContainerRuntime('');+ setViewMode('all');+ setStatusMode('all');++ blurFocusedTypeToSearch();+ } else {+ setShowFilters(!showFilters());+ }+ }+ };++ document.addEventListener('keydown', handleKeyDown);+ return () => document.removeEventListener('keydown', handleKeyDown);+ });++ const filteredGuests = createMemo(() => {+ const params: FilterWorkloadsParams = {+ guests: allGuests(),+ viewMode: viewMode(),+ statusMode: statusMode(),+ searchTerm: search().trim(),+ selectedNode: selectedNode(),+ selectedHostHint: selectedHostHint(),+ selectedKubernetesContext: selectedKubernetesContext(),+ selectedKubernetesNamespace: selectedKubernetesNamespace(),+ containerRuntime: containerRuntime().trim() || null,+ };+ return filterWorkloads(params);+ });++ const workloadsSummaryVisibleIds = createMemo<string[]>(() =>+ filteredGuests().map((guest) => getCanonicalWorkloadId(guest)),+ );++ const workloadsSummaryFallbackCounts = createMemo(() => {+ const guests = filteredGuests();+ const running = guests.filter(+ (guest) => guest.status === 'running' || guest.status === 'online',+ ).length;+ return {+ total: guests.length,+ running,+ stopped: Math.max(0, guests.length - running),+ };+ });++ const workloadsSummaryFallbackSnapshots = createMemo<WorkloadSummarySnapshot[]>(() =>+ filteredGuests().map((guest) => {+ const guestId = getCanonicalWorkloadId(guest);+ const memoryUsage = workloadMetricPercent(guest.memory?.usage);+ let diskUsage = workloadMetricPercent(guest.disk?.usage);+ if (+ (!diskUsage || diskUsage <= 0) &&+ typeof guest.disk?.used === 'number' &&+ typeof guest.disk?.total === 'number' &&+ Number.isFinite(guest.disk.used) &&+ Number.isFinite(guest.disk.total) &&+ guest.disk.total > 0+ ) {+ const selectorDiskUsage = getDiskUsagePercent(guest);+ const rawDiskUsage = (guest.disk.used / guest.disk.total) * 100;+ diskUsage = rawDiskUsage > 100 ? rawDiskUsage : (selectorDiskUsage ?? rawDiskUsage);+ }++ return {+ id: guestId,+ name: guest.name || guestId,+ cpu: workloadMetricPercent(guest.cpu),+ memory: memoryUsage,+ disk: Math.max(0, diskUsage),+ network: Math.max(0, guest.networkIn || 0) + Math.max(0, guest.networkOut || 0),+ };+ }),+ );++ createEffect(() => {+ const hoveredId = hoveredWorkloadId();+ if (!hoveredId) return;+ const exists = filteredGuests().some((guest) => getCanonicalWorkloadId(guest) === hoveredId);+ if (!exists) {+ setHoveredWorkloadId(null);+ }+ });++ const getGroupLabel = (+ groupKey: string,+ guests: WorkloadGuest[],+ ): { type: string; name: string } => {+ const node = nodeByInstance()[groupKey];+ if (node) return { type: '', name: getNodeDisplayName(node) };+ const normalizedGroupKey = guests.length > 0 ? getWorkloadGroupKey(guests[0]) : groupKey;+ const [prefix, ...rest] = normalizedGroupKey.split(':');+ const context = rest.length > 0 ? rest.join(':') : normalizedGroupKey;+ if (prefix === 'app-container') return { type: 'App Containers', name: context };+ if (prefix === 'pod') return { type: 'Pods', name: context };+ if (prefix === 'vm') return { type: 'VM', name: context };+ if (prefix === 'system-container') return { type: 'Container', name: context };+ const first = guests[0];+ if (first) {+ const cluster = (first.clusterName || '').trim();+ const nodeName = (first.node || '').trim();+ if (nodeName && cluster) return { type: cluster, name: nodeName };+ if (nodeName) return { type: '', name: nodeName };+ }+ return { type: '', name: context };+ };++ const groupedGuests = createMemo(() =>+ groupWorkloads(filteredGuests(), groupingMode(), guestSortComparator()),+ );++ const sortedGroupKeys = createMemo(() => {+ const groups = groupedGuests();+ const nodes = nodeByInstance();+ return Object.keys(groups).sort((a, b) => {+ const nodeA = nodes[a];+ const nodeB = nodes[b];+ const labelA = nodeA ? getNodeDisplayName(nodeA) : getGroupLabel(a, groups[a]).name;+ const labelB = nodeB ? getNodeDisplayName(nodeB) : getGroupLabel(b, groups[b]).name;+ return labelA.localeCompare(labelB) || a.localeCompare(b);+ });+ });++ const guestGlobalIndexById = createMemo(() => {+ const indexById = new Map<string, number>();+ const groups = groupedGuests();+ let globalIndex = 0;++ for (const groupKey of sortedGroupKeys()) {+ const guests = groups[groupKey] || [];+ for (const guest of guests) {+ indexById.set(getCanonicalWorkloadId(guest), globalIndex);+ globalIndex += 1;+ }+ }++ return indexById;+ });++ const revealGuestIndex = createMemo<number | null>(() => {+ const selectedId = selectedGuestId();+ if (!selectedId) return null;+ return guestGlobalIndexById().get(selectedId) ?? null;+ });++ const groupedWindowing = useGroupedTableWindowing({+ totalRowCount: () => filteredGuests().length,+ revealIndex: revealGuestIndex,+ });++ const groupStartIndexByKey = createMemo(() => {+ const starts = new Map<string, number>();+ const groups = groupedGuests();+ let globalIndex = 0;++ for (const groupKey of sortedGroupKeys()) {+ starts.set(groupKey, globalIndex);+ globalIndex += (groups[groupKey] || []).length;+ }++ return starts;+ });++ const windowedGroupedGuests = createMemo<Record<string, WorkloadGuest[]>>(() => {+ const groups = groupedGuests();+ if (!groupedWindowing.isWindowed()) {+ return groups;+ }++ const starts = groupStartIndexByKey();+ const result: Record<string, WorkloadGuest[]> = {};+ for (const groupKey of sortedGroupKeys()) {+ const guests = groups[groupKey] || [];+ const groupStart = starts.get(groupKey) ?? 0;+ const visible = groupedWindowing.getVisibleSlice(groupKey, guests, groupStart);+ if (visible.length > 0) {+ result[groupKey] = visible;+ }+ }++ return result;+ });++ const visibleGroupKeys = createMemo(() => {+ const keys = sortedGroupKeys();+ if (!groupedWindowing.isWindowed()) return keys;+ const groups = windowedGroupedGuests();+ return keys.filter((groupKey) => (groups[groupKey] || []).length > 0);+ });++ const topSpacerHeight = createMemo(() =>+ groupedWindowing.isWindowed()+ ? groupedWindowing.startIndex() * DASHBOARD_TABLE_ESTIMATED_ROW_HEIGHT+ : 0,+ );++ const bottomSpacerHeight = createMemo(() =>+ groupedWindowing.isWindowed()+ ? Math.max(+ 0,+ (filteredGuests().length - groupedWindowing.endIndex()) *+ DASHBOARD_TABLE_ESTIMATED_ROW_HEIGHT,+ )+ : 0,+ );++ const syncGuestWindowToViewport = () => {+ if (!groupedWindowing.isWindowed() || typeof window === 'undefined') return;+ const body = tableBodyRef();+ if (!body) return;+ const rect = body.getBoundingClientRect();+ const scrollTop = Math.max(0, -rect.top);+ groupedWindowing.onScroll(scrollTop, window.innerHeight, DASHBOARD_TABLE_ESTIMATED_ROW_HEIGHT);+ };++ createEffect(() => {+ if (typeof window === 'undefined') return;+ filteredGuests().length;+ if (!groupedWindowing.isWindowed()) return;+ if (!tableBodyRef()) return;++ const handleViewportChange = () => {+ syncGuestWindowToViewport();+ };++ handleViewportChange();+ window.addEventListener('scroll', handleViewportChange, { passive: true });+ window.addEventListener('resize', handleViewportChange);+ onCleanup(() => {+ window.removeEventListener('scroll', handleViewportChange);+ window.removeEventListener('resize', handleViewportChange);+ });+ });++ const totalStats = createMemo<WorkloadStats>(() => computeWorkloadStats(filteredGuests()));+ const workloadIOEmphasis = createMemo(() => computeWorkloadIOEmphasis(filteredGuests()));++ const handleNodeSelect = (nodeId: string | null, nodeType: 'pve' | 'pbs' | 'pmg' | null) => {+ logger.debug('handleNodeSelect called', { nodeId, nodeType });++ if (nodeType === 'pve' || nodeType === null) {+ setSelectedHostHint(null);+ setSelectedNode(nodeId);+ logger.debug('Set selected node', { nodeId });+ if (nodeId && !showFilters()) {+ setShowFilters(true);+ }+ }+ };++ const handleBeforeAutoFocus = () => {+ if (aiChatStore.focusInput()) return true;+ if (!showFilters()) setShowFilters(true);+ return false;+ };++ const handleTagClick = (tag: string) => {+ const currentSearch = search().trim();+ const tagFilter = `tags:${tag}`;++ if (currentSearch.includes(tagFilter)) {+ let newSearch = currentSearch;++ if (currentSearch === tagFilter) {+ newSearch = '';+ } else if (currentSearch.startsWith(tagFilter + ',')) {+ newSearch = currentSearch.replace(tagFilter + ',', '').trim();+ } else if (currentSearch.endsWith(', ' + tagFilter)) {+ newSearch = currentSearch.replace(', ' + tagFilter, '').trim();+ } else if (currentSearch.includes(', ' + tagFilter + ',')) {+ newSearch = currentSearch.replace(', ' + tagFilter + ',', ',').trim();+ } else if (currentSearch.includes(tagFilter + ', ')) {+ newSearch = currentSearch.replace(tagFilter + ', ', '').trim();+ }++ setSearch(newSearch);+ if (!newSearch) {+ setIsSearchLocked(false);+ }+ } else {+ if (!currentSearch || isSearchLocked()) {+ setSearch(tagFilter);+ setIsSearchLocked(false);+ } else {+ setSearch(`${currentSearch}, ${tagFilter}`);+ }++ if (!showFilters()) {+ setShowFilters(true);+ }+ }+ };++ return {+ activeAlerts,+ alertsEnabled,+ allGuests,+ bottomSpacerHeight,+ columnVisibility,+ connected,+ containerRuntime,+ containerRuntimeOptions,+ dashboardDisconnectedState,+ dashboardGuestsEmptyState,+ dashboardInfrastructureEmptyState,+ dashboardLoadingState,+ filteredGuests,+ getGroupLabel,+ groupedGuests,+ groupedWindowing,+ guestMetadata,+ guestParentNodeMap,+ handleBeforeAutoFocus,+ handleCustomUrlUpdate,+ handleNodeSelect,+ handleSort,+ handleTagClick,+ hoveredWorkloadId,+ initialDataReceived,+ isMobile,+ isSearchLocked,+ isWorkloadsRoute,+ kioskMode,+ kubernetesContextOptions,+ kubernetesNamespaceOptions,+ mobileVisibleColumnIds,+ mobileVisibleColumns,+ navigate,+ nodeByInstance,+ reconnect,+ search,+ selectedGuestId,+ selectedKubernetesContext,+ selectedKubernetesNamespace,+ selectedNode,+ setContainerRuntime,+ setGroupingMode,+ setHoveredWorkloadId,+ setSearch,+ setSelectedGuestId,+ setSelectedKubernetesContext,+ setSelectedKubernetesNamespace,+ setSortDirection,+ setSortKey,+ setStatusMode,+ setTableBodyRef,+ setTableWrapperRef,+ setViewMode,+ setWorkloadsSummaryCollapsed,+ setWorkloadsSummaryRange,+ sortDirection,+ sortKey,+ statusMode,+ topSpacerHeight,+ totalColumns,+ totalStats,+ viewMode,+ visibleColumns,+ visibleGroupKeys,+ windowedGroupedGuests,+ workloadIOEmphasis,+ workloadNodeOptions,+ workloads,+ workloadsSummaryCollapsed,+ workloadsSummaryFallbackCounts,+ workloadsSummaryFallbackSnapshots,+ workloadsSummaryRange,+ workloadsSummaryVisibleIds,+ ws,+ groupingMode,+ } as const;+}diff --git a/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts b/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.tsindex d15706479e..5537d88877 100644--- a/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts+++ b/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts@@ -49,6 +49,7 @@ import recoveryTablePresentationSource from '@/utils/recoveryTablePresentation.timport recoveryTimelineChartPresentationSource from '@/utils/recoveryTimelineChartPresentation.ts?raw';import recoveryTimelinePresentationSource from '@/utils/recoveryTimelinePresentation.ts?raw';import dashboardSource from '@/components/Dashboard/Dashboard.tsx?raw';+import dashboardStateSource from '@/components/Dashboard/useDashboardState.ts?raw';import workloadsSummarySource from '@/components/Workloads/WorkloadsSummary.tsx?raw';import dashboardRouteSource from '@/pages/Dashboard.tsx?raw';import dashboardHelpersSource from '@/pages/DashboardPanels/dashboardHelpers.ts?raw';@@ -399,14 +400,16 @@ describe('frontend resource type boundaries', () => {expect(workloadsSource).toContain('export const normalizeWorkloadViewModeParam');expect(orgScopeSource).toContain("export const DEFAULT_ORG_SCOPE = 'default'");expect(orgScopeSource).toContain('export const normalizeOrgScope');- expect(dashboardSource).toContain('normalizeWorkloadViewModeParam');+ expect(dashboardSource).toContain('useDashboardState');+ expect(dashboardSource).not.toContain('const [search, setSearch] = createSignal(');+ expect(dashboardStateSource).toContain('normalizeWorkloadViewModeParam');expect(dashboardSource).not.toContain('function normalizeViewModeParam');expect(dashboardSource).not.toContain('workloadSummaryGuestId');expect(dashboardSource).toContain('createMemo(() => getCanonicalWorkloadId(guest()))');- expect(dashboardSource).toContain('normalizeOrgScope(getOrgID())');- expect(dashboardSource).not.toContain("const DEFAULT_ORG_SCOPE = 'default'");- expect(dashboardSource).not.toContain('const normalizeOrgScope =');- expect(dashboardSource).not.toContain('const guestId = () => {');+ expect(dashboardStateSource).toContain('normalizeOrgScope(getOrgID())');+ expect(dashboardStateSource).not.toContain("const DEFAULT_ORG_SCOPE = 'default'");+ expect(dashboardStateSource).not.toContain('const normalizeOrgScope =');+ expect(dashboardStateSource).not.toContain('const guestId = () => {');expect(workloadsSummarySource).toContain('normalizeOrgScope(getOrgID())');expect(workloadsSummarySource).not.toContain("const DEFAULT_ORG_SCOPE = 'default'");expect(workloadsSummarySource).not.toContain('const normalizeOrgScope =');@@ -2795,10 +2798,10 @@ describe('frontend resource type boundaries', () => {});it('keeps dashboard empty-state copy in a shared presentation utility', () => {- expect(dashboardSource).toContain('getDashboardInfrastructureEmptyState');- expect(dashboardSource).toContain('getDashboardGuestsEmptyState');- expect(dashboardSource).toContain('getDashboardLoadingState');- expect(dashboardSource).toContain('getDashboardDisconnectedState');+ expect(dashboardStateSource).toContain('getDashboardInfrastructureEmptyState');+ expect(dashboardStateSource).toContain('getDashboardGuestsEmptyState');+ expect(dashboardStateSource).toContain('getDashboardLoadingState');+ expect(dashboardStateSource).toContain('getDashboardDisconnectedState');expect(dashboardSource).not.toContain('Loading dashboard data...');expect(dashboardSource).not.toContain('Connection lost');expect(dashboardSource).not.toContain('Attempting to reconnect…');