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.

Cut per-tick realtime merge and workload row churn

rcourtman7bac525af355
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index cf46821d84..3b9c87749d 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -209,13 +209,24 @@ provider-backed fixture set refreshes once per full rotation rather than on
every tick.
The browser applies resource deltas to its connection-scoped raw baseline, but
-canonicalizes and reconciles only changed resources plus the bounded
-host-coalescing set. Unchanged non-host display resources retain object identity.
+canonicalizes and reconciles only changed resources plus the host-merge groups
+the delta could have altered: a group refreshes when a flagged id names one of
+its members (a flagged id absent from the incoming snapshot conservatively
+refreshes every group), and a tick that flags no member preserves the cached
+merged host row by object identity. Unchanged non-host display resources retain
+object identity.
`frontend-modern/src/stores/websocket.ts` publishes the changed-ID set and a
monotonic resource revision with each reconciliation. The shared
`useUnifiedResources` owner applies that revision to the process-wide canonical
cache once, then projects route filters from the already-canonical result;
-route-scoped consumers must not independently canonicalize the full estate.
+route-scoped consumers must not independently canonicalize the full estate. A
+hook instance observing an already-applied revision must not deep-unwrap the
+realtime store, and the merging instance dereferences raw store subtrees only
+for rows the delta merge will clone. Workload table rows derived from canonical
+snapshots reuse the previous row object whenever the serialized row is
+unchanged, and a refresh that changes nothing returns the previous row array
+itself, so per-tick row identity churn stays bounded to guests whose data
+changed.
Retained or prefetched tabs may keep fetched snapshots, but only the visible tab
consumes realtime projection work. Re-entering an inactive tab must catch up
from the shared canonical cache rather than replaying every missed delta.
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 6ff96da270..ed116bb1df 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -1125,6 +1125,14 @@ recovery scope, or a storage/recovery-owned secret source.
boundary for storage/recovery consumers: org-scope or enabled-state changes
must invalidate stale in-flight REST refreshes before their errors or
request-guard cleanup can leak into the active resource snapshot.
+ The shared hook's realtime tick path may read the connection store lazily —
+ skipping revisions the shared canonical cache already holds and
+ dereferencing raw store subtrees only for rows the delta merge will clone —
+ but that optimization must stay invisible to storage/recovery consumers: it
+ must not change which canonical fields a merged row carries, must not
+ reorder the REST-first hydration guarantee above, and a skipped store read
+ must never leave a storage/recovery projection behind the shared cache's
+ applied revision.
Shared chart transports in `internal/api/chartapi/service.go` must follow the same
rule in mock mode: `/api/storage-charts` and adjacent infrastructure chart
payloads must read through `GetUnifiedReadStateOrSnapshot()` so storage and
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index db743a0d64..19d75465aa 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -1164,13 +1164,22 @@ AI-only summary payloads, or page-local heuristics.
between cold hydrate and later runtime updates
Realtime delta reconciliation must preserve exact display-object identity
for untouched non-host resources, canonicalize changed and newly added rows,
- and always recompute the bounded agent/host coalescing set. Incremental and
+ and re-evaluate exactly the host-merge groups the delta could have altered:
+ a group refreshes when a flagged id names one of its current members, and a
+ flagged id absent from the incoming snapshot (a removal, or a partner id an
+ earlier coalesce folded away) conservatively refreshes every group. A tick
+ that flags no member of a group must preserve that group's cached merged
+ host row by object identity. Incremental and
full-snapshot paths must therefore produce the same canonical host identity,
labels, and compatibility fields without cloning the entire estate per tick.
The connection store publishes each reconciliation's changed IDs and resource
revision. `useUnifiedResources` applies that revision to the shared
all-resources cache once and derives type-filtered route projections from the
- canonical result. A sequential revision with unchanged route membership
+ canonical result. An instance observing a revision the shared cache already
+ holds must not re-read or deep-unwrap the realtime store, and the merging
+ instance dereferences raw store subtrees only for rows the delta merge will
+ clone (flagged ids, host-merge members, and ids absent from the shared
+ cache). A sequential revision with unchanged route membership
patches only the changed row indices plus the bounded agent coalescing set;
initial hydration, missed revisions, additions, removals, or reorderings
fall back to keyed full reconciliation. Route-prefetch and route-realtime
diff --git a/frontend-modern/browser-verification.json b/frontend-modern/browser-verification.json
index 6dd79f70a6..eb4bc2a8e7 100644
--- a/frontend-modern/browser-verification.json
+++ b/frontend-modern/browser-verification.json
@@ -1,35 +1,47 @@
{
"version": 1,
- "base_sha": "d3bfb3bb7bef7e67ea62b41940ac240082c74532",
- "verified_at": "2026-08-25T07:11:13Z",
+ "base_sha": "831e55f011f3478767daa3d6578dab9f2bd96e45",
+ "verified_at": "2026-08-25T09:34:54Z",
"result": "passed",
"changed_paths": [
- "frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx"
+ "frontend-modern/src/hooks/useUnifiedResources.ts",
+ "frontend-modern/src/hooks/useWorkloads.ts",
+ "frontend-modern/src/utils/resourceStateAdapters.ts"
],
"content_sha256": {
- "frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx": "cf2a0e35fc4f412a2dec9dad378630e747539ea7e38849cc77a2b66b8d61c162"
+ "frontend-modern/src/hooks/useUnifiedResources.ts": "dd5880e08d41cd8d9595084a3bfedc292584e38e785ff144e4ead96c36a67a3b",
+ "frontend-modern/src/hooks/useWorkloads.ts": "e14581a0af97e49da1322b253be6a3ffa433163d00bbc436c31614539e70094d",
+ "frontend-modern/src/utils/resourceStateAdapters.ts": "2ec8e4754e323ae36f9c61148db4256732a2c7e8678746a7c0e9f60538539d1b"
},
"routes": [
- "/settings/infrastructure"
+ "/login",
+ "/proxmox/overview",
+ "/proxmox/storage",
+ "/proxmox/backups/date",
+ "/alerts"
],
"viewports": [
{
- "width": 1280,
- "height": 720
+ "width": 1440,
+ "height": 900
},
{
- "width": 375,
- "height": 812
+ "width": 390,
+ "height": 844
}
],
"states": [
- "Infrastructure connected systems list with 57 manage targets",
- "Manage Lab vCenter connection editor open",
- "editor closed via Cancel returning to the list"
+ "50-node/1512-resource mock estate with RandomMetrics websocket ticks every 2s riding through every dwell",
+ "Proxmox overview fully hydrated at desktop (11.7k DOM nodes) after login, including return visit after sub-tab navigation",
+ "Storage and Backups sub-tabs fully hydrated at desktop (11.4k / 15.4k DOM nodes)",
+ "Alerts page dwelled 20s at 390px under 4x CPU throttle while websocket deltas applied (CDP profile captured)",
+ "Proxmox overview dwelled 20s at 390px under 4x CPU throttle while websocket deltas applied (CDP profile captured)",
+ "zero console errors across the desktop exercise run"
],
"interactions": [
- "opened the Manage editor for vmware:vc-mock-1 and closed it with Cancel at 1280px and 375px",
- "confirmed focus returns to the row's manage control after the 250ms focus-return timer at both widths",
- "checked the console for errors, only the pre-existing dev websocket proxy reconnect noise present"
+ "headless-Chromium (Playwright) login form fill and submit as admin",
+ "SPA clicks across Proxmox sub-tab anchors Overview -> Storage -> Backups -> Overview at 1440x900",
+ "mobile bottom-bar data-tab-id click into Alerts at 390x844 with 4x CPU throttle",
+ "multi-tick idle dwells on Overview and Alerts confirming realtime delta merge, host coalescing, and workload row updates render live data"
]
-}
+}
\ No newline at end of file
diff --git a/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.ts b/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.ts
index 6a93177308..3b919bb9da 100644
--- a/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.ts
+++ b/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.ts
@@ -303,6 +303,47 @@ describe('useUnifiedResources', () => {
dispose();
});
+ it('hydrates realtime store entries that arrive without being flagged changed', async () => {
+ // The incremental path only unwraps raw subtrees for entries it expects to
+ // clone (changed ids, agents, and ids missing from the merge cache). An
+ // unflagged addition exercises the missing-from-cache branch: without its
+ // defensive unwrap, structuredClone on the store proxy would throw here.
+ const vm = createWsResource({
+ id: 'vm-1',
+ name: 'vm-1',
+ displayName: 'vm-1',
+ type: 'vm',
+ });
+ setWsState('resources', [vm]);
+ setWsResourceChange({ version: 1, changedIds: null });
+
+ let dispose = () => {};
+ let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
+ createRoot((d) => {
+ dispose = d;
+ result = useUnifiedResources({
+ query: '',
+ cacheKey: 'all-resources',
+ initialHydration: 'prefer-ws',
+ });
+ });
+
+ await waitForResourceCount(() => result!.resources().length);
+
+ batch(() => {
+ setWsState('resources', [
+ vm,
+ createWsResource({ id: 'vm-2', name: 'vm-2', displayName: 'vm-2', type: 'vm' }),
+ ]);
+ setWsResourceChange({ version: 2, changedIds: new Set(['vm-1']) });
+ setWsState('lastUpdate', 1738843202000);
+ });
+
+ await waitForValue(() => result!.resources().length, 2);
+ expect(result!.resources().map((resource) => resource.id)).toContain('vm-2');
+ dispose();
+ });
+
it('uses canonical websocket resource updates without a REST refetch for supported queries', async () => {
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
diff --git a/frontend-modern/src/hooks/__tests__/useWorkloads.test.ts b/frontend-modern/src/hooks/__tests__/useWorkloads.test.ts
index 7a9ee4f4ea..c5917ea119 100644
--- a/frontend-modern/src/hooks/__tests__/useWorkloads.test.ts
+++ b/frontend-modern/src/hooks/__tests__/useWorkloads.test.ts
@@ -290,6 +290,51 @@ describe('useWorkloads', () => {
dispose();
});
+ it('keeps row identity stable for guests whose data did not change', async () => {
+ const buildGuest = (id: string, vmid: number, cpu: number) =>
+ ({
+ id,
+ type: 'vm',
+ name: `vm-${vmid}`,
+ status: 'running',
+ platformType: 'proxmox-pve',
+ sources: ['proxmox'],
+ proxmox: { sourceId: id, vmid, nodeName: 'pve1', instance: 'cluster-a' },
+ cpu: { current: cpu },
+ }) as any;
+ const [snapshot, setSnapshot] = createSignal([
+ buildGuest('vm-a', 101, 10),
+ buildGuest('vm-b', 102, 20),
+ ]);
+
+ let dispose = () => {};
+ let result: ReturnType<UseWorkloadsModule['useWorkloads']> | undefined;
+ createRoot((d) => {
+ dispose = d;
+ const [enabled] = createSignal(true);
+ result = useWorkloads(enabled, { resourceSnapshot: snapshot });
+ });
+
+ await flushAsync();
+ const firstRows = result!.workloads();
+ expect(firstRows).toHaveLength(2);
+
+ // One guest changes; the untouched guest's row object must be reused.
+ setSnapshot([buildGuest('vm-a', 101, 10), buildGuest('vm-b', 102, 85)]);
+ await flushAsync();
+ const secondRows = result!.workloads();
+ expect(secondRows[0]).toBe(firstRows[0]);
+ expect(secondRows[1]).not.toBe(firstRows[1]);
+ expect(secondRows[1]?.cpu).toBeCloseTo(0.85);
+
+ // A refresh that changes nothing must keep the array identity itself.
+ setSnapshot([buildGuest('vm-a', 101, 10), buildGuest('vm-b', 102, 85)]);
+ await flushAsync();
+ expect(result!.workloads()).toBe(secondRows);
+
+ dispose();
+ });
+
it('retains the fulfilled workload snapshot when a forced refresh fails', async () => {
let dispose = () => {};
let result: ReturnType<UseWorkloadsModule['useWorkloads']> | undefined;
diff --git a/frontend-modern/src/hooks/useUnifiedResources.ts b/frontend-modern/src/hooks/useUnifiedResources.ts
index 59fbbfd5d8..69d786aec1 100644
--- a/frontend-modern/src/hooks/useUnifiedResources.ts
+++ b/frontend-modern/src/hooks/useUnifiedResources.ts
@@ -1,4 +1,4 @@
-import { batch, createEffect, createSignal, onCleanup, type Accessor } from 'solid-js';
+import { batch, createEffect, createSignal, onCleanup, untrack, type Accessor } from 'solid-js';
import { createStore, reconcile, unwrap } from 'solid-js/store';
import { canonicalizeMetricsHistoryTargetType } from '@/api/charts';
import { readAPIErrorMessage } from '@/api/responseUtils';
@@ -1618,9 +1618,6 @@ export function useUnifiedResources(options?: UseUnifiedResourcesOptions) {
blockedWsHydrationToken = null;
}
- const wsResources = Array.isArray(wsStore.state.resources)
- ? (unwrap(wsStore.state.resources) as Resource[])
- : [];
const resourceChange = wsStore.resourceChange?.() ?? {
version: Number(lastUpdateToken) || 0,
changedIds: null,
@@ -1644,15 +1641,35 @@ export function useUnifiedResources(options?: UseUnifiedResourcesOptions) {
resourceChange.version > 0 &&
allResourcesEntry.hasSnapshot &&
allResourcesEntry.realtimeVersion === resourceChange.version;
+ // Deep-unwrapping the whole resource store on every websocket tick was the
+ // single largest idle main-thread cost in the 2026-08-25 audit profile.
+ // The delta merge only dereferences raw subtrees for entries it will clone
+ // (changed ids, agents whose host-merge groups it re-evaluates, and ids it
+ // has no cached merge output for), so unwrap exactly those and skip the
+ // store read entirely when this realtime version is already applied.
+ // untrack keeps the per-item id/type reads from registering thousands of
+ // fine-grained dependencies; the effect is driven by resourceChange().
+ const readWsResources = (changedIds: ReadonlySet<string> | null): Resource[] =>
+ untrack(() => {
+ const stored = wsStore.state.resources;
+ if (!Array.isArray(stored)) return [];
+ if (changedIds === null) return unwrap(stored) as Resource[];
+ const cachedIds = new Set(allResourcesEntry.resources.map((resource) => resource.id));
+ return stored.map((resource) =>
+ resource.type === 'agent' || changedIds.has(resource.id) || !cachedIds.has(resource.id)
+ ? (unwrap(resource) as Resource)
+ : (resource as Resource),
+ );
+ });
const mergedWsResources = realtimeSnapshotAlreadyApplied
? allResourcesEntry.resources
: canApplyIncrementally
? mergeCanonicalResourceDeltaSnapshot(
- wsResources,
+ readWsResources(resourceChange.changedIds),
allResourcesEntry.resources,
resourceChange.changedIds!,
)
- : mergeCanonicalResourceSnapshot(wsResources, allResourcesEntry.resources);
+ : mergeCanonicalResourceSnapshot(readWsResources(null), allResourcesEntry.resources);
const projectedResources = filterCanonicalUnifiedResources(
mergedWsResources,
query,
@@ -1697,7 +1714,7 @@ export function useUnifiedResources(options?: UseUnifiedResourcesOptions) {
resolvedProjectedResources === projectedResources;
const changedResourceTouchesAgent =
canPatchProjectionIncrementally &&
- wsResources.some(
+ mergedWsResources.some(
(resource) => resource.type === 'agent' && resourceChange.changedIds!.has(resource.id),
);
const incrementalPatchIndices = canPatchProjectionIncrementally
diff --git a/frontend-modern/src/hooks/useWorkloads.ts b/frontend-modern/src/hooks/useWorkloads.ts
index c6d9debc45..cb1f34b074 100644
--- a/frontend-modern/src/hooks/useWorkloads.ts
+++ b/frontend-modern/src/hooks/useWorkloads.ts
@@ -209,7 +209,6 @@ type APIListResponse = {
type WorkloadsCacheEntry = {
workloads: WorkloadGuest[];
- signature: string;
cachedAt: number;
sharedFetch: Promise<WorkloadGuest[]> | null;
};
@@ -223,7 +222,6 @@ const getWorkloadsCacheEntry = (orgScope: string): WorkloadsCacheEntry => {
}
const created: WorkloadsCacheEntry = {
workloads: [],
- signature: '',
cachedAt: 0,
sharedFetch: null,
};
@@ -231,22 +229,52 @@ const getWorkloadsCacheEntry = (orgScope: string): WorkloadsCacheEntry => {
return created;
};
-// Workload objects are produced by one canonical mapper, so their property
-// order is stable. Serializing once per row gives refreshes a cheap immutable
-// signature without recursively comparing the same nested telemetry objects.
-const workloadSignature = (guest: WorkloadGuest): string => JSON.stringify(guest);
+// Workload objects are produced by one canonical mapper and never mutated
+// after construction, so their property order is stable and one serialization
+// per row object is a valid immutable signature. The WeakMap keeps reused row
+// objects from being re-serialized on every refresh.
+const workloadRowSignatures = new WeakMap<WorkloadGuest, string>();
-const buildWorkloadsSignature = (workloads: WorkloadGuest[]): string =>
- workloads.map(workloadSignature).join('\u001e');
+const workloadSignature = (guest: WorkloadGuest): string => {
+ const cached = workloadRowSignatures.get(guest);
+ if (cached !== undefined) return cached;
+ const signature = JSON.stringify(guest);
+ workloadRowSignatures.set(guest, signature);
+ return signature;
+};
-const areWorkloadsEqual = (
- current: WorkloadGuest[],
+// Rebuilding every row object on each refresh made row identity churn even
+// for guests whose data did not change, forcing keyed table rows to re-render
+// estate-wide on every metrics tick. Reusing the previous row object whenever
+// its serialized form is unchanged keeps referential identity stable, and
+// returning the previous array itself when nothing changed lets those
+// refreshes skip downstream work entirely.
+const reconcileWorkloadRowIdentity = (
+ previous: WorkloadGuest[],
next: WorkloadGuest[],
- currentSignature?: string,
-): boolean => {
- if (current === next) return true;
- if (current.length !== next.length) return false;
- return (currentSignature ?? buildWorkloadsSignature(current)) === buildWorkloadsSignature(next);
+): WorkloadGuest[] => {
+ if (previous === next || previous.length === 0 || next.length === 0) return next;
+ const previousById = new Map(previous.map((row) => [row.id, row] as const));
+ let reusedCount = 0;
+ const reconciled = next.map((row) => {
+ const previousRow = previousById.get(row.id);
+ if (previousRow && workloadSignature(previousRow) === workloadSignature(row)) {
+ reusedCount += 1;
+ return previousRow;
+ }
+ return row;
+ });
+ if (reusedCount === next.length && next.length === previous.length) {
+ let sameOrder = true;
+ for (let index = 0; index < reconciled.length; index += 1) {
+ if (reconciled[index] !== previous[index]) {
+ sameOrder = false;
+ break;
+ }
+ }
+ if (sameOrder) return previous;
+ }
+ return reconciled;
};
const normalizeWorkloadStatus = (status?: string | null): string => {
@@ -752,10 +780,8 @@ const setWorkloadsCache = (
entry: WorkloadsCacheEntry,
workloads: WorkloadGuest[],
at = Date.now(),
- signature = buildWorkloadsSignature(workloads),
) => {
entry.workloads = workloads;
- entry.signature = signature;
entry.cachedAt = at;
};
@@ -774,13 +800,13 @@ const fetchWorkloadsShared = async (
const request = (async () => {
const previous = entry.workloads;
const fetched = await fetchWorkloads();
- const fetchedSignature = buildWorkloadsSignature(fetched);
- if (areWorkloadsEqual(previous, fetched, entry.signature || undefined)) {
+ const reconciled = reconcileWorkloadRowIdentity(previous, fetched);
+ if (reconciled === previous) {
entry.cachedAt = Date.now();
return previous;
}
- setWorkloadsCache(entry, fetched, Date.now(), fetchedSignature);
- return fetched;
+ setWorkloadsCache(entry, reconciled, Date.now());
+ return reconciled;
})();
entry.sharedFetch = request;
@@ -827,35 +853,31 @@ export function useWorkloads(
const next = typeof value === 'function' ? value(current) : value;
const normalized = next ?? [];
const cacheEntry = resolveActiveCacheEntry();
- const nextSignature = buildWorkloadsSignature(normalized);
- const currentSignature =
- cacheEntry.workloads === current ? cacheEntry.signature : buildWorkloadsSignature(current);
- if (areWorkloadsEqual(current, normalized, currentSignature || undefined)) {
+ const reconciled = reconcileWorkloadRowIdentity(current, normalized);
+ if (reconciled === current) {
setWorkloadsCache(cacheEntry, current);
return current;
}
- setWorkloadsCache(cacheEntry, normalized, Date.now(), nextSignature);
- return normalized;
+ setWorkloadsCache(cacheEntry, reconciled, Date.now());
+ return reconciled;
});
const applyWorkloads = (next: WorkloadGuest[], targetOrgScope = resolveActiveOrgScope()) => {
const cacheEntry = getWorkloadsCacheEntry(targetOrgScope);
const current = targetOrgScope === resolveActiveOrgScope() ? workloads() : cacheEntry.workloads;
- const nextSignature = buildWorkloadsSignature(next);
- const currentSignature =
- cacheEntry.workloads === current ? cacheEntry.signature : buildWorkloadsSignature(current);
- if (areWorkloadsEqual(current, next, currentSignature || undefined)) {
- setWorkloadsCache(cacheEntry, current, Date.now(), cacheEntry.signature || nextSignature);
+ const reconciled = reconcileWorkloadRowIdentity(current, next);
+ if (reconciled === current) {
+ setWorkloadsCache(cacheEntry, current, Date.now());
if (targetOrgScope === resolveActiveOrgScope()) {
setWorkloads(() => current);
}
return current;
}
- setWorkloadsCache(cacheEntry, next, Date.now(), nextSignature);
+ setWorkloadsCache(cacheEntry, reconciled, Date.now());
if (targetOrgScope === resolveActiveOrgScope()) {
- setWorkloads(() => next);
+ setWorkloads(() => reconciled);
}
- return next;
+ return reconciled;
};
const loadWorkloads = async (
diff --git a/frontend-modern/src/utils/__tests__/resourceStateAdapters.test.ts b/frontend-modern/src/utils/__tests__/resourceStateAdapters.test.ts
index 1fba926680..b117e55f6a 100644
--- a/frontend-modern/src/utils/__tests__/resourceStateAdapters.test.ts
+++ b/frontend-modern/src/utils/__tests__/resourceStateAdapters.test.ts
@@ -1085,4 +1085,86 @@ describe('incremental canonical resource snapshots', () => {
expect(result[1]).not.toBe(changed);
expect(result[1]?.cpu?.current).toBe(75);
});
+
+ it('preserves agent identity when no member of its host-merge group changed', () => {
+ const agent = {
+ id: 'agent-a',
+ type: 'agent',
+ name: 'host-a',
+ status: 'online',
+ sources: ['agent'],
+ } as unknown as Resource;
+ const vm = {
+ id: 'vm-1',
+ type: 'vm',
+ name: 'vm-1',
+ status: 'running',
+ cpu: { current: 5 },
+ } as Resource;
+ const incoming = [structuredClone(agent), { ...structuredClone(vm), cpu: { current: 60 } }];
+
+ const result = mergeCanonicalResourceDeltaSnapshot(incoming, [agent, vm], new Set(['vm-1']));
+
+ expect(result[0]).toBe(agent);
+ expect(result[1]?.cpu?.current).toBe(60);
+ });
+
+ it('refreshes an agent when its own id is in the delta', () => {
+ const agent = {
+ id: 'agent-a',
+ type: 'agent',
+ name: 'host-a',
+ status: 'online',
+ cpu: { current: 10 },
+ sources: ['agent'],
+ } as unknown as Resource;
+ const incoming = [{ ...structuredClone(agent), cpu: { current: 90 } }];
+
+ const result = mergeCanonicalResourceDeltaSnapshot(incoming, [agent], new Set(['agent-a']));
+
+ expect(result[0]).not.toBe(agent);
+ expect(result[0]?.cpu?.current).toBe(90);
+ });
+
+ it('refreshes agent groups when a changed id is absent from the incoming snapshot', () => {
+ // A flagged id that no longer appears can be a removal or a partner id an
+ // earlier coalesce folded away; either can alter a group without flagging
+ // its surviving member, so such ticks refresh every agent group.
+ const agent = {
+ id: 'agent-a',
+ type: 'agent',
+ name: 'host-a',
+ status: 'online',
+ sources: ['agent'],
+ } as unknown as Resource;
+ const incoming = [structuredClone(agent)];
+
+ const result = mergeCanonicalResourceDeltaSnapshot(incoming, [agent], new Set(['gone-id']));
+
+ expect(result[0]).not.toBe(agent);
+ expect(result[0]?.id).toBe('agent-a');
+ });
+
+ it('still coalesces a dirty host-merge group into one merged agent', () => {
+ const agentSide = {
+ id: 'agent-a',
+ type: 'agent',
+ name: 'host-a',
+ status: 'online',
+ sources: ['agent'],
+ } as unknown as Resource;
+ const platformSide = {
+ id: 'pve-a',
+ type: 'agent',
+ name: 'host-a',
+ status: 'online',
+ sources: ['proxmox-pve'],
+ } as unknown as Resource;
+ const incoming = [structuredClone(agentSide), structuredClone(platformSide)];
+
+ const result = mergeCanonicalResourceDeltaSnapshot(incoming, [], new Set(['pve-a']));
+
+ expect(result).toHaveLength(1);
+ expect(result[0]?.sources).toEqual(expect.arrayContaining(['agent', 'proxmox-pve']));
+ });
});
diff --git a/frontend-modern/src/utils/resourceStateAdapters.ts b/frontend-modern/src/utils/resourceStateAdapters.ts
index 03a04a795b..d67a74c722 100644
--- a/frontend-modern/src/utils/resourceStateAdapters.ts
+++ b/frontend-modern/src/utils/resourceStateAdapters.ts
@@ -852,26 +852,59 @@ export const mergeCanonicalResourceDeltaSnapshot = (
}
const existingById = new Map(existing.map((resource) => [resource.id, resource] as const));
- const prepared = incoming.map((resource) => {
- const existingResource = existingById.get(resource.id);
- const mustRefresh =
- resource.type === 'agent' || changedIds.has(resource.id) || existingResource === undefined;
- if (!mustRefresh) {
- return existingResource;
- }
- return canonicalizeRealtimeResource(structuredClone(resource), {
- synthesizePlatformScopes: false,
- });
+
+ // Host coalescing only ever folds agent-type resources together, so an
+ // agent's merged output can change only when a member of its host-merge
+ // group is in the delta. Groups without a flagged member reuse the cached
+ // output instead of re-cloning and re-merging every agent on every tick.
+ // A changed id that is absent from `incoming` is either a true removal or a
+ // partner id that a previous coalesce folded away; both can dissolve or
+ // alter a group without flagging its surviving member, so such ticks
+ // conservatively refresh every agent group (the pre-optimization behavior).
+ const hostKeys = incoming.map((resource) => getHostResourceMergeKey(resource));
+ const incomingIds = new Set(incoming.map((resource) => resource.id));
+ let refreshAllHostGroups = false;
+ changedIds.forEach((id) => {
+ if (!incomingIds.has(id)) refreshAllHostGroups = true;
+ });
+ const dirtyHostKeys = new Set<string>();
+ const cachedHostKeys = new Set<string>();
+ incoming.forEach((resource, index) => {
+ const hostKey = hostKeys[index];
+ if (!hostKey) return;
+ if (refreshAllHostGroups || changedIds.has(resource.id)) dirtyHostKeys.add(hostKey);
+ if (existingById.has(resource.id)) cachedHostKeys.add(hostKey);
});
+ const SKIP = Symbol('skip');
+ const prepared = incoming
+ .map((resource, index) => {
+ const hostKey = hostKeys[index];
+ const existingResource = existingById.get(resource.id);
+ if (hostKey) {
+ if (!dirtyHostKeys.has(hostKey) && cachedHostKeys.has(hostKey)) {
+ // Clean group: cached outputs pass through untouched. Members whose
+ // ids were coalesced away are already represented by that output.
+ return existingResource ?? SKIP;
+ }
+ return canonicalizeRealtimeResource(structuredClone(resource), {
+ synthesizePlatformScopes: false,
+ });
+ }
+ const mustRefresh = changedIds.has(resource.id) || existingResource === undefined;
+ if (!mustRefresh) {
+ return existingResource;
+ }
+ return canonicalizeRealtimeResource(structuredClone(resource), {
+ synthesizePlatformScopes: false,
+ });
+ })
+ .filter((resource): resource is Resource => resource !== SKIP);
+
const coalesced = coalesceCanonicalRealtimeResourceSnapshot(prepared);
return coalesced.map((resource) => {
const existingResource = existingById.get(resource.id);
- if (
- resource.type !== 'agent' &&
- !changedIds.has(resource.id) &&
- existingResource !== undefined
- ) {
+ if (resource === existingResource) {
return existingResource;
}
return mergeCanonicalResource(resource, existingResource);