Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

Canonicalize realtime resource state in websocket store

rcourtman9fed7c2c12cc
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index be21ed3085..c9bb0316a2 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -90,11 +90,12 @@ querying, and the operator-facing storage health presentation layer.
That same adjacent API boundary now also owns SSO outbound discovery and metadata fetch trust: storage- and recovery-adjacent surfaces may share `internal/api/sso_outbound.go`, `internal/api/saml_service.go`, and `internal/api/oidc_service.go`, but they must not fork separate metadata/discovery HTTP clients, redirect policies, or credential-file read rules when they depend on shared backend auth helpers.
5. Route canonical storage/recovery resource selection through `frontend-modern/src/hooks/useUnifiedResources.ts` and the owning `unified-resources` contract
That shared hook now also projects resource `clusterId` through the shared cluster-name helper, so storage and recovery links keep the same cluster-context label as other unified-resource consumers instead of rebuilding a local fallback chain.
- That shared hook must keep realtime transport merges canonical for
- storage/recovery consumers too: thinner websocket `state.resources`
- payloads may refresh status and metrics, but they must not downgrade richer
- REST-hydrated platform summary fields or synthesize standalone `clusterId`
- values from resource names while the same session is open.
+ That shared hook plus the adjacent websocket/store adapter path must keep
+ realtime transport merges canonical for storage/recovery consumers too:
+ thinner websocket `state.resources` payloads may refresh status and metrics,
+ but they must not downgrade richer REST-hydrated platform summary fields or
+ synthesize standalone `clusterId` values from resource names while the same
+ session is open.
Storage and recovery consumers must also inherit the hook's canonical
`ResourceType` normalization for route/query filters, so storage subtypes
such as `physical_disk` stay on the same cache-backed snapshot instead of
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 69d8935cb4..ed8844a99b 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -163,17 +163,20 @@ assembly branch.
7. Add or change resource drawer timeline/facet presentation through `frontend-modern/src/components/Infrastructure/ResourceDetailDrawer.tsx`, `frontend-modern/src/components/Infrastructure/ResourceDetailDrawerOverviewTab.tsx`, `frontend-modern/src/components/Infrastructure/ResourceDetailDrawerDebugTab.tsx`, `frontend-modern/src/components/Infrastructure/useResourceDetailDrawerState.ts`, `frontend-modern/src/components/Infrastructure/ResourceFacetSummary.tsx`, `frontend-modern/src/components/Infrastructure/resourceDetailMappers.ts`, and the governed `internal/api/resources.go` facet/timeline contract together
8. Add or change discovery-support runtime under the resource drawer through `frontend-modern/src/components/Discovery/DiscoveryTab.tsx` for shell/presentation ownership and `frontend-modern/src/components/Discovery/useDiscoveryTabState.ts` for fetch, websocket-progress, and notes-mutation ownership
9. Keep dashboard and infrastructure freshness on the canonical unified-resource
- ownership path. `frontend-modern/src/hooks/useUnifiedResources.ts` may use
- REST for initial hydration and unsupported filtered queries, but supported
- snapshot freshness must come from websocket `state.resources` instead of
- layering confirmatory dashboard/infrastructure REST refetch loops over
- already-owned resource updates.
- That shared hook must also preserve canonical row shape across transport
- boundaries: thinner realtime `state.resources` payloads must merge into the
- existing canonical resource snapshot instead of downgrading richer REST-only
- infrastructure details such as disk I/O, source metadata, or platform
- summary fields after first hydrate.
- Canonical cluster membership in that shared hook must come only from
+ ownership path. `frontend-modern/src/stores/websocket.ts`,
+ `frontend-modern/src/utils/resourceStateAdapters.ts`, and
+ `frontend-modern/src/hooks/useUnifiedResources.ts` together own the frontend
+ canonicalization boundary: REST may hydrate the initial snapshot and
+ unsupported filtered queries, but supported snapshot freshness must come
+ from websocket `state.resources` instead of layering confirmatory
+ dashboard/infrastructure REST refetch loops over already-owned resource
+ updates.
+ That shared store/adapter/hook path must also preserve canonical row shape
+ across transport boundaries: thinner realtime `state.resources` payloads
+ must merge into the existing canonical resource snapshot instead of
+ downgrading richer REST-only infrastructure details such as disk I/O, source
+ metadata, or platform summary fields after first hydrate.
+ Canonical cluster membership in that shared path must come only from
explicit cluster identity such as Kubernetes context or platform cluster
labels; standalone resource names must never be repurposed as synthetic
`clusterId` values.
diff --git a/frontend-modern/src/hooks/useUnifiedResources.ts b/frontend-modern/src/hooks/useUnifiedResources.ts
index 171fbb90f2..b78f57ae4e 100644
--- a/frontend-modern/src/hooks/useUnifiedResources.ts
+++ b/frontend-modern/src/hooks/useUnifiedResources.ts
@@ -25,6 +25,7 @@ import { canonicalDiscoveryResourceType } from '@/utils/discoveryTarget';
import { canonicalizeFrontendResourceType } from '@/utils/resourceTypeCompat';
import { getPreferredNormalizedPlatformId } from '@/utils/resourceIdentity';
import { getExplicitResourceClusterName } from '@/utils/agentResources';
+import { mergeCanonicalResourceSnapshot } from '@/utils/resourceStateAdapters';
import {
resolvePlatformTypeFromSources,
resolveSourceTypeFromSources,
@@ -106,8 +107,6 @@ type APIHostRAIDArray = {
rebuildSpeed?: string;
};
-type JsonRecord = Record<string, unknown>;
-
type APIKubernetesData = {
clusterId?: string;
clusterName?: string;
@@ -570,332 +569,6 @@ const metricToResourceMetric = (metric?: APIMetricValue) => {
};
};
-const asRecord = (value: unknown): JsonRecord | undefined =>
- value && typeof value === 'object' && !Array.isArray(value) ? (value as JsonRecord) : undefined;
-
-const mergeStringArrays = (
- incoming?: string[],
- existing?: string[],
-): string[] | undefined => {
- const merged = [...(incoming ?? []), ...(existing ?? [])]
- .map((value) => asTrimmedString(value))
- .filter((value): value is string => Boolean(value));
- return merged.length > 0 ? Array.from(new Set(merged)) : undefined;
-};
-
-const mergeRecord = <T extends JsonRecord>(incoming?: T, existing?: T): T | undefined => {
- if (!incoming) return existing;
- if (!existing) return incoming;
- return { ...existing, ...incoming };
-};
-
-const mergePlatformData = (
- incomingValue: Resource['platformData'],
- existingValue: Resource['platformData'],
-): Resource['platformData'] => {
- const incoming = asRecord(incomingValue);
- const existing = asRecord(existingValue);
- if (!incoming) return existingValue;
- if (!existing) return incomingValue;
-
- const merged: JsonRecord = { ...existing, ...incoming };
- for (const key of [
- 'agent',
- 'docker',
- 'proxmox',
- 'pbs',
- 'pmg',
- 'kubernetes',
- 'vmware',
- 'storage',
- 'physicalDisk',
- 'ceph',
- 'metrics',
- 'discoveryTarget',
- ]) {
- const nested = mergeRecord(asRecord(incoming[key]), asRecord(existing[key]));
- if (nested) {
- merged[key] = nested;
- }
- }
-
- const sourceStatus = mergeRecord(
- asRecord(incoming.sourceStatus),
- asRecord(existing.sourceStatus),
- );
- if (sourceStatus) {
- merged.sourceStatus = sourceStatus;
- }
-
- const sources = mergeStringArrays(
- Array.isArray(incoming.sources) ? (incoming.sources as string[]) : undefined,
- Array.isArray(existing.sources) ? (existing.sources as string[]) : undefined,
- );
- if (sources) {
- merged.sources = sources;
- }
-
- return merged;
-};
-
-const deriveLegacySourceList = (resource: Resource): string[] | undefined => {
- switch (resource.platformType) {
- case 'proxmox-pve':
- return resource.sourceType === 'hybrid' ? ['proxmox', 'agent'] : ['proxmox'];
- case 'docker':
- return ['docker'];
- case 'kubernetes':
- return resource.sourceType === 'hybrid' ? ['agent', 'kubernetes'] : ['kubernetes'];
- case 'proxmox-pbs':
- return ['pbs'];
- case 'proxmox-pmg':
- return ['pmg'];
- case 'truenas':
- return ['truenas'];
- case 'vmware-vsphere':
- return ['vmware'];
- default:
- return resource.sourceType === 'agent' ? ['agent'] : undefined;
- }
-};
-
-const canonicalizeLegacyPlatformData = (resource: Resource): Resource['platformData'] => {
- const platformData = asRecord(resource.platformData);
- if (!platformData) {
- return resource.platformData;
- }
-
- const normalized: JsonRecord = { ...platformData };
- const normalizedSources =
- Array.isArray(platformData.sources) && platformData.sources.length > 0
- ? (platformData.sources as string[])
- : deriveLegacySourceList(resource);
- if (normalizedSources && normalizedSources.length > 0) {
- normalized.sources = normalizedSources;
- }
-
- if (!asRecord(platformData.agent)) {
- const agentPayload: JsonRecord = {};
- for (const [legacyKey, nextKey] of [
- ['agentId', 'agentId'],
- ['agentVersion', 'agentVersion'],
- ['hostname', 'hostname'],
- ['platform', 'platform'],
- ['osName', 'osName'],
- ['osVersion', 'osVersion'],
- ['kernelVersion', 'kernelVersion'],
- ['architecture', 'architecture'],
- ['commandsEnabled', 'commandsEnabled'],
- ] as const) {
- if (platformData[legacyKey] !== undefined) {
- agentPayload[nextKey] = platformData[legacyKey];
- }
- }
- if (platformData.memory !== undefined) agentPayload.memory = platformData.memory;
- if (platformData.interfaces !== undefined) agentPayload.networkInterfaces = platformData.interfaces;
- if (platformData.disks !== undefined) agentPayload.disks = platformData.disks;
- if (Object.keys(agentPayload).length > 0) {
- normalized.agent = agentPayload;
- }
- }
-
- if (!asRecord(platformData.docker)) {
- const dockerPayload: JsonRecord = {};
- for (const [legacyKey, nextKey] of [
- ['agentId', 'agentId'],
- ['runtime', 'runtime'],
- ['runtimeVersion', 'runtimeVersion'],
- ['dockerVersion', 'dockerVersion'],
- ['os', 'os'],
- ['kernelVersion', 'kernelVersion'],
- ['architecture', 'architecture'],
- ['agentVersion', 'agentVersion'],
- ['hostname', 'hostname'],
- ['displayName', 'displayName'],
- ['machineId', 'machineId'],
- ['containerCount', 'containerCount'],
- ['uptimeSeconds', 'uptimeSeconds'],
- ['intervalSeconds', 'intervalSeconds'],
- ['temperature', 'temperature'],
- ['hostSourceId', 'hostSourceId'],
- ] as const) {
- if (platformData[legacyKey] !== undefined) {
- dockerPayload[nextKey] = platformData[legacyKey];
- }
- }
- if (platformData.swarm !== undefined) dockerPayload.swarm = platformData.swarm;
- if (platformData.interfaces !== undefined) dockerPayload.networkInterfaces = platformData.interfaces;
- if (platformData.disks !== undefined) dockerPayload.disks = platformData.disks;
- if (Object.keys(dockerPayload).length > 0) {
- normalized.docker = dockerPayload;
- }
- }
-
- if (!asRecord(platformData.proxmox)) {
- const proxmoxPayload: JsonRecord = {};
- for (const [legacyKey, nextKey] of [
- ['instance', 'instance'],
- ['node', 'nodeName'],
- ['clusterName', 'clusterName'],
- ['vmid', 'vmid'],
- ['cpus', 'cpus'],
- ['template', 'template'],
- ['swapUsed', 'swapUsed'],
- ['swapTotal', 'swapTotal'],
- ['balloon', 'balloon'],
- ] as const) {
- if (platformData[legacyKey] !== undefined) {
- proxmoxPayload[nextKey] = platformData[legacyKey];
- }
- }
- if (platformData.disks !== undefined) proxmoxPayload.disks = platformData.disks;
- if (Object.keys(proxmoxPayload).length > 0) {
- normalized.proxmox = proxmoxPayload;
- }
- }
-
- if (!asRecord(platformData.pbs)) {
- const pbsPayload: JsonRecord = {};
- if (platformData.host !== undefined) pbsPayload.hostname = platformData.host;
- if (platformData.version !== undefined) pbsPayload.version = platformData.version;
- if (platformData.connectionHealth !== undefined) {
- pbsPayload.connectionHealth = platformData.connectionHealth;
- }
- if (platformData.numDatastores !== undefined) {
- pbsPayload.datastoreCount = platformData.numDatastores;
- }
- if (Object.keys(pbsPayload).length > 0) {
- normalized.pbs = pbsPayload;
- }
- }
-
- if (!asRecord(platformData.pmg)) {
- const pmgPayload: JsonRecord = {};
- if (platformData.host !== undefined) pmgPayload.hostname = platformData.host;
- if (platformData.version !== undefined) pmgPayload.version = platformData.version;
- if (platformData.connectionHealth !== undefined) {
- pmgPayload.connectionHealth = platformData.connectionHealth;
- }
- for (const [legacyKey, nextKey] of [
- ['nodeCount', 'nodeCount'],
- ['queueActive', 'queueActive'],
- ['queueDeferred', 'queueDeferred'],
- ['queueHold', 'queueHold'],
- ['queueIncoming', 'queueIncoming'],
- ['queueTotal', 'queueTotal'],
- ] as const) {
- if (platformData[legacyKey] !== undefined) {
- pmgPayload[nextKey] = platformData[legacyKey];
- }
- }
- if (Object.keys(pmgPayload).length > 0) {
- normalized.pmg = pmgPayload;
- }
- }
-
- if (!asRecord(platformData.kubernetes)) {
- const kubernetesPayload: JsonRecord = {};
- for (const [legacyKey, nextKey] of [
- ['agentId', 'agentId'],
- ['clusterId', 'clusterId'],
- ['context', 'context'],
- ['nodeName', 'nodeName'],
- ['namespace', 'namespace'],
- ['clusterName', 'clusterName'],
- ['pendingUninstall', 'pendingUninstall'],
- ] as const) {
- if (platformData[legacyKey] !== undefined) {
- kubernetesPayload[nextKey] = platformData[legacyKey];
- }
- }
- if (Object.keys(kubernetesPayload).length > 0) {
- normalized.kubernetes = kubernetesPayload;
- }
- }
-
- return normalized;
-};
-
-const canonicalizeRealtimeResource = (resource: Resource): Resource => {
- const platformData = canonicalizeLegacyPlatformData(resource);
- const platformRecord = asRecord(platformData);
- const normalizedBase = {
- ...resource,
- platformData,
- };
- return {
- ...normalizedBase,
- clusterId: resource.clusterId ?? getExplicitResourceClusterName(normalizedBase),
- platformData,
- agent: resource.agent ?? (platformRecord?.agent as Resource['agent']),
- proxmox: resource.proxmox ?? (platformRecord?.proxmox as Resource['proxmox']),
- pbs: resource.pbs ?? (platformRecord?.pbs as Resource['pbs']),
- kubernetes: resource.kubernetes ?? (platformRecord?.kubernetes as Resource['kubernetes']),
- vmware: resource.vmware ?? (platformRecord?.vmware as Resource['vmware']),
- storage: resource.storage ?? (platformRecord?.storage as Resource['storage']),
- physicalDisk:
- resource.physicalDisk ?? (platformRecord?.physicalDisk as Resource['physicalDisk']),
- };
-};
-
-const mergeCanonicalIdentity = (
- incoming?: Resource['canonicalIdentity'],
- existing?: Resource['canonicalIdentity'],
-): Resource['canonicalIdentity'] => {
- if (!incoming) return existing;
- if (!existing) return incoming;
- const aliases = mergeStringArrays(incoming.aliases, existing.aliases);
- return {
- ...existing,
- ...incoming,
- aliases,
- };
-};
-
-const mergeCanonicalResource = (incoming: Resource, existing?: Resource): Resource => {
- if (!existing) {
- return incoming;
- }
- return {
- ...existing,
- ...incoming,
- clusterId: incoming.clusterId ?? existing.clusterId,
- discoveryTarget: incoming.discoveryTarget ?? existing.discoveryTarget,
- metricsTarget: incoming.metricsTarget ?? existing.metricsTarget,
- canonicalIdentity: mergeCanonicalIdentity(incoming.canonicalIdentity, existing.canonicalIdentity),
- policy: incoming.policy ?? existing.policy,
- aiSafeSummary: incoming.aiSafeSummary ?? existing.aiSafeSummary,
- recentChanges: incoming.recentChanges ?? existing.recentChanges,
- facetCounts: incoming.facetCounts ?? existing.facetCounts,
- diskIO: incoming.diskIO ?? existing.diskIO,
- agent: mergeRecord(incoming.agent as JsonRecord | undefined, existing.agent as JsonRecord | undefined) as Resource['agent'],
- proxmox: mergeRecord(incoming.proxmox as JsonRecord | undefined, existing.proxmox as JsonRecord | undefined) as Resource['proxmox'],
- pbs: mergeRecord(incoming.pbs as JsonRecord | undefined, existing.pbs as JsonRecord | undefined) as Resource['pbs'],
- kubernetes: mergeRecord(incoming.kubernetes as JsonRecord | undefined, existing.kubernetes as JsonRecord | undefined) as Resource['kubernetes'],
- vmware: mergeRecord(incoming.vmware as JsonRecord | undefined, existing.vmware as JsonRecord | undefined) as Resource['vmware'],
- storage: mergeRecord(incoming.storage as JsonRecord | undefined, existing.storage as JsonRecord | undefined) as Resource['storage'],
- physicalDisk: mergeRecord(incoming.physicalDisk as JsonRecord | undefined, existing.physicalDisk as JsonRecord | undefined) as Resource['physicalDisk'],
- identity: mergeRecord(incoming.identity as JsonRecord | undefined, existing.identity as JsonRecord | undefined) as Resource['identity'],
- platformData: mergePlatformData(incoming.platformData, existing.platformData),
- tags: incoming.tags && incoming.tags.length > 0 ? incoming.tags : existing.tags,
- labels:
- incoming.labels && Object.keys(incoming.labels).length > 0 ? incoming.labels : existing.labels,
- };
-};
-
-const mergeCanonicalResourceSnapshot = (
- incoming: Resource[],
- existing: Resource[],
-): Resource[] => {
- if (incoming.length === 0) {
- return [];
- }
- const existingById = new Map(existing.map((resource) => [resource.id, resource] as const));
- return incoming.map((resource) =>
- mergeCanonicalResource(canonicalizeRealtimeResource(resource), existingById.get(resource.id)),
- );
-};
-
const toResource = (v2: APIResource): Resource => {
const sources = (v2.sources || []).filter(
(s): s is string => typeof s === 'string' && s.trim().length > 0,
diff --git a/frontend-modern/src/stores/__tests__/websocket-unified.test.ts b/frontend-modern/src/stores/__tests__/websocket-unified.test.ts
index 21d236f1cf..72445b54e1 100644
--- a/frontend-modern/src/stores/__tests__/websocket-unified.test.ts
+++ b/frontend-modern/src/stores/__tests__/websocket-unified.test.ts
@@ -181,6 +181,118 @@ describe('websocket store unified resource contract', () => {
}
});
+ it('preserves canonical resource details when realtime payloads are thinner', async () => {
+ const { store, dispose } = await createStoreHarness();
+ try {
+ await waitForOpenTick();
+
+ emitMessage({
+ type: 'initialState',
+ data: {
+ connectedInfrastructure: [],
+ resources: [
+ {
+ id: 'node-1',
+ type: 'agent',
+ name: 'West Production A',
+ displayName: 'West Production A',
+ platformId: 'west-production-a',
+ platformType: 'proxmox-pve',
+ sourceType: 'hybrid',
+ status: 'online',
+ lastSeen: Date.now(),
+ cpu: { current: 10 },
+ diskIO: { readRate: 1250000, writeRate: 640000 },
+ platformData: {
+ proxmox: {
+ clusterName: 'Core Fabric',
+ },
+ },
+ },
+ {
+ id: 'pbs-1',
+ type: 'pbs',
+ name: 'backup-vault',
+ displayName: 'backup-vault',
+ platformId: 'pbs-main',
+ platformType: 'proxmox-pbs',
+ sourceType: 'api',
+ status: 'online',
+ lastSeen: Date.now(),
+ platformData: {
+ pbs: {
+ hostname: '198.51.100.10',
+ version: '3.2.1',
+ connectionHealth: 'healthy',
+ datastoreCount: 2,
+ },
+ },
+ },
+ ],
+ lastUpdate: 1739059200000,
+ activeAlerts: [],
+ recentlyResolved: [],
+ },
+ });
+
+ emitMessage({
+ type: 'rawData',
+ data: {
+ connectedInfrastructure: [],
+ resources: [
+ {
+ id: 'node-1',
+ type: 'agent',
+ name: 'West Production A',
+ displayName: 'West Production A',
+ platformId: 'west-production-a',
+ platformType: 'proxmox-pve',
+ sourceType: 'hybrid',
+ status: 'online',
+ lastSeen: Date.now(),
+ cpu: { current: 42 },
+ platformData: {},
+ },
+ {
+ id: 'pbs-1',
+ type: 'pbs',
+ name: 'backup-vault',
+ displayName: 'backup-vault',
+ platformId: 'pbs-main',
+ platformType: 'proxmox-pbs',
+ sourceType: 'api',
+ status: 'online',
+ lastSeen: Date.now(),
+ platformData: {
+ host: '198.51.100.10',
+ version: '3.2.1',
+ connectionHealth: 'healthy',
+ numDatastores: 2,
+ },
+ },
+ ],
+ lastUpdate: 1739059260000,
+ activeAlerts: [],
+ recentlyResolved: [],
+ },
+ });
+
+ const agent = store.state.resources.find((resource) => resource.id === 'node-1');
+ const pbs = store.state.resources.find((resource) => resource.id === 'pbs-1');
+ expect(agent?.cpu?.current).toBe(42);
+ expect(agent?.diskIO).toEqual({ readRate: 1250000, writeRate: 640000 });
+ expect(agent?.clusterId).toBe('Core Fabric');
+ expect((pbs?.platformData as Record<string, unknown>)?.pbs).toMatchObject({
+ hostname: '198.51.100.10',
+ version: '3.2.1',
+ connectionHealth: 'healthy',
+ datastoreCount: 2,
+ });
+ } finally {
+ dispose();
+ }
+ });
+
it('accepts canonical alertResolved websocket payloads', async () => {
const { store, dispose } = await createStoreHarness();
try {
diff --git a/frontend-modern/src/stores/websocket.ts b/frontend-modern/src/stores/websocket.ts
index 676ae37a41..1a682e863e 100644
--- a/frontend-modern/src/stores/websocket.ts
+++ b/frontend-modern/src/stores/websocket.ts
@@ -18,6 +18,7 @@ import {
getAgentDiscoveryResourceId,
isAppContainerDiscoveryResourceType,
} from '@/utils/discoveryTarget';
+import { mergeCanonicalResourceSnapshot } from '@/utils/resourceStateAdapters';
const MAX_INBOUND_WEBSOCKET_MESSAGE_BYTES = 8 * 1024 * 1024; // 8 MiB
@@ -368,17 +369,17 @@ export function createWebSocketStore(url: string) {
if (message.data.stats !== undefined) setState('stats', message.data.stats);
// Handle unified resources
if (message.data.resources !== undefined) {
+ const nextResources = Array.isArray(message.data.resources)
+ ? mergeCanonicalResourceSnapshot(message.data.resources, state.resources)
+ : [];
logger.debug('[WebSocket] Updating resources', {
- count: message.data.resources?.length || 0,
- types: [...new Set(message.data.resources?.map((r: any) => r.type) || [])],
+ count: nextResources.length,
+ types: [...new Set(nextResources.map((resource) => resource.type) || [])],
});
- setState('resources', reconcile(message.data.resources, { key: 'id' }));
+ setState('resources', reconcile(nextResources, { key: 'id' }));
// Sync container update states with docker host command status payloads.
- const resources = Array.isArray(message.data.resources)
- ? message.data.resources
- : [];
- resources.forEach((resource: any) => {
+ nextResources.forEach((resource: any) => {
if (resource?.type !== 'docker-host') return;
const platformData = asRecord(resource.platformData);
const dockerData = asRecord(platformData?.docker);
diff --git a/frontend-modern/src/utils/__tests__/resourceStateAdapters.test.ts b/frontend-modern/src/utils/__tests__/resourceStateAdapters.test.ts
index 9eda55abef..c875b0befc 100644
--- a/frontend-modern/src/utils/__tests__/resourceStateAdapters.test.ts
+++ b/frontend-modern/src/utils/__tests__/resourceStateAdapters.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import {
+ mergeCanonicalResourceSnapshot,
nodeFromResource,
pbsInstanceFromResource,
pmgInstanceFromResource,
@@ -193,4 +194,123 @@ describe('resourceStateAdapters nodeFromResource', () => {
expect(instance?.name).toBe('PMG Main');
});
+
+ it('canonicalizes thin realtime resource platform data without inventing standalone clusters', () => {
+ const [resource] = mergeCanonicalResourceSnapshot(
+ [
+ {
+ id: 'docker-host-1',
+ type: 'docker-host',
+ name: 'Ops Services 01',
+ displayName: 'Ops Services 01',
+ platformId: 'ops-services-01',
+ platformType: 'docker',
+ sourceType: 'api',
+ status: 'online',
+ lastSeen: Date.now(),
+ platformData: {
+ hostname: 'ops-services-01',
+ hostSourceId: 'ops-services-01',
+ runtime: 'docker',
+ },
+ } as Resource,
+ {
+ id: 'pbs-1',
+ type: 'pbs',
+ name: 'backup-vault',
+ displayName: 'backup-vault',
+ platformId: 'pbs-1',
+ platformType: 'proxmox-pbs',
+ sourceType: 'api',
+ status: 'online',
+ lastSeen: Date.now(),
+ platformData: {
+ host: '198.51.100.10',
+ version: '3.2.1',
+ connectionHealth: 'healthy',
+ numDatastores: 2,
+ },
+ } as Resource,
+ ],
+ [],
+ );
+
+ expect(resource.clusterId).toBeUndefined();
+ const pbs = mergeCanonicalResourceSnapshot(
+ [
+ {
+ id: 'pbs-1',
+ type: 'pbs',
+ name: 'backup-vault',
+ displayName: 'backup-vault',
+ platformId: 'pbs-1',
+ platformType: 'proxmox-pbs',
+ sourceType: 'api',
+ status: 'online',
+ lastSeen: Date.now(),
+ platformData: {
+ host: '198.51.100.10',
+ version: '3.2.1',
+ connectionHealth: 'healthy',
+ numDatastores: 2,
+ },
+ } as Resource,
+ ],
+ [],
+ )[0];
+
+ expect((pbs.platformData as Record<string, unknown>)?.pbs).toMatchObject({
+ hostname: '198.51.100.10',
+ version: '3.2.1',
+ connectionHealth: 'healthy',
+ datastoreCount: 2,
+ });
+ });
+
+ it('preserves richer existing resource details when realtime updates are thinner', () => {
+ const existing: Resource = {
+ id: 'node-1',
+ type: 'agent',
+ name: 'West Production A',
+ displayName: 'West Production A',
+ platformId: 'west-production-a',
+ platformType: 'proxmox-pve',
+ sourceType: 'hybrid',
+ status: 'online',
+ lastSeen: Date.now(),
+ cpu: { current: 10 },
+ diskIO: { readRate: 1_250_000, writeRate: 640_000 },
+ platformData: {
+ proxmox: {
+ clusterName: 'Core Fabric',
+ },
+ },
+ } as Resource;
+
+ const [merged] = mergeCanonicalResourceSnapshot(
+ [
+ {
+ id: 'node-1',
+ type: 'agent',
+ name: 'West Production A',
+ displayName: 'West Production A',
+ platformId: 'west-production-a',
+ platformType: 'proxmox-pve',
+ sourceType: 'hybrid',
+ status: 'online',
+ lastSeen: Date.now(),
+ cpu: { current: 42 },
+ platformData: {},
+ } as Resource,
+ ],
+ [existing],
+ );
+
+ expect(merged.cpu?.current).toBe(42);
+ expect(merged.diskIO).toEqual({
+ readRate: 1_250_000,
+ writeRate: 640_000,
+ });
+ expect(merged.clusterId).toBe('Core Fabric');
+ });
});
diff --git a/frontend-modern/src/utils/resourceStateAdapters.ts b/frontend-modern/src/utils/resourceStateAdapters.ts
index 8153cfd522..0f5f8a934a 100644
--- a/frontend-modern/src/utils/resourceStateAdapters.ts
+++ b/frontend-modern/src/utils/resourceStateAdapters.ts
@@ -21,15 +21,20 @@ import type {
Temperature,
} from '@/types/api';
import type { Resource } from '@/types/resource';
-import { getActionableAgentIdFromResource } from '@/utils/agentResources';
+import {
+ getActionableAgentIdFromResource,
+ getExplicitResourceClusterName,
+} from '@/utils/agentResources';
import {
getPreferredInfrastructureDisplayName,
getPreferredResourceClusterName,
getPreferredResourceHostname,
} from '@/utils/resourceIdentity';
-const asRecord = (value: unknown): Record<string, unknown> | undefined =>
- value && typeof value === 'object' ? (value as Record<string, unknown>) : undefined;
+type JsonRecord = Record<string, unknown>;
+
+const asRecord = (value: unknown): JsonRecord | undefined =>
+ value && typeof value === 'object' ? (value as JsonRecord) : undefined;
const asString = (value: unknown): string | undefined =>
typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
@@ -61,6 +66,335 @@ const getCanonicalPlatformId = (resource: Resource): string | undefined => {
export const resourcePlatformData = (resource: Resource): Record<string, unknown> | undefined =>
asRecord(resource.platformData);
+const mergeStringArrays = (
+ incoming?: string[],
+ existing?: string[],
+): string[] | undefined => {
+ const merged = [...(incoming ?? []), ...(existing ?? [])]
+ .map((value) => asString(value))
+ .filter((value): value is string => Boolean(value));
+ return merged.length > 0 ? Array.from(new Set(merged)) : undefined;
+};
+
+const mergeRecord = <T extends JsonRecord>(incoming?: T, existing?: T): T | undefined => {
+ if (!incoming) return existing;
+ if (!existing) return incoming;
+ return { ...existing, ...incoming };
+};
+
+const mergePlatformData = (
+ incomingValue: Resource['platformData'],
+ existingValue: Resource['platformData'],
+): Resource['platformData'] => {
+ const incoming = asRecord(incomingValue);
+ const existing = asRecord(existingValue);
+ if (!incoming) return existingValue;
+ if (!existing) return incomingValue;
+
+ const merged: JsonRecord = { ...existing, ...incoming };
+ for (const key of [
+ 'agent',
+ 'docker',
+ 'proxmox',
+ 'pbs',
+ 'pmg',
+ 'kubernetes',
+ 'vmware',
+ 'storage',
+ 'physicalDisk',
+ 'ceph',
+ 'metrics',
+ 'discoveryTarget',
+ ]) {
+ const nested = mergeRecord(asRecord(incoming[key]), asRecord(existing[key]));
+ if (nested) {
+ merged[key] = nested;
+ }
+ }
+
+ const sourceStatus = mergeRecord(
+ asRecord(incoming.sourceStatus),
+ asRecord(existing.sourceStatus),
+ );
+ if (sourceStatus) {
+ merged.sourceStatus = sourceStatus;
+ }
+
+ const sources = mergeStringArrays(
+ Array.isArray(incoming.sources) ? (incoming.sources as string[]) : undefined,
+ Array.isArray(existing.sources) ? (existing.sources as string[]) : undefined,
+ );
+ if (sources) {
+ merged.sources = sources;
+ }
+
+ return merged;
+};
+
+const deriveLegacySourceList = (resource: Resource): string[] | undefined => {
+ switch (resource.platformType) {
+ case 'proxmox-pve':
+ return resource.sourceType === 'hybrid' ? ['proxmox', 'agent'] : ['proxmox'];
+ case 'docker':
+ return ['docker'];
+ case 'kubernetes':
+ return resource.sourceType === 'hybrid' ? ['agent', 'kubernetes'] : ['kubernetes'];
+ case 'proxmox-pbs':
+ return ['pbs'];
+ case 'proxmox-pmg':
+ return ['pmg'];
+ case 'truenas':
+ return ['truenas'];
+ case 'vmware-vsphere':
+ return ['vmware'];
+ default:
+ return resource.sourceType === 'agent' ? ['agent'] : undefined;
+ }
+};
+
+const canonicalizeLegacyPlatformData = (resource: Resource): Resource['platformData'] => {
+ const platformData = asRecord(resource.platformData);
+ if (!platformData) {
+ return resource.platformData;
+ }
+
+ const normalized: JsonRecord = { ...platformData };
+ const normalizedSources =
+ Array.isArray(platformData.sources) && platformData.sources.length > 0
+ ? (platformData.sources as string[])
+ : deriveLegacySourceList(resource);
+ if (normalizedSources && normalizedSources.length > 0) {
+ normalized.sources = normalizedSources;
+ }
+
+ if (!asRecord(platformData.agent)) {
+ const agentPayload: JsonRecord = {};
+ for (const [legacyKey, nextKey] of [
+ ['agentId', 'agentId'],
+ ['agentVersion', 'agentVersion'],
+ ['hostname', 'hostname'],
+ ['platform', 'platform'],
+ ['osName', 'osName'],
+ ['osVersion', 'osVersion'],
+ ['kernelVersion', 'kernelVersion'],
+ ['architecture', 'architecture'],
+ ['commandsEnabled', 'commandsEnabled'],
+ ] as const) {
+ if (platformData[legacyKey] !== undefined) {
+ agentPayload[nextKey] = platformData[legacyKey];
+ }
+ }
+ if (platformData.memory !== undefined) agentPayload.memory = platformData.memory;
+ if (platformData.interfaces !== undefined) agentPayload.networkInterfaces = platformData.interfaces;
+ if (platformData.disks !== undefined) agentPayload.disks = platformData.disks;
+ if (Object.keys(agentPayload).length > 0) {
+ normalized.agent = agentPayload;
+ }
+ }
+
+ if (!asRecord(platformData.docker)) {
+ const dockerPayload: JsonRecord = {};
+ for (const [legacyKey, nextKey] of [
+ ['agentId', 'agentId'],
+ ['runtime', 'runtime'],
+ ['runtimeVersion', 'runtimeVersion'],
+ ['dockerVersion', 'dockerVersion'],
+ ['os', 'os'],
+ ['kernelVersion', 'kernelVersion'],
+ ['architecture', 'architecture'],
+ ['agentVersion', 'agentVersion'],
+ ['hostname', 'hostname'],
+ ['displayName', 'displayName'],
+ ['machineId', 'machineId'],
+ ['containerCount', 'containerCount'],
+ ['uptimeSeconds', 'uptimeSeconds'],
+ ['intervalSeconds', 'intervalSeconds'],
+ ['temperature', 'temperature'],
+ ['hostSourceId', 'hostSourceId'],
+ ] as const) {
+ if (platformData[legacyKey] !== undefined) {
+ dockerPayload[nextKey] = platformData[legacyKey];
+ }
+ }
+ if (platformData.swarm !== undefined) dockerPayload.swarm = platformData.swarm;
+ if (platformData.interfaces !== undefined) dockerPayload.networkInterfaces = platformData.interfaces;
+ if (platformData.disks !== undefined) dockerPayload.disks = platformData.disks;
+ if (Object.keys(dockerPayload).length > 0) {
+ normalized.docker = dockerPayload;
+ }
+ }
+
+ if (!asRecord(platformData.proxmox)) {
+ const proxmoxPayload: JsonRecord = {};
+ for (const [legacyKey, nextKey] of [
+ ['instance', 'instance'],
+ ['node', 'nodeName'],
+ ['clusterName', 'clusterName'],
+ ['vmid', 'vmid'],
+ ['cpus', 'cpus'],
+ ['template', 'template'],
+ ['swapUsed', 'swapUsed'],
+ ['swapTotal', 'swapTotal'],
+ ['balloon', 'balloon'],
+ ] as const) {
+ if (platformData[legacyKey] !== undefined) {
+ proxmoxPayload[nextKey] = platformData[legacyKey];
+ }
+ }
+ if (platformData.disks !== undefined) proxmoxPayload.disks = platformData.disks;
+ if (Object.keys(proxmoxPayload).length > 0) {
+ normalized.proxmox = proxmoxPayload;
+ }
+ }
+
+ if (!asRecord(platformData.pbs)) {
+ const pbsPayload: JsonRecord = {};
+ if (platformData.host !== undefined) pbsPayload.hostname = platformData.host;
+ if (platformData.version !== undefined) pbsPayload.version = platformData.version;
+ if (platformData.connectionHealth !== undefined) {
+ pbsPayload.connectionHealth = platformData.connectionHealth;
+ }
+ if (platformData.numDatastores !== undefined) {
+ pbsPayload.datastoreCount = platformData.numDatastores;
+ }
+ if (Object.keys(pbsPayload).length > 0) {
+ normalized.pbs = pbsPayload;
+ }
+ }
+
+ if (!asRecord(platformData.pmg)) {
+ const pmgPayload: JsonRecord = {};
+ if (platformData.host !== undefined) pmgPayload.hostname = platformData.host;
+ if (platformData.version !== undefined) pmgPayload.version = platformData.version;
+ if (platformData.connectionHealth !== undefined) {
+ pmgPayload.connectionHealth = platformData.connectionHealth;
+ }
+ for (const [legacyKey, nextKey] of [
+ ['nodeCount', 'nodeCount'],
+ ['queueActive', 'queueActive'],
+ ['queueDeferred', 'queueDeferred'],
+ ['queueHold', 'queueHold'],
+ ['queueIncoming', 'queueIncoming'],
+ ['queueTotal', 'queueTotal'],
+ ] as const) {
+ if (platformData[legacyKey] !== undefined) {
+ pmgPayload[nextKey] = platformData[legacyKey];
+ }
+ }
+ if (Object.keys(pmgPayload).length > 0) {
+ normalized.pmg = pmgPayload;
+ }
+ }
+
+ if (!asRecord(platformData.kubernetes)) {
+ const kubernetesPayload: JsonRecord = {};
+ for (const [legacyKey, nextKey] of [
+ ['agentId', 'agentId'],
+ ['clusterId', 'clusterId'],
+ ['context', 'context'],
+ ['nodeName', 'nodeName'],
+ ['namespace', 'namespace'],
+ ['clusterName', 'clusterName'],
+ ['pendingUninstall', 'pendingUninstall'],
+ ] as const) {
+ if (platformData[legacyKey] !== undefined) {
+ kubernetesPayload[nextKey] = platformData[legacyKey];
+ }
+ }
+ if (Object.keys(kubernetesPayload).length > 0) {
+ normalized.kubernetes = kubernetesPayload;
+ }
+ }
+
+ return normalized;
+};
+
+export const canonicalizeRealtimeResource = (resource: Resource): Resource => {
+ const platformData = canonicalizeLegacyPlatformData(resource);
+ const platformRecord = asRecord(platformData);
+ const normalizedBase = {
+ ...resource,
+ platformData,
+ };
+ return {
+ ...normalizedBase,
+ clusterId: resource.clusterId ?? getExplicitResourceClusterName(normalizedBase),
+ platformData,
+ agent: resource.agent ?? (platformRecord?.agent as Resource['agent']),
+ proxmox: resource.proxmox ?? (platformRecord?.proxmox as Resource['proxmox']),
+ pbs: resource.pbs ?? (platformRecord?.pbs as Resource['pbs']),
+ kubernetes: resource.kubernetes ?? (platformRecord?.kubernetes as Resource['kubernetes']),
+ vmware: resource.vmware ?? (platformRecord?.vmware as Resource['vmware']),
+ storage: resource.storage ?? (platformRecord?.storage as Resource['storage']),
+ physicalDisk:
+ resource.physicalDisk ?? (platformRecord?.physicalDisk as Resource['physicalDisk']),
+ };
+};
+
+const mergeCanonicalIdentity = (
+ incoming?: Resource['canonicalIdentity'],
+ existing?: Resource['canonicalIdentity'],
+): Resource['canonicalIdentity'] => {
+ if (!incoming) return existing;
+ if (!existing) return incoming;
+ const aliases = mergeStringArrays(incoming.aliases, existing.aliases);
+ return {
+ ...existing,
+ ...incoming,
+ aliases,
+ };
+};
+
+export const mergeCanonicalResource = (incoming: Resource, existing?: Resource): Resource => {
+ if (!existing) {
+ return incoming;
+ }
+ const existingCanonical = canonicalizeRealtimeResource(existing);
+ return {
+ ...existingCanonical,
+ ...incoming,
+ clusterId: incoming.clusterId ?? existingCanonical.clusterId,
+ discoveryTarget: incoming.discoveryTarget ?? existingCanonical.discoveryTarget,
+ metricsTarget: incoming.metricsTarget ?? existingCanonical.metricsTarget,
+ canonicalIdentity: mergeCanonicalIdentity(
+ incoming.canonicalIdentity,
+ existingCanonical.canonicalIdentity,
+ ),
+ policy: incoming.policy ?? existingCanonical.policy,
+ aiSafeSummary: incoming.aiSafeSummary ?? existingCanonical.aiSafeSummary,
+ recentChanges: incoming.recentChanges ?? existingCanonical.recentChanges,
+ facetCounts: incoming.facetCounts ?? existingCanonical.facetCounts,
+ diskIO: incoming.diskIO ?? existingCanonical.diskIO,
+ agent: mergeRecord(incoming.agent as JsonRecord | undefined, existingCanonical.agent as JsonRecord | undefined) as Resource['agent'],
+ proxmox: mergeRecord(incoming.proxmox as JsonRecord | undefined, existingCanonical.proxmox as JsonRecord | undefined) as Resource['proxmox'],
+ pbs: mergeRecord(incoming.pbs as JsonRecord | undefined, existingCanonical.pbs as JsonRecord | undefined) as Resource['pbs'],
+ kubernetes: mergeRecord(incoming.kubernetes as JsonRecord | undefined, existingCanonical.kubernetes as JsonRecord | undefined) as Resource['kubernetes'],
+ vmware: mergeRecord(incoming.vmware as JsonRecord | undefined, existingCanonical.vmware as JsonRecord | undefined) as Resource['vmware'],
+ storage: mergeRecord(incoming.storage as JsonRecord | undefined, existingCanonical.storage as JsonRecord | undefined) as Resource['storage'],
+ physicalDisk: mergeRecord(incoming.physicalDisk as JsonRecord | undefined, existingCanonical.physicalDisk as JsonRecord | undefined) as Resource['physicalDisk'],
+ identity: mergeRecord(incoming.identity as JsonRecord | undefined, existingCanonical.identity as JsonRecord | undefined) as Resource['identity'],
+ platformData: mergePlatformData(incoming.platformData, existingCanonical.platformData),
+ tags: incoming.tags && incoming.tags.length > 0 ? incoming.tags : existingCanonical.tags,
+ labels:
+ incoming.labels && Object.keys(incoming.labels).length > 0
+ ? incoming.labels
+ : existingCanonical.labels,
+ };
+};
+
+export const mergeCanonicalResourceSnapshot = (
+ incoming: Resource[],
+ existing: Resource[],
+): Resource[] => {
+ if (incoming.length === 0) {
+ return [];
+ }
+ const existingById = new Map(existing.map((resource) => [resource.id, resource] as const));
+ return incoming.map((resource) =>
+ mergeCanonicalResource(canonicalizeRealtimeResource(resource), existingById.get(resource.id)),
+ );
+};
+
const buildMemory = (metric: Resource['memory'], fallback?: Record<string, unknown>): Memory => {
const total = metric?.total ?? asNumber(fallback?.total) ?? 0;
const used = metric?.used ?? asNumber(fallback?.used) ?? 0;