onChange(next as OverviewRange)}
- />
+
+ {label}
+
+ aria-label={label}
+ className="ov-range-select"
+ size="small"
+ value={value}
+ options={OPTIONS}
+ virtual={false}
+ onChange={(next) => onChange(next)}
+ />
+
);
}
diff --git a/frontend/src/pages/index/ThroughputCard.tsx b/frontend/src/pages/index/ThroughputCard.tsx
index 29d9ee24c..76799461f 100644
--- a/frontend/src/pages/index/ThroughputCard.tsx
+++ b/frontend/src/pages/index/ThroughputCard.tsx
@@ -7,8 +7,6 @@ import { SizeFormatter } from '@/utils';
import { Sparkline } from '@/components/viz';
import type { Status } from '@/models/status';
import { mean, peak } from './useOverviewHistory';
-import OverviewRangeSelect from './OverviewRangeSelect';
-import type { OverviewRange } from './OverviewRangeSelect';
interface ThroughputCardProps {
status: Status;
@@ -16,8 +14,6 @@ interface ThroughputCardProps {
down: number[];
labels: string[];
isMobile: boolean;
- range: OverviewRange;
- onRangeChange: (range: OverviewRange) => void;
}
export default function ThroughputCard({
@@ -26,8 +22,6 @@ export default function ThroughputCard({
down,
labels,
isMobile,
- range,
- onRangeChange,
}: ThroughputCardProps) {
const { t } = useTranslation();
const { token } = theme.useToken();
@@ -83,9 +77,6 @@ export default function ThroughputCard({
-
-
-
void;
}
-const ignoreRangeChange = () => undefined;
-
export default function VitalTile({
available = true,
icon,
@@ -35,8 +29,6 @@ export default function VitalTile({
footRight,
data,
isMobile,
- range = 2,
- onRangeChange = ignoreRangeChange,
}: VitalTileProps) {
const { token } = theme.useToken();
const labelId = useId();
@@ -74,9 +66,6 @@ export default function VitalTile({
{available ? footRight : '—'}
-
-
-
(emptyWindow);
+interface LiveHistoryWindow extends HistoryWindow {
+ scopeEpoch: number;
+ scopeSeeded: boolean;
+ unscopedSeeded: boolean;
+ scopeSampledAt?: number;
+}
- const seededUnscoped = useRef(false);
- const seedState = useRef<{ scope: string; complete: boolean } | null>(null);
+function seedTimesBefore(times: Iterable, firstSample: number, windowStart: number) {
+ return [...new Set(times)]
+ .filter((t) => t >= windowStart && t + SEED_BUCKET_SECONDS <= firstSample)
+ .sort((a, b) => a - b);
+}
+
+function useLiveTrend(status: Status, hasData: boolean, enabled: boolean): OverviewHistory {
+ const [trend, setTrend] = useState(() => ({
+ ...emptyWindow(),
+ scopeEpoch: 0,
+ scopeSeeded: false,
+ unscopedSeeded: false,
+ }));
+ const { scopeEpoch, scopeSeeded, unscopedSeeded } = trend;
+ const scope = status.resourceScope;
useEffect(() => {
// The placeholder has no resource scope. Wait for the first real status,
// then seed each scope once even if polling temporarily loses data.
- if (
- !hasData ||
- (seedState.current?.scope === status.resourceScope && seedState.current.complete)
- ) {
- return;
- }
- seedState.current = { scope: status.resourceScope, complete: false };
+ if (!enabled || !hasData || scopeSeeded) return;
let cancelled = false;
- const seedUnscoped = !seededUnscoped.current;
- const keys = seedUnscoped ? SERIES_KEYS : (['cpu', 'swap'] as const);
+ const keys = unscopedSeeded ? (['cpu', 'swap'] as const) : SERIES_KEYS;
const seed = async () => {
const responses = new Map();
@@ -114,35 +124,45 @@ function useLiveTrend(status: Status, hasData: boolean): OverviewHistory {
}),
);
if (cancelled || responses.size === 0) return;
- seedState.current = { scope: status.resourceScope, complete: true };
- seededUnscoped.current = true;
let axis: HistoryPoint[] = [];
for (const points of responses.values()) {
if (points.length > axis.length) axis = points;
}
- axis = tailWindow(axis);
- if (axis.length === 0) return;
-
- const seedTimes = axis.map((p) => Number(p.t) || 0);
- const seedSeries = emptySeries();
- for (const key of SERIES_KEYS) {
- const byTs = new Map();
- for (const p of responses.get(key) ?? []) byTs.set(Number(p.t) || 0, Number(p.v) || 0);
- seedSeries[key] =
- status.resourceScope && (key === 'cpu' || key === 'swap')
- ? seedTimes.flatMap((ts) => (byTs.has(ts) ? [byTs.get(ts)!] : []))
- : seedTimes.map((ts) => byTs.get(ts) ?? 0);
- }
-
+ const axisTimes = axis.map((p) => Number(p.t));
setTrend((prev) => {
- const merged = emptyWindow();
- merged.times = seedUnscoped ? tailWindow(seedTimes.concat(prev.times)) : prev.times;
- for (const key of SERIES_KEYS) {
- merged.series[key] =
- seedUnscoped || key === 'cpu' || key === 'swap'
- ? tailWindow(seedSeries[key].concat(prev.series[key]))
- : prev.series[key];
+ if (prev.scopeEpoch !== scopeEpoch) return prev;
+ // With no server timestamp on live samples, only join buckets inside the browser's window.
+ const windowStart =
+ prev.times[prev.times.length - 1] - OVERVIEW_WINDOW * LIVE_BUCKET_SECONDS;
+ const unscopedTimes = unscopedSeeded
+ ? []
+ : seedTimesBefore(axisTimes, prev.times[0], windowStart);
+ const firstScopedSample = prev.scopeSampledAt ?? prev.times[0];
+ const merged = {
+ ...prev,
+ scopeSeeded: true,
+ unscopedSeeded: true,
+ times: unscopedTimes.length ? tailWindow(unscopedTimes.concat(prev.times)) : prev.times,
+ series: { ...prev.series },
+ };
+ for (const key of keys) {
+ const scoped = key === 'cpu' || key === 'swap';
+ const byTime = new Map(
+ (responses.get(key) ?? []).map((p) => [Number(p.t), Number(p.v) || 0]),
+ );
+ const seedTimes = scoped
+ ? seedTimesBefore(
+ scope ? byTime.keys() : [...axisTimes, ...byTime.keys()],
+ firstScopedSample,
+ windowStart,
+ )
+ : unscopedTimes;
+ if (seedTimes.length) {
+ merged.series[key] = tailWindow(
+ seedTimes.map((t) => byTime.get(t) ?? 0).concat(prev.series[key]),
+ );
+ }
}
return merged;
});
@@ -152,7 +172,7 @@ function useLiveTrend(status: Status, hasData: boolean): OverviewHistory {
return () => {
cancelled = true;
};
- }, [hasData, status.resourceScope]);
+ }, [enabled, hasData, scope, scopeEpoch, scopeSeeded, unscopedSeeded]);
// Each polled status is appended during render; an effect would show the
// chart one sample behind the numbers beside it.
@@ -160,10 +180,17 @@ function useLiveTrend(status: Status, hasData: boolean): OverviewHistory {
if (hasData && status !== sampledStatus) {
setSampledStatus(status);
setTrend((prev) => {
- const scopeChanged = sampledStatus && sampledStatus.resourceScope !== status.resourceScope;
+ const sampledAt = Math.floor(Date.now() / 1000);
+ const scopeChanged = sampledStatus !== null && sampledStatus.resourceScope !== scope;
const point = sampleOf(status);
- const next = emptyWindow();
- next.times = tailWindow(prev.times.concat(Math.floor(Date.now() / 1000)));
+ const next = {
+ ...prev,
+ series: emptySeries(),
+ scopeEpoch: prev.scopeEpoch + Number(scopeChanged),
+ scopeSeeded: prev.scopeSeeded && !scopeChanged,
+ scopeSampledAt: scopeChanged ? sampledAt : (prev.scopeSampledAt ?? sampledAt),
+ };
+ next.times = tailWindow(prev.times.concat(sampledAt));
for (const key of SERIES_KEYS) {
const scoped = key === 'cpu' || key === 'swap';
const previous = scoped && scopeChanged ? [] : prev.series[key];
@@ -270,7 +297,7 @@ export function useOverviewHistory(
hasData: boolean,
bucketSeconds: number = LIVE_BUCKET_SECONDS,
): OverviewHistory {
- const live = useLiveTrend(status, hasData);
+ const live = useLiveTrend(status, hasData, bucketSeconds === LIVE_BUCKET_SECONDS);
const ranged = useRangedHistory(
status,
hasData && bucketSeconds !== LIVE_BUCKET_SECONDS,
diff --git a/frontend/src/test/container-history.test.tsx b/frontend/src/test/container-history.test.tsx
index 45cdc0e72..bf7903fc3 100644
--- a/frontend/src/test/container-history.test.tsx
+++ b/frontend/src/test/container-history.test.tsx
@@ -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 () => {
diff --git a/frontend/src/test/network-traffic-status.test.tsx b/frontend/src/test/network-traffic-status.test.tsx
index 4136741ad..466b3c107 100644
--- a/frontend/src/test/network-traffic-status.test.tsx
+++ b/frontend/src/test/network-traffic-status.test.tsx
@@ -39,8 +39,6 @@ describe('network traffic status', () => {
down={[200]}
labels={['12:00']}
isMobile={false}
- range={2}
- onRangeChange={() => undefined}
/>,
);
expect(
diff --git a/frontend/src/test/overview-global-range.test.tsx b/frontend/src/test/overview-global-range.test.tsx
new file mode 100644
index 000000000..35e3722f9
--- /dev/null
+++ b/frontend/src/test/overview-global-range.test.tsx
@@ -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();
+ 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();
+ 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( );
+ 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( );
+ await waitFor(() =>
+ expect(historyRequests()).toEqual(['/panel/api/server/overviewHistory/' + range]),
+ );
+ first.unmount();
+ get.mockClear();
+ renderWithProviders( );
+ 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( );
+ 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( );
+ 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( );
+ 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',
+ ]);
+});
diff --git a/frontend/src/test/overview-ranged-history.test.tsx b/frontend/src/test/overview-ranged-history.test.tsx
index d3573bebd..a24b335b5 100644
--- a/frontend/src/test/overview-ranged-history.test.tsx
+++ b/frontend/src/test/overview-ranged-history.test.tsx
@@ -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();
+ }
+ },
+);
diff --git a/frontend/src/test/overview-stop-confirm.test.tsx b/frontend/src/test/overview-stop-confirm.test.tsx
index 105a8f6c3..3f19fea48 100644
--- a/frontend/src/test/overview-stop-confirm.test.tsx
+++ b/frontend/src/test/overview-stop-confirm.test.tsx
@@ -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}
diff --git a/frontend/src/test/overview-update-tag-keyboard.test.tsx b/frontend/src/test/overview-update-tag-keyboard.test.tsx
index 93ee645e9..cf33af949 100644
--- a/frontend/src/test/overview-update-tag-keyboard.test.tsx
+++ b/frontend/src/test/overview-update-tag-keyboard.test.tsx
@@ -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}