feat(dashboard): persist one overview time range (#7277)

Consolidate the six overview range selectors into a single translated action-bar control beside Xray Metrics. Persist the validated selection per browser origin and panel base path with a safe 2m fallback, including unavailable storage. Restore the preference before history fetching and retain live status sampling while viewing longer ranges.

Avoid overlapping delayed live-history seeds, track sampled scope epochs, use separate scoped/unscoped boundaries and reject stale responses. Cover scope transitions, clock skew bounds, storage failures and range propagation. Update English and Persian documentation without changing schema or backend API contracts.

Validation: all 12 CI jobs and Docs CI passed on 2d3992766b277974f2cb4b4b44af1a6a456653dd; frontend 265 files / 2,330 tests, including 12 global-range, 11 ranged-history and 8 container-history cases. Browser restart and responsive/RTL checks reported by author, not independently rerun. Persistence is browser-local; arbitrary clock skew cannot guarantee complete live history.

Closes #7276
This commit is contained in:
Hamed
2026-12-03 01:18:05 +03:30
committed by GitHub
parent 1e1b32247e
commit b351b08601
16 changed files with 527 additions and 119 deletions
+5 -1
View File
@@ -1,5 +1,5 @@
import { act, renderHook, waitFor } from '@testing-library/react';
import { beforeEach, expect, it, vi } from 'vitest';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { Status } from '@/models/status';
import { useOverviewHistory } from '@/pages/index/useOverviewHistory';
@@ -12,8 +12,11 @@ vi.mock('@/utils', async (importOriginal) => {
beforeEach(() => {
get.mockReset();
vi.spyOn(Date, 'now').mockReturnValue(10_000);
});
afterEach(() => vi.restoreAllMocks());
it('keeps missing samples out of trends and resets a changed metric scope', async () => {
get.mockImplementation(async (path: string) => ({
success: true,
@@ -37,6 +40,7 @@ it('keeps missing samples out of trends and resets a changed metric scope', asyn
expect(result.current.series.cpu).toEqual([10, 20]);
rerender({ status: new Status({ cpu: 50 }) });
expect(result.current.series.cpu).toEqual([50]);
await act(async () => undefined);
});
it('ignores a legacy seed that resolves after the scope changes', async () => {
@@ -39,8 +39,6 @@ describe('network traffic status', () => {
down={[200]}
labels={['12:00']}
isMobile={false}
range={2}
onRangeChange={() => undefined}
/>,
);
expect(
@@ -0,0 +1,150 @@
import { fireEvent, screen, waitFor, within } from '@testing-library/react';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import IndexPage from '@/pages/index/IndexPage';
import { renderWithProviders } from './test-utils';
const { get, chart } = vi.hoisted(() => ({ get: vi.fn(), chart: vi.fn() }));
vi.mock('@/layouts/AppSidebar', () => ({ default: () => null }));
vi.mock('@/components/sponsor/SponsorSlot', () => ({ default: () => null }));
vi.mock('@/components/viz', async (importOriginal) => {
const original = await importOriginal<typeof import('@/components/viz')>();
return {
...original,
Sparkline: ({ data, data2 }: { data: number[]; data2?: number[] }) => {
chart(data, data2);
return null;
},
};
});
vi.mock('@/api/queries/useStatusQuery', async () => {
const { Status } = await import('@/models/status');
const status = new Status({ cpu: 12, mem: { current: 10, total: 100 } });
return { useStatusQuery: () => ({ status, fetched: true, fetchError: '', refresh: vi.fn() }) };
});
vi.mock('@/utils', async (importOriginal) => {
const original = await importOriginal<typeof import('@/utils')>();
return { ...original, HttpUtil: { get, post: vi.fn().mockResolvedValue({ success: false }) } };
});
const key = '3x-ui:overview-range:/test/';
const rangeControl = () => screen.getByRole('combobox', { name: 'Time range' });
const historyRequests = () =>
get.mock.calls
.map(([path]) => String(path))
.filter((path) => /\/(overviewHistory|history)\//.test(path));
beforeEach(() => {
vi.stubGlobal('X_UI_BASE_PATH', '/test/');
window.localStorage.clear();
get.mockReset();
chart.mockClear();
get.mockImplementation(async (path: string) => {
if (path.includes('/overviewHistory/')) {
const range = Number(path.split('/').at(-1));
return {
success: true,
obj: Object.fromEntries(
['cpu', 'mem', 'swap', 'diskUsage', 'netUp', 'netDown', 'tcpCount', 'udpCount'].map(
(metric, i) => [metric, [{ t: 1, v: range + i }]],
),
),
};
}
return { success: true, obj: [] };
});
});
afterEach(() => {
window.localStorage.clear();
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
it('uses one action-bar selector to update all chart summaries and save the range', async () => {
renderWithProviders(<IndexPage />);
const control = rangeControl();
const metrics = screen.getByRole('button', { name: 'Xray Metrics' });
expect(metrics.closest('.ov-bar')?.contains(control)).toBe(true);
fireEvent.mouseDown(control);
fireEvent.click(await screen.findByRole('option', { name: '30m' }));
await waitFor(() => expect(window.localStorage.getItem(key)).toBe('30'));
expect(
await within(screen.getByRole('group', { name: 'CPU' })).findAllByText('30%'),
).toHaveLength(2);
expect(
await within(screen.getByRole('group', { name: 'RAM' })).findAllByText('31%'),
).toHaveLength(2);
expect(historyRequests()).toContain('/panel/api/server/overviewHistory/30');
for (const value of [30, 31, 32, 33]) {
expect(chart).toHaveBeenCalledWith([value], undefined);
}
expect(chart).toHaveBeenCalledWith([34], [35]);
expect(chart).toHaveBeenCalledWith([36], [37]);
});
it.each([5, 30, 60, 360, 720])(
'restores %im on mount without querying the default history window',
async (range) => {
window.localStorage.setItem(key, String(range));
const first = renderWithProviders(<IndexPage />);
await waitFor(() =>
expect(historyRequests()).toEqual(['/panel/api/server/overviewHistory/' + range]),
);
first.unmount();
get.mockClear();
renderWithProviders(<IndexPage />);
await waitFor(() =>
expect(historyRequests()).toEqual(['/panel/api/server/overviewHistory/' + range]),
);
},
);
it.each([null, '2', '90', 'bad'])('uses the live range for %s', async (saved) => {
if (saved !== null) window.localStorage.setItem(key, saved);
window.localStorage.setItem('3x-ui:overview-range:/another-panel/', '720');
renderWithProviders(<IndexPage />);
expect(rangeControl()).toBeTruthy();
await waitFor(() => expect(historyRequests()).toContain('/panel/api/server/history/cpu/2'));
expect(historyRequests().some((path) => path.includes('/overviewHistory/'))).toBe(false);
});
it('renders even when storage is blocked', async () => {
vi.spyOn(Storage.prototype, 'getItem').mockImplementation((name) => {
if (name === key) throw new DOMException('Storage blocked', 'SecurityError');
return null;
});
renderWithProviders(<IndexPage />);
expect(rangeControl()).toBeTruthy();
await waitFor(() => expect(historyRequests()).toContain('/panel/api/server/history/cpu/2'));
});
it('applies a new range and updates its charts when saving the preference is blocked', async () => {
window.localStorage.setItem(key, '30');
const originalSetItem = Storage.prototype.setItem;
const setItem = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(function (
this: Storage,
name,
value,
) {
if (name === key) throw new DOMException('Storage blocked', 'QuotaExceededError');
originalSetItem.call(this, name, value);
});
renderWithProviders(<IndexPage />);
await waitFor(() => expect(historyRequests()).toEqual(['/panel/api/server/overviewHistory/30']));
fireEvent.mouseDown(rangeControl());
fireEvent.click(await screen.findByRole('option', { name: '1h' }));
expect(setItem).toHaveBeenCalledWith(key, '60');
expect(window.localStorage.getItem(key)).toBe('30');
expect(
await within(screen.getByRole('group', { name: 'CPU' })).findAllByText('60%'),
).toHaveLength(2);
expect(historyRequests()).toEqual([
'/panel/api/server/overviewHistory/30',
'/panel/api/server/overviewHistory/60',
]);
});
@@ -2,7 +2,8 @@ import { act, renderHook, waitFor } from '@testing-library/react';
import { beforeEach, expect, it, vi } from 'vitest';
import { Status } from '@/models/status';
import { useOverviewHistory } from '@/pages/index/useOverviewHistory';
import { mean, peak, useOverviewHistory } from '@/pages/index/useOverviewHistory';
import { TimeFormatter } from '@/utils';
const { get } = vi.hoisted(() => ({ get: vi.fn() }));
vi.mock('@/utils', async (importOriginal) => {
@@ -110,7 +111,232 @@ it('keeps sampling the live trend while a longer range is shown', async () => {
);
await waitFor(() => expect(result.current.series.cpu).toEqual([90]));
rerender({ status: new Status({ cpu: 12 }), bucket: 720 });
rerender({ status: new Status({ cpu: 13 }), bucket: 2 });
await act(async () => rerender({ status: new Status({ cpu: 13 }), bucket: 2 }));
expect(result.current.series.cpu).toEqual([11, 12, 13]);
});
it('only seeds buckets older than the live samples collected while a longer range was open', async () => {
const now = vi.spyOn(Date, 'now').mockReturnValue(101_000);
try {
get.mockImplementation(async (path: string) => ({
success: true,
obj: ranged(path)
? rollups(90)
: [
{ t: 96, v: 20 },
{ t: 98, v: 30 },
{ t: 100, v: 91 },
{ t: 102, v: 92 },
{ t: 104, v: 93 },
],
}));
const { result, rerender } = renderHook(
({ status, bucket }) => useOverviewHistory(status, true, bucket),
{ initialProps: { status: new Status({ cpu: 11 }), bucket: 60 } },
);
now.mockReturnValue(103_000);
rerender({ status: new Status({ cpu: 12 }), bucket: 60 });
now.mockReturnValue(105_000);
rerender({ status: new Status({ cpu: 13 }), bucket: 2 });
await waitFor(() => expect(result.current.series.cpu).toEqual([20, 30, 11, 12, 13]));
expect(result.current.labels).toHaveLength(5);
} finally {
now.mockRestore();
}
});
it('seeds a changed resource scope only up to its first status sample', async () => {
const now = vi.spyOn(Date, 'now').mockReturnValue(101_000);
try {
get.mockResolvedValue({
success: true,
obj: [{ t: 98, v: 20 }],
});
const { result, rerender } = renderHook(({ status }) => useOverviewHistory(status, true, 2), {
initialProps: { status: new Status({ cpu: 11, resourceScope: 'host' }) },
});
await waitFor(() => expect(result.current.series.cpu).toEqual([20, 11]));
now.mockReturnValue(111_000);
get.mockClear();
get.mockResolvedValue({
success: true,
obj: [
{ t: 108, v: 30 },
{ t: 110, v: 99 },
],
});
rerender({ status: new Status({ cpu: 12, resourceScope: 'container' }) });
await waitFor(() => expect(result.current.series.cpu).toEqual([30, 12]));
expect(get.mock.calls.map(([path]) => path)).toEqual([
'/panel/api/server/history/cpu/2',
'/panel/api/server/history/swap/2',
]);
} finally {
now.mockRestore();
}
});
const liveRequests = () =>
get.mock.calls.map(([path]) => String(path)).filter((path) => path.includes('/history/'));
function sample(resourceScope: string, cpu: number, swap: number, up: number) {
return new Status({
resourceScope,
cpu,
swap: { current: swap, total: 100 },
netIO: { up, down: 0 },
});
}
it('reseeds CPU and SWAP after sampling A → B → A while the live seed is disabled', async () => {
const now = vi.spyOn(Date, 'now').mockReturnValue(101_000);
try {
get.mockResolvedValue({ success: true, obj: [{ t: 98, v: 7 }] });
const { result, rerender } = renderHook(
({ status, bucket }) => useOverviewHistory(status, true, bucket),
{ initialProps: { status: sample('host', 11, 15, 8), bucket: 2 } },
);
await waitFor(() => expect(result.current.series.cpu).toEqual([7, 11]));
get.mockClear();
get.mockImplementation(async (path: string) => ({
success: true,
obj: ranged(path)
? rollups(90)
: [
{ t: 104, v: path.includes('/cpu/') ? 24 : 32 },
{ t: 108, v: 99 },
],
}));
now.mockReturnValue(105_000);
rerender({ status: sample('container', 41, 42, 9), bucket: 30 });
now.mockReturnValue(109_000);
const host = sample('host', 20, 36, 10);
rerender({ status: host, bucket: 30 });
expect(liveRequests()).toEqual([]);
rerender({ status: host, bucket: 2 });
await waitFor(() => expect(result.current.series.cpu).toEqual([24, 20]));
expect(result.current.series.swap).toEqual([32, 36]);
expect(result.current.series.netUp).toEqual([7, 8, 9, 10]);
expect(result.current.labels).toHaveLength(4);
expect(liveRequests()).toEqual([
'/panel/api/server/history/cpu/2',
'/panel/api/server/history/swap/2',
]);
} finally {
now.mockRestore();
}
});
it('seeds the first live visit from separate CPU/SWAP and unscoped cutoffs', async () => {
const now = vi.spyOn(Date, 'now').mockReturnValue(101_000);
try {
get.mockImplementation(async (path: string) => ({
success: true,
obj: ranged(path)
? rollups(90)
: [
{ t: 104, v: 88 },
{ t: 98, v: 7 },
{ t: 102, v: 24 },
{ t: 100, v: 20 },
{ t: 104, v: 28 },
{ t: 106, v: 99 },
{ t: 108, v: 99 },
],
}));
const { result, rerender } = renderHook(
({ status, bucket }) => useOverviewHistory(status, true, bucket),
{ initialProps: { status: sample('host', 11, 15, 8), bucket: 30 } },
);
now.mockReturnValue(107_000);
rerender({ status: sample('container', 30, 40, 9), bucket: 30 });
expect(liveRequests()).toEqual([]);
now.mockReturnValue(109_000);
rerender({ status: sample('container', 41, 43, 10), bucket: 2 });
await waitFor(() => expect(result.current.series.cpu).toEqual([7, 20, 24, 28, 30, 41]));
expect(result.current.series.swap).toEqual([7, 20, 24, 28, 40, 43]);
expect(mean(result.current.series.cpu)).toBe(25);
expect(peak(result.current.series.swap)).toBe(43);
expect(result.current.series.netUp).toEqual([7, 8, 9, 10]);
expect(result.current.labels).toEqual([98, 101, 107, 109].map(TimeFormatter.formatClock));
expect(liveRequests()).toHaveLength(metricKeys.length);
} finally {
now.mockRestore();
}
});
it('discards late live and ranged responses through rapid range and scope changes', async () => {
const now = vi.spyOn(Date, 'now').mockReturnValue(101_000);
try {
let releaseLive!: (msg: { success: boolean; obj: { t: number; v: number }[] }) => void;
const oldLive = new Promise<{ success: boolean; obj: { t: number; v: number }[] }>(
(resolve) => {
releaseLive = resolve;
},
);
let releaseRanged!: (msg: { success: boolean; obj: Rollups }) => void;
const oldRanged = new Promise<{ success: boolean; obj: Rollups }>((resolve) => {
releaseRanged = resolve;
});
get.mockReturnValue(oldLive);
const { result, rerender } = renderHook(
({ status, bucket }) => useOverviewHistory(status, true, bucket),
{ initialProps: { status: sample('host', 11, 15, 8), bucket: 2 } },
);
now.mockReturnValue(105_000);
get.mockClear();
get.mockReturnValue(oldRanged);
rerender({ status: sample('container', 90, 91, 9), bucket: 30 });
now.mockReturnValue(107_000);
get.mockResolvedValue({ success: true, obj: rollups(44) });
const host = sample('host', 20, 36, 10);
rerender({ status: host, bucket: 60 });
await waitFor(() => expect(result.current.series.cpu).toEqual([44]));
expect(liveRequests()).toEqual([]);
await act(async () => releaseRanged({ success: true, obj: rollups(99) }));
expect(result.current.series.cpu).toEqual([44]);
get.mockResolvedValue({ success: true, obj: [{ t: 98, v: 7 }] });
rerender({ status: host, bucket: 2 });
await waitFor(() => expect(result.current.series.cpu).toEqual([7, 20]));
await act(async () => releaseLive({ success: true, obj: [{ t: 96, v: 99 }] }));
expect(result.current.series.cpu).toEqual([7, 20]);
expect(result.current.series.swap).toEqual([7, 36]);
expect(result.current.series.netUp).toEqual([7, 8, 9, 10]);
expect(result.current.labels).toHaveLength(4);
} finally {
now.mockRestore();
}
});
it.each([
['ahead', 2_300],
['behind', 1_700],
] as const)(
'keeps live history ordered and bounded when the server clock is far %s',
async (_, serverTime) => {
const now = vi.spyOn(Date, 'now').mockReturnValue(2_001_000);
try {
get.mockResolvedValue({ success: true, obj: [{ t: serverTime, v: 99 }] });
const sampledHost = sample('host', 20, 36, 10);
const { result } = renderHook(() => useOverviewHistory(sampledHost, true));
await act(async () => undefined);
expect(liveRequests()).toHaveLength(metricKeys.length);
expect(result.current.series.cpu).toEqual([20]);
expect(result.current.series.swap).toEqual([36]);
expect(result.current.series.netUp).toEqual([10]);
expect(result.current.labels).toEqual([TimeFormatter.formatClock(2_001)]);
} finally {
now.mockRestore();
}
},
);
@@ -25,6 +25,8 @@ function renderBar(
panelVersion="v3.10.1"
latestVersion="v3.10.1"
updateAvailable={false}
historyRange={2}
onHistoryRangeChange={() => undefined}
onStopXray={onStopXray}
onRestartXray={onRestartXray}
onOpenLogs={noop}
@@ -21,6 +21,8 @@ describe('OverviewActionBar update tag', () => {
panelVersion="v3.10.1"
latestVersion="v3.10.2"
updateAvailable
historyRange={2}
onHistoryRangeChange={() => undefined}
onStopXray={noop}
onRestartXray={noop}
onOpenLogs={noop}