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 disk usage next to CPU and memory (#21940)

AmAzing-72ebac7507df
diff --git a/apps/server/src/routers/lambda/__tests__/deviceMetric.test.ts b/apps/server/src/routers/lambda/__tests__/deviceMetric.test.ts
index c0e39820e8d..9fe353c23bf 100644
--- a/apps/server/src/routers/lambda/__tests__/deviceMetric.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/deviceMetric.test.ts
@@ -26,16 +26,19 @@ vi.mock('@/server/services/deviceGateway', () => ({
const { deviceMetricRouter } = await import('../deviceMetric');
-const sample = (observedAt: number) => ({
+const sample = (observedAt: number, patch: Record<string, unknown> = {}) => ({
connected: true,
cpuCount: 8,
cpuPercent: 12,
+ diskTotalBytes: 1000,
+ diskUsedBytes: 500,
load1: 1,
load15: 1,
load5: 1,
memoryTotalBytes: 100,
memoryUsedBytes: 50,
observedAt,
+ ...patch,
});
describe('deviceMetricRouter.getSeries', () => {
@@ -70,6 +73,29 @@ describe('deviceMetricRouter.getSeries', () => {
expect(series.points).toHaveLength(1);
});
+ it('takes the disk size from the newest sample that read the disk', async () => {
+ deviceModel.findPersonalByDeviceId.mockResolvedValue({ id: 'row-1', workspaceId: null });
+ const now = Date.now();
+ queryDeviceMetrics.mockResolvedValue([
+ sample(now - 120_000, { diskTotalBytes: 2000 }),
+ sample(now - 60_000, { diskTotalBytes: null, diskUsedBytes: null }),
+ ]);
+
+ const series = await personal.getSeries({ deviceId: 'dev-1' });
+
+ expect(series.diskTotalBytes).toBe(2000);
+ });
+
+ it('has no disk size when the device never reported one', async () => {
+ deviceModel.findPersonalByDeviceId.mockResolvedValue({ id: 'row-1', workspaceId: null });
+ const { diskTotalBytes: _, diskUsedBytes: __, ...legacy } = sample(Date.now() - 60_000);
+ queryDeviceMetrics.mockResolvedValue([legacy]);
+
+ const series = await personal.getSeries({ deviceId: 'dev-1' });
+
+ expect(series.diskTotalBytes).toBeNull();
+ });
+
it('does not treat a workspace row as personal', async () => {
deviceModel.findPersonalByDeviceId.mockResolvedValue(undefined);
diff --git a/apps/server/src/routers/lambda/deviceMetric.ts b/apps/server/src/routers/lambda/deviceMetric.ts
index 7988d5e3a90..bbff550e436 100644
--- a/apps/server/src/routers/lambda/deviceMetric.ts
+++ b/apps/server/src/routers/lambda/deviceMetric.ts
@@ -57,7 +57,7 @@ const deviceMetricProcedure = wsCompatProcedure.use(serverDatabase).use(async (o
export const deviceMetricRouter = router({
/**
- * The machine's recent CPU / memory / load, read from the device gateway
+ * The machine's recent CPU / memory / load / disk, read from the device gateway
* (the only store — it keeps two days) and averaged into buckets sized so
* the window renders as roughly {@link TARGET_POINTS} points.
*/
@@ -96,6 +96,7 @@ export const deviceMetricRouter = router({
return {
bucketMs,
cpuCount: latest?.cpuCount ?? null,
+ diskTotalBytes: samples.findLast((s) => s.diskTotalBytes)?.diskTotalBytes ?? null,
from,
memoryTotalBytes: latest?.memoryTotalBytes ?? null,
points: bucketDeviceMetrics(samples, { bucketMs, from, to }),
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 4a319fb4ba9..e8046d9c275 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -420,6 +420,7 @@
"devices.capabilities.tools.desc": "Connect local tools to extend what agents can do.",
"devices.capabilities.tools.title": "Call system tools",
"devices.card.cpuUsage": "CPU usage",
+ "devices.card.diskUsage": "Disk usage",
"devices.card.hostname": "Hostname",
"devices.card.memoryUsage": "Memory usage",
"devices.card.runningTopics": "Running topics",
@@ -468,6 +469,7 @@
"devices.detail.cores_one": "{{count}} core",
"devices.detail.cores_other": "{{count}} cores",
"devices.detail.cpu": "CPU",
+ "devices.detail.disk": "Disk",
"devices.detail.lastConnected": "Last connected",
"devices.detail.loadUsage": "Load average",
"devices.detail.memory": "Memory",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 3d0bdb160c8..d186a0a3ebc 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -420,6 +420,7 @@
"devices.capabilities.tools.desc": "连接本地工具,扩展智能体的能力边界。",
"devices.capabilities.tools.title": "调用系统工具",
"devices.card.cpuUsage": "CPU 使用率",
+ "devices.card.diskUsage": "磁盘使用率",
"devices.card.hostname": "主机名",
"devices.card.memoryUsage": "内存使用率",
"devices.card.runningTopics": "运行中的话题",
@@ -468,6 +469,7 @@
"devices.detail.cores_one": "{{count}} 核",
"devices.detail.cores_other": "{{count}} 核",
"devices.detail.cpu": "CPU",
+ "devices.detail.disk": "磁盘",
"devices.detail.lastConnected": "最近连接",
"devices.detail.loadUsage": "平均负载",
"devices.detail.memory": "内存",
diff --git a/packages/device-control/src/metrics/sampler.test.ts b/packages/device-control/src/metrics/sampler.test.ts
index c24f6914fa5..c97cb72908b 100644
--- a/packages/device-control/src/metrics/sampler.test.ts
+++ b/packages/device-control/src/metrics/sampler.test.ts
@@ -10,6 +10,7 @@ import { DeviceMetricsSampler } from './sampler';
const setup = async (
overrides: {
connected?: () => boolean;
+ disk?: () => Promise<{ totalBytes: number; usedBytes: number } | undefined>;
upload?: (s: DeviceMetricSample[]) => Promise<void>;
} = {},
) => {
@@ -30,6 +31,7 @@ const setup = async (
readers: {
// Each reading adds 100 units of CPU time, 25 of them busy.
cpuTimes: () => ({ idle: (idle += 75), total: (total += 100) }),
+ disk: overrides.disk ?? (async () => ({ totalBytes: 1000, usedBytes: 600 })),
loadAverage: () => [1, 2, 3],
memory: async () => ({ totalBytes: 100, usedBytes: 40 }),
},
@@ -40,7 +42,7 @@ const setup = async (
};
describe('DeviceMetricsSampler', () => {
- it('records CPU, memory, load and connection state', async () => {
+ it('records CPU, memory, load, disk and connection state', async () => {
const { create, upload } = await setup({ connected: () => false });
const sampler = create();
await sampler.start();
@@ -52,6 +54,8 @@ describe('DeviceMetricsSampler', () => {
expect.objectContaining({
connected: false,
cpuPercent: 25,
+ diskTotalBytes: 1000,
+ diskUsedBytes: 600,
load1: 1,
load15: 3,
load5: 2,
@@ -62,6 +66,19 @@ describe('DeviceMetricsSampler', () => {
]);
});
+ it('still samples when the disk cannot be read, with the disk left null', async () => {
+ const { create, upload } = await setup({ disk: async () => undefined });
+ const sampler = create();
+ await sampler.start();
+ await sampler.sample();
+ await sampler.flush();
+ await sampler.stop();
+
+ expect(upload).toHaveBeenCalledWith([
+ expect.objectContaining({ diskTotalBytes: null, diskUsedBytes: null, memoryUsedBytes: 40 }),
+ ]);
+ });
+
it('keeps samples until an upload succeeds, across a restart', async () => {
let online = false;
const { advance, create, storagePath, upload } = await setup({
diff --git a/packages/device-control/src/metrics/sampler.ts b/packages/device-control/src/metrics/sampler.ts
index f01a8d7f542..a8265803d71 100644
--- a/packages/device-control/src/metrics/sampler.ts
+++ b/packages/device-control/src/metrics/sampler.ts
@@ -10,10 +10,11 @@ import {
deviceMetricSampleSchema,
} from '@lobechat/types';
-import type { CpuTimes, MemoryUsage } from './systemSnapshot';
+import type { CpuTimes, DiskUsage, MemoryUsage } from './systemSnapshot';
import {
cpuPercentBetween,
readCpuTimes,
+ readDiskUsage,
readLoadAverage,
readMemoryUsage,
} from './systemSnapshot';
@@ -35,6 +36,7 @@ export interface DeviceMetricsSamplerOptions {
/** Test seams for the machine readings. */
readers?: {
cpuTimes?: () => CpuTimes;
+ disk?: () => Promise<DiskUsage | undefined>;
loadAverage?: () => [number, number, number] | null;
memory?: () => Promise<MemoryUsage>;
};
@@ -50,7 +52,7 @@ export interface DeviceMetricsSamplerOptions {
}
/**
- * Samples this machine's CPU / memory / load once a minute and uploads the
+ * Samples this machine's CPU / memory / load / disk once a minute and uploads the
* samples in batches. Samples are kept locally until an upload succeeds, so
* the stretch a device spent disconnected is uploaded once it reconnects —
* that stretch is exactly what explains a drop.
@@ -122,11 +124,14 @@ export class DeviceMetricsSampler {
try {
const memory = await (readers.memory ?? readMemoryUsage)();
+ const disk = await (readers.disk ?? readDiskUsage)();
const load = (readers.loadAverage ?? readLoadAverage)();
this.pending.push({
connected: this.options.isConnected(),
cpuCount: Math.max(1, os.cpus().length),
cpuPercent,
+ diskTotalBytes: disk?.totalBytes ?? null,
+ diskUsedBytes: disk?.usedBytes ?? null,
load1: load?.[0] ?? null,
load15: load?.[2] ?? null,
load5: load?.[1] ?? null,
diff --git a/packages/device-control/src/metrics/systemSnapshot.test.ts b/packages/device-control/src/metrics/systemSnapshot.test.ts
index e46ce4549f3..437a3256273 100644
--- a/packages/device-control/src/metrics/systemSnapshot.test.ts
+++ b/packages/device-control/src/metrics/systemSnapshot.test.ts
@@ -1,6 +1,11 @@
import { describe, expect, it } from 'vitest';
-import { cpuPercentBetween, parseMemInfo, parseVmStat } from './systemSnapshot';
+import {
+ cpuPercentBetween,
+ diskUsageFromStatfs,
+ parseMemInfo,
+ parseVmStat,
+} from './systemSnapshot';
describe('cpuPercentBetween', () => {
it('is the busy share of elapsed CPU time', () => {
@@ -45,3 +50,17 @@ describe('parseMemInfo', () => {
});
});
});
+
+describe('diskUsageFromStatfs', () => {
+ it('counts every block the user can no longer write to as used', () => {
+ // 1000 blocks, 300 free, 250 of those available to non-root users.
+ expect(diskUsageFromStatfs({ bavail: 250, blocks: 1000, bsize: 4096 })).toEqual({
+ totalBytes: 1000 * 4096,
+ usedBytes: 750 * 4096,
+ });
+ });
+
+ it('is undefined for a volume reporting no size', () => {
+ expect(diskUsageFromStatfs({ bavail: 0, blocks: 0, bsize: 4096 })).toBeUndefined();
+ });
+});
diff --git a/packages/device-control/src/metrics/systemSnapshot.ts b/packages/device-control/src/metrics/systemSnapshot.ts
index 18f3775cb73..a14cfa96595 100644
--- a/packages/device-control/src/metrics/systemSnapshot.ts
+++ b/packages/device-control/src/metrics/systemSnapshot.ts
@@ -1,5 +1,5 @@
import { execFile } from 'node:child_process';
-import { readFile } from 'node:fs/promises';
+import { readFile, statfs } from 'node:fs/promises';
import os from 'node:os';
export interface CpuTimes {
@@ -7,6 +7,11 @@ export interface CpuTimes {
total: number;
}
+export interface DiskUsage {
+ totalBytes: number;
+ usedBytes: number;
+}
+
export interface MemoryUsage {
totalBytes: number;
usedBytes: number;
@@ -96,3 +101,30 @@ export const readLoadAverage = (): [number, number, number] | null => {
const [load1, load5, load15] = os.loadavg();
return [load1, load5, load15];
};
+
+/**
+ * `statfs` reading → the volume's size and the bytes no longer available to
+ * the user (total minus `bavail`). Counting against `bavail` rather than
+ * `bfree` means a volume reads 100% exactly when the user can no longer write
+ * to it (root-reserved blocks included), and on APFS it covers every volume
+ * sharing the container, as Finder's storage bar does.
+ */
+export const diskUsageFromStatfs = (stats: {
+ bavail: number;
+ blocks: number;
+ bsize: number;
+}): DiskUsage | undefined => {
+ const totalBytes = stats.blocks * stats.bsize;
+ if (!(totalBytes > 0)) return undefined;
+ const usedBytes = Math.min(totalBytes, Math.max(0, (stats.blocks - stats.bavail) * stats.bsize));
+ return { totalBytes, usedBytes };
+};
+
+/** The volume holding the home directory — where agents' working directories usually live. */
+export const readDiskUsage = async (dir = os.homedir()): Promise<DiskUsage | undefined> => {
+ try {
+ return diskUsageFromStatfs(await statfs(dir));
+ } catch {
+ return undefined;
+ }
+};
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 76cf81dba0c..e89945460b4 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -726,6 +726,7 @@ export default {
'devices.detail.cores_one': '{{count}} core',
'devices.detail.cores_other': '{{count}} cores',
'devices.detail.cpu': 'CPU',
+ 'devices.detail.disk': 'Disk',
'devices.detail.lastConnected': 'Last connected',
'devices.detail.loadUsage': 'Load average',
'devices.detail.memory': 'Memory',
@@ -758,6 +759,7 @@ export default {
'devices.capabilities.tools.desc': 'Connect local tools to extend what agents can do.',
'devices.capabilities.tools.title': 'Call system tools',
'devices.card.cpuUsage': 'CPU usage',
+ 'devices.card.diskUsage': 'Disk usage',
'devices.card.hostname': 'Hostname',
'devices.card.memoryUsage': 'Memory usage',
'devices.card.runningTopics': 'Running topics',
diff --git a/packages/types/src/deviceMetric.test.ts b/packages/types/src/deviceMetric.test.ts
index 38db7e58ca8..ab70b091dc6 100644
--- a/packages/types/src/deviceMetric.test.ts
+++ b/packages/types/src/deviceMetric.test.ts
@@ -10,6 +10,8 @@ const sample = (
connected: true,
cpuCount: 8,
cpuPercent: 20,
+ diskTotalBytes: 1000,
+ diskUsedBytes: 400,
load1: 2,
load15: 1,
load5: 1.5,
@@ -25,7 +27,12 @@ describe('bucketDeviceMetrics', () => {
[
sample(9 * MIN, { cpuPercent: 10 }),
sample(6 * MIN, { connected: false, cpuPercent: 30 }),
- sample(21 * MIN, { cpuPercent: 80, load1: null, memoryUsedBytes: 12_000 }),
+ sample(21 * MIN, {
+ cpuPercent: 80,
+ diskUsedBytes: 900,
+ load1: null,
+ memoryUsedBytes: 12_000,
+ }),
sample(99 * MIN), // outside the window
],
{ bucketMs: 5 * MIN, from: 0, to: 60 * MIN },
@@ -35,6 +42,8 @@ describe('bucketDeviceMetrics', () => {
{
connected: false,
cpuPercent: 20,
+ diskPercent: 40,
+ diskUsedBytes: 400,
load1: 2,
memoryPercent: 50,
memoryUsedBytes: 8000,
@@ -43,6 +52,8 @@ describe('bucketDeviceMetrics', () => {
{
connected: true,
cpuPercent: 80,
+ diskPercent: 90,
+ diskUsedBytes: 900,
load1: null,
memoryPercent: 75,
memoryUsedBytes: 12_000,
@@ -50,4 +61,16 @@ describe('bucketDeviceMetrics', () => {
},
]);
});
+
+ it('leaves the disk empty for samples from devices that do not report it', () => {
+ const { diskTotalBytes: _, diskUsedBytes: __, ...legacy } = sample(MIN);
+ const unreadable = sample(2 * MIN, { diskTotalBytes: null, diskUsedBytes: null });
+ const [point] = bucketDeviceMetrics([legacy, unreadable], {
+ bucketMs: 5 * MIN,
+ from: 0,
+ to: 10 * MIN,
+ });
+
+ expect(point).toMatchObject({ diskPercent: null, diskUsedBytes: null, memoryPercent: 50 });
+ });
});
diff --git a/packages/types/src/deviceMetric.ts b/packages/types/src/deviceMetric.ts
index 215a87a670b..973aacc525d 100644
--- a/packages/types/src/deviceMetric.ts
+++ b/packages/types/src/deviceMetric.ts
@@ -1,7 +1,7 @@
import { z } from 'zod';
// ============================================
-// Device metrics — machine health samples (CPU / memory / load average)
+// Device metrics — machine health samples (CPU / memory / load average / disk)
// ============================================
/** How often a device takes one sample. One sample averages CPU over this window. */
@@ -35,6 +35,13 @@ export const deviceMetricSampleSchema = z.object({
cpuCount: z.number().int().min(1).max(4096),
/** Share of all cores busy over the sample window, 0–100. */
cpuPercent: z.number().min(0).max(100).nullable(),
+ /**
+ * Size of the volume holding the user's home directory, and how much of it
+ * is no longer available to them. Null when the volume could not be read;
+ * absent in samples from devices that predate disk reporting.
+ */
+ diskTotalBytes: z.number().int().min(0).nullish(),
+ diskUsedBytes: z.number().int().min(0).nullish(),
/** 1 / 5 / 15 minute load averages; null on platforms without them (Windows). */
load1: z.number().min(0).nullable(),
load5: z.number().min(0).nullable(),
@@ -52,6 +59,8 @@ export interface DeviceMetricPoint {
/** False when any sample in the bucket was taken while disconnected. */
connected: boolean;
cpuPercent: number | null;
+ diskPercent: number | null;
+ diskUsedBytes: number | null;
load1: number | null;
memoryPercent: number | null;
memoryUsedBytes: number | null;
@@ -64,14 +73,16 @@ export interface DeviceMetricSeries {
bucketMs: number;
/** From the newest sample; null when the device never reported. */
cpuCount: number | null;
+ /** From the newest sample that read the disk; null when none did. */
+ diskTotalBytes: number | null;
from: number;
memoryTotalBytes: number | null;
points: DeviceMetricPoint[];
to: number;
}
-const average = (values: (number | null)[]): number | null => {
- const present = values.filter((v): v is number => v !== null);
+const average = (values: (number | null | undefined)[]): number | null => {
+ const present = values.filter((v): v is number => v !== null && v !== undefined);
return present.length === 0 ? null : present.reduce((a, b) => a + b, 0) / present.length;
};
@@ -98,6 +109,14 @@ export const bucketDeviceMetrics = (
.map(([observedAt, group]) => ({
connected: group.every((s) => s.connected),
cpuPercent: average(group.map((s) => s.cpuPercent)),
+ diskPercent: average(
+ group.map((s) =>
+ s.diskTotalBytes && s.diskUsedBytes != null
+ ? (s.diskUsedBytes * 100) / s.diskTotalBytes
+ : null,
+ ),
+ ),
+ diskUsedBytes: average(group.map((s) => s.diskUsedBytes)),
load1: average(group.map((s) => s.load1)),
memoryPercent: average(
group.map((s) =>
diff --git a/src/features/Conversation/WorkingSidebar/Overview/DeviceStatusSection.tsx b/src/features/Conversation/WorkingSidebar/Overview/DeviceStatusSection.tsx
index 14904a4a65d..6c7f669a54d 100644
--- a/src/features/Conversation/WorkingSidebar/Overview/DeviceStatusSection.tsx
+++ b/src/features/Conversation/WorkingSidebar/Overview/DeviceStatusSection.tsx
@@ -79,14 +79,14 @@ const styles = createStaticStyles(({ css }) => ({
}));
interface DeviceStatusSectionProps {
- /** Polls the device's presence and CPU / memory series only while the Overview is on screen. */
+ /** Polls the device's presence and CPU / memory / disk series only while the Overview is on screen. */
active: boolean;
deviceId: string;
}
/**
* The device the topic runs on, as its device card shows it: presence,
- * hostname, running topics and the latest CPU / memory load. Answers "is the
+ * hostname, running topics and the latest CPU / memory / disk usage. Answers "is the
* machine doing this work healthy and busy?" without leaving the conversation.
*/
const DeviceStatusSection = memo<DeviceStatusSectionProps>(({ active, deviceId }) => {
@@ -197,6 +197,9 @@ const DeviceStatusContent = ({ data, device, error }: DeviceStatusContentProps)
<UsageMeterGroup>
<UsageMeter label={t('devices.card.cpuUsage')} value={usage.latest?.cpuPercent} />
<UsageMeter label={t('devices.card.memoryUsage')} value={usage.latest?.memoryPercent} />
+ {usage.reportsDisk && (
+ <UsageMeter label={t('devices.card.diskUsage')} value={usage.latest?.diskPercent} />
+ )}
</UsageMeterGroup>
)}
</Flexbox>
diff --git a/src/features/DeviceManager/DeviceCard.tsx b/src/features/DeviceManager/DeviceCard.tsx
index 47f86665147..509ee9e6634 100644
--- a/src/features/DeviceManager/DeviceCard.tsx
+++ b/src/features/DeviceManager/DeviceCard.tsx
@@ -353,6 +353,9 @@ const DeviceCard = memo<DeviceCardProps>(({ device, isCurrent, onOpen }) => {
<UsageMeterGroup>
<UsageMeter label={t('devices.card.cpuUsage')} value={usage.latest?.cpuPercent} />
<UsageMeter label={t('devices.card.memoryUsage')} value={usage.latest?.memoryPercent} />
+ {usage.reportsDisk && (
+ <UsageMeter label={t('devices.card.diskUsage')} value={usage.latest?.diskPercent} />
+ )}
</UsageMeterGroup>
)}
</Flexbox>
diff --git a/src/features/DeviceManager/DeviceHealth/buildHealthTimeline.test.ts b/src/features/DeviceManager/DeviceHealth/buildHealthTimeline.test.ts
index 344b5cee984..ceca558b09c 100644
--- a/src/features/DeviceManager/DeviceHealth/buildHealthTimeline.test.ts
+++ b/src/features/DeviceManager/DeviceHealth/buildHealthTimeline.test.ts
@@ -11,6 +11,8 @@ const from = to - 12 * BUCKET;
const point = (bucketsAgo: number, patch: Partial<DeviceMetricPoint> = {}): DeviceMetricPoint => ({
connected: true,
cpuPercent: 10,
+ diskPercent: 40,
+ diskUsedBytes: 80,
load1: 1,
memoryPercent: 50,
memoryUsedBytes: 100,
@@ -19,7 +21,15 @@ const point = (bucketsAgo: number, patch: Partial<DeviceMetricPoint> = {}): Devi
});
const build = (points: DeviceMetricPoint[], cpuCount: number | null = 8) =>
- buildHealthTimeline({ bucketMs: BUCKET, cpuCount, from, memoryTotalBytes: 200, points, to });
+ buildHealthTimeline({
+ bucketMs: BUCKET,
+ cpuCount,
+ diskTotalBytes: 200,
+ from,
+ memoryTotalBytes: 200,
+ points,
+ to,
+ });
describe('buildHealthTimeline', () => {
it('lays out one slot per bucket across the window', () => {
@@ -55,7 +65,12 @@ describe('buildHealthTimeline', () => {
it('reports load as a share of the cores, with a chart ceiling of at least 100%', () => {
const timeline = build([point(4, { load1: 4 }), point(3, { cpuPercent: 90, load1: 12 })]);
- expect(timeline.latest).toEqual({ cpuPercent: 90, loadPercent: 150, memoryPercent: 50 });
+ expect(timeline.latest).toEqual({
+ cpuPercent: 90,
+ diskPercent: 40,
+ loadPercent: 150,
+ memoryPercent: 50,
+ });
expect(timeline.loadCeiling).toBe(150);
expect(build([point(3, { load1: 2 })]).loadCeiling).toBe(100);
});
@@ -100,7 +115,11 @@ describe('groupStripBlocks', () => {
});
it('aligns blocks to wall-clock boundaries rather than the window start', () => {
- const blocks = groupStripBlocks([slot(1, 'online'), slot(2, 'online'), slot(3, 'online')], BUCKET, 2 * BUCKET);
+ const blocks = groupStripBlocks(
+ [slot(1, 'online'), slot(2, 'online'), slot(3, 'online')],
+ BUCKET,
+ 2 * BUCKET,
+ );
expect(blocks.map(({ end, start }) => ({ end, start }))).toEqual([
{ end: 2 * BUCKET, start: BUCKET },
diff --git a/src/features/DeviceManager/DeviceHealth/buildHealthTimeline.ts b/src/features/DeviceManager/DeviceHealth/buildHealthTimeline.ts
index e55f0f619ec..5b9de849b0f 100644
--- a/src/features/DeviceManager/DeviceHealth/buildHealthTimeline.ts
+++ b/src/features/DeviceManager/DeviceHealth/buildHealthTimeline.ts
@@ -19,6 +19,14 @@ export interface HealthUsage {
memoryPercent: number | null;
}
+/**
+ * The newest reading: the charted metrics plus the disk, which moves too
+ * slowly to chart or to color the strip but still answers "is it filling up?".
+ */
+export interface LatestUsage extends HealthUsage {
+ diskPercent: number | null;
+}
+
export interface HealthSlot extends HealthUsage {
memoryUsedBytes: number | null;
start: number;
@@ -27,7 +35,7 @@ export interface HealthSlot extends HealthUsage {
export interface HealthTimeline {
/** Newest reading of each metric, for the chart headers and the row preview. */
- latest: HealthUsage | null;
+ latest: LatestUsage | null;
/** Upper bound for the load chart — at least 100%, so an overloaded machine still fits. */
loadCeiling: number;
slots: HealthSlot[];
@@ -75,6 +83,8 @@ export const buildHealthTimeline = (series: DeviceMetricSeries): HealthTimeline
latest: newest
? {
cpuPercent: newest.cpuPercent,
+ // A series cached before devices reported the disk has no such field.
+ diskPercent: newest.diskPercent ?? null,
loadPercent: loadPercentOf(newest.load1, cpuCount),
memoryPercent: newest.memoryPercent,
}
diff --git a/src/features/DeviceManager/DeviceHealth/viewState.test.ts b/src/features/DeviceManager/DeviceHealth/viewState.test.ts
index af728cd17f6..eb728770139 100644
--- a/src/features/DeviceManager/DeviceHealth/viewState.test.ts
+++ b/src/features/DeviceManager/DeviceHealth/viewState.test.ts
@@ -34,12 +34,15 @@ describe('latestUsageView', () => {
const reported = {
bucketMs: BUCKET,
cpuCount: 8,
+ diskTotalBytes: 1000,
from: to - 12 * BUCKET,
memoryTotalBytes: 200,
points: [
{
connected: true,
cpuPercent: 14,
+ diskPercent: 62,
+ diskUsedBytes: 620,
load1: 1,
memoryPercent: 35,
memoryUsedBytes: 70,
@@ -59,14 +62,45 @@ describe('latestUsageView', () => {
const view = latestUsageView({ data: reported });
expect(view.loading).toBe(false);
- expect(!view.loading && view.latest).toMatchObject({ cpuPercent: 14, memoryPercent: 35 });
+ expect(!view.loading && view.latest).toMatchObject({
+ cpuPercent: 14,
+ diskPercent: 62,
+ memoryPercent: 35,
+ });
+ });
+
+ it('shows the disk row only for a device that reports its disk', () => {
+ const view = latestUsageView({ data: reported });
+
+ expect(!view.loading && view.reportsDisk).toBe(true);
+ });
+
+ // An lh / desktop version that predates disk reporting would otherwise show a permanent em dash.
+ it('hides the disk row for a device that never reported its disk', () => {
+ const view = latestUsageView({ data: { ...reported, diskTotalBytes: null } });
+
+ expect(!view.loading && view.reportsDisk).toBe(false);
+ });
+
+ // A series persisted before devices reported the disk has no disk fields at all.
+ it('reads no disk usage from a series cached before the disk was reported', () => {
+ const { diskTotalBytes: _, ...cachedSeries } = reported;
+ const { diskPercent: __, diskUsedBytes: ___, ...cachedPoint } = reported.points[0];
+ const view = latestUsageView({ data: { ...cachedSeries, points: [cachedPoint] } as any });
+
+ expect(view).toMatchObject({ latest: { diskPercent: null }, reportsDisk: false });
});
it('resolves to no reading, not loading, for a silent device or a failed read', () => {
- expect(latestUsageView({ data: series(0) })).toEqual({ latest: null, loading: false });
+ expect(latestUsageView({ data: series(0) })).toEqual({
+ latest: null,
+ loading: false,
+ reportsDisk: false,
+ });
expect(latestUsageView({ error: new Error('gateway down') })).toEqual({
latest: null,
loading: false,
+ reportsDisk: false,
});
});
});
@@ -77,12 +111,15 @@ describe('currentUsage', () => {
const at = (observedAt: number) => ({
bucketMs: BUCKET,
cpuCount: 4,
+ diskTotalBytes: null,
from: to - 144 * BUCKET,
memoryTotalBytes: 100,
points: [
{
connected: true,
cpuPercent: 12,
+ diskPercent: null,
+ diskUsedBytes: null,
load1: 2,
memoryPercent: 40,
memoryUsedBytes: 40,
diff --git a/src/features/DeviceManager/DeviceHealth/viewState.ts b/src/features/DeviceManager/DeviceHealth/viewState.ts
index 8ff858e4fa6..b292e2d9f64 100644
--- a/src/features/DeviceManager/DeviceHealth/viewState.ts
+++ b/src/features/DeviceManager/DeviceHealth/viewState.ts
@@ -3,6 +3,7 @@ import type { DeviceMetricSeries } from '@lobechat/types';
import {
buildHealthTimeline,
type HealthUsage,
+ type LatestUsage,
loadPercentOf,
UPLOAD_GRACE_MS,
} from './buildHealthTimeline';
@@ -25,10 +26,21 @@ export const healthViewState = ({
return data.points.length === 0 ? 'empty' : 'ready';
};
-export type LatestUsageView = { latest: HealthUsage | null; loading: false } | { loading: true };
+export type LatestUsageView =
+ | {
+ latest: LatestUsage | null;
+ loading: false;
+ /**
+ * Whether the device reports its disk at all. A device on an `lh` /
+ * desktop version that predates disk reporting never will, so its disk
+ * row is hidden rather than left as a permanent em dash.
+ */
+ reportsDisk: boolean;
+ }
+ | { loading: true };
/**
- * The current CPU / memory / load reading for the card meters and detail stat
+ * The current CPU / memory / load / disk reading for the card meters and detail stat
* cards. Loading only while the first read is in flight; a device that never
* reported, or a failed read, resolves to no reading (em dashes) instead of a
* skeleton that never ends.
@@ -42,6 +54,8 @@ export const latestUsageView = (state: {
return {
latest: data && data.points.length > 0 ? buildHealthTimeline(data).latest : null,
loading: false,
+ // A series cached before devices reported the disk has no such field.
+ reportsDisk: !!data?.diskTotalBytes,
};
};
diff --git a/src/features/DeviceManager/DeviceHoverPanel.tsx b/src/features/DeviceManager/DeviceHoverPanel.tsx
index b3f2fe6f941..e0e9ab52325 100644
--- a/src/features/DeviceManager/DeviceHoverPanel.tsx
+++ b/src/features/DeviceManager/DeviceHoverPanel.tsx
@@ -8,6 +8,7 @@ import {
CalendarClockIcon,
CpuIcon,
FolderIcon,
+ HardDriveIcon,
LayersIcon,
type LucideIcon,
MemoryStickIcon,
@@ -169,6 +170,9 @@ const DeviceHoverPanel = ({ device }: DeviceHoverPanelProps) => {
label={t('devices.card.memoryUsage')}
value={usage.latest?.memoryPercent}
/>
+ {usage.reportsDisk && (
+ <UsageMeter label={t('devices.card.diskUsage')} value={usage.latest?.diskPercent} />
+ )}
</UsageMeterGroup>
)}
</div>
@@ -194,6 +198,11 @@ const DeviceHoverPanel = ({ device }: DeviceHoverPanelProps) => {
<InfoRow icon={MemoryStickIcon} label={t('devices.detail.memory')}>
{summary.memoryTotalBytes ? formatSize(summary.memoryTotalBytes) : undefined}
</InfoRow>
+ {summary.diskTotalBytes && (
+ <InfoRow icon={HardDriveIcon} label={t('devices.detail.disk')}>
+ {formatSize(summary.diskTotalBytes)}
+ </InfoRow>
+ )}
<InfoRow icon={ServerIcon} label={t('devices.card.hostname')}>
{summary.hostname ? (
<span className={styles.code} title={summary.hostname}>
diff --git a/src/features/DeviceManager/DeviceOverview.tsx b/src/features/DeviceManager/DeviceOverview.tsx
index 9e9f3089e66..354f8cfd8fd 100644
--- a/src/features/DeviceManager/DeviceOverview.tsx
+++ b/src/features/DeviceManager/DeviceOverview.tsx
@@ -21,6 +21,7 @@ import {
CpuIcon,
FolderIcon,
GaugeIcon,
+ HardDriveIcon,
HeartPulseIcon,
LayersIcon,
type LucideIcon,
@@ -251,6 +252,8 @@ const DeviceOverview = ({ canOperate, device }: DeviceOverviewProps) => {
const cores = data?.cpuCount ?? null;
const memoryTotal = data?.memoryTotalBytes ?? null;
const memoryUsed = newest?.memoryUsedBytes ?? null;
+ const diskTotal = data?.diskTotalBytes ?? null;
+ const diskUsed = newest?.diskUsedBytes ?? null;
const lastConnected = dayjs(channels[0]?.connectedAt ?? device.lastSeen).fromNow();
const platformLabel = getPlatformLabel(device.platform);
@@ -356,6 +359,11 @@ const DeviceOverview = ({ canOperate, device }: DeviceOverviewProps) => {
<InfoRow icon={MemoryStickIcon} label={t('devices.detail.memory')}>
{memoryTotal ? <Text>{formatSize(memoryTotal)}</Text> : <Empty />}
</InfoRow>
+ {diskTotal ? (
+ <InfoRow icon={HardDriveIcon} label={t('devices.detail.disk')}>
+ <Text>{formatSize(diskTotal)}</Text>
+ </InfoRow>
+ ) : null}
<InfoRow icon={FolderIcon} label={t('devices.card.workingDir')}>
{device.defaultCwd ? (
<span className={styles.code} title={device.defaultCwd}>
@@ -413,6 +421,18 @@ const DeviceOverview = ({ canOperate, device }: DeviceOverviewProps) => {
: undefined
}
/>
+ {!usage.loading && usage.reportsDisk && (
+ <StatCard
+ icon={HardDriveIcon}
+ title={t('devices.card.diskUsage')}
+ value={latest?.diskPercent}
+ detail={
+ diskUsed !== null && diskTotal
+ ? `${formatSize(diskUsed)} / ${formatSize(diskTotal)}`
+ : undefined
+ }
+ />
+ )}
</div>
<DetailCard extra={<HealthLegend />} icon={HeartPulseIcon} title={t('devices.health.title')}>
diff --git a/src/features/DeviceManager/deviceHoverSummary.test.ts b/src/features/DeviceManager/deviceHoverSummary.test.ts
index 5abf1bcc971..bddd87b2d45 100644
--- a/src/features/DeviceManager/deviceHoverSummary.test.ts
+++ b/src/features/DeviceManager/deviceHoverSummary.test.ts
@@ -6,6 +6,7 @@ import { buildDeviceHoverSummary } from './deviceHoverSummary';
const series: DeviceMetricSeries = {
bucketMs: 300_000,
cpuCount: 8,
+ diskTotalBytes: 512 * 1024 ** 3,
from: 0,
memoryTotalBytes: 32 * 1024 ** 3,
points: [],
@@ -40,6 +41,7 @@ describe('buildDeviceHoverSummary', () => {
architecture: 'x64',
connections: 2,
cores: 8,
+ diskTotalBytes: 512 * 1024 ** 3,
enrollerName: undefined,
hostname: 'dev-box.local',
lastConnectedAt: '2026-10-15T10:00:00.000Z',
@@ -61,13 +63,14 @@ describe('buildDeviceHoverSummary', () => {
online: false,
platform: null,
}),
- { ...series, cpuCount: null, memoryTotalBytes: null },
+ { ...series, cpuCount: null, diskTotalBytes: null, memoryTotalBytes: null },
);
expect(summary).toMatchObject({
architecture: undefined,
connections: 0,
cores: undefined,
+ diskTotalBytes: undefined,
hostname: undefined,
lastConnectedAt: '2026-10-14T00:00:00.000Z',
memoryTotalBytes: undefined,
diff --git a/src/features/DeviceManager/deviceHoverSummary.ts b/src/features/DeviceManager/deviceHoverSummary.ts
index e2196f8eaf0..a7b714e22bf 100644
--- a/src/features/DeviceManager/deviceHoverSummary.ts
+++ b/src/features/DeviceManager/deviceHoverSummary.ts
@@ -7,6 +7,7 @@ export interface DeviceHoverSummary {
/** Live connections; only meaningful while online. */
connections: number;
cores?: number;
+ diskTotalBytes?: number;
/**
* Who enrolled a workspace device. `null` names an enroller the list could
* not resolve; `undefined` means the row has no enroller to show.
@@ -37,6 +38,7 @@ export const buildDeviceHoverSummary = (
architecture: device.architecture || undefined,
connections: channels.length,
cores: series?.cpuCount || undefined,
+ diskTotalBytes: series?.diskTotalBytes || undefined,
enrollerName:
device.scope === 'workspace' && device.enroller
? device.enroller.fullName || device.enroller.username || null
diff --git a/src/store/device/deviceMetricSeriesReplica.test.ts b/src/store/device/deviceMetricSeriesReplica.test.ts
index ce4c15d72e2..df8a0cb290a 100644
--- a/src/store/device/deviceMetricSeriesReplica.test.ts
+++ b/src/store/device/deviceMetricSeriesReplica.test.ts
@@ -44,12 +44,15 @@ const wrapper = ({ children }: PropsWithChildren) =>
const series = (cpuPercent: number): DeviceMetricSeries => ({
bucketMs: 300_000,
cpuCount: 8,
+ diskTotalBytes: null,
from: 0,
memoryTotalBytes: 100,
points: [
{
connected: true,
cpuPercent,
+ diskPercent: null,
+ diskUsedBytes: null,
load1: 1,
memoryPercent: 30,
memoryUsedBytes: 30,