feat!: release v2 (#6545)

Co-authored-by: Artur <145776561+arturict@users.noreply.github.com>
Co-authored-by: arturict <arturict@users.noreply.github.com>
Co-authored-by: Thomas <thomas@ajnart.fr>
Co-authored-by: Afonso Jorge Ramos <afonsojorgeramos@gmail.com>
Co-authored-by: Danura30082 <danura30082+github@gmail.com>
Co-authored-by: Kushie <122986913+kushiemoon-dev@users.noreply.github.com>
Co-authored-by: ajnart <thomas@ajnart.fr>
Co-authored-by: ajnart <thomas@ajnart.dev>
Co-authored-by: chenjun <chenjun@foxmail.com>
Co-authored-by: Wikibear <wikibear@users.noreply.github.com>
Co-authored-by: Bergasha <bergasha@gmail.com>
Co-authored-by: leafyelin <43306196+leafyelin@users.noreply.github.com>
Co-authored-by: Lucas Araujo <lucas.lra@gmail.com>
Co-authored-by: GreenMonito <86085570+GreenMonito@users.noreply.github.com>
Co-authored-by: Nerdy-Technician <roffo@nerdy-technician.social>
Co-authored-by: Jun <34545896+jcstrong@users.noreply.github.com>
Co-authored-by: Edmond Abraham <54119952+gitedmond@users.noreply.github.com>
Co-authored-by: thrawnx <tight.bulb9384@fastmail.com>
Co-authored-by: Chris <58918656+nordada@users.noreply.github.com>
Co-authored-by: yi111 <153097222+Yi-111-a@users.noreply.github.com>
Co-authored-by: Yanis <naamaneyanis@gmail.com>
Co-authored-by: Wikibear <me@sej.de>
Co-authored-by: alessiottavo <93441886+alessiottavo@users.noreply.github.com>
This commit is contained in:
3286 files changed
+284386 -139176

No files matched your search

@@ -2,7 +2,9 @@ import { describe, expect, test } from "vitest";
import type { BeszelSystemStatsRecord } from "@homarr/integrations/types";
import { buildDiskChartData, padLiveTimeGrid } from "./chart";
import { buildDiskChartData, normalizeBeszelByteRate, padLiveTimeGrid } from "./chart";
const GIBIBYTE = 1024 ** 3;
const record = (
created: string,
@@ -30,7 +32,7 @@ const record = (
});
describe("buildDiskChartData", () => {
test("keeps root and extra filesystem usage in GiB without stacking or byte conversion", () => {
test("normalizes root and extra filesystem usage to bytes without stacking", () => {
const data = buildDiskChartData(
[
record("2026-07-11T13:46:00.000Z", 455.81, {
@@ -45,7 +47,12 @@ describe("buildDiskChartData", () => {
);
expect(data).toHaveLength(1);
expect(data[0]).toMatchObject({ Root: 455.81, sda: 1656.45, sdb: 3936.86, sdc: 1589.84 });
expect(data[0]).toMatchObject({
Root: 455.81 * GIBIBYTE,
sda: 1656.45 * GIBIBYTE,
sdb: 3936.86 * GIBIBYTE,
sdc: 1589.84 * GIBIBYTE,
});
});
test("uses zero for a filesystem missing from an individual sample and orders historical records oldest first", () => {
@@ -60,12 +67,23 @@ describe("buildDiskChartData", () => {
);
expect(data.map((point) => ({ Root: point.Root, sda: point.sda }))).toEqual([
{ Root: 1, sda: 0 },
{ Root: 2, sda: 4 },
{ Root: GIBIBYTE, sda: 0 },
{ Root: 2 * GIBIBYTE, sda: 4 * GIBIBYTE },
]);
});
});
describe("normalizeBeszelByteRate", () => {
test("converts legacy MiB/s values to bytes/s", () => {
expect(normalizeBeszelByteRate(undefined, 1.5)).toBe(1.5 * 1024 ** 2);
});
test("keeps the preferred bytes/s value authoritative, including zero", () => {
expect(normalizeBeszelByteRate(0, 1.5)).toBe(0);
expect(normalizeBeszelByteRate(1_500_000, 1.5)).toBe(1_500_000);
});
});
describe("padLiveTimeGrid", () => {
test("keeps a fixed 60-second window with the newest sample at the right edge", () => {
const data = padLiveTimeGrid([{ time: "13:51:30", rawTime: "2026-07-11T13:51:30.217Z", CPU: 18.07 }]);
+101 -39
View File
@@ -8,33 +8,38 @@ import dayjs from "dayjs";
import type { BeszelContainerStatsRecord, BeszelSystemStatsRecord } from "@homarr/integrations/types";
import { formatLocalizedDate } from "../../common/locale";
export type BeszelTimePeriod = "1m" | "1h" | "12h" | "24h" | "1w" | "30d";
const timeFormats: Record<BeszelTimePeriod, string> = {
"1m": "HH:mm:ss",
"1h": "HH:mm",
"12h": "HH:mm",
"24h": "HH:mm",
"1w": "MMM D",
"30d": "MMM D",
const timeFormatOptions: Record<BeszelTimePeriod, Intl.DateTimeFormatOptions> = {
"1m": { hour: "numeric", minute: "2-digit", second: "2-digit" },
"1h": { hour: "numeric", minute: "2-digit" },
"12h": { hour: "numeric", minute: "2-digit" },
"24h": { hour: "numeric", minute: "2-digit" },
"1w": { month: "short", day: "numeric" },
"30d": { month: "short", day: "numeric" },
};
const periodDays: Partial<Record<BeszelTimePeriod, number>> = { "1w": 7, "30d": 30 };
function prepareRecords<T>(records: T[], timePeriod: BeszelTimePeriod) {
const fmt = (timestamp: string) => dayjs(timestamp).format(timeFormats[timePeriod]);
export const formatBeszelChartTimestamp = (timestamp: string, timePeriod: BeszelTimePeriod, locale: string): string =>
formatLocalizedDate(timestamp, locale, timeFormatOptions[timePeriod]);
function prepareRecords<T>(records: T[], timePeriod: BeszelTimePeriod, locale: string) {
const fmt = (timestamp: string) => formatBeszelChartTimestamp(timestamp, timePeriod, locale);
if (timePeriod === "1m") {
return { fmt, ordered: records };
}
return { fmt, ordered: [...records].toReversed() };
return { fmt, ordered: records.toReversed() };
}
function padTimeGrid(data: Record<string, unknown>[], timePeriod: BeszelTimePeriod) {
if (timePeriod === "1m") return padLiveTimeGrid(data);
function padTimeGrid(data: Record<string, unknown>[], timePeriod: BeszelTimePeriod, locale: string) {
if (timePeriod === "1m") return padLiveTimeGrid(data, 60, locale);
const days = periodDays[timePeriod];
if (!days) return data;
const fmt = (ts: string) => dayjs(ts).format(timeFormats[timePeriod]);
const fmt = (timestamp: string) => formatBeszelChartTimestamp(timestamp, timePeriod, locale);
const now = dayjs();
const existingDays = new Set(data.map((d) => dayjs(d.rawTime as string).format("YYYY-MM-DD")));
const result = [...data];
@@ -51,7 +56,7 @@ function padTimeGrid(data: Record<string, unknown>[], timePeriod: BeszelTimePeri
return result.toSorted((a, b) => new Date(a.rawTime as string).getTime() - new Date(b.rawTime as string).getTime());
}
export function padLiveTimeGrid(data: Record<string, unknown>[], pointCount = 60) {
export function padLiveTimeGrid(data: Record<string, unknown>[], pointCount = 60, locale = "en-US") {
if (data.length === 0) return data;
const end = dayjs(
@@ -76,16 +81,20 @@ export function padLiveTimeGrid(data: Record<string, unknown>[], pointCount = 60
const timestamp = end.subtract(pointCount - index - 1, "second");
return (
pointsBySecond.get(timestamp.valueOf()) ?? {
time: timestamp.format(timeFormats["1m"]),
time: formatBeszelChartTimestamp(timestamp.toISOString(), "1m", locale),
rawTime: timestamp.toISOString(),
}
);
});
}
const yAxisBase = { tickMargin: 0, tick: { fontSize: 10 } } as const;
const yAxisBase = {
tickMargin: 0,
tick: { fontSize: "var(--mantine-font-size-xs)" },
} as const;
const chartStyle = { minWidth: 0, minHeight: 1 } as const;
const panelStyle = { minWidth: 0, overflow: "hidden" } as const;
const panelStyle = { minWidth: 0 } as const;
const chartMargin = { top: 0, right: 0, bottom: 0, left: 0 } as const;
export const CPU_Y_AXIS_DOMAIN: [number, string] = [0, "auto"];
interface BeszelChartPanelProps {
@@ -96,12 +105,12 @@ interface BeszelChartPanelProps {
export const BeszelChartPanel = memo(({ title, subtitle, chartProps }: BeszelChartPanelProps) => (
<Stack gap={4} style={panelStyle}>
<Group gap="xs">
<Text size="sm" fw={600}>
<Group gap="xs" wrap="nowrap">
<Text size="sm" fw={600} style={{ flexShrink: 0 }}>
{title}
</Text>
{subtitle && (
<Text size="xs" c="dimmed">
<Text size="xs" c="dimmed" truncate style={{ minWidth: 0 }}>
{subtitle}
</Text>
)}
@@ -110,7 +119,7 @@ export const BeszelChartPanel = memo(({ title, subtitle, chartProps }: BeszelCha
</Stack>
));
type BeszelAreaChartProps = Omit<AreaChartProps, "dataKey" | "curveType" | "withDots" | "withXAxis" | "withYAxis"> & {
type BeszelAreaChartProps = Omit<AreaChartProps, "dataKey" | "curveType" | "withDots" | "withYAxis"> & {
yAxisFormatter: (value: number) => string;
yAxisDomain?: [number, string];
};
@@ -118,15 +127,25 @@ type BeszelAreaChartProps = Omit<AreaChartProps, "dataKey" | "curveType" | "with
const BeszelAreaChart = memo(
({
yAxisFormatter,
withXAxis = true,
yAxisDomain,
yAxisProps: yAxisPropsOverride,
xAxisProps: xAxisPropsOverride,
areaChartProps: areaChartPropsOverride,
type = "default",
...props
}: BeszelAreaChartProps) => {
const mergedXAxis = useMemo(
() => ({
interval: "preserveEnd" as const,
...xAxisPropsOverride,
}),
[xAxisPropsOverride],
);
const mergedYAxis = useMemo(() => {
const base = {
...yAxisBase,
width: 48,
width: 56,
tickMargin: 2,
tickFormatter: yAxisFormatter,
...yAxisPropsOverride,
@@ -147,10 +166,12 @@ const BeszelAreaChart = memo(
type={type}
strokeWidth={1}
fillOpacity={0.2}
withXAxis
withXAxis={withXAxis}
withYAxis
w="100%"
areaChartProps={{ margin: chartMargin, ...areaChartPropsOverride }}
style={chartStyle}
xAxisProps={mergedXAxis}
yAxisProps={mergedYAxis}
{...props}
/>
@@ -162,17 +183,18 @@ export const useSystemChartData = (
systemStats: BeszelSystemStatsRecord[] | undefined,
mapFn: (stats: BeszelSystemStatsRecord["stats"]) => Record<string, unknown>,
timePeriod: BeszelTimePeriod = "1h",
locale = "en-US",
) =>
useMemo(() => {
if (!systemStats) return [];
const { fmt, ordered } = prepareRecords(systemStats, timePeriod);
const { fmt, ordered } = prepareRecords(systemStats, timePeriod, locale);
const mapped = ordered.map((r) => ({
time: fmt(r.created),
rawTime: r.created,
...mapFn(r.stats),
}));
return padTimeGrid(mapped, timePeriod);
}, [systemStats, mapFn, timePeriod]);
return padTimeGrid(mapped, timePeriod, locale);
}, [systemStats, mapFn, timePeriod, locale]);
export const useContainerNames = (containerStats: BeszelContainerStatsRecord[] | undefined, max = 15) => {
const prevRef = useRef<string[]>([]);
@@ -198,13 +220,19 @@ export const useContainerNames = (containerStats: BeszelContainerStatsRecord[] |
type ContainerExtractor = (container: BeszelContainerStatsRecord["stats"][number] | undefined) => number;
// c = CPU (%), m = memory (MB), b = bandwidth [sent,recv] (bytes/s), ns/nr = legacy net (bytes/s)
const MB = 1024 * 1024;
// c = CPU (%), m = memory (MiB), b = bandwidth [sent,recv] (bytes/s), ns/nr = legacy net (MiB/s)
const MEBIBYTE = 1024 * 1024;
const GIBIBYTE = 1024 * MEBIBYTE;
export const normalizeBeszelByteRate = (
bytesPerSecond: number | undefined,
legacyMebibytesPerSecond: number | undefined,
): number => bytesPerSecond ?? (legacyMebibytesPerSecond ?? 0) * MEBIBYTE;
const defaultContainerExtractors: Record<string, ContainerExtractor> = {
cpu: (c) => c?.c ?? 0,
memory: (c) => (c?.m ?? 0) * MB,
network: (c) => (c?.b ? c.b[0] + c.b[1] : (c?.ns ?? 0) + (c?.nr ?? 0)),
memory: (c) => (c?.m ?? 0) * MEBIBYTE,
network: (c) => normalizeBeszelByteRate(c?.b?.[0], c?.ns) + normalizeBeszelByteRate(c?.b?.[1], c?.nr),
};
export const useDiskChartData = (
@@ -212,10 +240,11 @@ export const useDiskChartData = (
efsPaths: string[],
rootSeriesName: string,
timePeriod: BeszelTimePeriod = "1h",
locale = "en-US",
) =>
useMemo(
() => buildDiskChartData(systemStats, efsPaths, rootSeriesName, timePeriod),
[systemStats, efsPaths, rootSeriesName, timePeriod],
() => buildDiskChartData(systemStats, efsPaths, rootSeriesName, timePeriod, locale),
[systemStats, efsPaths, rootSeriesName, timePeriod, locale],
);
export const buildDiskChartData = (
@@ -223,35 +252,68 @@ export const buildDiskChartData = (
efsPaths: string[],
rootSeriesName: string,
timePeriod: BeszelTimePeriod = "1h",
locale = "en-US",
) => {
if (!systemStats?.length) return [];
const { fmt, ordered } = prepareRecords(systemStats, timePeriod);
const { fmt, ordered } = prepareRecords(systemStats, timePeriod, locale);
const mapped = ordered.map((record) => {
const point: Record<string, unknown> = {
time: fmt(record.created),
rawTime: record.created,
[rootSeriesName]: record.stats.du,
[rootSeriesName]: record.stats.du * GIBIBYTE,
};
const efs = record.stats.efs ?? {};
for (const path of efsPaths) {
point[path] = efs[path]?.du ?? 0;
point[path] = (efs[path]?.du ?? 0) * GIBIBYTE;
}
return point;
});
return padTimeGrid(mapped, timePeriod);
return padTimeGrid(mapped, timePeriod, locale);
};
export const useDiskIOChartData = (
systemStats: BeszelSystemStatsRecord[] | undefined,
efsPaths: string[],
rootReadSeriesName: string,
rootWriteSeriesName: string,
readLabel: string,
writeLabel: string,
timePeriod: BeszelTimePeriod = "1h",
locale = "en-US",
) =>
useMemo(() => {
if (!systemStats?.length) return [];
const { fmt, ordered } = prepareRecords(systemStats, timePeriod, locale);
const mapped = ordered.map((record) => {
const point: Record<string, unknown> = {
time: fmt(record.created),
rawTime: record.created,
[rootReadSeriesName]: normalizeBeszelByteRate(record.stats.dio?.[0], record.stats.dr),
[rootWriteSeriesName]: normalizeBeszelByteRate(record.stats.dio?.[1], record.stats.dw),
};
const efs = record.stats.efs ?? {};
for (const path of efsPaths) {
const filesystem = efs[path];
point[`${path} ${readLabel}`] = normalizeBeszelByteRate(filesystem?.rb, filesystem?.r);
point[`${path} ${writeLabel}`] = normalizeBeszelByteRate(filesystem?.wb, filesystem?.w);
}
return point;
});
return padTimeGrid(mapped, timePeriod, locale);
}, [systemStats, efsPaths, rootReadSeriesName, rootWriteSeriesName, readLabel, writeLabel, timePeriod, locale]);
export const useDockerChartData = (
containerStats: BeszelContainerStatsRecord[] | undefined,
containerNames: string[],
metric: "cpu" | "memory" | "network",
timePeriod: BeszelTimePeriod = "1h",
locale = "en-US",
) =>
useMemo(() => {
if (!containerStats?.length) return [];
const extract = defaultContainerExtractors[metric];
if (!extract) return [];
const { fmt, ordered } = prepareRecords(containerStats, timePeriod);
const { fmt, ordered } = prepareRecords(containerStats, timePeriod, locale);
const mapped = ordered.map((record) => {
const point: Record<string, unknown> = { time: fmt(record.created), rawTime: record.created };
const byName = new Map(record.stats.map((c) => [c.n, c]));
@@ -260,5 +322,5 @@ export const useDockerChartData = (
}
return point;
});
return padTimeGrid(mapped, timePeriod);
}, [containerStats, containerNames, metric, timePeriod]);
return padTimeGrid(mapped, timePeriod, locale);
}, [containerStats, containerNames, metric, timePeriod, locale]);
@@ -0,0 +1,13 @@
.target {
position: relative;
z-index: 2;
min-width: 24px;
min-height: 24px;
}
@media (pointer: coarse) {
.target {
min-width: 44px;
min-height: 44px;
}
}
@@ -1,8 +1,12 @@
import { Box, Group, HoverCard, Progress, Stack, Text, UnstyledButton } from "@mantine/core";
import { useEffect, useState } from "react";
import { Box, Group, Popover, Progress, Stack, Text, UnstyledButton } from "@mantine/core";
import { useI18n } from "@homarr/translation/client";
import type { BeszelSystemRow } from "./types";
import { thresholdColor } from "./colors";
import { formatPercent, getProgressTrackSize } from "./format";
import classes from "./disk-usage.module.css";
interface DiskUsageProps {
system: BeszelSystemRow;
@@ -17,33 +21,44 @@ const mountLabel = (path: string) =>
const severityColor = (value: number) => `var(--mantine-color-${thresholdColor(value)}-6)`;
export const DiskUsage = ({ system, fontSize, progressSize, valueMiw, valueGap = 6 }: DiskUsageProps) => {
const t = useI18n("common");
const [opened, setOpened] = useState(false);
const filesystems = Object.entries(system.extraFilesystems).filter(([path]) => path !== "/");
const filesystemUsageLabel = t("filesystemUsage", { count: filesystems.length + 1 });
const trackSize = getProgressTrackSize(progressSize);
const dotSize = progressSize === "xs" ? 2 : 3;
const dotGap = 2;
useEffect(() => {
if (filesystems.length === 0) setOpened(false);
}, [filesystems.length]);
return (
<Group gap={valueGap} wrap="nowrap" style={{ flex: 1, minWidth: 0, marginLeft: "auto" }}>
<Text size={fontSize} fw={500} w={valueMiw} ta="left" style={{ whiteSpace: "nowrap", flexShrink: 0 }}>
{formatPercent(system.disk)}
</Text>
<HoverCard
position="right"
withArrow
shadow="md"
openDelay={200}
closeDelay={100}
disabled={filesystems.length === 0}
>
<HoverCard.Target>
{filesystems.length > 0 ? (
{filesystems.length > 0 ? (
<Popover
opened={opened}
onChange={setOpened}
zIndex="var(--homarr-z-index-widget-background-tooltip)"
position="right"
withArrow
shadow="md"
>
<Popover.Target>
<UnstyledButton
aria-label={`Show usage for ${filesystems.length + 1} filesystems`}
aria-label={filesystemUsageLabel}
className={classes.target}
onMouseEnter={() => setOpened(true)}
onMouseLeave={() => setOpened(false)}
onBlur={() => setOpened(false)}
onClick={() => setOpened(true)}
style={{
display: "flex",
alignItems: "center",
flex: 1,
minWidth: 24,
cursor: "pointer",
}}
>
@@ -74,32 +89,32 @@ export const DiskUsage = ({ system, fontSize, progressSize, valueMiw, valueGap =
</Group>
</Box>
</UnstyledButton>
) : (
<Box style={{ display: "flex", alignItems: "center", flex: 1, minWidth: 24 }}>
<Box pos="relative" style={{ flex: 1, minWidth: 24 }}>
<Progress value={system.disk} color={thresholdColor(system.disk)} size={trackSize} />
</Box>
</Box>
)}
</HoverCard.Target>
<HoverCard.Dropdown p={8}>
<Stack gap={6} miw={145}>
{[["/", system.disk] as const, ...filesystems].map(([path, value]) => (
<Stack key={path} gap={1}>
<Text size="10px" c="dimmed" fw={500} lh={1.2}>
{mountLabel(path)}
</Text>
<Group gap={8} wrap="nowrap">
<Text size="sm" fw={600} miw={48} lh={1.25}>
{formatPercent(value)}
</Popover.Target>
<Popover.Dropdown aria-label={filesystemUsageLabel} p={8}>
<Stack gap={6} miw={145}>
{[["/", system.disk] as const, ...filesystems].map(([path, value]) => (
<Stack key={path} gap={1}>
<Text size="xs" c="dimmed" fw={500} lh={1.2}>
{mountLabel(path)}
</Text>
<Progress value={value} color={thresholdColor(value)} size="xs" style={{ flex: 1 }} />
</Group>
</Stack>
))}
</Stack>
</HoverCard.Dropdown>
</HoverCard>
<Group gap={8} wrap="nowrap">
<Text size="sm" fw={600} miw={48} lh={1.25}>
{formatPercent(value)}
</Text>
<Progress value={value} color={thresholdColor(value)} size="xs" style={{ flex: 1 }} />
</Group>
</Stack>
))}
</Stack>
</Popover.Dropdown>
</Popover>
) : (
<Box style={{ display: "flex", alignItems: "center", flex: 1, minWidth: 24 }}>
<Box pos="relative" style={{ flex: 1, minWidth: 24 }}>
<Progress value={system.disk} color={thresholdColor(system.disk)} size={trackSize} />
</Box>
</Box>
)}
</Group>
);
};
@@ -1,25 +0,0 @@
"use client";
import { Tooltip } from "@mantine/core";
import { IconAlertTriangle } from "@tabler/icons-react";
interface IntegrationResult {
integrationId: string;
integrationName?: string;
error?: string;
}
interface BeszelIntegrationErrorIndicatorProps {
results: IntegrationResult[];
}
export function BeszelIntegrationErrorIndicator({ results }: BeszelIntegrationErrorIndicatorProps) {
const failed = results.filter((r) => "error" in r && r.error);
if (failed.length === 0) return null;
const label = failed.map((r) => r.integrationName ?? r.integrationId).join(", ");
return (
<Tooltip label={label} position="left" withArrow>
<IconAlertTriangle size={14} color="var(--mantine-color-orange-6)" style={{ cursor: "help", flexShrink: 0 }} />
</Tooltip>
);
}
@@ -1,17 +1,23 @@
import { describe, expect, test } from "vitest";
import { chartAxisFormatters, formatGB, getProgressTrackSize } from "./format";
import { formatByteRate, formatBytes } from "@homarr/common";
import { createByteChartAxisFormatters, getProgressTrackSize } from "./format";
const GIBIBYTE = 1024 ** 3;
const binaryAxisFormatters = createByteChartAxisFormatters(
(bytes) => formatBytes(bytes, { unit: "binary" }),
(bytes) => formatByteRate(bytes, { unit: "binary" }),
);
describe("Beszel storage formatting", () => {
test("keeps smaller values in GB", () => {
expect(formatGB(455.81)).toBe("455.81 GB");
expect(chartAxisFormatters.gb(455.81)).toBe("456G");
test("formats canonical byte values with shared binary units", () => {
expect(binaryAxisFormatters.bytes(455.81 * GIBIBYTE)).toBe("455.8GiB");
});
test("promotes large GiB values to TB", () => {
expect(formatGB(3323)).toBe("3.25 TB");
expect(formatGB(3936.86)).toBe("3.84 TB");
expect(chartAxisFormatters.gb(3323)).toBe("3.2T");
test("promotes large canonical byte values to TiB", () => {
expect(binaryAxisFormatters.bytes(3323 * GIBIBYTE)).toBe("3.2TiB");
expect(binaryAxisFormatters.bytes(3936.86 * GIBIBYTE)).toBe("3.8TiB");
});
test("maps progress sizes consistently", () => {
+10 -38
View File
@@ -5,51 +5,23 @@ import relativeTime from "dayjs/plugin/relativeTime";
dayjs.extend(duration);
dayjs.extend(relativeTime);
const byteUnits = ["B", "KB", "MB", "GB", "TB"] as const;
const rateUnits = ["B/s", "KB/s", "MB/s", "GB/s"] as const;
const formatScaled = (value: number, units: readonly string[], zeroLabel: string): string => {
if (!value || !Number.isFinite(value)) return zeroLabel;
const i = Math.max(0, Math.min(Math.floor(Math.log(Math.abs(value)) / Math.log(1024)), units.length - 1));
const scaled = value / 1024 ** i;
const decimals = scaled < 10 ? 2 : 1;
return `${scaled.toFixed(decimals)} ${units[i] ?? ""}`;
const compactByteLabel = (value: number, formatter: (value: number) => string): string => {
if (!value || !Number.isFinite(value)) return "0";
return formatter(Number(value)).replace(".0 ", "").replace(" ", "");
};
const formatScaledCompact = (value: number, units: readonly string[], zeroLabel: string): string => {
if (!value || !Number.isFinite(value)) return zeroLabel;
const i = Math.max(0, Math.min(Math.floor(Math.log(Math.abs(value)) / Math.log(1024)), units.length - 1));
const scaled = value / 1024 ** i;
return `${scaled < 10 ? scaled.toFixed(1) : Math.round(scaled)}${units[i] ?? ""}`;
};
export const formatByteRate = (value: number): string => formatScaled(value, rateUnits, "0 B/s");
export const formatStorageBytes = (bytes: number): string => formatScaled(bytes, byteUnits, "0 B");
export const formatGB = (value: number): string => {
if (!value || !Number.isFinite(value)) return "0 GB";
if (Math.abs(value) >= 1024) return `${(value / 1024).toFixed(2)} TB`;
return `${value.toFixed(2)} GB`;
};
export const createByteChartAxisFormatters = (
formatBytes: (bytes: number) => string,
formatByteRate: (bytes: number) => string,
) => ({
bytes: (value: number) => compactByteLabel(value, formatBytes),
rate: (value: number) => compactByteLabel(value, formatByteRate),
});
export const formatPercent = (value: number): string => `${value.toFixed(1)}%`;
export const getProgressTrackSize = (size: "xs" | "sm"): number => (size === "xs" ? 6 : 9);
export const chartAxisFormatters = {
percent: formatPercent,
gb: (value: number) => {
const numericValue = Number(value);
if (!numericValue) return "0";
if (Math.abs(numericValue) >= 1024) return `${(numericValue / 1024).toFixed(1)}T`;
return `${numericValue.toFixed(0)}G`;
},
mb: (value: number) => (!value ? "0" : `${Number(value).toFixed(0)}M`),
bytes: (value: number) => formatScaledCompact(Number(value), byteUnits, "0"),
rate: (value: number) => formatScaledCompact(Number(value), rateUnits, "0"),
} as const;
export const formatUptime = (seconds: number): string => dayjs.duration(seconds, "seconds").humanize();
export const formatTemp = (celsius: number | null, fahrenheit: boolean): string => {
+2 -2
View File
@@ -4,7 +4,7 @@ import { useMemo } from "react";
import type { BeszelSystemRow } from "./types";
type SystemRowWithKey = BeszelSystemRow & { _key: string };
type SystemRowWithKey = BeszelSystemRow & { rowKey: string };
export const useBeszelFilteredSystems = (
results: { integrationId: string; systems: BeszelSystemRow[] }[],
@@ -13,7 +13,7 @@ export const useBeszelFilteredSystems = (
const allSystems = useMemo(
() =>
results
.flatMap((r) => r.systems.map((s) => ({ ...s, _key: `${r.integrationId}:${s.id}` })))
.flatMap((r) => r.systems.map((s) => ({ ...s, rowKey: `${r.integrationId}:${s.id}` })))
.toSorted((a, b) => a.name.localeCompare(b.name)),
[results],
);
@@ -1,44 +1,37 @@
"use client";
import { useMemo } from "react";
import { Button, Center, Group, SimpleGrid, Skeleton, Stack, Text } from "@mantine/core";
import { Button, Center, SimpleGrid, Stack, Text } from "@mantine/core";
import { IconPlugConnectedX, IconServerOff } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
import { invariantTechnicalLabels } from "@homarr/definitions";
import type { BeszelContainerStatsRecord, BeszelSystemStatsRecord } from "@homarr/integrations/types";
import { useScopedI18n } from "@homarr/translation/client";
import { useByteFormatter } from "@homarr/settings";
import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";
import { zoomCompensatedSize } from "@homarr/ui";
import { getUsableWidgetQueryData } from "../../common/query-state";
import { WidgetQueryLoadingState } from "../../common/query-state-indicator";
import { containerColors } from "./colors";
import type { BeszelTimePeriod } from "./chart";
import {
BeszelChartPanel,
CPU_Y_AXIS_DOMAIN,
normalizeBeszelByteRate,
useContainerNames,
useDiskChartData,
useDiskIOChartData,
useDockerChartData,
useSystemChartData,
} from "./chart";
import { chartAxisFormatters, formatByteRate, formatGB, formatPercent, formatStorageBytes } from "./format";
import { createByteChartAxisFormatters, formatPercent } from "./format";
import { makeTooltipProps } from "./tooltip";
import { useLiveStats } from "./use-live-stats";
const CHART_HEIGHT = 180;
const MB = 1024 * 1024;
const tooltipPercent = makeTooltipProps(formatPercent);
const tooltipGB = makeTooltipProps(formatGB, true);
const tooltipRate = makeTooltipProps(formatByteRate, true);
const tooltipPercentTotal = makeTooltipProps(formatPercent, true);
const tooltipBytesTotal = makeTooltipProps(formatStorageBytes, true);
const ChartSkeleton = () => (
<Stack gap={4} style={{ minWidth: 0 }}>
<Group gap="xs">
<Skeleton h={14} w={72} radius="sm" />
<Skeleton h={10} w={110} radius="sm" />
</Group>
<Skeleton h={CHART_HEIGHT} radius="sm" />
</Stack>
);
const MEBIBYTE = 1024 * 1024;
const GIBIBYTE = 1024 * MEBIBYTE;
export interface BeszelStatsVisibility {
cpu: boolean;
@@ -57,9 +50,21 @@ interface BeszelStatsViewProps {
timePeriod: BeszelTimePeriod;
visibility: BeszelStatsVisibility;
columns: 1 | 2;
availableHeight?: number;
showXAxis?: boolean;
onSwitchToHistorical?: () => void;
}
const MIN_CHART_HEIGHT = 64;
const PANEL_ROW_OVERHEAD = 25;
const GRID_ROW_GAP = 16;
const computeChartHeight = (availableHeight: number | undefined, rowCount: number) => {
if (availableHeight === undefined || rowCount <= 0) return CHART_HEIGHT;
const perRow = (availableHeight - (rowCount - 1) * GRID_ROW_GAP) / rowCount - PANEL_ROW_OVERHEAD;
return Math.max(MIN_CHART_HEIGHT, Math.floor(perRow));
};
const whenVisible = <T,>(visible: boolean, data: T | undefined) => (visible ? data : undefined);
export function BeszelStatsView({
@@ -68,16 +73,35 @@ export function BeszelStatsView({
timePeriod,
visibility,
columns,
availableHeight,
showXAxis = true,
onSwitchToHistorical,
}: BeszelStatsViewProps) {
const t = useScopedI18n("widget.beszelSystemStats");
const t = useI18n("widget.beszelSystemStats");
const tBeszel = useI18n("widget.beszel");
const locale = useCurrentIntlLocale();
const { formatByteRate, formatBytes } = useByteFormatter();
const byteAxisFormatters = useMemo(
() => createByteChartAxisFormatters(formatBytes, formatByteRate),
[formatByteRate, formatBytes],
);
const tooltips = useMemo(
() => ({
percent: makeTooltipProps(formatPercent),
bytes: makeTooltipProps(formatBytes, true),
rate: makeTooltipProps(formatByteRate, true),
percentTotal: makeTooltipProps(formatPercent, true),
bytesTotal: makeTooltipProps(formatBytes, true),
}),
[formatByteRate, formatBytes],
);
const showDocker = visibility.dockerCpu || visibility.dockerMemory || visibility.dockerNetwork;
const isLive = timePeriod === "1m";
const { data: historicalData, error: historicalError } = clientApi.widget.beszel.getSystemStats.useQuery(
const historicalQuery = clientApi.widget.beszel.getSystemStats.useQuery(
{ integrationIds, systemId, timePeriod, includeDocker: showDocker },
{ refetchInterval: isLive ? false : 5_000, enabled: !isLive && systemId !== "" },
);
const historicalData = isLive ? historicalQuery.data : getUsableWidgetQueryData(historicalQuery);
const { data: liveData, error: liveError } = useLiveStats(integrationIds, systemId, isLive && systemId !== "");
const activeStats:
@@ -87,18 +111,14 @@ export function BeszelStatsView({
const mappers = useMemo(
() => ({
cpu: (s: { cpu: number }) => ({ [t("chart.cpu.series")]: s.cpu }),
cpu: (s: { cpu: number }) => ({ [invariantTechnicalLabels.cpu]: s.cpu }),
memory: (s: { mu: number; mb: number }) => ({
[t("chart.memory.series")]: s.mu,
[t("chart.memory.cache")]: s.mb ?? 0,
}),
diskIO: (s: { dr?: number; dw?: number }) => ({
[t("chart.diskIO.read")]: (s.dr ?? 0) * MB,
[t("chart.diskIO.write")]: (s.dw ?? 0) * MB,
[t("chart.memory.series")]: s.mu * GIBIBYTE,
[t("chart.memory.cache")]: (s.mb ?? 0) * GIBIBYTE,
}),
network: (s: { ns?: number; nr?: number; b?: [number, number] }) => ({
[t("chart.network.sent")]: s.b?.[0] ?? s.ns ?? 0,
[t("chart.network.recv")]: s.b?.[1] ?? s.nr ?? 0,
[t("chart.network.sent")]: normalizeBeszelByteRate(s.b?.[0], s.ns),
[t("chart.network.recv")]: normalizeBeszelByteRate(s.b?.[1], s.nr),
}),
}),
[t],
@@ -106,15 +126,11 @@ export function BeszelStatsView({
const series = useMemo(
() => ({
cpu: [{ name: t("chart.cpu.series"), color: "teal.6" }],
cpu: [{ name: invariantTechnicalLabels.cpu, color: "teal.6" }],
memory: [
{ name: t("chart.memory.series"), color: "teal.5" },
{ name: t("chart.memory.cache"), color: "teal.8" },
],
diskIO: [
{ name: t("chart.diskIO.write"), color: "orange.6" },
{ name: t("chart.diskIO.read"), color: "blue.6" },
],
network: [
{ name: t("chart.network.sent"), color: "blue.6" },
{ name: t("chart.network.recv"), color: "teal.6" },
@@ -125,10 +141,19 @@ export function BeszelStatsView({
const systemStats = activeStats?.systemStats;
const containerStats = activeStats?.containerStats;
const cpuData = useSystemChartData(whenVisible(visibility.cpu, systemStats), mappers.cpu, timePeriod);
const memoryData = useSystemChartData(whenVisible(visibility.memory, systemStats), mappers.memory, timePeriod);
const diskIOData = useSystemChartData(whenVisible(visibility.diskIO, systemStats), mappers.diskIO, timePeriod);
const networkData = useSystemChartData(whenVisible(visibility.network, systemStats), mappers.network, timePeriod);
const cpuData = useSystemChartData(whenVisible(visibility.cpu, systemStats), mappers.cpu, timePeriod, locale);
const memoryData = useSystemChartData(
whenVisible(visibility.memory, systemStats),
mappers.memory,
timePeriod,
locale,
);
const networkData = useSystemChartData(
whenVisible(visibility.network, systemStats),
mappers.network,
timePeriod,
locale,
);
const efsPaths = useMemo(() => {
const paths = new Set<string>();
@@ -138,7 +163,27 @@ export function BeszelStatsView({
return [...paths];
}, [systemStats]);
const rootSeriesName = t("chart.disk.series");
const diskData = useDiskChartData(whenVisible(visibility.disk, systemStats), efsPaths, rootSeriesName, timePeriod);
const readLabel = t("chart.diskIO.read");
const writeLabel = t("chart.diskIO.write");
const rootReadSeriesName = `${rootSeriesName} ${readLabel}`;
const rootWriteSeriesName = `${rootSeriesName} ${writeLabel}`;
const diskData = useDiskChartData(
whenVisible(visibility.disk, systemStats),
efsPaths,
rootSeriesName,
timePeriod,
locale,
);
const diskIOData = useDiskIOChartData(
whenVisible(visibility.diskIO, systemStats),
efsPaths,
rootReadSeriesName,
rootWriteSeriesName,
readLabel,
writeLabel,
timePeriod,
locale,
);
const diskSeries = useMemo(
() => [
{ name: rootSeriesName, color: "grape.6" },
@@ -149,6 +194,23 @@ export function BeszelStatsView({
],
[efsPaths, rootSeriesName],
);
const diskIOSeries = useMemo(
() => [
{ name: rootWriteSeriesName, color: "orange.6" },
{ name: rootReadSeriesName, color: "blue.6" },
...efsPaths.flatMap((path, index) => [
{
name: `${path} ${writeLabel}`,
color: containerColors[(index * 2 + 2) % containerColors.length] as string,
},
{
name: `${path} ${readLabel}`,
color: containerColors[(index * 2 + 3) % containerColors.length] as string,
},
]),
],
[efsPaths, readLabel, rootReadSeriesName, rootWriteSeriesName, writeLabel],
);
const containerNames = useContainerNames(whenVisible(showDocker, containerStats));
const containerSeries = useMemo(
@@ -161,27 +223,28 @@ export function BeszelStatsView({
containerNames,
"cpu",
timePeriod,
locale,
);
const dockerMemoryData = useDockerChartData(
whenVisible(visibility.dockerMemory, containerStats),
containerNames,
"memory",
timePeriod,
locale,
);
const dockerNetworkData = useDockerChartData(
whenVisible(visibility.dockerNetwork, containerStats),
containerNames,
"network",
timePeriod,
locale,
);
if (historicalError) throw historicalError;
if (isLive && liveError) {
return (
<Center h={CHART_HEIGHT}>
<Stack align="center" gap="sm" p="md">
<IconPlugConnectedX size={40} />
<IconPlugConnectedX style={zoomCompensatedSize(40)} />
<Text size="sm" c="dimmed" ta="center">
{t("error.liveConnectionFailed")}
</Text>
@@ -196,42 +259,51 @@ export function BeszelStatsView({
}
if (!activeStats) {
const visibleChartCount = Object.values(visibility).filter(Boolean).length;
return (
<SimpleGrid cols={columns} spacing="md" aria-label="Loading system statistics">
{Array.from({ length: visibleChartCount }, (_, index) => (
<ChartSkeleton key={index} />
))}
</SimpleGrid>
);
return <WidgetQueryLoadingState />;
}
if ("error" in activeStats && activeStats.error) {
return (
<Center h={CHART_HEIGHT}>
<Stack align="center" gap="xs">
<IconServerOff size={24} opacity={0.5} />
<IconServerOff style={zoomCompensatedSize(24)} opacity={0.5} />
<Text size="sm" c="dimmed">
{activeStats.error}
{tBeszel("error.internalServerError")}
</Text>
</Stack>
</Center>
);
}
const renderedPanelCount =
(visibility.cpu && cpuData.length > 0 ? 1 : 0) +
(visibility.memory && memoryData.length > 0 ? 1 : 0) +
(visibility.disk && diskData.length > 0 ? 1 : 0) +
(visibility.diskIO && diskIOData.length > 0 ? 1 : 0) +
(visibility.network && networkData.length > 0 ? 1 : 0) +
(showDocker && containerSeries.length > 0
? (visibility.dockerCpu && dockerCpuData.length > 0 ? 1 : 0) +
(visibility.dockerMemory && dockerMemoryData.length > 0 ? 1 : 0) +
(visibility.dockerNetwork && dockerNetworkData.length > 0 ? 1 : 0)
: 0);
const effectiveColumns = Math.min(columns, Math.max(1, renderedPanelCount)) as 1 | 2;
const rowCount = Math.ceil(renderedPanelCount / effectiveColumns);
const chartHeight = computeChartHeight(availableHeight, rowCount);
return (
<SimpleGrid cols={columns} spacing="md">
<SimpleGrid cols={effectiveColumns} spacing="md">
{visibility.cpu && cpuData.length > 0 && (
<BeszelChartPanel
title={t("chart.cpu.title")}
subtitle={t("chart.cpu.subtitle")}
chartProps={{
h: CHART_HEIGHT,
h: chartHeight,
withXAxis: showXAxis,
data: cpuData,
series: series.cpu,
yAxisFormatter: chartAxisFormatters.percent,
yAxisFormatter: formatPercent,
yAxisDomain: CPU_Y_AXIS_DOMAIN,
tooltipProps: tooltipPercent,
tooltipProps: tooltips.percent,
}}
/>
)}
@@ -240,12 +312,13 @@ export function BeszelStatsView({
title={t("chart.memory.title")}
subtitle={t("chart.memory.subtitle")}
chartProps={{
h: CHART_HEIGHT,
h: chartHeight,
withXAxis: showXAxis,
data: memoryData,
type: "stacked",
series: series.memory,
yAxisFormatter: chartAxisFormatters.gb,
tooltipProps: tooltipGB,
yAxisFormatter: byteAxisFormatters.bytes,
tooltipProps: tooltips.bytes,
}}
/>
)}
@@ -254,12 +327,13 @@ export function BeszelStatsView({
title={t("chart.disk.title")}
subtitle={t("chart.disk.subtitle")}
chartProps={{
h: CHART_HEIGHT,
h: chartHeight,
withXAxis: showXAxis,
data: diskData,
type: "stacked",
series: diskSeries,
yAxisFormatter: chartAxisFormatters.gb,
tooltipProps: tooltipGB,
yAxisFormatter: byteAxisFormatters.bytes,
tooltipProps: tooltips.bytes,
}}
/>
)}
@@ -268,11 +342,12 @@ export function BeszelStatsView({
title={t("chart.diskIO.title")}
subtitle={t("chart.diskIO.subtitle")}
chartProps={{
h: CHART_HEIGHT,
h: chartHeight,
withXAxis: showXAxis,
data: diskIOData,
series: series.diskIO,
yAxisFormatter: chartAxisFormatters.rate,
tooltipProps: tooltipRate,
series: diskIOSeries,
yAxisFormatter: byteAxisFormatters.rate,
tooltipProps: tooltips.rate,
}}
/>
)}
@@ -281,11 +356,12 @@ export function BeszelStatsView({
title={t("chart.network.title")}
subtitle={t("chart.network.subtitle")}
chartProps={{
h: CHART_HEIGHT,
h: chartHeight,
withXAxis: showXAxis,
data: networkData,
series: series.network,
yAxisFormatter: chartAxisFormatters.rate,
tooltipProps: tooltipRate,
yAxisFormatter: byteAxisFormatters.rate,
tooltipProps: tooltips.rate,
}}
/>
)}
@@ -296,12 +372,13 @@ export function BeszelStatsView({
title={t("chart.dockerCpu.title")}
subtitle={t("chart.dockerCpu.subtitle")}
chartProps={{
h: CHART_HEIGHT,
h: chartHeight,
withXAxis: showXAxis,
data: dockerCpuData,
type: "stacked",
series: containerSeries,
yAxisFormatter: chartAxisFormatters.percent,
tooltipProps: tooltipPercentTotal,
yAxisFormatter: formatPercent,
tooltipProps: tooltips.percentTotal,
}}
/>
)}
@@ -310,12 +387,13 @@ export function BeszelStatsView({
title={t("chart.dockerMemory.title")}
subtitle={t("chart.dockerMemory.subtitle")}
chartProps={{
h: CHART_HEIGHT,
h: chartHeight,
withXAxis: showXAxis,
data: dockerMemoryData,
type: "stacked",
series: containerSeries,
yAxisFormatter: chartAxisFormatters.bytes,
tooltipProps: tooltipBytesTotal,
yAxisFormatter: byteAxisFormatters.bytes,
tooltipProps: tooltips.bytesTotal,
}}
/>
)}
@@ -324,11 +402,12 @@ export function BeszelStatsView({
title={t("chart.dockerNetwork.title")}
subtitle={t("chart.dockerNetwork.subtitle")}
chartProps={{
h: CHART_HEIGHT,
h: chartHeight,
withXAxis: showXAxis,
data: dockerNetworkData,
series: containerSeries,
yAxisFormatter: chartAxisFormatters.rate,
tooltipProps: tooltipRate,
yAxisFormatter: byteAxisFormatters.rate,
tooltipProps: tooltips.rate,
}}
/>
)}
@@ -1,10 +1,9 @@
"use client";
import type { CSSProperties } from "react";
import dayjs from "dayjs";
import localizedFormat from "dayjs/plugin/localizedFormat";
import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";
dayjs.extend(localizedFormat);
import { formatLocalizedDate } from "../../common/locale";
const styles: Record<string, CSSProperties> = {
wrapper: {
@@ -12,7 +11,7 @@ const styles: Record<string, CSSProperties> = {
border: "1px solid var(--mantine-color-dark-4)",
borderRadius: 6,
padding: "6px 10px",
fontSize: 12,
fontSize: "var(--mantine-font-size-xs)",
lineHeight: 1.5,
pointerEvents: "none",
overflowX: "hidden",
@@ -54,6 +53,8 @@ interface BeszelTooltipProps {
}
const BeszelTooltipContent = ({ active, label, payload, formatter, showTotal }: BeszelTooltipProps) => {
const locale = useCurrentIntlLocale();
const t = useI18n("common");
const isActive = active && (payload?.length ?? 0) > 0;
if (!isActive) return null;
@@ -66,7 +67,9 @@ const BeszelTooltipContent = ({ active, label, payload, formatter, showTotal }:
if (!sorted.length) return null;
const rawTime = sorted[0]?.payload?.rawTime as string | undefined;
const tooltipLabel = rawTime ? dayjs(rawTime).format("MMM D, LT") : label;
const tooltipLabel = rawTime
? formatLocalizedDate(rawTime, locale, { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" })
: label;
const total = sorted.reduce((sum, p) => sum + p.value, 0);
return (
@@ -81,7 +84,7 @@ const BeszelTooltipContent = ({ active, label, payload, formatter, showTotal }:
))}
{showTotal && sorted.length > 1 && (
<div style={{ ...styles.row, ...styles.separator }}>
<span style={styles.name}>Total</span>
<span style={styles.name}>{t("total")}</span>
<span style={styles.value}>{formatter(total)}</span>
</div>
)}
@@ -100,6 +103,6 @@ export const makeTooltipProps = (formatter: (v: number) => string, showTotal = f
showTotal={showTotal}
/>
),
wrapperStyle: { zIndex: 10000, pointerEvents: "none" as const },
wrapperStyle: { pointerEvents: "none" as const },
isAnimationActive: false,
});