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.

✨ feat(device): show a load meter in the composer's device chip (#21690)

LiJiand8799acb4a73
diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
index ee457a187b2..5504bfdf064 100644
--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
@@ -30,6 +30,7 @@ import { DOWNLOAD_URL } from '@/const/url';
import { useChatInputResourceAccess } from '@/features/ChatInput/hooks/useChatInputResourceAccess';
import { useLocalSandboxCapability } from '@/features/ChatInput/hooks/useLocalSandboxCapability';
import { useSelectExecutionTarget } from '@/features/ChatInput/hooks/useSelectExecutionTarget';
+import DeviceLoadMeter, { useDeviceLoad } from '@/features/DeviceManager/DeviceLoadMeter';
import {
devicePoolForAgent,
ExecutionTargetIcon,
@@ -474,12 +475,14 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
isWorkspacePreferenceLoading,
]);
- if (!canShowExecutionTarget) return null;
-
const boundDevice =
canShowExecutionTargetSelector && executionTarget === 'device'
? devices?.find((d) => d.deviceId === boundDeviceId)
: undefined;
+ // Only a picked remote device; the local machine is the one already in front of the user.
+ const load = useDeviceLoad(topicDeviceUnknown ? undefined : boundDevice);
+
+ if (!canShowExecutionTarget) return null;
// The picker splits by whether the caller is inside a workspace agent:
// - **Personal agent** — flat list of the caller's personal-scope devices
@@ -828,6 +831,7 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
<div className={cx(styles.button, !canShowExecutionTargetSelector && styles.buttonReadonly)}>
{chipIcon}
<span className={styles.buttonLabel}>{chipLabel}</span>
+ {load && <DeviceLoadMeter load={load} />}
{canShowExecutionTargetSelector ? <Icon icon={ChevronDownIcon} size={12} /> : null}
</div>
);
@@ -854,7 +858,8 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
trigger="click"
onOpenChange={setOpen}
>
- {chip}
+ {/* A stable wrapper, so adding the load tooltip never swaps the popover's anchor. */}
+ <div>{open || !load ? chip : <Tooltip title={load.summary}>{chip}</Tooltip>}</div>
</Popover>
);
});
diff --git a/src/features/ChatInput/ControlBar/ProjectDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/ProjectDeviceSwitcher.tsx
index ef71d05410a..552b628595a 100644
--- a/src/features/ChatInput/ControlBar/ProjectDeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/ProjectDeviceSwitcher.tsx
@@ -6,6 +6,7 @@ import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useChatInputResourceAccess } from '@/features/ChatInput/hooks/useChatInputResourceAccess';
+import DeviceLoadMeter, { useDeviceLoad } from '@/features/DeviceManager/DeviceLoadMeter';
import { ExecutionTargetDeviceStatus, ExecutionTargetIcon } from '@/features/ExecutionTargetPicker';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
@@ -80,6 +81,7 @@ const ProjectDeviceSwitcher = ({
const { canUseResource } = useChatInputResourceAccess();
const directory = directories.find((d) => d.id === directoryId);
const { data: devices } = useDeviceList();
+ const load = useDeviceLoad(devices?.find((d) => d.deviceId === directory?.deviceId));
// The shared row, not the topic-pinned effective config: a fixed target is
// the author's setting, and it is what the server checks the move against.
const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));
@@ -155,10 +157,19 @@ const ProjectDeviceSwitcher = ({
? projectDirectoryDeviceName(directory, devices)
: t('heteroAgent.executionTarget.unknownDevice')}
</span>
+ {load && <DeviceLoadMeter load={load} />}
<Icon icon={ChevronDownIcon} size={12} />
</div>
);
+ // The tooltip's body lays its children out in a row; stack the two lines.
+ const tooltip = directory ? (
+ <Flexbox gap={4}>
+ <span>{t('directories.boundTip', { ns: 'project', path: directory.path })}</span>
+ {load && <span>{load.summary}</span>}
+ </Flexbox>
+ ) : undefined;
+
return (
<Popover
content={content}
@@ -168,15 +179,7 @@ const ProjectDeviceSwitcher = ({
trigger="click"
onOpenChange={setOpen}
>
- <div>
- {open || !directory ? (
- trigger
- ) : (
- <Tooltip title={t('directories.boundTip', { ns: 'project', path: directory.path })}>
- {trigger}
- </Tooltip>
- )}
- </div>
+ <div>{open || !tooltip ? trigger : <Tooltip title={tooltip}>{trigger}</Tooltip>}</div>
</Popover>
);
};
diff --git a/src/features/DeviceManager/DeviceHealth/shared.tsx b/src/features/DeviceManager/DeviceHealth/shared.tsx
index 5ee153ed504..cf3712b82d6 100644
--- a/src/features/DeviceManager/DeviceHealth/shared.tsx
+++ b/src/features/DeviceManager/DeviceHealth/shared.tsx
@@ -1,35 +1,35 @@
-import type { DeviceMetricSeries, DeviceScope } from '@lobechat/types';
+import type { DeviceScope } from '@lobechat/types';
import { cssVar, Flexbox, Text } from '@lobehub/ui';
import dayjs from 'dayjs';
import { useTranslation } from 'react-i18next';
-import { useClientDataSWR } from '@/libs/swr';
-import { deviceService } from '@/services/device';
+import { deviceSelectors, useDeviceStore } from '@/store/device';
import type { HealthSlotStatus, HealthStripBlock } from './buildHealthTimeline';
import { formatPercent, peakUsageLevel, type UsageLevel } from './format';
-const DEVICE_METRICS_SWR_KEY = 'device/metricSeries';
-/** Devices upload every 5 minutes; polling faster only re-reads the same samples. */
-const REFRESH_INTERVAL_MS = 5 * 60_000;
-
/**
- * The device's health series. The list-row preview and the detail panel read
- * the same key, so opening a device reuses the preview's data. `scope` is the
- * list item's, so a deviceId enrolled both personally and in the workspace
- * reads the row it was listed as. `enabled: false` (an off-screen row) stops
- * fetching; cached data comes back when it is on screen again.
+ * The device's health series, from the device store's replica. The list-row
+ * preview, the hover panel, the composer chip and the detail panel read the
+ * same entry, so opening a device reuses the preview's data, and a revisit
+ * charts the persisted copy before the server answers. `scope` is the list
+ * item's, so a deviceId enrolled both personally and in the workspace reads
+ * the row it was listed as. `enabled: false` (an off-screen row) stops
+ * fetching; the stored series stays.
*/
export const useDeviceMetricSeries = (
deviceId: string,
scope: DeviceScope | undefined,
enabled = true,
-) =>
- useClientDataSWR<DeviceMetricSeries>(
- enabled ? [DEVICE_METRICS_SWR_KEY, deviceId, scope] : null,
- () => deviceService.getMetricSeries(deviceId, scope),
- { refreshInterval: REFRESH_INTERVAL_MS },
+) => {
+ const params = { deviceId, scope };
+ const { error, isValidating, revalidate } = useDeviceStore((s) => s.useFetchDeviceMetricSeries)(
+ params,
+ enabled && !!deviceId,
);
+ const data = useDeviceStore(deviceSelectors.getMetricSeries(params));
+ return { data, error, isValidating, mutate: revalidate };
+};
export const USAGE_COLOR: Record<UsageLevel, string> = {
critical: cssVar.colorError,
diff --git a/src/features/DeviceManager/DeviceHealth/viewState.test.ts b/src/features/DeviceManager/DeviceHealth/viewState.test.ts
index 6ad76bbb49a..af728cd17f6 100644
--- a/src/features/DeviceManager/DeviceHealth/viewState.test.ts
+++ b/src/features/DeviceManager/DeviceHealth/viewState.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { healthViewState, latestUsageView } from './viewState';
+import { currentUsage, healthViewState, latestUsageView } from './viewState';
const series = (points: number) =>
({
@@ -70,3 +70,48 @@ describe('latestUsageView', () => {
});
});
});
+
+describe('currentUsage', () => {
+ const BUCKET = 5 * 60_000;
+ const to = 1000 * BUCKET;
+ const at = (observedAt: number) => ({
+ bucketMs: BUCKET,
+ cpuCount: 4,
+ from: to - 144 * BUCKET,
+ memoryTotalBytes: 100,
+ points: [
+ {
+ connected: true,
+ cpuPercent: 12,
+ load1: 2,
+ memoryPercent: 40,
+ memoryUsedBytes: 40,
+ observedAt,
+ },
+ ],
+ to,
+ });
+
+ it('reads the newest point while it is recent, with load relative to the cores', () => {
+ expect(currentUsage(at(to - BUCKET), to)).toEqual({
+ cpuPercent: 12,
+ loadPercent: 50,
+ memoryPercent: 40,
+ });
+ });
+
+ // A device that just reconnected still has last night's samples; the chip must not show them as now.
+ it('drops a reading older than one bucket plus the upload grace', () => {
+ expect(currentUsage(at(to - BUCKET - 11 * 60_000), to)).toBeNull();
+ });
+
+ // A persisted series painted on reload is fresh relative to its own `to`, but hours old now.
+ it('judges age by the wall clock, not by the series end', () => {
+ expect(currentUsage(at(to), to + 3 * 60 * 60_000)).toBeNull();
+ });
+
+ it('has nothing to read without data or samples', () => {
+ expect(currentUsage(undefined, to)).toBeNull();
+ expect(currentUsage(series(0), to)).toBeNull();
+ });
+});
diff --git a/src/features/DeviceManager/DeviceHealth/viewState.ts b/src/features/DeviceManager/DeviceHealth/viewState.ts
index cf745705b91..8ff858e4fa6 100644
--- a/src/features/DeviceManager/DeviceHealth/viewState.ts
+++ b/src/features/DeviceManager/DeviceHealth/viewState.ts
@@ -1,6 +1,11 @@
import type { DeviceMetricSeries } from '@lobechat/types';
-import { buildHealthTimeline, type HealthUsage } from './buildHealthTimeline';
+import {
+ buildHealthTimeline,
+ type HealthUsage,
+ loadPercentOf,
+ UPLOAD_GRACE_MS,
+} from './buildHealthTimeline';
export type HealthViewState = 'empty' | 'error' | 'loading' | 'ready';
@@ -39,3 +44,21 @@ export const latestUsageView = (state: {
loading: false,
};
};
+
+/**
+ * The newest reading, only while it still describes the machine now: taken
+ * within one bucket plus the upload grace of `now`. Judged by the wall clock,
+ * not the series' own `to`: a persisted series painted on a reload is as old
+ * as its newest sample, and a device that just reconnected after a night
+ * offline would otherwise show last night's load as current.
+ */
+export const currentUsage = (data?: DeviceMetricSeries, now = Date.now()): HealthUsage | null => {
+ const newest = data?.points.at(-1);
+ if (!data || !newest) return null;
+ if (now - newest.observedAt > data.bucketMs + UPLOAD_GRACE_MS) return null;
+ return {
+ cpuPercent: newest.cpuPercent,
+ loadPercent: loadPercentOf(newest.load1, data.cpuCount),
+ memoryPercent: newest.memoryPercent,
+ };
+};
diff --git a/src/features/DeviceManager/DeviceLoadMeter.tsx b/src/features/DeviceManager/DeviceLoadMeter.tsx
new file mode 100644
index 00000000000..7a66935ff80
--- /dev/null
+++ b/src/features/DeviceManager/DeviceLoadMeter.tsx
@@ -0,0 +1,79 @@
+'use client';
+
+import type { DeviceListItem } from '@lobechat/types';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { useTranslation } from 'react-i18next';
+
+import { formatPercent } from './DeviceHealth/format';
+import { USAGE_COLOR, useDeviceMetricSeries } from './DeviceHealth/shared';
+import { currentUsage } from './DeviceHealth/viewState';
+import { LOAD_HINT_SEGMENTS, type LoadHint, loadHint, type LoadHintMetric } from './deviceLoadHint';
+
+const styles = stylex.create({
+ lit: (color: string) => ({ backgroundColor: color }),
+ // Bottom segment first in the DOM, stacked upwards.
+ root: {
+ display: 'flex',
+ flex: 'none',
+ flexDirection: 'column-reverse',
+ gap: 1,
+ },
+ segment: {
+ backgroundColor: cssVar.colorFillSecondary,
+ borderRadius: 1,
+ height: 2,
+ width: 8,
+ },
+});
+
+const LABEL_KEY = {
+ cpu: 'devices.health.cpu',
+ load: 'devices.health.loadShort',
+ memory: 'devices.health.memory',
+} as const satisfies Record<LoadHintMetric, string>;
+
+export interface DeviceLoad {
+ hint: LoadHint;
+ /** Every reading on one line, e.g. "CPU 4% · Memory 29% · Load 12%". */
+ summary: string;
+}
+
+/**
+ * The current load of the device a chip names, or `null` while the device is
+ * offline or its newest reading is stale — an old load must not read as
+ * current. The readings are returned as text so the chip can carry them on
+ * its own tooltip, rather than nesting a second tooltip inside the chip.
+ */
+export const useDeviceLoad = (device: DeviceListItem | undefined): DeviceLoad | null => {
+ const { t } = useTranslation('setting');
+ const online = !!device?.online;
+ const { data } = useDeviceMetricSeries(device?.deviceId ?? '', device?.scope, online);
+ const hint = loadHint(online ? currentUsage(data) : null);
+ if (!hint) return null;
+
+ const summary = hint.readings
+ .map(({ metric, value }) => `${t(LABEL_KEY[metric])} ${formatPercent(value)}`)
+ .join(' · ');
+ return { hint, summary };
+};
+
+/**
+ * A five-segment level meter for inside a device chip, between the name and
+ * the chevron, so a busy machine shows before a run is sent there. It rises
+ * with the busiest of CPU, memory and load, colored by the device page's
+ * thresholds.
+ */
+const DeviceLoadMeter = ({ load }: { load: DeviceLoad }) => {
+ const color = USAGE_COLOR[load.hint.level];
+
+ return (
+ <div aria-label={load.summary} role={'img'} {...stylex.props(styles.root)}>
+ {Array.from({ length: LOAD_HINT_SEGMENTS }, (_, i) => (
+ <span key={i} {...stylex.props(styles.segment, i < load.hint.lit && styles.lit(color))} />
+ ))}
+ </div>
+ );
+};
+
+export default DeviceLoadMeter;
diff --git a/src/features/DeviceManager/deviceLoadHint.test.ts b/src/features/DeviceManager/deviceLoadHint.test.ts
new file mode 100644
index 00000000000..ab3bde05f59
--- /dev/null
+++ b/src/features/DeviceManager/deviceLoadHint.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from 'vitest';
+
+import { loadHint } from './deviceLoadHint';
+
+describe('loadHint', () => {
+ it('lights the meter by the busiest reading', () => {
+ expect(loadHint({ cpuPercent: 4, loadPercent: 12, memoryPercent: 29 })).toEqual({
+ level: 'normal',
+ lit: 2,
+ readings: [
+ { metric: 'cpu', value: 4 },
+ { metric: 'memory', value: 29 },
+ { metric: 'load', value: 12 },
+ ],
+ });
+ });
+
+ it('turns yellow and red at the device-page thresholds', () => {
+ expect(loadHint({ cpuPercent: 85, loadPercent: 10, memoryPercent: 10 })).toMatchObject({
+ level: 'high',
+ lit: 5,
+ });
+ expect(loadHint({ cpuPercent: 10, loadPercent: 10, memoryPercent: 97 })).toMatchObject({
+ level: 'critical',
+ lit: 5,
+ });
+ });
+
+ it('lights one segment for any load and none for a true zero', () => {
+ expect(loadHint({ cpuPercent: 1, loadPercent: 0, memoryPercent: 0 })?.lit).toBe(1);
+ expect(loadHint({ cpuPercent: 0, loadPercent: 0, memoryPercent: 0 })?.lit).toBe(0);
+ });
+
+ it('caps an overloaded machine at a full meter', () => {
+ expect(loadHint({ cpuPercent: 10, loadPercent: 250, memoryPercent: 10 })).toMatchObject({
+ level: 'critical',
+ 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']);
+ });
+
+ it('has nothing to show without a reading', () => {
+ expect(loadHint(null)).toBeNull();
+ expect(loadHint({ cpuPercent: null, loadPercent: null, memoryPercent: null })).toBeNull();
+ });
+});
diff --git a/src/features/DeviceManager/deviceLoadHint.ts b/src/features/DeviceManager/deviceLoadHint.ts
new file mode 100644
index 00000000000..ce438ebf9ae
--- /dev/null
+++ b/src/features/DeviceManager/deviceLoadHint.ts
@@ -0,0 +1,46 @@
+import type { HealthUsage } from './DeviceHealth/buildHealthTimeline';
+import { type UsageLevel, usageLevel } from './DeviceHealth/format';
+
+/** Segments of the level meter, bottom to top; each stands for 20%. */
+export const LOAD_HINT_SEGMENTS = 5;
+
+export type LoadHintMetric = 'cpu' | 'memory' | 'load';
+
+export interface LoadHint {
+ /** Color of the lit segments: the level of the busiest reading. */
+ level: UsageLevel;
+ /** Lit segments from the bottom, 0 – {@link LOAD_HINT_SEGMENTS}. */
+ lit: number;
+ /** Every reading the device has, for the tooltip. */
+ readings: { metric: LoadHintMetric; value: number }[];
+}
+
+/**
+ * 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
+ * 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.
+ */
+export const loadHint = (usage: HealthUsage | null): LoadHint | null => {
+ if (!usage) return null;
+ const readings = (
+ [
+ ['cpu', usage.cpuPercent],
+ ['memory', usage.memoryPercent],
+ ['load', usage.loadPercent],
+ ] as const
+ )
+ .filter((entry): entry is readonly [LoadHintMetric, number] => entry[1] !== null)
+ .map(([metric, value]) => ({ metric, value }));
+ if (readings.length === 0) return null;
+
+ const peak = Math.max(...readings.map((r) => r.value));
+ const lit =
+ peak <= 0
+ ? 0
+ : Math.min(LOAD_HINT_SEGMENTS, Math.max(1, Math.ceil((peak / 100) * LOAD_HINT_SEGMENTS)));
+
+ return { level: usageLevel(peak) ?? 'normal', lit, readings };
+};
diff --git a/src/store/device/action.ts b/src/store/device/action.ts
index 76c8be7cb8f..29bbc93a6e6 100644
--- a/src/store/device/action.ts
+++ b/src/store/device/action.ts
@@ -1,11 +1,17 @@
-import type { DeviceListItem, WorkingDirEntry } from '@lobechat/types';
+import type { DeviceListItem, DeviceMetricSeries, WorkingDirEntry } from '@lobechat/types';
import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';
import { deviceService } from '@/services/device';
import { type StoreSetter } from '@/store/types';
import { nextWorkingDirs, removeWorkingDir, WORKING_DIRS_MAX } from './deviceCwd';
-import { DEVICE_LIST_KEY, type DeviceListParams, deviceListResource } from './projection';
+import {
+ DEVICE_LIST_KEY,
+ type DeviceListParams,
+ deviceListResource,
+ type DeviceMetricSeriesParams,
+ deviceMetricSeriesResource,
+} from './projection';
import { deviceSelectors } from './selectors';
import { type DeviceStore } from './store';
@@ -21,6 +27,11 @@ const LIST_PARAMS = {} as DeviceListParams;
*/
const DEVICE_LIST_DEDUPING_INTERVAL = 10_000;
+/** Devices upload every 5 minutes; polling faster only re-reads the same samples. */
+const METRIC_SERIES_REFRESH_INTERVAL = 5 * 60_000;
+/** The chip, the hover panel and the detail page mount one device's series together; let them share one request. */
+const METRIC_SERIES_DEDUPING_INTERVAL = 30_000;
+
type UpdateDeviceInput = Parameters<typeof deviceService.updateDevice>[0];
/**
@@ -39,6 +50,7 @@ export const deviceSlice = (set: Setter, get: () => DeviceStore, _api?: unknown)
export class DeviceActionImpl {
readonly #get: () => DeviceStore;
readonly #list;
+ readonly #metricSeries;
constructor(set: Setter, get: () => DeviceStore, _api?: unknown) {
void _api;
@@ -51,6 +63,14 @@ export class DeviceActionImpl {
stateKey: 'deviceListReplica',
view: recordLens<DeviceStore, DeviceListItem[]>('deviceListMap'),
});
+ this.#metricSeries = createReplicaSlice(deviceMetricSeriesResource, {
+ actionPrefix: 'device/metricSeries',
+ fetcher: ({ deviceId, scope }) => deviceService.getMetricSeries(deviceId, scope),
+ get,
+ set,
+ stateKey: 'deviceMetricSeriesReplica',
+ view: recordLens<DeviceStore, DeviceMetricSeries>('deviceMetricSeriesMap'),
+ });
}
#devices = (): DeviceListItem[] => deviceSelectors.deviceList(this.#get());
@@ -221,6 +241,21 @@ export class DeviceActionImpl {
enabled,
...schedule,
});
+
+ /**
+ * Fetch orchestration for one device's health series; read it with
+ * `deviceSelectors.getMetricSeries`. `enabled: false` (an off-screen card,
+ * an offline device) stops fetching and keeps what the store holds.
+ */
+ useFetchDeviceMetricSeries = (
+ params: DeviceMetricSeriesParams,
+ enabled = true,
+ ): ReplicaSyncResult =>
+ this.#metricSeries.useSync(params, {
+ dedupingInterval: METRIC_SERIES_DEDUPING_INTERVAL,
+ enabled,
+ refreshInterval: METRIC_SERIES_REFRESH_INTERVAL,
+ });
}
export type DeviceAction = Pick<DeviceActionImpl, keyof DeviceActionImpl>;
diff --git a/src/store/device/deviceMetricSeriesReplica.test.ts b/src/store/device/deviceMetricSeriesReplica.test.ts
new file mode 100644
index 00000000000..ce4c15d72e2
--- /dev/null
+++ b/src/store/device/deviceMetricSeriesReplica.test.ts
@@ -0,0 +1,130 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * A device's health series is a replica: every reader (card, hover panel,
+ * composer chip, detail page) shares one entry per device + scope, and a
+ * revisit charts the persisted copy before the server answers.
+ */
+import { randomUUID } from 'node:crypto';
+
+import type { DeviceMetricSeries } from '@lobechat/types';
+import { act, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { deviceService } from '@/services/device';
+
+import { initialState } from './initialState';
+import { type DeviceMetricSeriesParams, deviceMetricSeriesResource } from './projection';
+import { deviceSelectors } from './selectors';
+import { useDeviceStore } from './store';
+
+vi.mock('@/services/device', () => ({
+ deviceService: { getMetricSeries: vi.fn() },
+}));
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map() } },
+ createElement(MutateBridge),
+ children,
+ );
+
+const series = (cpuPercent: number): DeviceMetricSeries => ({
+ bucketMs: 300_000,
+ cpuCount: 8,
+ from: 0,
+ memoryTotalBytes: 100,
+ points: [
+ {
+ connected: true,
+ cpuPercent,
+ load1: 1,
+ memoryPercent: 30,
+ memoryUsedBytes: 30,
+ observedAt: 1,
+ },
+ ],
+ to: 2,
+});
+
+const WORKSPACE: DeviceMetricSeriesParams = { deviceId: 'dev-1', scope: 'workspace' };
+const PERSONAL: DeviceMetricSeriesParams = { deviceId: 'dev-1', scope: 'personal' };
+
+const read = (params: DeviceMetricSeriesParams) =>
+ deviceSelectors.getMetricSeries(params)(useDeviceStore.getState());
+
+describe('device metric series replica', () => {
+ let scope = '';
+
+ beforeEach(() => {
+ scope = `metric-user-${randomUUID()}:personal`;
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ act(() => useDeviceStore.setState(initialState));
+ });
+
+ afterEach(async () => {
+ await Promise.all(
+ [WORKSPACE, PERSONAL].map((params) =>
+ deviceMetricSeriesResource.storage!.remove({
+ queryKey: deviceMetricSeriesResource.storageKey(params),
+ scope,
+ }),
+ ),
+ );
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ it('keeps one entry per device and scope', async () => {
+ vi.mocked(deviceService.getMetricSeries).mockImplementation(async (_id, s) =>
+ series(s === 'workspace' ? 40 : 10),
+ );
+
+ renderHook(
+ () => {
+ useDeviceStore((s) => s.useFetchDeviceMetricSeries)(WORKSPACE);
+ useDeviceStore((s) => s.useFetchDeviceMetricSeries)(PERSONAL);
+ },
+ { wrapper },
+ );
+
+ await waitFor(() => expect(read(WORKSPACE)?.points[0].cpuPercent).toBe(40));
+ await waitFor(() => expect(read(PERSONAL)?.points[0].cpuPercent).toBe(10));
+ expect(deviceService.getMetricSeries).toHaveBeenCalledWith('dev-1', 'workspace');
+ });
+
+ it('charts the persisted series before the network answers', async () => {
+ await deviceMetricSeriesResource.storage!.set(
+ { queryKey: deviceMetricSeriesResource.storageKey(WORKSPACE), scope },
+ { data: series(55), updatedAt: 1 },
+ );
+ vi.mocked(deviceService.getMetricSeries).mockImplementation(() => new Promise(() => {}));
+
+ renderHook(() => useDeviceStore((s) => s.useFetchDeviceMetricSeries)(WORKSPACE), { wrapper });
+
+ await waitFor(() => expect(read(WORKSPACE)?.points[0].cpuPercent).toBe(55));
+ });
+
+ it('does not fetch while disabled', async () => {
+ renderHook(() => useDeviceStore((s) => s.useFetchDeviceMetricSeries)(WORKSPACE, false), {
+ wrapper,
+ });
+
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(deviceService.getMetricSeries).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/store/device/initialState.ts b/src/store/device/initialState.ts
index 40267dbe2a1..233b8fe22d9 100644
--- a/src/store/device/initialState.ts
+++ b/src/store/device/initialState.ts
@@ -1,4 +1,4 @@
-import type { DeviceListItem } from '@lobechat/types';
+import type { DeviceListItem, DeviceMetricSeries } from '@lobechat/types';
import { createReplicaState, type ReplicaState } from '@/libs/replica';
@@ -10,9 +10,15 @@ export interface DeviceState {
deviceListMap: Record<string, DeviceListItem[]>;
/** Replica bookkeeping for `deviceListMap`. */
deviceListReplica: ReplicaState<DeviceListItem[]>;
+ /** Health series per `deviceMetricSeriesKey`; read it through `deviceSelectors.getMetricSeries`. */
+ deviceMetricSeriesMap: Record<string, DeviceMetricSeries>;
+ /** Replica bookkeeping for `deviceMetricSeriesMap`. */
+ deviceMetricSeriesReplica: ReplicaState<DeviceMetricSeries>;
}
export const initialState: DeviceState = {
deviceListMap: {},
deviceListReplica: createReplicaState(),
+ deviceMetricSeriesMap: {},
+ deviceMetricSeriesReplica: createReplicaState(),
};
diff --git a/src/store/device/projection.ts b/src/store/device/projection.ts
index 149f0647d34..6bd4851615b 100644
--- a/src/store/device/projection.ts
+++ b/src/store/device/projection.ts
@@ -1,4 +1,4 @@
-import type { DeviceListItem } from '@lobechat/types';
+import type { DeviceListItem, DeviceMetricSeries, DeviceScope } from '@lobechat/types';
import { AppLocalStorage } from '@/libs/replica';
import { defineReplica, REPLICA_INDEX_KEY, type ReplicaStorage } from '@/libs/replica';
@@ -58,3 +58,30 @@ export const deviceListResource = defineReplica<DeviceListParams, DeviceListItem
storage: createDeviceListStorage('replica:deviceList:v1'),
version: 1,
});
+
+export interface DeviceMetricSeriesParams {
+ deviceId: string;
+ /** The list row's scope: a deviceId enrolled both personally and in the workspace reads the row it was listed as. */
+ scope?: DeviceScope;
+}
+
+export const deviceMetricSeriesKey = ({ deviceId, scope }: DeviceMetricSeriesParams) =>
+ `${scope ?? 'default'}:${deviceId}`;
+
+/**
+ * A device's CPU / memory / load over the recent window, one entry per device.
+ * Persisted so the device page and hover panel chart history on first paint;
+ * the newest reading of a persisted copy is old by however long the app was
+ * closed, so "current load" readers judge it by wall-clock age, never by
+ * presence of data. Bounded: a device grid persists one row per device seen.
+ */
+export const deviceMetricSeriesResource = defineReplica<
+ DeviceMetricSeriesParams,
+ DeviceMetricSeries
+>({
+ key: deviceMetricSeriesKey,
+ name: 'deviceMetricSeries',
+ persist: { maxEntries: 20 },
+ storage: 'indexedDB',
+ version: 1,
+});
diff --git a/src/store/device/selectors.ts b/src/store/device/selectors.ts
index cd6d8d4eae8..16382da69b9 100644
--- a/src/store/device/selectors.ts
+++ b/src/store/device/selectors.ts
@@ -1,9 +1,13 @@
-import type { DeviceListItem } from '@lobechat/types';
+import type { DeviceListItem, DeviceMetricSeries } from '@lobechat/types';
import { getChannelKind } from '@/features/DeviceManager/channelKind';
import type { DeviceState } from './initialState';
-import { DEVICE_LIST_KEY } from './projection';
+import {
+ DEVICE_LIST_KEY,
+ deviceMetricSeriesKey,
+ type DeviceMetricSeriesParams,
+} from './projection';
const EMPTY_DEVICES: DeviceListItem[] = [];
@@ -66,11 +70,18 @@ const getDeviceDefaultCwd =
const getDeviceWorkingDirs = (deviceId: string | undefined) => (s: DeviceState) =>
getDeviceById(deviceId)(s)?.workingDirs ?? [];
+/** A device's health series, or `undefined` until storage or the server answers. */
+const getMetricSeries =
+ (params: DeviceMetricSeriesParams) =>
+ (s: DeviceState): DeviceMetricSeries | undefined =>
+ s.deviceMetricSeriesMap[deviceMetricSeriesKey(params)];
+
export const deviceSelectors = {
deviceList,
getDeviceById,
getDeviceDefaultCwd,
getDeviceWorkingDirs,
+ getMetricSeries,
hasTerminalTarget,
isDeviceListConfirmed,
isDeviceListLoaded,