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): chart the last 12 hours of machine health (CPU / memory / load) (#20002)

Arvin Xud0d3f86625ab
diff --git a/apps/cli/src/commands/connect.test.ts b/apps/cli/src/commands/connect.test.ts
index 09b574cb720..a3d936c6731 100644
--- a/apps/cli/src/commands/connect.test.ts
+++ b/apps/cli/src/commands/connect.test.ts
@@ -1,3 +1,4 @@
+import type * as DeviceControlModule from '@lobechat/device-control';
import { GatewayClient } from '@lobechat/device-gateway-client';
import { Command } from 'commander';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -42,6 +43,7 @@ vi.mock('../settings', () => ({
loadWorkspaceEnrollments: vi.fn().mockReturnValue([]),
normalizeUrl: vi.fn((url?: string) => (url ? url.replace(/\/$/, '') : undefined)),
removeWorkspaceEnrollment: vi.fn(),
+ resolveDeviceMetricsBacklogPath: vi.fn((id: string) => `/tmp/device-metrics/${id}.json`),
saveSettings: vi.fn(),
}));
@@ -86,6 +88,22 @@ let clientOptions: any = {};
let connectCalled = false;
let lastSentToolResponse: any = null;
let lastSentSystemInfoResponse: any = null;
+const clientReportMetrics = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
+const metricsSampler = vi.hoisted(() => ({
+ flush: vi.fn().mockResolvedValue(undefined),
+ options: undefined as any,
+ start: vi.fn().mockResolvedValue(undefined),
+ stop: vi.fn().mockResolvedValue(undefined),
+}));
+
+vi.mock('@lobechat/device-control', async (importOriginal) => ({
+ ...(await importOriginal<typeof DeviceControlModule>()),
+ DeviceMetricsSampler: vi.fn().mockImplementation(function (opts: any) {
+ metricsSampler.options = opts;
+ return metricsSampler;
+ }),
+}));
+
vi.mock('@lobechat/device-gateway-client', () => ({
GatewayClient: vi.fn().mockImplementation(function (opts: any) {
clientOptions = opts;
@@ -103,6 +121,7 @@ vi.mock('@lobechat/device-gateway-client', () => ({
clientEventHandlers[event] = handler;
}),
reconnect: vi.fn().mockResolvedValue(undefined),
+ reportMetrics: clientReportMetrics,
sendSystemInfoResponse: vi.fn().mockImplementation((data: any) => {
lastSentSystemInfoResponse = data;
}),
@@ -178,6 +197,22 @@ describe('connect command', () => {
);
});
+ it('samples machine health and pushes the backlog to the gateway on connect', async () => {
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'connect']);
+
+ expect(metricsSampler.start).toHaveBeenCalled();
+ const deviceId = clientOptions.deviceId;
+ expect(metricsSampler.options.storagePath).toBe(`/tmp/device-metrics/${deviceId}.json`);
+
+ clientEventHandlers.connected?.();
+ expect(metricsSampler.flush).toHaveBeenCalled();
+
+ const samples = [{ observedAt: 1 }] as any;
+ await metricsSampler.options.upload(samples);
+ expect(clientReportMetrics).toHaveBeenCalledWith(samples);
+ });
+
it('should connect to gateway', async () => {
const program = createProgram();
await program.parseAsync(['node', 'test', 'connect']);
@@ -355,7 +390,7 @@ describe('connect command', () => {
});
it('should handle SIGINT', async () => {
- const sigintHandlers: Array<() => void> = [];
+ const sigintHandlers: Array<() => Promise<void> | void> = [];
const origOn = process.on;
vi.spyOn(process, 'on').mockImplementation((event: any, handler: any) => {
if (event === 'SIGINT') sigintHandlers.push(handler);
@@ -367,9 +402,14 @@ describe('connect command', () => {
// Trigger SIGINT handler
for (const handler of sigintHandlers) {
- handler();
+ await handler();
}
+ // Pending health samples get a bounded push before the socket closes.
+ expect(metricsSampler.stop).toHaveBeenCalledWith({ flushTimeoutMs: 3000 });
+ expect(metricsSampler.stop.mock.invocationCallOrder[0]).toBeLessThan(
+ vi.mocked(cleanupAllProcesses).mock.invocationCallOrder[0],
+ );
expect(cleanupAllProcesses).toHaveBeenCalled();
expect(removeStatus).toHaveBeenCalled();
});
@@ -388,7 +428,7 @@ describe('connect command', () => {
});
it('should handle SIGTERM', async () => {
- const sigtermHandlers: Array<() => void> = [];
+ const sigtermHandlers: Array<() => Promise<void> | void> = [];
const origOn = process.on;
vi.spyOn(process, 'on').mockImplementation((event: any, handler: any) => {
if (event === 'SIGTERM') sigtermHandlers.push(handler);
@@ -399,7 +439,7 @@ describe('connect command', () => {
await program.parseAsync(['node', 'test', 'connect']);
for (const handler of sigtermHandlers) {
- handler();
+ await handler();
}
expect(cleanupAllProcesses).toHaveBeenCalled();
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.ts
index 3b633c6769c..2b57e00e1e0 100644
--- a/apps/cli/src/commands/connect.ts
+++ b/apps/cli/src/commands/connect.ts
@@ -7,7 +7,9 @@ import {
defaultGetProjectFileIndex,
defaultSearchProjectFiles,
type DeviceControlDeps,
+ DeviceMetricsSampler,
executeDeviceRpc,
+ pushMetrics,
} from '@lobechat/device-control';
import type {
AgentRunRequestMessage,
@@ -66,6 +68,7 @@ import {
loadWorkspaceEnrollments,
normalizeUrl,
removeWorkspaceEnrollment,
+ resolveDeviceMetricsBacklogPath,
saveSettings,
} from '../settings';
import { executeToolCall } from '../tools';
@@ -73,6 +76,8 @@ import { cleanupAllProcesses } from '../tools/shell';
import { log, setVerbose } from '../utils/logger';
import { sweepLocalTraces } from '../utils/traceMaintenance';
+/** Longest a clean stop waits to push pending device health samples. */
+const SHUTDOWN_METRICS_FLUSH_MS = 3000;
const CONNECT_SERVICE_NAME = CLI_CONNECT_SERVICE_NAME;
interface ConnectOptions {
@@ -465,8 +470,29 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
// shared with the workspace-share connections opened via `enrollWorkspace`.
bindGatewayClientHandlers(client, handlerContext, workspaceId);
+ // Machine health (CPU / memory / load) for the device page. Samples go to
+ // the device gateway over this socket (the gateway is their only store);
+ // they keep accruing while disconnected and upload once the connection is
+ // back, so the stretch around a drop is visible afterwards. Each batch is
+ // mirrored to this machine's workspace-share connections so a shared
+ // device's workspace row has the same history.
+ const metricsSampler = identity
+ ? new DeviceMetricsSampler({
+ isConnected: () => client.connectionStatus === 'connected',
+ logger: { warn: (msg) => info(msg) },
+ storagePath: resolveDeviceMetricsBacklogPath(identity.deviceId),
+ upload: (samples) =>
+ pushMetrics(
+ client,
+ [...workspaceConnections.values()].map((entry) => entry.client),
+ samples,
+ ),
+ })
+ : undefined;
+
client.on('connected', () => {
updateStatus('connected');
+ void metricsSampler?.flush();
});
client.on('disconnected', () => {
@@ -757,6 +783,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
// Close share connections but keep the persisted enrollments — the next
// startup restores them (or clears them if revoked meanwhile).
for (const wsId of workspaceConnections.keys()) closeWorkspaceConnection(wsId);
+ void metricsSampler?.stop();
client.disconnect();
removeStatus();
if (isDaemonChild) {
@@ -764,15 +791,17 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
}
};
- process.on('SIGINT', () => {
+ // A clean stop pushes the health samples taken since the last upload
+ // (bounded) before the socket closes, so the device page doesn't show the
+ // final minutes as "not running".
+ const shutdown = async () => {
+ await metricsSampler?.stop({ flushTimeoutMs: SHUTDOWN_METRICS_FLUSH_MS });
cleanup();
process.exit(0);
- });
+ };
- process.on('SIGTERM', () => {
- cleanup();
- process.exit(0);
- });
+ process.on('SIGINT', shutdown);
+ process.on('SIGTERM', shutdown);
// Register this device in the server registry before opening the WS, so the
// row exists by the time the gateway reports it online. `lh login` already
@@ -810,6 +839,8 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
await reportDaemonStartupReady();
+ await metricsSampler?.start();
+
// Connect
await client.connect();
diff --git a/apps/cli/src/settings/index.test.ts b/apps/cli/src/settings/index.test.ts
index 260b728e71a..1dcc811b9a4 100644
--- a/apps/cli/src/settings/index.test.ts
+++ b/apps/cli/src/settings/index.test.ts
@@ -11,6 +11,7 @@ import {
loadOrCreateConnectionId,
loadSettings,
normalizeUrl,
+ resolveDeviceMetricsBacklogPath,
resolveServerUrl,
saveActiveWorkspace,
saveSettings,
@@ -153,3 +154,11 @@ describe('settings', () => {
expect(loadOrCreateConnectionId()).toBe(id);
});
});
+
+describe('resolveDeviceMetricsBacklogPath', () => {
+ it('keeps custom device ids that differ only in punctuation in separate backlogs', () => {
+ expect(resolveDeviceMetricsBacklogPath('prod/api')).not.toBe(
+ resolveDeviceMetricsBacklogPath('prod:api'),
+ );
+ });
+});
diff --git a/apps/cli/src/settings/index.ts b/apps/cli/src/settings/index.ts
index acba192fcb1..e2d0734f47d 100644
--- a/apps/cli/src/settings/index.ts
+++ b/apps/cli/src/settings/index.ts
@@ -3,6 +3,8 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
+import { deviceMetricsBacklogFileName } from '@lobechat/device-control/metrics';
+
import { resolveCliDirName } from '../constants/identity';
import { OFFICIAL_AGENT_GATEWAY_URL, OFFICIAL_SERVER_URL } from '../constants/urls';
import { log } from '../utils/logger';
@@ -70,6 +72,15 @@ export function saveSettings(settings: StoredSettings): void {
fs.writeFileSync(SETTINGS_FILE, JSON.stringify(normalized, null, 2), { mode: 0o600 });
}
+/**
+ * Machine health samples not yet uploaded, one file per device identity so a
+ * personal and a workspace connection on the same machine keep separate
+ * backlogs.
+ */
+export function resolveDeviceMetricsBacklogPath(deviceId: string): string {
+ return path.join(SETTINGS_DIR, 'device-metrics', deviceMetricsBacklogFileName(deviceId));
+}
+
/**
* Stable per-install connection routing key for `lh connect`. Decoupled from
* the (machine-derived, shared-across-clients) deviceId so the gateway only
diff --git a/apps/desktop/pnpm-lock.yaml b/apps/desktop/pnpm-lock.yaml
index 9da1255a9da..66f498d6b56 100644
--- a/apps/desktop/pnpm-lock.yaml
+++ b/apps/desktop/pnpm-lock.yaml
@@ -340,6 +340,9 @@ importers:
'@lobechat/local-file-shell':
specifier: workspace:*
version: link:../local-file-shell
+ '@lobechat/types':
+ specifier: workspace:*
+ version: link:../types
'@lobechat/utils':
specifier: workspace:*
version: link:../utils
diff --git a/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.metrics.test.ts b/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.metrics.test.ts
new file mode 100644
index 00000000000..ca3ffe6e5b5
--- /dev/null
+++ b/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.metrics.test.ts
@@ -0,0 +1,91 @@
+import type * as DeviceMetricsModule from '@lobechat/device-control/metrics';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { App } from '@/core/App';
+
+import GatewayConnectionService from '../gatewayConnectionSrv';
+
+const samplers = vi.hoisted(() => [] as any[]);
+
+vi.mock('electron', () => ({
+ app: {
+ getPath: vi.fn((name: string) => `/mock/path/${name}`),
+ getVersion: vi.fn(() => '0.0.0-test'),
+ },
+ powerSaveBlocker: { isStarted: vi.fn(() => false), start: vi.fn(() => 1), stop: vi.fn() },
+}));
+
+vi.mock('@lobechat/device-control/metrics', async (importOriginal) => ({
+ ...(await importOriginal<typeof DeviceMetricsModule>()),
+ DeviceMetricsSampler: vi.fn().mockImplementation(function (options: any) {
+ const sampler = {
+ flush: vi.fn().mockResolvedValue(undefined),
+ options,
+ start: vi.fn().mockResolvedValue(undefined),
+ stop: vi.fn().mockResolvedValue(undefined),
+ };
+ samplers.push(sampler);
+ return sampler;
+ }),
+}));
+
+vi.mock('@/utils/logger', () => ({
+ createLogger: () => ({ debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() }),
+}));
+
+describe('GatewayConnectionService device metrics', () => {
+ let service: GatewayConnectionService;
+
+ beforeEach(() => {
+ samplers.length = 0;
+ service = new GatewayConnectionService({
+ browserManager: { broadcastToAllWindows: vi.fn() },
+ storeManager: { get: (_key: string, fallback?: unknown) => fallback, set: vi.fn() },
+ } as unknown as App);
+ });
+
+ it('samples into a per-device backlog under userData and pushes over the live client', async () => {
+ await (service as any).startMetricsSampler('dev-1');
+
+ const [sampler] = samplers;
+ expect(sampler.start).toHaveBeenCalled();
+ expect(sampler.options.storagePath).toMatch(
+ /^\/mock\/path\/userData\/device-metrics\/dev-1-[\da-f]{16}\.json$/,
+ );
+
+ const samples = [{ observedAt: 1 }];
+ await expect(sampler.options.upload(samples)).rejects.toThrow('not connected');
+
+ // Reconnects swap the client instance; upload must follow the current one.
+ const reportMetrics = vi.fn().mockResolvedValue(undefined);
+ (service as any).client = { connectionStatus: 'connected', disconnect: vi.fn(), reportMetrics };
+ // A workspace-share connection gets the same batch, so the shared row has history too.
+ const shareReport = vi.fn().mockResolvedValue(undefined);
+ (service as any).workspaceClients.set('ws-1', {
+ connectionStatus: 'connected',
+ reportMetrics: shareReport,
+ });
+ await sampler.options.upload(samples);
+ expect(reportMetrics).toHaveBeenCalledWith(samples);
+ expect(shareReport).toHaveBeenCalledWith(samples);
+ });
+
+ it('keeps one sampler across reconnects and flushes the backlog when connected', async () => {
+ await (service as any).startMetricsSampler('dev-1');
+ await (service as any).startMetricsSampler('dev-1');
+ expect(samplers).toHaveLength(1);
+
+ const [sampler] = samplers;
+ expect(sampler.options.isConnected()).toBe(false);
+ (service as any).setStatus('connected');
+ expect(sampler.options.isConnected()).toBe(true);
+ expect(sampler.flush).toHaveBeenCalled();
+ });
+
+ it('stops sampling on an explicit disconnect', async () => {
+ await (service as any).startMetricsSampler('dev-1');
+ await service.disconnect();
+
+ expect(samplers[0].stop).toHaveBeenCalledWith({ flushTimeoutMs: 3000 });
+ });
+});
diff --git a/apps/desktop/src/main/services/gatewayConnectionSrv.ts b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
index 8d786d228f3..ef748513eb0 100644
--- a/apps/desktop/src/main/services/gatewayConnectionSrv.ts
+++ b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
@@ -1,5 +1,6 @@
import { randomUUID } from 'node:crypto';
import os from 'node:os';
+import path from 'node:path';
import { OFFICIAL_DEVICE_GATEWAY_URL } from '@lobechat/const/url';
import type {
@@ -7,6 +8,7 @@ import type {
EnrollWorkspaceResult,
UnenrollWorkspaceParams,
} from '@lobechat/device-control';
+import type { DeviceMetricsSampler } from '@lobechat/device-control/metrics';
import type {
AgentRunRequestMessage,
DeviceSystemInfo,
@@ -166,6 +168,8 @@ export default class GatewayConnectionService extends ServiceModule {
private agentRunHandler: AgentRunHandler | null = null;
private rpcHandler: RpcHandler | null = null;
private deviceRegistrar: DeviceRegistrar | null = null;
+ /** Samples CPU / memory / load for the personal device while the connection is on. */
+ private metricsSampler: { deviceId: string; sampler: DeviceMetricsSampler } | null = null;
private workspaceTokenProvider: WorkspaceTokenProvider | null = null;
private workspaceDeviceChecker: WorkspaceDeviceChecker | null = null;
@@ -358,6 +362,11 @@ export default class GatewayConnectionService extends ServiceModule {
}
async disconnect(): Promise<{ success: boolean }> {
+ // A user-initiated disconnect turns the device off, so stop sampling too —
+ // the page then shows no data rather than "running but unreachable". The
+ // samples since the last upload are pushed first (bounded), while the
+ // socket is still open.
+ await this.stopMetricsSampler({ flushTimeoutMs: 3000 });
if (this.client) {
await this.client.disconnect();
this.client = null;
@@ -414,6 +423,7 @@ export default class GatewayConnectionService extends ServiceModule {
}).catch((err) => {
logger.warn(`Device registration failed (non-fatal): ${(err as Error).message}`);
});
+ await this.startMetricsSampler(identity.deviceId);
}
const { GatewayClient } = await import('@lobechat/device-gateway-client');
@@ -981,6 +991,44 @@ export default class GatewayConnectionService extends ServiceModule {
this.powerSaveBlockerId = null;
}
+ // ─── Device Metrics ───
+
+ /**
+ * Keeps sampling across drops and reconnects (that stretch is what explains
+ * a drop); only a new identity or an explicit disconnect replaces it.
+ * Samples go to the device gateway (their only store) over the personal
+ * connection, whichever client instance currently holds it.
+ */
+ private async startMetricsSampler(deviceId: string) {
+ if (this.metricsSampler?.deviceId === deviceId) return;
+ await this.stopMetricsSampler();
+
+ const userData = safeGetPath('userData');
+ const { DeviceMetricsSampler, deviceMetricsBacklogFileName, pushMetrics } =
+ await import('@lobechat/device-control/metrics');
+ const sampler = new DeviceMetricsSampler({
+ isConnected: () => this.status === 'connected',
+ logger: { warn: (msg) => logger.warn(msg) },
+ storagePath: userData
+ ? path.join(userData, 'device-metrics', deviceMetricsBacklogFileName(deviceId))
+ : undefined,
+ // Mirrored to the workspace-share connections so a shared device's
+ // workspace row has the same history (the gateway stores per socket).
+ upload: async (samples) => {
+ if (!this.client) throw new Error('Gateway not connected');
+ await pushMetrics(this.client, this.workspaceClients.values(), samples);
+ },
+ });
+ this.metricsSampler = { deviceId, sampler };
+ await sampler.start();
+ }
+
+ private async stopMetricsSampler(options?: { flushTimeoutMs?: number }) {
+ const current = this.metricsSampler;
+ this.metricsSampler = null;
+ await current?.sampler.stop(options);
+ }
+
// ─── Status Broadcasting ───
private setStatus(status: GatewayConnectionStatus) {
@@ -989,6 +1037,8 @@ export default class GatewayConnectionService extends ServiceModule {
logger.info(`Connection status: ${this.status} → ${status}`);
this.status = status;
+ // Upload what accrued while offline right away, not at the next tick.
+ if (status === 'connected') void this.metricsSampler?.sampler.flush();
this.syncPowerSaveBlocker();
this.scheduleStatusBroadcast(status);
}
diff --git a/apps/server/src/routers/lambda/__tests__/deviceMetric.test.ts b/apps/server/src/routers/lambda/__tests__/deviceMetric.test.ts
new file mode 100644
index 00000000000..0a96afacaea
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/deviceMetric.test.ts
@@ -0,0 +1,102 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return {};
+ }),
+}));
+
+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {
+ const { authedProcedure } = await import('@/libs/trpc/lambda');
+ return { wsCompatProcedure: authedProcedure };
+});
+
+const deviceModel = { findByDeviceId: vi.fn(), findWorkspaceDeviceById: vi.fn() };
+vi.mock('@/database/models/device', () => ({
+ DeviceModel: vi.fn(function () {
+ return deviceModel;
+ }),
+}));
+
+const queryDeviceMetrics = vi.fn();
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: { queryDeviceMetrics },
+}));
+
+const { deviceMetricRouter } = await import('../deviceMetric');
+
+const sample = (observedAt: number) => ({
+ connected: true,
+ cpuCount: 8,
+ cpuPercent: 12,
+ load1: 1,
+ load15: 1,
+ load5: 1,
+ memoryTotalBytes: 100,
+ memoryUsedBytes: 50,
+ observedAt,
+});
+
+describe('deviceMetricRouter.getSeries', () => {
+ const personal = deviceMetricRouter.createCaller({ serverDB: {}, userId: 'user-1' } as any);
+ const workspace = deviceMetricRouter.createCaller({
+ serverDB: {},
+ userId: 'user-1',
+ workspaceId: 'ws-1',
+ } as any);
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ queryDeviceMetrics.mockResolvedValue([]);
+ });
+
+ it('reads the gateway for a visible personal device and buckets 12 hours into 5-minute points', async () => {
+ deviceModel.findByDeviceId.mockResolvedValue({ id: 'row-1', workspaceId: null });
+ const now = Date.now();
+ queryDeviceMetrics.mockResolvedValue([sample(now - 60_000)]);
+
+ const series = await personal.getSeries({ deviceId: 'dev-1' });
+
+ expect(queryDeviceMetrics).toHaveBeenCalledWith({
+ deviceId: 'dev-1',
+ since: series.from,
+ userId: 'user-1',
+ workspaceId: undefined,
+ });
+ expect(series.bucketMs).toBe(5 * 60_000);
+ expect(series.to - series.from).toBe(12 * 60 * 60 * 1000);
+ expect(series.cpuCount).toBe(8);
+ expect(series.points).toHaveLength(1);
+ });
+
+ it('does not treat a workspace row as personal', async () => {
+ deviceModel.findByDeviceId.mockResolvedValue({ id: 'row-ws', workspaceId: 'ws-1' });
+
+ await expect(personal.getSeries({ deviceId: 'dev-ws' })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ expect(queryDeviceMetrics).not.toHaveBeenCalled();
+ });
+
+ it('hides workspace devices the caller cannot see', async () => {
+ deviceModel.findWorkspaceDeviceById.mockResolvedValue(undefined);
+
+ await expect(workspace.getSeries({ deviceId: 'private' })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ expect(queryDeviceMetrics).not.toHaveBeenCalled();
+ });
+
+ it('routes a visible workspace device to the workspace principal', async () => {
+ deviceModel.findWorkspaceDeviceById.mockResolvedValue({ id: 'row-ws', workspaceId: 'ws-1' });
+
+ const series = await workspace.getSeries({ deviceId: 'dev-ws' });
+
+ expect(queryDeviceMetrics).toHaveBeenCalledWith(
+ expect.objectContaining({ deviceId: 'dev-ws', workspaceId: 'ws-1' }),
+ );
+ expect(series.cpuCount).toBeNull();
+ expect(series.points).toEqual([]);
+ });
+});
diff --git a/apps/server/src/routers/lambda/deviceMetric.ts b/apps/server/src/routers/lambda/deviceMetric.ts
new file mode 100644
index 00000000000..952796e37ef
--- /dev/null
+++ b/apps/server/src/routers/lambda/deviceMetric.ts
@@ -0,0 +1,88 @@
+import type { DeviceMetricSeries } from '@lobechat/types';
+import {
+ bucketDeviceMetrics,
+ DEVICE_METRIC_RETENTION_MS,
+ DEVICE_METRIC_SAMPLE_INTERVAL_MS,
+ DEVICE_METRIC_VIEW_WINDOW_MS,
+} from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
+import { DeviceModel } from '@/database/models/device';
+import { router } from '@/libs/trpc/lambda';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { deviceGateway } from '@/server/services/deviceGateway';
+
+/** Aim for about this many points per chart, whatever the window. */
+const TARGET_POINTS = 144;
+
+const deviceMetricProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+ const workspaceId = ctx.workspaceId ?? undefined;
+ const deviceModel = new DeviceModel(ctx.serverDB, ctx.userId, workspaceId);
+
+ /**
+ * Gate a client-supplied `deviceId` with the same visibility rule every
+ * device route uses: in a workspace only rows the caller can see (public,
+ * or its own private enrollment); otherwise only the caller's personal
+ * rows. The gateway itself only knows principals, not visibility.
+ */
+ const assertDeviceVisible = async (deviceId: string) => {
+ const row = workspaceId
+ ? await deviceModel.findWorkspaceDeviceById(deviceId)
+ : await deviceModel.findByDeviceId(deviceId);
+ if (!row || (!workspaceId && row.workspaceId)) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Device not found.' });
+ }
+ };
+
+ return opts.next({ ctx: { assertDeviceVisible, userId: ctx.userId, workspaceId } });
+});
+
+export const deviceMetricRouter = router({
+ /**
+ * The machine's recent CPU / memory / load, 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.
+ */
+ getSeries: deviceMetricProcedure
+ .input(
+ z.object({
+ deviceId: z.string().min(1).max(64),
+ windowMs: z
+ .number()
+ .int()
+ .min(DEVICE_METRIC_SAMPLE_INTERVAL_MS)
+ .max(DEVICE_METRIC_RETENTION_MS)
+ .default(DEVICE_METRIC_VIEW_WINDOW_MS),
+ }),
+ )
+ .query(async ({ ctx, input }): Promise<DeviceMetricSeries> => {
+ await ctx.assertDeviceVisible(input.deviceId);
+ const to = Date.now();
+ const from = to - input.windowMs;
+ const bucketMs = Math.max(
+ DEVICE_METRIC_SAMPLE_INTERVAL_MS,
+ Math.ceil(input.windowMs / TARGET_POINTS / DEVICE_METRIC_SAMPLE_INTERVAL_MS) *
+ DEVICE_METRIC_SAMPLE_INTERVAL_MS,
+ );
+
+ const samples = await deviceGateway.queryDeviceMetrics({
+ deviceId: input.deviceId,
+ since: from,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ const latest = samples.at(-1);
+
+ return {
+ bucketMs,
+ cpuCount: latest?.cpuCount ?? null,
+ from,
+ memoryTotalBytes: latest?.memoryTotalBytes ?? null,
+ points: bucketDeviceMetrics(samples, { bucketMs, from, to }),
+ to,
+ };
+ }),
+});
diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.ts
index 6ca56a27c09..d108850025e 100644
--- a/apps/server/src/routers/lambda/index.ts
+++ b/apps/server/src/routers/lambda/index.ts
@@ -50,6 +50,7 @@ import { composioRouter } from './composio';
import { configRouter } from './config';
import { connectorRouter } from './connector';
import { deviceRouter } from './device';
+import { deviceMetricRouter } from './deviceMetric';
import { documentRouter } from './document';
import { documentCommentRouter } from './documentComment';
import { documentLikeRouter } from './documentLike';
@@ -134,6 +135,7 @@ export const lambdaRouter = router({
config: configRouter,
connector: connectorRouter,
device: deviceRouter,
+ deviceMetric: deviceMetricRouter,
document: documentRouter,
documentComment: documentCommentRouter,
documentLike: documentLikeRouter,
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index eee3fdad5fe..bd288188b40 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -50,6 +50,7 @@ import type {
DeviceListeningPortsResult,
DeviceListProjectSkillsResult,
DeviceLocalFilePreviewResult,
+ DeviceMetricSample,
DeviceMoveProjectFileItem,
DeviceMoveProjectFileResultItem,
DeviceProjectDirectoryListResult,
@@ -257,6 +258,25 @@ export class DeviceGateway {
}
}
+ /**
+ * The device's health samples held by the gateway (two days), observed at or
+ * after `since`. Unlike the RPC reads this works while the device is
+ * offline — the samples live in gateway storage, not on the device.
+ */
+ async queryDeviceMetrics(params: {
+ deviceId: string;
+ since: number;
+ userId: string;
+ workspaceId?: string;
+ }): Promise<DeviceMetricSample[]> {
+ const client = this.getClient();
+ if (!client) return [];
+ return client.getDeviceMetrics(params.userId, params.deviceId, {
+ since: params.since,
+ workspaceId: params.workspaceId,
+ });
+ }
+
/**
* Scan a bound project directory on the device in a single round-trip:
* project skills (`.agents/skills` + `.claude/skills`) plus the root
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index bd7311e1d01..a35bdf866b5 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -383,6 +383,12 @@
"devices.actions.edit": "Edit",
"devices.actions.refresh": "Refresh",
"devices.actions.remove": "Remove",
+ "devices.agents.empty": "No agents found on this device",
+ "devices.agents.error": "Could not check this device: {{error}}",
+ "devices.agents.installed": "Installed",
+ "devices.agents.offline": "This device is offline. Installed agents are detected once it reconnects.",
+ "devices.agents.rescan": "Check again",
+ "devices.agents.scanning": "Checking installed agents…",
"devices.appUpdate.checkFailed": "Couldn't check for updates: {{message}}",
"devices.appUpdate.confirmDesc": "LobeHub on this device will quit and restart. Anything it is running, including agent tasks, will be interrupted.",
"devices.appUpdate.confirmTitle": "Restart and update to v{{version}}?",
@@ -428,6 +434,9 @@
"devices.detail.connections": "Connections",
"devices.detail.noRecent": "No recent directories",
"devices.detail.recentDirs": "Recent directories",
+ "devices.detail.tabs.agents": "Agent runtimes",
+ "devices.detail.tabs.files": "Directories",
+ "devices.detail.tabs.overview": "Overview",
"devices.edit.browse": "Browse…",
"devices.edit.cancel": "Cancel",
"devices.edit.defaultCwd": "Default working directory",
@@ -445,6 +454,28 @@
"devices.empty.title": "Connect your first device",
"devices.fallbackBadge": "Unstable identity",
"devices.fallbackTooltip": "This device couldn't be identified by its machine ID, so reinstalling the app may create a duplicate entry.",
+ "devices.health.cpu": "CPU",
+ "devices.health.cpuCores_one": "CPU · {{count}} core",
+ "devices.health.cpuCores_other": "CPU · {{count}} cores",
+ "devices.health.empty": "No health data yet. It starts recording once this device runs the latest LobeHub desktop app or CLI.",
+ "devices.health.error": "Couldn't load health data",
+ "devices.health.level.critical": "Critical",
+ "devices.health.level.high": "High",
+ "devices.health.level.missing": "No data",
+ "devices.health.level.normal": "Normal",
+ "devices.health.level.offline": "Disconnected",
+ "devices.health.loadShort": "Load",
+ "devices.health.load_one": "Load · {{count}} core",
+ "devices.health.load_other": "Load · {{count}} cores",
+ "devices.health.loading": "Loading health data…",
+ "devices.health.memory": "Memory",
+ "devices.health.now": "Now",
+ "devices.health.retry": "Retry",
+ "devices.health.status.missing": "No data — asleep, off, or LobeHub not running",
+ "devices.health.status.offline": "Running but disconnected",
+ "devices.health.status.online": "Online",
+ "devices.health.status.pending": "Not uploaded yet",
+ "devices.health.title": "Health · last 12 hours",
"devices.keepAwake.desc": "Prevent automatic sleep while this computer is connected as a device, so it stays reachable. The display can still turn off; closing a laptop lid without an external display still puts it to sleep.",
"devices.keepAwake.title": "Keep Awake While Connected",
"devices.lastSeen": "Last connected {{time}}",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 1c4449fc4b4..05888d1ea42 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -383,6 +383,12 @@
"devices.actions.edit": "编辑",
"devices.actions.refresh": "刷新",
"devices.actions.remove": "移除",
+ "devices.agents.empty": "这台设备上没有检测到 Agent",
+ "devices.agents.error": "检测失败:{{error}}",
+ "devices.agents.installed": "已安装",
+ "devices.agents.offline": "设备离线,重新连接后可检测已安装的 Agent。",
+ "devices.agents.rescan": "重新检测",
+ "devices.agents.scanning": "正在检测已安装的 Agent…",
"devices.appUpdate.checkFailed": "检查更新失败:{{message}}",
"devices.appUpdate.confirmDesc": "该设备上的 LobeHub 会退出并重启,正在运行的内容(包括助理任务)都会被中断。",
"devices.appUpdate.confirmTitle": "重启并更新到 v{{version}}?",
@@ -428,6 +434,9 @@
"devices.detail.connections": "连接通道",
"devices.detail.noRecent": "暂无最近目录",
"devices.detail.recentDirs": "最近目录",
+ "devices.detail.tabs.agents": "Agent 运行时",
+ "devices.detail.tabs.files": "文件目录",
+ "devices.detail.tabs.overview": "概览",
"devices.edit.browse": "浏览…",
"devices.edit.cancel": "取消",
"devices.edit.defaultCwd": "默认工作目录",
@@ -445,6 +454,28 @@
"devices.empty.title": "连接你的第一台设备",
"devices.fallbackBadge": "身份不稳定",
"devices.fallbackTooltip": "未能通过机器 ID 识别此设备,重装应用可能会产生重复条目。",
+ "devices.health.cpu": "CPU",
+ "devices.health.cpuCores_one": "CPU · {{count}} 核",
+ "devices.health.cpuCores_other": "CPU · {{count}} 核",
+ "devices.health.empty": "暂无运行数据。设备运行最新版 LobeHub 桌面端或 CLI 后开始记录。",
+ "devices.health.error": "运行状况加载失败",
+ "devices.health.level.critical": "过高",
+ "devices.health.level.high": "偏高",
+ "devices.health.level.missing": "无数据",
+ "devices.health.level.normal": "正常",
+ "devices.health.level.offline": "断开",
+ "devices.health.loadShort": "负载",
+ "devices.health.load_one": "负载 · {{count}} 核",
+ "devices.health.load_other": "负载 · {{count}} 核",
+ "devices.health.loading": "正在加载运行状况…",
+ "devices.health.memory": "内存",
+ "devices.health.now": "现在",
+ "devices.health.retry": "重试",
+ "devices.health.status.missing": "无数据:休眠、关机或 LobeHub 未运行",
+ "devices.health.status.offline": "运行中但已断开连接",
+ "devices.health.status.online": "在线",
+ "devices.health.status.pending": "尚未上传",
+ "devices.health.title": "运行状况 · 过去 12 小时",
"devices.keepAwake.desc": "作为设备连接期间阻止电脑自动睡眠,保证它始终可被访问。屏幕仍可正常关闭;未连接外接显示器时合上笔记本屏幕仍会睡眠。",
"devices.keepAwake.title": "连接期间保持唤醒",
"devices.lastSeen": "最后连接于 {{time}}",
diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.ts
index f3d8a9a03ef..e62da458512 100644
--- a/packages/const/src/apiKeyScope.ts
+++ b/packages/const/src/apiKeyScope.ts
@@ -213,6 +213,7 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRule
config: 'open',
connector: 'blocked',
device: 'blocked',
+ deviceMetric: 'blocked',
document: rw('knowledge:read', 'knowledge:write'),
documentComment: rw('knowledge:read', 'knowledge:write'),
documentLike: rw('knowledge:read', 'knowledge:write'),
diff --git a/packages/device-control/package.json b/packages/device-control/package.json
index 27247160b56..cd2dac5e189 100644
--- a/packages/device-control/package.json
+++ b/packages/device-control/package.json
@@ -6,6 +6,7 @@
"exports": {
".": "./src/index.ts",
"./file-preview": "./src/filePreview.ts",
+ "./metrics": "./src/metrics/index.ts",
"./project-file-index": "./src/projectFileIndex.ts",
"./skill-directory": "./src/skillDirectory.ts",
"./workspace": "./src/workspace.ts"
@@ -20,6 +21,7 @@
"@lobechat/heterogeneous-agents": "workspace:*",
"@lobechat/html-artifact": "workspace:*",
"@lobechat/local-file-shell": "workspace:*",
+ "@lobechat/types": "workspace:*",
"@lobechat/utils": "workspace:*",
"fast-glob": "^3.3.3",
"fflate": "^0.8.3",
diff --git a/packages/device-control/src/index.ts b/packages/device-control/src/index.ts
index 11d4be6902b..08c9871bbc2 100644
--- a/packages/device-control/src/index.ts
+++ b/packages/device-control/src/index.ts
@@ -19,6 +19,12 @@ export {
type ListListeningPortsParams,
type ListListeningPortsResult,
} from './listeningPorts';
+export {
+ deviceMetricsBacklogFileName,
+ DeviceMetricsSampler,
+ type DeviceMetricsSamplerOptions,
+ pushMetrics,
+} from './metrics';
export {
defaultGetProjectFileIndex,
defaultListProjectDirectory,
diff --git a/packages/device-control/src/metrics/backlogFileName.test.ts b/packages/device-control/src/metrics/backlogFileName.test.ts
new file mode 100644
index 00000000000..92ea91079a6
--- /dev/null
+++ b/packages/device-control/src/metrics/backlogFileName.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest';
+
+import { deviceMetricsBacklogFileName } from './backlogFileName';
+
+describe('deviceMetricsBacklogFileName', () => {
+ it('keeps ids that sanitize to the same prefix in different files', () => {
+ const names = ['prod/api', 'prod:api', 'prod_api', 'Prod_api'].map(
+ deviceMetricsBacklogFileName,
+ );
+ expect(new Set(names.map((name) => name.toLowerCase())).size).toBe(names.length);
+ });
+
+ it('is stable and a safe single path segment', () => {
+ const name = deviceMetricsBacklogFileName('../../etc/passwd');
+ expect(name).toBe(deviceMetricsBacklogFileName('../../etc/passwd'));
+ expect(name).toMatch(/^[\w-]+\.json$/);
+ });
+
+ it('bounds the length for very long ids', () => {
+ expect(deviceMetricsBacklogFileName('x'.repeat(1000)).length).toBeLessThanOrEqual(64 + 22);
+ });
+});
diff --git a/packages/device-control/src/metrics/backlogFileName.ts b/packages/device-control/src/metrics/backlogFileName.ts
new file mode 100644
index 00000000000..d0ea8f1b505
--- /dev/null
+++ b/packages/device-control/src/metrics/backlogFileName.ts
@@ -0,0 +1,14 @@
+import { createHash } from 'node:crypto';
+
+/**
+ * File name for a device's unsent-sample backlog. Device ids can be arbitrary
+ * user strings (`lh connect --device-id`), so the readable prefix alone is
+ * lossy (`prod/api` and `prod:api` both sanitize to `prod_api`); the hash of
+ * the raw id keeps distinct ids in distinct files, also on case-insensitive
+ * file systems.
+ */
+export const deviceMetricsBacklogFileName = (deviceId: string): string => {
+ const readable = deviceId.replaceAll(/[^\w-]/g, '_').slice(0, 64);
+ const digest = createHash('sha256').update(deviceId).digest('hex').slice(0, 16);
+ return `${readable}-${digest}.json`;
+};
diff --git a/packages/device-control/src/metrics/index.ts b/packages/device-control/src/metrics/index.ts
new file mode 100644
index 00000000000..9df68295ca5
--- /dev/null
+++ b/packages/device-control/src/metrics/index.ts
@@ -0,0 +1,3 @@
+export { deviceMetricsBacklogFileName } from './backlogFileName';
+export { pushMetrics } from './pushMetrics';
+export { DeviceMetricsSampler, type DeviceMetricsSamplerOptions } from './sampler';
diff --git a/packages/device-control/src/metrics/pushMetrics.test.ts b/packages/device-control/src/metrics/pushMetrics.test.ts
new file mode 100644
index 00000000000..adb86152faa
--- /dev/null
+++ b/packages/device-control/src/metrics/pushMetrics.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { pushMetrics } from './pushMetrics';
+
+const target = (connectionStatus = 'connected', fails = false) => ({
+ connectionStatus,
+ reportMetrics: vi.fn(() => (fails ? Promise.reject(new Error('down')) : Promise.resolve())),
+});
+
+describe('pushMetrics', () => {
+ const samples = [{ observedAt: 1 }] as any;
+
+ it('mirrors the batch to connected workspace-share connections', async () => {
+ const primary = target();
+ const shared = target();
+ const offline = target('reconnecting');
+
+ await pushMetrics(primary, [shared, offline], samples);
+
+ expect(primary.reportMetrics).toHaveBeenCalledWith(samples);
+ expect(shared.reportMetrics).toHaveBeenCalledWith(samples);
+ expect(offline.reportMetrics).not.toHaveBeenCalled();
+ });
+
+ it('fails when the device connection fails, so the batch is kept', async () => {
+ const shared = target();
+
+ await expect(pushMetrics(target('connected', true), [shared], samples)).rejects.toThrow('down');
+ expect(shared.reportMetrics).not.toHaveBeenCalled();
+ });
+
+ it('does not fail on a mirror error', async () => {
+ await expect(
+ pushMetrics(target(), [target('connected', true)], samples),
+ ).resolves.toBeUndefined();
+ });
+});
diff --git a/packages/device-control/src/metrics/pushMetrics.ts b/packages/device-control/src/metrics/pushMetrics.ts
new file mode 100644
index 00000000000..658d9bd1a68
--- /dev/null
+++ b/packages/device-control/src/metrics/pushMetrics.ts
@@ -0,0 +1,29 @@
+import type { DeviceMetricSample } from '@lobechat/types';
+
+interface MetricsTarget {
+ readonly connectionStatus: string;
+ reportMetrics: (samples: DeviceMetricSample[]) => Promise<void>;
+}
+
+/**
+ * Push one batch to the device's own connection and mirror it to the
+ * workspace-share connections of the same machine. The gateway stores samples
+ * under each socket's device identity, so a shared device's workspace row only
+ * has health data if the batch also travels over that workspace's socket.
+ *
+ * The primary push must succeed (a failure keeps the batch for the next
+ * attempt); mirrors are best-effort, so a share connection that happens to be
+ * down misses that batch rather than holding the device's backlog hostage.
+ */
+export const pushMetrics = async (
+ primary: MetricsTarget,
+ mirrors: Iterable<MetricsTarget>,
+ samples: DeviceMetricSample[],
+): Promise<void> => {
+ await primary.reportMetrics(samples);
+ await Promise.allSettled(
+ [...mirrors]
+ .filter((mirror) => mirror !== primary && mirror.connectionStatus === 'connected')
+ .map((mirror) => mirror.reportMetrics(samples)),
+ );
+};
diff --git a/packages/device-control/src/metrics/sampler.test.ts b/packages/device-control/src/metrics/sampler.test.ts
new file mode 100644
index 00000000000..c24f6914fa5
--- /dev/null
+++ b/packages/device-control/src/metrics/sampler.test.ts
@@ -0,0 +1,162 @@
+import { mkdtemp, readFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import type { DeviceMetricSample } from '@lobechat/types';
+import { describe, expect, it, vi } from 'vitest';
+
+import { DeviceMetricsSampler } from './sampler';
+
+const setup = async (
+ overrides: {
+ connected?: () => boolean;
+ upload?: (s: DeviceMetricSample[]) => Promise<void>;
+ } = {},
+) => {
+ let now = 1_000_000;
+ let idle = 0;
+ let total = 0;
+ const storagePath = path.join(
+ await mkdtemp(path.join(os.tmpdir(), 'lh-metrics-')),
+ 'backlog.json',
+ );
+ const upload = vi.fn(overrides.upload ?? (async () => {}));
+ const warn = vi.fn();
+ const create = () =>
+ new DeviceMetricsSampler({
+ isConnected: overrides.connected ?? (() => true),
+ logger: { warn },
+ now: () => now,
+ readers: {
+ // Each reading adds 100 units of CPU time, 25 of them busy.
+ cpuTimes: () => ({ idle: (idle += 75), total: (total += 100) }),
+ loadAverage: () => [1, 2, 3],
+ memory: async () => ({ totalBytes: 100, usedBytes: 40 }),
+ },
+ storagePath,
+ upload,
+ });
+ return { advance: (ms: number) => (now += ms), create, storagePath, upload, warn };
+};
+
+describe('DeviceMetricsSampler', () => {
+ it('records CPU, memory, load and connection state', async () => {
+ const { create, upload } = await setup({ connected: () => false });
+ const sampler = create();
+ await sampler.start();
+ await sampler.sample();
+ await sampler.flush();
+ await sampler.stop();
+
+ expect(upload).toHaveBeenCalledWith([
+ expect.objectContaining({
+ connected: false,
+ cpuPercent: 25,
+ load1: 1,
+ load15: 3,
+ load5: 2,
+ memoryTotalBytes: 100,
+ memoryUsedBytes: 40,
+ observedAt: 1_000_000,
+ }),
+ ]);
+ });
+
+ it('keeps samples until an upload succeeds, across a restart', async () => {
+ let online = false;
+ const { advance, create, storagePath, upload } = await setup({
+ upload: async () => {
+ if (!online) throw new Error('offline');
+ },
+ });
+
+ const first = create();
+ await first.start();
+ await first.sample();
+ advance(60_000);
+ await first.sample();
+ await first.flush();
+ await first.stop();
+ expect(JSON.parse(await readFile(storagePath, 'utf8'))).toHaveLength(2);
+
+ online = true;
+ const second = create();
+ await second.start();
+ await second.flush();
+ await second.stop();
+
+ expect(upload).toHaveBeenLastCalledWith([
+ expect.objectContaining({ observedAt: 1_000_000 }),
+ expect.objectContaining({ observedAt: 1_060_000 }),
+ ]);
+ expect(second.pendingCount).toBe(0);
+ expect(JSON.parse(await readFile(storagePath, 'utf8'))).toEqual([]);
+ });
+
+ it('drops backlog older than the retention window', async () => {
+ const { advance, create, upload } = await setup({
+ upload: async () => {
+ throw new Error('offline');
+ },
+ });
+ const sampler = create();
+ await sampler.start();
+ await sampler.sample();
+ advance(4 * 24 * 60 * 60 * 1000);
+ await sampler.sample();
+ await sampler.stop();
+
+ expect(sampler.pendingCount).toBe(1);
+ expect(upload).not.toHaveBeenCalled();
+ });
+
+ it('pushes pending samples on a clean stop', async () => {
+ const { create, upload } = await setup();
+ const sampler = create();
+ await sampler.start();
+ await sampler.sample();
+ await sampler.stop({ flushTimeoutMs: 3000 });
+
+ expect(upload).toHaveBeenCalledTimes(1);
+ expect(sampler.pendingCount).toBe(0);
+ });
+
+ it('does not hang a clean stop on an upload that never answers', async () => {
+ vi.useFakeTimers();
+ try {
+ const { create } = await setup({ upload: () => new Promise(() => {}) });
+ const sampler = create();
+ await sampler.start();
+ await sampler.sample();
+
+ let stopped = false;
+ const stopping = sampler.stop({ flushTimeoutMs: 3000 }).then(() => (stopped = true));
+ await vi.advanceTimersByTimeAsync(2999);
+ expect(stopped).toBe(false);
+ await vi.advanceTimersByTimeAsync(1);
+ await stopping;
+ // The unsent sample stays in the backlog for the next start.
+ expect(sampler.pendingCount).toBe(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('keeps the backlog file intact when writes overlap', async () => {
+ const { create, storagePath, warn } = await setup({
+ upload: async () => {
+ throw new Error('offline');
+ },
+ });
+ const sampler = create();
+ await sampler.start();
+
+ // Sampling and flushing both persist; overlapping writes shared one temp
+ // path, so the second rename failed and the backlog went stale.
+ await Promise.all([sampler.sample(), sampler.flush(), sampler.sample(), sampler.flush()]);
+
+ expect(warn).not.toHaveBeenCalled();
+ expect(JSON.parse(await readFile(storagePath, 'utf8'))).toHaveLength(2);
+ await sampler.stop();
+ });
+});
diff --git a/packages/device-control/src/metrics/sampler.ts b/packages/device-control/src/metrics/sampler.ts
new file mode 100644
index 00000000000..f01a8d7f542
--- /dev/null
+++ b/packages/device-control/src/metrics/sampler.ts
@@ -0,0 +1,226 @@
+import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import type { DeviceMetricSample } from '@lobechat/types';
+import {
+ DEVICE_METRIC_MAX_BATCH,
+ DEVICE_METRIC_RETENTION_MS,
+ DEVICE_METRIC_SAMPLE_INTERVAL_MS,
+ deviceMetricSampleSchema,
+} from '@lobechat/types';
+
+import type { CpuTimes, MemoryUsage } from './systemSnapshot';
+import {
+ cpuPercentBetween,
+ readCpuTimes,
+ readLoadAverage,
+ readMemoryUsage,
+} from './systemSnapshot';
+
+/** Upload cadence. Samples are still taken every minute and survive until uploaded. */
+const DEFAULT_FLUSH_INTERVAL_MS = 5 * 60_000;
+
+interface SamplerLogger {
+ debug?: (msg: string) => void;
+ warn?: (msg: string) => void;
+}
+
+export interface DeviceMetricsSamplerOptions {
+ flushIntervalMs?: number;
+ /** Whether the device currently holds a live gateway connection. */
+ isConnected: () => boolean;
+ logger?: SamplerLogger;
+ now?: () => number;
+ /** Test seams for the machine readings. */
+ readers?: {
+ cpuTimes?: () => CpuTimes;
+ loadAverage?: () => [number, number, number] | null;
+ memory?: () => Promise<MemoryUsage>;
+ };
+ sampleIntervalMs?: number;
+ /**
+ * File holding samples not yet uploaded, so a backlog collected while the
+ * device could not reach LobeHub survives a restart. Omit to keep it in
+ * memory only.
+ */
+ storagePath?: string;
+ /** Deliver a batch to LobeHub; throw to keep the batch for the next attempt. */
+ upload: (samples: DeviceMetricSample[]) => Promise<void>;
+}
+
+/**
+ * Samples this machine's CPU / memory / load 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.
+ */
+export class DeviceMetricsSampler {
+ private readonly options: DeviceMetricsSamplerOptions;
+ private readonly now: () => number;
+ private pending: DeviceMetricSample[] = [];
+ private lastCpu?: CpuTimes;
+ private sampleTimer?: ReturnType<typeof setInterval>;
+ private flushTimer?: ReturnType<typeof setInterval>;
+ private flushing?: Promise<void>;
+ /** Backlog writes run one at a time; see {@link persist}. */
+ private writeQueue: Promise<void> = Promise.resolve();
+ private started = false;
+
+ constructor(options: DeviceMetricsSamplerOptions) {
+ this.options = options;
+ this.now = options.now ?? Date.now;
+ }
+
+ async start(): Promise<void> {
+ if (this.started) return;
+ this.started = true;
+ this.pending = [...(await this.loadBacklog()), ...this.pending];
+ this.lastCpu = (this.options.readers?.cpuTimes ?? readCpuTimes)();
+
+ const sampleEvery = this.options.sampleIntervalMs ?? DEVICE_METRIC_SAMPLE_INTERVAL_MS;
+ const flushEvery = this.options.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS;
+ this.sampleTimer = setInterval(() => void this.sample(), sampleEvery);
+ this.flushTimer = setInterval(() => void this.flush(), flushEvery);
+ // A background sampler must never keep a CLI process alive on its own.
+ this.sampleTimer.unref?.();
+ this.flushTimer.unref?.();
+ }
+
+ /**
+ * Stop sampling. With `flushTimeoutMs`, first try to upload what is pending
+ * (bounded, so shutdown never hangs on a dead connection): on a clean exit
+ * the minutes since the last upload would otherwise read as "not running"
+ * until the next start.
+ */
+ async stop(options: { flushTimeoutMs?: number } = {}): Promise<void> {
+ if (!this.started) return;
+ this.started = false;
+ clearInterval(this.sampleTimer);
+ clearInterval(this.flushTimer);
+ if (options.flushTimeoutMs) {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ await Promise.race([
+ this.flush(),
+ new Promise<void>((resolve) => {
+ timer = setTimeout(resolve, options.flushTimeoutMs);
+ }),
+ ]);
+ clearTimeout(timer);
+ } else {
+ await this.flushing;
+ }
+ await this.persist();
+ }
+
+ /** Take one sample now. Exposed for the interval and for tests. */
+ async sample(): Promise<void> {
+ const readers = this.options.readers ?? {};
+ const cpu = (readers.cpuTimes ?? readCpuTimes)();
+ const cpuPercent = this.lastCpu ? cpuPercentBetween(this.lastCpu, cpu) : null;
+ this.lastCpu = cpu;
+
+ try {
+ const memory = await (readers.memory ?? readMemoryUsage)();
+ const load = (readers.loadAverage ?? readLoadAverage)();
+ this.pending.push({
+ connected: this.options.isConnected(),
+ cpuCount: Math.max(1, os.cpus().length),
+ cpuPercent,
+ load1: load?.[0] ?? null,
+ load15: load?.[2] ?? null,
+ load5: load?.[1] ?? null,
+ memoryTotalBytes: memory.totalBytes,
+ memoryUsedBytes: memory.usedBytes,
+ observedAt: this.now(),
+ });
+ this.trim();
+ await this.persist();
+ } catch (error) {
+ this.options.logger?.warn?.(`device metrics sample failed: ${(error as Error).message}`);
+ }
+ }
+
+ /**
+ * Upload everything pending, oldest first. Called on the timer and by the
+ * host right after the device (re)connects, so a backlog lands promptly.
+ */
+ flush(): Promise<void> {
+ this.flushing ??= this.doFlush().finally(() => {
+ this.flushing = undefined;
+ });
+ return this.flushing;
+ }
+
+ /** Samples waiting for upload (tests / diagnostics). */
+ get pendingCount(): number {
+ return this.pending.length;
+ }
+
+ private async doFlush(): Promise<void> {
+ while (this.pending.length > 0) {
+ const batch = this.pending.slice(0, DEVICE_METRIC_MAX_BATCH);
+ try {
+ await this.options.upload(batch);
+ } catch (error) {
+ this.options.logger?.debug?.(
+ `device metrics upload deferred (${this.pending.length} pending): ${(error as Error).message}`,
+ );
+ return;
+ }
+ // Samples taken while the upload was in flight stay queued.
+ const uploaded = new Set(batch);
+ this.pending = this.pending.filter((s) => !uploaded.has(s));
+ await this.persist();
+ }
+ }
+
+ private trim() {
+ const oldest = this.now() - DEVICE_METRIC_RETENTION_MS;
+ this.pending = this.pending.filter((s) => s.observedAt >= oldest);
+ }
+
+ private async loadBacklog(): Promise<DeviceMetricSample[]> {
+ const file = this.options.storagePath;
+ if (!file) return [];
+ try {
+ const parsed = JSON.parse(await readFile(file, 'utf8'));
+ if (!Array.isArray(parsed)) return [];
+ const oldest = this.now() - DEVICE_METRIC_RETENTION_MS;
+ return parsed.flatMap((raw) => {
+ const result = deviceMetricSampleSchema.safeParse(raw);
+ return result.success && result.data.observedAt >= oldest ? [result.data] : [];
+ });
+ } catch {
+ return [];
+ }
+ }
+
+ /**
+ * Write the backlog file. Sampling and flushing both persist and can overlap
+ * (coinciding timers, a reconnect flush); every write goes through the same
+ * temp path, so they are queued — each run writes the backlog as it stands
+ * when its turn comes.
+ */
+ private persist(): Promise<void> {
+ const run = this.writeQueue.then(() => this.writeBacklog());
+ this.writeQueue = run;
+ return run;
+ }
+
+ private async writeBacklog(): Promise<void> {
+ const file = this.options.storagePath;
+ if (!file) return;
+ try {
+ await mkdir(path.dirname(file), { recursive: true });
+ // Write-then-rename: a crash mid-write must not corrupt the backlog.
+ const tmp = `${file}.${process.pid}.tmp`;
+ await writeFile(tmp, JSON.stringify(this.pending));
+ await rename(tmp, file);
+ } catch (error) {
+ this.options.logger?.warn?.(
+ `device metrics backlog write failed: ${(error as Error).message}`,
+ );
+ }
+ }
+}
diff --git a/packages/device-control/src/metrics/systemSnapshot.test.ts b/packages/device-control/src/metrics/systemSnapshot.test.ts
new file mode 100644
index 00000000000..e46ce4549f3
--- /dev/null
+++ b/packages/device-control/src/metrics/systemSnapshot.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from 'vitest';
+
+import { cpuPercentBetween, parseMemInfo, parseVmStat } from './systemSnapshot';
+
+describe('cpuPercentBetween', () => {
+ it('is the busy share of elapsed CPU time', () => {
+ expect(cpuPercentBetween({ idle: 100, total: 200 }, { idle: 175, total: 300 })).toBe(25);
+ });
+
+ it('is null when no CPU time elapsed', () => {
+ expect(cpuPercentBetween({ idle: 1, total: 2 }, { idle: 1, total: 2 })).toBeNull();
+ });
+});
+
+describe('parseVmStat', () => {
+ const output = `Mach Virtual Memory Statistics: (page size of 16384 bytes)
+Pages free: 10000.
+Pages active: 200000.
+Pages inactive: 190000.
+Pages speculative: 5000.
+Pages wired down: 100000.
+Pages purgeable: 20000.
+Pages occupied by compressor: 50000.
+Anonymous pages: 150000.
+`;
+
+ it('counts app, wired and compressed memory — not file cache', () => {
+ expect(parseVmStat(output, 64 * 1024 ** 3)).toBe(
+ (150_000 - 20_000 + 100_000 + 50_000) * 16_384,
+ );
+ });
+
+ it('is undefined for unrecognized output', () => {
+ expect(parseVmStat('nope', 1)).toBeUndefined();
+ });
+});
+
+describe('parseMemInfo', () => {
+ it('is total minus available', () => {
+ expect(
+ parseMemInfo('MemTotal: 1000 kB\nMemFree: 10 kB\nMemAvailable: 250 kB\n'),
+ ).toEqual({
+ totalBytes: 1000 * 1024,
+ usedBytes: 750 * 1024,
+ });
+ });
+});
diff --git a/packages/device-control/src/metrics/systemSnapshot.ts b/packages/device-control/src/metrics/systemSnapshot.ts
new file mode 100644
index 00000000000..18f3775cb73
--- /dev/null
+++ b/packages/device-control/src/metrics/systemSnapshot.ts
@@ -0,0 +1,98 @@
+import { execFile } from 'node:child_process';
+import { readFile } from 'node:fs/promises';
+import os from 'node:os';
+
+export interface CpuTimes {
+ idle: number;
+ total: number;
+}
+
+export interface MemoryUsage {
+ totalBytes: number;
+ usedBytes: number;
+}
+
+/** Summed across cores, so two readings give the busy share of the whole machine. */
+export const readCpuTimes = (): CpuTimes => {
+ let idle = 0;
+ let total = 0;
+ for (const cpu of os.cpus()) {
+ const { idle: cpuIdle, irq, nice, sys, user } = cpu.times;
+ idle += cpuIdle;
+ total += cpuIdle + irq + nice + sys + user;
+ }
+ return { idle, total };
+};
+
+/** Busy share of all cores between two readings, 0–100; null when no time elapsed. */
+export const cpuPercentBetween = (prev: CpuTimes, next: CpuTimes): number | null => {
+ const total = next.total - prev.total;
+ if (total <= 0) return null;
+ const busy = total - (next.idle - prev.idle);
+ return Math.min(100, Math.max(0, (busy / total) * 100));
+};
+
+/**
+ * `vm_stat` output → bytes in use the way Activity Monitor counts "Memory
+ * Used" (app + wired + compressed). `os.freemem()` on macOS reports only
+ * truly free pages, so file cache would read as used and every Mac would
+ * look nearly full.
+ */
+export const parseVmStat = (output: string, totalBytes: number): number | undefined => {
+ const pageSize = Number(/page size of (\d+) bytes/.exec(output)?.[1]);
+ if (!pageSize) return undefined;
+ const pages = (label: string) => {
+ const match = new RegExp(`^${label}:\\s+(\\d+)`, 'm').exec(output);
+ return match ? Number(match[1]) : 0;
+ };
+ const used =
+ (pages('Anonymous pages') -
+ pages('Pages purgeable') +
+ pages('Pages wired down') +
+ pages('Pages occupied by compressor')) *
+ pageSize;
+ return Math.min(totalBytes, Math.max(0, used));
+};
+
+/** `/proc/meminfo` → total minus MemAvailable (what `free` calls used + non-reclaimable). */
+export const parseMemInfo = (content: string): MemoryUsage | undefined => {
+ const kb = (label: string) => {
+ const match = new RegExp(`^${label}:\\s+(\\d+) kB`, 'm').exec(content);
+ return match ? Number(match[1]) * 1024 : undefined;
+ };
+ const total = kb('MemTotal');
+ const available = kb('MemAvailable');
+ if (total === undefined || available === undefined) return undefined;
+ return { totalBytes: total, usedBytes: Math.max(0, total - available) };
+};
+
+const runVmStat = () =>
+ new Promise<string>((resolve, reject) => {
+ execFile('vm_stat', { timeout: 5000 }, (error, stdout) =>
+ error ? reject(error) : resolve(stdout),
+ );
+ });
+
+export const readMemoryUsage = async (): Promise<MemoryUsage> => {
+ const totalBytes = os.totalmem();
+ const fallback = { totalBytes, usedBytes: Math.max(0, totalBytes - os.freemem()) };
+ try {
+ if (process.platform === 'darwin') {
+ const used = parseVmStat(await runVmStat(), totalBytes);
+ return used === undefined ? fallback : { totalBytes, usedBytes: used };
+ }
+ if (process.platform === 'linux') {
+ return parseMemInfo(await readFile('/proc/meminfo', 'utf8')) ?? fallback;
+ }
+ } catch {
+ // Fall through to the portable reading.
+ }
+ return fallback;
+};
+
+/** 1 / 5 / 15 minute load averages; Windows has none (Node reports zeros). */
+export const readLoadAverage = (): [number, number, number] | null => {
+ if (process.platform === 'win32') return null;
+ const [load1, load5, load15] = os.loadavg();
+ return [load1, load5, load15];
+};
diff --git a/packages/device-gateway-client/src/client.test.ts b/packages/device-gateway-client/src/client.test.ts
index 386b7783de0..d0379e0624a 100644
--- a/packages/device-gateway-client/src/client.test.ts
+++ b/packages/device-gateway-client/src/client.test.ts
@@ -553,6 +553,52 @@ describe('GatewayClient', () => {
});
});
+ describe('reportMetrics', () => {
+ const samples = [{ observedAt: 1 }] as any;
+
+ const connectAndAuth = async () => {
+ client.connect();
+ await vi.advanceTimersByTimeAsync(1);
+ (client as any).handleMessage(JSON.stringify({ type: 'auth_success' }));
+ return (client as any).ws;
+ };
+
+ it('rejects when not connected', async () => {
+ await expect(client.reportMetrics(samples)).rejects.toThrow('not connected');
+ });
+
+ it('resolves on the matching ack', async () => {
+ const ws = await connectAndAuth();
+ const pending = client.reportMetrics(samples);
+
+ const sent = JSON.parse(ws.send.mock.calls.at(-1)[0]);
+ expect(sent).toMatchObject({ samples, type: 'device_metrics' });
+ (client as any).handleMessage(
+ JSON.stringify({ accepted: 1, batchId: sent.batchId, type: 'device_metrics_ack' }),
+ );
+
+ await expect(pending).resolves.toBeUndefined();
+ });
+
+ it('rejects when no ack arrives in time', async () => {
+ await connectAndAuth();
+ const pending = client.reportMetrics(samples);
+ const assertion = expect(pending).rejects.toThrow('Timed out');
+
+ await vi.advanceTimersByTimeAsync(15_000);
+ await assertion;
+ });
+
+ it('rejects in-flight batches when the socket goes away', async () => {
+ await connectAndAuth();
+ const pending = client.reportMetrics(samples);
+ const assertion = expect(pending).rejects.toThrow('closed');
+
+ await client.disconnect();
+ await assertion;
+ });
+ });
+
describe('tunnel serving', () => {
it('forwards tunnel frames to the tunnel host', async () => {
client.connect();
diff --git a/packages/device-gateway-client/src/client.ts b/packages/device-gateway-client/src/client.ts
index 49a920583a4..46f0bc58624 100644
--- a/packages/device-gateway-client/src/client.ts
+++ b/packages/device-gateway-client/src/client.ts
@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';
import { EventEmitter } from 'node:events';
import os from 'node:os';
+import type { DeviceMetricSample } from '@lobechat/types';
import WebSocket from 'ws';
import { DeviceTunnelHost } from './tunnel';
@@ -36,6 +37,7 @@ const MAX_MISSED_HEARTBEATS = 3; // Force reconnect after 3 missed acks
* stalling a reconnect for 15+ minutes while the device sat offline.
*/
const CONNECT_TIMEOUT = 15_000; // 15s
+const METRICS_ACK_TIMEOUT_MS = 15_000;
// ─── Logger Interface ───
@@ -109,6 +111,10 @@ export class GatewayClient extends EventEmitter {
private reconnectDelay = INITIAL_RECONNECT_DELAY;
private missedHeartbeats = 0;
private status: ConnectionStatus = 'disconnected';
+ private pendingMetricAcks = new Map<
+ string,
+ { reject: (error: Error) => void; resolve: () => void }
+ >();
private intentionalDisconnect = false;
private deviceId: string;
private connectionId: string;
@@ -227,6 +233,36 @@ export class GatewayClient extends EventEmitter {
});
}
+ /**
+ * Push a batch of health samples to the gateway (its only store) and resolve
+ * once the gateway acks it. Rejects when not connected, when the connection
+ * drops mid-flight, or when no ack arrives in time — the caller keeps the
+ * batch and retries later.
+ */
+ reportMetrics(samples: DeviceMetricSample[]): Promise<void> {
+ if (this.status !== 'connected' || this.ws?.readyState !== WebSocket.OPEN) {
+ return Promise.reject(new Error('Gateway not connected'));
+ }
+ const batchId = randomUUID();
+ return new Promise<void>((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.pendingMetricAcks.delete(batchId);
+ reject(new Error('Timed out waiting for device_metrics_ack'));
+ }, METRICS_ACK_TIMEOUT_MS);
+ this.pendingMetricAcks.set(batchId, {
+ reject: (error) => {
+ clearTimeout(timer);
+ reject(error);
+ },
+ resolve: () => {
+ clearTimeout(timer);
+ resolve();
+ },
+ });
+ this.sendMessage({ batchId, samples, type: 'device_metrics' });
+ });
+ }
+
sendSystemInfoResponse(response: Omit<SystemInfoResponseMessage, 'type'>): void {
this.sendMessage({
...response,
@@ -406,6 +442,13 @@ export class GatewayClient extends EventEmitter {
break;
}
+ case 'device_metrics_ack': {
+ const pending = this.pendingMetricAcks.get(message.batchId);
+ this.pendingMetricAcks.delete(message.batchId);
+ pending?.resolve();
+ break;
+ }
+
case 'tunnel_open':
case 'tunnel_data':
case 'tunnel_ack':
@@ -439,6 +482,7 @@ export class GatewayClient extends EventEmitter {
// In-flight tunnels can't survive the socket: their frames have nowhere to
// go and the browser side is already being failed by the gateway.
this.tunnelHost?.closeAll('DEVICE_DISCONNECTED');
+ this.rejectPendingMetricAcks();
// `handshakeTimeout` closes the socket on its own, so the watchdog must be
// disarmed here or it would fire later and force a SECOND reconnect on top
// of the one this close already scheduled.
@@ -563,11 +607,20 @@ export class GatewayClient extends EventEmitter {
}
}
+ /** An ack can no longer arrive on this socket; fail the batches so the sampler retries. */
+ private rejectPendingMetricAcks() {
+ for (const pending of this.pendingMetricAcks.values()) {
+ pending.reject(new Error('Gateway connection closed'));
+ }
+ this.pendingMetricAcks.clear();
+ }
+
private closeWebSocket() {
// Every teardown funnels through here — including `forceReconnect`, which
// detaches `handleClose` — so tunnels must be released here or a forced
// reconnect would leave loopback fetches running and slots consumed.
this.tunnelHost?.closeAll('DEVICE_DISCONNECTED');
+ this.rejectPendingMetricAcks();
if (!this.ws) {
return;
}
diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.ts
index c2a385fc74f..f60f0ce8acb 100644
--- a/packages/device-gateway-client/src/http.ts
+++ b/packages/device-gateway-client/src/http.ts
@@ -1,3 +1,5 @@
+import type { DeviceMetricSample } from '@lobechat/types';
+
import {
describeGatewayRequestFailure,
describeGatewayResponseFailure,
@@ -384,6 +386,26 @@ export class GatewayHttpClient {
};
}
+ /**
+ * Health samples the gateway holds for a device (it keeps two days), observed
+ * at or after `since`. Served from gateway storage, so an offline device
+ * still has its history.
+ */
+ async getDeviceMetrics(
+ userId: string,
+ deviceId: string,
+ options: { since?: number; workspaceId?: string } = {},
+ ): Promise<DeviceMetricSample[]> {
+ const res = await this.post(
+ '/api/device/metrics',
+ { deviceId, since: options.since, userId, workspaceId: options.workspaceId },
+ { timeout: DEVICE_QUERY_TIMEOUT_MS },
+ );
+ if (!res.ok) throw new Error(`device metrics read failed: HTTP ${res.status}`);
+ const data = (await res.json()) as { samples?: DeviceMetricSample[] };
+ return data.samples ?? [];
+ }
+
// ─── Tunnel registry (gateway admin API) ───
//
// These do NOT reach the device: they manage the slug → { device, port }
diff --git a/packages/device-gateway-client/src/index.ts b/packages/device-gateway-client/src/index.ts
index 4259a56d35e..070a349ddea 100644
--- a/packages/device-gateway-client/src/index.ts
+++ b/packages/device-gateway-client/src/index.ts
@@ -22,3 +22,4 @@ export type { DeviceTunnelHostOptions } from './tunnel';
export { DeviceTunnelHost } from './tunnel';
export * from './types';
export type { TunnelUpstreamFactory, TunnelUpstreamSocket } from './wsTunnel';
+export type { DeviceMetricSample } from '@lobechat/types';
diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.ts
index 52bbd85036b..2d168301035 100644
--- a/packages/device-gateway-client/src/types.ts
+++ b/packages/device-gateway-client/src/types.ts
@@ -1,3 +1,5 @@
+import type { DeviceMetricSample } from '@lobechat/types';
+
// ─── Device Info ───
/** A single live gateway WebSocket connection belonging to a device. */
@@ -91,7 +93,20 @@ export interface MessageApiResponseMessage {
type: 'message_api_response';
}
+/** A batch of machine health samples; the gateway stores them for two days. */
+export interface DeviceMetricsMessage {
+ batchId: string;
+ samples: DeviceMetricSample[];
+ type: 'device_metrics';
+}
+
// Server → Client
+export interface DeviceMetricsAckMessage {
+ accepted: number;
+ batchId: string;
+ type: 'device_metrics_ack';
+}
+
export interface HeartbeatAckMessage {
type: 'heartbeat_ack';
}
@@ -464,6 +479,7 @@ export interface AgentRunAckMessage {
export type ClientMessage =
| AgentRunAckMessage
| AuthMessage
+ | DeviceMetricsMessage
| HeartbeatMessage
| MessageApiResponseMessage
| RpcResponseMessage
@@ -475,6 +491,7 @@ export type ServerMessage =
| AuthExpiredMessage
| AuthFailedMessage
| AuthSuccessMessage
+ | DeviceMetricsAckMessage
| HeartbeatAckMessage
| MessageApiRequestMessage
| RpcRequestMessage
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 3d0b874b724..4f42f84ac11 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -632,10 +632,20 @@ export default {
'devices.channel.connected': 'Connected {{time}}',
'devices.channel.unknown': 'Unknown client',
'devices.currentBadge': 'This device',
+ 'devices.agents.empty': 'No agents found on this device',
+ 'devices.agents.error': 'Could not check this device: {{error}}',
+ 'devices.agents.installed': 'Installed',
+ 'devices.agents.offline':
+ 'This device is offline. Installed agents are detected once it reconnects.',
+ 'devices.agents.rescan': 'Check again',
+ 'devices.agents.scanning': 'Checking installed agents…',
'devices.detail.addDir': 'Add directory',
'devices.detail.connections': 'Connections',
'devices.detail.noRecent': 'No recent directories',
'devices.detail.recentDirs': 'Recent directories',
+ 'devices.detail.tabs.agents': 'Agent runtimes',
+ 'devices.detail.tabs.files': 'Directories',
+ 'devices.detail.tabs.overview': 'Overview',
'devices.edit.browse': 'Browse…',
'devices.edit.cancel': 'Cancel',
'devices.edit.defaultCwd': 'Default working directory',
@@ -687,6 +697,29 @@ export default {
'devices.fallbackBadge': 'Unstable identity',
'devices.fallbackTooltip':
"This device couldn't be identified by its machine ID, so reinstalling the app may create a duplicate entry.",
+ 'devices.health.cpu': 'CPU',
+ 'devices.health.error': "Couldn't load health data",
+ 'devices.health.loading': 'Loading health data…',
+ 'devices.health.retry': 'Retry',
+ 'devices.health.cpuCores_one': 'CPU · {{count}} core',
+ 'devices.health.cpuCores_other': 'CPU · {{count}} cores',
+ 'devices.health.level.critical': 'Critical',
+ 'devices.health.level.high': 'High',
+ 'devices.health.level.missing': 'No data',
+ 'devices.health.level.normal': 'Normal',
+ 'devices.health.level.offline': 'Disconnected',
+ 'devices.health.loadShort': 'Load',
+ 'devices.health.load_one': 'Load · {{count}} core',
+ 'devices.health.load_other': 'Load · {{count}} cores',
+ 'devices.health.empty':
+ 'No health data yet. It starts recording once this device runs the latest LobeHub desktop app or CLI.',
+ 'devices.health.memory': 'Memory',
+ 'devices.health.now': 'Now',
+ 'devices.health.status.missing': 'No data — asleep, off, or LobeHub not running',
+ 'devices.health.status.offline': 'Running but disconnected',
+ 'devices.health.status.online': 'Online',
+ 'devices.health.status.pending': 'Not uploaded yet',
+ 'devices.health.title': 'Health · last 12 hours',
'devices.lastSeen': 'Last connected {{time}}',
'devices.remove.confirm': 'Remove this device?',
'devices.remove.confirmDesc':
diff --git a/packages/types/src/deviceMetric.test.ts b/packages/types/src/deviceMetric.test.ts
new file mode 100644
index 00000000000..38db7e58ca8
--- /dev/null
+++ b/packages/types/src/deviceMetric.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from 'vitest';
+
+import { bucketDeviceMetrics, type DeviceMetricSample } from './deviceMetric';
+
+const MIN = 60_000;
+const sample = (
+ observedAt: number,
+ patch: Partial<DeviceMetricSample> = {},
+): DeviceMetricSample => ({
+ connected: true,
+ cpuCount: 8,
+ cpuPercent: 20,
+ load1: 2,
+ load15: 1,
+ load5: 1.5,
+ memoryTotalBytes: 16_000,
+ memoryUsedBytes: 8000,
+ observedAt,
+ ...patch,
+});
+
+describe('bucketDeviceMetrics', () => {
+ it('averages each bucket, marks buckets with a disconnected sample, and leaves gaps empty', () => {
+ const points = bucketDeviceMetrics(
+ [
+ sample(9 * MIN, { cpuPercent: 10 }),
+ sample(6 * MIN, { connected: false, cpuPercent: 30 }),
+ sample(21 * MIN, { cpuPercent: 80, load1: null, memoryUsedBytes: 12_000 }),
+ sample(99 * MIN), // outside the window
+ ],
+ { bucketMs: 5 * MIN, from: 0, to: 60 * MIN },
+ );
+
+ expect(points).toEqual([
+ {
+ connected: false,
+ cpuPercent: 20,
+ load1: 2,
+ memoryPercent: 50,
+ memoryUsedBytes: 8000,
+ observedAt: 5 * MIN,
+ },
+ {
+ connected: true,
+ cpuPercent: 80,
+ load1: null,
+ memoryPercent: 75,
+ memoryUsedBytes: 12_000,
+ observedAt: 20 * MIN,
+ },
+ ]);
+ });
+});
diff --git a/packages/types/src/deviceMetric.ts b/packages/types/src/deviceMetric.ts
new file mode 100644
index 00000000000..215a87a670b
--- /dev/null
+++ b/packages/types/src/deviceMetric.ts
@@ -0,0 +1,110 @@
+import { z } from 'zod';
+
+// ============================================
+// Device metrics — machine health samples (CPU / memory / load average)
+// ============================================
+
+/** How often a device takes one sample. One sample averages CPU over this window. */
+export const DEVICE_METRIC_SAMPLE_INTERVAL_MS = 60_000;
+
+/** The window the device page charts. */
+export const DEVICE_METRIC_VIEW_WINDOW_MS = 12 * 60 * 60 * 1000;
+
+/**
+ * How long samples are kept, both on the device (backlog awaiting upload) and
+ * in the device gateway, which is the only place they are stored. Longer than
+ * the view window so a machine that was offline overnight can still upload
+ * the stretch it spent disconnected.
+ */
+export const DEVICE_METRIC_RETENTION_MS = 2 * 24 * 60 * 60 * 1000;
+
+/** Samples per `device_metrics` socket frame (the gateway caps a frame at this many). */
+export const DEVICE_METRIC_MAX_BATCH = 500;
+
+/**
+ * One machine health sample as reported by a device.
+ *
+ * `connected` records whether the device held a live gateway connection when
+ * the sample was taken. Samples are buffered on the device and uploaded later,
+ * so a stretch of `connected: false` samples means "the machine was running
+ * but could not reach LobeHub", while a stretch with no samples at all means
+ * the machine (or the LobeHub process on it) was not running.
+ */
+export const deviceMetricSampleSchema = z.object({
+ connected: z.boolean(),
+ 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(),
+ /** 1 / 5 / 15 minute load averages; null on platforms without them (Windows). */
+ load1: z.number().min(0).nullable(),
+ load5: z.number().min(0).nullable(),
+ load15: z.number().min(0).nullable(),
+ memoryTotalBytes: z.number().int().min(0),
+ memoryUsedBytes: z.number().int().min(0),
+ /** Epoch milliseconds, taken on the device. */
+ observedAt: z.number().int().min(0),
+});
+
+export type DeviceMetricSample = z.infer<typeof deviceMetricSampleSchema>;
+
+/** One charted point — a sample, or the average of the samples in one bucket. */
+export interface DeviceMetricPoint {
+ /** False when any sample in the bucket was taken while disconnected. */
+ connected: boolean;
+ cpuPercent: number | null;
+ load1: number | null;
+ memoryPercent: number | null;
+ memoryUsedBytes: number | null;
+ /** Epoch milliseconds — bucket start when bucketed. */
+ observedAt: number;
+}
+
+export interface DeviceMetricSeries {
+ /** Bucket width the points were aggregated into. */
+ bucketMs: number;
+ /** From the newest sample; null when the device never reported. */
+ cpuCount: 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);
+ return present.length === 0 ? null : present.reduce((a, b) => a + b, 0) / present.length;
+};
+
+/**
+ * Average raw samples into `bucketMs`-wide buckets over `[from, to]`,
+ * ascending. Buckets with no samples are absent — the gap IS the signal (the
+ * machine, or LobeHub on it, was not running).
+ */
+export const bucketDeviceMetrics = (
+ samples: DeviceMetricSample[],
+ { bucketMs, from, to }: { bucketMs: number; from: number; to: number },
+): DeviceMetricPoint[] => {
+ const buckets = new Map<number, DeviceMetricSample[]>();
+ for (const sample of samples) {
+ if (sample.observedAt < from || sample.observedAt > to) continue;
+ const start = Math.floor(sample.observedAt / bucketMs) * bucketMs;
+ const bucket = buckets.get(start) ?? [];
+ bucket.push(sample);
+ buckets.set(start, bucket);
+ }
+
+ return [...buckets.entries()]
+ .sort(([a], [b]) => a - b)
+ .map(([observedAt, group]) => ({
+ connected: group.every((s) => s.connected),
+ cpuPercent: average(group.map((s) => s.cpuPercent)),
+ load1: average(group.map((s) => s.load1)),
+ memoryPercent: average(
+ group.map((s) =>
+ s.memoryTotalBytes > 0 ? (s.memoryUsedBytes * 100) / s.memoryTotalBytes : null,
+ ),
+ ),
+ memoryUsedBytes: average(group.map((s) => s.memoryUsedBytes)),
+ observedAt,
+ }));
+};
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index b3101b788f4..802ca3523a6 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -15,6 +15,7 @@ export * from './clientDB';
export * from './conversation';
export * from './creds';
export * from './device';
+export * from './deviceMetric';
export * from './discover';
export * from './document';
export * from './documentComment';
diff --git a/src/features/DeviceManager/AgentRuntimes/index.tsx b/src/features/DeviceManager/AgentRuntimes/index.tsx
new file mode 100644
index 00000000000..e542fb61a51
--- /dev/null
+++ b/src/features/DeviceManager/AgentRuntimes/index.tsx
@@ -0,0 +1,99 @@
+'use client';
+
+import type { DeviceListItem } from '@lobechat/types';
+import { Flexbox } from '@lobehub/ui';
+import { Button, Tag, Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { useTranslation } from 'react-i18next';
+
+import { CONNECTABLE_PROVIDERS } from '@/features/ConnectAgent/providers';
+import { useClientDataSWR } from '@/libs/swr';
+import { deviceService } from '@/services/device';
+
+import FieldLabel from '../FieldLabel';
+import { partitionScan } from './partitionScan';
+
+const styles = createStaticStyles(({ css }) => ({
+ row: css`
+ padding-block: 8px;
+ padding-inline: 10px;
+ border-radius: ${cssVar.borderRadius};
+ background: ${cssVar.colorFillQuaternary};
+ `,
+}));
+
+/**
+ * The agent runtimes installed on the device (Claude Code, Codex, …), probed
+ * live over the device connection. Only an online device can answer, so an
+ * offline one says so instead of showing a stale or empty list.
+ */
+const AgentRuntimes = ({ device }: { device: DeviceListItem }) => {
+ const { t } = useTranslation('setting');
+ const online = (device.channels ?? []).length > 0;
+
+ const { data, error, isLoading, isValidating, mutate } = useClientDataSWR(
+ online ? ['device/agentScan', device.deviceId] : null,
+ () => deviceService.scanAgents({ deviceId: device.deviceId }),
+ { revalidateOnFocus: false },
+ );
+
+ if (!online) {
+ return (
+ <Text fontSize={12} type={'secondary'}>
+ {t('devices.agents.offline')}
+ </Text>
+ );
+ }
+
+ if (isLoading) {
+ return (
+ <Text fontSize={12} type={'secondary'}>
+ {t('devices.agents.scanning')}
+ </Text>
+ );
+ }
+
+ const failure = error?.message ?? data?.error;
+ const rescan = (
+ <Button loading={isValidating} size={'small'} onClick={() => mutate()}>
+ {t('devices.agents.rescan')}
+ </Button>
+ );
+
+ if (failure || !data) {
+ return (
+ <Flexbox gap={8}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('devices.agents.error', { error: failure ?? '' })}
+ </Text>
+ <Flexbox horizontal>{rescan}</Flexbox>
+ </Flexbox>
+ );
+ }
+
+ // Only what is installed for now; the not-found list read as noise.
+ const { installed } = partitionScan(data.agents, CONNECTABLE_PROVIDERS);
+
+ return (
+ <Flexbox gap={8}>
+ <FieldLabel extra={rescan}>{t('devices.agents.installed')}</FieldLabel>
+ {installed.length === 0 ? (
+ <Text fontSize={12} type={'secondary'}>
+ {t('devices.agents.empty')}
+ </Text>
+ ) : (
+ installed.map(({ provider, version }) => (
+ <Flexbox horizontal align={'center'} className={styles.row} gap={10} key={provider.type}>
+ <provider.brand.Avatar size={24} />
+ <Text ellipsis style={{ flex: 1, minWidth: 0 }} weight={500}>
+ {provider.title}
+ </Text>
+ {version && <Tag size={'small'}>{version}</Tag>}
+ </Flexbox>
+ ))
+ )}
+ </Flexbox>
+ );
+};
+
+export default AgentRuntimes;
diff --git a/src/features/DeviceManager/AgentRuntimes/partitionScan.test.ts b/src/features/DeviceManager/AgentRuntimes/partitionScan.test.ts
new file mode 100644
index 00000000000..a17627dfe6a
--- /dev/null
+++ b/src/features/DeviceManager/AgentRuntimes/partitionScan.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest';
+
+import { partitionScan } from './partitionScan';
+
+describe('partitionScan', () => {
+ const providers = [{ type: 'claude-code' }, { type: 'codex' }, { type: 'kimi-code' }];
+
+ it('keeps display order, carries versions, and skips unprobed types', () => {
+ const result = partitionScan(
+ {
+ 'claude-code': { available: true, version: '2.1.0' },
+ 'codex': { available: false, reason: 'not found' },
+ } as any,
+ providers,
+ );
+
+ expect(result).toEqual({
+ installed: [{ provider: { type: 'claude-code' }, version: '2.1.0' }],
+ missing: [{ type: 'codex' }],
+ });
+ });
+});
diff --git a/src/features/DeviceManager/AgentRuntimes/partitionScan.ts b/src/features/DeviceManager/AgentRuntimes/partitionScan.ts
new file mode 100644
index 00000000000..10c3b488fe2
--- /dev/null
+++ b/src/features/DeviceManager/AgentRuntimes/partitionScan.ts
@@ -0,0 +1,26 @@
+import type { HeterogeneousAgentScanMap } from '@lobechat/heterogeneous-agents';
+
+export interface ScannedAgent<P> {
+ provider: P;
+ version?: string;
+}
+
+/**
+ * Split a device scan into what is installed (with its version) and what was
+ * probed but not found, in the providers' display order. Types the device did
+ * not probe at all (older clients) are left out rather than shown as missing.
+ */
+export const partitionScan = <P extends { type: string }>(
+ scan: HeterogeneousAgentScanMap,
+ providers: P[],
+): { installed: ScannedAgent<P>[]; missing: P[] } => {
+ const installed: ScannedAgent<P>[] = [];
+ const missing: P[] = [];
+ for (const provider of providers) {
+ const status = scan[provider.type as keyof HeterogeneousAgentScanMap];
+ if (!status) continue;
+ if (status.available) installed.push({ provider, version: status.version });
+ else missing.push(provider);
+ }
+ return { installed, missing };
+};
diff --git a/src/features/DeviceManager/DeviceDetailPanel.tsx b/src/features/DeviceManager/DeviceDetailPanel.tsx
index 3fec5ed3b9a..36a5c32fe23 100644
--- a/src/features/DeviceManager/DeviceDetailPanel.tsx
+++ b/src/features/DeviceManager/DeviceDetailPanel.tsx
@@ -3,7 +3,16 @@
import { isDesktop } from '@lobechat/const';
import type { DeviceListItem, DeviceWorkspaceShare } from '@lobechat/types';
import { Flexbox, Icon, Input, SortableList } from '@lobehub/ui';
-import { ActionIcon, Avatar, Button, confirmModal, Tag, Text, toast } from '@lobehub/ui/base-ui';
+import {
+ ActionIcon,
+ Avatar,
+ Button,
+ confirmModal,
+ Tabs,
+ Tag,
+ Text,
+ toast,
+} from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
import { FolderOpenIcon, FolderPlusIcon, LockIcon, XIcon } from 'lucide-react';
import { memo, useState } from 'react';
@@ -16,8 +25,10 @@ import { deviceService } from '@/services/device';
import { electronSystemService } from '@/services/electron/system';
import { nextWorkingDirs } from '@/store/device';
+import AgentRuntimes from './AgentRuntimes';
import Connections from './Connections';
import { refreshDeviceList } from './const';
+import DeviceHealth, { HealthLegend } from './DeviceHealth';
import FieldLabel from './FieldLabel';
import { getDeviceIcon } from './getDeviceIcon';
import PresenceDot from './PresenceDot';
@@ -76,8 +87,15 @@ const styles = createStaticStyles(({ css }) => ({
padding-block: 8px;
padding-inline: 8px;
`,
+ tabs: css`
+ flex: none;
+ padding-block: 8px 0;
+ padding-inline: 14px;
+ `,
}));
+type DetailTab = 'agents' | 'files' | 'overview';
+
interface DeviceDetailPanelProps {
device: DeviceListItem;
isCurrent?: boolean;
@@ -87,6 +105,9 @@ interface DeviceDetailPanelProps {
const DeviceDetailPanel = memo<DeviceDetailPanelProps>(({ device, isCurrent, onClose }) => {
const { t } = useTranslation(['setting', 'device']);
const canEdit = useCanEditDevice()(device);
+ // Health monitoring and the directory settings are separate jobs; a tab each
+ // keeps the charts from pushing the directories below the fold.
+ const [tab, setTab] = useState<DetailTab>('overview');
const [name, setName] = useState(device.friendlyName ?? '');
const [cwd, setCwd] = useState(device.defaultCwd ?? '');
@@ -253,6 +274,19 @@ const DeviceDetailPanel = memo<DeviceDetailPanelProps>(({ device, isCurrent, onC
<ActionIcon icon={XIcon} size={'small'} onClick={onClose} />
</Flexbox>
+ <Tabs
+ activeKey={tab}
+ className={styles.tabs}
+ size={'small'}
+ variant={'square'}
+ items={[
+ { key: 'overview', label: t('devices.detail.tabs.overview') },
+ { key: 'files', label: t('devices.detail.tabs.files') },
+ { key: 'agents', label: t('devices.detail.tabs.agents') },
+ ]}
+ onChange={(key) => setTab(key as DetailTab)}
+ />
+
<Flexbox className={styles.body} gap={20}>
{/* Visible hint when the caller can't mutate the row — explains why the
fields below are read-only without the user needing to try and hit a
@@ -267,154 +301,174 @@ const DeviceDetailPanel = memo<DeviceDetailPanelProps>(({ device, isCurrent, onC
</Flexbox>
)}
- {/* ─── Enrolled by (workspace only) ─── */}
- {device.scope === 'workspace' && device.enroller && (
- <Flexbox gap={8}>
- <FieldLabel>{t('workspaceSetting.devices.enrolledByLabel')}</FieldLabel>
- <Flexbox horizontal align={'center'} gap={8}>
- <Avatar avatar={device.enroller.avatar ?? undefined} size={24} />
- <Text>
- {device.enroller.fullName ||
- device.enroller.username ||
- t('workspaceSetting.devices.unknownEnroller')}
- </Text>
- </Flexbox>
- </Flexbox>
- )}
-
- {/* ─── Shared to workspaces (personal only) ─── */}
- {device.scope === 'personal' && !!device.sharedWorkspaces?.length && (
- <Flexbox gap={8}>
- <FieldLabel>{t('devices.share.detailLabel')}</FieldLabel>
- {device.sharedWorkspaces.map((share) => (
- <Flexbox horizontal align={'center'} gap={8} key={share.workspaceId}>
- <Text ellipsis style={{ flex: 1, minWidth: 0 }}>
- {share.workspaceName ?? share.workspaceId}
- </Text>
- <Tag size={'small'}>
- {share.visibility === 'private'
- ? t('devices.share.visibilityTag.private')
- : t('devices.share.visibilityTag.public')}
- </Tag>
- <ActionIcon
- icon={XIcon}
- size={'small'}
- title={t('devices.share.revoke')}
- onClick={() => handleRevokeShare(share)}
- />
+ {tab === 'overview' && (
+ <>
+ {/* ─── Enrolled by (workspace only) ─── */}
+ {device.scope === 'workspace' && device.enroller && (
+ <Flexbox gap={8}>
+ <FieldLabel>{t('workspaceSetting.devices.enrolledByLabel')}</FieldLabel>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Avatar avatar={device.enroller.avatar ?? undefined} size={24} />
+ <Text>
+ {device.enroller.fullName ||
+ device.enroller.username ||
+ t('workspaceSetting.devices.unknownEnroller')}
+ </Text>
+ </Flexbox>
</Flexbox>
- ))}
- </Flexbox>
- )}
+ )}
+
+ {/* ─── Shared to workspaces (personal only) ─── */}
+ {device.scope === 'personal' && !!device.sharedWorkspaces?.length && (
+ <Flexbox gap={8}>
+ <FieldLabel>{t('devices.share.detailLabel')}</FieldLabel>
+ {device.sharedWorkspaces.map((share) => (
+ <Flexbox horizontal align={'center'} gap={8} key={share.workspaceId}>
+ <Text ellipsis style={{ flex: 1, minWidth: 0 }}>
+ {share.workspaceName ?? share.workspaceId}
+ </Text>
+ <Tag size={'small'}>
+ {share.visibility === 'private'
+ ? t('devices.share.visibilityTag.private')
+ : t('devices.share.visibilityTag.public')}
+ </Tag>
+ <ActionIcon
+ icon={XIcon}
+ size={'small'}
+ title={t('devices.share.revoke')}
+ onClick={() => handleRevokeShare(share)}
+ />
+ </Flexbox>
+ ))}
+ </Flexbox>
+ )}
- {/* ─── Connections, each with its client version; desktop carries the update ─── */}
- <Connections canEdit={canEdit} device={device} />
-
- {/* ─── Name ─── */}
- <Flexbox gap={8}>
- <FieldLabel>{t('devices.edit.friendlyName')}</FieldLabel>
- {canEdit ? (
- <Input
- placeholder={t('devices.edit.friendlyNamePlaceholder')}
- value={name}
- onBlur={commitName}
- onChange={(e) => setName(e.target.value)}
- onPressEnter={commitName}
- />
- ) : device.friendlyName ? (
- // Read-only: render the canonical value (not the local draft), so a
- // value the caller can't actually commit never bleeds through.
- <Text>{device.friendlyName}</Text>
- ) : (
- <Text type={'secondary'}>—</Text>
- )}
- </Flexbox>
+ {/* ─── Connections, each with its client version; desktop carries the update ─── */}
+ <Connections canEdit={canEdit} device={device} />
- {/* ─── Default working directory ─── */}
- <Flexbox gap={8}>
- <FieldLabel>{t('devices.edit.defaultCwd')}</FieldLabel>
- {canEdit ? (
- <Flexbox horizontal gap={8}>
- <Input
- placeholder={t('devices.edit.defaultCwdPlaceholder')}
- value={cwd}
- onBlur={handleCwdBlur}
- onChange={(e) => setCwd(e.target.value)}
- onPressEnter={handleCwdBlur}
- />
- {canBrowse && (
- <Button icon={<Icon icon={FolderOpenIcon} />} onClick={handleBrowse}>
- {t('devices.edit.browse')}
- </Button>
- )}
+ {/* ─── Machine health ─── */}
+ <Flexbox gap={8}>
+ <FieldLabel extra={<HealthLegend />}>{t('devices.health.title')}</FieldLabel>
+ <DeviceHealth deviceId={device.deviceId} />
</Flexbox>
- ) : device.defaultCwd ? (
- // Code font only when there's an actual path to read; empty falls back
- // to the same dash style as Name so the two fields look consistent.
- <Text className={styles.path}>{device.defaultCwd}</Text>
- ) : (
- <Text type={'secondary'}>—</Text>
- )}
- </Flexbox>
- {/* ─── Recent directories ─── */}
- <Flexbox gap={8}>
- <FieldLabel
- extra={
- canEdit && (
- <ActionIcon
- icon={FolderPlusIcon}
- size={'small'}
- title={t('devices.detail.addDir')}
- onClick={handleAddRecent}
+ {/* ─── Name ─── */}
+ <Flexbox gap={8}>
+ <FieldLabel>{t('devices.edit.friendlyName')}</FieldLabel>
+ {canEdit ? (
+ <Input
+ placeholder={t('devices.edit.friendlyNamePlaceholder')}
+ value={name}
+ onBlur={commitName}
+ onChange={(e) => setName(e.target.value)}
+ onPressEnter={commitName}
/>
- )
- }
- >
- {t('devices.detail.recentDirs')}
- </FieldLabel>
- {device.workingDirs.length === 0 ? (
- <Text fontSize={12} type={'secondary'}>
- {t('devices.detail.noRecent')}
- </Text>
- ) : canEdit ? (
- <SortableList
- items={device.workingDirs.map((d) => ({ id: d.path, repoType: d.repoType }))}
- renderItem={(item: { id: string; repoType?: 'git' | 'github' }) => (
- <SortableList.Item className={styles.recentItem} id={item.id} variant={'filled'}>
- <SortableList.DragHandle />
- <DirIcon repoType={item.repoType} />
- <Text className={styles.path} title={item.id}>
- {item.id}
- </Text>
- <ActionIcon
- icon={XIcon}
- size={'small'}
- onClick={() => handleRemoveRecent(item.id)}
+ ) : device.friendlyName ? (
+ // Read-only: render the canonical value (not the local draft), so a
+ // value the caller can't actually commit never bleeds through.
+ <Text>{device.friendlyName}</Text>
+ ) : (
+ <Text type={'secondary'}>—</Text>
+ )}
+ </Flexbox>
+ </>
+ )}
+
+ {tab === 'agents' && <AgentRuntimes device={device} />}
+
+ {tab === 'files' && (
+ <>
+ {/* ─── Default working directory ─── */}
+ <Flexbox gap={8}>
+ <FieldLabel>{t('devices.edit.defaultCwd')}</FieldLabel>
+ {canEdit ? (
+ <Flexbox horizontal gap={8}>
+ <Input
+ placeholder={t('devices.edit.defaultCwdPlaceholder')}
+ value={cwd}
+ onBlur={handleCwdBlur}
+ onChange={(e) => setCwd(e.target.value)}
+ onPressEnter={handleCwdBlur}
/>
- </SortableList.Item>
+ {canBrowse && (
+ <Button icon={<Icon icon={FolderOpenIcon} />} onClick={handleBrowse}>
+ {t('devices.edit.browse')}
+ </Button>
+ )}
+ </Flexbox>
+ ) : device.defaultCwd ? (
+ // Code font only when there's an actual path to read; empty falls back
+ // to the same dash style as Name so the two fields look consistent.
+ <Text className={styles.path}>{device.defaultCwd}</Text>
+ ) : (
+ <Text type={'secondary'}>—</Text>
)}
- onChange={handleReorderRecent}
- />
- ) : (
- // Read-only listing: same row layout minus the drag handle and the
- // remove button. Keeps the path + repo type icon visible for context.
- device.workingDirs.map((d) => (
- <Flexbox
- horizontal
- align={'center'}
- className={styles.recentItem}
- gap={8}
- key={d.path}
+ </Flexbox>
+
+ {/* ─── Recent directories ─── */}
+ <Flexbox gap={8}>
+ <FieldLabel
+ extra={
+ canEdit && (
+ <ActionIcon
+ icon={FolderPlusIcon}
+ size={'small'}
+ title={t('devices.detail.addDir')}
+ onClick={handleAddRecent}
+ />
+ )
+ }
>
- <DirIcon repoType={d.repoType} />
- <Text className={styles.path} title={d.path}>
- {d.path}
+ {t('devices.detail.recentDirs')}
+ </FieldLabel>
+ {device.workingDirs.length === 0 ? (
+ <Text fontSize={12} type={'secondary'}>
+ {t('devices.detail.noRecent')}
</Text>
- </Flexbox>
- ))
- )}
- </Flexbox>
+ ) : canEdit ? (
+ <SortableList
+ items={device.workingDirs.map((d) => ({ id: d.path, repoType: d.repoType }))}
+ renderItem={(item: { id: string; repoType?: 'git' | 'github' }) => (
+ <SortableList.Item
+ className={styles.recentItem}
+ id={item.id}
+ variant={'filled'}
+ >
+ <SortableList.DragHandle />
+ <DirIcon repoType={item.repoType} />
+ <Text className={styles.path} title={item.id}>
+ {item.id}
+ </Text>
+ <ActionIcon
+ icon={XIcon}
+ size={'small'}
+ onClick={() => handleRemoveRecent(item.id)}
+ />
+ </SortableList.Item>
+ )}
+ onChange={handleReorderRecent}
+ />
+ ) : (
+ // Read-only listing: same row layout minus the drag handle and the
+ // remove button. Keeps the path + repo type icon visible for context.
+ device.workingDirs.map((d) => (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.recentItem}
+ gap={8}
+ key={d.path}
+ >
+ <DirIcon repoType={d.repoType} />
+ <Text className={styles.path} title={d.path}>
+ {d.path}
+ </Text>
+ </Flexbox>
+ ))
+ )}
+ </Flexbox>
+ </>
+ )}
</Flexbox>
</Flexbox>
);
diff --git a/src/features/DeviceManager/DeviceHealth/Preview.tsx b/src/features/DeviceManager/DeviceHealth/Preview.tsx
new file mode 100644
index 00000000000..cc44dbde7bf
--- /dev/null
+++ b/src/features/DeviceManager/DeviceHealth/Preview.tsx
@@ -0,0 +1,66 @@
+'use client';
+
+import { Tracker } from '@lobehub/charts';
+import { Flexbox } from '@lobehub/ui';
+import { Text } from '@lobehub/ui/base-ui';
+import { useTranslation } from 'react-i18next';
+
+import { buildHealthTimeline, groupStripBlocks } from './buildHealthTimeline';
+import { formatPercent, usageLevel } from './format';
+import { blockColor, usageTextColor, useBlockTooltip, useDeviceMetricSeries } from './shared';
+
+/** Half-hour blocks: 24 across the 12-hour window, enough to spot a drop at a glance. */
+const PREVIEW_BLOCK_MS = 30 * 60_000;
+const PREVIEW_WIDTH = 168;
+
+/**
+ * At-a-glance health for a device-list row, before the detail panel is
+ * opened: a mini status strip plus the latest CPU / memory / load, each
+ * colored by how loaded it is. Renders nothing for a device that never
+ * reported.
+ */
+const DeviceHealthPreview = ({ active, deviceId }: { active: boolean; deviceId: string }) => {
+ const { t } = useTranslation('setting');
+ const { data } = useDeviceMetricSeries(deviceId, active);
+ const blockTooltip = useBlockTooltip();
+
+ if (!data || data.points.length === 0) return null;
+
+ const timeline = buildHealthTimeline(data);
+ const blocks = groupStripBlocks(
+ timeline.slots,
+ data.bucketMs,
+ Math.max(data.bucketMs, PREVIEW_BLOCK_MS),
+ );
+ const readings = [
+ { label: t('devices.health.cpu'), value: timeline.latest?.cpuPercent },
+ { label: t('devices.health.memory'), value: timeline.latest?.memoryPercent },
+ { label: t('devices.health.loadShort'), value: timeline.latest?.loadPercent },
+ ];
+
+ return (
+ <Flexbox gap={4} style={{ flex: 'none', width: PREVIEW_WIDTH }}>
+ <Tracker
+ blockGap={1}
+ blockHeight={10}
+ blockWidth={'100%'}
+ width={'100%'}
+ data={blocks.map((block) => ({
+ color: blockColor(block),
+ key: block.start,
+ tooltip: blockTooltip(block),
+ }))}
+ />
+ <Flexbox horizontal distribution={'space-between'}>
+ {readings.map(({ label, value }) => (
+ <Text fontSize={11} key={label} type={'secondary'}>
+ {label}{' '}
+ <span style={{ color: usageTextColor(usageLevel(value)) }}>{formatPercent(value)}</span>
+ </Text>
+ ))}
+ </Flexbox>
+ </Flexbox>
+ );
+};
+
+export default DeviceHealthPreview;
diff --git a/src/features/DeviceManager/DeviceHealth/buildHealthTimeline.test.ts b/src/features/DeviceManager/DeviceHealth/buildHealthTimeline.test.ts
new file mode 100644
index 00000000000..344b5cee984
--- /dev/null
+++ b/src/features/DeviceManager/DeviceHealth/buildHealthTimeline.test.ts
@@ -0,0 +1,123 @@
+import type { DeviceMetricPoint } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { buildHealthTimeline, groupStripBlocks, type HealthSlot } from './buildHealthTimeline';
+
+const MIN = 60_000;
+const BUCKET = 5 * MIN;
+const to = 1000 * BUCKET;
+const from = to - 12 * BUCKET;
+
+const point = (bucketsAgo: number, patch: Partial<DeviceMetricPoint> = {}): DeviceMetricPoint => ({
+ connected: true,
+ cpuPercent: 10,
+ load1: 1,
+ memoryPercent: 50,
+ memoryUsedBytes: 100,
+ observedAt: to - bucketsAgo * BUCKET,
+ ...patch,
+});
+
+const build = (points: DeviceMetricPoint[], cpuCount: number | null = 8) =>
+ buildHealthTimeline({ bucketMs: BUCKET, cpuCount, from, memoryTotalBytes: 200, points, to });
+
+describe('buildHealthTimeline', () => {
+ it('lays out one slot per bucket across the window', () => {
+ const { slots } = build([]);
+
+ expect(slots).toHaveLength(13);
+ expect(slots[0].start).toBe(from);
+ expect(slots.at(-1)!.start).toBe(to);
+ });
+
+ it('separates running-but-disconnected from no data', () => {
+ const { slots } = build([
+ point(12),
+ point(11, { connected: false }),
+ // 10 … 7 buckets ago: no samples
+ point(6),
+ point(3),
+ ]);
+
+ const statusAt = (bucketsAgo: number) =>
+ slots.find((s) => s.start === to - bucketsAgo * BUCKET)!.status;
+ expect(statusAt(11)).toBe('offline');
+ expect(statusAt(9)).toBe('missing');
+ expect(statusAt(6)).toBe('online');
+ });
+
+ it('does not call the not-yet-uploaded tail missing', () => {
+ const { slots } = build([point(12), point(3)]);
+
+ expect(slots.slice(-3).map((s) => s.status)).toEqual(['pending', 'pending', 'pending']);
+ });
+
+ 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.loadCeiling).toBe(150);
+ expect(build([point(3, { load1: 2 })]).loadCeiling).toBe(100);
+ });
+});
+
+describe('groupStripBlocks', () => {
+ const slot = (
+ i: number,
+ status: HealthSlot['status'],
+ usage: Partial<HealthSlot> = {},
+ ): HealthSlot => ({
+ cpuPercent: null,
+ loadPercent: null,
+ memoryPercent: null,
+ memoryUsedBytes: null,
+ start: i * BUCKET,
+ status,
+ ...usage,
+ });
+
+ it('keeps a disconnect visible and reads partial running as running', () => {
+ const blocks = groupStripBlocks(
+ [
+ slot(0, 'missing'),
+ slot(1, 'online'),
+ slot(2, 'online'),
+ slot(3, 'online'),
+ slot(4, 'offline'),
+ slot(5, 'online'),
+ slot(6, 'missing'),
+ slot(7, 'pending'),
+ ],
+ BUCKET,
+ 3 * BUCKET,
+ );
+
+ expect(blocks.map(({ end, start, status }) => ({ end, start, status }))).toEqual([
+ { end: 3 * BUCKET, start: 0, status: 'online' },
+ { end: 6 * BUCKET, start: 3 * BUCKET, status: 'offline' },
+ { end: 8 * BUCKET, start: 6 * BUCKET, status: 'pending' },
+ ]);
+ });
+
+ 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);
+
+ expect(blocks.map(({ end, start }) => ({ end, start }))).toEqual([
+ { end: 2 * BUCKET, start: BUCKET },
+ { end: 4 * BUCKET, start: 2 * BUCKET },
+ ]);
+ });
+
+ it('carries the highest reading of each metric in the block', () => {
+ const [block] = groupStripBlocks(
+ [
+ slot(0, 'online', { cpuPercent: 40, loadPercent: 95, memoryPercent: 60 }),
+ slot(1, 'online', { cpuPercent: 80, memoryPercent: 55 }),
+ ],
+ BUCKET,
+ 2 * BUCKET,
+ );
+
+ expect(block.peak).toEqual({ cpuPercent: 80, loadPercent: 95, memoryPercent: 60 });
+ });
+});
diff --git a/src/features/DeviceManager/DeviceHealth/buildHealthTimeline.ts b/src/features/DeviceManager/DeviceHealth/buildHealthTimeline.ts
new file mode 100644
index 00000000000..e55f0f619ec
--- /dev/null
+++ b/src/features/DeviceManager/DeviceHealth/buildHealthTimeline.ts
@@ -0,0 +1,139 @@
+import type { DeviceMetricPoint, DeviceMetricSeries } from '@lobechat/types';
+
+/**
+ * What the device was doing during one bucket:
+ * - `online` — running and connected to LobeHub.
+ * - `offline` — running (it took samples) but not connected: a network or
+ * gateway problem rather than a machine problem.
+ * - `missing` — no samples: the machine was asleep / off, or LobeHub was not
+ * running on it.
+ * - `pending` — the most recent buckets, whose samples may simply not have
+ * been uploaded yet.
+ */
+export type HealthSlotStatus = 'online' | 'offline' | 'missing' | 'pending';
+
+/** CPU / memory / load, each as a percentage (load relative to the core count). */
+export interface HealthUsage {
+ cpuPercent: number | null;
+ loadPercent: number | null;
+ memoryPercent: number | null;
+}
+
+export interface HealthSlot extends HealthUsage {
+ memoryUsedBytes: number | null;
+ start: number;
+ status: HealthSlotStatus;
+}
+
+export interface HealthTimeline {
+ /** Newest reading of each metric, for the chart headers and the row preview. */
+ latest: HealthUsage | null;
+ /** Upper bound for the load chart — at least 100%, so an overloaded machine still fits. */
+ loadCeiling: number;
+ slots: HealthSlot[];
+}
+
+/**
+ * Devices upload every few minutes, so the tail of the window is expected to
+ * be empty for a while; only call it missing once it is older than this.
+ */
+export const UPLOAD_GRACE_MS = 10 * 60_000;
+
+/** Load average as a share of the machine's cores; null without both. */
+export const loadPercentOf = (load1: number | null | undefined, cpuCount: number | null) =>
+ load1 === null || load1 === undefined || !cpuCount ? null : (load1 / cpuCount) * 100;
+
+export const buildHealthTimeline = (series: DeviceMetricSeries): HealthTimeline => {
+ const { bucketMs, cpuCount, from, points, to } = series;
+ const byStart = new Map(points.map((p) => [p.observedAt, p]));
+ const firstStart = Math.floor(from / bucketMs) * bucketMs;
+
+ const slots: HealthSlot[] = [];
+ for (let start = firstStart; start <= to; start += bucketMs) {
+ const point = byStart.get(start);
+ const status: HealthSlotStatus = point
+ ? point.connected
+ ? 'online'
+ : 'offline'
+ : start + bucketMs > to - UPLOAD_GRACE_MS
+ ? 'pending'
+ : 'missing';
+ slots.push({
+ cpuPercent: point?.cpuPercent ?? null,
+ loadPercent: loadPercentOf(point?.load1, cpuCount),
+ memoryPercent: point?.memoryPercent ?? null,
+ memoryUsedBytes: point?.memoryUsedBytes ?? null,
+ start,
+ status,
+ });
+ }
+
+ const newest: DeviceMetricPoint | undefined = points.at(-1);
+ const maxLoad = Math.max(0, ...slots.map((s) => s.loadPercent ?? 0));
+
+ return {
+ latest: newest
+ ? {
+ cpuPercent: newest.cpuPercent,
+ loadPercent: loadPercentOf(newest.load1, cpuCount),
+ memoryPercent: newest.memoryPercent,
+ }
+ : null,
+ loadCeiling: Math.max(100, Math.ceil(maxLoad)),
+ slots,
+ };
+};
+
+export interface HealthStripBlock {
+ end: number;
+ /** Highest CPU / memory / load inside the block — what its color reflects. */
+ peak: HealthUsage;
+ start: number;
+ status: HealthSlotStatus;
+}
+
+/** Most to least telling when slots of different kinds share one block. */
+const STRIP_PRIORITY: HealthSlotStatus[] = ['offline', 'online', 'pending', 'missing'];
+
+const maxOf = (values: (number | null)[]) => {
+ const present = values.filter((v): v is number => v !== null);
+ return present.length === 0 ? null : Math.max(...present);
+};
+
+/**
+ * Merge consecutive slots into blocks wide enough to see and hover — a 12h
+ * window of 5-minute slots is 144 hair-thin blocks in a side panel. Blocks
+ * sit on wall-clock boundaries (e.g. :00 / :30) so their hover times read
+ * naturally. A block takes its most telling slot status: a disconnect
+ * anywhere in it shows, and a block where the device ran for part of the time
+ * reads as running.
+ */
+export const groupStripBlocks = (
+ slots: HealthSlot[],
+ bucketMs: number,
+ blockMs: number,
+): HealthStripBlock[] => {
+ const groups = new Map<number, HealthSlot[]>();
+ for (const slot of slots) {
+ const key = Math.floor(slot.start / blockMs) * blockMs;
+ const group = groups.get(key) ?? [];
+ group.push(slot);
+ groups.set(key, group);
+ }
+
+ return [...groups.values()].map((group) => {
+ const status =
+ STRIP_PRIORITY.find((candidate) => group.some((slot) => slot.status === candidate)) ??
+ 'missing';
+ return {
+ end: group.at(-1)!.start + bucketMs,
+ peak: {
+ cpuPercent: maxOf(group.map((s) => s.cpuPercent)),
+ loadPercent: maxOf(group.map((s) => s.loadPercent)),
+ memoryPercent: maxOf(group.map((s) => s.memoryPercent)),
+ },
+ start: group[0].start,
+ status,
+ };
+ });
+};
diff --git a/src/features/DeviceManager/DeviceHealth/format.test.ts b/src/features/DeviceManager/DeviceHealth/format.test.ts
new file mode 100644
index 00000000000..94d15d2db6e
--- /dev/null
+++ b/src/features/DeviceManager/DeviceHealth/format.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from 'vitest';
+
+import { formatPercent, peakUsageLevel, usageLevel } from './format';
+
+describe('device health formatters', () => {
+ // The chart calls its formatter for every slot, including slots with no
+ // samples — a null value used to crash the whole settings page.
+ it('render a gap slot as a dash', () => {
+ expect(formatPercent(null)).toBe('—');
+ expect(formatPercent(undefined)).toBe('—');
+ });
+
+ it('format present values', () => {
+ expect(formatPercent(41.6)).toBe('42%');
+ });
+});
+
+describe('usage levels', () => {
+ it('turns yellow from 70% and red from 90%', () => {
+ expect(usageLevel(69.9)).toBe('normal');
+ expect(usageLevel(70)).toBe('high');
+ expect(usageLevel(89.9)).toBe('high');
+ expect(usageLevel(90)).toBe('critical');
+ expect(usageLevel(null)).toBeUndefined();
+ });
+
+ it('rates a block by its busiest metric', () => {
+ expect(peakUsageLevel(40, 55, 93)).toBe('critical');
+ expect(peakUsageLevel(null, 72, undefined)).toBe('high');
+ expect(peakUsageLevel(null, undefined)).toBeUndefined();
+ });
+});
diff --git a/src/features/DeviceManager/DeviceHealth/format.ts b/src/features/DeviceManager/DeviceHealth/format.ts
new file mode 100644
index 00000000000..bfa4d75d7f9
--- /dev/null
+++ b/src/features/DeviceManager/DeviceHealth/format.ts
@@ -0,0 +1,24 @@
+/** A slot with no samples charts as a gap; formatters must accept it. */
+type ChartValue = number | null | undefined;
+
+export const formatPercent = (value: ChartValue) =>
+ value === null || value === undefined ? '—' : `${Math.round(value)}%`;
+
+/** How loaded a machine is: yellow from 70%, red from 90%. */
+export type UsageLevel = 'normal' | 'high' | 'critical';
+
+export const HIGH_USAGE_PERCENT = 70;
+export const CRITICAL_USAGE_PERCENT = 90;
+
+export const usageLevel = (value: ChartValue): UsageLevel | undefined => {
+ if (value === null || value === undefined) return undefined;
+ if (value >= CRITICAL_USAGE_PERCENT) return 'critical';
+ if (value >= HIGH_USAGE_PERCENT) 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));
+};
diff --git a/src/features/DeviceManager/DeviceHealth/index.tsx b/src/features/DeviceManager/DeviceHealth/index.tsx
new file mode 100644
index 00000000000..320c16e88e4
--- /dev/null
+++ b/src/features/DeviceManager/DeviceHealth/index.tsx
@@ -0,0 +1,165 @@
+'use client';
+
+import { AreaChart, Tracker } from '@lobehub/charts';
+import { Flexbox } from '@lobehub/ui';
+import { Button, Text } from '@lobehub/ui/base-ui';
+import { useTranslation } from 'react-i18next';
+
+import { formatSize } from '@/utils/format';
+
+import { buildHealthTimeline, groupStripBlocks, type HealthSlot } from './buildHealthTimeline';
+import { formatPercent, usageLevel } from './format';
+import {
+ blockColor,
+ formatClock as time,
+ usageTextColor,
+ useBlockTooltip,
+ useDeviceMetricSeries,
+} from './shared';
+import { healthViewState } from './viewState';
+
+export { HealthLegend } from './shared';
+
+/** Status-strip block width: wide enough to see and hover in the side panel. */
+const STRIP_BLOCK_MS = 15 * 60_000;
+
+interface MetricChartProps {
+ ceiling: number;
+ data: { time: string; value: number | null }[];
+ label: string;
+ latest: number | null | undefined;
+}
+
+/** Left: what is measured (with its size); right: the latest share, colored by level. */
+const MetricChart = ({ ceiling, data, label, latest }: 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}>
+ {formatPercent(latest)}
+ </Text>
+ </Flexbox>
+ <AreaChart
+ startEndOnly
+ categories={['value']}
+ customCategories={{ value: label }}
+ data={data}
+ height={72}
+ index={'time'}
+ showLegend={false}
+ showYAxis={false}
+ valueFormatter={formatPercent}
+ yAxisDomain={[0, ceiling]}
+ />
+ </Flexbox>
+);
+
+/**
+ * The machine's CPU / memory / load over the recent window, with a status
+ * strip colored by how loaded the machine was and telling apart "running but
+ * disconnected" from "not running at all" — what a user needs to explain why
+ * a device dropped.
+ */
+const DeviceHealth = ({ deviceId }: { deviceId: string }) => {
+ const { t } = useTranslation('setting');
+ const { data, error, isValidating, mutate } = useDeviceMetricSeries(deviceId);
+ const blockTooltip = useBlockTooltip();
+
+ const view = healthViewState({ data, error });
+
+ // A failed read (gateway down or not yet upgraded) must not look like loading.
+ if (view === 'error') {
+ return (
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('devices.health.error')}
+ </Text>
+ <Button loading={isValidating} size={'small'} onClick={() => mutate()}>
+ {t('devices.health.retry')}
+ </Button>
+ </Flexbox>
+ );
+ }
+
+ if (view === 'loading' || !data) {
+ return (
+ <Text fontSize={12} type={'secondary'}>
+ {t('devices.health.loading')}
+ </Text>
+ );
+ }
+
+ if (view === 'empty') {
+ return (
+ <Text fontSize={12} type={'secondary'}>
+ {t('devices.health.empty')}
+ </Text>
+ );
+ }
+
+ const timeline = buildHealthTimeline(data);
+ const rows = (pick: (slot: HealthSlot) => number | null) =>
+ timeline.slots.map((slot) => ({ time: time(slot.start), value: pick(slot) }));
+ const cores = data.cpuCount ?? 1;
+
+ return (
+ <Flexbox gap={16}>
+ <Flexbox gap={6}>
+ {/* Blocks flex to an equal share of the panel — the default fixed
+ 12px overflowed and clipped the newest hours. */}
+ <Tracker
+ blockGap={2}
+ blockHeight={16}
+ blockWidth={'100%'}
+ width={'100%'}
+ data={groupStripBlocks(
+ timeline.slots,
+ data.bucketMs,
+ Math.max(data.bucketMs, STRIP_BLOCK_MS),
+ ).map((block) => ({
+ color: blockColor(block),
+ key: block.start,
+ tooltip: blockTooltip(block),
+ }))}
+ />
+ <Flexbox horizontal distribution={'space-between'}>
+ <Text fontSize={11} type={'secondary'}>
+ {time(data.from)}
+ </Text>
+ <Text fontSize={11} type={'secondary'}>
+ {t('devices.health.now')}
+ </Text>
+ </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) && (
+ <MetricChart
+ ceiling={timeline.loadCeiling}
+ data={rows((slot) => slot.loadPercent)}
+ label={t('devices.health.load', { count: cores })}
+ latest={timeline.latest?.loadPercent}
+ />
+ )}
+ </Flexbox>
+ );
+};
+
+export default DeviceHealth;
diff --git a/src/features/DeviceManager/DeviceHealth/shared.tsx b/src/features/DeviceManager/DeviceHealth/shared.tsx
new file mode 100644
index 00000000000..2717b791d34
--- /dev/null
+++ b/src/features/DeviceManager/DeviceHealth/shared.tsx
@@ -0,0 +1,110 @@
+import type { DeviceMetricSeries } from '@lobechat/types';
+import { Flexbox } from '@lobehub/ui';
+import { Text } from '@lobehub/ui/base-ui';
+import { cssVar } from 'antd-style';
+import dayjs from 'dayjs';
+import { useTranslation } from 'react-i18next';
+
+import { useClientDataSWR } from '@/libs/swr';
+import { deviceService } from '@/services/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. `enabled: false`
+ * (an off-screen row) stops fetching; cached data comes back when it is on
+ * screen again.
+ */
+export const useDeviceMetricSeries = (deviceId: string, enabled = true) =>
+ useClientDataSWR<DeviceMetricSeries>(
+ enabled ? [DEVICE_METRICS_SWR_KEY, deviceId] : null,
+ () => deviceService.getMetricSeries(deviceId),
+ { refreshInterval: REFRESH_INTERVAL_MS },
+ );
+
+export const USAGE_COLOR: Record<UsageLevel, string> = {
+ critical: cssVar.colorError,
+ high: cssVar.colorWarning,
+ normal: cssVar.colorSuccess,
+};
+
+/**
+ * Non-running states stay grey so green / yellow / red keep meaning how loaded
+ * a running machine is: a disconnect is a bright grey (the machine was still
+ * running), no data a faint one.
+ */
+const STATUS_COLOR: Record<Exclude<HealthSlotStatus, 'online'>, string> = {
+ missing: cssVar.colorFillTertiary,
+ offline: cssVar.colorTextQuaternary,
+ pending: cssVar.colorFillQuaternary,
+};
+
+export const blockColor = (block: HealthStripBlock) =>
+ block.status === 'online'
+ ? USAGE_COLOR[
+ peakUsageLevel(block.peak.cpuPercent, block.peak.memoryPercent, block.peak.loadPercent) ??
+ 'normal'
+ ]
+ : STATUS_COLOR[block.status];
+
+/** Text color for a reading — the same green / yellow / red as the strip; no reading keeps the default. */
+export const usageTextColor = (level: UsageLevel | undefined) =>
+ level ? USAGE_COLOR[level] : undefined;
+
+export const formatClock = (ms: number) => dayjs(ms).format('HH:mm');
+
+export const useStatusLabels = (): Record<HealthSlotStatus, string> => {
+ const { t } = useTranslation('setting');
+ return {
+ missing: t('devices.health.status.missing'),
+ offline: t('devices.health.status.offline'),
+ online: t('devices.health.status.online'),
+ pending: t('devices.health.status.pending'),
+ };
+};
+
+/** Hover text for one strip block: its time span, state, and peak readings while running. */
+export const useBlockTooltip = () => {
+ const { t } = useTranslation('setting');
+ const statusLabel = useStatusLabels();
+ return (block: HealthStripBlock) => {
+ const head = `${formatClock(block.start)}–${formatClock(block.end)} · ${statusLabel[block.status]}`;
+ if (block.status !== 'online' && block.status !== 'offline') return head;
+ return `${head} · ${t('devices.health.cpu')} ${formatPercent(block.peak.cpuPercent)} · ${t(
+ 'devices.health.memory',
+ )} ${formatPercent(block.peak.memoryPercent)} · ${t('devices.health.loadShort')} ${formatPercent(
+ block.peak.loadPercent,
+ )}`;
+ };
+};
+
+const LEGEND: { color: string; key: string }[] = [
+ { color: USAGE_COLOR.normal, key: 'devices.health.level.normal' },
+ { color: USAGE_COLOR.high, key: 'devices.health.level.high' },
+ { color: USAGE_COLOR.critical, key: 'devices.health.level.critical' },
+ { color: STATUS_COLOR.offline, key: 'devices.health.level.offline' },
+ { color: STATUS_COLOR.missing, key: 'devices.health.level.missing' },
+];
+
+/** One-line key for the strip colors — replaces the old per-period text list. */
+export const HealthLegend = () => {
+ const { t } = useTranslation('setting');
+ return (
+ <Flexbox horizontal align={'center'} gap={8}>
+ {LEGEND.map(({ color, key }) => (
+ <Flexbox horizontal align={'center'} gap={4} key={key}>
+ <span style={{ background: color, borderRadius: 2, height: 8, width: 8 }} />
+ <Text fontSize={11} type={'secondary'}>
+ {t(key as 'devices.health.level.normal')}
+ </Text>
+ </Flexbox>
+ ))}
+ </Flexbox>
+ );
+};
diff --git a/src/features/DeviceManager/DeviceHealth/viewState.test.ts b/src/features/DeviceManager/DeviceHealth/viewState.test.ts
new file mode 100644
index 00000000000..b90887f173e
--- /dev/null
+++ b/src/features/DeviceManager/DeviceHealth/viewState.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from 'vitest';
+
+import { healthViewState } from './viewState';
+
+const series = (points: number) =>
+ ({
+ bucketMs: 1,
+ cpuCount: 1,
+ from: 0,
+ memoryTotalBytes: 1,
+ points: Array.from({ length: points }, (_, i) => ({ observedAt: i })),
+ to: 1,
+ }) as any;
+
+describe('healthViewState', () => {
+ // A rejected read used to render nothing forever — indistinguishable from loading.
+ it('surfaces a failed read as an error, not as loading', () => {
+ expect(healthViewState({ error: new Error('gateway down') })).toBe('error');
+ expect(healthViewState({})).toBe('loading');
+ });
+
+ it('keeps showing cached data when a refresh fails', () => {
+ expect(healthViewState({ data: series(3), error: new Error('x') })).toBe('ready');
+ });
+
+ it('tells a device that never reported apart from one with data', () => {
+ expect(healthViewState({ data: series(0) })).toBe('empty');
+ });
+});
diff --git a/src/features/DeviceManager/DeviceHealth/viewState.ts b/src/features/DeviceManager/DeviceHealth/viewState.ts
new file mode 100644
index 00000000000..9d0c0727817
--- /dev/null
+++ b/src/features/DeviceManager/DeviceHealth/viewState.ts
@@ -0,0 +1,19 @@
+import type { DeviceMetricSeries } from '@lobechat/types';
+
+export type HealthViewState = 'empty' | 'error' | 'loading' | 'ready';
+
+/**
+ * What the health section should show. A failed read with nothing cached is
+ * an error to surface (with a retry), never an endless blank "loading"; once
+ * data exists, a later failed refresh keeps showing it.
+ */
+export const healthViewState = ({
+ data,
+ error,
+}: {
+ data?: DeviceMetricSeries;
+ error?: unknown;
+}): HealthViewState => {
+ if (!data) return error ? 'error' : 'loading';
+ return data.points.length === 0 ? 'empty' : 'ready';
+};
diff --git a/src/features/DeviceManager/DeviceItem.tsx b/src/features/DeviceManager/DeviceItem.tsx
index cdc0db9b369..a7413fe686a 100644
--- a/src/features/DeviceManager/DeviceItem.tsx
+++ b/src/features/DeviceManager/DeviceItem.tsx
@@ -3,6 +3,7 @@
import type { DeviceListItem } from '@lobechat/types';
import { DropdownMenu, Flexbox, Icon, Tooltip } from '@lobehub/ui';
import { Avatar, Button, confirmModal, Tag, Text } from '@lobehub/ui/base-ui';
+import { useInViewport } from 'ahooks';
import { createStaticStyles, cssVar, cx } from 'antd-style';
import dayjs from 'dayjs';
import {
@@ -14,7 +15,7 @@ import {
Trash2Icon,
TriangleAlertIcon,
} from 'lucide-react';
-import { memo } from 'react';
+import { memo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import VisibilityConfirmContent from '@/features/VisibilityConfirmContent';
@@ -23,6 +24,7 @@ import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
import { refreshDeviceList } from './const';
+import DeviceHealthPreview from './DeviceHealth/Preview';
import { getDeviceIcon } from './getDeviceIcon';
import { openShareDeviceModal } from './ShareDeviceModal';
import { useCanEditDevice } from './useCanEditDevice';
@@ -117,249 +119,260 @@ interface DeviceItemProps {
isCurrent?: boolean;
onSelect: () => void;
selected?: boolean;
+ /** At-a-glance health strip; hidden while a detail panel is open. */
+ showHealthPreview?: boolean;
}
-const DeviceItem = memo<DeviceItemProps>(({ device, isCurrent, onSelect, selected }) => {
- const { t } = useTranslation('setting');
- const { t: tCommon } = useTranslation('common');
- const canEdit = useCanEditDevice()(device);
- const currentUserId = useUserStore(userProfileSelectors.userId);
+const DeviceItem = memo<DeviceItemProps>(
+ ({ device, isCurrent, onSelect, selected, showHealthPreview }) => {
+ // Rows are not virtualized; only rows on screen keep their health preview polling.
+ const rowRef = useRef<HTMLDivElement>(null);
+ const [inViewport] = useInViewport(rowRef);
+ const { t } = useTranslation('setting');
+ const { t: tCommon } = useTranslation('common');
+ const canEdit = useCanEditDevice()(device);
+ const currentUserId = useUserStore(userProfileSelectors.userId);
- // Workspace devices are self-or-owner-gated + workspace-scoped on the
- // server; personal devices stay userId-scoped. Route by the device's own
- // scope.
- const onRemoveSuccess = () => refreshDeviceList();
- const removePersonal = lambdaQuery.device.removeDevice.useMutation({
- onSuccess: onRemoveSuccess,
- });
- const removeWorkspace = lambdaQuery.device.removeWorkspaceDevice.useMutation({
- onSuccess: onRemoveSuccess,
- });
- const removeDevice = device.scope === 'workspace' ? removeWorkspace : removePersonal;
-
- const displayName = device.friendlyName || device.hostname || device.deviceId;
- const isFallback = device.identitySource === 'fallback';
- // Online when the device has at least one live connection in `device.channels`.
- const channels = device.channels ?? [];
- const online = channels.length > 0;
- // Rendered inline (not as a dot tooltip): "when was this machine last
- // reachable" is the answer needed to pick between rows, and hover can't
- // answer it for a whole list at once — nor at all on touch.
- //
- // Online reads the gateway's live `connectedAt` from `channels[0]` — the
- // newest connection, since the pool is sorted newest-first in
- // `deviceGateway.queryDeviceList`. That is the same channel
- // `sortDevicesByActivity` ranks this row by, so the label always explains
- // the row's position.
- //
- // Offline can only report `lastSeen`, which is stamped on register — and
- // every client registers right before opening its WS
- // (`gatewayConnectionSrv`, CLI `registerDevice`) — so it means "last
- // CONNECTED", not "last active". The copy says exactly that; it becomes a
- // true last-active once a writer stamps liveness.
- const activityText = online
- ? `${t('devices.status.onlineConnections', { count: channels.length })} · ${t(
- 'devices.channel.connected',
- {
- time: dayjs(channels[0]?.connectedAt ?? device.lastSeen).fromNow(),
- },
- )}`
- : t('devices.lastSeen', { time: dayjs(device.lastSeen).fromNow() });
+ // Workspace devices are self-or-owner-gated + workspace-scoped on the
+ // server; personal devices stay userId-scoped. Route by the device's own
+ // scope.
+ const onRemoveSuccess = () => refreshDeviceList();
+ const removePersonal = lambdaQuery.device.removeDevice.useMutation({
+ onSuccess: onRemoveSuccess,
+ });
+ const removeWorkspace = lambdaQuery.device.removeWorkspaceDevice.useMutation({
+ onSuccess: onRemoveSuccess,
+ });
+ const removeDevice = device.scope === 'workspace' ? removeWorkspace : removePersonal;
- // Publish / make-private for workspace enrollments. Reuses the
- // shared visibility-confirm body so the consequences copy matches agents /
- // files. Success feedback is the row itself moving to the other tab after
- // the list refresh.
- const setVisibility = lambdaQuery.device.setWorkspaceDeviceVisibility.useMutation({
- onSuccess: () => refreshDeviceList(),
- });
+ const displayName = device.friendlyName || device.hostname || device.deviceId;
+ const isFallback = device.identitySource === 'fallback';
+ // Online when the device has at least one live connection in `device.channels`.
+ const channels = device.channels ?? [];
+ const online = channels.length > 0;
+ // Rendered inline (not as a dot tooltip): "when was this machine last
+ // reachable" is the answer needed to pick between rows, and hover can't
+ // answer it for a whole list at once — nor at all on touch.
+ //
+ // Online reads the gateway's live `connectedAt` from `channels[0]` — the
+ // newest connection, since the pool is sorted newest-first in
+ // `deviceGateway.queryDeviceList`. That is the same channel
+ // `sortDevicesByActivity` ranks this row by, so the label always explains
+ // the row's position.
+ //
+ // Offline can only report `lastSeen`, which is stamped on register — and
+ // every client registers right before opening its WS
+ // (`gatewayConnectionSrv`, CLI `registerDevice`) — so it means "last
+ // CONNECTED", not "last active". The copy says exactly that; it becomes a
+ // true last-active once a writer stamps liveness.
+ const activityText = online
+ ? `${t('devices.status.onlineConnections', { count: channels.length })} · ${t(
+ 'devices.channel.connected',
+ {
+ time: dayjs(channels[0]?.connectedAt ?? device.lastSeen).fromNow(),
+ },
+ )}`
+ : t('devices.lastSeen', { time: dayjs(device.lastSeen).fromNow() });
- const handlePublish = () =>
- confirmModal({
- content: <VisibilityConfirmContent variant={'publish'} />,
- okText: t('devices.visibility.publish'),
- onOk: async () => {
- await setVisibility.mutateAsync({ deviceId: device.deviceId, visibility: 'public' });
- },
- title: t('devices.visibility.publishConfirmTitle'),
+ // Publish / make-private for workspace enrollments. Reuses the
+ // shared visibility-confirm body so the consequences copy matches agents /
+ // files. Success feedback is the row itself moving to the other tab after
+ // the list refresh.
+ const setVisibility = lambdaQuery.device.setWorkspaceDeviceVisibility.useMutation({
+ onSuccess: () => refreshDeviceList(),
});
- const handleMakePrivate = () =>
- confirmModal({
- content: <VisibilityConfirmContent variant={'makePrivate'} />,
- okButtonProps: { danger: true },
- okText: tCommon('makePrivate.confirm.ok'),
- onOk: async () => {
- await setVisibility.mutateAsync({ deviceId: device.deviceId, visibility: 'private' });
- },
- title: tCommon('makePrivate.confirm.title'),
- });
+ const handlePublish = () =>
+ confirmModal({
+ content: <VisibilityConfirmContent variant={'publish'} />,
+ okText: t('devices.visibility.publish'),
+ onOk: async () => {
+ await setVisibility.mutateAsync({ deviceId: device.deviceId, visibility: 'public' });
+ },
+ title: t('devices.visibility.publishConfirmTitle'),
+ });
- // Only persisted workspace rows carry a visibility to toggle — ghosts
- // (unregistered) and personal devices don't. The toggle is enroller-only
- //: an owner demoting another member's public device would
- // move it into that member's private list, appropriating their data. The
- // server rejects non-enroller writes as the backstop.
- const isEnroller = !!currentUserId && device.enroller?.userId === currentUserId;
- const visibilityItems =
- device.scope === 'workspace' && device.registered && isEnroller
- ? device.visibility === 'private'
+ const handleMakePrivate = () =>
+ confirmModal({
+ content: <VisibilityConfirmContent variant={'makePrivate'} />,
+ okButtonProps: { danger: true },
+ okText: tCommon('makePrivate.confirm.ok'),
+ onOk: async () => {
+ await setVisibility.mutateAsync({ deviceId: device.deviceId, visibility: 'private' });
+ },
+ title: tCommon('makePrivate.confirm.title'),
+ });
+
+ // Only persisted workspace rows carry a visibility to toggle — ghosts
+ // (unregistered) and personal devices don't. The toggle is enroller-only
+ //: an owner demoting another member's public device would
+ // move it into that member's private list, appropriating their data. The
+ // server rejects non-enroller writes as the backstop.
+ const isEnroller = !!currentUserId && device.enroller?.userId === currentUserId;
+ const visibilityItems =
+ device.scope === 'workspace' && device.registered && isEnroller
+ ? device.visibility === 'private'
+ ? [
+ {
+ icon: <Icon icon={GlobeIcon} />,
+ key: 'publish',
+ label: t('devices.visibility.publish'),
+ onClick: handlePublish,
+ },
+ ]
+ : [
+ {
+ icon: <Icon icon={EyeOffIcon} />,
+ key: 'makePrivate',
+ label: tCommon('makePrivate'),
+ onClick: handleMakePrivate,
+ },
+ ]
+ : [];
+
+ // Share-to-workspace entry for personal enrollments. The share
+ // handshake needs a live connection to mint the workspace identity, so the
+ // item stays disabled (with an explanatory desc) while the device is offline.
+ const shareItems =
+ device.scope === 'personal' && device.registered
? [
{
- icon: <Icon icon={GlobeIcon} />,
- key: 'publish',
- label: t('devices.visibility.publish'),
- onClick: handlePublish,
- },
- ]
- : [
- {
- icon: <Icon icon={EyeOffIcon} />,
- key: 'makePrivate',
- label: tCommon('makePrivate'),
- onClick: handleMakePrivate,
+ desc: online ? undefined : t('devices.share.offlineDesc'),
+ disabled: !online,
+ icon: <Icon icon={Share2Icon} />,
+ key: 'share',
+ label: t('devices.share.menu'),
+ onClick: () => openShareDeviceModal(device),
},
]
- : [];
+ : [];
- // Share-to-workspace entry for personal enrollments. The share
- // handshake needs a live connection to mint the workspace identity, so the
- // item stays disabled (with an explanatory desc) while the device is offline.
- const shareItems =
- device.scope === 'personal' && device.registered
- ? [
- {
- desc: online ? undefined : t('devices.share.offlineDesc'),
- disabled: !online,
- icon: <Icon icon={Share2Icon} />,
- key: 'share',
- label: t('devices.share.menu'),
- onClick: () => openShareDeviceModal(device),
- },
- ]
- : [];
+ const handleRemove = () =>
+ confirmModal({
+ content: isCurrent
+ ? `${t('devices.remove.confirmDesc')}\n\n${t('devices.remove.currentSessionWarning')}`
+ : t('devices.remove.confirmDesc'),
+ okButtonProps: { danger: true },
+ okText: t('devices.actions.remove'),
+ onOk: async () => {
+ await removeDevice.mutateAsync({ deviceId: device.deviceId });
+ },
+ title: t('devices.remove.confirm'),
+ });
- const handleRemove = () =>
- confirmModal({
- content: isCurrent
- ? `${t('devices.remove.confirmDesc')}\n\n${t('devices.remove.currentSessionWarning')}`
- : t('devices.remove.confirmDesc'),
- okButtonProps: { danger: true },
- okText: t('devices.actions.remove'),
- onOk: async () => {
- await removeDevice.mutateAsync({ deviceId: device.deviceId });
- },
- title: t('devices.remove.confirm'),
- });
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ aria-pressed={selected}
+ className={cx(styles.row, selected && styles.rowActive)}
+ gap={16}
+ ref={rowRef}
+ role={'button'}
+ tabIndex={0}
+ onClick={onSelect}
+ onKeyDown={(e) => {
+ // Mirror native button keyboard semantics for the div-as-button row.
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ onSelect();
+ }
+ }}
+ >
+ <div className={styles.iconTile}>{getDeviceIcon(device.platform, 20)}</div>
- return (
- <Flexbox
- horizontal
- align={'center'}
- aria-pressed={selected}
- className={cx(styles.row, selected && styles.rowActive)}
- gap={16}
- role={'button'}
- tabIndex={0}
- onClick={onSelect}
- onKeyDown={(e) => {
- // Mirror native button keyboard semantics for the div-as-button row.
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- onSelect();
- }
- }}
- >
- <div className={styles.iconTile}>{getDeviceIcon(device.platform, 20)}</div>
+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text ellipsis fontSize={15} weight={500}>
+ {displayName}
+ </Text>
+ <span className={online ? styles.statusOnline : styles.statusOffline} />
+ {isCurrent && <Tag>{t('devices.currentBadge')}</Tag>}
+ {device.scope === 'workspace' && device.sharedFromPersonal && (
+ // Member-shared machine (vs directly enrolled infra) — mirrors the
+ // "Shared by {name}" tag on workspace connectors/credentials.
+ <Tag>
+ {t('devices.share.sharedByTag', {
+ name:
+ device.enroller?.fullName ||
+ device.enroller?.username ||
+ t('workspaceSetting.devices.unknownEnroller'),
+ })}
+ </Tag>
+ )}
+ {device.scope === 'personal' && !!device.sharedWorkspaces?.length && (
+ // At-a-glance "this machine also lives in N workspaces" marker;
+ // the per-workspace list (and revoke) sits in the detail panel.
+ <Tag>{t('devices.share.badge', { count: device.sharedWorkspaces.length })}</Tag>
+ )}
+ {isFallback && (
+ <Tooltip title={t('devices.fallbackTooltip')}>
+ <Tag icon={<Icon icon={TriangleAlertIcon} />}>{t('devices.fallbackBadge')}</Tag>
+ </Tooltip>
+ )}
+ </Flexbox>
+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
+ <Text className={styles.activity} type={'secondary'}>
+ {activityText}
+ </Text>
+ {device.defaultCwd && (
+ <>
+ <span className={styles.metaDivider} />
+ <Icon icon={FolderIcon} size={12} style={{ color: cssVar.colorTextQuaternary }} />
+ <Text className={styles.cwd} type={'secondary'}>
+ {device.defaultCwd}
+ </Text>
+ </>
+ )}
+ </Flexbox>
+ </Flexbox>
- <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
- <Flexbox horizontal align={'center'} gap={8}>
- <Text ellipsis fontSize={15} weight={500}>
- {displayName}
- </Text>
- <span className={online ? styles.statusOnline : styles.statusOffline} />
- {isCurrent && <Tag>{t('devices.currentBadge')}</Tag>}
- {device.scope === 'workspace' && device.sharedFromPersonal && (
- // Member-shared machine (vs directly enrolled infra) — mirrors the
- // "Shared by {name}" tag on workspace connectors/credentials.
- <Tag>
- {t('devices.share.sharedByTag', {
+ <Flexbox horizontal align={'center'} gap={8} style={{ flex: 'none' }}>
+ {showHealthPreview && (
+ <DeviceHealthPreview active={!!inViewport} deviceId={device.deviceId} />
+ )}
+ {device.scope === 'workspace' && device.enroller && (
+ // Enroller avatar — the at-a-glance "who put this here" answer for
+ // shared workspace pools. Hidden in personal scope (always the
+ // caller) and for ghost rows (no row yet).
+ <Tooltip
+ title={t('workspaceSetting.devices.enrolledBy', {
name:
- device.enroller?.fullName ||
- device.enroller?.username ||
+ device.enroller.fullName ||
+ device.enroller.username ||
t('workspaceSetting.devices.unknownEnroller'),
})}
- </Tag>
- )}
- {device.scope === 'personal' && !!device.sharedWorkspaces?.length && (
- // At-a-glance "this machine also lives in N workspaces" marker;
- // the per-workspace list (and revoke) sits in the detail panel.
- <Tag>{t('devices.share.badge', { count: device.sharedWorkspaces.length })}</Tag>
- )}
- {isFallback && (
- <Tooltip title={t('devices.fallbackTooltip')}>
- <Tag icon={<Icon icon={TriangleAlertIcon} />}>{t('devices.fallbackBadge')}</Tag>
+ >
+ <span onClick={(e) => e.stopPropagation()}>
+ <Avatar avatar={device.enroller.avatar ?? undefined} size={20} />
+ </span>
</Tooltip>
)}
- </Flexbox>
- <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
- <Text className={styles.activity} type={'secondary'}>
- {activityText}
- </Text>
- {device.defaultCwd && (
- <>
- <span className={styles.metaDivider} />
- <Icon icon={FolderIcon} size={12} style={{ color: cssVar.colorTextQuaternary }} />
- <Text className={styles.cwd} type={'secondary'}>
- {device.defaultCwd}
- </Text>
- </>
- )}
- </Flexbox>
- </Flexbox>
-
- <Flexbox horizontal align={'center'} gap={8} style={{ flex: 'none' }}>
- {device.scope === 'workspace' && device.enroller && (
- // Enroller avatar — the at-a-glance "who put this here" answer for
- // shared workspace pools. Hidden in personal scope (always the
- // caller) and for ghost rows (no row yet).
- <Tooltip
- title={t('workspaceSetting.devices.enrolledBy', {
- name:
- device.enroller.fullName ||
- device.enroller.username ||
- t('workspaceSetting.devices.unknownEnroller'),
- })}
- >
+ {canEdit && (
<span onClick={(e) => e.stopPropagation()}>
- <Avatar avatar={device.enroller.avatar ?? undefined} size={20} />
+ <DropdownMenu
+ placement={'bottomRight'}
+ items={[
+ ...visibilityItems,
+ ...shareItems,
+ {
+ danger: true,
+ icon: <Icon icon={Trash2Icon} />,
+ key: 'remove',
+ label: t('devices.actions.remove'),
+ onClick: handleRemove,
+ },
+ ]}
+ >
+ <Button icon={MoreHorizontalIcon} />
+ </DropdownMenu>
</span>
- </Tooltip>
- )}
- {canEdit && (
- <span onClick={(e) => e.stopPropagation()}>
- <DropdownMenu
- placement={'bottomRight'}
- items={[
- ...visibilityItems,
- ...shareItems,
- {
- danger: true,
- icon: <Icon icon={Trash2Icon} />,
- key: 'remove',
- label: t('devices.actions.remove'),
- onClick: handleRemove,
- },
- ]}
- >
- <Button icon={MoreHorizontalIcon} />
- </DropdownMenu>
- </span>
- )}
+ )}
+ </Flexbox>
</Flexbox>
- </Flexbox>
- );
-});
+ );
+ },
+);
DeviceItem.displayName = 'DeviceItem';
diff --git a/src/features/DeviceManager/DeviceManager.tsx b/src/features/DeviceManager/DeviceManager.tsx
index 809f9e5b32a..1e3e5e15fe9 100644
--- a/src/features/DeviceManager/DeviceManager.tsx
+++ b/src/features/DeviceManager/DeviceManager.tsx
@@ -405,6 +405,9 @@ const DeviceManager = memo<DeviceManagerProps>((props) => {
isCurrent={isCurrent(device.deviceId)}
key={device.deviceId}
selected={device.deviceId === selectedId}
+ // The row preview stands in for the detail panel; once a panel is
+ // open the narrowed rows give that width back to the name.
+ showHealthPreview={!selectedId}
onSelect={() =>
setSelectedId(selectedId === device.deviceId ? undefined : device.deviceId)
}
diff --git a/src/services/device.ts b/src/services/device.ts
index 726c73af916..f6b9d34c0ec 100644
--- a/src/services/device.ts
+++ b/src/services/device.ts
@@ -84,6 +84,11 @@ class DeviceService {
return lambdaClient.device.installAppUpdate.mutate(input);
}
+ /** The device's recent CPU / memory / load history, bucketed for charting. */
+ getMetricSeries(deviceId: string) {
+ return lambdaClient.deviceMetric.getSeries.query({ deviceId });
+ }
+
/** Revoke a link. */
revokeTunnel(input: Parameters<DeviceClient['revokeTunnel']['mutate']>[0]) {
return lambdaClient.device.revokeTunnel.mutate(input);