🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(device): read personal device metrics inside a workspace (#21040)
Rdmclin29832696d427f
diff --git a/apps/server/src/routers/lambda/__tests__/deviceMetric.test.ts b/apps/server/src/routers/lambda/__tests__/deviceMetric.test.tsindex 0a96afacaea..c0e39820e8d 100644--- a/apps/server/src/routers/lambda/__tests__/deviceMetric.test.ts+++ b/apps/server/src/routers/lambda/__tests__/deviceMetric.test.ts@@ -12,7 +12,7 @@ vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {return { wsCompatProcedure: authedProcedure };});-const deviceModel = { findByDeviceId: vi.fn(), findWorkspaceDeviceById: vi.fn() };+const deviceModel = { findPersonalByDeviceId: vi.fn(), findWorkspaceDeviceById: vi.fn() };vi.mock('@/database/models/device', () => ({DeviceModel: vi.fn(function () {return deviceModel;@@ -52,7 +52,7 @@ describe('deviceMetricRouter.getSeries', () => {});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 });+ deviceModel.findPersonalByDeviceId.mockResolvedValue({ id: 'row-1', workspaceId: null });const now = Date.now();queryDeviceMetrics.mockResolvedValue([sample(now - 60_000)]);@@ -71,7 +71,7 @@ describe('deviceMetricRouter.getSeries', () => {});it('does not treat a workspace row as personal', async () => {- deviceModel.findByDeviceId.mockResolvedValue({ id: 'row-ws', workspaceId: 'ws-1' });+ deviceModel.findPersonalByDeviceId.mockResolvedValue(undefined);await expect(personal.getSeries({ deviceId: 'dev-ws' })).rejects.toMatchObject({code: 'NOT_FOUND',@@ -79,8 +79,11 @@ describe('deviceMetricRouter.getSeries', () => {expect(queryDeviceMetrics).not.toHaveBeenCalled();});- it('hides workspace devices the caller cannot see', async () => {+ it('hides workspace devices and personal devices the caller cannot see', async () => {deviceModel.findWorkspaceDeviceById.mockResolvedValue(undefined);+ // `findPersonalByDeviceId` is scoped to the caller, so another user's+ // personal device resolves to nothing as well.+ deviceModel.findPersonalByDeviceId.mockResolvedValue(undefined);await expect(workspace.getSeries({ deviceId: 'private' })).rejects.toMatchObject({code: 'NOT_FOUND',@@ -99,4 +102,40 @@ describe('deviceMetricRouter.getSeries', () => {expect(series.cpuCount).toBeNull();expect(series.points).toEqual([]);});++ it('reads the caller’s own personal device from a workspace under the user principal', async () => {+ deviceModel.findWorkspaceDeviceById.mockResolvedValue(undefined);+ deviceModel.findPersonalByDeviceId.mockResolvedValue({ id: 'row-1', workspaceId: null });+ queryDeviceMetrics.mockResolvedValue([sample(Date.now() - 60_000)]);++ const series = await workspace.getSeries({ deviceId: 'dev-1' });++ expect(deviceModel.findPersonalByDeviceId).toHaveBeenCalledWith('dev-1');+ expect(queryDeviceMetrics).toHaveBeenCalledWith(+ expect.objectContaining({ deviceId: 'dev-1', userId: 'user-1', workspaceId: undefined }),+ );+ expect(series.cpuCount).toBe(8);+ expect(series.points).toHaveLength(1);+ });+ it('reads the personal row of a deviceId shared with a workspace row when scoped personal', async () => {+ deviceModel.findWorkspaceDeviceById.mockResolvedValue({ id: 'row-ws', workspaceId: 'ws-1' });+ deviceModel.findPersonalByDeviceId.mockResolvedValue({ id: 'row-1', workspaceId: null });++ await workspace.getSeries({ deviceId: 'shared', scope: 'personal' });++ expect(deviceModel.findWorkspaceDeviceById).not.toHaveBeenCalled();+ expect(queryDeviceMetrics).toHaveBeenCalledWith(+ expect.objectContaining({ deviceId: 'shared', workspaceId: undefined }),+ );+ });++ it('does not fall back to a personal row when scoped workspace', async () => {+ deviceModel.findWorkspaceDeviceById.mockResolvedValue(undefined);+ deviceModel.findPersonalByDeviceId.mockResolvedValue({ id: 'row-1', workspaceId: null });++ await expect(+ workspace.getSeries({ deviceId: 'shared', scope: 'workspace' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(queryDeviceMetrics).not.toHaveBeenCalled();+ });});diff --git a/apps/server/src/routers/lambda/deviceMetric.ts b/apps/server/src/routers/lambda/deviceMetric.tsindex 952796e37ef..7988d5e3a90 100644--- a/apps/server/src/routers/lambda/deviceMetric.ts+++ b/apps/server/src/routers/lambda/deviceMetric.ts@@ -1,4 +1,4 @@-import type { DeviceMetricSeries } from '@lobechat/types';+import type { DeviceMetricSeries, DeviceScope } from '@lobechat/types';import {bucketDeviceMetrics,DEVICE_METRIC_RETENTION_MS,@@ -24,20 +24,35 @@ const deviceMetricProcedure = wsCompatProcedure.use(serverDatabase).use(async (o/*** 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+ * device route uses: in a workspace the rows the caller can see (public, or+ * its own private enrollment) plus the caller's own personal devices, which+ * `listDevices` surfaces there too; otherwise only the caller's personal* rows. The gateway itself only knows principals, not visibility.+ *+ * Returns the workspace principal the device's metrics live under —+ * `undefined` for a personal device, which reports under the user principal+ * even when it is read from a workspace. A personal and a workspace row can+ * share a deviceId (an explicit `--device-id` on both connections), so the+ * list item's `scope` picks the row; without it the workspace row wins.*/- const assertDeviceVisible = async (deviceId: string) => {- const row = workspaceId- ? await deviceModel.findWorkspaceDeviceById(deviceId)- : await deviceModel.findByDeviceId(deviceId);- if (!row || (!workspaceId && row.workspaceId)) {+ const resolveDevicePrincipal = async (+ deviceId: string,+ scope?: DeviceScope,+ ): Promise<string | undefined> => {+ if (+ workspaceId &&+ scope !== 'personal' &&+ (await deviceModel.findWorkspaceDeviceById(deviceId))+ )+ return workspaceId;++ if (scope === 'workspace' || !(await deviceModel.findPersonalByDeviceId(deviceId))) {throw new TRPCError({ code: 'NOT_FOUND', message: 'Device not found.' });}+ return undefined;};- return opts.next({ ctx: { assertDeviceVisible, userId: ctx.userId, workspaceId } });+ return opts.next({ ctx: { resolveDevicePrincipal, userId: ctx.userId } });});export const deviceMetricRouter = router({@@ -50,6 +65,8 @@ export const deviceMetricRouter = router({.input(z.object({deviceId: z.string().min(1).max(64),+ /** The list item's scope; disambiguates a deviceId shared by both scopes. */+ scope: z.enum(['personal', 'workspace']).optional(),windowMs: z.number().int()@@ -59,7 +76,7 @@ export const deviceMetricRouter = router({}),).query(async ({ ctx, input }): Promise<DeviceMetricSeries> => {- await ctx.assertDeviceVisible(input.deviceId);+ const workspaceId = await ctx.resolveDevicePrincipal(input.deviceId, input.scope);const to = Date.now();const from = to - input.windowMs;const bucketMs = Math.max(@@ -72,7 +89,7 @@ export const deviceMetricRouter = router({deviceId: input.deviceId,since: from,userId: ctx.userId,- workspaceId: ctx.workspaceId,+ workspaceId,});const latest = samples.at(-1);diff --git a/packages/database/src/models/__tests__/device.test.ts b/packages/database/src/models/__tests__/device.test.tsindex 7b89b3ee996..06bff1afa4b 100644--- a/packages/database/src/models/__tests__/device.test.ts+++ b/packages/database/src/models/__tests__/device.test.ts@@ -323,6 +323,22 @@ describe('DeviceModel', () => {expect(ids).toEqual(['w1', 'w2']);});+ it('findPersonalByDeviceId never resolves to a workspace enrollment', async () => {+ await serverDB.insert(devices).values([+ { deviceId: 'both', identitySource: 'machine-id', userId, workspaceId: wsId },+ { deviceId: 'both', identitySource: 'machine-id', userId },+ { deviceId: 'ws-only', identitySource: 'machine-id', userId, workspaceId: wsId },+ { deviceId: 'theirs', identitySource: 'machine-id', userId: otherUserId },+ ]);++ expect(await deviceModel.findPersonalByDeviceId('both')).toMatchObject({+ deviceId: 'both',+ workspaceId: null,+ });+ expect(await deviceModel.findPersonalByDeviceId('ws-only')).toBeUndefined();+ expect(await deviceModel.findPersonalByDeviceId('theirs')).toBeUndefined();+ });+it('queryWorkspaceDevices returns [] without workspace context', async () => {await serverDB.insert(devices)diff --git a/packages/database/src/models/device.ts b/packages/database/src/models/device.tsindex 2d7ed85ecfb..63263c6ab18 100644--- a/packages/database/src/models/device.ts+++ b/packages/database/src/models/device.ts@@ -313,6 +313,21 @@ export class DeviceModel {});};+ /**+ * The caller's PERSONAL row for a deviceId. Unlike `findByDeviceId`, never+ * resolves to a workspace enrollment of the same machine, which may share the+ * deviceId (the personal and workspace unique indexes are partial).+ */+ findPersonalByDeviceId = async (deviceId: string) => {+ return this.db.query.devices.findFirst({+ where: and(+ eq(devices.userId, this.userId),+ eq(devices.deviceId, deviceId),+ isNull(devices.workspaceId),+ ),+ });+ };+update = async (deviceId: string, value: UpdateDeviceParams) => {return this.db.update(devices)diff --git a/src/features/Conversation/WorkingSidebar/Overview/DeviceStatusSection.tsx b/src/features/Conversation/WorkingSidebar/Overview/DeviceStatusSection.tsxindex e02c6abc0c2..14904a4a65d 100644--- a/src/features/Conversation/WorkingSidebar/Overview/DeviceStatusSection.tsx+++ b/src/features/Conversation/WorkingSidebar/Overview/DeviceStatusSection.tsx@@ -94,7 +94,7 @@ const DeviceStatusSection = memo<DeviceStatusSectionProps>(({ active, deviceId }const { t: tCommon } = useTranslation('common');const bound = useBoundDevice(deviceId, active);const device = bound.status === 'ready' ? bound.device : undefined;- const { data, error } = useDeviceMetricSeries(deviceId, active && !!device);+ const { data, error } = useDeviceMetricSeries(deviceId, device?.scope, active && !!device);if (bound.status === 'loading')return (diff --git a/src/features/DeviceManager/DeviceCard.tsx b/src/features/DeviceManager/DeviceCard.tsxindex e3063aec81d..bcba0f8312a 100644--- a/src/features/DeviceManager/DeviceCard.tsx+++ b/src/features/DeviceManager/DeviceCard.tsx@@ -131,7 +131,7 @@ const DeviceCard = memo<DeviceCardProps>(({ device, isCurrent, onOpen }) => {// Cards are not virtualized; only cards on screen keep their usage meters polling.const cardRef = useRef<HTMLDivElement>(null);const [inViewport] = useInViewport(cardRef);- const { data, error } = useDeviceMetricSeries(device.deviceId, !!inViewport);+ const { data, error } = useDeviceMetricSeries(device.deviceId, device.scope, !!inViewport);const { t } = useTranslation('setting');const { t: tCommon } = useTranslation('common');const canEdit = useCanEditDevice()(device);diff --git a/src/features/DeviceManager/DeviceHealth/index.tsx b/src/features/DeviceManager/DeviceHealth/index.tsxindex 312f939e73d..b3ed8f467e2 100644--- a/src/features/DeviceManager/DeviceHealth/index.tsx+++ b/src/features/DeviceManager/DeviceHealth/index.tsx@@ -1,5 +1,6 @@'use client';+import type { DeviceScope } from '@lobechat/types';import { AreaChart, Tracker } from '@lobehub/charts';import { Button, Flexbox, Text } from '@lobehub/ui';import { useTranslation } from 'react-i18next';@@ -65,9 +66,9 @@ const MetricChart = ({ ceiling, data, label, latest }: MetricChartProps) => (* disconnected" from "not running at all" — what a user needs to explain why* a device dropped.*/-const DeviceHealth = ({ deviceId }: { deviceId: string }) => {+const DeviceHealth = ({ deviceId, scope }: { deviceId: string; scope: DeviceScope }) => {const { t } = useTranslation('setting');- const { data, error, isValidating, mutate } = useDeviceMetricSeries(deviceId);+ const { data, error, isValidating, mutate } = useDeviceMetricSeries(deviceId, scope);const blockTooltip = useBlockTooltip();const view = healthViewState({ data, error });diff --git a/src/features/DeviceManager/DeviceHealth/shared.tsx b/src/features/DeviceManager/DeviceHealth/shared.tsxindex 9fb16c9ea05..5ee153ed504 100644--- a/src/features/DeviceManager/DeviceHealth/shared.tsx+++ b/src/features/DeviceManager/DeviceHealth/shared.tsx@@ -1,4 +1,4 @@-import type { DeviceMetricSeries } from '@lobechat/types';+import type { DeviceMetricSeries, DeviceScope } from '@lobechat/types';import { cssVar, Flexbox, Text } from '@lobehub/ui';import dayjs from 'dayjs';import { useTranslation } from 'react-i18next';@@ -15,14 +15,19 @@ 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.+ * the same key, so opening a device reuses the preview's data. `scope` is the+ * list item's, so a deviceId enrolled both personally and in the workspace+ * reads the row it was listed as. `enabled: false` (an off-screen row) stops+ * fetching; cached data comes back when it is on screen again.*/-export const useDeviceMetricSeries = (deviceId: string, enabled = true) =>+export const useDeviceMetricSeries = (+ deviceId: string,+ scope: DeviceScope | undefined,+ enabled = true,+) =>useClientDataSWR<DeviceMetricSeries>(- enabled ? [DEVICE_METRICS_SWR_KEY, deviceId] : null,- () => deviceService.getMetricSeries(deviceId),+ enabled ? [DEVICE_METRICS_SWR_KEY, deviceId, scope] : null,+ () => deviceService.getMetricSeries(deviceId, scope),{ refreshInterval: REFRESH_INTERVAL_MS },);diff --git a/src/features/DeviceManager/DeviceHoverPanel.tsx b/src/features/DeviceManager/DeviceHoverPanel.tsxindex d0969f1965b..8cdac2adb06 100644--- a/src/features/DeviceManager/DeviceHoverPanel.tsx+++ b/src/features/DeviceManager/DeviceHoverPanel.tsx@@ -114,7 +114,7 @@ const DeviceHoverPanel = ({ device }: DeviceHoverPanelProps) => {// The series also carries the specs (cores, memory), so fetch it for offline// devices too; only an online device's last reading is shown as its load.- const { data, error } = useDeviceMetricSeries(device.deviceId);+ const { data, error } = useDeviceMetricSeries(device.deviceId, device.scope);const usage = latestUsageView({ data, error });const summary = buildDeviceHoverSummary(device, data);const { online } = summary;diff --git a/src/features/DeviceManager/DeviceOverview.tsx b/src/features/DeviceManager/DeviceOverview.tsxindex 2459ff840aa..f1f985b50cc 100644--- a/src/features/DeviceManager/DeviceOverview.tsx+++ b/src/features/DeviceManager/DeviceOverview.tsx@@ -238,7 +238,7 @@ interface DeviceOverviewProps {*/const DeviceOverview = ({ canOperate, device }: DeviceOverviewProps) => {const { t } = useTranslation('setting');- const { data, error } = useDeviceMetricSeries(device.deviceId);+ const { data, error } = useDeviceMetricSeries(device.deviceId, device.scope);const usage = latestUsageView({ data, error });const latest = usage.loading ? null : usage.latest;@@ -410,7 +410,7 @@ const DeviceOverview = ({ canOperate, device }: DeviceOverviewProps) => {</div><DetailCard extra={<HealthLegend />} icon={HeartPulseIcon} title={t('devices.health.title')}>- <DeviceHealth deviceId={device.deviceId} />+ <DeviceHealth deviceId={device.deviceId} scope={device.scope} /></DetailCard><DetailCard icon={CableIcon} title={t('devices.detail.connections')}>diff --git a/src/services/device.ts b/src/services/device.tsindex c37f6bd8b87..a6dbbea8d8e 100644--- a/src/services/device.ts+++ b/src/services/device.ts@@ -1,4 +1,9 @@-import type { DeviceBoundAgentItem, DeviceEnroller, DeviceRunningSummary } from '@lobechat/types';+import type {+ DeviceBoundAgentItem,+ DeviceEnroller,+ DeviceRunningSummary,+ DeviceScope,+} from '@lobechat/types';import { lambdaClient } from '@/libs/trpc/client';import { type TopicListItem } from '@/services/topic';@@ -171,8 +176,8 @@ class DeviceService {}/** The device's recent CPU / memory / load history, bucketed for charting. */- getMetricSeries(deviceId: string) {- return lambdaClient.deviceMetric.getSeries.query({ deviceId });+ getMetricSeries(deviceId: string, scope?: DeviceScope) {+ return lambdaClient.deviceMetric.getSeries.query({ deviceId, scope });}/** Revoke a link. */