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
Ship the infrastructure projection as per-client keyed deltas
rcourtmanf3d34346528f
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex fc83b56f8f..ede9eaeb9c 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -6770,6 +6770,14 @@ arrays at all for this surface; Connected infrastructure rowidentity, reporting-surface labels, and ignore/reconnect scope must be ownedby the backend payload contract, with frontend rendering limited topresentation and operator actions.+Over the state WebSocket that projection now travels the same per-client+keyed delta transport as resources: once a full payload establishes the+client's baseline, `connectedInfrastructureDelta` carries id-keyed JSON merge+patches plus removed ids and order instead of re-shipping the whole+projection on every broadcast. An entry that cannot key by id drops the+whole field back to plain whole-payload diffing, and a client without a+baseline ignores the delta and heals on the next full payload, so the keyed+path can never corrupt the projection.That same install-command payload continuity now also applies when auth isoptional: copied install and upgrade commands must omit token argumentsentirely on token-optional Pulse instances rather than serializing a fakediff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex 25f88230fb..4d9c241dbb 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -251,7 +251,13 @@ through the state-level `capabilityCatalog` and per-resource`capabilitiesRef`, default-posture policy and AI-safe prose are omitted andsynthesized at ingestion, and superseded canonical ids are not duplicatedinto the alias list, so full snapshots, REST recovery, and reconnects do not-re-ship static metadata per resource. Workload table rows derived from canonical+re-ship static metadata per resource. The connected-infrastructure reporting+projection rides the same per-client keyed delta engine: a broadcast carries+id-keyed merge patches for changed items only (at 50-node scale, timestamp+patches of a few hundred bytes instead of the full ~55KB projection every+tick), and the client applies them to an isolated baseline then reconciles+the store with reference-stable untouched items so the per-tick deep walk of+the whole projection is gone. Workload table rows derived from canonicalsnapshots reuse the previous row object whenever the serialized row isunchanged, and a refresh that changes nothing returns the previous row arrayitself, so per-tick row identity churn stays bounded to guests whose datadiff --git a/frontend-modern/browser-verification.json b/frontend-modern/browser-verification.jsonindex e8a18814bb..9465bf3681 100644--- a/frontend-modern/browser-verification.json+++ b/frontend-modern/browser-verification.json@@ -1,31 +1,40 @@{"version": 1,- "base_sha": "6ecdc81d1c0062d131a15ac0381dd20335f969a9",- "verified_at": "2026-08-26T17:00:35Z",+ "base_sha": "20503086ffc1eca6a4bb2121fe2c2ebd67160a0b",+ "verified_at": "2026-08-26T17:08:31Z","result": "passed",- "changed_paths": ["frontend-modern/src/features/docker/DockerContainersTable.tsx"],+ "changed_paths": [+ "frontend-modern/src/stores/websocket.ts"+ ],"content_sha256": {- "frontend-modern/src/features/docker/DockerContainersTable.tsx": "1874570ea11ff3c0a4e9e6de8028ca84629322c367ec2126e212b2b7eccd3b1f"+ "frontend-modern/src/stores/websocket.ts": "c648fbef42e36c2ae8502d258a6da2ab009f3d6bb9718e36192ba05085c3b760"},- "routes": ["/docker/overview"],+ "routes": [+ "/proxmox/overview",+ "/settings/infrastructure"+ ],"viewports": [{"width": 2560,- "height": 1063+ "height": 1240},{- "width": 768,- "height": 688+ "width": 700,+ "height": 900}],"states": [- "default multi-host grouped Docker inventory with an active nginx text search",- "expanded nginx container drawer with History selected and a non-default 1 hour range",- "desktop and half-width responsive layouts while live resource refreshes continued"+ "isolated test backend built from this change serving the 50-node/929-guest mock estate over the state websocket",+ "fresh socket connection: initialState ships the full connectedInfrastructure projection once to establish the client baseline",+ "steady realtime ticks carrying connectedInfrastructureDelta merge patches with zero full projection re-ships",+ "Connected systems settings surface rendering the delta-maintained projection with live per-item freshness",+ "narrow 700px viewport rendering the same projection surface"],"interactions": [- "searched for nginx in the default grouped multi-host view, expanded its drawer, selected History, and changed the range from 24 hours to 1 hour",- "observed multiple live refresh ticks on desktop and half-width layouts; the drawer remained expanded with History and 1 hour selected",- "verified the full resource-snapshot replacement path with the focused regression test, which fails without the grouped key extractor and passes with it"+ "raw websocket capture: ticks carry connectedInfrastructureDelta at 0.7-4KB of id+lastSeen merge patches instead of the ~55-60KB full projection previously re-shipped every tick; the full array shipped exactly once at initialState",+ "client message counting over 30s: 3 delta ticks consumed, 0 full projection re-ships, 140 workload rows mounted, no console errors",+ "Connected systems surface observed live at /settings/infrastructure: 71 systems with per-item freshness reading 1-5s ago, values that now only travel as merge patches, updating across ticks",+ "unit-verified reference stability: untouched projection items keep their store identity across a delta sync, so reconcile no longer deep-walks the whole projection per tick",+ "narrow 700px emulated viewport rendered the projection surface with live freshness text"]}diff --git a/frontend-modern/src/stores/__tests__/websocket-unified.test.ts b/frontend-modern/src/stores/__tests__/websocket-unified.test.tsindex 94a73d7a44..63d2b970ff 100644--- a/frontend-modern/src/stores/__tests__/websocket-unified.test.ts+++ b/frontend-modern/src/stores/__tests__/websocket-unified.test.ts@@ -1017,6 +1017,122 @@ describe('websocket store unified resource contract', () => {}});+ it('applies infrastructure merge-patch deltas touching only changed items', async () => {+ const { store, dispose } = await createStoreHarness();+ try {+ await waitForOpenTick();+ emitMessage({+ type: 'initialState',+ data: {+ connectedInfrastructure: [+ { id: 'infra-1', name: 'host-1', status: 'online', lastSeen: 100 },+ { id: 'infra-2', name: 'host-2', status: 'online', lastSeen: 100 },+ ],+ resources: [],+ lastUpdate: 100,+ activeAlerts: [],+ recentlyResolved: [],+ },+ });+ const { unwrap } = await import('solid-js/store');+ const untouchedBefore = unwrap(store.state.connectedInfrastructure)[1];++ emitMessage({+ type: 'rawData',+ data: {+ lastUpdate: 200,+ connectedInfrastructureDelta: { upserts: [{ id: 'infra-1', lastSeen: 200 }] },+ },+ });++ expect(store.state.connectedInfrastructure[0]?.lastSeen).toBe(200);+ expect(store.state.connectedInfrastructure[0]?.name).toBe('host-1');+ // The untouched item keeps its store identity: the sync hands reconcile+ // reference-equal objects so it never deep-walks the rest.+ expect(unwrap(store.state.connectedInfrastructure)[1]).toBe(untouchedBefore);++ // Removal and reorder ride the same keyed payload.+ emitMessage({+ type: 'rawData',+ data: {+ lastUpdate: 300,+ connectedInfrastructureDelta: {+ upserts: [{ id: 'infra-3', name: 'host-3', status: 'online', lastSeen: 300 }],+ removed: ['infra-1'],+ order: ['infra-3', 'infra-2'],+ },+ },+ });+ expect(store.state.connectedInfrastructure.map((item) => item.id)).toEqual([+ 'infra-3',+ 'infra-2',+ ]);+ } finally {+ dispose();+ }+ });++ it('ignores infrastructure deltas that arrive without a projection baseline', async () => {+ const { store, dispose } = await createStoreHarness();+ try {+ await waitForOpenTick();+ // No full payload has delivered connectedInfrastructure on this socket.+ emitMessage({+ type: 'rawData',+ data: {+ lastUpdate: 200,+ connectedInfrastructureDelta: { upserts: [{ id: 'infra-1', lastSeen: 200 }] },+ },+ });+ expect(store.state.connectedInfrastructure).toEqual([]);+ } finally {+ dispose();+ }+ });++ it('defers infrastructure deltas during operator input and coalesces them at idle', async () => {+ const { store, dispose } = await createStoreHarness();+ try {+ await waitForOpenTick();+ emitMessage({+ type: 'initialState',+ data: {+ connectedInfrastructure: [+ { id: 'infra-1', name: 'host-1', status: 'online', lastSeen: 100 },+ ],+ resources: [],+ lastUpdate: 100,+ activeAlerts: [],+ recentlyResolved: [],+ },+ });++ window.dispatchEvent(new Event('scroll'));+ emitMessage({+ type: 'rawData',+ data: {+ lastUpdate: 200,+ connectedInfrastructureDelta: { upserts: [{ id: 'infra-1', lastSeen: 200 }] },+ },+ });+ vi.advanceTimersByTime(200);+ window.dispatchEvent(new Event('scroll'));+ emitMessage({+ type: 'rawData',+ data: {+ lastUpdate: 300,+ connectedInfrastructureDelta: { upserts: [{ id: 'infra-1', lastSeen: 300 }] },+ },+ });+ expect(store.state.connectedInfrastructure[0]?.lastSeen).toBe(100);++ vi.advanceTimersByTime(800);+ expect(store.state.connectedInfrastructure[0]?.lastSeen).toBe(300);+ } finally {+ dispose();+ }+ });+it('drops scroll-queued deltas when a full snapshot supersedes their baseline', async () => {const { store, dispose } = await createStoreHarness();try {diff --git a/frontend-modern/src/stores/websocket.ts b/frontend-modern/src/stores/websocket.tsindex 778224edf2..465fb9173e 100644--- a/frontend-modern/src/stores/websocket.ts+++ b/frontend-modern/src/stores/websocket.ts@@ -1,5 +1,5 @@import { createSignal, onCleanup, batch } from 'solid-js';-import { createStore, produce, reconcile } from 'solid-js/store';+import { createStore, produce, reconcile, unwrap } from 'solid-js/store';import type {State,WSMessage,@@ -118,11 +118,13 @@ const collectResourcePatchKeys = (patch: Record<string, unknown>): readonly strireturn keys;};-const applyResourceStateDelta = (- current: readonly Resource[],- delta: { upserts?: unknown; removed?: unknown; order?: unknown },+type KeyedStateDelta = { upserts?: unknown; removed?: unknown; order?: unknown };++const applyKeyedStateDelta = <T extends { id: string }>(+ current: readonly T[],+ delta: KeyedStateDelta,): {- resources: Resource[];+ entries: T[];changedIds: Set<string>;changedKeys: Map<string, readonly string[] | null>;} => {@@ -151,7 +153,7 @@ const applyResourceStateDelta = (} else {changedKeys.set(id, collectResourcePatchKeys(patchRecord));}- const next = applyJSONMergePatch(resourcesById.get(id), patch) as Resource;+ const next = applyJSONMergePatch(resourcesById.get(id), patch) as T;if (next.id === id) resourcesById.set(id, next);});}@@ -165,12 +167,28 @@ const applyResourceStateDelta = (];const ordered = order.map((id) => resourcesById.get(id))- .filter((resource): resource is Resource => Boolean(resource));+ .filter((resource): resource is T => Boolean(resource));const included = new Set(ordered.map((resource) => resource.id));resourcesById.forEach((resource, id) => {if (!included.has(id)) ordered.push(resource);});- return { resources: ordered, changedIds, changedKeys };+ return { entries: ordered, changedIds, changedKeys };+};++const applyResourceStateDelta = (+ current: readonly Resource[],+ delta: KeyedStateDelta,+): {+ resources: Resource[];+ changedIds: Set<string>;+ changedKeys: Map<string, readonly string[] | null>;+} => {+ const applied = applyKeyedStateDelta(current, delta);+ return {+ resources: applied.entries,+ changedIds: applied.changedIds,+ changedKeys: applied.changedKeys,+ };};const parseTimestampMs = (value: unknown): number | null => {@@ -438,10 +456,14 @@ export function createWebSocketStore(url: string) {const DEFERRED_FLUSH_RECHECK_MS = 300;const deferredResourceDeltaQueue: { upserts?: unknown; removed?: unknown; order?: unknown }[] =[];- // The reporting projection is a whole-array replace, so mid-gesture ticks- // keep only the latest payload instead of a queue; reconciling it deep-walks- // every entry and is the other main-thread cost a tick pays.- let deferredConnectedInfrastructure: ConnectedInfrastructureItem[] | null = null;+ // The reporting projection arrives as per-item merge patches keyed like+ // resources. The raw baseline mirrors the server's per-client snapshot and+ // stays isolated from the store; the pending set records which items the+ // store has not reconciled yet, so a sync touches only changed items and a+ // tick never deep-walks the whole projection again.+ let rawConnectedInfrastructure: ConnectedInfrastructureItem[] | null = null;+ const pendingInfrastructureIds = new Set<string>();+ let pendingInfrastructureFull = false;// lastUpdate is the realtime tick token every downstream consumer keys on// (unified resource projections, workload remaps). It defers with the rest// so a mid-interaction tick triggers no derived recomputation at all.@@ -544,7 +566,9 @@ export function createWebSocketStore(url: string) {deferredResourceIds.clear();deferredResourceKeys.clear();deferredResourceDeltaQueue.length = 0;- deferredConnectedInfrastructure = null;+ rawConnectedInfrastructure = null;+ pendingInfrastructureIds.clear();+ pendingInfrastructureFull = false;deferredLastUpdate = null;lastFullStateRecoveryAt = 0;oversizedSnapshotObserved = false;@@ -708,9 +732,35 @@ export function createWebSocketStore(url: string) {}};+ // Reconcile the projection store from the raw baseline, touching only items+ // whose ids are pending. Untouched items keep their current store references+ // so reconcile's per-item identity check skips them outright; changed items+ // are cloned so the store never adopts baseline-owned objects.+ const syncInfrastructureStore = () => {+ const baseline = rawConnectedInfrastructure;+ if (baseline === null) return;+ if (pendingInfrastructureFull) {+ pendingInfrastructureFull = false;+ pendingInfrastructureIds.clear();+ setState('connectedInfrastructure', reconcile(structuredClone(baseline), { key: 'id' }));+ return;+ }+ if (pendingInfrastructureIds.size === 0) return;+ const changed = new Set(pendingInfrastructureIds);+ pendingInfrastructureIds.clear();+ const currentItems = unwrap(state.connectedInfrastructure) as ConnectedInfrastructureItem[];+ const currentById = new Map(currentItems.map((item) => [item.id, item] as const));+ const next = baseline.map((item) => {+ if (!changed.has(item.id)) {+ const existing = currentById.get(item.id);+ if (existing) return existing;+ }+ return structuredClone(item);+ });+ setState('connectedInfrastructure', reconcile(next, { key: 'id' }));+ };+const flushDeferredResources = () => {- const pendingInfrastructure = deferredConnectedInfrastructure;- deferredConnectedInfrastructure = null;const pendingLastUpdate = deferredLastUpdate;deferredLastUpdate = null;if (rawServerResources !== null) {@@ -732,13 +782,14 @@ export function createWebSocketStore(url: string) {commitDeferredMerge = () =>commitResources(nextResources, changedResourceIds, changedResourceKeys);}- if (!commitDeferredMerge && !pendingInfrastructure && pendingLastUpdate === null) {+ const hasInfrastructureFlush =+ rawConnectedInfrastructure !== null &&+ (pendingInfrastructureFull || pendingInfrastructureIds.size > 0);+ if (!commitDeferredMerge && !hasInfrastructureFlush && pendingLastUpdate === null) {return;}batch(() => {- if (pendingInfrastructure) {- setState('connectedInfrastructure', reconcile(pendingInfrastructure, { key: 'id' }));- }+ syncInfrastructureStore();commitDeferredMerge?.();if (pendingLastUpdate !== null) {setState('lastUpdate', pendingLastUpdate);@@ -753,7 +804,8 @@ export function createWebSocketStore(url: string) {if (deferredResourceIds.size === 0 &&deferredResourceDeltaQueue.length === 0 &&- deferredConnectedInfrastructure === null &&+ !pendingInfrastructureFull &&+ pendingInfrastructureIds.size === 0 &&deferredLastUpdate === null) {return;@@ -936,21 +988,45 @@ export function createWebSocketStore(url: string) {const connectedInfrastructure = Array.isArray(message.data.connectedInfrastructure)? (message.data.connectedInfrastructure as ConnectedInfrastructureItem[]): [];+ // A full payload re-establishes the projection baseline the way+ // a full resource snapshot re-establishes rawServerResources.+ rawConnectedInfrastructure = structuredClone(connectedInfrastructure);+ pendingInfrastructureIds.clear();+ pendingInfrastructureFull = true;if (typeof document !== 'undefined' &&document.visibilityState !== 'hidden' &&isOperatorInputActive()) {- // Latest-wins: a newer payload simply replaces the pending one.- deferredConnectedInfrastructure = connectedInfrastructure;scheduleDeferredResourceFlush();} else {- deferredConnectedInfrastructure = null;- setState(- 'connectedInfrastructure',- reconcile(connectedInfrastructure, { key: 'id' }),+ syncInfrastructureStore();+ }+ } else if (+ 'connectedInfrastructureDelta' in message.data &&+ message.data.connectedInfrastructureDelta !== undefined+ ) {+ if (rawConnectedInfrastructure !== null) {+ const appliedInfrastructure = applyKeyedStateDelta(+ rawConnectedInfrastructure,+ message.data.connectedInfrastructureDelta as KeyedStateDelta,);+ rawConnectedInfrastructure = appliedInfrastructure.entries;+ appliedInfrastructure.changedIds.forEach((id) => {+ pendingInfrastructureIds.add(id);+ });+ if (+ typeof document !== 'undefined' &&+ document.visibilityState !== 'hidden' &&+ isOperatorInputActive()+ ) {+ scheduleDeferredResourceFlush();+ } else {+ syncInfrastructureStore();+ }}+ // No baseline: leave the current projection; the next full+ // payload (reconnect or snapshot) re-establishes it.}if (message.data.metrics !== undefined) setState('metrics', message.data.metrics);if (message.data.performance !== undefined)diff --git a/internal/websocket/state_delta.go b/internal/websocket/state_delta.goindex 9c863a3fbe..2e73506d6f 100644--- a/internal/websocket/state_delta.go+++ b/internal/websocket/state_delta.go@@ -9,11 +9,22 @@ import ()const resourceDeltaField = "resourceDelta"+const infrastructureField = "connectedInfrastructure"+const infrastructureDeltaField = "connectedInfrastructureDelta"type clientStateSnapshot struct {fields map[string]json.RawMessageresources map[string]json.RawMessageresourceOrder []string+ // The connected-infrastructure projection is keyed the same way as+ // resources so per-item merge patches replace re-shipping the whole+ // projection on every broadcast. When the payload cannot be keyed (an+ // entry without an id), it stays in fields and diffs whole, so the+ // keyed path can never corrupt the projection.+ infrastructure map[string]json.RawMessage+ infrastructureOrder []string+ infrastructureRaw json.RawMessage+ infrastructureKeyed bool}type resourceDeltaPayload struct {@@ -22,6 +33,35 @@ type resourceDeltaPayload struct {Order []string `json:"order,omitempty"`}+func extractKeyedEntries(+ encoded json.RawMessage,+ field string,+) (map[string]json.RawMessage, []string, error) {+ var entries []json.RawMessage+ if err := json.Unmarshal(encoded, &entries); err != nil {+ return nil, nil, fmt.Errorf("decode state %s: %w", field, err)+ }+ byID := make(map[string]json.RawMessage)+ order := make([]string, 0, len(entries))+ for _, entry := range entries {+ var identity struct {+ ID string `json:"id"`+ }+ if err := json.Unmarshal(entry, &identity); err != nil {+ return nil, nil, fmt.Errorf("decode state %s identity: %w", field, err)+ }+ if identity.ID == "" {+ return nil, nil, fmt.Errorf("state %s entry is missing id", field)+ }+ if _, exists := byID[identity.ID]; exists {+ return nil, nil, fmt.Errorf("state %s id %q is duplicated", field, identity.ID)+ }+ byID[identity.ID] = append(json.RawMessage(nil), entry...)+ order = append(order, identity.ID)+ }+ return byID, order, nil+}+func buildClientStateSnapshot(state interface{}) (*clientStateSnapshot, error) {encoded, err := json.Marshal(state)if err != nil {@@ -36,34 +76,72 @@ func buildClientStateSnapshot(state interface{}) (*clientStateSnapshot, error) {resources := make(map[string]json.RawMessage)resourceOrder := make([]string, 0)if encodedResources, ok := fields["resources"]; ok {- var entries []json.RawMessage- if err := json.Unmarshal(encodedResources, &entries); err != nil {- return nil, fmt.Errorf("decode state resources: %w", err)- }- for _, entry := range entries {- var identity struct {- ID string `json:"id"`- }- if err := json.Unmarshal(entry, &identity); err != nil {- return nil, fmt.Errorf("decode state resource identity: %w", err)- }- if identity.ID == "" {- return nil, fmt.Errorf("state resource is missing id")- }- if _, exists := resources[identity.ID]; exists {- return nil, fmt.Errorf("state resource id %q is duplicated", identity.ID)- }- resources[identity.ID] = append(json.RawMessage(nil), entry...)- resourceOrder = append(resourceOrder, identity.ID)+ resources, resourceOrder, err = extractKeyedEntries(encodedResources, "resource")+ if err != nil {+ return nil, err}delete(fields, "resources")}- return &clientStateSnapshot{+ snapshot := &clientStateSnapshot{fields: fields,resources: resources,resourceOrder: resourceOrder,- }, nil+ }++ if encodedInfrastructure, ok := fields[infrastructureField]; ok {+ infrastructure, infrastructureOrder, keyErr := extractKeyedEntries(+ encodedInfrastructure,+ infrastructureField,+ )+ if keyErr == nil {+ snapshot.infrastructure = infrastructure+ snapshot.infrastructureOrder = infrastructureOrder+ snapshot.infrastructureRaw = append(json.RawMessage(nil), encodedInfrastructure...)+ snapshot.infrastructureKeyed = true+ delete(fields, infrastructureField)+ }+ }++ return snapshot, nil+}++func buildKeyedArrayDelta(+ previousEntries, currentEntries map[string]json.RawMessage,+ previousOrder, currentOrder []string,+ label string,+) (resourceDeltaPayload, error) {+ payload := resourceDeltaPayload{}+ for _, id := range currentOrder {+ currentEntry := currentEntries[id]+ previousEntry, exists := previousEntries[id]+ if !exists {+ payload.Upserts = append(payload.Upserts, currentEntry)+ continue+ }+ if bytes.Equal(previousEntry, currentEntry) {+ continue+ }+ patch, err := createJSONMergePatch(previousEntry, currentEntry)+ if err != nil {+ return resourceDeltaPayload{}, fmt.Errorf("build %s %q patch: %w", label, id, err)+ }+ payload.Upserts = append(payload.Upserts, patch)+ }+ for id := range previousEntries {+ if _, exists := currentEntries[id]; !exists {+ payload.Removed = append(payload.Removed, id)+ }+ }+ sort.Strings(payload.Removed)+ if !reflect.DeepEqual(previousOrder, currentOrder) {+ payload.Order = append([]string(nil), currentOrder...)+ }+ return payload, nil+}++func (p resourceDeltaPayload) isEmpty() bool {+ return len(p.Upserts) == 0 && len(p.Removed) == 0 && len(p.Order) == 0}func buildClientStateDelta(previous, current *clientStateSnapshot) (map[string]interface{}, error) {@@ -83,35 +161,51 @@ func buildClientStateDelta(previous, current *clientStateSnapshot) (map[string]i}}- resourceDelta := resourceDeltaPayload{}- for _, id := range current.resourceOrder {- currentResource := current.resources[id]- previousResource, exists := previous.resources[id]- if !exists {- resourceDelta.Upserts = append(resourceDelta.Upserts, currentResource)- continue+ resourceDelta, err := buildKeyedArrayDelta(+ previous.resources,+ current.resources,+ previous.resourceOrder,+ current.resourceOrder,+ "resource",+ )+ if err != nil {+ return nil, err+ }+ if !resourceDelta.isEmpty() {+ delta[resourceDeltaField] = resourceDelta+ }++ switch {+ case previous.infrastructureKeyed && current.infrastructureKeyed:+ infrastructureDelta, err := buildKeyedArrayDelta(+ previous.infrastructure,+ current.infrastructure,+ previous.infrastructureOrder,+ current.infrastructureOrder,+ infrastructureField,+ )+ if err != nil {+ return nil, err}- if bytes.Equal(previousResource, currentResource) {- continue+ if !infrastructureDelta.isEmpty() {+ delta[infrastructureDeltaField] = infrastructureDelta}- patch, err := createJSONMergePatch(previousResource, currentResource)- if err != nil {- return nil, fmt.Errorf("build resource %q patch: %w", id, err)+ case current.infrastructureKeyed:+ // The previous snapshot carried the projection as a plain field (or+ // not at all): fall back to shipping the full array once so the+ // client re-adopts a clean baseline.+ if previousRaw, ok := previous.fields[infrastructureField]; !ok ||+ !bytes.Equal(previousRaw, current.infrastructureRaw) {+ delta[infrastructureField] = current.infrastructureRaw}- resourceDelta.Upserts = append(resourceDelta.Upserts, patch)- }- for id := range previous.resources {- if _, exists := current.resources[id]; !exists {- resourceDelta.Removed = append(resourceDelta.Removed, id)+ case previous.infrastructureKeyed:+ // The projection left the keyed path. If the current snapshot still+ // carries it as a plain field, the fields loop above already shipped+ // it whole; if it vanished entirely, clear it like any removed field.+ if _, ok := current.fields[infrastructureField]; !ok {+ delta[infrastructureField] = nil}}- sort.Strings(resourceDelta.Removed)- if !reflect.DeepEqual(previous.resourceOrder, current.resourceOrder) {- resourceDelta.Order = append([]string(nil), current.resourceOrder...)- }- if len(resourceDelta.Upserts) > 0 || len(resourceDelta.Removed) > 0 || len(resourceDelta.Order) > 0 {- delta[resourceDeltaField] = resourceDelta- }return delta, nil}diff --git a/internal/websocket/state_delta_test.go b/internal/websocket/state_delta_test.goindex dd31d41e03..d4040c1171 100644--- a/internal/websocket/state_delta_test.go+++ b/internal/websocket/state_delta_test.go@@ -93,6 +93,164 @@ func TestClientStateDeltaTracksResourceRemovalAndOrder(t *testing.T) {}}+func TestClientStateDeltaShipsInfrastructureAsKeyedPatches(t *testing.T) {+ previousState := models.EmptyStateFrontend()+ previousState.ConnectedInfrastructure = []models.ConnectedInfrastructureItemFrontend{+ {+ ID: "infra-1", Name: "host-1", Status: "online", LastSeen: 100,+ Surfaces: []models.ConnectedInfrastructureSurfaceFrontend{{+ ID: "surface-1", Kind: "agent", Label: strings.Repeat("s", 8*1024),+ }},+ },+ {ID: "infra-2", Name: "host-2", Status: "online", LastSeen: 100},+ }+ currentState := previousState+ currentState.ConnectedInfrastructure = append(+ []models.ConnectedInfrastructureItemFrontend(nil),+ previousState.ConnectedInfrastructure...,+ )+ currentState.ConnectedInfrastructure[0].LastSeen = 200++ previous, err := buildClientStateSnapshot(previousState)+ if err != nil {+ t.Fatal(err)+ }+ current, err := buildClientStateSnapshot(currentState)+ if err != nil {+ t.Fatal(err)+ }+ delta, err := buildClientStateDelta(previous, current)+ if err != nil {+ t.Fatal(err)+ }+ if _, ok := delta[infrastructureField]; ok {+ t.Fatal("state delta re-shipped the full connectedInfrastructure projection")+ }+ payload, ok := delta[infrastructureDeltaField].(resourceDeltaPayload)+ if !ok {+ t.Fatalf("infrastructure delta type = %T", delta[infrastructureDeltaField])+ }+ if len(payload.Upserts) != 1 {+ t.Fatalf("upserts = %d, want 1", len(payload.Upserts))+ }+ patch := string(payload.Upserts[0])+ if !strings.Contains(patch, `"id":"infra-1"`) || !strings.Contains(patch, `"lastSeen":200`) {+ t.Fatalf("patch = %s, want id + lastSeen", patch)+ }+ if strings.Contains(patch, strings.Repeat("s", 128)) {+ t.Fatal("patch re-shipped the unchanged surfaces payload")+ }+ if len(patch) >= 256 {+ t.Fatalf("patch = %d bytes, want a bounded timestamp patch", len(patch))+ }+}++func TestClientStateDeltaTracksInfrastructureRemovalAndOrder(t *testing.T) {+ previousState := models.EmptyStateFrontend()+ previousState.ConnectedInfrastructure = []models.ConnectedInfrastructureItemFrontend{+ {ID: "a", Name: "a", Status: "online"},+ {ID: "b", Name: "b", Status: "online"},+ }+ currentState := models.EmptyStateFrontend()+ currentState.ConnectedInfrastructure = []models.ConnectedInfrastructureItemFrontend{+ {ID: "c", Name: "c", Status: "online"},+ {ID: "a", Name: "a", Status: "online"},+ }++ previous, err := buildClientStateSnapshot(previousState)+ if err != nil {+ t.Fatal(err)+ }+ current, err := buildClientStateSnapshot(currentState)+ if err != nil {+ t.Fatal(err)+ }+ delta, err := buildClientStateDelta(previous, current)+ if err != nil {+ t.Fatal(err)+ }+ payload, ok := delta[infrastructureDeltaField].(resourceDeltaPayload)+ if !ok {+ t.Fatalf("infrastructure delta type = %T", delta[infrastructureDeltaField])+ }+ if len(payload.Removed) != 1 || payload.Removed[0] != "b" {+ t.Fatalf("removed = %#v, want [b]", payload.Removed)+ }+ if len(payload.Order) != 2 || payload.Order[0] != "c" || payload.Order[1] != "a" {+ t.Fatalf("order = %#v, want [c a]", payload.Order)+ }+ if len(payload.Upserts) != 1 || !strings.Contains(string(payload.Upserts[0]), `"id":"c"`) {+ t.Fatalf("upserts = %s, want full item c", payload.Upserts)+ }+}++func TestClientStateDeltaFallsBackToFullInfrastructureWhenUnkeyed(t *testing.T) {+ // An entry without an id cannot key: the projection must fall back to the+ // plain whole-field diff instead of corrupting the keyed path.+ previousState := models.EmptyStateFrontend()+ previousState.ConnectedInfrastructure = []models.ConnectedInfrastructureItemFrontend{+ {Name: "anonymous", Status: "online"},+ }+ currentState := models.EmptyStateFrontend()+ currentState.ConnectedInfrastructure = []models.ConnectedInfrastructureItemFrontend{+ {Name: "anonymous", Status: "offline"},+ }++ previous, err := buildClientStateSnapshot(previousState)+ if err != nil {+ t.Fatal(err)+ }+ if previous.infrastructureKeyed {+ t.Fatal("id-less projection must not key")+ }+ current, err := buildClientStateSnapshot(currentState)+ if err != nil {+ t.Fatal(err)+ }+ delta, err := buildClientStateDelta(previous, current)+ if err != nil {+ t.Fatal(err)+ }+ if _, ok := delta[infrastructureDeltaField]; ok {+ t.Fatal("unkeyed projection produced a keyed delta")+ }+ full, ok := delta[infrastructureField].(json.RawMessage)+ if !ok || !strings.Contains(string(full), `"offline"`) {+ t.Fatalf("full field = %v, want whole projection", delta[infrastructureField])+ }+}++func TestClientStateDeltaShipsFullInfrastructureWhenBaselineWasUnkeyed(t *testing.T) {+ previousState := models.EmptyStateFrontend()+ previousState.ConnectedInfrastructure = []models.ConnectedInfrastructureItemFrontend{+ {Name: "anonymous", Status: "online"},+ }+ currentState := models.EmptyStateFrontend()+ currentState.ConnectedInfrastructure = []models.ConnectedInfrastructureItemFrontend{+ {ID: "a", Name: "a", Status: "online"},+ }++ previous, err := buildClientStateSnapshot(previousState)+ if err != nil {+ t.Fatal(err)+ }+ current, err := buildClientStateSnapshot(currentState)+ if err != nil {+ t.Fatal(err)+ }+ delta, err := buildClientStateDelta(previous, current)+ if err != nil {+ t.Fatal(err)+ }+ if _, ok := delta[infrastructureDeltaField]; ok {+ t.Fatal("keyed delta emitted against an unkeyed baseline")+ }+ full, ok := delta[infrastructureField].(json.RawMessage)+ if !ok || !strings.Contains(string(full), `"id":"a"`) {+ t.Fatalf("full field = %v, want whole projection re-ship", delta[infrastructureField])+ }+}+func TestClientStateBaselineAdvancesOnlyAfterDeltaIsQueued(t *testing.T) {initial := models.EmptyStateFrontend()initial.LastUpdate = 100