Surface server websocketStateStalled warnings in dashboard header (#5439)

GET /api/health already exposes websocketStateStalled: true whenever the
shared WebSocket state-build slot stalls, but useAppRuntimeState stopped
polling /api/health while connected and discarded the response body,
leaving operators with a green Connected dot (or "Backend is healthy.")
while live dashboard updates were stalled.

Poll /api/health periodically across authenticated states, parse
websocketStateStalled with a request-generation guard, and surface a
warning AppConnectionStatus ("Updates stalled") that AppLayout's
ConnectionStatusBadge renders visibly in both light and dark modes at
desktop and phone viewports, recovering cleanly when the flag clears.

Also deduplicate the empty WebSocket State initializer, WebSocket store
teardown (closing a shutdown listener/timer leak), catalog ref
expansion,
and table windowing hooks so Total JS drops from 1611.70 kB (over budget
on main) to 1611.04 kB / 1611.57 kB without touching .bundlesize.json.

Contract-Neutral: Consumes the existing public GET /api/health
websocketStateStalled field in the frontend runtime hook and
consolidates internal store and table windowing helpers without changing
backend APIs, routes, auth, polling policy, or subsystem contracts.

---
Fleet candidate `20261128T191059Z-web-product` from the `web-product`
lane. Reviewed tip `fed6afa043f482e599127c9da59035db451e9302` on `main`.

[How Pulse handles
triage](https://github.com/rcourtman/Pulse/blob/main/docs/AI_TRANSPARENCY.md)
This commit is contained in:
pulse-triage[bot]
2026-11-28 20:21:15 +00:00
committed by GitHub
8 changed files with 492 additions and 371 deletions

View File

@@ -0,0 +1,42 @@
{
"version": 1,
"base_sha": "dd86143f5536d770a49c27a22848fae249b19702",
"verified_at": "2026-11-28T19:36:04Z",
"result": "passed",
"changed_paths": [
"frontend-modern/src/components/Infrastructure/useTableWindowing.ts",
"frontend-modern/src/components/Workloads/useGroupedTableWindowing.ts",
"frontend-modern/src/stores/websocket-global.ts",
"frontend-modern/src/stores/websocket.ts",
"frontend-modern/src/useAppRuntimeState.ts"
],
"content_sha256": {
"frontend-modern/src/components/Infrastructure/useTableWindowing.ts": "cef33f5a92a9fa3e6815e52e73a765db20f49cf1dfde30fc4d50b09ca581c78e",
"frontend-modern/src/components/Workloads/useGroupedTableWindowing.ts": "f46d7065dd6ad999f2ee042079b8d1f8c69d113d5d28f534bc62a85afb8a15d6",
"frontend-modern/src/stores/websocket-global.ts": "6877585f940253c225e82cb70fe43c33b3c3fdfc4a62288cd422abdd896d32be",
"frontend-modern/src/stores/websocket.ts": "f22011342037e7f7e1ea0524dae17224a691d7d20875b12f008c94901286b468",
"frontend-modern/src/useAppRuntimeState.ts": "e60df379376c40d79147a555ac5fbd7281aceb5cd6aee466a40dc04326cc7a72"
},
"routes": [
"/proxmox/overview"
],
"viewports": [
{
"width": 1440,
"height": 940
},
{
"width": 360,
"height": 820
}
],
"states": [
"Paired production dist builds of base dd86143f55 and patched tree served over loopback HTTP in Playwright Chromium (1440x940 dark and light) and touch WebKit (360x820 dark, isMobile/hasTouch).",
"Signed-in Proxmox overview with open WebSocket, delivered initialState snapshot (node pve-node-01 and VM web-prod-01), and GET /api/health returning websocketStateStalled: true.",
"Before: header ConnectionStatusBadge rendered a green Connected dot with label opacity 0 and aria-label 'Live updates are connected. Source readings may be older.' despite the stalled server state build.",
"After: header ConnectionStatusBadge renders the visible amber Updates stalled pill (opacity 1, 8.15:1 contrast dark, 7.28:1 contrast light, 116x24px, 0px overflow) with aria-label 'Backend is reachable, but live dashboard state updates are stalled.' while non-stalled /api/health stays green Connected."
],
"interactions": [
"Verified WebSocket initialState hydration, /api/health websocketStateStalled polling in connected state, healthy-control comparison with websocketStateStalled omitted, zero console/page/HTTP errors, zero horizontal overflow, and native pixel inspection of all 7 captured PNGs."
]
}

View File

@@ -44,6 +44,30 @@ describe('ConnectionStatusBadge', () => {
expect(screen.queryByText('Disconnected')).not.toBeInTheDocument();
});
it('renders a stalled-updates warning badge visibly with warning contrast tokens', () => {
render(() => (
<ConnectionStatusBadge
connectionStatus={() => ({
kind: 'state-stalled',
label: 'Updates stalled',
detail: 'Backend is reachable, but live dashboard state updates are stalled.',
tone: 'warning',
})}
/>
));
expect(screen.getByText('Updates stalled')).toBeInTheDocument();
const badge = screen.getByRole('status', {
name: 'Backend is reachable, but live dashboard state updates are stalled.',
});
expect(badge).toHaveClass(
'bg-amber-200',
'dark:bg-amber-900',
'text-amber-900',
'dark:text-amber-100',
);
});
it('renders a disconnected state when both backend and stream are unavailable', () => {
render(() => (
<ConnectionStatusBadge

View File

@@ -1977,4 +1977,198 @@ describe('useAppRuntimeState', () => {
window.localStorage.removeItem('pulse_remembered_login_username');
}
});
it('surfaces a stalled-updates warning when /api/health reports websocketStateStalled while connected and recovers when cleared', async () => {
vi.useFakeTimers();
try {
let stalled = false;
websocketState = makeWebSocketState({ lastUpdate: 1_700_000_000_000 });
websocketConnected = true;
websocketInitialDataReceived = true;
websocketResourceSnapshotReceived = true;
apiFetchMock.mockImplementation(async (url: string) => {
if (url === '/api/state/summary') {
return new Response(
JSON.stringify({ activeAlerts: 0, nodes: 0, vms: 0, containers: 0, dockerHosts: [] }),
{ status: 200 },
);
}
if (url === '/api/security/status') {
return new Response(JSON.stringify({ hasAuthentication: true }), { status: 200 });
}
if (url === '/api/health') {
return new Response(
JSON.stringify(
stalled ? { status: 'healthy', websocketStateStalled: true } : { status: 'healthy' },
),
{ status: 200 },
);
}
throw new Error(`Unhandled apiFetch URL: ${url}`);
});
const { hookState, dispose } = mountHook();
await flushAsync();
await flushAsync();
expect(hookState.connectionStatus()).toMatchObject({
kind: 'connected',
label: 'Connected',
tone: 'healthy',
});
stalled = true;
await vi.advanceTimersByTimeAsync(30_000);
await flushAsync();
expect(hookState.connectionStatus()).toEqual({
kind: 'state-stalled',
label: 'Updates stalled',
detail: 'Backend is reachable, but live dashboard state updates are stalled.',
tone: 'warning',
});
stalled = false;
await vi.advanceTimersByTimeAsync(30_000);
await flushAsync();
expect(hookState.connectionStatus()).toMatchObject({
kind: 'connected',
label: 'Connected',
tone: 'healthy',
});
dispose();
} finally {
vi.useRealTimers();
}
});
it.each([
{ connected: true, snapshotReceived: false, reconnecting: false, label: 'waiting for data' },
{ connected: false, snapshotReceived: false, reconnecting: true, label: 'reconnecting' },
{
connected: false,
snapshotReceived: false,
reconnecting: false,
label: 'disconnected socket',
},
])(
'prefers the stalled-updates warning over $label when /api/health reports websocketStateStalled',
async ({ connected, snapshotReceived, reconnecting }) => {
websocketState = makeWebSocketState();
websocketConnected = connected;
websocketReconnecting = reconnecting;
websocketInitialDataReceived = snapshotReceived;
websocketResourceSnapshotReceived = snapshotReceived;
apiFetchMock.mockImplementation(async (url: string) => {
if (url === '/api/state/summary') {
return new Response(
JSON.stringify({ activeAlerts: 0, nodes: 0, vms: 0, containers: 0, dockerHosts: [] }),
{ status: 200 },
);
}
if (url === '/api/security/status') {
return new Response(JSON.stringify({ hasAuthentication: true }), { status: 200 });
}
if (url === '/api/health') {
return new Response(JSON.stringify({ status: 'healthy', websocketStateStalled: true }), {
status: 200,
});
}
throw new Error(`Unhandled apiFetch URL: ${url}`);
});
const { hookState, dispose } = mountHook();
await waitFor(() => {
expect(hookState.connectionStatus()).toMatchObject({
kind: 'state-stalled',
label: 'Updates stalled',
tone: 'warning',
});
});
dispose();
},
);
it('keeps offline states ahead of stalled when /api/health is unavailable and ignores non-JSON bodies', async () => {
websocketState = makeWebSocketState();
websocketConnected = false;
websocketReconnecting = true;
apiFetchMock.mockImplementation(async (url: string) => {
if (url === '/api/state/summary') {
return new Response(
JSON.stringify({ activeAlerts: 0, nodes: 0, vms: 0, containers: 0, dockerHosts: [] }),
{ status: 200 },
);
}
if (url === '/api/security/status') {
return new Response(JSON.stringify({ hasAuthentication: true }), { status: 200 });
}
if (url === '/api/health') {
return new Response(JSON.stringify({ status: 'unhealthy', websocketStateStalled: true }), {
status: 503,
});
}
throw new Error(`Unhandled apiFetch URL: ${url}`);
});
const { hookState, dispose } = mountHook();
await waitFor(() => {
expect(hookState.backendHealthy()).toBe(false);
expect(hookState.connectionStatus()).toMatchObject({
kind: 'reconnecting',
tone: 'offline',
});
});
dispose();
});
it('ignores a late stalled /api/health response that resolves after sign-out', async () => {
let resolveHealth!: (response: Response) => void;
websocketState = makeWebSocketState({ lastUpdate: 1_700_000_000_000 });
websocketConnected = true;
websocketInitialDataReceived = true;
websocketResourceSnapshotReceived = true;
apiFetchMock.mockImplementation(async (url: string) => {
if (url === '/api/state/summary') {
return new Response(
JSON.stringify({ activeAlerts: 0, nodes: 0, vms: 0, containers: 0, dockerHosts: [] }),
{ status: 200 },
);
}
if (url === '/api/security/status') {
return new Response(JSON.stringify({ hasAuthentication: true }), { status: 200 });
}
if (url === '/api/logout') {
return new Response(JSON.stringify({ success: true }), { status: 200 });
}
if (url === '/api/health') {
return new Promise<Response>((resolve) => {
resolveHealth = resolve;
});
}
throw new Error(`Unhandled apiFetch URL: ${url}`);
});
const { hookState, dispose } = mountHook();
await waitFor(() => expect(resolveHealth).toBeTypeOf('function'));
await hookState.handleLogout();
resolveHealth(
new Response(JSON.stringify({ status: 'healthy', websocketStateStalled: true }), {
status: 200,
}),
);
await flushAsync();
expect(hookState.needsAuth()).toBe(true);
expect(hookState.backendHealthy()).toBe(false);
expect(hookState.connectionStatus()).toMatchObject({
kind: 'disconnected',
tone: 'offline',
});
dispose();
});
});

View File

@@ -1,4 +1,4 @@
import { createEffect, createMemo, createSignal } from 'solid-js';
import { createEffect, createMemo, createSignal, untrack } from 'solid-js';
export interface UseTableWindowingOptions {
/** Total number of renderable items (rows + group headers) */
@@ -11,6 +11,8 @@ export interface UseTableWindowingOptions {
enableThreshold?: number;
/** Index to ensure is visible (for deep-link/highlight reveal) */
revealIndex?: () => number | null;
/** Resolve a row index from a virtual offset when grouped decorations add height. */
rowIndexAtOffset?: (offset: number, rowHeight: number) => number;
}
export interface UseTableWindowingResult {
@@ -85,7 +87,11 @@ export const useTableWindowing = (options: UseTableWindowingOptions): UseTableWi
const safeRowHeight = rowHeight > 0 ? rowHeight : 40;
const safeContainerHeight = containerHeight > 0 ? containerHeight : safeRowHeight;
const rowsInView = Math.max(1, Math.ceil(safeContainerHeight / safeRowHeight));
const firstVisibleRow = Math.floor(Math.max(0, scrollTop) / safeRowHeight);
const safeScrollTop = Math.max(0, scrollTop);
const resolvedFirstVisibleRow = options.rowIndexAtOffset?.(safeScrollTop, safeRowHeight);
const firstVisibleRow = Number.isFinite(resolvedFirstVisibleRow)
? Math.max(0, Math.floor(resolvedFirstVisibleRow!))
: Math.floor(safeScrollTop / safeRowHeight);
const visibleEnd = Math.min(options.totalCount(), firstVisibleRow + rowsInView);
const availableBuffer = Math.max(0, normalizedWindowSize() - rowsInView);
const targetRunway = Math.floor(availableBuffer / 2);
@@ -130,7 +136,8 @@ export const useTableWindowing = (options: UseTableWindowingOptions): UseTableWi
if (!isWindowed()) return;
const target = options.revealIndex?.();
if (target == null || target < 0) return;
revealIndex(target);
// A reveal target is an initial positioning request, not a permanent pin.
untrack(() => revealIndex(target));
});
return {

View File

@@ -1,4 +1,5 @@
import { createEffect, createMemo, createSignal, untrack } from 'solid-js';
import { createMemo } from 'solid-js';
import { useTableWindowing } from '@/components/Infrastructure/useTableWindowing';
import type { WorkloadGuest } from '@/types/workloads';
export interface UseGroupedTableWindowingOptions {
@@ -37,99 +38,18 @@ export interface UseGroupedTableWindowingResult {
revealIndex: (index: number) => void;
}
const DEFAULT_WINDOW_SIZE = 140;
// Keep even medium estates virtualized. On mobile, mounting a few hundred
// metric-heavy rows is already enough to cause long layout and paint tasks.
const DEFAULT_ENABLE_THRESHOLD = DEFAULT_WINDOW_SIZE;
// A mutation frame costs a near-constant style/layout pass on the mounted
// table whatever the shift size, so runway top-ups run in dead-band-sized
// batches: most scroll frames stay compositor-only, and sub-row scroll jitter
// cannot thrash one-row shifts in alternating directions.
const TOP_UP_DEADBAND_ROWS = 8;
export const useGroupedTableWindowing = (
options: UseGroupedTableWindowingOptions,
): UseGroupedTableWindowingResult => {
const [windowStart, setWindowStart] = createSignal(0);
const normalizedWindowSize = createMemo(() =>
Math.max(1, Math.floor(options.windowSize ?? DEFAULT_WINDOW_SIZE)),
);
const isWindowed = createMemo(() => {
const total = options.totalRowCount();
const threshold = Math.max(0, Math.floor(options.enableThreshold ?? DEFAULT_ENABLE_THRESHOLD));
const enabled = options.enabled?.() ?? total > threshold;
return enabled && total > 0;
const { isWindowed, startIndex, endIndex, onScroll, revealIndex } = useTableWindowing({
totalCount: options.totalRowCount,
windowSize: options.windowSize,
enableThreshold: options.enableThreshold,
enabled: options.enabled,
revealIndex: options.revealIndex,
rowIndexAtOffset: options.rowIndexAtOffset,
});
const maxStart = createMemo(() => Math.max(0, options.totalRowCount() - normalizedWindowSize()));
const startIndex = createMemo(() => {
if (!isWindowed()) return 0;
return Math.max(0, Math.min(windowStart(), maxStart()));
});
const endIndex = createMemo(() => {
if (!isWindowed()) return options.totalRowCount();
return Math.min(options.totalRowCount(), startIndex() + normalizedWindowSize());
});
const setClampedStart = (nextStart: number) => {
const clamped = Math.max(0, Math.min(Math.floor(nextStart), maxStart()));
setWindowStart((current) => (current === clamped ? current : clamped));
};
const revealIndex = (index: number) => {
if (!isWindowed()) return;
if (!Number.isFinite(index)) return;
const normalizedIndex = Math.max(0, Math.min(Math.floor(index), options.totalRowCount() - 1));
if (normalizedIndex >= startIndex() && normalizedIndex < endIndex()) return;
const centeredStart = normalizedIndex - Math.floor(normalizedWindowSize() / 2);
setClampedStart(centeredStart);
};
const onScroll = (scrollTop: number, containerHeight: number, rowHeight: number) => {
if (!isWindowed()) return;
const safeRowHeight = rowHeight > 0 ? rowHeight : 40;
const safeContainerHeight = containerHeight > 0 ? containerHeight : safeRowHeight;
const rowsInView = Math.max(1, Math.ceil(safeContainerHeight / safeRowHeight));
const resolvedFirstVisibleRow = options.rowIndexAtOffset?.(
Math.max(0, scrollTop),
safeRowHeight,
);
const firstVisibleRow = Number.isFinite(resolvedFirstVisibleRow)
? Math.max(0, Math.floor(resolvedFirstVisibleRow!))
: Math.floor(Math.max(0, scrollTop) / safeRowHeight);
const visibleEnd = Math.min(options.totalRowCount(), firstVisibleRow + rowsInView);
const availableBuffer = Math.max(0, normalizedWindowSize() - rowsInView);
const targetRunway = Math.floor(availableBuffer / 2);
const leadingRunway = firstVisibleRow - startIndex();
const trailingRunway = endIndex() - visibleEnd;
if (leadingRunway < 0 || trailingRunway < 0) {
// Teleport (scrollbar drag, deep jump): the viewport left the mounted
// window entirely, so re-center the window on it.
setClampedStart(firstVisibleRow - targetRunway);
return;
}
// Top up only the depleted side, and only once its deficit clears the
// dead-band, restoring that side to the full target. Leading and trailing
// runway always sum to the spare buffer, so at most one side is below
// target. Steady scrolling therefore pays one bounded mutation frame per
// dead-band of travel instead of a slice update on every scroll event.
const topUpThreshold = Math.min(TOP_UP_DEADBAND_ROWS, Math.max(1, Math.ceil(targetRunway / 2)));
if (targetRunway - trailingRunway >= topUpThreshold) {
setClampedStart(startIndex() + (targetRunway - trailingRunway));
} else if (targetRunway - leadingRunway >= topUpThreshold) {
setClampedStart(startIndex() - (targetRunway - leadingRunway));
}
};
const getVisibleSlice = (
_groupKey: string,
guests: WorkloadGuest[],
@@ -150,24 +70,6 @@ export const useGroupedTableWindowing = (
return Math.max(0, endIndex() - startIndex());
});
createEffect(() => {
if (!isWindowed()) {
setWindowStart(0);
return;
}
setClampedStart(windowStart());
});
createEffect(() => {
if (!isWindowed()) return;
const target = options.revealIndex?.();
if (target == null || target < 0) return;
// A reveal target is an initial positioning request, not a permanent pin.
// Reading the current window inside this effect would otherwise make every
// scroll-driven window shift snap back to an expanded or deep-linked row.
untrack(() => revealIndex(target));
});
return {
isWindowed,
startIndex,

View File

@@ -1,5 +1,9 @@
import { createAlertAcknowledgementRequests } from './alertAcknowledgementRequests';
import { createWebSocketStore, type ActiveAlertsHydrationStatus } from './websocket';
import {
createEmptyWebSocketState,
createWebSocketStore,
type ActiveAlertsHydrationStatus,
} from './websocket';
import { createSignal, createRoot } from 'solid-js';
import { createStore } from 'solid-js/store';
import { getPulseWebSocketUrl } from '@/utils/url';
@@ -32,33 +36,7 @@ const createNoopWebSocketStore = (): ReturnType<typeof createWebSocketStore> =>
// The no-op app's request owner lives as long as this store; shutdown ends
// it, as the real store's shutdown does.
const alertAcknowledgementRequests = createAlertAcknowledgementRequests();
const [state] = createStore<State>({
connectedInfrastructure: [],
metrics: [],
performance: {
apiCallDuration: {},
lastPollDuration: 0,
pollingStartTime: '',
totalApiCalls: 0,
failedApiCalls: 0,
cacheHits: 0,
cacheMisses: 0,
},
connectionHealth: {},
stats: {
startTime: new Date().toISOString(),
uptime: 0,
pollingCycles: 0,
webSocketClients: 0,
version: '2.0.0',
},
activeAlerts: [],
recentlyResolved: [],
lastUpdate: 0,
pveTagColors: {},
pveTagStyles: {},
resources: [],
});
const [state] = createStore<State>(createEmptyWebSocketState());
return {
state,

View File

@@ -270,6 +270,36 @@ const shouldShowAutoRegisterNotification = (
return true;
};
export const createEmptyWebSocketState = (version = '2.0.0'): State => ({
// Canonical v6 state comes from unified resources.
connectedInfrastructure: [],
metrics: [],
performance: {
apiCallDuration: {},
lastPollDuration: 0,
pollingStartTime: '',
totalApiCalls: 0,
failedApiCalls: 0,
cacheHits: 0,
cacheMisses: 0,
},
connectionHealth: {},
stats: {
startTime: new Date().toISOString(),
uptime: 0,
pollingCycles: 0,
webSocketClients: 0,
version,
},
activeAlerts: [],
recentlyResolved: [],
lastUpdate: 0,
pveTagColors: {},
pveTagStyles: {},
// Unified resources for cross-platform monitoring
resources: [],
});
// Type-safe WebSocket store
export function createWebSocketStore(url: string) {
let wsUrl = url;
@@ -279,35 +309,7 @@ export function createWebSocketStore(url: string) {
// Display admission survives transport reconnects, but not an organisation
// change. Alerts/status alone cannot establish an empty resource estate.
const [resourceSnapshotReceived, setResourceSnapshotReceived] = createSignal(false);
const createInitialState = (): State => ({
// Canonical v6 state comes from unified resources.
connectedInfrastructure: [],
metrics: [],
performance: {
apiCallDuration: {},
lastPollDuration: 0,
pollingStartTime: '',
totalApiCalls: 0,
failedApiCalls: 0,
cacheHits: 0,
cacheMisses: 0,
},
connectionHealth: {},
stats: {
startTime: new Date().toISOString(),
uptime: 0,
pollingCycles: 0,
webSocketClients: 0,
version: '2.0.0',
},
activeAlerts: [],
recentlyResolved: [],
lastUpdate: 0,
pveTagColors: {},
pveTagStyles: {},
// Unified resources for cross-platform monitoring
resources: [],
});
const createInitialState = (): State => createEmptyWebSocketState();
const [state, setState] = createStore<State>(createInitialState());
const [activeAlerts, setActiveAlerts] = createStore<Record<string, Alert>>({});
const [activeAlertsHydrationStatus, setActiveAlertsHydrationStatus] =
@@ -518,52 +520,58 @@ export function createWebSocketStore(url: string) {
const actionReadinessExpandedFromRef = new WeakMap<object, string>();
const policyExpandedFromRef = new WeakMap<object, string>();
const expandCatalogRef = <T extends object>(
ref: string | undefined,
current: T | undefined,
cache: WeakMap<object, string>,
catalog: Record<string, T>,
assign: (value: T) => void,
): void => {
if (!ref || (current && cache.get(current) === ref)) return;
const entry = catalog[ref];
if (!entry) return;
// Per-row clone: reconcile mutates adopted objects in place, so rows
// must not share one materialized catalog entry.
const expanded = structuredClone(entry);
cache.set(expanded, ref);
assign(expanded);
};
const hydrateSlimResource = (resource: Resource): void => {
if (!resource || typeof resource !== 'object') return;
const ref = resource.capabilitiesRef;
if (ref) {
const current = resource.capabilities as unknown as object | undefined;
if (!current || capabilitiesExpandedFromRef.get(current) !== ref) {
const entry = capabilityCatalog[ref];
if (entry) {
// Per-row clone: reconcile mutates adopted objects in place, so rows
// must not share one materialized capabilities array.
const expanded = structuredClone(entry);
capabilitiesExpandedFromRef.set(expanded as unknown as object, ref);
resource.capabilities = expanded;
}
}
}
expandCatalogRef(
resource.capabilitiesRef,
resource.capabilities as unknown as object | undefined,
capabilitiesExpandedFromRef,
capabilityCatalog as unknown as Record<string, object>,
(expanded) => {
resource.capabilities = expanded as unknown as ResourceCapability[];
},
);
// The server sends refusals only as refs, so a row without one refuses
// nothing, and a patch that removed the ref must take the old list with it.
const actionReadinessRef = resource.actionReadinessRef;
if (actionReadinessRef) {
const current = resource.actionReadiness as unknown as object | undefined;
if (!current || actionReadinessExpandedFromRef.get(current) !== actionReadinessRef) {
const entry = actionReadinessCatalog[actionReadinessRef];
if (entry) {
// Per-row clone: reconcile mutates adopted objects in place.
const expanded = structuredClone(entry);
actionReadinessExpandedFromRef.set(expanded as unknown as object, actionReadinessRef);
resource.actionReadiness = expanded;
}
}
if (resource.actionReadinessRef) {
expandCatalogRef(
resource.actionReadinessRef,
resource.actionReadiness as unknown as object | undefined,
actionReadinessExpandedFromRef,
actionReadinessCatalog as unknown as Record<string, object>,
(expanded) => {
resource.actionReadiness = expanded as unknown as ResourceActionReadiness[];
},
);
} else {
delete resource.actionReadiness;
}
const policyRef = resource.policyRef;
if (policyRef) {
const currentPolicy = resource.policy as unknown as object | undefined;
if (!currentPolicy || policyExpandedFromRef.get(currentPolicy) !== policyRef) {
const policyEntry = policyCatalog[policyRef];
if (policyEntry) {
// Per-row clone: reconcile mutates adopted objects in place.
const expandedPolicy = structuredClone(policyEntry);
policyExpandedFromRef.set(expandedPolicy as unknown as object, policyRef);
resource.policy = expandedPolicy;
}
}
}
expandCatalogRef(
resource.policyRef,
resource.policy as unknown as object | undefined,
policyExpandedFromRef,
policyCatalog as unknown as Record<string, object>,
(expanded) => {
resource.policy = expanded as unknown as Resource['policy'];
},
);
if (resource.aiSafeSummaryRef) {
const summary = aiSafeSummaryCatalog[resource.aiSafeSummaryRef];
// Strings are immutable; no clone needed.
@@ -723,10 +731,12 @@ export function createWebSocketStore(url: string) {
}, ACTIVE_ALERTS_COLD_HYDRATION_DELAY_MS);
};
const clearHeartbeatTimer = () => {
if (heartbeatInterval) {
window.clearInterval(heartbeatInterval);
heartbeatInterval = 0;
const clearActiveAlertsRecovery = () => {
activeAlertsRecoveryRequestId += 1;
activeAlertsRecoveryInFlight = null;
if (activeAlertsColdHydrationTimeout) {
window.clearTimeout(activeAlertsColdHydrationTimeout);
activeAlertsColdHydrationTimeout = 0;
}
};
@@ -762,7 +772,7 @@ export function createWebSocketStore(url: string) {
}
};
const resetConnectionBaseline = () => {
const clearDeltaBaselines = () => {
rawServerResources = null;
deferredResourceIds.clear();
deferredResourceKeys.clear();
@@ -771,6 +781,10 @@ export function createWebSocketStore(url: string) {
pendingInfrastructureIds.clear();
pendingInfrastructureFull = false;
rawActiveAlerts = null;
};
const resetConnectionBaseline = () => {
clearDeltaBaselines();
deferredLastUpdate = null;
lastFullStateRecoveryAt = 0;
oversizedSnapshotObserved = false;
@@ -1085,17 +1099,22 @@ export function createWebSocketStore(url: string) {
clearReconnectDelayTimeout();
clearHeartbeatInterval();
resetAlertAcknowledgements();
activeAlertsRecoveryRequestId += 1;
activeAlertsRecoveryInFlight = null;
if (activeAlertsColdHydrationTimeout) {
window.clearTimeout(activeAlertsColdHydrationTimeout);
activeAlertsColdHydrationTimeout = 0;
}
clearActiveAlertsRecovery();
activeConnectionId = null;
resetConnectionBaseline();
if (typeof window !== 'undefined') {
window.removeEventListener(ALERTS_DETECTION_EVENT, handleAlertsDetectionEvent);
for (const eventName of OPERATOR_INPUT_EVENTS) {
window.removeEventListener(eventName, handleOperatorInput, { capture: true });
}
}
if (typeof document !== 'undefined') {
document.removeEventListener('visibilitychange', handleResourceVisibilityChange);
}
if (deferredFlushTimer) {
window.clearTimeout(deferredFlushTimer);
deferredFlushTimer = 0;
}
if (ws) {
@@ -1483,14 +1502,7 @@ export function createWebSocketStore(url: string) {
// The server deliberately did not adopt the withheld payload as this
// client's delta baseline. Invalidate any prior baseline before REST
// hydration and remain delta-free until a full socket snapshot lands.
rawServerResources = null;
deferredResourceIds.clear();
deferredResourceKeys.clear();
deferredResourceDeltaQueue.length = 0;
rawConnectedInfrastructure = null;
pendingInfrastructureIds.clear();
pendingInfrastructureFull = false;
rawActiveAlerts = null;
clearDeltaBaselines();
oversizedSnapshotObserved = true;
logger.warn('Server withheld an oversized state payload. Recovering over REST', {
supersedes: message.data.supersedes,
@@ -1693,7 +1705,7 @@ export function createWebSocketStore(url: string) {
currentConnectionOpenedAtMs = lastServerActivityAt;
// Start heartbeat to keep connection alive
clearHeartbeatTimer();
clearHeartbeatInterval();
heartbeatInterval = window.setInterval(() => {
if (isCurrentConnection(connectionId) && socket.readyState === WebSocket.OPEN) {
const silenceDuration = Date.now() - lastServerActivityAt;
@@ -1770,7 +1782,7 @@ export function createWebSocketStore(url: string) {
setConnected(false);
// Clear heartbeat interval
clearHeartbeatTimer();
clearHeartbeatInterval();
if (isDisposed) {
return;
@@ -1836,39 +1848,7 @@ export function createWebSocketStore(url: string) {
connect();
// Cleanup on unmount
onCleanup(() => {
isDisposed = true;
isReconnecting = false;
activeConnectionId = null;
resetConnectionBaseline();
window.clearTimeout(reconnectDelayTimeout);
window.clearTimeout(reconnectTimeout);
window.clearInterval(heartbeatInterval);
resetAlertAcknowledgements();
activeAlertsRecoveryRequestId += 1;
activeAlertsRecoveryInFlight = null;
if (activeAlertsColdHydrationTimeout) {
window.clearTimeout(activeAlertsColdHydrationTimeout);
activeAlertsColdHydrationTimeout = 0;
}
if (typeof window !== 'undefined') {
window.removeEventListener(ALERTS_DETECTION_EVENT, handleAlertsDetectionEvent);
for (const eventName of OPERATOR_INPUT_EVENTS) {
window.removeEventListener(eventName, handleOperatorInput, { capture: true });
}
}
if (typeof document !== 'undefined') {
document.removeEventListener('visibilitychange', handleResourceVisibilityChange);
}
if (deferredFlushTimer) {
window.clearTimeout(deferredFlushTimer);
deferredFlushTimer = 0;
}
if (ws) {
ws.close(1000, 'Component unmounting');
ws = null;
}
});
onCleanup(shutdown);
const markTokenRevoked = (
key: 'dockerRuntimes' | 'agents',
@@ -1967,12 +1947,7 @@ export function createWebSocketStore(url: string) {
}
wsUrl = nextUrl;
activeAlertsRecoveryRequestId += 1;
activeAlertsRecoveryInFlight = null;
if (activeAlertsColdHydrationTimeout) {
window.clearTimeout(activeAlertsColdHydrationTimeout);
activeAlertsColdHydrationTimeout = 0;
}
clearActiveAlertsRecovery();
lastActiveAlertsRecoveryAt = 0;
hasActiveAlertsSnapshot = false;
activeAlertsRevision += 1;

View File

@@ -10,8 +10,8 @@ import {
runWithOwner,
} from 'solid-js';
import { getGlobalWebSocketStore, shutdownGlobalWebSocketStore } from '@/stores/websocket-global';
import { createEmptyWebSocketState } from '@/stores/websocket';
import { logger } from '@/utils/logger';
import { apiFetchJSON } from '@/utils/apiClient';
import {
PRIMARY_PLATFORM_NAV_IDS,
type PlatformNavigationVisibility,
@@ -25,6 +25,8 @@ import type { State } from '@/types/api';
import { SettingsAPI } from '@/api/settings';
import {
apiFetch,
apiFetchJSON,
clearAuth,
getOrgID as getSelectedOrgID,
hasAuth as hasStoredAuthSession,
setOrgID as setSelectedOrgID,
@@ -72,6 +74,7 @@ type EnhancedStore = ReturnType<typeof getGlobalWebSocketStore>;
export type AppConnectionStatus = {
kind:
| 'connected'
| 'state-stalled'
| 'waiting-for-data'
| 'sync-reconnecting'
| 'backend-healthy'
@@ -82,6 +85,51 @@ export type AppConnectionStatus = {
tone: 'healthy' | 'warning' | 'offline';
};
const CONNECTION_STATUSES: Record<AppConnectionStatus['kind'], AppConnectionStatus> = {
connected: {
kind: 'connected',
label: 'Connected',
detail: 'Live updates are connected. Source readings may be older.',
tone: 'healthy',
},
'state-stalled': {
kind: 'state-stalled',
label: 'Updates stalled',
detail: 'Backend is reachable, but live dashboard state updates are stalled.',
tone: 'warning',
},
'waiting-for-data': {
kind: 'waiting-for-data',
label: 'Waiting for data',
detail: 'Live updates are connected. Waiting for the first dashboard snapshot.',
tone: 'warning',
},
'sync-reconnecting': {
kind: 'sync-reconnecting',
label: 'Sync reconnecting',
detail: 'Backend is healthy. Live updates are reconnecting.',
tone: 'warning',
},
'backend-healthy': {
kind: 'backend-healthy',
label: 'Backend healthy',
detail: 'Backend is healthy, but the live data stream is not connected.',
tone: 'warning',
},
reconnecting: {
kind: 'reconnecting',
label: 'Reconnecting...',
detail: 'Attempting to reconnect to the backend and live data stream.',
tone: 'offline',
},
disconnected: {
kind: 'disconnected',
label: 'Disconnected',
detail: 'Backend and live data stream are unavailable.',
tone: 'offline',
},
};
export type OrganizationListIssue = 'unavailable' | 'empty';
const isPreAuthLoginBootstrapPath = (pathname: string): boolean =>
@@ -170,32 +218,7 @@ export const useAppRuntimeState = () => {
}
};
const fallbackState: State = {
connectedInfrastructure: [],
metrics: [],
performance: {
apiCallDuration: {},
lastPollDuration: 0,
pollingStartTime: '',
totalApiCalls: 0,
failedApiCalls: 0,
cacheHits: 0,
cacheMisses: 0,
},
connectionHealth: {},
stats: {
startTime: new Date().toISOString(),
uptime: 0,
pollingCycles: 0,
webSocketClients: 0,
version: '0.0.0',
},
activeAlerts: [],
recentlyResolved: [],
pveTagColors: {},
lastUpdate: 0,
resources: [],
};
const fallbackState: State = createEmptyWebSocketState('0.0.0');
const [isLoading, setIsLoading] = createSignal(true);
const [bootstrapFailed, setBootstrapFailed] = createSignal(false);
const [needsAuth, setNeedsAuth] = createSignal(false);
@@ -223,6 +246,11 @@ export const useAppRuntimeState = () => {
const [platformAdmission, setPlatformAdmission] =
createSignal<PlatformNavigationVisibility | null>(null);
const [backendHealthy, setBackendHealthy] = createSignal(false);
const [websocketStateStalled, setWebsocketStateStalled] = createSignal(false);
let healthCheckRead = 0;
onCleanup(() => {
healthCheckRead += 1;
});
const runtimeStateResolved = (): boolean => {
const store = wsStore();
// Alert REST recovery can populate state before the first resource frame.
@@ -247,56 +275,16 @@ export const useAppRuntimeState = () => {
});
const [versionInfo, setVersionInfo] = createSignal<VersionInfo | null>(null);
const connectionStatus = createMemo<AppConnectionStatus>(() => {
if (websocketStateStalled() && (connected() || backendHealthy())) {
return CONNECTION_STATUSES['state-stalled'];
}
if (connected()) {
if (!runtimeStateResolved()) {
return {
kind: 'waiting-for-data',
label: 'Waiting for data',
detail: 'Live updates are connected. Waiting for the first dashboard snapshot.',
tone: 'warning',
};
}
return {
kind: 'connected',
label: 'Connected',
detail: 'Live updates are connected. Source readings may be older.',
tone: 'healthy',
};
return CONNECTION_STATUSES[runtimeStateResolved() ? 'connected' : 'waiting-for-data'];
}
if (backendHealthy() && reconnecting()) {
return {
kind: 'sync-reconnecting',
label: 'Sync reconnecting',
detail: 'Backend is healthy. Live updates are reconnecting.',
tone: 'warning',
};
}
if (backendHealthy()) {
return {
kind: 'backend-healthy',
label: 'Backend healthy',
detail: 'Backend is healthy, but the live data stream is not connected.',
tone: 'warning',
};
return CONNECTION_STATUSES[reconnecting() ? 'sync-reconnecting' : 'backend-healthy'];
}
if (reconnecting()) {
return {
kind: 'reconnecting',
label: 'Reconnecting...',
detail: 'Attempting to reconnect to the backend and live data stream.',
tone: 'offline',
};
}
return {
kind: 'disconnected',
label: 'Disconnected',
detail: 'Backend and live data stream are unavailable.',
tone: 'offline',
};
return CONNECTION_STATUSES[reconnecting() ? 'reconnecting' : 'disconnected'];
});
const showOrgSwitcher = createMemo(() => {
if (!isMultiTenantEnabled()) {
@@ -433,12 +421,28 @@ export const useAppRuntimeState = () => {
};
const checkBackendHealth = async () => {
const read = ++healthCheckRead;
try {
const response = await apiFetch('/api/health', { cache: 'no-store' });
setBackendHealthy(response.ok);
let stalled = false;
try {
const payload: unknown = await response.json();
stalled = isRecord(payload) && payload.websocketStateStalled === true;
} catch {
// Non-JSON or empty /api/health responses do not assert a stall.
}
if (read !== healthCheckRead) return response.ok;
batch(() => {
setBackendHealthy(response.ok);
setWebsocketStateStalled(stalled);
});
return response.ok;
} catch {
setBackendHealthy(false);
if (read !== healthCheckRead) return false;
batch(() => {
setBackendHealthy(false);
setWebsocketStateStalled(false);
});
return false;
}
};
@@ -617,13 +621,18 @@ export const useAppRuntimeState = () => {
createEffect(() => {
if (isLoading() || needsAuth() || bootstrapFailed() || !hasAuth()) {
setBackendHealthy(false);
healthCheckRead += 1;
batch(() => {
setBackendHealthy(false);
setWebsocketStateStalled(false);
});
return;
}
if (connected()) {
const isConnected = connected();
const resolved = runtimeStateResolved();
if (isConnected) {
setBackendHealthy(true);
return;
}
void checkBackendHealth();
@@ -631,7 +640,7 @@ export const useAppRuntimeState = () => {
() => {
void checkBackendHealth();
},
reconnecting() ? 5000 : 15000,
isConnected ? (resolved ? 30000 : 15000) : reconnecting() ? 5000 : 15000,
);
onCleanup(() => {
@@ -710,7 +719,6 @@ export const useAppRuntimeState = () => {
'[App] Security status request returned 401. Clearing stored credentials and showing login.',
);
try {
const { clearAuth } = await import('@/utils/apiClient');
clearAuth();
} catch (clearError) {
logger.warn('[App] Failed to clear stored auth after 401', clearError);
@@ -753,18 +761,22 @@ export const useAppRuntimeState = () => {
const authConfigured = securityData.hasAuthentication;
setHasAuth(authConfigured);
if (securityData.hasProxyAuth && securityData.proxyAuthUsername) {
logger.info('[App] Proxy auth detected', { user: securityData.proxyAuthUsername });
setProxyAuthInfo({
username: securityData.proxyAuthUsername,
logoutURL: securityData.proxyAuthLogoutURL,
});
const completeDelegatedSession = async (username: string, logoutURL?: string) => {
setProxyAuthInfo({ username, logoutURL });
if (!(await beginAuthenticatedRuntime())) {
setIsLoading(false);
return;
}
void syncVersionInfoFromUpdateStore();
setIsLoading(false);
};
if (securityData.hasProxyAuth && securityData.proxyAuthUsername) {
logger.info('[App] Proxy auth detected', { user: securityData.proxyAuthUsername });
await completeDelegatedSession(
securityData.proxyAuthUsername,
securityData.proxyAuthLogoutURL,
);
return;
}
@@ -773,16 +785,7 @@ export const useAppRuntimeState = () => {
securityData.ssoSessionDisplayName || securityData.ssoSessionUsername;
logger.info('[App] SSO session detected', { user: ssoDisplayName });
setHasAuth(true);
setProxyAuthInfo({
username: ssoDisplayName,
logoutURL: securityData.ssoLogoutURL,
});
if (!(await beginAuthenticatedRuntime())) {
setIsLoading(false);
return;
}
void syncVersionInfoFromUpdateStore();
setIsLoading(false);
await completeDelegatedSession(ssoDisplayName, securityData.ssoLogoutURL);
return;
}
@@ -848,13 +851,10 @@ export const useAppRuntimeState = () => {
});
const timeout = window.setTimeout(() => controller.abort(), 15_000);
const raceAbort = <T>(promise: Promise<T>): Promise<T> => Promise.race([promise, aborted]);
try {
const { apiFetch: runtimeApiFetch, clearAuth } = await Promise.race([
import('@/utils/apiClient'),
aborted,
]);
const response = await Promise.race([
runtimeApiFetch('/api/logout', {
const response = await raceAbort(
apiFetch('/api/logout', {
method: 'POST',
// Keep normal credentials and CSRF, including token-only browsers.
// The endpoint ends only the cookie session; it does not revoke tokens.
@@ -864,9 +864,8 @@ export const useAppRuntimeState = () => {
redirect: 'error',
signal: controller.signal,
}),
aborted,
]);
const acknowledgement = response.ok ? await Promise.race([response.json(), aborted]) : null;
);
const acknowledgement = response.ok ? await raceAbort(response.json()) : null;
if (acknowledgement?.success !== true) {
throw new Error('Pulse did not acknowledge sign-out');
}