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
Keep an operator-split host pair as two rows in the browser
rcourtman33184012ce96
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.mdindex b443c8a2b6..7d5af65e03 100644--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md@@ -5246,10 +5246,13 @@ the realtime store has already reported. Authenticated cold starts must renderfrom retained realtime or unified-resource state without falling back tofirst-run/welcome posture or replaying stale setup success notifications, andbackground revalidation may update rows in place but may not blank the page.-Realtime resource adapters must defensively coalesce split host identities by-the same source-bridge rule as the API boundary so a transient backend rebuild-cannot surface duplicate infrastructure rows while the next canonical REST-snapshot is settling.+Realtime resource adapters render each server row as one display row and never+re-join host rows: the websocket payload, its deltas and `/api/state` already+carry the server's presentation coalesce, which applies the operator's merge+exclusions and provider scope the browser cannot see, so a browser-side join+could only undo a split the server made. A row whose own server `sources`+list shrank is rebuilt from the incoming row instead of inheriting the+previous display row's provider metadata.Shared identity helpers in `frontend-modern/src/utils/resourceIdentity.ts`and `frontend-modern/src/utils/agentResources.ts` use the trimmed-string helperfrom `frontend-modern/src/utils/stringUtils.ts` so shared components do not keepdiff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex 84c77d9849..a7372f932d 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -702,7 +702,7 @@ or a measured fleet performance improvement.WebSocket startup, so a delayed or blocked first stream snapshot cannothide server-owned platform scopes; auth-mode branches must not forkadditional state probes or perform the same hydration twice.-20. `frontend-modern/src/utils/resourceStateAdapters.ts` shared with `unified-resources`: canonical resource compatibility and host coalescence are both a unified-resource contract and a fleet-scale reconciliation hot path.+20. `frontend-modern/src/utils/resourceStateAdapters.ts` shared with `unified-resources`: canonical resource compatibility and realtime row merging are both a unified-resource contract and a fleet-scale reconciliation hot path.17. `frontend-modern/src/utils/workloads.ts` shared with `unified-resources`: the stable workload metadata identity helper is both a unified-resource persistence boundary and a workloads hot-path lookup boundary.18. `internal/api/slo.go` shared with `api-contracts`: the SLO endpoint is both an API contract surface and a protected performance hot-path boundary.21. `internal/mock/fixture_graph.go` shared with `monitoring`: the canonical mock fixture graph is both monitoring-owned runtime data and a protected large-estate demo transport hot path.@@ -741,16 +741,15 @@ cluster's pods in each usage update, keyed by node name, with no per-pod scanof other pods or nodes.The browser applies resource deltas to its connection-scoped raw baseline, but-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.-Same-hostname provider disambiguation must retain that locality: candidate-rows are indexed by normalized host key, and machine, DMI, cluster, endpoint,-and linked-agent comparisons may inspect only the matching key's bucket rather-than rescan unrelated estate rows.+canonicalizes and reconciles only changed and newly added resources. Each+server row is one display row, because the server already coalesced host+views for presentation, so unchanged display resources, host rows included,+retain object identity and the browser runs no host-merge pass of its own.+The hook's full merge (initial hydration and uncovered revision gaps) clones+the connection store's rows once, because cache rows must not share nested+arrays with rows the store reconciles in place; delta merges already clone each+changed row that takes the full merge path, and fast-path rows clone only the+patched subtrees.`frontend-modern/src/stores/websocket.ts` publishes the changed-ID set and amonotonic resource revision with each reconciliation. The shared`useUnifiedResources` owner applies that revision to the process-wide canonicaldiff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.jsonindex dc127fc759..a36932d2d1 100644--- a/docs/release-control/v6/internal/subsystems/registry.json+++ b/docs/release-control/v6/internal/subsystems/registry.json@@ -485,7 +485,7 @@},{"path": "frontend-modern/src/utils/resourceStateAdapters.ts",- "rationale": "canonical resource compatibility and host coalescence are both a unified-resource contract and a fleet-scale reconciliation hot path",+ "rationale": "canonical resource compatibility and realtime row merging are both a unified-resource contract and a fleet-scale reconciliation hot path","subsystems": ["performance-and-scalability","unified-resources"diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 7e472db885..a1b9dc254c 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -1834,6 +1834,12 @@ recovery scope, or a storage/recovery-owned secret source.reorder the REST-first hydration guarantee above, and a skipped store readmust never leave a storage/recovery projection behind the shared cache'sapplied revision.+ The shared hook's full merge also clones the connection store's rows before+ merging them, so a cached storage/recovery row never shares a nested array+ with a row the store reconciles in place, and the browser no longer re-joins+ same-hostname host rows itself (each server row is one display row, as the+ server's presentation coalesce delivers it). Neither may change which+ canonical storage, disk, or recovery fields a merged row carries.The same invisibility bound covers the per-key fast merge: a changed rowwhose recorded patch keys stay within the metric fast-path allow-list maybe merged as the previous display row with only the patched subtreesdiff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex 33200622df..b8605dcbdf 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -807,11 +807,12 @@ grouping metadata, not same-machine evidence; cross-instance equality requiresthe same node identity, the exact configured endpoint, or independentlycorroborated host evidence.Frontend REST and realtime resource mirrors must retain the canonical-`hostnames`, `machineId`, and `dmiUuid` evidence used for that decision. When-independent Proxmox connections expose the same native node hostname, browser-compatibility coalescing must preserve the server-authored provider split; in-an ambiguous hostname bucket, a separate agent row may join a provider node-only through its explicit linked-agent identity rather than hostname alone.+`hostnames`, `machineId`, and `dmiUuid` evidence. The browser never re-joins+host rows, so when independent Proxmox connections expose the same native node+hostname the server-authored provider split reaches the UI as delivered; in an+ambiguous hostname bucket the server joins a separate agent row to a provider+node only through its explicit linked-agent identity rather than hostname+alone.The same boundary carries cluster-node presentation without weakeningcanonical identity. `ProxmoxData` preserves the immutable connection-scopednode identity, current native node name, prior native-name aliases, and@@ -1917,7 +1918,7 @@ container inventory table.It must carry the manifest `surface_kind` distinction so `docker` remainsmachine-readable as a `runtime-lens` while owning infrastructure sourcesremain `platform` entries.-18. `frontend-modern/src/utils/resourceStateAdapters.ts` shared with `performance-and-scalability`: canonical resource compatibility and host coalescence are both a unified-resource contract and a fleet-scale reconciliation hot path.+18. `frontend-modern/src/utils/resourceStateAdapters.ts` shared with `performance-and-scalability`: canonical resource compatibility and realtime row merging are both a unified-resource contract and a fleet-scale reconciliation hot path.19. `frontend-modern/src/utils/sourcePlatforms.ts` shared with `frontend-primitives`: the source platform normalizer is both a canonical unified-resource source adapter boundary and a shared frontend source/platform vocabulary boundary.That shared vocabulary boundary owns the generic `docker` platform label:selectors, badges, and filter options render it as "Docker / Podman" so@@ -2283,13 +2284,11 @@ canonical unified-resource lists must preserve one deterministicwebsocket-backed refreshes so equal-name resources do not silently reshufflebetween cold hydrate and later runtime updatesRealtime delta reconciliation must preserve exact display-object identity-for untouched non-host resources, canonicalize changed and newly added rows,-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+for untouched resources and canonicalize changed and newly added rows. Each+server row is one display row: the server coalesced host views for+presentation, and the browser runs no host-merge pass of its own, so a pair+the server keeps apart (an operator split, a provider-scoped Proxmox site)+renders as two rows. Incremental andfull-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@@ -2298,9 +2297,9 @@ all-resources cache once and derives type-filtered route projections from thecanonical result. An instance observing a revision the shared cache alreadyholds must not re-read or deep-unwrap the realtime store, and the merginginstance 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.+clone (flagged ids and ids absent from the shared cache). A sequential+revision with unchanged route membership patches only the changed row+indices.The connection store retains a bounded per-revision changed-id history; aninstance that resumes several revisions behind the shared cache must catchup through the unioned changed-id set as an incremental delta merge whenever@@ -2320,8 +2319,9 @@ connection store and instance projections as per-key subtree writes ratherthan whole-row keyed reconciles. The fast output must staycontent-equivalent to the full path (facet keeps, deletion semantics, anddefault-policy synthesis included), must never adopt raw-baseline subtrees-by reference, and any row outside the allow-list — including agent rows,-whose output can depend on host coalescing — must take the full path. Route-prefetch and route-realtime+by reference, and any row outside the allow-list must take the full path.+Agent rows still take it: the fast path has not been shown equivalent for+their facet keeps since the browser stopped coalescing host rows. Route-prefetch and route-realtimeactivation are separate:a prefetched hidden surface may retain REST data without subscribing its fullprojection to every realtime tick, and activation catches up from the shared@@ -7664,15 +7664,9 @@ reports no machine key and declares it refuses any joined-era pin while itsown linked agent is missing, keeping its own ID until that agent reports. An exclusion keyed by theagent's machine-derived ID stops naming the agent if the agent's effectivecanonical key changes (it stops reporting a machine ID and no pin restores-it), as every exclusion keyed by a canonical ID does. The browser's realtime-coalesce (`mergeCanonicalResourceSnapshot` in `resourceStateAdapters.ts`,-used by the websocket store and `useUnifiedResources`) receives no-exclusions and joins a Proxmox-only row and an agent-only row that share a-hostname unless their machine IDs or DMI UUIDs disagree, their Proxmox-facets name different clusters or provider scopes, or several Proxmox nodes-share the hostname and the node does not name the agent, so the UI still-renders such a split pair, from this change or from an identity-match split,-as one row.+it), as every exclusion keyed by a canonical ID does. The browser renders+the split as the server presents it; see "The browser renders those rows as+delivered" below.The resources API seeds its registry from the monitor's listing, whichalready has the link applied, so it cannot split the pair itself: an unlink@@ -7704,6 +7698,89 @@ that one broadcast. Both surfaces share one known limit: the filter comparesthe IDs of the rows being merged, so a third same-host fragment that mergesfirst can carry an excluded pair into one row.+The browser renders those rows as delivered. Its realtime merge+(`mergeCanonicalResourceSnapshot` and `mergeCanonicalResourceDeltaSnapshot`+in `resourceStateAdapters.ts`, used by the websocket store and+`useUnifiedResources`) used to join an agent-only row and a platform row+(Proxmox, Docker, Kubernetes, vSphere or TrueNAS) that shared a hostname+unless their machine IDs, DMI UUIDs or Proxmox provider scopes disagreed. It+read no exclusions, so a host pair the operator split reached the browser as+two rows and rendered as one. Every realtime payload (the websocket+snapshot, its deltas and `/api/state`) already carries the server's+presentation coalesce, so the browser now merges each row only with the+previous row of its ID and never joins host rows. A split usually leaves one+side on the joined row's ID, and that per-ID merge keeps what the incoming+row omits, so the agent kept the node's Proxmox facts: the flattened+`platformData` the Proxmox facet is rebuilt from, its platform scopes,+`clusterId`, identity fields and canonical aliases. When the incoming row's+own `sources` list lacks a source the previous row of its ID listed,+`mergeCanonicalResource` rebuilds the row from the incoming one instead of+merging. A list inferred from the facets a thin row carries is no such+evidence. The rebuilt row keeps the REST-only enrichments the realtime+payload never carries where the departed sources did not own them: platform+scopes minus the departed sources' own that no surviving source, Docker LXC+host or non-host facet supports (a Docker container in a Proxmox LXC stays on+the Proxmox page when its availability check is removed, because its host ID+still places it there, and an agent-reported disk keeps the Proxmox scope its+ownership facet gives it; a host row's facets are no evidence, since+canonicalizing flattened platform data synthesizes them), the source status+of the sources that remain (status the pruning empties is deleted), discovery+readiness unless a coordinate it names (`targetId` the reporter, `resourceId`+the resource) differs from the same coordinate of the row's discovery target+(realtime carries a target only for agent and Docker host rows, so a row+without one keeps it unless the agent left), and action readiness unless the+agent left. Everything else REST adds returns with the next REST refresh. The fast merge path never rebuilds+a row: `sources` is outside its allow-list, so it patches the previous display+row and a rebuild waits for the row's next full merge (see the limits below).++Three rules keep REST enrichment from outliving a source. Source status is+REST enrichment, since the realtime payload carries none, and the platform data+merge and the top-level merge prune its entries to the sources the merged row+lists (only a list the row carries itself counts; canonicalizing a thin row+that carries none synthesizes one from its facets, which the merge cannot tell+apart, so a thin row can prune the status of a source its facets omit); a+joined host's `proxmox` entry otherwise kept the Machines page from+listing the agent that was split off it, because that page reads source status+as provider ownership. A previous row claims every source either of its own+lists names, its top-level `sources` and its `platformData.sources`, so a row+whose two lists disagree, because an enrichment of another generation landed on+it or a shared array changed under it, is rebuilt as soon as the realtime row+drops the extra source instead of carrying that source's metadata on. And the+resources hook's full merge no longer hands the websocket store's rows to the+merge: the store reconciles server changes into its own rows in place, and cache+rows that shared a nested array with them, such as `sources`, flipped to the+split value while keeping the REST enrichment of the joined era. It clones the+store's rows once on that path, as the delta path clones each changed row.+Known limits: a hook's own store is still created from its cache's rows, so a+store commit can edit rows another cache entry shares (the claimed-sources rule+rebuilds such a row on its next merge), and the fast merge path is+content-equivalent to the full path only for a display row whose own lists+agree, so enrichment of another generation can leave a departed source's status+on a non-agent row until its next full merge. After a rebuild the browser+judges whether REST-only scopes and readiness still belong to the row from+names and target coordinates alone, because the realtime payload carries no+provenance for them: a facet canonicalization synthesized from flattened+platform data on a row that is not a host (a guest's `disks`, a storage+row's `instance`, a Kubernetes node's kernel version) can keep the scope it+names, a Docker host row (`docker-host`) can keep the agent scope through its+synthesized agent facet, and a guest without a discovery target keeps the+previous reporter's readiness when its reporter changes in the same interval+without an `agent` source leaving (and loses it when an in-guest agent is+unlinked while the node's reporter still serves discovery). The next REST+refresh restores every one of these. `keeps an+operator-split node and agent as two rows through snapshots and deltas`+(`resourceStateAdapters.test.ts`), `keeps an operator-split host pair as two+rows through a snapshot and deltas` (`websocket-unified.test.ts`), `keeps an+operator-split host pair as two rows and an unchanged agent peer by identity`+and `drops REST enrichment of a departed source when the store reconciles a+split in place` (`useUnifiedResources.test.ts`) pin a split pair in the+broadcast's shape through full snapshots, the delta that splits a joined row,+later deltas and the resources hook (the last also that hook rows share no+array with the store's), `rebuilds a row whose own source lists disagree once+the realtime row drops the extra source` pins the claimed-sources rule, and+`prunes source status entries of sources the merged row no longer lists` pins+the status rule.+A write leaves one row for its pair: `AddLink` and `AddExclusion` also deletea row of their own kind that succession stored in the other order, and thein-memory store replaces a pair's rows on every write and stamps `CreatedAt`diff --git a/frontend-modern/browser-verification/8e93ae59e6bfb7df.json b/frontend-modern/browser-verification/8e93ae59e6bfb7df.jsonnew file mode 100644index 0000000000..2773a83ee1--- /dev/null+++ b/frontend-modern/browser-verification/8e93ae59e6bfb7df.json@@ -0,0 +1,38 @@+{+ "version": 1,+ "base_sha": "e4da1b037000e4eb4b6ea7089704993c74708db8",+ "verified_at": "2026-10-10T10:26:34Z",+ "result": "passed",+ "changed_paths": [+ "frontend-modern/src/hooks/useUnifiedResources.ts",+ "frontend-modern/src/utils/resourceStateAdapters.ts"+ ],+ "content_sha256": {+ "frontend-modern/src/hooks/useUnifiedResources.ts": "e68ee6d94e38e710200c479e383ac0f01a66f6b892b8833b0fb84deb97044e28",+ "frontend-modern/src/utils/resourceStateAdapters.ts": "4e250e2cc01e8a735299862fd1eb253bec064bf57fa3cbf52cc811f1a9205d76"+ },+ "routes": [+ "/proxmox/overview",+ "/standalone/machines"+ ],+ "viewports": [+ {+ "width": 1280,+ "height": 800+ },+ {+ "width": 390,+ "height": 844+ }+ ],+ "states": [+ "Private dev stack at 127.0.0.1 (PR 2741's server on main plus a loopback fake Proxmox API and a test host agent for the same machine): headless Chromium (Playwright on pulse-dev) at 1280x800 and 390x844, plus the built-in browser pane on 2026-10-08 on earlier code. Joined node+agent = one Proxmox node row and no Machines row.",+ "Operator split (POST /api/resources/{id}/report-merge, the drawer's Split merged resource) delivered live by websocket delta with no reload: the Proxmox page keeps one node row (node uptime) and the Machines page lists the agent as its own row; its drawer reads Agent, Debian 12, own primary and machine ID, no node alias or Proxmox context. The last browser pass (2 of 2 completed transitions at 390 and 2 of 2 at 1280; two more runs died at the login field while Vite cold-compiled, before any split) ran on the revision before this commit's final edits to which REST-only fields a rebuilt row keeps (scope evidence for non-host facets, discovery readiness matching); the browser pass does not observe those fields and unit tests with negative controls cover them. Earlier revisions: 2 of 2 at 390 and 3 of 3 at 1280, and 3 of 3 and 3 of 3 before that. Before the fixes in this change the same transition left the agent missing from Machines in 4 of 4 and then 2 of 4 phone-width runs. On main's frontend the split agent was drawn as a second Proxmox node and Machines showed 'No Pulse Agent machines'.",+ "Relink (POST /api/resources/{id}/link) returns the pair to one joined row before every run. Screenshots of the joined, split Proxmox and split Machines states inspected at both widths (earlier code; later runs were checked by row text).",+ "Not covered: a physical phone, other platforms' host rows (Docker, Kubernetes, vSphere, TrueNAS pairs) and an operator unlink through the drawer on the final code."+ ],+ "interactions": [+ "Split merged resource dialog opened and confirmed in the built-in browser pane (2026-10-08, earlier code); report-merge and link requests posted for the repeated runs. Proxmox page to Machines page by in-app navigation (no reload) after the split; Machines row expanded to its drawer.",+ "Websocket updates arrive while the page is open; no uncaught page error in the final-code runs (console output was not otherwise captured). All traffic is local to the private stack."+ ]+}diff --git a/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.ts b/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.tsindex 3d1f06a4ba..c18e955172 100644--- a/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.ts+++ b/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.ts@@ -1,5 +1,5 @@import { batch, createRoot, createSignal } from 'solid-js';-import { createStore, reconcile, type SetStoreFunction } from 'solid-js/store';+import { createStore, reconcile, unwrap, type SetStoreFunction } from 'solid-js/store';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { buildProxmoxPageModel } from '@/features/proxmox/proxmoxPageModel';import { getDockerContainerLifecycleDisabledReason } from '@/features/docker/dockerContainerLifecycleActions';@@ -289,18 +289,18 @@ describe('useUnifiedResources', () => {);expect(- resolveIncrementalResourcePatchIndices(current, next, new Set(['resource-900']), false),+ resolveIncrementalResourcePatchIndices(current, next, new Set(['resource-900'])),).toEqual([900]);- const hostRefresh = resolveIncrementalResourcePatchIndices(- current,- next,- new Set(['resource-900']),- true,- );- expect(hostRefresh).toHaveLength(51);- expect(hostRefresh?.slice(0, 50)).toEqual(Array.from({ length: 50 }, (_, index) => index));- expect(hostRefresh?.at(-1)).toBe(900);+ // Each server row is one display row, so a changed agent patches only+ // itself rather than the whole agent subset.+ expect(+ resolveIncrementalResourcePatchIndices(+ current,+ next,+ new Set(['resource-7', 'resource-900']),+ ),+ ).toEqual([7, 900]);});it('falls back to a full keyed reconcile when realtime membership or order changes', () => {@@ -312,11 +312,10 @@ describe('useUnifiedResources', () => {[first, second],[second, first],new Set(['first', 'second']),- false,),).toBeNull();expect(- resolveIncrementalResourcePatchIndices([first], [first, second], new Set(['second']), false),+ resolveIncrementalResourcePatchIndices([first], [first, second], new Set(['second'])),).toBeNull();});@@ -357,6 +356,216 @@ describe('useUnifiedResources', () => {dispose();});+ it('keeps an operator-split host pair as two rows and an unchanged agent peer by identity', async () => {+ // Broadcast shape: a joined host's platformData is the flattened Proxmox+ // facts; the split agent row arrives agent-only under the+ // joined row's id and the node arrives as a new row.+ const proxmoxFacet = { nodeName: 'pve1', instance: 'pve1', clusterName: 'homelab' };+ const joined = createWsResource({+ id: 'agent-machine-pve1',+ name: 'pve1',+ displayName: 'pve1',+ platformType: 'proxmox-pve',+ sourceType: 'hybrid',+ sources: ['agent', 'proxmox'],+ clusterId: 'cluster:homelab',+ cpu: { current: 15 },+ proxmox: proxmoxFacet,+ platformData: { instance: 'pve1', pveVersion: '9.1.9', clusterName: 'homelab' },+ } as Partial<Resource>);+ const peer = createWsResource({+ id: 'agent-peer',+ name: 'peer',+ displayName: 'peer',+ sources: ['agent'],+ cpu: { current: 20 },+ } as Partial<Resource>);+ setWsState('resources', [joined, peer]);+ 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);+ expect(result!.resources()).toHaveLength(2);+ const peerBefore = result!.resources().find((resource) => resource.id === 'agent-peer');++ const splitAgent = createWsResource({+ id: 'agent-machine-pve1',+ name: 'pve1',+ displayName: 'pve1',+ sources: ['agent'],+ cpu: { current: 15 },+ platformData: { platform: 'linux', osName: 'Debian GNU/Linux' },+ } as Partial<Resource>);+ const splitNode = createWsResource({+ id: 'agent-node-pve1',+ name: 'pve1',+ displayName: 'pve1',+ platformType: 'proxmox-pve',+ sourceType: 'api',+ sources: ['proxmox'],+ clusterId: 'cluster:homelab',+ proxmox: proxmoxFacet,+ platformData: { instance: 'pve1', pveVersion: '9.1.9', clusterName: 'homelab' },+ } as Partial<Resource>);+ batch(() => {+ setWsState('resources', [splitAgent, peer, splitNode]);+ setWsResourceChange({+ version: 2,+ changedIds: new Set(['agent-machine-pve1', 'agent-node-pve1']),+ });+ setWsState('lastUpdate', 1738843202000);+ });++ await waitForResourceCount(() => result!.resources().length, 3);+ const agentRow = result!.resources().find((resource) => resource.id === 'agent-machine-pve1');+ const nodeRow = result!.resources().find((resource) => resource.id === 'agent-node-pve1');+ expect(agentRow?.sources).toEqual(['agent']);+ expect(agentRow?.proxmox).toBeUndefined();+ expect(agentRow?.clusterId).toBeUndefined();+ expect((agentRow?.platformData as Record<string, unknown>).pveVersion).toBeUndefined();+ expect(nodeRow?.sources).toEqual(['proxmox']);+ expect(nodeRow?.proxmox).toMatchObject({ nodeName: 'pve1' });+ expect(result!.resources().find((resource) => resource.id === 'agent-peer')).toBe(peerBefore);++ // A tick on the split agent alone patches that row; the node and the+ // unchanged agent peer stay as they were.+ batch(() => {+ setWsState('resources', 0, 'cpu', 'current', 42);+ setWsResourceChange({ version: 3, changedIds: new Set(['agent-machine-pve1']) });+ setWsState('lastUpdate', 1738843203000);+ });++ await waitForValue(+ () =>+ result!.resources().find((resource) => resource.id === 'agent-machine-pve1')?.cpu?.current,+ 42,+ );+ expect(result!.resources()).toHaveLength(3);+ expect(result!.resources().find((resource) => resource.id === 'agent-peer')).toBe(peerBefore);+ expect(+ result!.resources().find((resource) => resource.id === 'agent-node-pve1')?.sources,+ ).toEqual(['proxmox']);+ expect(apiFetchMock).not.toHaveBeenCalled();+ dispose();+ });++ it('drops REST enrichment of a departed source when the store reconciles a split in place', async () => {+ // The websocket store reconciles a split into its own rows in place. Cache+ // rows built by the hook's first full merge must not share nested arrays+ // with those rows, or the in-place edit flips the cached row's sources+ // while its REST-only enrichment (source status, platform scopes) stays,+ // and no later merge sees a source leave.+ const proxmoxFacet = { nodeName: 'pve1', instance: 'pve1', clusterName: 'homelab' };+ const joined = createWsResource({+ id: 'agent-machine-pve1',+ name: 'pve1',+ displayName: 'pve1',+ platformType: 'proxmox-pve',+ sourceType: 'hybrid',+ sources: ['agent', 'proxmox'],+ proxmox: proxmoxFacet,+ } as Partial<Resource>);+ setWsState('resources', reconcile([joined], { key: 'id' }));+ setWsResourceChange({ version: 1, changedIds: null });+ apiFetchMock.mockResolvedValue(+ resourceResponse([+ {+ ...v2Resource,+ id: 'agent-machine-pve1',+ name: 'pve1',+ sources: ['agent', 'proxmox'],+ platformScopes: ['agent', 'proxmox-pve'],+ sourceStatus: {+ agent: { status: 'online', lastSeen: '2026-02-06T12:00:00Z' },+ proxmox: { status: 'online', lastSeen: '2026-02-06T12:00:00Z' },+ },+ proxmox: proxmoxFacet,+ },+ ]),+ );++ let dispose = () => {};+ let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;+ createRoot((d) => {+ dispose = d;+ result = useUnifiedResources({+ query: 'type=agent',+ cacheKey: 'standalone-workspace',+ initialHydration: 'prefer-ws',+ });+ });++ await waitForResourceCount(() => result!.resources().length);+ // Rows the hook's full merge built share no nested array with the store's+ // rows, which the store reconciles in place.+ const storeRow = (unwrap((wsStoreMock.state as TestWsState).resources) as Resource[]).find(+ (resource) => resource.id === 'agent-machine-pve1',+ );+ const hookRow = unwrap(result!.resources()).find(+ (resource) => resource.id === 'agent-machine-pve1',+ );+ expect(hookRow?.sources).toEqual(['agent', 'proxmox']);+ expect(hookRow?.sources).not.toBe(storeRow?.sources);+ expect(hookRow?.platformData).not.toBe(storeRow?.platformData);+ await result!.refetch();+ const enriched = result!.resources().find((resource) => resource.id === 'agent-machine-pve1');+ expect(enriched?.sourceStatus).toHaveProperty('proxmox');+ expect(enriched?.platformScopes).toContain('proxmox-pve');++ // The server splits the pair: the agent keeps the id, the node is a new row.+ const splitAgent = createWsResource({+ id: 'agent-machine-pve1',+ name: 'pve1',+ displayName: 'pve1',+ sources: ['agent'],+ } as Partial<Resource>);+ const splitNode = createWsResource({+ id: 'agent-node-pve1',+ name: 'pve1',+ displayName: 'pve1',+ platformType: 'proxmox-pve',+ sourceType: 'api',+ sources: ['proxmox'],+ proxmox: proxmoxFacet,+ } as Partial<Resource>);+ batch(() => {+ setWsState('resources', reconcile([splitAgent, splitNode], { key: 'id' }));+ setWsResourceChange({+ version: 2,+ changedIds: new Set(['agent-machine-pve1', 'agent-node-pve1']),+ });+ setWsState('lastUpdate', 1738843202000);+ });++ await waitForResourceCount(() => result!.resources().length, 2);+ const agentRow = result!.resources().find((resource) => resource.id === 'agent-machine-pve1');+ expect(agentRow?.sources).toEqual(['agent']);+ expect(Object.keys(agentRow?.sourceStatus ?? {})).not.toContain('proxmox');+ expect(+ Object.keys(+ ((agentRow?.platformData as Record<string, unknown> | undefined)?.sourceStatus ??+ {}) as Record<string, unknown>,+ ),+ ).not.toContain('proxmox');+ expect(agentRow?.platformData?.sources).toEqual(['agent']);+ expect(agentRow?.platformScopes ?? []).not.toContain('proxmox-pve');+ expect(+ ((agentRow?.platformData as Record<string, unknown> | undefined)?.platformScopes ??+ []) as string[],+ ).not.toContain('proxmox-pve');+ dispose();+ });+it('catches up multi-tick version gaps through the changed-id history instead of a full remerge', async () => {// Distinct nested cpu objects: the shared wsResource base would otherwise// alias one cpu object across both rows and the two writes below.diff --git a/frontend-modern/src/hooks/useUnifiedResources.ts b/frontend-modern/src/hooks/useUnifiedResources.tsindex 6c6547e550..a77adb24fe 100644--- a/frontend-modern/src/hooks/useUnifiedResources.ts+++ b/frontend-modern/src/hooks/useUnifiedResources.ts@@ -1310,17 +1310,13 @@ const buildUnifiedResourceFacets = (resources: readonly Resource[]): UnifiedReso* Resolve the small set of store rows that need reconciliation for one* canonical realtime revision. A structural mismatch returns `null` so the* caller can fall back to a full keyed reconcile for additions, removals, type- * membership changes, or order changes.- *- * Agent rows are a bounded exception: when an agent changed, canonical host- * coalescing can update another agent row as well, so refresh the complete- * agent subset while leaving every non-host row outside the delta untouched.+ * membership changes, or order changes. Each server row is one display row,+ * so only the changed rows need reconciling.*/export const resolveIncrementalResourcePatchIndices = (current: readonly Resource[],next: readonly Resource[],changedIds: ReadonlySet<string>,- refreshAgentRows: boolean,): number[] | null => {if (current.length !== next.length) return null;@@ -1331,7 +1327,7 @@ export const resolveIncrementalResourcePatchIndices = (if (!currentResource || !nextResource || currentResource.id !== nextResource.id) {return null;}- if (changedIds.has(nextResource.id) || (refreshAgentRows && nextResource.type === 'agent')) {+ if (changedIds.has(nextResource.id)) {patchIndices.push(index);}}@@ -1865,21 +1861,25 @@ export function useUnifiedResources(options?: UseUnifiedResourcesOptions) {// 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.+ // (changed ids 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 = (catchUp: CatchUpMeta | null): Resource[] =>untrack(() => {const stored = wsStore.state.resources;if (!Array.isArray(stored)) return [];- if (catchUp === null) return unwrap(stored) as Resource[];+ // The cache rows built from this read must not share nested arrays or+ // objects with the store's rows: the store reconciles server changes+ // into its own rows in place, and a shared `sources` array would flip+ // on a cached row while that row keeps its REST-only enrichment.+ if (catchUp === null) return structuredClone(unwrap(stored)) as Resource[];const cachedById = new Map(allResourcesEntry.resources.map((resource) => [resource.id, resource] as const),);return stored.map((resource) => {- if (resource.type === 'agent' || !cachedById.has(resource.id)) {+ if (!cachedById.has(resource.id)) {return unwrap(resource) as Resource;}if (!catchUp.changedIds.has(resource.id)) {@@ -1974,17 +1974,11 @@ export function useUnifiedResources(options?: UseUnifiedResourcesOptions) {? resolveCatchUpMeta(previousCacheRealtimeVersion): null;const canPatchProjectionIncrementally = cacheEntryCatchUp !== null;- const changedResourceTouchesAgent =- canPatchProjectionIncrementally &&- mergedWsResources.some(- (resource) => resource.type === 'agent' && cacheEntryCatchUp!.changedIds.has(resource.id),- );const incrementalPatchIndices = canPatchProjectionIncrementally? resolveIncrementalResourcePatchIndices(resources as unknown as Resource[],resolvedProjectedResources,cacheEntryCatchUp!.changedIds,- changedResourceTouchesAgent,): null;diff --git a/frontend-modern/src/stores/__tests__/websocket-unified.test.ts b/frontend-modern/src/stores/__tests__/websocket-unified.test.tsindex d8a246a34f..925f76d9fb 100644--- a/frontend-modern/src/stores/__tests__/websocket-unified.test.ts+++ b/frontend-modern/src/stores/__tests__/websocket-unified.test.ts@@ -207,74 +207,161 @@ describe('websocket store unified resource contract', () => {}});- it('coalesces split host identities from realtime resource snapshots', async () => {+ it('keeps an operator-split host pair as two rows through a snapshot and deltas', async () => {const { store, dispose } = await createStoreHarness();try {await waitForOpenTick();+ const agentFacet = { agentId: 'agent-pve1', hostname: 'pve1', machineId: 'machine-pve1' };+ // The monitor's node record keeps its link to the agent after a split.+ const proxmoxFacet = {+ nodeName: 'pve1',+ instance: 'pve1',+ clusterName: 'homelab',+ linkedAgentId: 'agent-pve1',+ };+ // Broadcast platformData for a Proxmox host: flattened facts, no sources.+ const proxmoxPlatformData = {+ instance: 'pve1',+ pveVersion: '9.1.9',+ isClusterMember: true,+ clusterName: 'homelab',+ connectionHealth: 'online',+ };+ const agentPlatformData = { platform: 'linux', osName: 'Debian GNU/Linux' };+ const splitAgent = {+ id: 'agent-machine-pve1',+ type: 'agent',+ name: 'pve1',+ displayName: 'pve1',+ platformId: 'pve1',+ platformType: 'agent',+ sourceType: 'agent',+ sources: ['agent'],+ status: 'online',+ lastSeen: 100,+ identity: { hostnames: ['pve1'], machineId: 'machine-pve1' },+ canonicalIdentity: { primaryId: 'agent:machine-pve1', aliases: ['agent:machine-pve1'] },+ agent: agentFacet,+ platformData: agentPlatformData,+ };+ const splitNode = {+ id: 'agent-node-pve1',+ type: 'agent',+ name: 'pve1',+ displayName: 'pve1',+ platformId: 'pve1',+ platformType: 'proxmox-pve',+ sourceType: 'api',+ sources: ['proxmox'],+ status: 'online',+ lastSeen: 100,+ clusterId: 'cluster:homelab',+ identity: { hostnames: ['pve1'], clusterName: 'homelab' },+ canonicalIdentity: { primaryId: 'node:pve1:pve1', aliases: ['node:pve1:pve1'] },+ proxmox: proxmoxFacet,+ platformData: proxmoxPlatformData,+ };+ const expectSplitRows = () => {+ expect(store.state.resources.map((resource) => resource.id)).toEqual([+ 'agent-machine-pve1',+ 'agent-node-pve1',+ ]);+ const [agent, node] = store.state.resources;+ expect(agent?.sources).toEqual(['agent']);+ expect(agent?.platformType).toBe('agent');+ expect(agent?.proxmox).toBeUndefined();+ expect((agent?.platformData as Record<string, unknown>).clusterName).toBeUndefined();+ expect(agent?.platformScopes ?? []).not.toContain('proxmox-pve');+ expect(agent?.clusterId).toBeUndefined();+ expect(agent?.canonicalIdentity?.aliases).toEqual(['agent:machine-pve1']);+ expect(node?.sources).toEqual(['proxmox']);+ expect(node?.agent).toBeUndefined();+ };++ // Joined: the server presents one hybrid row.emitMessage({type: 'initialState',data: {connectedInfrastructure: [],resources: [{- id: 'agent-proxmox-delly',- type: 'agent',- name: 'delly',- displayName: 'delly',- platformId: 'delly',+ ...splitAgent,platformType: 'proxmox-pve',- sourceType: 'api',- sources: ['proxmox'],- status: 'online',- lastSeen: Date.now() - 1000,- proxmox: {- nodeName: 'delly',- clusterName: 'homelab',- },- platformData: {- sources: ['proxmox'],- proxmox: {- nodeName: 'delly',- clusterName: 'homelab',- },- },- },- {- id: 'agent-runtime-delly',- type: 'agent',- name: 'delly',- displayName: 'delly',- platformId: 'delly',- platformType: 'agent',- sourceType: 'agent',- sources: ['agent'],- status: 'online',- lastSeen: Date.now(),- agent: {- hostname: 'delly',- osName: 'Debian GNU/Linux',- },- platformData: {- sources: ['agent'],- agent: {- hostname: 'delly',- osName: 'Debian GNU/Linux',- },+ sourceType: 'hybrid',+ sources: ['agent', 'proxmox'],+ clusterId: 'cluster:homelab',+ identity: { hostnames: ['pve1'], machineId: 'machine-pve1', clusterName: 'homelab' },+ canonicalIdentity: {+ primaryId: 'agent:machine-pve1',+ aliases: ['agent:machine-pve1', 'node:pve1:pve1'],},+ proxmox: proxmoxFacet,+ platformData: proxmoxPlatformData,},],- lastUpdate: 1739059200000,+ lastUpdate: 100,activeAlerts: [],recentlyResolved: [],},});-expect(store.state.resources).toHaveLength(1);- expect(store.state.resources[0]?.id).toBe('agent-runtime-delly');expect(store.state.resources[0]?.sourceType).toBe('hybrid');- expect(store.state.resources[0]?.proxmox).toMatchObject({ clusterName: 'homelab' });- expect(store.state.resources[0]?.agent).toMatchObject({ osName: 'Debian GNU/Linux' });++ // The operator splits the pair: the server's delta strips the node's+ // facet from the agent row and adds the node row.+ emitMessage({+ type: 'rawData',+ data: {+ lastUpdate: 200,+ resourceDelta: {+ upserts: [+ {+ id: 'agent-machine-pve1',+ platformType: 'agent',+ sourceType: 'agent',+ sources: ['agent'],+ clusterId: null,+ identity: { clusterName: null },+ canonicalIdentity: { aliases: ['agent:machine-pve1'] },+ proxmox: null,+ platformData: {+ instance: null,+ pveVersion: null,+ isClusterMember: null,+ clusterName: null,+ connectionHealth: null,+ ...agentPlatformData,+ },+ },+ splitNode,+ ],+ order: ['agent-machine-pve1', 'agent-node-pve1'],+ },+ },+ });+ expectSplitRows();++ // A later metrics tick on one side leaves the pair apart.+ emitMessage({+ type: 'rawData',+ data: {+ lastUpdate: 300,+ resourceDelta: { upserts: [{ id: 'agent-machine-pve1', lastSeen: 300 }] },+ },+ });+ expectSplitRows();+ expect(store.state.resources[0]?.lastSeen).toBe(300);++ // So does the next full snapshot.+ emitMessage({+ type: 'rawData',+ data: {+ resources: [splitAgent, splitNode],+ lastUpdate: 400,+ },+ });+ expectSplitRows();} finally {dispose();}@@ -655,15 +742,14 @@ describe('websocket store unified resource contract', () => {}});- it('keeps canonically merged hosts consistent with full snapshots across deltas (#1601)', async () => {+ it('applies deltas for same-host rows to the raw server baseline (#1601)', async () => {const { store, dispose } = await createStoreHarness();try {await waitForOpenTick();- // Two server resources that the client coalesces into ONE host: an- // agent host and a docker host sharing a hostname. The server's- // per-client delta baseline keeps both IDs, so deltas reference IDs- // the merged client view no longer holds.+ // Two server rows sharing a hostname: an agent host and a docker host.+ // Each server row is one display row, so a delta for either ID patches+ // that row and never surfaces a typeless stub.emitMessage({type: 'initialState',data: {@@ -692,12 +778,11 @@ describe('websocket store unified resource contract', () => {},});- expect(store.state.resources).toHaveLength(1);- expect(store.state.resources[0]?.id).toBe('agent-host-1');+ expect(store.state.resources.map((resource) => resource.id)).toEqual([+ 'agent-host-1',+ 'docker-host-1',+ ]);- // A merge patch for the coalesced-away docker ID must not surface a- // typeless stub resource: the delta applies to the raw server baseline- // and the canonical merge runs again on the result.emitMessage({type: 'rawData',data: {@@ -708,13 +793,13 @@ describe('websocket store unified resource contract', () => {},});- expect(store.state.resources).toHaveLength(1);- expect(store.state.resources[0]?.id).toBe('agent-host-1');+ expect(store.state.resources).toHaveLength(2);+ expect(store.state.resources[1]?.id).toBe('docker-host-1');+ expect(store.state.resources[1]?.lastSeen).toBe(200);expect(store.state.resources.every((resource) => Boolean(resource.type))).toBe(true);// Removing the agent side server-side must leave the surviving docker- // host visible. Before the raw-baseline fix this removed the single- // merged client resource outright and the docker host never came back.+ // host visible.emitMessage({type: 'rawData',data: {diff --git a/frontend-modern/src/utils/__tests__/resourceStateAdapters.branchcov0723pm.test.ts b/frontend-modern/src/utils/__tests__/resourceStateAdapters.branchcov0723pm.test.tsindex 05005a8ce5..1bec42ec97 100644--- a/frontend-modern/src/utils/__tests__/resourceStateAdapters.branchcov0723pm.test.ts+++ b/frontend-modern/src/utils/__tests__/resourceStateAdapters.branchcov0723pm.test.ts@@ -325,9 +325,7 @@ describe('mergeCanonicalIdentity + merge fallbacks (via mergeCanonicalResource)'});// ===========================================================================-// mergeCanonicalResourceSnapshot — empty-incoming early return, and the-// getHostResourceMergeKey `undefined` arm (reached only when every identity-// candidate — including the resource id — is blank).+// mergeCanonicalResourceSnapshot — empty-incoming early return.// ===========================================================================describe('mergeCanonicalResourceSnapshot edge arms', () => {@@ -335,25 +333,6 @@ describe('mergeCanonicalResourceSnapshot edge arms', () => {const existing: Resource = agent({ platformData: { sources: ['agent'] } });expect(mergeCanonicalResourceSnapshot([], [existing])).toEqual([]);});-- it('does not coalesce two agents whose every identity candidate is blank', () => {- const blank = (): Resource =>- ({- id: '',- type: 'agent',- name: '',- displayName: '',- platformId: '',- platformType: 'agent',- sourceType: 'agent',- status: 'online',- lastSeen: 100,- }) as unknown as Resource;- const out = mergeCanonicalResourceSnapshot([blank(), blank()], []);- // No host key derivable (getHostResourceMergeKey returns undefined) → both- // stay as separate entries instead of being coalesced.- expect(out).toHaveLength(2);- });});// ===========================================================================@@ -482,69 +461,6 @@ describe('pmgInstanceFromResource fallback arms', () => {});});-// ===========================================================================-// normalizeResourceIdentityToken — the `normalized.length > 0 ? normalized :-// undefined` false arm. Only reachable via getHostResourceMergeKey, which runs-// every identity candidate through the normaliser. A whitespace-only candidate-// is truthy (so it skips the `!value` guard) but trims to ''.-// ===========================================================================--describe('normalizeResourceIdentityToken whitespace candidate (via mergeCanonicalResourceSnapshot)', () => {- it('drops a whitespace-only platformId candidate while still coalescing on a valid hostname', () => {- const mkAgent = (id: string, lastSeen: number): Resource =>- ({- id,- type: 'agent',- name: 'merge-host',- displayName: 'merge-host',- platformId: 'merge-host',- platformType: 'proxmox-pve',- sourceType: 'hybrid',- status: 'online',- lastSeen,- canonicalIdentity: { platformId: ' ', hostname: 'merge-host' },- }) as unknown as Resource;-- const out = mergeCanonicalResourceSnapshot([mkAgent('a', 100), mkAgent('b', 200)], []);- // The whitespace platformId candidate exercises the length===0 false arm- // (→ undefined) but 'merge-host' still forms hostKey 'agent:merge-host',- // so the two hybrid agents coalesce into one.- expect(out).toHaveLength(1);- });-});--// ===========================================================================-// sourceListHas — the `!sources || sources.length === 0` early-return arm.-// sourceListHas is only ever called with an empty/undefined list through-// sourceListContainsRuntimePlatform when unionSources is undefined, which-// happens when two coalescing agents each derive no canonical sources.-// ===========================================================================--describe('sourceListHas empty-sources arm (via mergeCanonicalResourceSnapshot)', () => {- it('does not merge two agents that share a host key but derive no canonical sources', () => {- const mkAgent = (id: string, lastSeen: number): Resource =>- ({- id,- type: 'agent',- name: 'gen-host',- displayName: 'gen-host',- platformId: 'gen-host',- platformType: 'generic',- sourceType: 'api',- status: 'online',- lastSeen,- canonicalIdentity: { hostname: 'gen-host' },- }) as unknown as Resource;-- const out = mergeCanonicalResourceSnapshot([mkAgent('a', 100), mkAgent('b', 200)], []);- // Both derive hostKey 'agent:gen-host', but getCanonicalSourceList returns- // undefined for each (generic + api, no facets) → unionSources undefined →- // sourceListHas(undefined, 'agent') takes its empty-sources arm → false.- expect(out).toHaveLength(2);- expect(out.map((r) => r.id).sort()).toEqual(['a', 'b']);- });-});-// ===========================================================================// readStringArray — the `normalized.length > 0 ? ... : undefined` false arm.// Reached when an array is supplied but every entry is blank after trim. Thediff --git a/frontend-modern/src/utils/__tests__/resourceStateAdapters.coverage2.test.ts b/frontend-modern/src/utils/__tests__/resourceStateAdapters.coverage2.test.tsindex d78b7157dc..234cfd52dd 100644--- a/frontend-modern/src/utils/__tests__/resourceStateAdapters.coverage2.test.ts+++ b/frontend-modern/src/utils/__tests__/resourceStateAdapters.coverage2.test.ts@@ -3,7 +3,6 @@ import { describe, expect, it } from 'vitest';import {canonicalizeRealtimeResource,mergeCanonicalResource,- mergeCanonicalResourceSnapshot,nodeFromResource,pbsInstanceFromResource,pmgInstanceFromResource,@@ -197,81 +196,6 @@ describe('getCanonicalPlatformId (via nodeFromResource.instance)', () => {});});-// ===================================================================-// normalizeResourceIdentityToken + getHostResourceMergeKey — reached-// through coalesceRealtimeResourceSnapshot (via mergeCanonicalResourceSnapshot)-// ===================================================================--describe('normalizeResourceIdentityToken + getHostResourceMergeKey (via mergeCanonicalResourceSnapshot)', () => {- it('lowercases and trims canonical hostname to form the agent merge key', () => {- const merged = mergeCanonicalResourceSnapshot(- [- {- id: 'a',- type: 'agent',- name: 'Host',- displayName: 'Host',- platformId: 'host',- platformType: 'agent',- sourceType: 'agent',- sources: ['agent', 'proxmox'],- status: 'online',- lastSeen: 100,- canonicalIdentity: { hostname: 'HOST.LOCAL', platformId: 'host' },- } as Resource,- {- id: 'b',- type: 'agent',- name: 'Host',- displayName: 'Host',- platformId: 'host',- platformType: 'proxmox-pve',- sourceType: 'api',- sources: ['proxmox'],- status: 'online',- lastSeen: 200,- canonicalIdentity: { hostname: 'host.local', platformId: 'host' },- } as Resource,- ],- [],- );- // Both normalize to 'host.local' → same merge key → coalesced into one- expect(merged).toHaveLength(1);- });-- it('returns undefined merge key when all identity candidates are empty, keeping resources separate', () => {- const resources = mergeCanonicalResourceSnapshot(- [- {- id: 'empty-1',- type: 'agent',- name: '',- displayName: '',- platformId: '',- platformType: 'agent',- sourceType: 'agent',- status: 'online',- lastSeen: 100,- } as Resource,- {- id: 'empty-2',- type: 'agent',- name: '',- displayName: '',- platformId: '',- platformType: 'agent',- sourceType: 'agent',- status: 'online',- lastSeen: 200,- } as Resource,- ],- [],- );- // No host key derivable → both stay separate- expect(resources).toHaveLength(2);- });-});-// ===================================================================// sourceListHas + normalizeSourceToken — reached through many paths.// normalizeSourceToken tries normalizeSourcePlatformKey first, then falls@@ -1129,7 +1053,7 @@ describe('mergePlatformData (via mergeCanonicalResource)', () => {platformType: 'agent',sourceType: 'agent',platformData: {- sources: ['agent'],+ sources: ['agent', 'proxmox'],storage: { platform: 'zfs' },sourceStatus: { agent: { healthy: true } },},@@ -1139,7 +1063,7 @@ describe('mergePlatformData (via mergeCanonicalResource)', () => {platformType: 'agent',sourceType: 'agent',platformData: {- sources: ['agent'],+ sources: ['agent', 'proxmox'],storage: { topology: 'pool' },sourceStatus: { proxmox: { healthy: false } },},@@ -1167,89 +1091,6 @@ describe('mergeCanonicalResource (no existing)', () => {});});-// ===================================================================-// shouldMergeRealtimeHostResources + preferHostResourcePrimary +-// withMergedSnapshotSources — reached through mergeCanonicalResourceSnapshot-// ===================================================================--describe('shouldMergeRealtimeHostResources + preferHostResourcePrimary (via mergeCanonicalResourceSnapshot)', () => {- it('does not merge two docker-sourced agents because union lacks "agent" source', () => {- const resources = mergeCanonicalResourceSnapshot(- [- {- id: 'docker-a',- type: 'agent',- name: 'same-host',- displayName: 'same-host',- platformId: 'same-host',- platformType: 'docker',- sourceType: 'api',- sources: ['docker'],- status: 'online',- lastSeen: 100,- canonicalIdentity: { hostname: 'same-host', platformId: 'same-host' },- } as Resource,- {- id: 'docker-b',- type: 'agent',- name: 'same-host',- displayName: 'same-host',- platformId: 'same-host',- platformType: 'docker',- sourceType: 'api',- sources: ['docker'],- status: 'online',- lastSeen: 200,- canonicalIdentity: { hostname: 'same-host', platformId: 'same-host' },- } as Resource,- ],- [],- );- // shouldMergeRealtimeHostResources: union has 'docker' (runtime) but not 'agent' → false- expect(resources).toHaveLength(2);- });-- it('uses lastSeen as tiebreaker when both merged agents have agent sources', () => {- const merged = mergeCanonicalResourceSnapshot(- [- {- id: 'older',- type: 'agent',- name: 'tie-host',- displayName: 'tie-host',- platformId: 'tie-host',- platformType: 'proxmox-pve',- sourceType: 'hybrid',- sources: ['agent', 'proxmox'],- status: 'online',- lastSeen: 1000,- canonicalIdentity: { hostname: 'tie-host', platformId: 'tie-host' },- proxmox: { nodeName: 'tie-host' } as unknown as Resource['proxmox'],- } as Resource,- {- id: 'newer',- type: 'agent',- name: 'tie-host',- displayName: 'tie-host',- platformId: 'tie-host',- platformType: 'proxmox-pve',- sourceType: 'hybrid',- sources: ['agent', 'proxmox'],- status: 'online',- lastSeen: 2000,- canonicalIdentity: { hostname: 'tie-host', platformId: 'tie-host' },- proxmox: { nodeName: 'tie-host' } as unknown as Resource['proxmox'],- } as Resource,- ],- [],- );- // Both have agent + runtime → merge. Both have agent sources → lastSeen tiebreaker.- // 'newer' (lastSeen 2000) >= 'older' (1000) → primary = newer- expect(merged).toHaveLength(1);- expect(merged[0].id).toBe('newer');- });-});-// ===================================================================// mapPMGQuarantine — reached through pmgInstanceFromResource// ===================================================================diff --git a/frontend-modern/src/utils/__tests__/resourceStateAdapters.test.ts b/frontend-modern/src/utils/__tests__/resourceStateAdapters.test.tsindex 9d9502f7b8..f318072289 100644--- a/frontend-modern/src/utils/__tests__/resourceStateAdapters.test.ts+++ b/frontend-modern/src/utils/__tests__/resourceStateAdapters.test.ts@@ -756,90 +756,526 @@ describe('resourceStateAdapters nodeFromResource', () => {});});- it('coalesces split realtime Proxmox and agent host records before rendering', () => {- const proxmoxOnly = {- id: 'agent-proxmox-delly',+ // The server presents host rows already coalesced (presentation coalesce+ // with the operator's exclusions), so the browser renders each realtime row+ // as delivered: a joined node and agent arrive as one hybrid row, and a pair+ // the operator split arrives as two rows that must stay two. Fixtures follow+ // the broadcast shape (monitorPlatformData flattens a Proxmox host's facts+ // into platformData; the broadcast adds platformData.sources itself).+ const lastSeen = Date.now();+ const proxmoxFacet = {+ nodeName: 'pve1',+ instance: 'pve1',+ clusterName: 'homelab',+ linkedAgentId: 'agent-pve1',+ };+ const proxmoxPlatformData = {+ instance: 'pve1',+ host: '',+ pveVersion: '9.1.9',+ kernelVersion: '6.14.8-2-pve',+ cpuInfo: { model: 'Xeon', cores: 8 },+ isClusterMember: true,+ clusterName: 'homelab',+ connectionHealth: 'online',+ };+ const agentFacet = { agentId: 'agent-pve1', hostname: 'pve1', machineId: 'machine-pve1' };+ const splitNode = {+ id: 'agent-node-pve1',+ type: 'agent',+ name: 'pve1',+ displayName: 'pve1',+ platformId: 'pve1',+ platformType: 'proxmox-pve',+ sourceType: 'api',+ sources: ['proxmox'],+ clusterId: 'cluster:homelab',+ status: 'online',+ lastSeen,+ canonicalIdentity: {+ displayName: 'pve1',+ hostname: 'pve1',+ platformId: 'pve1',+ primaryId: 'node:pve1:pve1',+ aliases: ['node:pve1:pve1'],+ },+ identity: { hostnames: ['pve1'], clusterName: 'homelab' },+ // The monitor's node record keeps its link to the agent after a split.+ proxmox: proxmoxFacet,+ platformData: proxmoxPlatformData,+ } as unknown as Resource;+ const splitAgent = {+ id: 'agent-machine-pve1',+ type: 'agent',+ name: 'pve1',+ displayName: 'pve1',+ platformId: 'pve1',+ platformType: 'agent',+ sourceType: 'agent',+ sources: ['agent'],+ status: 'online',+ lastSeen,+ canonicalIdentity: {+ displayName: 'pve1',+ hostname: 'pve1',+ platformId: 'pve1',+ primaryId: 'agent:machine-pve1',+ aliases: ['agent:machine-pve1'],+ },+ identity: { hostnames: ['pve1'], machineId: 'machine-pve1' },+ agent: agentFacet,+ platformData: {+ platform: 'linux',+ osName: 'Debian GNU/Linux',+ osVersion: '13',+ agentVersion: '6.0.0',+ },+ } as unknown as Resource;+ // What the server presented while the pair was joined.+ const joinedHost = {+ ...splitAgent,+ platformType: 'proxmox-pve',+ sourceType: 'hybrid',+ sources: ['agent', 'proxmox'],+ clusterId: 'cluster:homelab',+ canonicalIdentity: {+ ...splitAgent.canonicalIdentity,+ aliases: ['agent:machine-pve1', 'node:pve1:pve1'],+ },+ identity: { hostnames: ['pve1'], machineId: 'machine-pve1', clusterName: 'homelab' },+ proxmox: proxmoxFacet,+ platformData: proxmoxPlatformData,+ } as unknown as Resource;++ it('keeps a server-joined node and agent as one hybrid row', () => {+ const rows = mergeCanonicalResourceSnapshot([structuredClone(joinedHost)], []);++ expect(rows).toHaveLength(1);+ expect(rows[0]?.id).toBe('agent-machine-pve1');+ expect(rows[0]?.platformType).toBe('proxmox-pve');+ expect(rows[0]?.sourceType).toBe('hybrid');+ expect(rows[0]?.proxmox).toMatchObject({ nodeName: 'pve1' });+ expect(rows[0]?.agent).toMatchObject({ agentId: 'agent-pve1' });+ });++ it('keeps an operator-split node and agent as two rows through snapshots and deltas', () => {+ const expectSplitRows = (rows: Resource[]) => {+ expect(rows.map((row) => row.id).sort()).toEqual(['agent-machine-pve1', 'agent-node-pve1']);+ const node = rows.find((row) => row.id === 'agent-node-pve1');+ const agent = rows.find((row) => row.id === 'agent-machine-pve1');+ expect(node?.sources).toEqual(['proxmox']);+ expect(node?.agent?.agentId).toBeUndefined();+ expect((node?.agent as Record<string, unknown> | undefined)?.machineId).toBeUndefined();+ expect(agent?.sources).toEqual(['agent']);+ expect(agent?.sourceType).toBe('agent');+ expect(agent?.platformType).toBe('agent');+ // Nothing the joined row carried for the node stays on the agent: no+ // Proxmox facet (nor the flattened facts it is synthesized from), scope,+ // cluster, cluster identity, or node alias.+ expect(agent?.proxmox).toBeUndefined();+ const agentPlatformData = agent?.platformData as Record<string, unknown>;+ expect(agentPlatformData.proxmox).toBeUndefined();+ expect(agentPlatformData.pveVersion).toBeUndefined();+ expect(agentPlatformData.clusterName).toBeUndefined();+ expect(agent?.platformScopes ?? []).not.toContain('proxmox-pve');+ expect(agent?.clusterId).toBeUndefined();+ expect((agent?.identity as Record<string, unknown>).clusterName).toBeUndefined();+ expect(agent?.canonicalIdentity?.aliases).toEqual(['agent:machine-pve1']);+ };++ for (const incoming of [+ [splitNode, splitAgent],+ [splitAgent, splitNode],+ ]) {+ expectSplitRows(mergeCanonicalResourceSnapshot(structuredClone(incoming), []));+ }++ // The split lands on a browser still holding the joined row: the agent+ // keeps the joined row's ID and must shed the node's Proxmox facet.+ const full = mergeCanonicalResourceSnapshot(+ [structuredClone(splitNode), structuredClone(splitAgent)],+ [mergeCanonicalResourceSnapshot([structuredClone(joinedHost)], [])[0]!],+ );+ expectSplitRows(full);++ const agentTick = mergeCanonicalResourceDeltaSnapshot(+ [structuredClone(splitNode), { ...structuredClone(splitAgent), cpu: { current: 42 } }],+ full,+ new Set(['agent-machine-pve1']),+ );+ expectSplitRows(agentTick);+ expect(agentTick[0]).toBe(full[0]);+ expect(agentTick[1]?.cpu?.current).toBe(42);++ const bothTick = mergeCanonicalResourceDeltaSnapshot(+ [+ { ...structuredClone(splitNode), cpu: { current: 7 } },+ { ...structuredClone(splitAgent), cpu: { current: 43 } },+ ],+ agentTick,+ new Set(['agent-node-pve1', 'agent-machine-pve1']),+ );+ expectSplitRows(bothTick);+ expect(bothTick.map((row) => row.cpu?.current)).toEqual([7, 43]);++ // A delta that adds the node beside the joined row (the split's first+ // tick) leaves two rows as well.+ const firstSplitTick = mergeCanonicalResourceDeltaSnapshot(+ [structuredClone(splitAgent), structuredClone(splitNode)],+ mergeCanonicalResourceSnapshot([structuredClone(joinedHost)], []),+ new Set(['agent-machine-pve1', 'agent-node-pve1']),+ );+ expectSplitRows(firstSplitTick);+ });++ it('keeps REST-only scopes and readiness a departed source did not own', () => {+ // A Docker container in a Proxmox LXC whose availability check was+ // removed: REST promoted its platform scopes, source status and readiness,+ // which the realtime payload never carries. Docker stays listed, so its+ // status entry, its recorded action refusal and its Proxmox scope (the LXC+ // host) stay; only the availability entry goes.+ const restRow = {+ id: 'app-container-frigate',+ type: 'app-container',+ name: 'frigate',+ displayName: 'frigate',+ platformType: 'docker',+ platformScopes: ['proxmox-pve', 'docker', 'availability'],+ sourceType: 'hybrid',+ status: 'online',+ lastSeen,+ discoveryReadiness: { state: 'fresh', targetId: 'agent-141', resourceId: 'frigate-141' },+ actionReadiness: [{ name: 'restart', available: false, reason: 'lifecycle disabled' }],+ availability: { status: 'up' },+ sourceStatus: { docker: { status: 'impaired' }, availability: { status: 'online' } },+ platformData: {+ sources: ['docker', 'availability'],+ sourceStatus: { docker: { status: 'impaired' }, availability: { status: 'online' } },+ docker: { hostSourceId: 'proxmox-lxc-docker:pve-a:node-a:141', runtime: 'docker' },+ },+ } as unknown as Resource;+ const [row] = mergeCanonicalResourceSnapshot(+ [+ {+ id: 'app-container-frigate',+ type: 'app-container',+ name: 'frigate',+ displayName: 'frigate',+ platformType: 'docker',+ sourceType: 'api',+ sources: ['docker'],+ status: 'online',+ lastSeen,+ docker: { hostSourceId: 'proxmox-lxc-docker:pve-a:node-a:141', runtime: 'docker' },+ } as unknown as Resource,+ ],+ [restRow],+ );++ expect(row?.platformScopes).toEqual(['proxmox-pve', 'docker']);+ // Realtime carries a discovery target only for agent and Docker host rows,+ // so a container row's readiness (REST enrichment) cannot be judged and stays.+ expect(row?.discoveryReadiness).toEqual({+ state: 'fresh',+ targetId: 'agent-141',+ resourceId: 'frigate-141',+ });+ expect(row?.actionReadiness).toEqual([+ { name: 'restart', available: false, reason: 'lifecycle disabled' },+ ]);+ expect(row?.availability).toBeUndefined();+ expect(row?.sourceStatus).toEqual({ docker: { status: 'impaired' } });+ expect((row?.platformData as Record<string, unknown>).sourceStatus).toEqual({+ docker: { status: 'impaired' },+ });+ });++ it('keeps the Proxmox scope of a Docker LXC host when a Proxmox source departs', () => {+ // The row's two lists disagree (an enrichment of another generation named a+ // Proxmox source). The Docker host still runs inside a Proxmox container, so+ // the server keeps placing it on the Proxmox page whatever sources it lists;+ // an agent scope no surviving source or facet supports goes.+ const hostSourceId = 'proxmox-lxc-docker:pve-a:node-a:141';+ const skewed = {+ id: 'docker-host-141',type: 'agent',- name: 'delly',- displayName: 'delly',- platformId: 'delly',- platformType: 'proxmox-pve',+ name: 'frigate-host',+ displayName: 'frigate-host',+ platformType: 'docker',+ platformScopes: ['proxmox-pve', 'docker', 'agent'],sourceType: 'api',- sources: ['proxmox'],+ sources: ['docker'],status: 'online',- lastSeen: Date.now() - 1_000,- canonicalIdentity: {- displayName: 'delly',- hostname: 'delly',- platformId: 'delly',- primaryId: 'node:homelab-delly',- },- proxmox: {- nodeName: 'delly',- clusterName: 'homelab',- pveVersion: '9.1.9',- },+ lastSeen,+ docker: { hostSourceId, runtime: 'docker' },platformData: {- sources: ['proxmox'],- proxmox: {- nodeName: 'delly',- clusterName: 'homelab',- pveVersion: '9.1.9',- },+ sources: ['docker', 'proxmox', 'agent'],+ docker: { hostSourceId, runtime: 'docker' },},- } as Resource;- const agentOnly = {- id: 'agent-runtime-delly',+ } as unknown as Resource;+ const realtime = {+ id: 'docker-host-141',type: 'agent',- name: 'delly',- displayName: 'delly',- platformId: 'delly',+ name: 'frigate-host',+ displayName: 'frigate-host',+ platformType: 'docker',+ sourceType: 'api',+ sources: ['docker'],+ status: 'online',+ lastSeen,+ docker: { hostSourceId, runtime: 'docker' },+ } as unknown as Resource;++ const [row] = mergeCanonicalResourceSnapshot([realtime], [skewed]);++ expect(row?.platformScopes).toEqual(['proxmox-pve', 'docker']);+ });++ it('drops the agent scope of a split node that keeps the joined id', () => {+ // The node's flattened kernel version reads as an agent facet once the row+ // is canonicalized; that is compatibility synthesis, not evidence that the+ // agent still reports for this row.+ const joined = {+ ...structuredClone(joinedHost),+ platformScopes: ['agent', 'proxmox-pve'],+ } as unknown as Resource;+ const node = {+ ...structuredClone(splitNode),+ id: joinedHost.id,+ platformData: { ...proxmoxPlatformData, kernelVersion: '6.14.8-2-pve' },+ } as unknown as Resource;++ const [row] = mergeCanonicalResourceSnapshot([node], [joined]);++ expect(row?.sources).toEqual(['proxmox']);+ expect(row?.platformScopes).toEqual(['proxmox-pve']);+ });++ it('drops discovery readiness whose target the rebuilt row no longer has', () => {+ const previous = {+ id: 'host-1',+ type: 'agent',+ name: 'host-1',+ displayName: 'host-1',+ platformType: 'proxmox-pve',+ sourceType: 'hybrid',+ sources: ['proxmox', 'docker'],+ status: 'online',+ lastSeen,+ discoveryTarget: { resourceType: 'agent', agentId: 'docker-agent-1', resourceId: 'host-1' },+ discoveryReadiness: { state: 'fresh', targetId: 'docker-agent-1', source: 'docker' },+ platformData: { sources: ['proxmox', 'docker'] },+ } as unknown as Resource;+ const node = {+ ...structuredClone(previous),+ sourceType: 'api',+ sources: ['proxmox'],+ discoveryTarget: { resourceType: 'agent', agentId: 'pve-node', resourceId: 'pve-node' },+ discoveryReadiness: undefined,+ platformData: { sources: ['proxmox'] },+ } as unknown as Resource;+ delete (node as unknown as Record<string, unknown>).discoveryReadiness;++ const [row] = mergeCanonicalResourceSnapshot([node], [previous]);++ expect(row?.sources).toEqual(['proxmox']);+ expect(row?.discoveryReadiness).toBeUndefined();+ });++ it('compares each discovery coordinate with the same coordinate of the row target', () => {+ const rebuild = (readiness: Record<string, string>, agentId: string, resourceId: string) => {+ const previous = {+ id: 'host-2',+ type: 'agent',+ name: 'host-2',+ displayName: 'host-2',+ platformType: 'proxmox-pve',+ sourceType: 'hybrid',+ sources: ['proxmox', 'docker'],+ status: 'online',+ lastSeen,+ discoveryReadiness: { state: 'fresh', ...readiness },+ platformData: { sources: ['proxmox', 'docker'] },+ } as unknown as Resource;+ const node = {+ ...structuredClone(previous),+ sourceType: 'api',+ sources: ['proxmox'],+ discoveryTarget: { resourceType: 'agent', agentId, resourceId },+ platformData: { sources: ['proxmox'] },+ } as unknown as Resource;+ delete (node as unknown as Record<string, unknown>).discoveryReadiness;+ return mergeCanonicalResourceSnapshot([node], [previous])[0]?.discoveryReadiness;+ };++ const named = { targetId: 'agent-1', resourceId: 'r1' };+ expect(rebuild(named, 'agent-1', 'r1')).toMatchObject(named);+ // One coordinate matching is not enough, and equal values in the other+ // field do not count.+ expect(rebuild(named, 'agent-1', 'r2')).toBeUndefined();+ expect(rebuild(named, 'agent-2', 'r1')).toBeUndefined();+ expect(rebuild({ targetId: 'r1' }, 'agent-9', 'r1')).toBeUndefined();+ });++ it('keeps the Proxmox scope of an agent-reported disk that carries a Proxmox facet', () => {+ // The server gives an agent-reported SMART disk under a merged Proxmox node+ // a Proxmox ownership facet while it lists only the agent (registry.go).+ const previous = {+ id: 'disk-1',+ type: 'physical_disk',+ name: 'sda',+ displayName: 'sda',platformType: 'agent',+ platformScopes: ['agent', 'proxmox-pve'],sourceType: 'agent',sources: ['agent'],status: 'online',- lastSeen: Date.now(),+ lastSeen,+ platformData: { sources: ['agent', 'proxmox'] },+ } as unknown as Resource;+ const incoming = {+ id: 'disk-1',+ type: 'physical_disk',+ name: 'sda',+ displayName: 'sda',+ platformType: 'agent',+ sourceType: 'agent',+ sources: ['agent'],+ status: 'online',+ lastSeen,+ proxmox: { nodeName: 'pve1', instance: 'pve1' },+ } as unknown as Resource;++ const [row] = mergeCanonicalResourceSnapshot([incoming], [previous]);++ expect(row?.platformScopes).toEqual(['agent', 'proxmox-pve']);+ });++ it('deletes inherited source status when pruning leaves nothing', () => {+ const status = { proxmox: { status: 'online', lastSeen: '2026-02-06T12:00:00Z' } };+ const previous = {+ ...structuredClone(joinedHost),+ sourceStatus: status,+ platformData: { sources: ['agent', 'proxmox'], sourceStatus: status },+ } as unknown as Resource;+ // The incoming row's own enrichment names only the departed source.+ const incoming = {+ ...structuredClone(splitAgent),+ sourceStatus: status,+ platformData: { sources: ['agent'], sourceStatus: status },+ } as unknown as Resource;++ const [row] = mergeCanonicalResourceSnapshot([incoming], [previous]);++ expect(row?.sourceStatus).toBeUndefined();+ expect((row?.platformData as Record<string, unknown>).sourceStatus).toBeUndefined();+ });++ it('rebuilds a row whose own source lists disagree once the realtime row drops the extra source', () => {+ // What a late REST response, or a shared array that changed under the row,+ // leaves behind: top-level sources already say agent, the joined era's+ // enrichment still says Proxmox too.+ const status = {+ agent: { status: 'online', lastSeen: '2026-02-06T12:00:00Z' },+ proxmox: { status: 'online', lastSeen: '2026-02-06T12:00:00Z' },+ };+ const halfUpdated = {+ ...structuredClone(splitAgent),+ platformType: 'proxmox-pve',+ platformScopes: ['agent', 'proxmox-pve'],+ sourceStatus: status,canonicalIdentity: {- displayName: 'delly',- hostname: 'delly',- platformId: 'delly',- primaryId: 'agent:delly-runtime',- },- agent: {- hostname: 'delly',- osName: 'Debian GNU/Linux',- osVersion: '13',+ ...splitAgent.canonicalIdentity,+ aliases: ['agent:machine-pve1', 'node:pve1:pve1'],},platformData: {- sources: ['agent'],- agent: {- hostname: 'delly',- osName: 'Debian GNU/Linux',- osVersion: '13',- },+ sources: ['agent', 'proxmox'],+ platformScopes: ['agent', 'proxmox-pve'],+ sourceStatus: status,+ ...proxmoxPlatformData,},- } as Resource;+ } as unknown as Resource;- for (const incoming of [- [proxmoxOnly, agentOnly],- [agentOnly, proxmoxOnly],- ]) {- const [resource] = mergeCanonicalResourceSnapshot(incoming, []);-- expect(mergeCanonicalResourceSnapshot(incoming, [])).toHaveLength(1);- expect(resource.id).toBe('agent-runtime-delly');- expect(resource.platformType).toBe('proxmox-pve');- expect(resource.sourceType).toBe('hybrid');- expect(new Set(resource.sources ?? [])).toEqual(new Set(['agent', 'proxmox']));- expect(resource.proxmox).toMatchObject({ nodeName: 'delly', clusterName: 'homelab' });- expect(resource.agent).toMatchObject({ hostname: 'delly', osName: 'Debian GNU/Linux' });- expect((resource.platformData as Record<string, unknown>).proxmox).toMatchObject({- nodeName: 'delly',- });- expect((resource.platformData as Record<string, unknown>).agent).toMatchObject({- hostname: 'delly',- });- }+ const [row] = mergeCanonicalResourceSnapshot([structuredClone(splitAgent)], [halfUpdated]);++ expect(row?.platformType).toBe('agent');+ expect(row?.platformScopes ?? []).not.toContain('proxmox-pve');+ expect(Object.keys(row?.sourceStatus ?? {})).not.toContain('proxmox');+ const platformData = row?.platformData as Record<string, unknown>;+ expect(platformData.sources).toEqual(['agent']);+ expect(platformData.platformScopes).toBeUndefined();+ expect(Object.keys(platformData.sourceStatus as object)).toEqual(['agent']);+ expect(Object.keys(row?.sourceStatus ?? {})).toEqual(['agent']);+ expect(platformData.pveVersion).toBeUndefined();+ expect(row?.canonicalIdentity?.aliases).toEqual(['agent:machine-pve1']);+ });++ it('prunes source status entries of sources the merged row no longer lists', () => {+ const status = {+ agent: { status: 'online', lastSeen: '2026-02-06T12:00:00Z' },+ proxmox: { status: 'online', lastSeen: '2026-02-06T12:00:00Z' },+ };+ // The previous display row already lists only the agent but still carries+ // the enrichment of the joined era (what a late REST response leaves).+ const existing = {+ id: 'agent-machine-pve1',+ type: 'agent',+ name: 'pve1',+ displayName: 'pve1',+ platformId: 'pve1',+ platformType: 'agent',+ sourceType: 'agent',+ sources: ['agent'],+ status: 'online',+ lastSeen,+ sourceStatus: status,+ platformData: { sources: ['agent'], sourceStatus: status },+ } as unknown as Resource;+ // A realtime row omits the key; it never sets it to undefined.+ const withoutStatus = (row: Resource, sources: string[]): Resource => {+ const copy = structuredClone(row) as unknown as Record<string, unknown>;+ delete copy.sourceStatus;+ copy.platformData = { sources };+ return copy as unknown as Resource;+ };+ const incoming = withoutStatus(existing, ['agent']);++ const [row] = mergeCanonicalResourceSnapshot([incoming], [existing]);++ expect(Object.keys(row?.sourceStatus ?? {})).toEqual(['agent']);+ expect(+ Object.keys((row?.platformData as Record<string, unknown>).sourceStatus as object),+ ).toEqual(['agent']);++ // Entries of listed sources stay, as REST enrichment the realtime row lacks.+ const joined = {+ ...structuredClone(existing),+ sources: ['agent', 'proxmox'],+ platformData: { sources: ['agent', 'proxmox'], sourceStatus: status },+ } as unknown as Resource;+ const [kept] = mergeCanonicalResourceSnapshot(+ [withoutStatus(joined, ['agent', 'proxmox'])],+ [joined],+ );+ expect(Object.keys(kept?.sourceStatus ?? {}).sort()).toEqual(['agent', 'proxmox']);+ });++ it('merges a thin row without a source list of its own instead of rebuilding it', () => {+ // Only a source list the incoming row carries proves a source left; one+ // inferred from a thin row's facets does not.+ const previous = mergeCanonicalResourceSnapshot([structuredClone(joinedHost)], [])[0]!;+ const thin = {+ ...structuredClone(joinedHost),+ sources: undefined,+ agent: undefined,+ platformData: undefined,+ } as unknown as Resource;++ const [row] = mergeCanonicalResourceSnapshot([thin], [previous]);++ expect(row?.clusterId).toBe('cluster:homelab');+ expect(row?.canonicalIdentity?.aliases).toEqual(['agent:machine-pve1', 'node:pve1:pve1']);+ expect((row?.identity as Record<string, unknown>).machineId).toBe('machine-pve1');});it('keeps same-hostname standalone Proxmox provider rows separate across realtime merges', () => {@@ -892,7 +1328,8 @@ describe('resourceStateAdapters nodeFromResource', () => {// Mirrors #1753 after one same-name site's agent has authenticated while// the other is still represented by its independent provider poll. The// browser must not undo the server's provider-scoped split on a later- // realtime reconciliation.+ // realtime reconciliation. Whether two rows of one endpoint join is the+ // server's presentation decision (presentation_coalesce.go).const staging = providerRow('staging-pve','Tripper Staging',@@ -924,14 +1361,6 @@ describe('resourceStateAdapters nodeFromResource', () => {'hema-production','hema-staging',]);-- const duplicateEndpoint = providerRow(- 'duplicate-pve',- 'Duplicate connection',- 'duplicate-instance',- 'pve.hemastaging.hot:8006',- );- expect(mergeCanonicalResourceSnapshot([staging, duplicateEndpoint], [])).toHaveLength(1);});it('does not coalesce same-name agent-only records without a platform source bridge', () => {@@ -1433,7 +1862,7 @@ describe('incremental canonical resource snapshots', () => {expect(result[1]?.cpu?.current).toBe(75);});- it('preserves agent identity when no member of its host-merge group changed', () => {+ it('preserves an unchanged agent row by identity', () => {const agent = {id: 'agent-a',type: 'agent',@@ -1473,10 +1902,9 @@ describe('incremental canonical resource snapshots', () => {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.+ it('drops a removed row and keeps its same-host neighbour by identity', () => {+ // A flagged id missing from the incoming snapshot is a removal; the+ // neighbour sharing its hostname is a separate server row and stays as is.const agent = {id: 'agent-a',type: 'agent',@@ -1484,15 +1912,25 @@ describe('incremental canonical resource snapshots', () => {status: 'online',sources: ['agent'],} as unknown as Resource;- const incoming = [structuredClone(agent)];+ const platformSide = {+ id: 'pve-a',+ type: 'agent',+ name: 'host-a',+ status: 'online',+ sources: ['proxmox-pve'],+ } as unknown as Resource;- const result = mergeCanonicalResourceDeltaSnapshot(incoming, [agent], new Set(['gone-id']));+ const result = mergeCanonicalResourceDeltaSnapshot(+ [structuredClone(agent)],+ [agent, platformSide],+ new Set(['pve-a']),+ );- expect(result[0]).not.toBe(agent);- expect(result[0]?.id).toBe('agent-a');+ expect(result).toHaveLength(1);+ expect(result[0]).toBe(agent);});- it('still coalesces a dirty host-merge group into one merged agent', () => {+ it('keeps two server rows that share a hostname as two rows', () => {const agentSide = {id: 'agent-a',type: 'agent',@@ -1511,8 +1949,9 @@ describe('incremental canonical resource snapshots', () => {const result = mergeCanonicalResourceDeltaSnapshot(incoming, [], new Set(['pve-a']));- expect(result).toHaveLength(1);- expect(result[0]?.sources).toEqual(expect.arrayContaining(['agent', 'proxmox-pve']));+ expect(result.map((row) => row.id)).toEqual(['agent-a', 'pve-a']);+ expect(result[0]?.sources).toEqual(['agent']);+ expect(result[1]?.sources).toEqual(['proxmox-pve']);});});diff --git a/frontend-modern/src/utils/resourceStateAdapters.ts b/frontend-modern/src/utils/resourceStateAdapters.tsindex fcd3bac486..7b7eeb6599 100644--- a/frontend-modern/src/utils/resourceStateAdapters.ts+++ b/frontend-modern/src/utils/resourceStateAdapters.ts@@ -75,12 +75,6 @@ const getCanonicalPlatformId = (resource: Resource): string | undefined => {: undefined;};-const normalizeResourceIdentityToken = (value: string | undefined): string | undefined => {- if (!value) return undefined;- const normalized = value.trim().toLowerCase();- return normalized.length > 0 ? normalized : undefined;-};-export const resourcePlatformData = (resource: Resource): Record<string, unknown> | undefined =>asRecord(resource.platformData);@@ -167,6 +161,21 @@ const mergeAgentFacet = <T extends JsonRecord>(incoming?: T, existing?: T): T |return next;};+// Source status is per-source evidence the realtime payload never carries, so+// it survives merges as REST enrichment. Entries of sources the merged row no+// longer lists are stale: they would keep a split-off provider claiming the row.+const pruneSourceStatus = (+ value: unknown,+ sources: string[] | undefined,+): JsonRecord | undefined => {+ const status = asRecord(value);+ if (!status || !sources || sources.length === 0) return status;+ const entries = Object.entries(status);+ const kept = entries.filter(([source]) => sourceListHas(sources, source));+ if (kept.length === entries.length) return status;+ return kept.length > 0 ? Object.fromEntries(kept) : undefined;+};+const mergePlatformData = (incomingValue: Resource['platformData'],existingValue: Resource['platformData'],@@ -229,12 +238,14 @@ const mergePlatformData = (}}- const sourceStatus = mergeRecord(- asRecord(incoming.sourceStatus),- asRecord(existing.sourceStatus),+ const sourceStatus = pruneSourceStatus(+ mergeRecord(asRecord(incoming.sourceStatus), asRecord(existing.sourceStatus)),+ sources,);if (sourceStatus) {merged.sourceStatus = sourceStatus;+ } else {+ delete merged.sourceStatus;}if (sources) {@@ -568,261 +579,6 @@ const getCanonicalSourceList = (: deriveLegacySourceList(resource, platformData);};-const sourceListContainsRuntimePlatform = (sources: string[] | undefined): boolean =>- sourceListHas(sources, 'proxmox-pve', 'docker', 'kubernetes', 'vmware-vsphere', 'truenas');--const getRealtimeAgentFacet = (resource: Resource): JsonRecord | undefined =>- asRecord(resource.agent) ?? asRecord(asRecord(resource.platformData)?.agent);--const getRealtimeProxmoxFacet = (resource: Resource): JsonRecord | undefined =>- asRecord(resource.proxmox) ?? asRecord(asRecord(resource.platformData)?.proxmox);--const getRealtimeHostIdentity = (resource: Resource): JsonRecord | undefined =>- asRecord(resource.identity);--const getRealtimeHostnameCandidates = (resource: Resource): Array<string | undefined> => {- const platform = asRecord(resource.platformData);- const identity = getRealtimeHostIdentity(resource);- const identityHostnames = readStringArray(identity?.hostnames) ?? [];- return [- resource.canonicalIdentity?.platformId,- resource.canonicalIdentity?.hostname,- resource.platformId,- ...identityHostnames,- asString(identity?.hostname),- asString(getRealtimeAgentFacet(resource)?.hostname),- asString(getRealtimeProxmoxFacet(resource)?.nodeName),- asString(asRecord(platform?.agent)?.hostname),- asString(asRecord(platform?.proxmox)?.nodeName),- getPreferredResourceHostname(resource),- getPreferredInfrastructureDisplayName(resource),- resource.displayName,- resource.name,- ];-};--const getHostResourceMergeKey = (resource: Resource): string | undefined => {- if (resource.type !== 'agent') return undefined;- const hostKey = getRealtimeHostnameCandidates(resource)- .map(normalizeResourceIdentityToken)- .find(Boolean);- return hostKey ? `agent:${hostKey}` : undefined;-};--const realtimeIdentityValuesEqual = (left: unknown, right: unknown): boolean => {- const leftValue = asString(left)?.toLowerCase();- const rightValue = asString(right)?.toLowerCase();- return Boolean(leftValue && rightValue && leftValue === rightValue);-};--const realtimeIdentityValuesConflict = (left: unknown, right: unknown): boolean => {- const leftValue = asString(left)?.toLowerCase();- const rightValue = asString(right)?.toLowerCase();- return Boolean(leftValue && rightValue && leftValue !== rightValue);-};--const extractRealtimeEndpointHostname = (value: unknown): string | undefined => {- const raw = asString(value);- if (!raw) return undefined;- try {- const parsed = asString(new URL(raw).hostname)?.toLowerCase();- if (parsed) return parsed;- } catch {- // Fall through to the host[:port][/path] compatibility form below.- }- return asString(raw.split('/', 1)[0]?.split(':', 1)[0])?.toLowerCase();-};--// Two hand-added standalone Proxmox sites can legitimately expose the same-// native short node name. Instance, immutable node identity, and endpoint are-// provider-scope evidence; the browser must preserve the server's split when-// those scopes differ (#1753).-const realtimeProxmoxNodeScopesDistinct = (- left: JsonRecord | undefined,- right: JsonRecord | undefined,-): boolean => {- if (!left || !right || !asString(left.nodeName) || !asString(right.nodeName)) return false;- if (!realtimeIdentityValuesConflict(left.instance, right.instance)) return false;- if (realtimeIdentityValuesEqual(left.nodeIdentity, right.nodeIdentity)) return false;- if (- realtimeIdentityValuesEqual(- extractRealtimeEndpointHostname(left.host),- extractRealtimeEndpointHostname(right.host),- )- ) {- return false;- }- return true;-};--const getRealtimeMachineIds = (resource: Resource): string[] => {- const identity = getRealtimeHostIdentity(resource);- const agent = getRealtimeAgentFacet(resource);- return [asString(identity?.machineId), asString(agent?.machineId)].filter(- (value): value is string => Boolean(value),- );-};--const realtimeMachineIdsOverlap = (left: string[], right: string[]): boolean =>- left.some((leftId) => right.some((rightId) => leftId.toLowerCase() === rightId.toLowerCase()));--const realtimeHostIdentitiesDistinct = (left: Resource, right: Resource): boolean => {- const leftMachineIds = getRealtimeMachineIds(left);- const rightMachineIds = getRealtimeMachineIds(right);- if (- leftMachineIds.length > 0 &&- rightMachineIds.length > 0 &&- !realtimeMachineIdsOverlap(leftMachineIds, rightMachineIds)- ) {- return true;- }-- if (- realtimeIdentityValuesConflict(- getRealtimeHostIdentity(left)?.dmiUuid,- getRealtimeHostIdentity(right)?.dmiUuid,- )- ) {- return true;- }-- const leftProxmox = getRealtimeProxmoxFacet(left);- const rightProxmox = getRealtimeProxmoxFacet(right);- if (realtimeIdentityValuesConflict(leftProxmox?.clusterName, rightProxmox?.clusterName)) {- return true;- }- return realtimeProxmoxNodeScopesDistinct(leftProxmox, rightProxmox);-};--const getAmbiguousRealtimeProxmoxHostKeys = (resources: Resource[]): Set<string> => {- const facetsByHostKey = new Map<string, JsonRecord[]>();- const ambiguous = new Set<string>();- for (const resource of resources) {- const facet = getRealtimeProxmoxFacet(resource);- const hostKey = getHostResourceMergeKey(resource);- if (!facet || !asString(facet.nodeName) || !hostKey || ambiguous.has(hostKey)) continue;- const existingFacets = facetsByHostKey.get(hostKey) ?? [];- if (existingFacets.some((existing) => realtimeProxmoxNodeScopesDistinct(existing, facet))) {- ambiguous.add(hostKey);- }- existingFacets.push(facet);- facetsByHostKey.set(hostKey, existingFacets);- }- return ambiguous;-};--const realtimeGuardedMergeAllowed = (left: Resource, right: Resource): boolean => {- const leftProxmox = getRealtimeProxmoxFacet(left);- const rightProxmox = getRealtimeProxmoxFacet(right);- const leftIsNode = Boolean(asString(leftProxmox?.nodeName));- const rightIsNode = Boolean(asString(rightProxmox?.nodeName));- if (leftIsNode === rightIsNode) return true;-- const node = leftIsNode ? left : right;- const agent = leftIsNode ? right : left;- const nodeProxmox = getRealtimeProxmoxFacet(node);- const nodePlatform = asRecord(node.platformData);- const linkedAgentId =- asString(nodeProxmox?.linkedAgentId) ??- asString(nodePlatform?.linkedAgentId) ??- asString(getRealtimeAgentFacet(node)?.agentId);- return realtimeIdentityValuesEqual(linkedAgentId, getRealtimeAgentFacet(agent)?.agentId);-};--const shouldMergeRealtimeHostResources = (incoming: Resource, existing: Resource): boolean => {- if (incoming.type !== 'agent' || existing.type !== 'agent') return false;- const incomingSources = getCanonicalSourceList(incoming, incoming.platformData);- const existingSources = getCanonicalSourceList(existing, existing.platformData);- const unionSources = mergeStringArrays(incomingSources, existingSources);- return sourceListHas(unionSources, 'agent') && sourceListContainsRuntimePlatform(unionSources);-};--const preferHostResourcePrimary = (candidate: Resource, other: Resource): boolean => {- const candidateSources = getCanonicalSourceList(candidate, candidate.platformData);- const otherSources = getCanonicalSourceList(other, other.platformData);- if (sourceListHas(candidateSources, 'agent') && !sourceListHas(otherSources, 'agent')) {- return true;- }- if (!sourceListHas(candidateSources, 'agent') && sourceListHas(otherSources, 'agent')) {- return false;- }- return candidate.lastSeen >= other.lastSeen;-};--const withMergedSnapshotSources = (resource: Resource, sources: string[] | undefined): Resource => {- if (!sources || sources.length === 0) return resource;- const platform = asRecord(resource.platformData);- return canonicalizeRealtimeResource({- ...resource,- sources,- platformData: {- ...(platform ?? {}),- sources,- },- });-};--const mergeRealtimeHostResources = (incoming: Resource, existing: Resource): Resource => {- const unionSources = mergeStringArrays(- getCanonicalSourceList(incoming, incoming.platformData),- getCanonicalSourceList(existing, existing.platformData),- );- const primary = preferHostResourcePrimary(incoming, existing) ? incoming : existing;- const secondary = primary === incoming ? existing : incoming;- return canonicalizeRealtimeResource(- mergeCanonicalResource(- withMergedSnapshotSources(primary, unionSources),- withMergedSnapshotSources(secondary, unionSources),- ),- );-};--const coalesceCanonicalRealtimeResourceSnapshot = (resources: Resource[]): Resource[] => {- const coalesced: Resource[] = [];- const indexesByHostKey = new Map<string, number[]>();- const ambiguousProxmoxHostKeys = getAmbiguousRealtimeProxmoxHostKeys(resources);-- for (const resource of resources) {- const hostKey = getHostResourceMergeKey(resource);- if (!hostKey) {- coalesced.push(resource);- continue;- }-- let merged = false;- for (const existingIndex of indexesByHostKey.get(hostKey) ?? []) {- const existing = coalesced[existingIndex];- if (realtimeHostIdentitiesDistinct(resource, existing)) continue;- if (- ambiguousProxmoxHostKeys.has(hostKey) &&- !realtimeGuardedMergeAllowed(resource, existing)- ) {- continue;- }- if (!shouldMergeRealtimeHostResources(resource, existing)) continue;- coalesced[existingIndex] = mergeRealtimeHostResources(resource, existing);- merged = true;- break;- }-- if (!merged) {- const indexes = indexesByHostKey.get(hostKey) ?? [];- indexes.push(coalesced.length);- indexesByHostKey.set(hostKey, indexes);- coalesced.push(resource);- }- }-- return coalesced;-};--const coalesceRealtimeResourceSnapshot = (resources: Resource[]): Resource[] =>- coalesceCanonicalRealtimeResourceSnapshot(- resources.map((resource) =>- canonicalizeRealtimeResource(resource, { synthesizePlatformScopes: false }),- ),- );-const hasAvailabilityFacet = (resource: Resource,platformData?: Resource['platformData'],@@ -928,13 +684,160 @@ const hasWithdrawnProxmoxMemory = (incoming: Resource): boolean =>incoming.memory == null &&asBoolean(asRecord(asRecord(incoming.proxmox)?.memory)?.usageUnavailable) === true;+// The source list a row carries itself: top-level on realtime rows, in+// platformData on REST rows. Never one inferred from the facets present.+const getOwnSourceList = (resource: Resource): string[] | undefined =>+ getExplicitResourceSources(resource) ?? readStringArray(asRecord(resource.platformData)?.sources);++// Every source a display row claims through a list it carries itself: the+// top-level `sources` of a realtime row and the `platformData.sources` of a REST+// row. A row whose two lists disagree (an enrichment from another generation+// landed on it, or a shared array changed under it) claims both compositions.+const getClaimedSources = (resource: Resource): string[] | undefined =>+ mergeStringArrays(+ getExplicitResourceSources(resource),+ readStringArray(asRecord(resource.platformData)?.sources),+ );++// Sources the previous display row of an id listed that the incoming realtime+// row no longer does: a split took a provider away, or a module or check+// stopped reporting. Only the realtime row's own top-level list is evidence;+// one inferred from the facets a thin row happens to carry is not.+const getDepartedSources = (incoming: Resource, existing: Resource): string[] => {+ const incomingSources = getExplicitResourceSources(incoming);+ const existingSources = getClaimedSources(existing);+ if (!incomingSources || !existingSources) return [];+ return existingSources.filter((source) => !sourceListHas(incomingSources, source));+};++// Facets a platform scope can rest on besides a source of that name; the+// server derives scopes from sources, from facets, and from a Docker host+// running inside a Proxmox container (platform_scopes.go).+const SCOPE_FACET_KEYS: Record<string, string> = {+ 'proxmox-pve': 'proxmox',+ 'proxmox-pbs': 'pbs',+ 'proxmox-pmg': 'pmg',+ docker: 'docker',+ kubernetes: 'kubernetes',+ 'vmware-vsphere': 'vmware',+ truenas: 'truenas',+ agent: 'agent',+};++const PROXMOX_LXC_DOCKER_HOST_PREFIX = 'proxmox-lxc-docker:';++// Whether the incoming row still holds evidence for a platform scope that a+// departed source also names: a surviving source of that platform, a Docker+// host running in a Proxmox container (the server places it on the Proxmox+// scope by its host ID whatever sources the row lists, platform_scopes.go), or,+// on a row that is not a host, a facet of that platform (an agent-reported disk+// under a Proxmox node carries a Proxmox ownership facet and lists only the+// agent). A host row's facets are no evidence: canonicalization synthesizes+// them from flattened platform data (a node's kernel version reads as an agent+// facet), and the snapshot wrappers canonicalize before this runs.+const scopeStillSupported = (scope: string, incoming: Resource): boolean => {+ if (sourceListHas(getExplicitResourceSources(incoming), scope)) return true;+ const record = getResourceRecord(incoming);+ const platform = normalizeSourceToken(scope);+ const hostSourceId = asString(asRecord(record.docker)?.hostSourceId);+ if (platform === 'proxmox-pve' && hostSourceId?.startsWith(PROXMOX_LXC_DOCKER_HOST_PREFIX)) {+ return true;+ }+ const facetKey = SCOPE_FACET_KEYS[platform];+ return incoming.type !== 'agent' && Boolean(facetKey && asRecord(record[facetKey]));+};++// Discovery readiness names the discovery target it was read for: `targetId`+// is the target's reporter (`agentId`) and `resourceId` its resource. It stays+// with the row unless the rebuilt row has a target and a coordinate the+// readiness names differs from the same coordinate of that target. A rebuilt+// row without a target (realtime carries one only for agent and Docker host+// rows; the rest is REST enrichment) cannot be judged, so the readiness stays+// unless the agent left.+const keepDiscoveryReadiness = (+ readiness: Resource['discoveryReadiness'],+ replacement: Resource,+ agentLeft: boolean,+): Resource['discoveryReadiness'] => {+ if (!readiness) return undefined;+ const target = replacement.discoveryTarget;+ if (!target) return agentLeft ? undefined : readiness;+ if (readiness.targetId && readiness.targetId !== target.agentId) return undefined;+ if (readiness.resourceId && readiness.resourceId !== target.resourceId) return undefined;+ return readiness;+};++// A row whose sources shrank describes a different composition, and the+// per-id merge would keep what the previous row carried for the departed+// source wherever the incoming row omits it: flattened provider facts in+// platformData (from which the provider facet is rebuilt), cluster, identity+// fields, canonical aliases, metrics. The row is rebuilt from the incoming one.+// The REST-only enrichments the realtime payload never carries are kept where+// the departed sources did not own them: platform scopes, minus the departed+// sources' own that no surviving source, Docker LXC host or non-host facet supports, source status+// of the sources that remain, discovery readiness unless its target coordinates now differ+// from the row's, and action readiness unless the agent left. Everything else+// REST adds returns with the next REST refresh.+const replaceRecomposedResource = (+ incoming: Resource,+ existingCanonical: Resource,+ departedSources: string[],+): Resource => {+ const replacement = canonicalizeRealtimeResource(incoming);+ const keptScopes =+ readExplicitPlatformScopes(incoming) === undefined+ ? existingCanonical.platformScopes?.filter(+ (scope) => !sourceListHas(departedSources, scope) || scopeStillSupported(scope, incoming),+ )+ : undefined;+ const survivingSources = getOwnSourceList(replacement);+ const keepStatus = (own: unknown, previous: unknown): JsonRecord | undefined =>+ pruneSourceStatus(mergeRecord(asRecord(own), asRecord(previous)), survivingSources);+ const sourceStatus = keepStatus(+ (replacement as unknown as JsonRecord).sourceStatus,+ existingCanonical.sourceStatus,+ );+ const platformData = asRecord(replacement.platformData);+ const platformStatus = keepStatus(+ platformData?.sourceStatus,+ asRecord(existingCanonical.platformData)?.sourceStatus,+ );+ const agentLeft = sourceListHas(departedSources, 'agent');+ const rebuilt: Resource = {+ ...replacement,+ platformScopes:+ keptScopes && keptScopes.length > 0+ ? normalizeSourcePlatformScopes(keptScopes, replacement.platformType)+ : replacement.platformScopes,+ discoveryReadiness:+ replacement.discoveryReadiness ??+ keepDiscoveryReadiness(existingCanonical.discoveryReadiness, replacement, agentLeft),+ actionReadiness:+ replacement.actionReadiness ?? (agentLeft ? undefined : existingCanonical.actionReadiness),+ };+ if (sourceStatus) {+ rebuilt.sourceStatus = sourceStatus as Resource['sourceStatus'];+ } else {+ delete rebuilt.sourceStatus;+ }+ if (platformData) {+ const { sourceStatus: _inherited, ...rest } = platformData;+ rebuilt.platformData = platformStatus ? { ...rest, sourceStatus: platformStatus } : rest;+ }+ return rebuilt;+};+export const mergeCanonicalResource = (incoming: Resource, existing?: Resource): Resource => {if (!existing) {return canonicalizeRealtimeResource(incoming);}const existingCanonical = canonicalizeRealtimeResource(existing);+ const departedSources = getDepartedSources(incoming, existing);+ if (departedSources.length > 0) {+ return replaceRecomposedResource(incoming, existingCanonical, departedSources);+ }const incomingSources = getCanonicalSourceList(incoming, incoming.platformData);- return {+ const merged: Resource = {...existingCanonical,...incoming,...(hasWithdrawnProxmoxMemory(incoming) ? { memory: undefined } : {}),@@ -1031,8 +934,27 @@ export const mergeCanonicalResource = (incoming: Resource, existing?: Resource):? incoming.labels: existingCanonical.labels,};+ // Only a list a row carries itself prunes: one inferred from the facets a+ // thin row happens to carry is no evidence that a source left.+ const status = pruneSourceStatus(+ merged.sourceStatus,+ getOwnSourceList(incoming) ?? getOwnSourceList(existingCanonical),+ );+ if (status) {+ merged.sourceStatus = status as Resource['sourceStatus'];+ } else if (merged.sourceStatus !== undefined) {+ delete merged.sourceStatus;+ }+ return merged;};+// Every realtime snapshot (the websocket payload, its deltas, and the+// `/api/state` recovery) carries the server's presentation rows: the server+// already coalesced host views, honouring operator splits and provider scope+// the browser cannot see. Each incoming row is therefore one display row; the+// browser only canonicalizes it and merges it with the previous row of its id.+// Re-joining same-hostname host rows here undid server splits (#1753, and a+// node and agent the operator split apart).export const mergeCanonicalResourceSnapshot = (incoming: Resource[],existing: Resource[],@@ -1040,10 +962,12 @@ export const mergeCanonicalResourceSnapshot = (if (incoming.length === 0) {return [];}- const coalescedIncoming = coalesceRealtimeResourceSnapshot(incoming);const existingById = new Map(existing.map((resource) => [resource.id, resource] as const));- return coalescedIncoming.map((resource) =>- mergeCanonicalResource(resource, existingById.get(resource.id)),+ return incoming.map((resource) =>+ mergeCanonicalResource(+ canonicalizeRealtimeResource(resource, { synthesizePlatformScopes: false }),+ existingById.get(resource.id),+ ),);};@@ -1108,8 +1032,9 @@ export const getFastResourceMergePatchKeys = (existing: Resource | undefined,): readonly string[] | null => {if (!changedKeys || !existing) return null;- // Agent rows can join host-coalescing groups; their merged output is not a- // per-row function of the patch.+ // Agent rows keep the full merge. The exclusion dates from browser host+ // coalescing, which made an agent's output depend on its group; equivalence+ // with the full path has not been proven for agent rows since.if (existing.type === 'agent') return null;const keys = changedKeys.get(id);if (!keys || keys.length === 0) return null;@@ -1253,13 +1178,14 @@ export const buildFastResourceStorePatchOps = (};// Incremental counterpart to mergeCanonicalResourceSnapshot. Server delta-// application preserves the raw object identity of untouched resources, so-// only changed rows and the small host-coalescing set need to be cloned and-// canonicalized. Non-host resources outside the delta retain their exact display-// objects, preventing an estate-wide reactive invalidation on every metrics-// tick while keeping the full-snapshot compatibility semantics intact. Rows-// whose per-key change shape passes getFastResourceMergePatchKeys skip the-// clone+canonicalize+merge entirely and patch the previous display row.+// application preserves the raw object identity of untouched resources, and+// each server row is one display row (the server coalesces host views), so+// only changed and newly added rows need to be cloned and canonicalized.+// Resources outside the delta retain their exact display objects, preventing+// an estate-wide reactive invalidation on every metrics tick while producing+// the same rows as the full-snapshot path. Rows whose per-key change shape+// passes getFastResourceMergePatchKeys skip the clone+canonicalize+merge+// entirely and patch the previous display row.export const mergeCanonicalResourceDeltaSnapshot = (incoming: Resource[],existing: Resource[],@@ -1271,76 +1197,28 @@ export const mergeCanonicalResourceDeltaSnapshot = (}const existingById = new Map(existing.map((resource) => [resource.id, resource] as const));-- // 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');- // Fast-path outputs are already fully merged display rows; they must bypass- // the final mergeCanonicalResource pass.- const fastMergedRows = new Set<Resource>();- 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;- }- if (existingResource !== undefined) {- const fastKeys = getFastResourceMergePatchKeys(changedKeys, resource.id, existingResource);- if (fastKeys) {- const fastRow = applyFastResourceMergePatch(resource, existingResource, fastKeys);- fastMergedRows.add(fastRow);- return fastRow;- }- }- return canonicalizeRealtimeResource(structuredClone(resource), {- synthesizePlatformScopes: false,- });- })- .filter((resource): resource is Resource => resource !== SKIP);-- const coalesced = coalesceCanonicalRealtimeResourceSnapshot(prepared);- return coalesced.map((resource) => {+ return incoming.map((resource) => {const existingResource = existingById.get(resource.id);- if (resource === existingResource) {+ if (existingResource === undefined) {+ return mergeCanonicalResource(+ canonicalizeRealtimeResource(structuredClone(resource), {+ synthesizePlatformScopes: false,+ }),+ );+ }+ if (!changedIds.has(resource.id)) {return existingResource;}- if (fastMergedRows.has(resource)) {- return resource;+ const fastKeys = getFastResourceMergePatchKeys(changedKeys, resource.id, existingResource);+ if (fastKeys) {+ return applyFastResourceMergePatch(resource, existingResource, fastKeys);}- return mergeCanonicalResource(resource, existingResource);+ return mergeCanonicalResource(+ canonicalizeRealtimeResource(structuredClone(resource), {+ synthesizePlatformScopes: false,+ }),+ existingResource,+ );});};