Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: end dashboard stats loading on stream failure and retry on refresh (#3930)
Kyle Mendell16b7b59d5e64
diff --git a/frontend/messages/en.json b/frontend/messages/en.jsonindex 05955e36c..7be87015c 100644--- a/frontend/messages/en.json+++ b/frontend/messages/en.json@@ -549,6 +549,8 @@"dashboard_all_environment_unavailable_description": "This environment is offline, pending, or otherwise unreachable right now.","dashboard_all_summary_unavailable": "Environment summary unavailable. {error}","dashboard_all_agent_incompatible": "Agent is running an older Arcane version and can't report dashboard data — upgrade the agent.",+ "stats_unavailable": "Live stats unavailable",+ "stats_stale": "Live stats aren't updating","containers": "Containers","containers_subtitle": "View and Manage your Containers","containers_recent": "Recent containers",diff --git a/frontend/src/lib/types/shared.ts b/frontend/src/lib/types/shared.tsindex 6237cefc6..c32e649e2 100644--- a/frontend/src/lib/types/shared.ts+++ b/frontend/src/lib/types/shared.ts@@ -277,3 +277,5 @@ export interface DashboardOverviewSummary {export interface DashboardEnvironmentCardState {environment: Environment;}++export type DashboardLiveStatsStatus = 'loading' | 'live' | 'stale' | 'unavailable' | 'denied';diff --git a/frontend/src/lib/utils/ws.ts b/frontend/src/lib/utils/ws.tsindex 328c47c4c..4b9df43b2 100644--- a/frontend/src/lib/utils/ws.ts+++ b/frontend/src/lib/utils/ws.ts@@ -21,6 +21,7 @@ export class ReconnectingWebSocket<T = unknown> {private readonly maxBackoff: number;private opts: ReconnectWSOptions<T>;private connecting = false;+ private generation = 0;private reconnectTimer: ReturnType<typeof setTimeout> | null = null;constructor(opts: ReconnectWSOptions<T>) {@@ -30,11 +31,8 @@ export class ReconnectingWebSocket<T = unknown> {}async connect() {- if (this.ws && !this.closed) {- this.close();- }+ this.close();this.closed = false;- this.attempt = 0;await this.connectOnce();}@@ -48,8 +46,10 @@ export class ReconnectingWebSocket<T = unknown> {this.ws = null;}+ const generation = ++this.generation;this.connecting = true;const urlResult = await tryCatch((async () => await this.opts.buildUrl())());+ if (generation !== this.generation || this.closed) return;if (urlResult.error !== null) {this.connecting = false;this.scheduleReconnect();@@ -132,6 +132,7 @@ export class ReconnectingWebSocket<T = unknown> {close() {this.closed = true;this.attempt = 0;+ this.generation++;if (this.reconnectTimer) {clearTimeout(this.reconnectTimer);@@ -147,6 +148,7 @@ export class ReconnectingWebSocket<T = unknown> {closeAndWait(timeoutMs = 2000) {this.closed = true;this.attempt = 0;+ this.generation++;if (this.reconnectTimer) {clearTimeout(this.reconnectTimer);diff --git a/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte b/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelteindex f28744c3b..22e3491f9 100644--- a/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte+++ b/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte@@ -22,6 +22,7 @@DashboardActionItemKind,DashboardEnvironmentCardState,DashboardEnvironmentOverview,+ DashboardLiveStatsStatus,SystemStats} from '#lib/types/shared.js';import type { Environment } from '#lib/types/environment.js';@@ -88,10 +89,13 @@type EnvironmentLiveStatsState = {stats: SystemStats | null;loading: boolean;- hasLoaded: boolean;+ failed: boolean;client: ReconnectingWebSocket<SystemStats> | null;+ deadline: ReturnType<typeof setTimeout> | null;};+ const LIVE_STATS_DEADLINE_MS = 10_000;+let isRefreshing = $state(false);let isPruneDialogOpen = $state(false);let pruneEnvironment = $state<DashboardEnvironmentOverview | null>(null);@@ -131,13 +135,38 @@return {stats: null,loading: true,- hasLoaded: false,- client: null+ failed: false,+ client: null,+ deadline: null};}+ function canLoadLiveStats(environment: Environment): boolean {+ return shouldLoadEnvironment(environment) && hasPermission('system:read', environment.id);+ }++ function clearLiveStatsDeadline(liveStatsState: EnvironmentLiveStatsState) {+ if (liveStatsState.deadline) {+ clearTimeout(liveStatsState.deadline);+ liveStatsState.deadline = null;+ }+ }++ function markLiveStatsFailed(liveStatsState: EnvironmentLiveStatsState) {+ clearLiveStatsDeadline(liveStatsState);+ liveStatsState.loading = false;+ liveStatsState.failed = true;+ }++ function startLiveStatsAttempt(liveStatsState: EnvironmentLiveStatsState) {+ clearLiveStatsDeadline(liveStatsState);+ liveStatsState.loading = liveStatsState.stats === null;+ liveStatsState.failed = liveStatsState.stats !== null && liveStatsState.failed;+ liveStatsState.deadline = setTimeout(() => markLiveStatsFailed(liveStatsState), LIVE_STATS_DEADLINE_MS);+ }+function ensureEnvironmentLiveStats(environment: Environment) {- if (!shouldLoadEnvironment(environment)) {+ if (!canLoadLiveStats(environment)) {removeEnvironmentLiveStats(environment.id);return;}@@ -155,32 +184,41 @@return;}- liveStatsState.loading = !liveStatsState.hasLoaded;+ startLiveStatsAttempt(liveStatsState);liveStatsState.client = createStatsWebSocket({getEnvId: () => environment.id,- onOpen: () => {- if (!liveStatsState.hasLoaded) {- liveStatsState.loading = true;- }- },onMessage: (stats) => {+ clearLiveStatsDeadline(liveStatsState);liveStatsState.stats = stats;- liveStatsState.hasLoaded = true;liveStatsState.loading = false;+ liveStatsState.failed = false;},onError: (error) => {console.error(`Stats websocket error for environment ${environment.id}:`, error);- }+ markLiveStatsFailed(liveStatsState);+ },+ onClose: () => markLiveStatsFailed(liveStatsState)});liveStatsState.client.connect();}+ function retryFailedLiveStats() {+ for (const liveStatsState of Object.values(liveStatsByEnvironmentId)) {+ if (!liveStatsState.failed || !liveStatsState.client) {+ continue;+ }+ startLiveStatsAttempt(liveStatsState);+ void liveStatsState.client.connect();+ }+ }+function removeEnvironmentLiveStats(environmentId: string) {const liveStatsState = liveStatsByEnvironmentId[environmentId];if (!liveStatsState) {return;}+ clearLiveStatsDeadline(liveStatsState);liveStatsState.client?.close();delete liveStatsByEnvironmentId[environmentId];}@@ -242,7 +280,14 @@.map((environment) => ({ environment }));});const loadableEnvironmentCards = $derived(environmentCards.filter(({ environment }) => shouldLoadEnvironment(environment)));- const loadableEnvironmentIds = $derived.by(() => new Set(loadableEnvironmentCards.map(({ environment }) => environment.id)));+ const liveStatsEnvironmentIds = $derived.by(+ () =>+ new Set(+ loadableEnvironmentCards+ .filter(({ environment }) => canLoadLiveStats(environment))+ .map(({ environment }) => environment.id)+ )+ );function resolveSnapshotErrorMessage(state: NonNullable<ReturnType<typeof dashboardStore.getEnvironmentState>>): string {if (state.errorCode === 'agent_incompatible') {@@ -332,11 +377,11 @@});$effect(() => {- const reachableEnvironmentIds = loadableEnvironmentIds;+ const activeEnvironmentIds = liveStatsEnvironmentIds;untrack(() => {for (const environmentId of Object.keys(liveStatsByEnvironmentId)) {- if (!reachableEnvironmentIds.has(environmentId)) {+ if (!activeEnvironmentIds.has(environmentId)) {removeEnvironmentLiveStats(environmentId);}}@@ -367,6 +412,7 @@async function refreshOverview() {isRefreshing = true;try {+ retryFailedLiveStats();await refreshAll();await dashboardStore.refresh();reloadVersion += 1;@@ -404,6 +450,23 @@return liveStatsByEnvironmentId[environmentId] ?? null;}+ function getLiveStatsStatus(environment: Environment): DashboardLiveStatsStatus {+ if (!shouldLoadEnvironment(environment)) {+ return 'live';+ }+ if (!hasPermission('system:read', environment.id)) {+ return 'denied';+ }+ const liveStatsState = getLiveStatsState(environment.id);+ if (!liveStatsState) {+ return 'loading';+ }+ if (liveStatsState.failed) {+ return liveStatsState.stats ? 'stale' : 'unavailable';+ }+ return liveStatsState.loading ? 'loading' : 'live';+ }+function canPruneEnvironment(item: DashboardEnvironmentOverview): boolean {return (canPruneInEnvironment(item.environment.id) &&@@ -488,6 +551,7 @@cpu: getCpuMetric(stats),memory: getMemoryMetric(stats),disk: getDiskMetric(stats),+ statsStatus: getLiveStatsStatus(environment),versionText: vInfo ? vInfo.displayVersion || vInfo.currentTag || vInfo.currentVersion || 'unknown' : null,updateAvailable: !!vInfo?.updateAvailable,useButton,@@ -756,15 +820,14 @@{@const environment = baseItem.environment}{@const overview = boardState.overviewById.get(environment.id) ?? baseItem}{@const isCurrent = currentEnvironmentId === environment.id}- {@const liveStatsState = getLiveStatsState(environment.id)}- {@const systemStats = liveStatsState?.stats ?? null}- {@const liveStatsLoading = liveStatsState?.loading ?? shouldLoadEnvironment(environment)}+ {@const systemStats = getLiveStatsState(environment.id)?.stats ?? null}+ {@const liveStatsStatus = getLiveStatsStatus(environment)}{@const [useButton, ...menuButtons] = getEnvironmentActionButtons(overview, isCurrent)}<DashboardEnvironmentCard{overview}{isCurrent}{systemStats}- {liveStatsLoading}+ {liveStatsStatus}snapshotLoading={isEnvironmentSnapshotLoading(environment.id)}{useButton}{menuButtons}diff --git a/frontend/src/routes/(app)/dashboard/dashboard-environment-card.svelte b/frontend/src/routes/(app)/dashboard/dashboard-environment-card.svelteindex 1ce35362d..e2f9f5006 100644--- a/frontend/src/routes/(app)/dashboard/dashboard-environment-card.svelte+++ b/frontend/src/routes/(app)/dashboard/dashboard-environment-card.svelte@@ -12,7 +12,7 @@import { CpuIcon, EnvironmentsIcon, GpuIcon, MemoryStickIcon, VolumesIcon } from '#lib/icons/index.js';import { m } from '#lib/paraglide/messages.js';import type { AppVersionInformation } from '#lib/types/settings.js';- import type { DashboardEnvironmentOverview, SystemStats } from '#lib/types/shared.js';+ import type { DashboardEnvironmentOverview, DashboardLiveStatsStatus, SystemStats } from '#lib/types/shared.js';import { cn } from '#lib/utils.js';import { isEnvironmentOnline } from '#lib/utils/docker.js';import {@@ -34,7 +34,7 @@overview,isCurrent,systemStats,- liveStatsLoading,+ liveStatsStatus,snapshotLoading,useButton,menuButtons,@@ -48,7 +48,7 @@overview: DashboardEnvironmentOverview;isCurrent: boolean;systemStats: SystemStats | null;- liveStatsLoading: boolean;+ liveStatsStatus: DashboardLiveStatsStatus;snapshotLoading: boolean;useButton?: ActionButton;menuButtons: ActionButton[];@@ -201,53 +201,68 @@{#if shouldLoadEnvironment(environment)}<div class="border-t border-border/60 pt-3">- <div class="grid grid-cols-1 gap-1 {gpuMetric !== null ? 'sm:grid-cols-2 lg:grid-cols-4' : 'sm:grid-cols-3'}">- {#if liveStatsLoading}- {#each [1, 2, 3] as tile (tile)}- <div class="min-w-0 px-2.5 py-2.5">- <div class="flex items-start justify-between gap-2">- <Skeleton class="h-3 w-20" />- <Skeleton class="h-5 w-12" />+ {#if liveStatsStatus === 'denied'}+ <p class="px-2.5 text-sm text-muted-foreground">{m.common_access_denied()}</p>+ {:else}+ <div+ class={cn(+ 'grid grid-cols-1 gap-1',+ gpuMetric !== null ? 'sm:grid-cols-2 lg:grid-cols-4' : 'sm:grid-cols-3',+ liveStatsStatus === 'stale' && 'opacity-60'+ )}+ >+ {#if liveStatsStatus === 'loading'}+ {#each [1, 2, 3] as tile (tile)}+ <div class="min-w-0 px-2.5 py-2.5">+ <div class="flex items-start justify-between gap-2">+ <Skeleton class="h-3 w-20" />+ <Skeleton class="h-5 w-12" />+ </div>+ <Skeleton class="mt-2 h-3 w-24" />+ <Skeleton class="mt-3 h-1.5 w-full" /></div>- <Skeleton class="mt-2 h-3 w-24" />- <Skeleton class="mt-3 h-1.5 w-full" />- </div>- {/each}- {:else}- <DashboardMetricTile- title={m.cpu_usage()}- icon={CpuIcon}- value={formatPercent(cpuMetric)}- label={getCpuMetricLabel(systemStats)}- meterValue={cpuMetric}- />- <DashboardMetricTile- title={m.memory_usage()}- icon={MemoryStickIcon}- value={formatPercent(memoryMetric)}- label={getCapacityLabel(systemStats?.memoryUsage, systemStats?.memoryTotal)}- labelClass="truncate"- meterValue={memoryMetric}- />- <DashboardMetricTile- title={m.dashboard_meter_disk()}- icon={VolumesIcon}- value={formatPercent(diskMetric)}- label={getCapacityLabel(systemStats?.diskUsage, systemStats?.diskTotal)}- labelClass="truncate"- meterValue={diskMetric}- />- {#if gpuMetric !== null}+ {/each}+ {:else}<DashboardMetricTile- title={m.dashboard_meter_gpu()}- icon={GpuIcon}- value={formatPercent(gpuMetric)}- label={getGpuMetricLabel(systemStats)}- meterValue={gpuMetric}+ title={m.cpu_usage()}+ icon={CpuIcon}+ value={formatPercent(cpuMetric)}+ label={getCpuMetricLabel(systemStats)}+ meterValue={cpuMetric}/>+ <DashboardMetricTile+ title={m.memory_usage()}+ icon={MemoryStickIcon}+ value={formatPercent(memoryMetric)}+ label={getCapacityLabel(systemStats?.memoryUsage, systemStats?.memoryTotal)}+ labelClass="truncate"+ meterValue={memoryMetric}+ />+ <DashboardMetricTile+ title={m.dashboard_meter_disk()}+ icon={VolumesIcon}+ value={formatPercent(diskMetric)}+ label={getCapacityLabel(systemStats?.diskUsage, systemStats?.diskTotal)}+ labelClass="truncate"+ meterValue={diskMetric}+ />+ {#if gpuMetric !== null}+ <DashboardMetricTile+ title={m.dashboard_meter_gpu()}+ icon={GpuIcon}+ value={formatPercent(gpuMetric)}+ label={getGpuMetricLabel(systemStats)}+ meterValue={gpuMetric}+ />+ {/if}{/if}+ </div>+ {#if liveStatsStatus === 'unavailable'}+ <p class="mt-2 px-2.5 text-xs text-muted-foreground">{m.stats_unavailable()}</p>+ {:else if liveStatsStatus === 'stale'}+ <p class="mt-2 px-2.5 text-xs text-amber-600 dark:text-amber-400">{m.stats_stale()}</p>{/if}- </div>+ {/if}</div>{/if}diff --git a/frontend/src/routes/(app)/dashboard/dashboard-environments-table.svelte b/frontend/src/routes/(app)/dashboard/dashboard-environments-table.svelteindex 58cca0971..e16b07fe3 100644--- a/frontend/src/routes/(app)/dashboard/dashboard-environments-table.svelte+++ b/frontend/src/routes/(app)/dashboard/dashboard-environments-table.svelte@@ -1,6 +1,7 @@<script lang="ts" module>import type { ActionButton } from '#lib/components/action-button-group/index.js';import type { Environment } from '#lib/types/environment.js';+ import type { DashboardLiveStatsStatus } from '#lib/types/shared.js';export interface EnvironmentTableRow {environment: Environment;@@ -15,6 +16,7 @@cpu: number | null;memory: number | null;disk: number | null;+ statsStatus: DashboardLiveStatsStatus;versionText: string | null;updateAvailable: boolean;useButton?: ActionButton;@@ -55,11 +57,18 @@</a>{/snippet}-{#snippet metric(value: number | null, variant: MetricRingVariant)}- {#if value === null || Number.isNaN(value)}- <span class="text-xs text-muted-foreground">—</span>+{#snippet metric(value: number | null, variant: MetricRingVariant, status: DashboardLiveStatsStatus)}+ {#if status === 'loading'}+ <Skeleton class="ml-auto h-4 w-12" />+ {:else if status === 'denied'}+ <span class="text-xs text-muted-foreground" title={m.common_access_denied()}>—</span>+ {:else if value === null || Number.isNaN(value)}+ <span class="text-xs text-muted-foreground" title={status === 'unavailable' ? m.stats_unavailable() : undefined}>—</span>{:else}- <span class="flex items-center justify-end gap-2">+ <span+ class={cn('flex items-center justify-end gap-2', status === 'stale' && 'opacity-60')}+ title={status === 'stale' ? m.stats_stale() : undefined}+ ><MetricRing percent={value} {variant} /><span class="text-xs font-medium text-foreground tabular-nums">{Math.round(value)}%</span></span>@@ -119,9 +128,9 @@{/if}</Table.Cell>{/if}- <Table.Cell class="text-right">{@render metric(row.cpu, 'cpu')}</Table.Cell>- <Table.Cell class="text-right">{@render metric(row.memory, 'memory')}</Table.Cell>- <Table.Cell class="text-right">{@render metric(row.disk, 'disk')}</Table.Cell>+ <Table.Cell class="text-right">{@render metric(row.cpu, 'cpu', row.statsStatus)}</Table.Cell>+ <Table.Cell class="text-right">{@render metric(row.memory, 'memory', row.statsStatus)}</Table.Cell>+ <Table.Cell class="text-right">{@render metric(row.disk, 'disk', row.statsStatus)}</Table.Cell>{/if}<Table.Cell class="text-right"><div class="flex items-center justify-end gap-1">diff --git a/tests/spec/dashboard-system-stats.spec.ts b/tests/spec/dashboard-system-stats.spec.tsindex 813f0e1a2..0c59a74ee 100644--- a/tests/spec/dashboard-system-stats.spec.ts+++ b/tests/spec/dashboard-system-stats.spec.ts@@ -16,89 +16,134 @@ const mockedStats = {gpus: []};-async function mockDashboardStatsWebSocket(page: Page) {- await page.addInitScript((statsPayload) => {- const browserWindow = globalThis as typeof globalThis & {- WebSocket: any;- EventTarget: any;- Event: any;- MessageEvent: any;- CloseEvent: any;- };- const NativeWebSocket = browserWindow.WebSocket;- const statsPathPattern = /\/api\/environments\/[^/]+\/ws\/system\/stats(?:\?.*)?$/;-- class MockStatsWebSocket extends browserWindow.EventTarget {- static CONNECTING = 0;- static OPEN = 1;- static CLOSING = 2;- static CLOSED = 3;-- url: string;- readyState = MockStatsWebSocket.CONNECTING;- bufferedAmount = 0;- extensions = '';- protocol = '';- binaryType = 'blob';- onopen: ((event: unknown) => void) | null = null;- onmessage: ((event: unknown) => void) | null = null;- onerror: ((event: unknown) => void) | null = null;- onclose: ((event: unknown) => void) | null = null;-- constructor(url: string | URL) {- super();- this.url = String(url);-- queueMicrotask(() => {- if (this.readyState !== MockStatsWebSocket.CONNECTING) return;- this.readyState = MockStatsWebSocket.OPEN;- const openEvent = new browserWindow.Event('open');- this.dispatchEvent(openEvent);- this.onopen?.(openEvent);-- const messageEvent = new browserWindow.MessageEvent('message', {- data: JSON.stringify(statsPayload)- });- this.dispatchEvent(messageEvent);- this.onmessage?.(messageEvent);- });- }+type StatsMockOptions = {+ deliverAfterMs?: number;+ failConnections?: boolean;+ closeAfterMessage?: boolean;+};- send(_data?: string | ArrayBufferLike | Blob | ArrayBufferView) {}+async function mockDashboardStatsWebSocket(page: Page, options: StatsMockOptions = {}) {+ await page.addInitScript(+ ({ statsPayload, options }) => {+ const browserWindow = globalThis as typeof globalThis & {+ WebSocket: any;+ EventTarget: any;+ Event: any;+ MessageEvent: any;+ CloseEvent: any;+ __arcaneStatsMock: { failConnections: boolean };+ };+ browserWindow.__arcaneStatsMock = { failConnections: options.failConnections ?? false };+ const NativeWebSocket = browserWindow.WebSocket;+ const statsPathPattern = /\/api\/environments\/[^/]+\/ws\/system\/stats(?:\?.*)?$/;++ class MockStatsWebSocket extends browserWindow.EventTarget {+ static CONNECTING = 0;+ static OPEN = 1;+ static CLOSING = 2;+ static CLOSED = 3;++ url: string;+ readyState = MockStatsWebSocket.CONNECTING;+ bufferedAmount = 0;+ extensions = '';+ protocol = '';+ binaryType = 'blob';+ onopen: ((event: unknown) => void) | null = null;+ onmessage: ((event: unknown) => void) | null = null;+ onerror: ((event: unknown) => void) | null = null;+ onclose: ((event: unknown) => void) | null = null;++ constructor(url: string | URL) {+ super();+ this.url = String(url);++ if (browserWindow.__arcaneStatsMock.failConnections) {+ queueMicrotask(() => {+ if (this.readyState !== MockStatsWebSocket.CONNECTING) return;+ const errorEvent = new browserWindow.Event('error');+ this.dispatchEvent(errorEvent);+ this.onerror?.(errorEvent);+ this.close(1006, '');+ });+ return;+ }++ const deliver = () => {+ if (this.readyState !== MockStatsWebSocket.CONNECTING) return;+ this.readyState = MockStatsWebSocket.OPEN;+ const openEvent = new browserWindow.Event('open');+ this.dispatchEvent(openEvent);+ this.onopen?.(openEvent);++ const messageEvent = new browserWindow.MessageEvent('message', {+ data: JSON.stringify(statsPayload)+ });+ this.dispatchEvent(messageEvent);+ this.onmessage?.(messageEvent);++ if (options.closeAfterMessage) {+ browserWindow.__arcaneStatsMock.failConnections = true;+ this.close(1006, '');+ }+ };++ if (options.deliverAfterMs) {+ setTimeout(deliver, options.deliverAfterMs);+ } else {+ queueMicrotask(deliver);+ }+ }- close(code = 1000, reason = '') {- if (this.readyState === MockStatsWebSocket.CLOSED) return;- this.readyState = MockStatsWebSocket.CLOSED;- const closeEvent = new browserWindow.CloseEvent('close', { code, reason, wasClean: true });- this.dispatchEvent(closeEvent);- this.onclose?.(closeEvent);- }- }+ send(_data?: string | ArrayBufferLike | Blob | ArrayBufferView) {}- const PatchedWebSocket = function (- this: unknown,- url: string | URL,- protocols?: string | string[]- ) {- const urlString = String(url);- if (statsPathPattern.test(urlString)) {- return new MockStatsWebSocket(urlString);+ close(code = 1000, reason = '') {+ if (this.readyState === MockStatsWebSocket.CLOSED) return;+ this.readyState = MockStatsWebSocket.CLOSED;+ const closeEvent = new browserWindow.CloseEvent('close', {+ code,+ reason,+ wasClean: true+ });+ this.dispatchEvent(closeEvent);+ this.onclose?.(closeEvent);+ }}- return protocols === undefined- ? new NativeWebSocket(url)- : new NativeWebSocket(url, protocols);- } as unknown as typeof WebSocket;-- Object.defineProperties(PatchedWebSocket, {- CONNECTING: { value: NativeWebSocket.CONNECTING },- OPEN: { value: NativeWebSocket.OPEN },- CLOSING: { value: NativeWebSocket.CLOSING },- CLOSED: { value: NativeWebSocket.CLOSED }- });- PatchedWebSocket.prototype = NativeWebSocket.prototype;- browserWindow.WebSocket = PatchedWebSocket;- }, mockedStats);+ const PatchedWebSocket = function (+ this: unknown,+ url: string | URL,+ protocols?: string | string[]+ ) {+ const urlString = String(url);+ if (statsPathPattern.test(urlString)) {+ return new MockStatsWebSocket(urlString);+ }+ return protocols === undefined+ ? new NativeWebSocket(url)+ : new NativeWebSocket(url, protocols);+ } as unknown as typeof WebSocket;++ Object.defineProperties(PatchedWebSocket, {+ CONNECTING: { value: NativeWebSocket.CONNECTING },+ OPEN: { value: NativeWebSocket.OPEN },+ CLOSING: { value: NativeWebSocket.CLOSING },+ CLOSED: { value: NativeWebSocket.CLOSED }+ });+ PatchedWebSocket.prototype = NativeWebSocket.prototype;++ browserWindow.WebSocket = PatchedWebSocket;+ },+ { statsPayload: mockedStats, options }+ );+}++async function allowStatsConnections(page: Page) {+ await page.evaluate(() => {+ (+ globalThis as typeof globalThis & { __arcaneStatsMock: { failConnections: boolean } }+ ).__arcaneStatsMock.failConnections = false;+ });}async function mockInputCapabilities(page: Page, hoverNone: boolean, maxTouchPoints: number) {@@ -182,6 +227,60 @@ test.describe('Dashboard system stats websocket', () => {await expect(page.locator('main').getByText('Local Docker', { exact: true })).toBeVisible();});+ test('keeps skeletons until the deadline when the stream opens without a sample', async ({+ page+ }) => {+ await mockDashboardStatsWebSocket(page, { deliverAfterMs: 12_000 });++ await page.goto(defaultDashboardPath);+ await page.waitForLoadState('load');+ await expect(page.getByRole('button', { name: 'Card view', exact: true })).toBeVisible();++ await page.waitForTimeout(5_000);+ await expect(page.getByText('Live stats unavailable', { exact: true })).toHaveCount(0);+ await expect(page.getByText('12.3%', { exact: true })).toHaveCount(0);++ await expect(page.getByText('Live stats unavailable', { exact: true })).toBeVisible({+ timeout: 10_000+ });+ await expect(page.getByText('12.3%', { exact: true })).toHaveCount(0);++ await expect(page.getByText('12.3%', { exact: true })).toBeVisible({ timeout: 10_000 });+ await expect(page.getByText('Live stats unavailable', { exact: true })).toHaveCount(0);+ });++ test('shows unavailable metrics on connection failure and recovers on refresh', async ({+ page+ }) => {+ await mockDashboardStatsWebSocket(page, { failConnections: true });++ await page.goto(defaultDashboardPath);+ await page.waitForLoadState('load');+ await expect(page.getByRole('button', { name: 'Card view', exact: true })).toBeVisible();++ await expect(page.getByText('Live stats unavailable', { exact: true })).toBeVisible();+ await expect(page.getByText('12.3%', { exact: true })).toHaveCount(0);++ await allowStatsConnections(page);+ await page.getByRole('button', { name: 'Refresh', exact: true }).click();++ await expect(page.getByText('12.3%', { exact: true })).toBeVisible();+ await expect(page.getByText('Live stats unavailable', { exact: true })).toHaveCount(0);+ });++ test('keeps the last sample and flags it stale after the stream disconnects', async ({+ page+ }) => {+ await mockDashboardStatsWebSocket(page, { closeAfterMessage: true });++ await page.goto(defaultDashboardPath);+ await page.waitForLoadState('load');+ await expect(page.getByRole('button', { name: 'Card view', exact: true })).toBeVisible();++ await expect(page.getByText('12.3%', { exact: true })).toBeVisible();+ await expect(page.getByText("Live stats aren't updating", { exact: true })).toBeVisible();+ });+test('loads dashboard content without eagerly loading docker info', async ({ page }) => {await mockDashboardStatsWebSocket(page);const requestPaths = collectDashboardRequestPaths(page);