🤯 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
✨ feat(device): show managed cloud device phases in the device list (#22274)
Neko7de5e3f196d1
diff --git a/apps/server/src/routers/lambda/__tests__/deviceListManagedPhase.test.ts b/apps/server/src/routers/lambda/__tests__/deviceListManagedPhase.test.tsnew file mode 100644index 00000000000..cff08212205--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/deviceListManagedPhase.test.ts@@ -0,0 +1,159 @@+// @vitest-environment node+import { MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { deviceRouter } from '../device';+import { MANAGED_PHASES_TIMEOUT_MS } from '../device/registry';++const mocks = vi.hoisted(() => ({+ isAvailable: vi.fn(),+ listStates: vi.fn(),+ queryDeviceList: vi.fn(),+ queryPersonal: vi.fn(),+ querySharedWorkspaceDevices: vi.fn(),+ queryWorkspaceDevices: vi.fn(),+}));++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn() }));+vi.mock('@/database/models/device', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ DeviceModel: class {+ queryPersonal = mocks.queryPersonal;+ querySharedWorkspaceDevices = mocks.querySharedWorkspaceDevices;+ queryWorkspaceDevices = mocks.queryWorkspaceDevices;+ },+}));+vi.mock('@/database/models/user', () => ({+ UserModel: { findByIds: vi.fn().mockResolvedValue([]) },+}));+vi.mock('@/server/services/deviceGateway', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ deviceGateway: { queryDeviceList: mocks.queryDeviceList },+}));+vi.mock('@/business/server/managedDevice', () => ({+ managedDeviceProvider: {+ isAvailable: mocks.isAvailable,+ listStates: mocks.listStates,+ wake: vi.fn(),+ },+}));++const row = (deviceId: string, identitySource: string, workspaceId: string | null = null) => ({+ architecture: null,+ defaultCwd: null,+ deviceId,+ friendlyName: null,+ hostname: null,+ identitySource,+ lastSeenAt: new Date('2026-01-01T00:00:00.000Z'),+ metadata: null,+ platform: 'linux',+ sharedFromDeviceId: null,+ userId: 'user',+ visibility: 'public',+ workingDirs: [],+ workspaceId,+});++const personalCaller = () => deviceRouter.createCaller({ userId: 'user' } as never);+const workspaceCaller = () =>+ deviceRouter.createCaller({+ userId: 'user',+ workspaceId: 'workspace',+ workspaceRole: 'member',+ } as never);++const phaseOf = (devices: { deviceId: string; managedPhase?: string }[], deviceId: string) =>+ devices.find((device) => device.deviceId === deviceId)?.managedPhase;++describe('device.listDevices managed device phases', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.isAvailable.mockReturnValue(true);+ mocks.queryDeviceList.mockResolvedValue([]);+ mocks.querySharedWorkspaceDevices.mockResolvedValue([]);+ mocks.queryWorkspaceDevices.mockResolvedValue([]);+ });++ it('attaches the provider phase to managed rows only', async () => {+ mocks.queryPersonal.mockResolvedValue([+ row('managed', MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE),+ row('laptop', 'machine-id'),+ ]);+ mocks.listStates.mockResolvedValue({ laptop: 'suspended', managed: 'suspended' });++ const devices = await personalCaller().listDevices();++ expect(phaseOf(devices, 'managed')).toBe('suspended');+ expect(phaseOf(devices, 'laptop')).toBeUndefined();+ expect(mocks.listStates).toHaveBeenCalledTimes(1);+ expect(mocks.listStates).toHaveBeenCalledWith({ userId: 'user' });+ });++ it('asks the provider nothing when no row is managed', async () => {+ mocks.queryPersonal.mockResolvedValue([row('laptop', 'machine-id')]);++ await personalCaller().listDevices();++ expect(mocks.isAvailable).not.toHaveBeenCalled();+ expect(mocks.listStates).not.toHaveBeenCalled();+ });++ it('asks each pool that holds a managed row under its own scope', async () => {+ mocks.queryPersonal.mockResolvedValue([+ row('personal-managed', MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE),+ ]);+ mocks.queryWorkspaceDevices.mockResolvedValue([+ row('ws-managed', MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE, 'workspace'),+ ]);+ mocks.listStates.mockImplementation(async (scope: { workspaceId?: string }) =>+ scope.workspaceId ? { 'ws-managed': 'waking' } : { 'personal-managed': 'failed' },+ );++ const devices = await workspaceCaller().listDevices();++ expect(phaseOf(devices, 'personal-managed')).toBe('failed');+ expect(phaseOf(devices, 'ws-managed')).toBe('waking');+ expect(mocks.listStates).toHaveBeenCalledTimes(2);+ expect(mocks.listStates).toHaveBeenCalledWith({ userId: 'user' });+ expect(mocks.listStates).toHaveBeenCalledWith({ userId: 'user', workspaceId: 'workspace' });+ });++ it('still lists managed devices when the provider is unavailable', async () => {+ mocks.isAvailable.mockReturnValue(false);+ mocks.queryPersonal.mockResolvedValue([row('managed', MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE)]);++ const devices = await personalCaller().listDevices();++ expect(devices.map((device) => device.deviceId)).toEqual(['managed']);+ expect(phaseOf(devices, 'managed')).toBeUndefined();+ expect(mocks.listStates).not.toHaveBeenCalled();+ });++ it('still lists managed devices when the provider fails', async () => {+ mocks.queryPersonal.mockResolvedValue([row('managed', MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE)]);+ mocks.listStates.mockRejectedValue(new Error('provider down'));++ const devices = await personalCaller().listDevices();++ expect(devices.map((device) => device.deviceId)).toEqual(['managed']);+ expect(phaseOf(devices, 'managed')).toBeUndefined();+ });++ it('still lists managed devices when the provider does not answer in time', async () => {+ vi.useFakeTimers();+ try {+ mocks.queryPersonal.mockResolvedValue([row('managed', MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE)]);+ mocks.listStates.mockReturnValue(new Promise(() => {}));++ const pending = personalCaller().listDevices();+ await vi.advanceTimersByTimeAsync(MANAGED_PHASES_TIMEOUT_MS);+ const devices = await pending;++ expect(devices.map((device) => device.deviceId)).toEqual(['managed']);+ expect(phaseOf(devices, 'managed')).toBeUndefined();+ } finally {+ vi.useRealTimers();+ }+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/deviceRegisterManaged.test.ts b/apps/server/src/routers/lambda/__tests__/deviceRegisterManaged.test.tsnew file mode 100644index 00000000000..cb1ca048310--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/deviceRegisterManaged.test.ts@@ -0,0 +1,174 @@+// @vitest-environment node+import { MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { ManagedDeviceRegistrationConflictError } from '@/database/models/device';++import { deviceRouter } from '../device';++const mocks = vi.hoisted(() => ({+ assertNoCrossUserPrivateConflict: vi.fn(),+ enrollWorkspace: vi.fn(),+ findByDeviceId: vi.fn(),+ findWorkspaceDeviceById: vi.fn(),+ overwriteSharedWorkspaceDevice: vi.fn(),+ register: vi.fn(),+ registerWorkspaceDevice: vi.fn(),+ unenrollWorkspace: vi.fn(),+}));++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn() }));+vi.mock('@/database/models/device', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ DeviceModel: class {+ assertNoCrossUserPrivateConflict = mocks.assertNoCrossUserPrivateConflict;+ findByDeviceId = mocks.findByDeviceId;+ findWorkspaceDeviceById = mocks.findWorkspaceDeviceById;+ overwriteSharedWorkspaceDevice = mocks.overwriteSharedWorkspaceDevice;+ register = mocks.register;+ registerWorkspaceDevice = mocks.registerWorkspaceDevice;+ },+}));+vi.mock('@/libs/trpc/utils/internalJwt', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ signWorkspaceDeviceToken: vi.fn().mockResolvedValue('workspace-token'),+}));+vi.mock('@/server/services/deviceGateway', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ deviceGateway: {+ enrollWorkspace: mocks.enrollWorkspace,+ unenrollWorkspace: mocks.unenrollWorkspace,+ },+}));++const registration = { deviceId: 'managed-device', identitySource: 'machine-id' as const };++const workspaceCaller = () =>+ deviceRouter.createCaller({+ userId: 'user',+ workspaceId: 'workspace',+ workspaceRole: 'member',+ } as never);++describe('registering a managed cloud device id', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.findWorkspaceDeviceById.mockResolvedValue(undefined);+ });++ it('answers a personal registration with CONFLICT', async () => {+ mocks.register.mockRejectedValue(new ManagedDeviceRegistrationConflictError('managed-device'));++ await expect(+ deviceRouter.createCaller({ userId: 'user' } as never).register(registration),+ ).rejects.toMatchObject({ code: 'CONFLICT' });+ });++ it('answers a workspace enrollment with CONFLICT', async () => {+ mocks.registerWorkspaceDevice.mockRejectedValue(+ new ManagedDeviceRegistrationConflictError('managed-device'),+ );++ await expect(workspaceCaller().registerWorkspaceDevice(registration)).rejects.toMatchObject({+ code: 'CONFLICT',+ });+ });+});++describe('sharing a device into a workspace', () => {+ const personal = {+ deviceId: 'laptop',+ friendlyName: null,+ hostname: 'laptop',+ identitySource: 'machine-id',+ platform: 'linux',+ userId: 'user',+ workspaceId: null,+ };+ const identity = { deviceId: 'laptop-workspace', identitySource: 'machine-id' };++ beforeEach(() => {+ vi.clearAllMocks();+ mocks.findByDeviceId.mockResolvedValue(personal);+ mocks.findWorkspaceDeviceById.mockResolvedValue(undefined);+ mocks.enrollWorkspace.mockResolvedValue({ identity, success: true });+ mocks.registerWorkspaceDevice.mockResolvedValue({+ deviceId: identity.deviceId,+ friendlyName: null,+ visibility: 'private',+ });+ });++ it('refuses a device that reports the managed identity source on the probe', async () => {+ mocks.enrollWorkspace.mockResolvedValue({+ identity: { ...identity, identitySource: MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE },+ success: true,+ });++ await expect(+ workspaceCaller().shareDeviceToWorkspace({ deviceId: 'laptop' }),+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ expect(mocks.enrollWorkspace).toHaveBeenCalledTimes(1);+ expect(mocks.registerWorkspaceDevice).not.toHaveBeenCalled();+ });++ it('rolls back and refuses when the enrollment reports the managed identity source', async () => {+ mocks.enrollWorkspace.mockResolvedValueOnce({ identity, success: true }).mockResolvedValueOnce({+ identity: { ...identity, identitySource: MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE },+ success: true,+ });++ await expect(+ workspaceCaller().shareDeviceToWorkspace({ deviceId: 'laptop' }),+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ expect(mocks.registerWorkspaceDevice).not.toHaveBeenCalled();+ expect(mocks.unenrollWorkspace).toHaveBeenCalledWith({+ deviceId: identity.deviceId,+ userId: 'user',+ workspaceId: 'workspace',+ });+ });++ it('refuses to overwrite a managed workspace row before enrolling the device', async () => {+ mocks.findWorkspaceDeviceById.mockResolvedValue({+ deviceId: identity.deviceId,+ identitySource: MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE,+ userId: 'user',+ visibility: 'public',+ });++ await expect(+ workspaceCaller().shareDeviceToWorkspace({+ confirmOverwrite: true,+ deviceId: 'laptop',+ }),+ ).rejects.toMatchObject({ code: 'CONFLICT' });+ // Only the identity-only probe ran; the device opened no share connection.+ expect(mocks.enrollWorkspace).toHaveBeenCalledTimes(1);+ expect(mocks.enrollWorkspace).toHaveBeenCalledWith(+ expect.objectContaining({ identityOnly: true }),+ );+ expect(mocks.overwriteSharedWorkspaceDevice).not.toHaveBeenCalled();+ });++ it('refuses to share a managed personal device', async () => {+ mocks.findByDeviceId.mockResolvedValue({+ ...personal,+ identitySource: MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE,+ });++ await expect(+ workspaceCaller().shareDeviceToWorkspace({ deviceId: 'laptop' }),+ ).rejects.toMatchObject({ code: 'CONFLICT' });+ expect(mocks.enrollWorkspace).not.toHaveBeenCalled();+ });++ it('registers a client identity source', async () => {+ await expect(+ workspaceCaller().shareDeviceToWorkspace({ deviceId: 'laptop' }),+ ).resolves.toMatchObject({ deviceId: identity.deviceId, success: true });+ expect(mocks.registerWorkspaceDevice).toHaveBeenCalledWith(+ expect.objectContaining({ identitySource: 'machine-id' }),+ );+ });+});diff --git a/apps/server/src/routers/lambda/device/guards.ts b/apps/server/src/routers/lambda/device/guards.tsindex 86b970f8541..0a4d74fb746 100644--- a/apps/server/src/routers/lambda/device/guards.ts+++ b/apps/server/src/routers/lambda/device/guards.ts@@ -1,10 +1,55 @@+import { isManagedCloudDevice } from '@lobechat/types';import { TRPCError } from '@trpc/server';+import { z } from 'zod';import { type WorkspaceRole } from '@/business/server/trpc-middlewares/workspaceAuth';-import type { DeviceModel } from '@/database/models/device';+import {+ type DeviceModel,+ ManagedDeviceRegistrationConflictError,+ WorkspaceDevicePrivateConflictError,+} from '@/database/models/device';import { canOperateWorkspaceDevice } from '../deviceWorkspaceGuard';+/**+ * Identity sources a client may claim for itself. The managed cloud device+ * source is written only by the server that creates such a device.+ */+export const clientIdentitySourceSchema = z.enum(['machine-id', 'fallback']);++/** Check an identity source a device reported over RPC (share flow). */+export const parseReportedIdentitySource = (value: unknown) => {+ const parsed = clientIdentitySourceSchema.safeParse(value);+ if (!parsed.success) {+ throw new TRPCError({+ code: 'PRECONDITION_FAILED',+ message: 'Device reported an identity source it may not claim.',+ });+ }+ return parsed.data;+};++/**+ * Refuse a client action on a managed cloud device's row with CONFLICT. The+ * platform owns that row, so a client cannot share or overwrite it.+ */+export const assertNotManagedDevice = (+ device: { identitySource: string | null },+ message: string,+) => {+ if (isManagedCloudDevice(device)) throw new TRPCError({ code: 'CONFLICT', message });+};++/**+ * The tRPC error for a failed device registration: CONFLICT for the+ * `DeviceModel` registration conflicts, the error itself for anything else.+ */+export const toRegistrationError = (error: unknown) =>+ error instanceof WorkspaceDevicePrivateConflictError ||+ error instanceof ManagedDeviceRegistrationConflictError+ ? new TRPCError({ code: 'CONFLICT', message: error.message })+ : error;+/*** A workspace device's user-editable fields (rename, working dirs, remove) may* be modified by:diff --git a/apps/server/src/routers/lambda/device/registry.ts b/apps/server/src/routers/lambda/device/registry.tsindex 394eccb6036..976b5de1075 100644--- a/apps/server/src/routers/lambda/device/registry.ts+++ b/apps/server/src/routers/lambda/device/registry.ts@@ -5,12 +5,19 @@ import type {DeviceRunningSummary,DeviceScope,DeviceWorkspaceShare,+ ManagedDevicePhase,WorkingDirEntry,} from '@lobechat/types';-import { sortDevicesByActivity, workingDirConfigSchema } from '@lobechat/types';+import {+ isManagedCloudDevice,+ sortDevicesByActivity,+ workingDirConfigSchema,+} from '@lobechat/types';import { TRPCError } from '@trpc/server';+import debug from 'debug';import { z } from 'zod';+import { managedDeviceProvider } from '@/business/server/managedDevice';import { getTopicDeviceId, TopicModel } from '@/database/models/topic';import { UserModel } from '@/database/models/user';import { router } from '@/libs/trpc/lambda';@@ -19,9 +26,47 @@ import { filterAuthorizedDevicePresence } from '@/server/services/deviceGateway/import { loadAgentDeviceBindings, loadDeviceBoundAgents } from '../deviceBoundAgents';import { preserveWorkspaceCache } from '../deviceWorkingDirs';+import { clientIdentitySourceSchema, toRegistrationError } from './guards';import { reportManagedDevicesRemoved } from './managedDeviceRemoval';import { deviceProcedure } from './procedures';+const log = debug('lobe-server:device-registry');++/** How long the device list waits for managed device phases. */+export const MANAGED_PHASES_TIMEOUT_MS = 3000;++/**+ * Phases of the managed cloud devices in one pool of the device list. Asks the+ * provider only when the pool holds a managed row, so a list without managed+ * devices makes no provider call. A provider failure or a reply slower than+ * {@link MANAGED_PHASES_TIMEOUT_MS} leaves the phases unknown: the list must+ * still load, and a managed device then reads like any other offline device.+ */+const loadManagedPhases = async (+ rows: { identitySource: string }[],+ scope: { userId: string; workspaceId?: string },+): Promise<Record<string, ManagedDevicePhase>> => {+ if (!rows.some(isManagedCloudDevice)) return {};+ if (!managedDeviceProvider.isAvailable()) return {};++ let timer: ReturnType<typeof setTimeout> | undefined;+ const timeout = new Promise<Record<string, ManagedDevicePhase>>((resolve) => {+ timer = setTimeout(() => {+ log('listStates timed out for scope=%o', scope);+ resolve({});+ }, MANAGED_PHASES_TIMEOUT_MS);+ });++ try {+ return await Promise.race([managedDeviceProvider.listStates(scope), timeout]);+ } catch (error) {+ log('listStates failed for scope=%o: %O', scope, error);+ return {};+ } finally {+ clearTimeout(timer);+ }+};+/*** Display info for the members behind a set of running topics. The ids come* from topic rows the caller was already allowed to read, so this only adds@@ -180,6 +225,16 @@ export const registryRouter = router({wsId ? deviceGateway.queryDeviceList(ctx.userId, wsId) : Promise.resolve([]),]);+ // Personal and workspace managed devices belong to different provider+ // scopes, so each pool that holds one asks once; a pool without managed+ // rows asks nothing.+ const [personalPhases, workspacePhases] = await Promise.all([+ loadManagedPhases(personalRows, { userId: ctx.userId }),+ wsId+ ? loadManagedPhases(workspaceRows, { userId: ctx.userId, workspaceId: wsId })+ : Promise.resolve({}),+ ]);+// Shares the caller created from their personal device list, grouped by the// source personal deviceId — attached to personal rows below so the list can// render "shared to N workspaces" and revoke individual shares.@@ -243,6 +298,7 @@ export const registryRouter = router({rows: Awaited<ReturnType<typeof ctx.deviceModel.queryPersonal>>,onlineList: DeviceAttachment[],scope: DeviceScope,+ phases: Record<string, ManagedDevicePhase>,): DeviceListItem[] => {const registeredDeviceIds = new Set(rows.map((device) => device.deviceId));const channelsByDevice = new Map<string, DeviceChannel[]>();@@ -276,6 +332,9 @@ export const registryRouter = router({hostname: d.hostname ?? live?.hostname ?? null,identitySource: d.identitySource,lastSeen: d.lastSeenAt.toISOString(),+ // Only a managed row takes a phase: the provider never relabels a+ // machine a user connected.+ managedPhase: isManagedCloudDevice(d) ? phases[d.deviceId] : undefined,metadata: d.metadata,online: channels.length > 0,platform: d.platform ?? live?.platform ?? null,@@ -334,8 +393,8 @@ export const registryRouter = router({// Consumers (settings list, picker) filter this down to a single scope, and// filtering preserves order, so one pass serves every surface.return sortDevicesByActivity([- ...buildItems(personalRows, personalOnline, 'personal'),- ...buildItems(workspaceRows, workspaceOnline, 'workspace'),+ ...buildItems(personalRows, personalOnline, 'personal', personalPhases),+ ...buildItems(workspaceRows, workspaceOnline, 'workspace', workspacePhases),]);}),@@ -349,7 +408,8 @@ export const registryRouter = router({/*** Auto-register the calling device (desktop after OIDC login / CLI on first* `lh connect`). Upserts on (userId, deviceId); user-owned fields are- * preserved on conflict.+ * preserved on conflict. A managed cloud device's id is refused with+ * CONFLICT: the platform owns that row.*/register: deviceProcedure.input(@@ -357,7 +417,7 @@ export const registryRouter = router({architecture: z.string().max(20).nullish(),deviceId: z.string().min(1).max(64),hostname: z.string().nullish(),- identitySource: z.enum(['machine-id', 'fallback']),+ identitySource: clientIdentitySourceSchema,/** Extensible client-reported info bag; free-form, size-capped to guard the column. */metadata: z.record(z.string().max(64), z.string().max(200))@@ -367,7 +427,11 @@ export const registryRouter = router({}),).mutation(async ({ ctx, input }) => {- return ctx.deviceModel.register(input);+ try {+ return await ctx.deviceModel.register(input);+ } catch (error) {+ throw toRegistrationError(error);+ }}),removeDevice: deviceProcedure.input(z.object({ deviceId: z.string() }))diff --git a/apps/server/src/routers/lambda/device/workspace.ts b/apps/server/src/routers/lambda/device/workspace.tsindex dbc52cc9cfb..9363053a8a3 100644--- a/apps/server/src/routers/lambda/device/workspace.ts+++ b/apps/server/src/routers/lambda/device/workspace.ts@@ -15,6 +15,12 @@ import { deviceGateway } from '@/server/services/deviceGateway';import { preserveWorkspaceCache } from '../deviceWorkingDirs';import { assertWorkspaceDeviceEditable, canEditWorkspaceDevice } from '../deviceWorkspaceGuard';+import {+ assertNotManagedDevice,+ clientIdentitySourceSchema,+ parseReportedIdentitySource,+ toRegistrationError,+} from './guards';import { reportManagedDevicesRemoved } from './managedDeviceRemoval';/**@@ -75,7 +81,7 @@ export const workspaceRouter = router({architecture: z.string().max(20).nullish(),deviceId: z.string().min(1).max(64),hostname: z.string().nullish(),- identitySource: z.enum(['machine-id', 'fallback']),+ identitySource: clientIdentitySourceSchema,/** Extensible client-reported info bag; free-form, size-capped to guard the column. */metadata: z.record(z.string().max(64), z.string().max(200))@@ -94,10 +100,7 @@ export const workspaceRouter = router({try {return await model.registerWorkspaceDevice({ ...input, workspaceId: ctx.workspaceId });} catch (error) {- if (error instanceof WorkspaceDevicePrivateConflictError) {- throw new TRPCError({ code: 'CONFLICT', message: error.message });- }- throw error;+ throw toRegistrationError(error);}}),/**@@ -139,6 +142,7 @@ export const workspaceRouter = router({if (!personal || personal.workspaceId) {throw new TRPCError({ code: 'NOT_FOUND', message: 'Personal device not found.' });}+ assertNotManagedDevice(personal, 'A managed cloud device cannot be shared to a workspace.');const token = await signWorkspaceDeviceToken(ctx.workspaceId);// Identity-only probe: learn the machine's workspace deviceId WITHOUT the@@ -159,6 +163,7 @@ export const workspaceRouter = router({message: probe.error ?? 'Device is offline or does not support workspace sharing.',});}+ parseReportedIdentitySource(probe.identity.identitySource);// Fail a cross-user PRIVATE collision NOW, before the machine opens and// persists a workspace share connection — rejecting only at the later@@ -177,6 +182,10 @@ export const workspaceRouter = router({// rejected above, so an undefined here really means "no row yet".const existing = await model.findWorkspaceDeviceById(probe.identity.deviceId);if (existing) {+ assertNotManagedDevice(+ existing,+ 'This workspace device is a managed cloud device and cannot be overwritten.',+ );if (!input.confirmOverwrite) {return {alreadyEnrolled: true as const,@@ -234,7 +243,7 @@ export const workspaceRouter = router({row = await model.registerWorkspaceDevice({deviceId: result.identity.deviceId,hostname: personal.hostname,- identitySource: result.identity.identitySource,+ identitySource: parseReportedIdentitySource(result.identity.identitySource),platform: personal.platform,sharedFromDeviceId: personal.deviceId,visibility: input.visibility,@@ -251,10 +260,7 @@ export const workspaceRouter = router({userId: ctx.userId,workspaceId: ctx.workspaceId,});- if (error instanceof WorkspaceDevicePrivateConflictError) {- throw new TRPCError({ code: 'CONFLICT', message: error.message });- }- throw error;+ throw toRegistrationError(error);}// Carry the personal alias over on first share so the workspace list shows// the machine under the name its owner gave it; never clobber a name adiff --git a/apps/server/src/services/deviceGateway/workspace.ts b/apps/server/src/services/deviceGateway/workspace.tsindex 12ac91660f9..5e552cd1f78 100644--- a/apps/server/src/services/deviceGateway/workspace.ts+++ b/apps/server/src/services/deviceGateway/workspace.ts@@ -145,7 +145,8 @@ export async function enrollWorkspace(},): Promise<{error?: string;- identity?: { deviceId: string; identitySource: 'fallback' | 'machine-id' };+ /** As the device reported it; callers validate `identitySource`. */+ identity?: { deviceId: string; identitySource: string };success: boolean;}> {const { deviceId, identityOnly, timeout = 30_000, token, userId, workspaceId } = params;@@ -153,10 +154,7 @@ export async function enrollWorkspace(if (!client) return { error: 'Device Gateway is not configured', success: false };try {- const result = await client.invokeRpc<{- deviceId: string;- identitySource: 'fallback' | 'machine-id';- }>(+ const result = await client.invokeRpc<{ deviceId: string; identitySource: string }>({ deviceId, timeout, userId },{method: 'enrollWorkspace',diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex da716e0373b..8f6f300bcaf 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -553,6 +553,8 @@"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}}",+ "devices.managed.badge": "Cloud",+ "devices.managed.badgeTooltip": "A cloud device that LobeHub runs for you. It sleeps when idle and wakes when an agent needs it.","devices.managed.create.button": "Create in cloud","devices.managed.create.class.label": "Size","devices.managed.create.class.notIncluded": "Not in your plan",@@ -571,6 +573,13 @@"devices.managed.create.submit": "Create","devices.managed.create.success": "Cloud device created. It starts in about a minute.","devices.managed.create.title": "Create a cloud device",+ "devices.managed.remove.confirmDesc": "This deletes the cloud device. You cannot undo this.",+ "devices.managed.status.deleting": "Deleting",+ "devices.managed.status.failed": "Unavailable",+ "devices.managed.status.sleeping": "Sleeping",+ "devices.managed.status.sleepingHint": "Sleeping · wakes when an agent needs it",+ "devices.managed.status.starting": "Starting",+ "devices.managed.status.stopping": "Going to sleep","devices.remove.confirm": "Remove this device?","devices.remove.confirmDesc": "This disconnects the device from your account. It does not sign the device out, and it can re-register on next connect.","devices.remove.currentSessionWarning": "This includes the device you're using right now — removing it disconnects your current session.",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 6bc925d1890..f6d4584ec8c 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -553,6 +553,8 @@"devices.keepAwake.desc": "作为设备连接期间阻止电脑自动睡眠,保证它始终可被访问。屏幕仍可正常关闭;未连接外接显示器时合上笔记本屏幕仍会睡眠。","devices.keepAwake.title": "连接期间保持唤醒","devices.lastSeen": "最后连接于 {{time}}",+ "devices.managed.badge": "云端",+ "devices.managed.badgeTooltip": "由 LobeHub 为你运行的云端设备。空闲时休眠,智能体需要时自动唤醒。","devices.managed.create.button": "在云端创建","devices.managed.create.class.label": "规格","devices.managed.create.class.notIncluded": "当前套餐不包含",@@ -571,6 +573,13 @@"devices.managed.create.submit": "创建","devices.managed.create.success": "云端设备已创建,约一分钟后启动。","devices.managed.create.title": "创建云端设备",+ "devices.managed.remove.confirmDesc": "这会删除此云端设备,且无法撤销。",+ "devices.managed.status.deleting": "删除中",+ "devices.managed.status.failed": "不可用",+ "devices.managed.status.sleeping": "休眠中",+ "devices.managed.status.sleepingHint": "休眠中 · 智能体需要时自动唤醒",+ "devices.managed.status.starting": "启动中",+ "devices.managed.status.stopping": "正在休眠","devices.remove.confirm": "移除此设备?","devices.remove.confirmDesc": "这会断开设备与你账户的关联,但不会让设备登出,下次连接时它可重新注册。","devices.remove.currentSessionWarning": "其中包含你当前正在使用的设备,移除后会断开当前会话。",diff --git a/packages/database/src/models/__tests__/device.managed.test.ts b/packages/database/src/models/__tests__/device.managed.test.tsnew file mode 100644index 00000000000..741ce8a20f3--- /dev/null+++ b/packages/database/src/models/__tests__/device.managed.test.ts@@ -0,0 +1,189 @@+// @vitest-environment node+import { MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE } from '@lobechat/types';+import { and, eq, inArray } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { devices, users, workspaces } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { DeviceModel, ManagedDeviceRegistrationConflictError } from '../device';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'devmanaged-user';+const otherUserId = 'devmanaged-other-user';+const workspaceId = 'devmanaged-workspace';+const managedId = '7d9c1f0e-5b2a-4c3d-9e8f-0a1b2c3d4e5f';++const cleanup = async () => {+ // devices / workspaces cascade from their owning user.+ await serverDB.delete(users).where(inArray(users.id, [userId, otherUserId]));+};++const insertManaged = (values: { userId: string; workspaceId?: string }) =>+ serverDB.insert(devices).values({+ deviceId: managedId,+ hostname: 'managed-host',+ identitySource: MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE,+ lastSeenAt: new Date('2026-01-01T00:00:00Z'),+ metadata: { cliVersion: '1.0.0' },+ platform: 'linux',+ visibility: 'public',+ ...values,+ });++const findManaged = (scope: { workspaceId?: string }) =>+ serverDB.query.devices.findFirst({+ where: and(+ eq(devices.deviceId, managedId),+ scope.workspaceId ? eq(devices.workspaceId, scope.workspaceId) : undefined,+ ),+ });++const clientRegistration = {+ architecture: 'arm64',+ deviceId: managedId,+ hostname: 'client-host',+ identitySource: 'machine-id',+ metadata: { appVersion: '9.9.9' },+ platform: 'darwin',+};++describe('DeviceModel client writes to a managed cloud device row', () => {+ beforeEach(async () => {+ await cleanup();+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+ await serverDB.insert(workspaces).values({+ id: workspaceId,+ name: 'devmanaged workspace',+ primaryOwnerId: userId,+ slug: 'devmanaged-workspace',+ });+ });++ afterEach(async () => {+ await cleanup();+ });++ describe('register', () => {+ it('rejects a client registration and leaves the managed row unchanged', async () => {+ await insertManaged({ userId });+ const before = await findManaged({});++ await expect(new DeviceModel(serverDB, userId).register(clientRegistration)).rejects.toThrow(+ ManagedDeviceRegistrationConflictError,+ );++ expect(await findManaged({})).toEqual(before);+ });++ it('still registers a new id with the managed identity source', async () => {+ const row = await new DeviceModel(serverDB, userId).register({+ deviceId: managedId,+ identitySource: MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE,+ });++ expect(row).toMatchObject({+ deviceId: managedId,+ identitySource: MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE,+ });+ });++ it('keeps refreshing a client device on re-registration', async () => {+ const model = new DeviceModel(serverDB, userId);+ await model.register({ deviceId: 'client-device', identitySource: 'fallback' });++ const row = await model.register({+ deviceId: 'client-device',+ hostname: 'renamed-host',+ identitySource: 'machine-id',+ });++ expect(row).toMatchObject({ hostname: 'renamed-host', identitySource: 'machine-id' });+ });+ });++ describe('registerWorkspaceDevice', () => {+ it('rejects re-enrolling a managed workspace device and leaves it unchanged', async () => {+ await insertManaged({ userId, workspaceId });+ const before = await findManaged({ workspaceId });++ await expect(+ new DeviceModel(serverDB, otherUserId, workspaceId).registerWorkspaceDevice({+ ...clientRegistration,+ visibility: 'public',+ workspaceId,+ }),+ ).rejects.toThrow(ManagedDeviceRegistrationConflictError);++ expect(await findManaged({ workspaceId })).toEqual(before);+ });++ it('rejects the enrolling member too', async () => {+ await insertManaged({ userId, workspaceId });++ await expect(+ new DeviceModel(serverDB, userId, workspaceId).registerWorkspaceDevice({+ ...clientRegistration,+ workspaceId,+ }),+ ).rejects.toThrow(ManagedDeviceRegistrationConflictError);++ expect((await findManaged({ workspaceId }))?.identitySource).toBe(+ MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE,+ );+ });++ it('keeps refreshing a client workspace device on re-enrollment', async () => {+ const model = new DeviceModel(serverDB, userId, workspaceId);+ await model.registerWorkspaceDevice({+ deviceId: 'client-ws-device',+ identitySource: 'machine-id',+ workspaceId,+ });++ const row = await model.registerWorkspaceDevice({+ deviceId: 'client-ws-device',+ hostname: 'renamed-host',+ identitySource: 'machine-id',+ workspaceId,+ });++ expect(row).toMatchObject({ hostname: 'renamed-host' });+ });+ });++ describe('overwriteSharedWorkspaceDevice', () => {+ it('leaves a managed workspace row unchanged', async () => {+ await insertManaged({ userId, workspaceId });+ const before = await findManaged({ workspaceId });++ const row = await new DeviceModel(+ serverDB,+ otherUserId,+ workspaceId,+ ).overwriteSharedWorkspaceDevice(managedId, {+ sharedFromDeviceId: 'other-laptop',+ visibility: 'private',+ });++ expect(row).toBeUndefined();+ expect(await findManaged({ workspaceId })).toEqual(before);+ });+ });++ describe('updateDeviceInfo', () => {+ it('leaves a managed personal row unchanged', async () => {+ await insertManaged({ userId });+ const before = await findManaged({});++ const row = await new DeviceModel(serverDB, userId).updateDeviceInfo(managedId, {+ architecture: 'arm64',+ hostname: 'client-host',+ });++ expect(row).toBeUndefined();+ expect(await findManaged({})).toEqual(before);+ });+ });+});diff --git a/packages/database/src/models/device.ts b/packages/database/src/models/device.tsindex 602b7581923..959c008b8a7 100644--- a/packages/database/src/models/device.ts+++ b/packages/database/src/models/device.ts@@ -1,4 +1,5 @@import type { WorkingDirEntry } from '@lobechat/types';+import { MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE } from '@lobechat/types';import { and, desc, eq, isNotNull, isNull, ne, sql } from 'drizzle-orm';import type { DeviceItem } from '../schemas';@@ -25,6 +26,30 @@ export class WorkspaceDevicePrivateConflictError extends Error {}}+/**+ * A registration named the `deviceId` of an existing managed cloud device.+ * The platform owns that row — its identity and machine-reported fields come+ * from the managed device provider, not from a client — so `register` and+ * `registerWorkspaceDevice` leave it untouched and fail with this instead.+ * Routers map it to a CONFLICT response.+ */+export class ManagedDeviceRegistrationConflictError extends Error {+ constructor(deviceId: string) {+ super(+ `Device "${deviceId}" is a managed cloud device and cannot be registered by a client — use a different device id.`,+ );+ this.name = 'ManagedDeviceRegistrationConflictError';+ }+}++/**+ * Upsert guard for both registration paths: the conflict update applies only+ * when the stored row is not a managed cloud device. Checked in the same+ * statement as the write, so no registration racing a managed device's+ * creation can overwrite it.+ */+const notManagedRow = ne(devices.identitySource, MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE);+export interface RegisterDeviceParams {/** CPU architecture reported by the client (`process.arch`); optional for older clients. */architecture?: string | null;@@ -108,7 +133,8 @@ export class DeviceModel {* Auto-register from desktop/CLI. Upserts on the (userId, deviceId) unique* index. On conflict only the machine-reported fields + lastSeenAt are* refreshed — friendlyName / defaultCwd / workingDirs are user-owned and- * must survive re-registration.+ * must survive re-registration. A conflict with a managed cloud device+ * changes nothing and throws {@link ManagedDeviceRegistrationConflictError}.*/register = async (params: RegisterDeviceParams) => {const now = new Date();@@ -133,11 +159,16 @@ export class DeviceModel {metadata: mergeReportedMetadata(params.metadata),platform: params.platform,},+ setWhere: notManagedRow,target: [devices.userId, devices.deviceId],targetWhere: sql`${devices.workspaceId} IS NULL`,}).returning();+ // No row back means the conflict update was skipped: the id is taken by a+ // managed cloud device.+ if (!result) throw new ManagedDeviceRegistrationConflictError(params.deviceId);+return result;};@@ -145,7 +176,9 @@ export class DeviceModel {* Enroll a machine as a WORKSPACE device (admin-driven). Upserts on* `(userId, deviceId)` like {@link register}, but stamps `workspace_id` so the* row belongs to the workspace and surfaces to all its members. `userId`- * records the enrolling admin.+ * records the enrolling admin. Like {@link register}, a conflict with a+ * managed cloud device changes nothing and throws+ * {@link ManagedDeviceRegistrationConflictError}.*//*** Fail closed when `deviceId` collides with ANOTHER member's PRIVATE@@ -230,11 +263,15 @@ export class DeviceModel {platform: params.platform,visibility: params.visibility === 'public' ? 'public' : sql`${devices.visibility}`,},+ setWhere: notManagedRow,target: [devices.workspaceId, devices.deviceId],targetWhere: sql`${devices.workspaceId} IS NOT NULL`,}).returning();+ // Skipped conflict update: the id is taken by a managed cloud device.+ if (!result) throw new ManagedDeviceRegistrationConflictError(params.deviceId);+return result;};@@ -347,6 +384,7 @@ export class DeviceModel {eq(devices.userId, this.userId),eq(devices.deviceId, deviceId),isNull(devices.workspaceId),+ notManagedRow,),).returning();@@ -472,7 +510,13 @@ export class DeviceModel {userId: this.userId,visibility: params.visibility,})- .where(and(eq(devices.workspaceId, this.workspaceId), eq(devices.deviceId, deviceId)))+ .where(+ and(+ eq(devices.workspaceId, this.workspaceId),+ eq(devices.deviceId, deviceId),+ notManagedRow,+ ),+ ).returning();return row;};diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex d1ef47751f1..bcca20d114f 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -854,6 +854,9 @@ export default {'devices.health.status.pending': 'Not uploaded yet','devices.health.title': 'Health · last 12 hours','devices.lastSeen': 'Last connected {{time}}',+ 'devices.managed.badge': 'Cloud',+ 'devices.managed.badgeTooltip':+ 'A cloud device that LobeHub runs for you. It sleeps when idle and wakes when an agent needs it.','devices.managed.create.button': 'Create in cloud','devices.managed.create.class.label': 'Size','devices.managed.create.class.notIncluded': 'Not in your plan',@@ -875,6 +878,13 @@ export default {'devices.managed.create.submit': 'Create','devices.managed.create.success': 'Cloud device created. It starts in about a minute.','devices.managed.create.title': 'Create a cloud device',+ 'devices.managed.remove.confirmDesc': 'This deletes the cloud device. You cannot undo this.',+ 'devices.managed.status.deleting': 'Deleting',+ 'devices.managed.status.failed': 'Unavailable',+ 'devices.managed.status.sleeping': 'Sleeping',+ 'devices.managed.status.sleepingHint': 'Sleeping · wakes when an agent needs it',+ 'devices.managed.status.starting': 'Starting',+ 'devices.managed.status.stopping': 'Going to sleep','devices.remove.confirm': 'Remove this device?','devices.remove.confirmDesc':'This disconnects the device from your account. It does not sign the device out, and it can re-register on next connect.',diff --git a/packages/types/src/device.ts b/packages/types/src/device.tsindex 25a1308e425..937e707597a 100644--- a/packages/types/src/device.ts+++ b/packages/types/src/device.ts@@ -1,6 +1,7 @@import { z } from 'zod';import type { DeviceLocalFilePreviewFailure } from './deviceFilePreviewFailure';+import type { ManagedDevicePhase } from './managedDevice';/** Structured context for an unavailable logical device. */export interface DeviceUnavailableErrorData {@@ -353,6 +354,14 @@ export interface DeviceListItem {hostname: string | null;identitySource: string | null;lastSeen: string;+ /**+ * Managed cloud devices only: the lifecycle phase the managed device+ * provider reports, so a sleeping device reads as sleeping instead of as an+ * offline machine. `undefined` for other devices, and for a managed device+ * whose phase is unknown (provider unavailable or the device not in its+ * answer).+ */+ managedPhase?: ManagedDevicePhase;/*** What the client reported about itself on its last connect — the desktop* app sends `appVersion` (plus runtime versions), the CLI `cliVersion`.diff --git a/src/features/DeviceManager/DeviceCard.tsx b/src/features/DeviceManager/DeviceCard.tsxindex 509ee9e6634..b274471767a 100644--- a/src/features/DeviceManager/DeviceCard.tsx+++ b/src/features/DeviceManager/DeviceCard.tsx@@ -1,6 +1,7 @@'use client';import type { DeviceListItem } from '@lobechat/types';+import { isManagedCloudDevice } from '@lobechat/types';import {ActionIcon,confirmModal,@@ -31,10 +32,13 @@ import { useUserStore } from '@/store/user';import { userProfileSelectors } from '@/store/user/selectors';import { DeviceRunningSummaryValue } from './DeviceActivity/RunningUsers';+import { canOfferDeviceShare, removeConfirmDescKey } from './deviceCardActions';import { useDeviceMetricSeries } from './DeviceHealth/shared';import UsageMeter, { UsageMeterGroup, UsageMeterSkeleton } from './DeviceHealth/UsageMeter';import { latestUsageView } from './DeviceHealth/viewState';import { getDeviceIcon, getPlatformLabel } from './getDeviceIcon';+import ManagedDeviceBadge from './ManagedDeviceBadge';+import { getManagedDeviceStatus, presenceDotColor } from './managedDeviceStatus';import { openShareDeviceModal } from './ShareDeviceModal';import { useCanEditDevice } from './useCanEditDevice';import { useDeviceActivityText } from './useDeviceActivityText';@@ -141,6 +145,8 @@ const DeviceCard = memo<DeviceCardProps>(({ device, isCurrent, onOpen }) => {const displayName = device.friendlyName || device.hostname || device.deviceId;const isFallback = device.identitySource === 'fallback';+ const isManaged = isManagedCloudDevice(device);+ const managedStatus = getManagedDeviceStatus(device);// Online when the device has at least one live connection in `device.channels`.const channels = device.channels ?? [];const online = channels.length > 0;@@ -204,25 +210,24 @@ const DeviceCard = memo<DeviceCardProps>(({ device, isCurrent, onOpen }) => {// 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 shareItems = canOfferDeviceShare(device)+ ? [+ {+ 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'),+ ? `${t(removeConfirmDescKey(device))}\n\n${t('devices.remove.currentSessionWarning')}`+ : t(removeConfirmDescKey(device)),okButtonProps: { danger: true },okText: t('devices.actions.remove'),onOk: async () => {@@ -268,6 +273,7 @@ const DeviceCard = memo<DeviceCardProps>(({ device, isCurrent, onOpen }) => {{platformLabel}</Text>)}+ {isManaged && <ManagedDeviceBadge />}{isCurrent && <Tag size={'small'}>{t('devices.currentBadge')}</Tag>}{device.scope === 'workspace' && device.sharedFromPersonal && (// Member-shared machine (vs directly enrolled infra) — mirrors the@@ -364,9 +370,14 @@ const DeviceCard = memo<DeviceCardProps>(({ device, isCurrent, onOpen }) => {<spanaria-hiddenclassName={styles.presence}- style={{ background: online ? cssVar.colorSuccess : cssVar.colorTextQuaternary }}+ style={{ background: presenceDotColor(managedStatus, online) }}/>- <Text ellipsis fontSize={13} style={{ minWidth: 0 }} type={'secondary'}>+ <Text+ ellipsis+ fontSize={13}+ style={{ minWidth: 0 }}+ type={managedStatus === 'failed' ? 'danger' : 'secondary'}+ >{activityText}</Text></Flexbox>diff --git a/src/features/DeviceManager/DeviceDetail.tsx b/src/features/DeviceManager/DeviceDetail.tsxindex dc33a75ad91..1d97edd07f3 100644--- a/src/features/DeviceManager/DeviceDetail.tsx+++ b/src/features/DeviceManager/DeviceDetail.tsx@@ -2,6 +2,7 @@import { isDesktop } from '@lobechat/const';import type { DeviceListItem } from '@lobechat/types';+import { isManagedCloudDevice } from '@lobechat/types';import {ActionIcon,Button,@@ -44,6 +45,12 @@ import { refreshDeviceList } from './const';import DeviceOverview from './DeviceOverview';import FieldLabel from './FieldLabel';import { getDeviceIcon } from './getDeviceIcon';+import ManagedDeviceBadge from './ManagedDeviceBadge';+import {+ getManagedDeviceStatus,+ managedStatusLabelKey,+ presenceDotColor,+} from './managedDeviceStatus';import { useCanEditDevice, useCanOperateDevice } from './useCanEditDevice';const styles = createStaticStyles(({ css }) => ({@@ -171,6 +178,7 @@ const DeviceDetail = memo<DeviceDetailProps>(({ device, isConfirmed, isCurrent,const channels = device.channels ?? [];const online = channels.length > 0;const presenceUnknown = !!device.onlineUnknown;+ const managedStatus = getManagedDeviceStatus(device);// Every edit persists immediately — there is no Save button. Name and the// default cwd commit on blur; recent-dir add / remove / reorder commit on the@@ -290,13 +298,15 @@ const DeviceDetail = memo<DeviceDetailProps>(({ device, isConfirmed, isCurrent,{getDeviceIcon(device.platform, 26)}<spanclassName={styles.presence}- style={{ background: online ? cssVar.colorSuccess : cssVar.colorTextQuaternary }}+ style={{ background: presenceDotColor(managedStatus, online) }}title={- presenceUnknown- ? t('devices.status.checking')- : online- ? t('devices.status.onlineConnections', { count: channels.length })- : t('devices.status.offline')+ managedStatus+ ? t(managedStatusLabelKey[managedStatus])+ : presenceUnknown+ ? t('devices.status.checking')+ : online+ ? t('devices.status.onlineConnections', { count: channels.length })+ : t('devices.status.offline')}/></span>@@ -337,6 +347,7 @@ const DeviceDetail = memo<DeviceDetailProps>(({ device, isConfirmed, isCurrent,</span><CopyButton content={device.deviceId} size={'small'} /></Flexbox>+ {isManagedCloudDevice(device) && <ManagedDeviceBadge />}{isCurrent && <Tag size={'small'}>{t('devices.currentBadge')}</Tag>}{device.scope === 'workspace' && device.visibility === 'private' && (<Tag icon={<Icon icon={LockIcon} />} size={'small'}>diff --git a/src/features/DeviceManager/DeviceHoverPanel.tsx b/src/features/DeviceManager/DeviceHoverPanel.tsxindex b52a4c4b834..d2a4013e2f6 100644--- a/src/features/DeviceManager/DeviceHoverPanel.tsx+++ b/src/features/DeviceManager/DeviceHoverPanel.tsx@@ -29,6 +29,11 @@ import UsageMeter, { UsageMeterGroup, UsageMeterSkeleton } from './DeviceHealth/import { latestUsageView } from './DeviceHealth/viewState';import { buildDeviceHoverSummary } from './deviceHoverSummary';import { getDeviceIcon } from './getDeviceIcon';+import {+ getManagedDeviceStatus,+ managedStatusLabelKey,+ presenceDotColor,+} from './managedDeviceStatus';const styles = createStaticStyles(({ css }) => ({code: css`@@ -121,6 +126,7 @@ const DeviceHoverPanel = ({ device }: DeviceHoverPanelProps) => {const usage = latestUsageView({ data, error });const summary = buildDeviceHoverSummary(device, data);const { online } = summary;+ const managedStatus = getManagedDeviceStatus(device);return (<Flexbox className={styles.container}>@@ -128,7 +134,7 @@ const DeviceHoverPanel = ({ device }: DeviceHoverPanelProps) => {<InfoRow icon={PowerIcon} label={t('devices.detail.status')}><spanstyle={{- background: online ? cssVar.colorSuccess : cssVar.colorTextQuaternary,+ background: presenceDotColor(managedStatus, online),borderRadius: '50%',flex: 'none',height: 6,@@ -136,11 +142,13 @@ const DeviceHoverPanel = ({ device }: DeviceHoverPanelProps) => {}}/><span>- {summary.onlineUnknown- ? t('devices.status.checking')- : online- ? t('devices.status.online')- : t('devices.status.offline')}+ {managedStatus+ ? t(managedStatusLabelKey[managedStatus])+ : summary.onlineUnknown+ ? t('devices.status.checking')+ : online+ ? t('devices.status.online')+ : t('devices.status.offline')}</span></InfoRow>{online && (diff --git a/src/features/DeviceManager/DeviceOverview.tsx b/src/features/DeviceManager/DeviceOverview.tsxindex 354f8cfd8fd..daf89bb3e36 100644--- a/src/features/DeviceManager/DeviceOverview.tsx+++ b/src/features/DeviceManager/DeviceOverview.tsx@@ -52,6 +52,13 @@ import { usageTextColor, useDeviceMetricSeries } from './DeviceHealth/shared';import { UsageBar } from './DeviceHealth/UsageMeter';import { latestUsageView } from './DeviceHealth/viewState';import { getDeviceIcon, getPlatformLabel } from './getDeviceIcon';+import {+ getManagedDeviceStatus,+ managedStatusBackground,+ managedStatusColor,+ managedStatusLabelKey,+ presenceDotColor,+} from './managedDeviceStatus';const styles = createStaticStyles(({ css }) => ({card: css`@@ -247,6 +254,7 @@ const DeviceOverview = ({ canOperate, device }: DeviceOverviewProps) => {const online = channels.length > 0;// The persisted copy carries no channels: presence is unknown, not offline.const presenceUnknown = !!device.onlineUnknown;+ const managedStatus = getManagedDeviceStatus(device);const newest = data?.points.at(-1);const cores = data?.cpuCount ?? null;@@ -295,23 +303,33 @@ const DeviceOverview = ({ canOperate, device }: DeviceOverviewProps) => {<spanclassName={styles.statusPill}style={{- background: online ? cssVar.colorSuccessBg : cssVar.colorFillTertiary,- color: online ? cssVar.colorSuccess : cssVar.colorTextSecondary,+ background: managedStatus+ ? managedStatusBackground[managedStatus]+ : online+ ? cssVar.colorSuccessBg+ : cssVar.colorFillTertiary,+ color: managedStatus+ ? managedStatusColor[managedStatus]+ : online+ ? cssVar.colorSuccess+ : cssVar.colorTextSecondary,}}><spanstyle={{- background: online ? cssVar.colorSuccess : cssVar.colorTextQuaternary,+ background: presenceDotColor(managedStatus, online),borderRadius: '50%',height: 6,width: 6,}}/>- {presenceUnknown- ? t('devices.status.checking')- : online- ? t('devices.status.online')- : t('devices.status.offline')}+ {managedStatus+ ? t(managedStatusLabelKey[managedStatus])+ : presenceUnknown+ ? t('devices.status.checking')+ : online+ ? t('devices.status.online')+ : t('devices.status.offline')}</span></InfoRow><InfoRow icon={MonitorIcon} label={t('devices.detail.os')}>diff --git a/src/features/DeviceManager/ManagedDeviceBadge.tsx b/src/features/DeviceManager/ManagedDeviceBadge.tsxnew file mode 100644index 00000000000..12f2df2dddd--- /dev/null+++ b/src/features/DeviceManager/ManagedDeviceBadge.tsx@@ -0,0 +1,20 @@+'use client';++import { Icon, Tag, Tooltip } from '@lobehub/ui';+import { CloudIcon } from 'lucide-react';+import { useTranslation } from 'react-i18next';++/** Marks a managed cloud device among the machines a user connected themselves. */+const ManagedDeviceBadge = () => {+ const { t } = useTranslation('setting');++ return (+ <Tooltip title={t('devices.managed.badgeTooltip')}>+ <Tag color={'info'} icon={<Icon icon={CloudIcon} />} size={'small'}>+ {t('devices.managed.badge')}+ </Tag>+ </Tooltip>+ );+};++export default ManagedDeviceBadge;diff --git a/src/features/DeviceManager/deviceCardActions.test.ts b/src/features/DeviceManager/deviceCardActions.test.tsnew file mode 100644index 00000000000..8cbbe7a817f--- /dev/null+++ b/src/features/DeviceManager/deviceCardActions.test.ts@@ -0,0 +1,40 @@+import { MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { canOfferDeviceShare, removeConfirmDescKey } from './deviceCardActions';++const connected = {+ identitySource: 'machine-id',+ registered: true,+ scope: 'personal' as const,+};+const managed = { ...connected, identitySource: MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE };++describe('canOfferDeviceShare', () => {+ it('offers sharing for a registered personal device the user connected', () => {+ expect(canOfferDeviceShare(connected)).toBe(true);+ });++ // Regression: the card offered "Share to Workspace" on a managed cloud+ // device, which the server always refuses.+ it('never offers sharing for a managed cloud device', () => {+ expect(canOfferDeviceShare(managed)).toBe(false);+ });++ it('never offers sharing for a workspace or unregistered row', () => {+ expect(canOfferDeviceShare({ ...connected, scope: 'workspace' })).toBe(false);+ expect(canOfferDeviceShare({ ...connected, registered: false })).toBe(false);+ });+});++describe('removeConfirmDescKey', () => {+ // Regression: removing a managed cloud device said it could register again,+ // but the removal deletes it.+ it('warns that removing a managed cloud device deletes it', () => {+ expect(removeConfirmDescKey(managed)).toBe('devices.managed.remove.confirmDesc');+ });++ it('keeps the reconnect wording for a connected device', () => {+ expect(removeConfirmDescKey(connected)).toBe('devices.remove.confirmDesc');+ });+});diff --git a/src/features/DeviceManager/deviceCardActions.ts b/src/features/DeviceManager/deviceCardActions.tsnew file mode 100644index 00000000000..269a2c8c510--- /dev/null+++ b/src/features/DeviceManager/deviceCardActions.ts@@ -0,0 +1,24 @@+import type { DeviceListItem } from '@lobechat/types';+import { isManagedCloudDevice } from '@lobechat/types';++type CardDevice = Pick<DeviceListItem, 'identitySource' | 'registered' | 'scope'>;++/**+ * Whether the device card offers "Share to Workspace". Only a registered+ * personal device the user connected can be shared: the share flow asks the+ * machine's desktop app for a workspace identity, and the server refuses a+ * managed cloud device.+ */+export const canOfferDeviceShare = (device: CardDevice): boolean =>+ device.scope === 'personal' && device.registered && !isManagedCloudDevice(device);++/**+ * Locale key (namespace `setting`) of the remove confirmation body. Removing a+ * managed cloud device deletes it. A connected device can register again.+ */+export const removeConfirmDescKey = (+ device: Pick<DeviceListItem, 'identitySource'>,+): 'devices.managed.remove.confirmDesc' | 'devices.remove.confirmDesc' =>+ isManagedCloudDevice(device)+ ? 'devices.managed.remove.confirmDesc'+ : 'devices.remove.confirmDesc';diff --git a/src/features/DeviceManager/managedDeviceStatus.test.ts b/src/features/DeviceManager/managedDeviceStatus.test.tsnew file mode 100644index 00000000000..6070947e64a--- /dev/null+++ b/src/features/DeviceManager/managedDeviceStatus.test.ts@@ -0,0 +1,126 @@+/**+ * @vitest-environment happy-dom+ */+import type { DeviceListItem, ManagedDevicePhase } from '@lobechat/types';+import { MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE } from '@lobechat/types';+import { cssVar } from '@lobehub/ui';+import { renderHook } from '@testing-library/react';+import dayjs from 'dayjs';+import relativeTime from 'dayjs/plugin/relativeTime';+import { describe, expect, it } from 'vitest';++import {+ getManagedDeviceStatus,+ managedStatusColor,+ presenceDotColor,+} from './managedDeviceStatus';+import { useDeviceActivityText } from './useDeviceActivityText';++dayjs.extend(relativeTime);++const channel = {+ channel: 'cli' as const,+ connectedAt: '2026-01-01T00:00:00.000Z',+ hostname: 'managed-host',+ platform: 'linux',+};++const buildDevice = (overrides: Partial<DeviceListItem> = {}): DeviceListItem => ({+ channels: [],+ defaultCwd: null,+ deviceId: 'managed-device',+ enroller: null,+ friendlyName: null,+ hostname: null,+ identitySource: MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE,+ lastSeen: '2026-01-01T00:00:00.000Z',+ online: false,+ platform: 'linux',+ registered: true,+ scope: 'personal',+ visibility: null,+ workingDirs: [],+ ...overrides,+});++const managed = (managedPhase: ManagedDevicePhase, overrides: Partial<DeviceListItem> = {}) =>+ buildDevice({ managedPhase, ...overrides });++describe('getManagedDeviceStatus', () => {+ it.each([+ ['suspended', 'sleeping'],+ ['suspending', 'stopping'],+ ['pending', 'starting'],+ ['waking', 'starting'],+ ['running', 'starting'],+ ['failed', 'failed'],+ ['deleting', 'deleting'],+ ] as const)('maps an offline %s device to %s', (phase, status) => {+ expect(getManagedDeviceStatus(managed(phase))).toBe(status);+ });++ it.each(['suspended', 'pending', 'waking', 'running'] as const)(+ 'lets a live connection describe a %s device',+ (phase) => {+ expect(getManagedDeviceStatus(managed(phase, { channels: [channel], online: true }))).toBe(+ null,+ );+ },+ );++ it('keeps failed and deleting even while connected', () => {+ const connected = { channels: [channel], online: true };+ expect(getManagedDeviceStatus(managed('failed', connected))).toBe('failed');+ expect(getManagedDeviceStatus(managed('deleting', connected))).toBe('deleting');+ });++ it('keeps the checking state for a restored row', () => {+ expect(getManagedDeviceStatus(managed('suspended', { onlineUnknown: true }))).toBe(null);+ });++ it('ignores a phase on a device the user connected', () => {+ expect(+ getManagedDeviceStatus(managed('suspended', { identitySource: 'machine-id' })),+ ).toBeNull();+ });++ it('falls back to presence when the phase is unknown', () => {+ expect(getManagedDeviceStatus(buildDevice())).toBeNull();+ });+});++describe('presenceDotColor', () => {+ it('uses the managed status color, else the online and offline colors', () => {+ expect(presenceDotColor('sleeping', true)).toBe(managedStatusColor.sleeping);+ expect(presenceDotColor(null, true)).toBe(cssVar.colorSuccess);+ expect(presenceDotColor(null, false)).toBe(cssVar.colorTextQuaternary);+ });+});++describe('useDeviceActivityText for a managed device', () => {+ const text = (device: DeviceListItem) =>+ renderHook(() => useDeviceActivityText(device)).result.current;++ it('says a sleeping device wakes on demand instead of when it last connected', () => {+ expect(text(managed('suspended'))).toBe('devices.managed.status.sleepingHint');+ });++ it('says a waking device is starting', () => {+ expect(text(managed('waking'))).toBe('devices.managed.status.starting');+ expect(text(managed('pending'))).toBe('devices.managed.status.starting');+ });++ it('shows a failed device as unavailable', () => {+ expect(text(managed('failed'))).toBe('devices.managed.status.failed');+ });++ it('shows an online managed device like any other online device', () => {+ expect(text(managed('running', { channels: [channel], online: true }))).toContain(+ 'devices.status.online',+ );+ });++ it('shows the last connection when the phase is unknown', () => {+ expect(text(buildDevice())).toBe('devices.lastSeen');+ });+});diff --git a/src/features/DeviceManager/managedDeviceStatus.ts b/src/features/DeviceManager/managedDeviceStatus.tsnew file mode 100644index 00000000000..857aef742e7--- /dev/null+++ b/src/features/DeviceManager/managedDeviceStatus.ts@@ -0,0 +1,90 @@+import type { DeviceListItem } from '@lobechat/types';+import { isManagedCloudDevice } from '@lobechat/types';+import { cssVar } from '@lobehub/ui';++/**+ * What a managed cloud device is doing when its connection alone does not say+ * it. An offline managed device is usually asleep, not broken, so it shows its+ * provider phase instead of a bare "Offline".+ */+export type ManagedDeviceStatus = 'deleting' | 'failed' | 'sleeping' | 'starting' | 'stopping';++type ManagedStatusInput = Pick<+ DeviceListItem,+ 'channels' | 'identitySource' | 'managedPhase' | 'onlineUnknown'+>;++/**+ * The phase-driven status of a managed cloud device, or `null` when the+ * ordinary presence (online / offline / checking) describes it. A live+ * connection wins over every phase except the two that end the device:+ * `failed` and `deleting`.+ */+export const getManagedDeviceStatus = (device: ManagedStatusInput): ManagedDeviceStatus | null => {+ if (!isManagedCloudDevice(device) || !device.managedPhase) return null;++ switch (device.managedPhase) {+ case 'failed': {+ return 'failed';+ }+ case 'deleting': {+ return 'deleting';+ }+ }++ // A row restored from the persisted list has unknown presence: keep the+ // "checking" state until a fresh list confirms the connection.+ if (device.onlineUnknown || (device.channels ?? []).length > 0) return null;++ switch (device.managedPhase) {+ case 'suspended': {+ return 'sleeping';+ }+ case 'suspending': {+ return 'stopping';+ }+ // `running` without a connection: the device is up and its agent has not+ // connected yet.+ case 'pending':+ case 'running':+ case 'waking': {+ return 'starting';+ }+ }+};++/** Short status label (detail page, status pill, hover panel). */+export const managedStatusLabelKey = {+ deleting: 'devices.managed.status.deleting',+ failed: 'devices.managed.status.failed',+ sleeping: 'devices.managed.status.sleeping',+ starting: 'devices.managed.status.starting',+ stopping: 'devices.managed.status.stopping',+} as const satisfies Record<ManagedDeviceStatus, string>;++/** Presence-dot color: sleeping stays calm, starting reads as in progress, failed as an error. */+export const managedStatusColor: Record<ManagedDeviceStatus, string> = {+ deleting: cssVar.colorTextQuaternary,+ failed: cssVar.colorError,+ sleeping: cssVar.colorInfo,+ starting: cssVar.colorWarning,+ stopping: cssVar.colorInfo,+};++/**+ * Color of a device's presence dot: its managed status color when it has one,+ * else green when online and grey when offline.+ */+export const presenceDotColor = (managedStatus: ManagedDeviceStatus | null, online: boolean) => {+ if (managedStatus) return managedStatusColor[managedStatus];+ return online ? cssVar.colorSuccess : cssVar.colorTextQuaternary;+};++/** Status-pill background matching {@link managedStatusColor}. */+export const managedStatusBackground: Record<ManagedDeviceStatus, string> = {+ deleting: cssVar.colorFillTertiary,+ failed: cssVar.colorErrorBg,+ sleeping: cssVar.colorInfoBg,+ starting: cssVar.colorWarningBg,+ stopping: cssVar.colorInfoBg,+};diff --git a/src/features/DeviceManager/useDeviceActivityText.ts b/src/features/DeviceManager/useDeviceActivityText.tsindex f11bce8c3d3..a9079339f69 100644--- a/src/features/DeviceManager/useDeviceActivityText.ts+++ b/src/features/DeviceManager/useDeviceActivityText.ts@@ -2,6 +2,8 @@ import type { DeviceListItem } from '@lobechat/types';import dayjs from 'dayjs';import { useTranslation } from 'react-i18next';+import { getManagedDeviceStatus, managedStatusLabelKey } from './managedDeviceStatus';+/*** A device's presence as one line — "Online · Connected 5 minutes ago" or* "Last connected 2 days ago". Shared by the device card footer and the@@ -22,11 +24,19 @@ import { useTranslation } from 'react-i18next';** A row restored from the persisted list (`onlineUnknown`) has no channels by* construction, so it reads as "checking" rather than as offline.+ *+ * A managed cloud device reports its phase instead when the connection does+ * not explain it: a sleeping one says it wakes on demand rather than showing+ * when it last connected.*/export const useDeviceActivityText = (device: DeviceListItem) => {const { t } = useTranslation('setting');const channels = device.channels ?? [];+ const managedStatus = getManagedDeviceStatus(device);+ if (managedStatus === 'sleeping') return t('devices.managed.status.sleepingHint');+ if (managedStatus) return t(managedStatusLabelKey[managedStatus]);+if (device.onlineUnknown) return t('devices.status.checking');if (channels.length === 0)