Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

💄 style(device): raise load-average warning thresholds and lay health charts out in two columns (#22770)

Arvin Xu920ed52d1c6f
diff --git a/src/features/DeviceManager/DeviceHealth/UsageMeter.tsx b/src/features/DeviceManager/DeviceHealth/UsageMeter.tsx
index f92349015c9..95ab8d43b2b 100644
--- a/src/features/DeviceManager/DeviceHealth/UsageMeter.tsx
+++ b/src/features/DeviceManager/DeviceHealth/UsageMeter.tsx
@@ -6,7 +6,7 @@ import { type ReactNode, useRef } from 'react';
import SkeletonBar from '@/components/Skeleton/Bar';
-import { formatPercent, usageLevel } from './format';
+import { formatPercent, usageLevel, type UsageThresholds } from './format';
import { USAGE_COLOR, usageTextColor } from './shared';
/**
@@ -57,6 +57,8 @@ export const litSegments = (value: number | null | undefined, segments: number)
interface UsageBarProps {
/** Bar height in px. */
height?: number;
+ /** Where the bar turns yellow / red; CPU-style shares by default. */
+ thresholds?: UsageThresholds;
value: number | null | undefined;
}
@@ -64,11 +66,11 @@ interface UsageBarProps {
* The segmented bar alone, colored by the normal / high / critical thresholds.
* No reading keeps every segment unlit.
*/
-export const UsageBar = ({ height = 12, value }: UsageBarProps) => {
+export const UsageBar = ({ height = 12, thresholds, value }: UsageBarProps) => {
const ref = useRef<HTMLDivElement>(null);
const size = useSize(ref);
const segments = segmentCount(size?.width ?? 0);
- const level = usageLevel(value);
+ const level = usageLevel(value, thresholds);
const lit = litSegments(value, segments);
const color = level ? USAGE_COLOR[level] : cssVar.colorFillSecondary;
@@ -87,6 +89,7 @@ export const UsageBar = ({ height = 12, value }: UsageBarProps) => {
interface UsageMeterProps {
label: string;
+ thresholds?: UsageThresholds;
value: number | null | undefined;
}
@@ -128,15 +131,15 @@ export const UsageMeterSkeleton = () => (
* the bar unlit and the value as an em dash, so a card keeps its height
* whether or not the device has reported. Render inside {@link UsageMeterGroup}.
*/
-const UsageMeter = ({ label, value }: UsageMeterProps) => {
- const level = usageLevel(value);
+const UsageMeter = ({ label, thresholds, value }: UsageMeterProps) => {
+ const level = usageLevel(value, thresholds);
return (
<>
<Text fontSize={13} style={{ whiteSpace: 'nowrap' }} type={'secondary'}>
{label}
</Text>
- <UsageBar value={value} />
+ <UsageBar thresholds={thresholds} value={value} />
<Text
fontSize={13}
style={{ color: usageTextColor(level), textAlign: 'end' }}
diff --git a/src/features/DeviceManager/DeviceHealth/format.test.ts b/src/features/DeviceManager/DeviceHealth/format.test.ts
index ad7042d64bf..e84d0f80538 100644
--- a/src/features/DeviceManager/DeviceHealth/format.test.ts
+++ b/src/features/DeviceManager/DeviceHealth/format.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { formatPercent, peakUsageLevel, usageLevel } from './format';
+import { formatPercent, LOAD_THRESHOLDS, peakUsageLevel, usageLevel } from './format';
describe('device health formatters', () => {
// The chart calls its formatter for every slot, including slots with no
@@ -24,9 +24,16 @@ describe('usage levels', () => {
expect(usageLevel(null)).toBeUndefined();
});
- it('rates a block by its busiest metric', () => {
- expect(peakUsageLevel(40, 55, 96)).toBe('critical');
- expect(peakUsageLevel(null, 82, undefined)).toBe('high');
- expect(peakUsageLevel(null, undefined)).toBeUndefined();
+ it('rates load per core: yellow above the core count, red only at twice it', () => {
+ expect(usageLevel(99.9, LOAD_THRESHOLDS)).toBe('normal');
+ expect(usageLevel(129, LOAD_THRESHOLDS)).toBe('high');
+ expect(usageLevel(199.9, LOAD_THRESHOLDS)).toBe('high');
+ expect(usageLevel(200, LOAD_THRESHOLDS)).toBe('critical');
+ });
+
+ it('rates a block by its hottest level', () => {
+ expect(peakUsageLevel('normal', 'normal', 'critical')).toBe('critical');
+ expect(peakUsageLevel(undefined, 'high', 'normal')).toBe('high');
+ expect(peakUsageLevel(undefined, undefined)).toBeUndefined();
});
});
diff --git a/src/features/DeviceManager/DeviceHealth/format.ts b/src/features/DeviceManager/DeviceHealth/format.ts
index 4ee151faad6..532d4197604 100644
--- a/src/features/DeviceManager/DeviceHealth/format.ts
+++ b/src/features/DeviceManager/DeviceHealth/format.ts
@@ -4,21 +4,39 @@ type ChartValue = number | null | undefined;
export const formatPercent = (value: ChartValue) =>
value === null || value === undefined ? '—' : `${Math.round(value)}%`;
-/** How loaded a machine is: yellow from 80%, red from 95%. */
+/** How loaded a machine is: green, yellow, then red. */
export type UsageLevel = 'normal' | 'high' | 'critical';
-export const HIGH_USAGE_PERCENT = 80;
-export const CRITICAL_USAGE_PERCENT = 95;
+export interface UsageThresholds {
+ critical: number;
+ high: number;
+}
-export const usageLevel = (value: ChartValue): UsageLevel | undefined => {
+/** CPU / memory / disk share: yellow from 80%, red from 95%. */
+export const USAGE_THRESHOLDS: UsageThresholds = { critical: 95, high: 80 };
+
+/**
+ * Load average per core. macOS counts threads waiting on disk as well as
+ * runnable ones, so a busy dev machine sits above 100% with CPU to spare:
+ * yellow once threads outnumber cores, red only at twice the cores.
+ */
+export const LOAD_THRESHOLDS: UsageThresholds = { critical: 200, high: 100 };
+
+export const usageLevel = (
+ value: ChartValue,
+ thresholds: UsageThresholds = USAGE_THRESHOLDS,
+): UsageLevel | undefined => {
if (value === null || value === undefined) return undefined;
- if (value >= CRITICAL_USAGE_PERCENT) return 'critical';
- if (value >= HIGH_USAGE_PERCENT) return 'high';
+ if (value >= thresholds.critical) return 'critical';
+ if (value >= thresholds.high) return 'high';
return 'normal';
};
-/** The level of the busiest of several readings — a block is as hot as its hottest metric. */
-export const peakUsageLevel = (...values: ChartValue[]): UsageLevel | undefined => {
- const present = values.filter((v): v is number => v !== null && v !== undefined);
- return present.length === 0 ? undefined : usageLevel(Math.max(...present));
-};
+const LEVEL_RANK: Record<UsageLevel, number> = { critical: 2, high: 1, normal: 0 };
+
+/** The hottest of several levels — a block is as hot as its hottest metric. */
+export const peakUsageLevel = (...levels: (UsageLevel | undefined)[]): UsageLevel | undefined =>
+ levels.reduce<UsageLevel | undefined>(
+ (peak, level) => (level && (!peak || LEVEL_RANK[level] > LEVEL_RANK[peak]) ? level : peak),
+ undefined,
+ );
diff --git a/src/features/DeviceManager/DeviceHealth/index.tsx b/src/features/DeviceManager/DeviceHealth/index.tsx
index b3ed8f467e2..e6c3e93713c 100644
--- a/src/features/DeviceManager/DeviceHealth/index.tsx
+++ b/src/features/DeviceManager/DeviceHealth/index.tsx
@@ -3,12 +3,13 @@
import type { DeviceScope } from '@lobechat/types';
import { AreaChart, Tracker } from '@lobehub/charts';
import { Button, Flexbox, Text } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
import { useTranslation } from 'react-i18next';
import { formatSize } from '@/utils/format';
import { buildHealthTimeline, groupStripBlocks, type HealthSlot } from './buildHealthTimeline';
-import { formatPercent, usageLevel } from './format';
+import { formatPercent, LOAD_THRESHOLDS, usageLevel, type UsageThresholds } from './format';
import {
blockColor,
formatClock as time,
@@ -27,21 +28,41 @@ export { HealthLegend } from './shared';
*/
const STRIP_BLOCK_MS = 5 * 60_000;
+const styles = stylex.create({
+ /**
+ * Charts side by side, at most two per row: each column is at least half
+ * the row, so a third chart wraps instead of squeezing in, and a row too
+ * narrow for two 320px charts falls back to one column, which itself
+ * shrinks to the row when the row is under 320px.
+ */
+ charts: {
+ display: 'grid',
+ gap: 16,
+ gridTemplateColumns:
+ 'repeat(auto-fill, minmax(max(min(100%, 320px), calc((100% - 16px) / 2)), 1fr))',
+ },
+});
+
interface MetricChartProps {
ceiling: number;
data: { time: string; value: number | null }[];
label: string;
latest: number | null | undefined;
+ thresholds?: UsageThresholds;
}
/** Left: what is measured (with its size); right: the latest share, colored by level. */
-const MetricChart = ({ ceiling, data, label, latest }: MetricChartProps) => (
+const MetricChart = ({ ceiling, data, label, latest, thresholds }: MetricChartProps) => (
<Flexbox gap={4}>
<Flexbox horizontal align={'baseline'} distribution={'space-between'}>
<Text fontSize={12} type={'secondary'}>
{label}
</Text>
- <Text fontSize={12} style={{ color: usageTextColor(usageLevel(latest)) }} weight={500}>
+ <Text
+ fontSize={12}
+ style={{ color: usageTextColor(usageLevel(latest, thresholds)) }}
+ weight={500}
+ >
{formatPercent(latest)}
</Text>
</Flexbox>
@@ -139,30 +160,33 @@ const DeviceHealth = ({ deviceId, scope }: { deviceId: string; scope: DeviceScop
</Flexbox>
</Flexbox>
- <MetricChart
- ceiling={100}
- data={rows((slot) => slot.cpuPercent)}
- label={t('devices.health.cpuCores', { count: cores })}
- latest={timeline.latest?.cpuPercent}
- />
- <MetricChart
- ceiling={100}
- data={rows((slot) => slot.memoryPercent)}
- latest={timeline.latest?.memoryPercent}
- label={
- data.memoryTotalBytes
- ? `${t('devices.health.memory')} · ${formatSize(data.memoryTotalBytes)}`
- : t('devices.health.memory')
- }
- />
- {timeline.slots.some((slot) => slot.loadPercent !== null) && (
+ <div {...stylex.props(styles.charts)}>
+ <MetricChart
+ ceiling={100}
+ data={rows((slot) => slot.cpuPercent)}
+ label={t('devices.health.cpuCores', { count: cores })}
+ latest={timeline.latest?.cpuPercent}
+ />
<MetricChart
- ceiling={timeline.loadCeiling}
- data={rows((slot) => slot.loadPercent)}
- label={t('devices.health.load', { count: cores })}
- latest={timeline.latest?.loadPercent}
+ ceiling={100}
+ data={rows((slot) => slot.memoryPercent)}
+ latest={timeline.latest?.memoryPercent}
+ label={
+ data.memoryTotalBytes
+ ? `${t('devices.health.memory')} · ${formatSize(data.memoryTotalBytes)}`
+ : t('devices.health.memory')
+ }
/>
- )}
+ {timeline.slots.some((slot) => slot.loadPercent !== null) && (
+ <MetricChart
+ ceiling={timeline.loadCeiling}
+ data={rows((slot) => slot.loadPercent)}
+ label={t('devices.health.load', { count: cores })}
+ latest={timeline.latest?.loadPercent}
+ thresholds={LOAD_THRESHOLDS}
+ />
+ )}
+ </div>
</Flexbox>
);
};
diff --git a/src/features/DeviceManager/DeviceHealth/shared.tsx b/src/features/DeviceManager/DeviceHealth/shared.tsx
index cf3712b82d6..57d94c90abb 100644
--- a/src/features/DeviceManager/DeviceHealth/shared.tsx
+++ b/src/features/DeviceManager/DeviceHealth/shared.tsx
@@ -6,7 +6,13 @@ import { useTranslation } from 'react-i18next';
import { deviceSelectors, useDeviceStore } from '@/store/device';
import type { HealthSlotStatus, HealthStripBlock } from './buildHealthTimeline';
-import { formatPercent, peakUsageLevel, type UsageLevel } from './format';
+import {
+ formatPercent,
+ LOAD_THRESHOLDS,
+ peakUsageLevel,
+ type UsageLevel,
+ usageLevel,
+} from './format';
/**
* The device's health series, from the device store's replica. The list-row
@@ -51,8 +57,11 @@ const STATUS_COLOR: Record<Exclude<HealthSlotStatus, 'online'>, string> = {
export const blockColor = (block: HealthStripBlock) =>
block.status === 'online'
? USAGE_COLOR[
- peakUsageLevel(block.peak.cpuPercent, block.peak.memoryPercent, block.peak.loadPercent) ??
- 'normal'
+ peakUsageLevel(
+ usageLevel(block.peak.cpuPercent),
+ usageLevel(block.peak.memoryPercent),
+ usageLevel(block.peak.loadPercent, LOAD_THRESHOLDS),
+ ) ?? 'normal'
]
: STATUS_COLOR[block.status];
diff --git a/src/features/DeviceManager/DeviceHoverPanel.tsx b/src/features/DeviceManager/DeviceHoverPanel.tsx
index d2a4013e2f6..4c6a40a9e75 100644
--- a/src/features/DeviceManager/DeviceHoverPanel.tsx
+++ b/src/features/DeviceManager/DeviceHoverPanel.tsx
@@ -24,6 +24,7 @@ import { useTranslation } from 'react-i18next';
import { formatSize } from '@/utils/format';
import { DeviceRunningSummaryValue } from './DeviceActivity/RunningUsers';
+import { LOAD_THRESHOLDS } from './DeviceHealth/format';
import { useDeviceMetricSeries } from './DeviceHealth/shared';
import UsageMeter, { UsageMeterGroup, UsageMeterSkeleton } from './DeviceHealth/UsageMeter';
import { latestUsageView } from './DeviceHealth/viewState';
@@ -185,6 +186,7 @@ const DeviceHoverPanel = ({ device }: DeviceHoverPanelProps) => {
{usage.reportsLoad && (
<UsageMeter
label={t('devices.detail.loadUsage')}
+ thresholds={LOAD_THRESHOLDS}
value={usage.latest?.loadPercent}
/>
)}
diff --git a/src/features/DeviceManager/DeviceOverview.tsx b/src/features/DeviceManager/DeviceOverview.tsx
index daf89bb3e36..6dbf5b02058 100644
--- a/src/features/DeviceManager/DeviceOverview.tsx
+++ b/src/features/DeviceManager/DeviceOverview.tsx
@@ -47,7 +47,12 @@ import Connections from './Connections';
import { refreshDeviceList } from './const';
import { BoundAgentList, RunningTopicList } from './DeviceActivity';
import DeviceHealth, { HealthLegend } from './DeviceHealth';
-import { formatPercent, usageLevel } from './DeviceHealth/format';
+import {
+ formatPercent,
+ LOAD_THRESHOLDS,
+ usageLevel,
+ type UsageThresholds,
+} from './DeviceHealth/format';
import { usageTextColor, useDeviceMetricSeries } from './DeviceHealth/shared';
import { UsageBar } from './DeviceHealth/UsageMeter';
import { latestUsageView } from './DeviceHealth/viewState';
@@ -198,12 +203,13 @@ interface StatCardProps {
icon: LucideIcon;
/** First read still in flight: placeholders in the reading's own line boxes. */
loading?: boolean;
+ thresholds?: UsageThresholds;
title: string;
value: number | null | undefined;
}
/** One reading at a glance: the big share, its absolute size, and the segmented bar. */
-const StatCard = ({ detail, icon, loading, title, value }: StatCardProps) => (
+const StatCard = ({ detail, icon, loading, thresholds, title, value }: StatCardProps) => (
<DetailCard icon={icon} title={title}>
{loading ? (
<Flexbox aria-busy gap={14}>
@@ -217,7 +223,7 @@ const StatCard = ({ detail, icon, loading, title, value }: StatCardProps) => (
<Flexbox horizontal align={'baseline'} distribution={'space-between'} gap={8}>
<Text
fontSize={28}
- style={{ color: usageTextColor(usageLevel(value)), lineHeight: 1.2 }}
+ style={{ color: usageTextColor(usageLevel(value, thresholds)), lineHeight: 1.2 }}
weight={600}
>
{formatPercent(value)}
@@ -228,7 +234,7 @@ const StatCard = ({ detail, icon, loading, title, value }: StatCardProps) => (
</Text>
)}
</Flexbox>
- <UsageBar height={8} value={value} />
+ <UsageBar height={8} thresholds={thresholds} value={value} />
</Flexbox>
)}
</DetailCard>
@@ -431,6 +437,7 @@ const DeviceOverview = ({ canOperate, device }: DeviceOverviewProps) => {
<StatCard
icon={GaugeIcon}
loading={usage.loading}
+ thresholds={LOAD_THRESHOLDS}
title={t('devices.detail.loadUsage')}
value={latest?.loadPercent}
detail={
diff --git a/src/features/DeviceManager/deviceLoadHint.test.ts b/src/features/DeviceManager/deviceLoadHint.test.ts
index ab3bde05f59..388d493d07e 100644
--- a/src/features/DeviceManager/deviceLoadHint.test.ts
+++ b/src/features/DeviceManager/deviceLoadHint.test.ts
@@ -38,6 +38,13 @@ describe('loadHint', () => {
});
});
+ it('keeps load above the core count yellow until it doubles', () => {
+ expect(loadHint({ cpuPercent: 55, loadPercent: 129, memoryPercent: 62 })).toMatchObject({
+ level: 'high',
+ lit: 5,
+ });
+ });
+
it('ignores a reading the platform does not have', () => {
const hint = loadHint({ cpuPercent: 10, loadPercent: null, memoryPercent: 20 });
expect(hint?.readings.map((r) => r.metric)).toEqual(['cpu', 'memory']);
diff --git a/src/features/DeviceManager/deviceLoadHint.ts b/src/features/DeviceManager/deviceLoadHint.ts
index ce438ebf9ae..858fdda2232 100644
--- a/src/features/DeviceManager/deviceLoadHint.ts
+++ b/src/features/DeviceManager/deviceLoadHint.ts
@@ -1,5 +1,10 @@
import type { HealthUsage } from './DeviceHealth/buildHealthTimeline';
-import { type UsageLevel, usageLevel } from './DeviceHealth/format';
+import {
+ LOAD_THRESHOLDS,
+ peakUsageLevel,
+ type UsageLevel,
+ usageLevel,
+} from './DeviceHealth/format';
/** Segments of the level meter, bottom to top; each stands for 20%. */
export const LOAD_HINT_SEGMENTS = 5;
@@ -18,7 +23,7 @@ export interface LoadHint {
/**
* One meter for the whole machine: a run stalls on whichever of CPU, memory
* or load is exhausted, so the meter shows the busiest of them, with the same
- * yellow / red thresholds as the device page. Load averages are absent on
+ * yellow / red thresholds as the device page (load has its own, higher ones). Load averages are absent on
* Windows and are then simply not considered. Load above 100% of the cores
* fills the meter; any non-zero reading lights the bottom segment, so a
* running machine never reads as empty.
@@ -42,5 +47,9 @@ export const loadHint = (usage: HealthUsage | null): LoadHint | null => {
? 0
: Math.min(LOAD_HINT_SEGMENTS, Math.max(1, Math.ceil((peak / 100) * LOAD_HINT_SEGMENTS)));
- return { level: usageLevel(peak) ?? 'normal', lit, readings };
+ const level = peakUsageLevel(
+ ...readings.map((r) => usageLevel(r.value, r.metric === 'load' ? LOAD_THRESHOLDS : undefined)),
+ );
+
+ return { level: level ?? 'normal', lit, readings };
};