Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

fix(websocket): recover state over REST when the snapshot exceeds the inbound guard

rcourtman75fcc9242462
diff --git a/frontend-modern/browser-verification.json b/frontend-modern/browser-verification.json
index 7fe0753f13..5beedfefe2 100644
--- a/frontend-modern/browser-verification.json
+++ b/frontend-modern/browser-verification.json
@@ -1,37 +1,21 @@
{
"version": 1,
- "base_sha": "06d8bfe65ebf3683a07d9ec7775a50a9872418ce",
- "verified_at": "2026-08-07T19:15:00Z",
"result": "passed",
+ "base_sha": "755a8887874e21d0115e1490b9e69e9501d2a31e",
+ "verified_at": "2026-08-07T19:21:05Z",
"changed_paths": [
- "frontend-modern/src/components/Settings/Settings.tsx",
- "frontend-modern/src/components/Settings/settingsNavCatalog.ts",
- "frontend-modern/src/components/Settings/useInfrastructureDiscoveryRuntimeState.ts",
- "frontend-modern/src/components/Settings/useInfrastructureSettingsState.ts",
- "frontend-modern/src/components/Settings/useSettingsAccess.ts",
- "frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts",
- "frontend-modern/src/components/Settings/useVMwareSettingsPanelState.ts",
- "frontend-modern/src/types/config.ts"
+ "frontend-modern/src/stores/websocket.ts"
],
"content_sha256": {
- "frontend-modern/src/components/Settings/Settings.tsx": "0e400e1896d2272364f298f721ff6f7a867900cd0e49fb5c7a64432928662f6b",
- "frontend-modern/src/components/Settings/settingsNavCatalog.ts": "534c501a82919927c7bfcbbffd26a0f822d362247d8339e7de54696bd9ab172a",
- "frontend-modern/src/components/Settings/useInfrastructureDiscoveryRuntimeState.ts": "d56324453d07a8ec7ce81f9a385251da456cae68c2b674d692c231f86b24498e",
- "frontend-modern/src/components/Settings/useInfrastructureSettingsState.ts": "406a7e7328017a501a085ce3e0754afb23d9927b4011fc4b976b5d79aa341a47",
- "frontend-modern/src/components/Settings/useSettingsAccess.ts": "8e7ff8c036632b474aa9e66ba388e1fa6a514d1cf85b15ff56a581fb6ab5a163",
- "frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts": "5e7ac8b1ba5b481323eb4d7e9751919ff2478840c85532452991649939732e80",
- "frontend-modern/src/components/Settings/useVMwareSettingsPanelState.ts": "cdaeb8a98deef07dee1069fd09ecd618360ba9058b197c297a8bd3ef7daddda0",
- "frontend-modern/src/types/config.ts": "b918901c67294b7dcf6b0243ba92fd7a741468a009ea0a927f7caedb602ce2f9"
+ "frontend-modern/src/stores/websocket.ts": "1a27dd2c374fc3fe09f718044e3685c450ff4fddfce2f0ada92ac5210676bbd9"
},
"routes": [
- "/settings/infrastructure (non-admin proxy-auth session: route blocked, falls back to the first reachable tab)",
- "/settings (non-admin: bare settings path resolves through the same blocked default tab)",
- "/settings/infrastructure (admin proxy-auth session: page renders and loads)"
+ "/infrastructure (Proxmox overview, nodes + workloads tables)"
],
"viewports": [
{
"width": 1280,
- "height": 800
+ "height": 720
},
{
"width": 375,
@@ -39,18 +23,14 @@
}
],
"states": [
- "authenticated non-admin proxy-auth session (X-Remote-Role=viewer) against a local backend on port 7855 fronted by a header-injecting shim; /api/security/status reports detailLevel=authenticated and settingsCapabilities.infrastructureRead=false",
- "admin proxy-auth session (X-Remote-Role=admin) on the same instance; detailLevel=privileged and infrastructureRead=true",
- "settings sidebar for the non-admin: the whole Infrastructure group is absent and the sidebar starts at Monitoring > Availability checks",
- "settings sidebar for the admin: Infrastructure group present and selected, discovery card shows 'Last scanned 0s ago' proving the gated load ran once the capability resolved",
- "empty-estate instance (0 connected systems) so the Infrastructure page renders its onboarding empty state rather than a populated table"
+ "inbound guard tripped: MAX_INBOUND_WEBSOCKET_MESSAGE_BYTES temporarily lowered to 256 KiB against a live backend on port 7655 whose real initialState frame is ~741 KB, reproducing the oversized-snapshot condition a >3100-resource estate hits at the shipped 8 MiB cap",
+ "post-recovery steady state: 265 resources hydrated from /api/state with 48 distinct resource types, then held across subsequent resourceDelta ticks (delta frames logged with resourceCount 0 while the store stayed at 265), proving the REST snapshot established a usable delta baseline",
+ "shipped 8 MiB cap restored: the same ~741 KB frame is accepted and hydrates via initialState over the socket with no oversized warning and no REST fetch, confirming the fallback is inert on normal estates"
],
"interactions": [
- "deep-linked a non-admin straight to /settings/infrastructure and confirmed the route redirected to Availability checks instead of ping-ponging back to the blocked default tab",
- "queried the rendered DOM for any /settings/infrastructure link or 'Infrastructure' text as the non-admin at both widths and found none",
- "measured the backend warn log over a 60s idle window on the non-admin settings page before and after the gate: /api/connections 4/min and /api/discover 2/min dropped to 0, with 0 denials on /api/config/nodes, /api/system/settings, /api/truenas/connections and /api/vmware/connections",
- "switched the shim to an admin role, reloaded /settings/infrastructure and confirmed the page renders, then instrumented window.fetch for 152s and observed /api/discover x4 (30s poller) and /api/connections x3 (15s ledger poller) with 0 denials",
- "repeated the non-admin deep link and the admin page load at 375x812 and confirmed the same outcomes on the mobile drill-down layout",
- "confirmed the footer still reads 'Pulse | Version: 4.26.0' for the non-admin throughout, since the version comes from the public /api/version rather than the admin-only update check"
+ "loaded /infrastructure with the guard tripped and read the console sequence: 'Ignoring oversized WebSocket payload {characterCount: 741468, maxBytes: 262144}' then 'Recovering full state over REST' then 'Hydrated full state over REST after an oversized WebSocket snapshot' then 'Updating resources {count: 265}'",
+ "confirmed the nodes table and workloads table rendered populated rows (6 PVE nodes with live CPU/memory/disk/temp, guest rows beneath) rather than the empty UI the dropped snapshot previously produced",
+ "re-ran the same oversized-recovery load at 375x812 and confirmed identical console recovery sequence plus a populated mobile nodes list and bottom nav counters",
+ "restored the 8 MiB constant, reloaded, and confirmed the console showed 'message {type: initialState, resourceCount: 265}' with no oversized warning and no /api/state recovery fetch"
]
}
diff --git a/frontend-modern/src/stores/__tests__/websocket-unified.test.ts b/frontend-modern/src/stores/__tests__/websocket-unified.test.ts
index 8eb5811e2e..9edb5a28fa 100644
--- a/frontend-modern/src/stores/__tests__/websocket-unified.test.ts
+++ b/frontend-modern/src/stores/__tests__/websocket-unified.test.ts
@@ -1,6 +1,18 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createRoot } from 'solid-js';
+// Mirrors MAX_INBOUND_WEBSOCKET_MESSAGE_BYTES in the store under test.
+const MAX_INBOUND_WEBSOCKET_MESSAGE_BYTES = 8 * 1024 * 1024;
+
+const apiFetchJSONMock = vi.fn();
+vi.mock('@/utils/apiClient', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/utils/apiClient')>();
+ return {
+ ...actual,
+ apiFetchJSON: (...args: unknown[]) => apiFetchJSONMock(...args),
+ };
+});
+
interface MockWebSocketInstance {
url: string;
readyState: number;
@@ -59,6 +71,35 @@ const emitMessage = (payload: unknown) => {
mockWsInstance.onmessage({ data: JSON.stringify(payload) } as MessageEvent);
};
+const emitRawMessage = (raw: string) => {
+ if (!mockWsInstance?.onmessage) {
+ throw new Error('WebSocket onmessage handler is not initialized');
+ }
+ mockWsInstance.onmessage({ data: raw } as MessageEvent);
+};
+
+// Builds a valid all-ASCII rawData frame of exactly `totalBytes`, so the inbound
+// size guard can be exercised right at its boundary without allocating a
+// realistic multi-thousand-resource estate.
+const frameOfExactly = (totalBytes: number): string => {
+ const prefix = '{"type":"rawData","data":{"lastUpdate":1,"pad":"';
+ const suffix = '"}}';
+ const fillerLength = totalBytes - prefix.length - suffix.length;
+ if (fillerLength < 0) throw new Error(`totalBytes ${totalBytes} is too small`);
+ return `${prefix}${'x'.repeat(fillerLength)}${suffix}`;
+};
+
+// The REST recovery path awaits a fetch, so the store settles over several
+// microtask turns rather than synchronously.
+const flushMicrotasks = async (turns = 6) => {
+ for (let i = 0; i < turns; i += 1) {
+ await Promise.resolve();
+ }
+};
+
+const sentMessageTypes = () =>
+ (mockWsInstance?.send.mock.calls ?? []).map((call) => JSON.parse(call[0] as string).type);
+
const createStoreHarness = async () => {
const { createWebSocketStore } = await import('@/stores/websocket');
let dispose = () => {};
@@ -75,6 +116,7 @@ describe('websocket store unified resource contract', () => {
vi.resetModules();
mockWsInstance = null;
MockWebSocket.mockClear();
+ apiFetchJSONMock.mockReset();
installWebSocketMock();
});
@@ -403,6 +445,174 @@ describe('websocket store unified resource contract', () => {
}
});
+ // Regression: on estates large enough that the full snapshot exceeds the
+ // inbound guard (~3100 resources at the ~2.7 KB/resource measured against a
+ // real /api/state payload; ~12.8 MB at 5000), the client dropped initialState
+ // and asked the server for another one over the same socket. That response is
+ // the same oversized frame, so it was dropped too and the UI never hydrated.
+ describe('oversized snapshot recovery', () => {
+ it('processes a frame sitting exactly on the inbound byte limit', async () => {
+ const { store, dispose } = await createStoreHarness();
+ try {
+ await waitForOpenTick();
+
+ emitRawMessage(frameOfExactly(MAX_INBOUND_WEBSOCKET_MESSAGE_BYTES));
+ await flushMicrotasks();
+
+ // Accepted and parsed: no recovery of any kind was triggered.
+ expect(apiFetchJSONMock).not.toHaveBeenCalled();
+ expect(sentMessageTypes()).not.toContain('requestData');
+ expect(store.state.lastUpdate).toBe(1);
+ } finally {
+ dispose();
+ }
+ });
+
+ it('hydrates over REST when the snapshot exceeds the inbound byte limit by one byte', async () => {
+ apiFetchJSONMock.mockResolvedValue({
+ lastUpdate: 500,
+ resources: [
+ { id: 'agent-host-1', type: 'agent', name: 'host-1', lastSeen: 100 },
+ { id: 'agent-host-2', type: 'agent', name: 'host-2', lastSeen: 100 },
+ ],
+ });
+
+ const { store, dispose } = await createStoreHarness();
+ try {
+ await waitForOpenTick();
+
+ emitRawMessage(frameOfExactly(MAX_INBOUND_WEBSOCKET_MESSAGE_BYTES + 1));
+ await flushMicrotasks();
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/state');
+ expect(store.state.resources).toHaveLength(2);
+ expect(store.state.resources.map((resource) => resource.id)).toEqual([
+ 'agent-host-1',
+ 'agent-host-2',
+ ]);
+ expect(store.initialDataReceived()).toBe(true);
+ } finally {
+ dispose();
+ }
+ });
+
+ it('establishes a delta baseline from the REST snapshot', async () => {
+ apiFetchJSONMock.mockResolvedValue({
+ lastUpdate: 500,
+ resources: [{ id: 'agent-host-1', type: 'agent', name: 'host-1', lastSeen: 100 }],
+ });
+
+ const { store, dispose } = await createStoreHarness();
+ try {
+ await waitForOpenTick();
+
+ emitRawMessage(frameOfExactly(MAX_INBOUND_WEBSOCKET_MESSAGE_BYTES + 1));
+ await flushMicrotasks();
+ expect(store.state.resources).toHaveLength(1);
+
+ // The REST payload must serve as the baseline the server's deltas are
+ // patched onto — otherwise recovery hydrates once and then stalls again.
+ emitMessage({
+ type: 'rawData',
+ data: {
+ lastUpdate: 600,
+ resourceDelta: {
+ upserts: [{ id: 'agent-host-1', lastSeen: 200 }],
+ },
+ },
+ });
+ await flushMicrotasks();
+
+ expect(store.state.resources).toHaveLength(1);
+ expect(store.state.resources[0]?.lastSeen).toBe(200);
+ expect(store.state.resources[0]?.name).toBe('host-1');
+ expect(sentMessageTypes()).not.toContain('requestData');
+ } finally {
+ dispose();
+ }
+ });
+
+ it('recovers immediately after a reconnect instead of inheriting the throttle', async () => {
+ apiFetchJSONMock.mockResolvedValue({
+ lastUpdate: 500,
+ resources: [{ id: 'agent-host-1', type: 'agent', name: 'host-1', lastSeen: 100 }],
+ });
+
+ const { store, dispose } = await createStoreHarness();
+ try {
+ await waitForOpenTick();
+
+ emitRawMessage(frameOfExactly(MAX_INBOUND_WEBSOCKET_MESSAGE_BYTES + 1));
+ await flushMicrotasks();
+ expect(apiFetchJSONMock).toHaveBeenCalledTimes(1);
+ expect(store.state.resources).toHaveLength(1);
+
+ // Drop the connection and let the reconnect timer fire.
+ mockWsInstance?.onclose?.({ code: 1011, reason: 'network blip' } as CloseEvent);
+ vi.advanceTimersByTime(5000);
+ await flushMicrotasks();
+ await waitForOpenTick();
+
+ // The fresh connection re-sends the same oversized snapshot. Recovery
+ // must not be suppressed by the previous connection's throttle window.
+ emitRawMessage(frameOfExactly(MAX_INBOUND_WEBSOCKET_MESSAGE_BYTES + 1));
+ await flushMicrotasks();
+
+ expect(apiFetchJSONMock).toHaveBeenCalledTimes(2);
+ expect(sentMessageTypes()).not.toContain('requestData');
+ expect(store.state.resources).toHaveLength(1);
+ } finally {
+ dispose();
+ }
+ });
+
+ it('never re-requests the snapshot over the socket once one was dropped', async () => {
+ apiFetchJSONMock.mockRejectedValue(new Error('state endpoint unavailable'));
+
+ const { store, dispose } = await createStoreHarness();
+ try {
+ await waitForOpenTick();
+
+ emitRawMessage(frameOfExactly(MAX_INBOUND_WEBSOCKET_MESSAGE_BYTES + 1));
+ await flushMicrotasks();
+ expect(apiFetchJSONMock).toHaveBeenCalledTimes(1);
+
+ // A baseline-less delta arrives while the estate is still unhydrated.
+ // The old behaviour asked the socket for another full snapshot, which
+ // the guard drops again — an endless 30s retry loop on an empty UI.
+ emitMessage({
+ type: 'rawData',
+ data: {
+ lastUpdate: 600,
+ resourceDelta: { upserts: [{ id: 'agent-host-1', lastSeen: 200 }] },
+ },
+ });
+ await flushMicrotasks();
+
+ expect(sentMessageTypes()).not.toContain('requestData');
+ expect(store.state.resources).toHaveLength(0);
+
+ // Recovery stays throttled rather than hammering the endpoint.
+ expect(apiFetchJSONMock).toHaveBeenCalledTimes(1);
+
+ vi.advanceTimersByTime(30001);
+ emitMessage({
+ type: 'rawData',
+ data: {
+ lastUpdate: 700,
+ resourceDelta: { upserts: [{ id: 'agent-host-1', lastSeen: 300 }] },
+ },
+ });
+ await flushMicrotasks();
+
+ expect(sentMessageTypes()).not.toContain('requestData');
+ expect(apiFetchJSONMock).toHaveBeenCalledTimes(2);
+ } finally {
+ dispose();
+ }
+ });
+ });
+
it('requests a full snapshot instead of applying a delta without a baseline', async () => {
const { store, dispose } = await createStoreHarness();
try {
diff --git a/frontend-modern/src/stores/websocket.ts b/frontend-modern/src/stores/websocket.ts
index 02f44f9d6c..04d223b31d 100644
--- a/frontend-modern/src/stores/websocket.ts
+++ b/frontend-modern/src/stores/websocket.ts
@@ -19,6 +19,7 @@ import {
isAppContainerDiscoveryResourceType,
} from '@/utils/discoveryTarget';
import { mergeCanonicalResourceSnapshot } from '@/utils/resourceStateAdapters';
+import { apiFetchJSON } from '@/utils/apiClient';
const MAX_INBOUND_WEBSOCKET_MESSAGE_BYTES = 8 * 1024 * 1024; // 8 MiB
const AUTO_REGISTER_NOTIFICATION_FRESH_MS = 2 * 60 * 1000;
@@ -310,7 +311,12 @@ export function createWebSocketStore(url: string) {
// merge are cloned first, because the merge output shares nested references
// and Solid's reconcile mutates adopted objects in place.
let rawServerResources: Resource[] | null = null;
- let lastDeltaRecoveryRequestAt = 0;
+ let lastFullStateRecoveryAt = 0;
+ // Set once the server has sent a full snapshot too large for the inbound
+ // guard. Asking for another one over the socket would only reproduce the same
+ // oversized frame, so recovery has to leave the WebSocket entirely.
+ let oversizedSnapshotObserved = false;
+ let restHydrationInFlight = false;
let reconnectTimeout = 0;
let reconnectDelayTimeout = 0;
let lastServerActivityAt = Date.now();
@@ -437,10 +443,300 @@ export function createWebSocketStore(url: string) {
}, delay);
};
+ // Applies one decoded server message to the store. Shared by the socket
+ // handler and the REST recovery path so a snapshot fetched over HTTP
+ // establishes the same delta baseline a socket snapshot would.
+ const processServerMessage = (data: unknown) => {
+ try {
+ const message = data as TimestampedWSMessage;
+
+ if (
+ message.type === WEBSOCKET.MESSAGE_TYPES.INITIAL_STATE ||
+ message.type === WEBSOCKET.MESSAGE_TYPES.RAW_DATA
+ ) {
+ // Update state properties individually, but batch the whole payload to
+ // reduce reactive recomputations and UI thrash on large updates.
+ if (message.data)
+ batch(() => {
+ // Mark that we've received usable data (initial payload or raw update)
+ if (!initialDataReceived()) {
+ setInitialDataReceived(true);
+ }
+
+ // Canonical resource contract:
+ // `state.resources` is the authoritative frontend model.
+ // `state.connectedInfrastructure` is the authoritative reporting projection.
+ if (message.data.connectedInfrastructure !== undefined) {
+ const connectedInfrastructure = Array.isArray(message.data.connectedInfrastructure)
+ ? (message.data.connectedInfrastructure as ConnectedInfrastructureItem[])
+ : [];
+ setState(
+ 'connectedInfrastructure',
+ reconcile(connectedInfrastructure, { key: 'id' }),
+ );
+ }
+ if (message.data.metrics !== undefined) setState('metrics', message.data.metrics);
+ if (message.data.performance !== undefined)
+ setState('performance', message.data.performance);
+ if (message.data.connectionHealth !== undefined)
+ setState('connectionHealth', message.data.connectionHealth);
+ if (message.data.stats !== undefined) setState('stats', message.data.stats);
+ if (message.data.pveTagColors !== undefined) {
+ setState('pveTagColors', message.data.pveTagColors ?? {});
+ }
+ if (message.data.pveTagStyles !== undefined) {
+ setState('pveTagStyles', message.data.pveTagStyles ?? {});
+ }
+ // Handle unified resources
+ let nextResources: Resource[] | undefined;
+ if (message.data.resources !== undefined) {
+ if (Array.isArray(message.data.resources)) {
+ rawServerResources = structuredClone(message.data.resources) as Resource[];
+ nextResources = mergeCanonicalResourceSnapshot(
+ message.data.resources,
+ state.resources,
+ );
+ } else {
+ rawServerResources = [];
+ nextResources = [];
+ }
+ } else if (
+ 'resourceDelta' in message.data &&
+ message.data.resourceDelta !== undefined
+ ) {
+ if (rawServerResources) {
+ rawServerResources = applyResourceStateDelta(
+ rawServerResources,
+ message.data.resourceDelta,
+ );
+ nextResources = mergeCanonicalResourceSnapshot(
+ structuredClone(rawServerResources) as Resource[],
+ state.resources,
+ );
+ } else {
+ // A delta landed before any full snapshot (e.g. the initial
+ // payload was dropped as oversized). There is no baseline to
+ // patch, so re-acquire a full snapshot instead of applying the
+ // delta to nothing and rendering stubs.
+ requestFullStateRecovery();
+ }
+ }
+ if (nextResources !== undefined) {
+ logger.debug('[WebSocket] Updating resources', {
+ count: nextResources.length,
+ types: [...new Set(nextResources.map((resource) => resource.type) || [])],
+ });
+ setState('resources', reconcile(nextResources, { key: 'id' }));
+
+ // Sync container update states with docker host command status payloads.
+ nextResources.forEach((resource: any) => {
+ if (resource?.type !== 'docker-host') return;
+ const platformData = asRecord(resource.platformData);
+ const dockerData = asRecord(platformData?.docker);
+ const command = dockerData?.command || platformData?.command;
+ if (!command || typeof command !== 'object') return;
+
+ const agentIds = new Set<string>([
+ resource.id,
+ asString(dockerData?.hostSourceId) || '',
+ asString(platformData?.hostSourceId) || '',
+ asString(resource?.discoveryTarget?.agentId) || '',
+ isAppContainerDiscoveryResourceType(resource?.discoveryTarget?.resourceType)
+ ? asString(resource?.discoveryTarget?.resourceId) || ''
+ : '',
+ ]);
+ agentIds.forEach((agentId) => {
+ if (agentId) {
+ syncWithAgentCommand(agentId, command as any);
+ }
+ });
+ });
+ }
+ // Sync active alerts from state
+ if (message.data.activeAlerts !== undefined) {
+ const newAlerts: Record<string, Alert> = {};
+ if (message.data.activeAlerts && Array.isArray(message.data.activeAlerts)) {
+ message.data.activeAlerts.forEach((alert: Alert) => {
+ newAlerts[alert.id] = alert;
+ });
+ }
+
+ lastActiveAlertsPayload = newAlerts;
+ applyActiveAlerts(alertsEnabled ? newAlerts : {});
+ }
+ // Sync recently resolved alerts
+ if (message.data.recentlyResolved !== undefined) {
+ // Received recentlyResolved update
+
+ // Update resolved alerts atomically to prevent race conditions
+ const newResolvedAlerts: Record<string, ResolvedAlert> = {};
+ if (message.data.recentlyResolved && Array.isArray(message.data.recentlyResolved)) {
+ message.data.recentlyResolved.forEach((alert: ResolvedAlert) => {
+ newResolvedAlerts[alert.id] = alert;
+ });
+ }
+
+ // Clear existing resolved alerts and set new ones
+ const currentResolvedIds = Object.keys(recentlyResolved);
+ currentResolvedIds.forEach((id) => {
+ if (!newResolvedAlerts[id]) {
+ setRecentlyResolved(id, undefined as unknown as ResolvedAlert);
+ }
+ });
+
+ // Add new resolved alerts
+ Object.entries(newResolvedAlerts).forEach(([id, alert]) => {
+ setRecentlyResolved(id, alert);
+ });
+
+ setState('recentlyResolved', Object.values(newResolvedAlerts));
+
+ // Updated recentlyResolved
+ }
+ setState(
+ 'lastUpdate',
+ typeof message.data.lastUpdate === 'number' ? message.data.lastUpdate : Date.now(),
+ );
+ });
+ logger.debug('message', {
+ type: message.type,
+ hasData: !!message.data,
+ resourceCount: message.data?.resources?.length || 0,
+ });
+ } else if (message.type === WEBSOCKET.MESSAGE_TYPES.ERROR) {
+ logger.debug('error', message.error);
+ } else if (message.type === 'ping') {
+ // Respond to ping with pong
+ if (ws && ws.readyState === WebSocket.OPEN) {
+ ws.send(JSON.stringify({ type: 'pong', data: { timestamp: Date.now() } }));
+ }
+ } else if (message.type === 'pong') {
+ // Server acknowledged our ping
+ logger.debug('Received pong from server');
+ } else if (message.type === 'welcome') {
+ // Welcome message from server
+ logger.info('WebSocket connection established');
+ } else if (message.type === 'alert') {
+ // Individual alerts now handled via state sync
+ logger.debug('New alert received (will sync with next state update)', message.data);
+ } else if (message.type === 'alertResolved') {
+ // Individual alert resolution now handled via state sync
+ logger.info('Alert resolved (will sync with next state update)', {
+ alertIdentifier: message.data.alertIdentifier,
+ });
+ } else if (message.type === 'update:progress') {
+ // Update progress event
+ setUpdateProgress(message.data);
+ logger.info('Update progress:', message.data);
+ } else if (message.type === 'node_auto_registered') {
+ const node = message.data;
+ const nodeName = node.name || node.host;
+ const nodeType = node.type === 'pve' ? 'Proxmox VE' : 'Proxmox Backup Server';
+
+ if (
+ shouldShowAutoRegisterNotification(message, node, Date.now(), currentConnectionOpenedAtMs)
+ ) {
+ notificationStore.success(
+ `${nodeType} node "${nodeName}" was successfully auto-registered and is now being monitored!`,
+ 8000,
+ );
+ eventBus.emit('node_auto_registered', node);
+ logger.info('Node auto-registered:', node);
+ } else {
+ logger.debug('Suppressed stale or duplicate node auto-registration notification', {
+ nodeName,
+ nodeType: node.type,
+ timestamp: message.timestamp,
+ });
+ }
+
+ eventBus.emit('refresh_nodes');
+ } else if (message.type === 'node_deleted' || message.type === 'nodes_changed') {
+ // Nodes configuration has changed, refresh the list
+ eventBus.emit('refresh_nodes');
+ } else if (message.type === 'discovery_update') {
+ // Discovery scan completed with new results
+ eventBus.emit('discovery_updated', message.data);
+ } else if (message.type === 'discovery_started') {
+ eventBus.emit('discovery_status', {
+ scanning: true,
+ subnet: message.data?.subnet,
+ timestamp: message.data?.timestamp,
+ });
+ } else if (message.type === 'discovery_complete') {
+ eventBus.emit('discovery_status', {
+ scanning: false,
+ timestamp: message.data?.timestamp,
+ });
+ } else if ((message as { type: string }).type === 'ai_discovery_progress') {
+ // AI-powered discovery progress update
+ eventBus.emit(
+ 'ai_discovery_progress',
+ (message as { data: unknown }).data as import('../types/discovery').DiscoveryProgress,
+ );
+ } else if (message.type === 'settingsUpdate') {
+ // Settings have been updated (e.g., theme change)
+ if (message.data?.theme) {
+ // Emit event for theme change
+ eventBus.emit('theme_changed', message.data.theme);
+ logger.info('Theme update received via WebSocket:', message.data.theme);
+ }
+ } else {
+ // Log any unhandled message types in dev mode only
+ if (import.meta.env.DEV) {
+ // Silently ignore unhandled message types
+ }
+ }
+ } catch (err) {
+ logger.error('Failed to process WebSocket message', err);
+ }
+ };
+
+ // Hydrate from the REST snapshot endpoint. `/api/state` serves the same
+ // `BuildFrontendState()` value the socket sends as `initialState`, but over a
+ // transport with no frame-size ceiling, so it is the only recovery path that
+ // works once the snapshot has outgrown the inbound guard. The response is fed
+ // through the normal message handler so it establishes the delta baseline
+ // exactly as a socket snapshot would.
+ const hydrateFullStateFromREST = async () => {
+ if (isDisposed || restHydrationInFlight) return;
+ restHydrationInFlight = true;
+ try {
+ const snapshot = await apiFetchJSON<State>('/api/state');
+ if (isDisposed) return;
+ if (!snapshot || typeof snapshot !== 'object') {
+ logger.error('REST state recovery returned an unusable payload');
+ return;
+ }
+ logger.info('Hydrated full state over REST after an oversized WebSocket snapshot');
+ processServerMessage({ type: WEBSOCKET.MESSAGE_TYPES.RAW_DATA, data: snapshot });
+ } catch (error) {
+ // Leave the throttle stamp in place; the next delta without a baseline
+ // retries. Failing here is not fatal — the UI stays in its current state.
+ logger.error('REST state recovery failed', error);
+ } finally {
+ restHydrationInFlight = false;
+ }
+ };
+
+ // Single throttled entry point for re-acquiring a full snapshot, whichever
+ // trigger noticed the gap: a frame dropped as oversized, or a delta arriving
+ // with no baseline to patch. Sharing one budget keeps a server that repeatedly
+ // emits an undeliverable snapshot from turning into a REST hammer.
const requestFullStateRecovery = () => {
const now = Date.now();
- if (now - lastDeltaRecoveryRequestAt < 30000) return;
- lastDeltaRecoveryRequestAt = now;
+ if (now - lastFullStateRecoveryAt < 30000) return;
+ lastFullStateRecoveryAt = now;
+
+ if (oversizedSnapshotObserved) {
+ // The socket has already proven it cannot deliver this estate's snapshot.
+ // `requestData` would just queue another frame the guard drops, which is
+ // what left large estates stuck on an empty UI, retrying every 30s.
+ logger.warn('Recovering full state over REST; socket snapshot exceeds the inbound limit');
+ void hydrateFullStateFromREST();
+ return;
+ }
+
logger.warn('Received resource delta without a full snapshot baseline; requesting full state');
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'requestData' }));
@@ -498,6 +794,14 @@ export function createWebSocketStore(url: string) {
characterCount: event.data.length,
maxBytes: MAX_INBOUND_WEBSOCKET_MESSAGE_BYTES,
});
+ // A dropped frame is almost always the full snapshot: it is the only
+ // message that scales with estate size (~2.7 KB per resource, so the
+ // 8 MiB guard trips around 3100 resources). Recover over REST rather
+ // than waiting for a baseline-less delta to notice, otherwise the first
+ // paint on a large estate is an empty UI.
+ oversizedSnapshotObserved = true;
+ lastServerActivityAt = Date.now();
+ requestFullStateRecovery();
return;
}
@@ -510,254 +814,7 @@ export function createWebSocketStore(url: string) {
}
lastServerActivityAt = Date.now();
- try {
- const message = data as TimestampedWSMessage;
-
- if (
- message.type === WEBSOCKET.MESSAGE_TYPES.INITIAL_STATE ||
- message.type === WEBSOCKET.MESSAGE_TYPES.RAW_DATA
- ) {
- // Update state properties individually, but batch the whole payload to
- // reduce reactive recomputations and UI thrash on large updates.
- if (message.data)
- batch(() => {
- // Mark that we've received usable data (initial payload or raw update)
- if (!initialDataReceived()) {
- setInitialDataReceived(true);
- }
-
- // Canonical resource contract:
- // `state.resources` is the authoritative frontend model.
- // `state.connectedInfrastructure` is the authoritative reporting projection.
- if (message.data.connectedInfrastructure !== undefined) {
- const connectedInfrastructure = Array.isArray(message.data.connectedInfrastructure)
- ? (message.data.connectedInfrastructure as ConnectedInfrastructureItem[])
- : [];
- setState(
- 'connectedInfrastructure',
- reconcile(connectedInfrastructure, { key: 'id' }),
- );
- }
- if (message.data.metrics !== undefined) setState('metrics', message.data.metrics);
- if (message.data.performance !== undefined)
- setState('performance', message.data.performance);
- if (message.data.connectionHealth !== undefined)
- setState('connectionHealth', message.data.connectionHealth);
- if (message.data.stats !== undefined) setState('stats', message.data.stats);
- if (message.data.pveTagColors !== undefined) {
- setState('pveTagColors', message.data.pveTagColors ?? {});
- }
- if (message.data.pveTagStyles !== undefined) {
- setState('pveTagStyles', message.data.pveTagStyles ?? {});
- }
- // Handle unified resources
- let nextResources: Resource[] | undefined;
- if (message.data.resources !== undefined) {
- if (Array.isArray(message.data.resources)) {
- rawServerResources = structuredClone(message.data.resources) as Resource[];
- nextResources = mergeCanonicalResourceSnapshot(
- message.data.resources,
- state.resources,
- );
- } else {
- rawServerResources = [];
- nextResources = [];
- }
- } else if (
- 'resourceDelta' in message.data &&
- message.data.resourceDelta !== undefined
- ) {
- if (rawServerResources) {
- rawServerResources = applyResourceStateDelta(
- rawServerResources,
- message.data.resourceDelta,
- );
- nextResources = mergeCanonicalResourceSnapshot(
- structuredClone(rawServerResources) as Resource[],
- state.resources,
- );
- } else {
- // A delta landed before any full snapshot (e.g. the initial
- // payload was dropped as oversized). There is no baseline to
- // patch, so ask the server for a full snapshot instead of
- // applying the delta to nothing and rendering stubs.
- requestFullStateRecovery();
- }
- }
- if (nextResources !== undefined) {
- logger.debug('[WebSocket] Updating resources', {
- count: nextResources.length,
- types: [...new Set(nextResources.map((resource) => resource.type) || [])],
- });
- setState('resources', reconcile(nextResources, { key: 'id' }));
-
- // Sync container update states with docker host command status payloads.
- nextResources.forEach((resource: any) => {
- if (resource?.type !== 'docker-host') return;
- const platformData = asRecord(resource.platformData);
- const dockerData = asRecord(platformData?.docker);
- const command = dockerData?.command || platformData?.command;
- if (!command || typeof command !== 'object') return;
-
- const agentIds = new Set<string>([
- resource.id,
- asString(dockerData?.hostSourceId) || '',
- asString(platformData?.hostSourceId) || '',
- asString(resource?.discoveryTarget?.agentId) || '',
- isAppContainerDiscoveryResourceType(resource?.discoveryTarget?.resourceType)
- ? asString(resource?.discoveryTarget?.resourceId) || ''
- : '',
- ]);
- agentIds.forEach((agentId) => {
- if (agentId) {
- syncWithAgentCommand(agentId, command as any);
- }
- });
- });
- }
- // Sync active alerts from state
- if (message.data.activeAlerts !== undefined) {
- const newAlerts: Record<string, Alert> = {};
- if (message.data.activeAlerts && Array.isArray(message.data.activeAlerts)) {
- message.data.activeAlerts.forEach((alert: Alert) => {
- newAlerts[alert.id] = alert;
- });
- }
-
- lastActiveAlertsPayload = newAlerts;
- applyActiveAlerts(alertsEnabled ? newAlerts : {});
- }
- // Sync recently resolved alerts
- if (message.data.recentlyResolved !== undefined) {
- // Received recentlyResolved update
-
- // Update resolved alerts atomically to prevent race conditions
- const newResolvedAlerts: Record<string, ResolvedAlert> = {};
- if (message.data.recentlyResolved && Array.isArray(message.data.recentlyResolved)) {
- message.data.recentlyResolved.forEach((alert: ResolvedAlert) => {
- newResolvedAlerts[alert.id] = alert;
- });
- }
-
- // Clear existing resolved alerts and set new ones
- const currentResolvedIds = Object.keys(recentlyResolved);
- currentResolvedIds.forEach((id) => {
- if (!newResolvedAlerts[id]) {
- setRecentlyResolved(id, undefined as unknown as ResolvedAlert);
- }
- });
-
- // Add new resolved alerts
- Object.entries(newResolvedAlerts).forEach(([id, alert]) => {
- setRecentlyResolved(id, alert);
- });
-
- setState('recentlyResolved', Object.values(newResolvedAlerts));
-
- // Updated recentlyResolved
- }
- setState(
- 'lastUpdate',
- typeof message.data.lastUpdate === 'number' ? message.data.lastUpdate : Date.now(),
- );
- });
- logger.debug('message', {
- type: message.type,
- hasData: !!message.data,
- resourceCount: message.data?.resources?.length || 0,
- });
- } else if (message.type === WEBSOCKET.MESSAGE_TYPES.ERROR) {
- logger.debug('error', message.error);
- } else if (message.type === 'ping') {
- // Respond to ping with pong
- if (ws && ws.readyState === WebSocket.OPEN) {
- ws.send(JSON.stringify({ type: 'pong', data: { timestamp: Date.now() } }));
- }
- } else if (message.type === 'pong') {
- // Server acknowledged our ping
- logger.debug('Received pong from server');
- } else if (message.type === 'welcome') {
- // Welcome message from server
- logger.info('WebSocket connection established');
- } else if (message.type === 'alert') {
- // Individual alerts now handled via state sync
- logger.debug('New alert received (will sync with next state update)', message.data);
- } else if (message.type === 'alertResolved') {
- // Individual alert resolution now handled via state sync
- logger.info('Alert resolved (will sync with next state update)', {
- alertIdentifier: message.data.alertIdentifier,
- });
- } else if (message.type === 'update:progress') {
- // Update progress event
- setUpdateProgress(message.data);
- logger.info('Update progress:', message.data);
- } else if (message.type === 'node_auto_registered') {
- const node = message.data;
- const nodeName = node.name || node.host;
- const nodeType = node.type === 'pve' ? 'Proxmox VE' : 'Proxmox Backup Server';
-
- if (
- shouldShowAutoRegisterNotification(
- message,
- node,
- Date.now(),
- currentConnectionOpenedAtMs,
- )
- ) {
- notificationStore.success(
- `${nodeType} node "${nodeName}" was successfully auto-registered and is now being monitored!`,
- 8000,
- );
- eventBus.emit('node_auto_registered', node);
- logger.info('Node auto-registered:', node);
- } else {
- logger.debug('Suppressed stale or duplicate node auto-registration notification', {
- nodeName,
- nodeType: node.type,
- timestamp: message.timestamp,
- });
- }
-
- eventBus.emit('refresh_nodes');
- } else if (message.type === 'node_deleted' || message.type === 'nodes_changed') {
- // Nodes configuration has changed, refresh the list
- eventBus.emit('refresh_nodes');
- } else if (message.type === 'discovery_update') {
- // Discovery scan completed with new results
- eventBus.emit('discovery_updated', message.data);
- } else if (message.type === 'discovery_started') {
- eventBus.emit('discovery_status', {
- scanning: true,
- subnet: message.data?.subnet,
- timestamp: message.data?.timestamp,
- });
- } else if (message.type === 'discovery_complete') {
- eventBus.emit('discovery_status', {
- scanning: false,
- timestamp: message.data?.timestamp,
- });
- } else if ((message as { type: string }).type === 'ai_discovery_progress') {
- // AI-powered discovery progress update
- eventBus.emit(
- 'ai_discovery_progress',
- (message as { data: unknown }).data as import('../types/discovery').DiscoveryProgress,
- );
- } else if (message.type === 'settingsUpdate') {
- // Settings have been updated (e.g., theme change)
- if (message.data?.theme) {
- // Emit event for theme change
- eventBus.emit('theme_changed', message.data.theme);
- logger.info('Theme update received via WebSocket:', message.data.theme);
- }
- } else {
- // Log any unhandled message types in dev mode only
- if (import.meta.env.DEV) {
- // Silently ignore unhandled message types
- }
- }
- } catch (err) {
- logger.error('Failed to process WebSocket message', err);
- }
+ processServerMessage(data);
};
ws.onclose = (event) => {
@@ -765,6 +822,11 @@ export function createWebSocketStore(url: string) {
logger.debug('disconnect', { code: event.code, reason: event.reason });
setConnected(false);
setInitialDataReceived(false);
+ // The next connection re-sends the snapshot, so let its recovery fire
+ // immediately instead of inheriting this connection's throttle window —
+ // otherwise a reconnect on an estate whose snapshot the guard drops can
+ // sit unhydrated for up to 30s.
+ lastFullStateRecoveryAt = 0;
// Clear heartbeat interval
clearHeartbeatTimer();
@@ -927,7 +989,9 @@ export function createWebSocketStore(url: string) {
});
rawServerResources = null;
- lastDeltaRecoveryRequestAt = 0;
+ lastFullStateRecoveryAt = 0;
+ // A different backend may have an estate that fits the socket guard.
+ oversizedSnapshotObserved = false;
clearReconnectTimeout();
clearReconnectDelayTimeout();
reconnectAttempt = 0;