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): add the managed cloud device contract (#22269)

Nekoa055c93dc706
diff --git a/apps/server/src/router-hono/device/handlers/__tests__/managedDeviceToken.test.ts b/apps/server/src/router-hono/device/handlers/__tests__/managedDeviceToken.test.ts
new file mode 100644
index 00000000000..4d7c5f4e5e8
--- /dev/null
+++ b/apps/server/src/router-hono/device/handlers/__tests__/managedDeviceToken.test.ts
@@ -0,0 +1,119 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as managedDeviceModule from '@/business/server/managedDevice';
+
+import app from '../../index';
+
+type ManagedDeviceModule = typeof managedDeviceModule;
+
+const mocks = vi.hoisted(() => ({
+ exchange: vi.fn(),
+ isAvailable: vi.fn(),
+}));
+
+vi.mock('@/business/server/managedDevice', async (importOriginal) => {
+ const actual = await importOriginal<ManagedDeviceModule>();
+ return {
+ ...actual,
+ exchangeManagedDeviceToken: mocks.exchange,
+ managedDeviceProvider: {
+ ...actual.managedDeviceProvider,
+ isAvailable: mocks.isAvailable,
+ },
+ };
+});
+
+const post = (body: unknown) =>
+ app.request('/api/device/managed/token', {
+ body: typeof body === 'string' ? body : JSON.stringify(body),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ });
+
+const credentials = { deviceId: 'managed-device-1', secret: 'bootstrap-secret' };
+
+const makeAvailable = () => mocks.isAvailable.mockReturnValue(true);
+
+beforeEach(async () => {
+ vi.restoreAllMocks();
+ // Start every test from the open-source defaults.
+ const actual = await vi.importActual<ManagedDeviceModule>('@/business/server/managedDevice');
+ mocks.isAvailable.mockReset().mockImplementation(actual.managedDeviceProvider.isAvailable);
+ mocks.exchange.mockReset().mockImplementation(actual.exchangeManagedDeviceToken);
+});
+
+describe('POST /api/device/managed/token', () => {
+ it('answers 404 with the open-source defaults', async () => {
+ const response = await post(credentials);
+
+ expect(response.status).toBe(404);
+ expect(response.headers.get('Cache-Control')).toBe('no-store');
+ });
+
+ it('answers 404 when the exchange reports the capability unavailable', async () => {
+ makeAvailable();
+
+ expect((await post(credentials)).status).toBe(404);
+ expect(mocks.exchange).toHaveBeenCalledWith(credentials);
+ });
+
+ it('rejects a malformed body without calling the exchange', async () => {
+ makeAvailable();
+
+ expect((await post('not json')).status).toBe(400);
+ expect((await post({ deviceId: '', secret: 'x' })).status).toBe(400);
+ expect((await post({ deviceId: 'managed-device-1' })).status).toBe(400);
+ expect((await post({ ...credentials, deviceId: 'x'.repeat(65) })).status).toBe(400);
+ expect(mocks.exchange).not.toHaveBeenCalled();
+ });
+
+ it('refuses an oversized body', async () => {
+ makeAvailable();
+
+ const response = await post({ ...credentials, padding: 'x'.repeat(32 * 1024) });
+
+ expect(response.status).toBe(413);
+ expect(response.headers.get('Cache-Control')).toBe('no-store');
+ expect(mocks.exchange).not.toHaveBeenCalled();
+ });
+
+ it('returns the issued token', async () => {
+ makeAvailable();
+ mocks.exchange.mockResolvedValue({
+ expiresAt: '2030-01-01T00:00:00.000Z',
+ status: 'issued',
+ token: 'signed-token',
+ });
+
+ const response = await post(credentials);
+
+ expect(mocks.exchange).toHaveBeenCalledWith(credentials);
+ expect(response.status).toBe(200);
+ expect(response.headers.get('Cache-Control')).toBe('no-store');
+ expect(await response.json()).toEqual({
+ expiresAt: '2030-01-01T00:00:00.000Z',
+ token: 'signed-token',
+ });
+ });
+
+ it('answers 401 when the credentials do not match', async () => {
+ makeAvailable();
+ mocks.exchange.mockResolvedValue({
+ status: 'invalid-credentials',
+ });
+
+ expect((await post(credentials)).status).toBe(401);
+ });
+
+ it('answers 500 without details when the exchange fails', async () => {
+ makeAvailable();
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ mocks.exchange.mockRejectedValue(new Error('boom'));
+
+ const response = await post(credentials);
+
+ expect(response.status).toBe(500);
+ expect(JSON.stringify(await response.json())).not.toContain('boom');
+ });
+});
diff --git a/apps/server/src/router-hono/device/handlers/managedDeviceToken.ts b/apps/server/src/router-hono/device/handlers/managedDeviceToken.ts
new file mode 100644
index 00000000000..0a40958df1c
--- /dev/null
+++ b/apps/server/src/router-hono/device/handlers/managedDeviceToken.ts
@@ -0,0 +1,51 @@
+import type { Context } from 'hono';
+import { z } from 'zod';
+
+import { exchangeManagedDeviceToken, managedDeviceProvider } from '@/business/server/managedDevice';
+
+const requestSchema = z.object({
+ // Same bound as `devices.device_id`.
+ deviceId: z.string().trim().min(1).max(64),
+ secret: z.string().min(1).max(1024),
+});
+
+export const NO_STORE = { 'Cache-Control': 'no-store' };
+
+/**
+ * POST /api/device/managed/token — a managed cloud device trades its device id
+ * and secret for a short-lived device-gateway token.
+ *
+ * Body `{ deviceId, secret }` → 200 `{ token, expiresAt }`; 400 on a malformed
+ * body; 401 when the credentials do not match; 404 when this deployment does
+ * not offer managed devices.
+ */
+export async function managedDeviceToken(c: Context): Promise<Response> {
+ if (!managedDeviceProvider.isAvailable()) {
+ return c.json({ error: 'Not found' }, 404, NO_STORE);
+ }
+
+ const body = await c.req.json().catch(() => undefined);
+ const parsed = requestSchema.safeParse(body);
+ if (!parsed.success) {
+ return c.json({ error: 'Invalid request body' }, 400, NO_STORE);
+ }
+
+ try {
+ const result = await exchangeManagedDeviceToken(parsed.data);
+
+ switch (result.status) {
+ case 'issued': {
+ return c.json({ expiresAt: result.expiresAt, token: result.token }, 200, NO_STORE);
+ }
+ case 'invalid-credentials': {
+ return c.json({ error: 'Invalid device credentials' }, 401, NO_STORE);
+ }
+ case 'unavailable': {
+ return c.json({ error: 'Not found' }, 404, NO_STORE);
+ }
+ }
+ } catch (error) {
+ console.error('[managedDeviceToken] Failed to exchange managed device token:', error);
+ return c.json({ error: 'Failed to issue token' }, 500, NO_STORE);
+ }
+}
diff --git a/apps/server/src/router-hono/device/index.ts b/apps/server/src/router-hono/device/index.ts
new file mode 100644
index 00000000000..87c99d9d779
--- /dev/null
+++ b/apps/server/src/router-hono/device/index.ts
@@ -0,0 +1,26 @@
+import { Hono } from 'hono';
+import { bodyLimit } from 'hono/body-limit';
+
+import { managedDeviceToken, NO_STORE } from './handlers/managedDeviceToken';
+
+/**
+ * Hono app for `/api/device/*` endpoints called by devices themselves, outside
+ * a user session. Each path has its own Next.js route shell under
+ * `src/app/(backend)/api/device`.
+ */
+const MAX_BODY_BYTES = 16 * 1024;
+
+const app = new Hono().basePath('/api/device');
+
+app.use(
+ '*',
+ bodyLimit({
+ maxSize: MAX_BODY_BYTES,
+ onError: (c) => c.json({ error: 'Request body is too large' }, 413, NO_STORE),
+ }),
+);
+
+// POST /api/device/managed/token — managed cloud device credential exchange
+app.post('/managed/token', managedDeviceToken);
+
+export default app;
diff --git a/apps/server/src/router-hono/index.ts b/apps/server/src/router-hono/index.ts
index 3f123619e73..53f06604acb 100644
--- a/apps/server/src/router-hono/index.ts
+++ b/apps/server/src/router-hono/index.ts
@@ -2,6 +2,7 @@ import type { Context } from 'hono';
import { Hono } from 'hono';
import acceptanceReview from './acceptance-review';
+import device from './device';
const app = new Hono();
@@ -22,6 +23,7 @@ app.get('/health', (c) =>
app.all('/api/agent', (c) => fetchWith(c, () => import('./agent')));
app.all('/api/agent/*', (c) => fetchWith(c, () => import('./agent')));
app.all('/api/acceptance-review/*', (c) => acceptanceReview.fetch(c.req.raw));
+app.all('/api/device/managed/*', (c) => device.fetch(c.req.raw));
app.all('/api/workflows', (c) => fetchWith(c, () => import('./workflows')));
app.all('/api/workflows/*', (c) => fetchWith(c, () => import('./workflows')));
diff --git a/apps/server/src/routers/lambda/device/index.businessSlot.test.ts b/apps/server/src/routers/lambda/device/index.businessSlot.test.ts
new file mode 100644
index 00000000000..b43cd4d7de4
--- /dev/null
+++ b/apps/server/src/routers/lambda/device/index.businessSlot.test.ts
@@ -0,0 +1,24 @@
+// @vitest-environment node
+import { describe, expect, it, vi } from 'vitest';
+
+import type * as lambdaTrpc from '@/libs/trpc/lambda';
+
+import { deviceRouter } from '.';
+
+vi.mock('@/business/server/lambda-routers/device', async () => {
+ const { publicProcedure, router } =
+ await vi.importActual<typeof lambdaTrpc>('@/libs/trpc/lambda');
+ return {
+ businessDeviceRouter: router({
+ businessSlotProbe: publicProcedure.query(() => 'probe'),
+ }),
+ };
+});
+
+describe('deviceRouter business slot', () => {
+ it('merges the procedures of the business device router', () => {
+ const procedures = (deviceRouter as any)._def.procedures as Record<string, any>;
+
+ expect(procedures.businessSlotProbe?._def.type).toBe('query');
+ });
+});
diff --git a/apps/server/src/routers/lambda/device/index.ts b/apps/server/src/routers/lambda/device/index.ts
index fa6d5b2a2f1..671e7f75a98 100644
--- a/apps/server/src/routers/lambda/device/index.ts
+++ b/apps/server/src/routers/lambda/device/index.ts
@@ -1,3 +1,4 @@
+import { businessDeviceRouter } from '@/business/server/lambda-routers/device';
import { mergeRouters, router } from '@/libs/trpc/lambda';
import { workspaceDeviceWorkingDirProcedures } from '../deviceWorkspaceWorkingDirs';
@@ -18,4 +19,5 @@ export const deviceRouter = mergeRouters(
router({
...workspaceDeviceWorkingDirProcedures,
}),
+ businessDeviceRouter,
);
diff --git a/apps/server/src/routers/lambda/device/managedDeviceRemoval.ts b/apps/server/src/routers/lambda/device/managedDeviceRemoval.ts
new file mode 100644
index 00000000000..2bd5a74784c
--- /dev/null
+++ b/apps/server/src/routers/lambda/device/managedDeviceRemoval.ts
@@ -0,0 +1,31 @@
+import { isManagedCloudDevice } from '@lobechat/types';
+
+import { onManagedDeviceRemoved } from '@/business/server/managedDevice';
+import type { DeviceItem } from '@/database/schemas';
+
+type RemovedDevice = Pick<DeviceItem, 'deviceId' | 'identitySource' | 'userId' | 'workspaceId'>;
+
+/**
+ * Report each removed managed cloud device to the deployment. Call it after
+ * the rows are deleted. A hook failure is logged and never fails the removal.
+ */
+export const reportManagedDevicesRemoved = async (
+ removed: RemovedDevice[] | undefined,
+): Promise<void> => {
+ for (const row of removed ?? []) {
+ if (!isManagedCloudDevice(row)) continue;
+
+ try {
+ await onManagedDeviceRemoved({
+ deviceId: row.deviceId,
+ userId: row.userId,
+ ...(row.workspaceId ? { workspaceId: row.workspaceId } : {}),
+ });
+ } catch (error) {
+ console.error('[device] Failed to report a removed managed device:', {
+ deviceId: row.deviceId,
+ error,
+ });
+ }
+ }
+};
diff --git a/apps/server/src/routers/lambda/device/registry.ts b/apps/server/src/routers/lambda/device/registry.ts
index 9b393f0900a..394eccb6036 100644
--- a/apps/server/src/routers/lambda/device/registry.ts
+++ b/apps/server/src/routers/lambda/device/registry.ts
@@ -19,6 +19,7 @@ import { filterAuthorizedDevicePresence } from '@/server/services/deviceGateway/
import { loadAgentDeviceBindings, loadDeviceBoundAgents } from '../deviceBoundAgents';
import { preserveWorkspaceCache } from '../deviceWorkingDirs';
+import { reportManagedDevicesRemoved } from './managedDeviceRemoval';
import { deviceProcedure } from './procedures';
/**
@@ -371,7 +372,8 @@ export const registryRouter = router({
removeDevice: deviceProcedure
.input(z.object({ deviceId: z.string() }))
.mutation(async ({ ctx, input }) => {
- await ctx.deviceModel.delete(input.deviceId);
+ const removed = await ctx.deviceModel.delete(input.deviceId);
+ await reportManagedDevicesRemoved(removed);
return { success: true };
}),
status: deviceProcedure.query(async ({ ctx }) => {
diff --git a/apps/server/src/routers/lambda/device/remove.managedDevice.test.ts b/apps/server/src/routers/lambda/device/remove.managedDevice.test.ts
new file mode 100644
index 00000000000..314b5ba5aaa
--- /dev/null
+++ b/apps/server/src/routers/lambda/device/remove.managedDevice.test.ts
@@ -0,0 +1,158 @@
+// @vitest-environment node
+import { MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { registryRouter } from './registry';
+import { workspaceRouter } from './workspace';
+
+const mocks = vi.hoisted(() => ({
+ delete: vi.fn(),
+ deleteWorkspaceDevice: vi.fn(),
+ findWorkspaceDeviceById: vi.fn(),
+ hasFixedAgentBinding: vi.fn(),
+ onManagedDeviceRemoved: vi.fn(),
+}));
+
+vi.mock('@/business/server/managedDevice', () => ({
+ onManagedDeviceRemoved: mocks.onManagedDeviceRemoved,
+}));
+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {
+ const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');
+ return {
+ requireWorkspaceRole: () => mod.trpc.middleware(async (opts: any) => opts.next()),
+ wsCompatProcedure: mod.trpc.procedure,
+ wsProcedure: mod.trpc.procedure,
+ };
+});
+vi.mock('@/libs/trpc/lambda/middleware', () => ({
+ serverDatabase: async (opts: any) => opts.next({ ctx: { ...opts.ctx, serverDB: {} } }),
+}));
+vi.mock('@/database/models/device', () => ({
+ DeviceModel: class {
+ delete = mocks.delete;
+ deleteWorkspaceDevice = mocks.deleteWorkspaceDevice;
+ findWorkspaceDeviceById = mocks.findWorkspaceDeviceById;
+ hasFixedAgentBinding = mocks.hasFixedAgentBinding;
+ },
+ WorkspaceDevicePrivateConflictError: class extends Error {},
+}));
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: {
+ queryDeviceList: vi.fn().mockResolvedValue([]),
+ unenrollWorkspace: vi.fn().mockResolvedValue({ success: true }),
+ },
+}));
+
+const row = (identitySource: string, workspaceId: string | null) => ({
+ deviceId: 'device-1',
+ identitySource,
+ userId: 'user-1',
+ workspaceId,
+});
+
+const personalCaller = () => registryRouter.createCaller({ userId: 'user-1' } as never);
+const workspaceCaller = () =>
+ workspaceRouter.createCaller({
+ userId: 'user-1',
+ workspaceId: 'workspace-1',
+ workspaceRole: 'owner',
+ } as never);
+
+describe('removing a managed cloud device', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.onManagedDeviceRemoved.mockResolvedValue(undefined);
+ mocks.findWorkspaceDeviceById.mockResolvedValue(row('machine-id', 'workspace-1'));
+ mocks.hasFixedAgentBinding.mockResolvedValue(false);
+ });
+
+ it('reports a removed personal managed device after deleting it', async () => {
+ mocks.delete.mockResolvedValue([row(MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE, null)]);
+
+ await expect(personalCaller().removeDevice({ deviceId: 'device-1' })).resolves.toEqual({
+ success: true,
+ });
+
+ expect(mocks.delete).toHaveBeenCalledWith('device-1');
+ expect(mocks.onManagedDeviceRemoved).toHaveBeenCalledExactlyOnceWith({
+ deviceId: 'device-1',
+ userId: 'user-1',
+ });
+ expect(mocks.delete.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.onManagedDeviceRemoved.mock.invocationCallOrder[0],
+ );
+ });
+
+ it('does not report a removed connected device', async () => {
+ mocks.delete.mockResolvedValue([row('machine-id', null)]);
+
+ await personalCaller().removeDevice({ deviceId: 'device-1' });
+
+ expect(mocks.onManagedDeviceRemoved).not.toHaveBeenCalled();
+ });
+
+ it('keeps the personal removal successful when the hook fails', async () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ mocks.delete.mockResolvedValue([row(MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE, null)]);
+ mocks.onManagedDeviceRemoved.mockRejectedValue(new Error('hook failed'));
+
+ await expect(personalCaller().removeDevice({ deviceId: 'device-1' })).resolves.toEqual({
+ success: true,
+ });
+ expect(consoleError).toHaveBeenCalledOnce();
+ consoleError.mockRestore();
+ });
+
+ it('reports a removed workspace managed device with its workspace', async () => {
+ mocks.deleteWorkspaceDevice.mockResolvedValue([
+ row(MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE, 'workspace-1'),
+ ]);
+
+ await expect(
+ workspaceCaller().removeWorkspaceDevice({ deviceId: 'device-1' }),
+ ).resolves.toEqual({ success: true });
+
+ expect(mocks.deleteWorkspaceDevice).toHaveBeenCalledWith('device-1');
+ expect(mocks.onManagedDeviceRemoved).toHaveBeenCalledExactlyOnceWith({
+ deviceId: 'device-1',
+ userId: 'user-1',
+ workspaceId: 'workspace-1',
+ });
+ });
+
+ it('reports the enrolling member when an owner removes their workspace device', async () => {
+ mocks.deleteWorkspaceDevice.mockResolvedValue([
+ { ...row(MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE, 'workspace-1'), userId: 'enroller-1' },
+ ]);
+
+ await workspaceCaller().removeWorkspaceDevice({ deviceId: 'device-1' });
+
+ expect(mocks.onManagedDeviceRemoved).toHaveBeenCalledExactlyOnceWith({
+ deviceId: 'device-1',
+ userId: 'enroller-1',
+ workspaceId: 'workspace-1',
+ });
+ });
+
+ it('does not report a removed connected workspace device', async () => {
+ mocks.deleteWorkspaceDevice.mockResolvedValue([row('machine-id', 'workspace-1')]);
+
+ await workspaceCaller().removeWorkspaceDevice({ deviceId: 'device-1' });
+
+ expect(mocks.onManagedDeviceRemoved).not.toHaveBeenCalled();
+ });
+
+ it('keeps the workspace removal successful when the hook fails', async () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ mocks.deleteWorkspaceDevice.mockResolvedValue([
+ row(MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE, 'workspace-1'),
+ ]);
+ mocks.onManagedDeviceRemoved.mockRejectedValue(new Error('hook failed'));
+
+ await expect(
+ workspaceCaller().removeWorkspaceDevice({ deviceId: 'device-1' }),
+ ).resolves.toEqual({ success: true });
+ expect(consoleError).toHaveBeenCalledOnce();
+ consoleError.mockRestore();
+ });
+});
diff --git a/apps/server/src/routers/lambda/device/workspace.ts b/apps/server/src/routers/lambda/device/workspace.ts
index c2a789d060a..dbc52cc9cfb 100644
--- a/apps/server/src/routers/lambda/device/workspace.ts
+++ b/apps/server/src/routers/lambda/device/workspace.ts
@@ -15,6 +15,7 @@ import { deviceGateway } from '@/server/services/deviceGateway';
import { preserveWorkspaceCache } from '../deviceWorkingDirs';
import { assertWorkspaceDeviceEditable, canEditWorkspaceDevice } from '../deviceWorkspaceGuard';
+import { reportManagedDevicesRemoved } from './managedDeviceRemoval';
/**
* Fixed workspace agents promise every member the same execution device. Keep
@@ -378,7 +379,8 @@ export const workspaceRouter = router({
});
}
}
- await model.deleteWorkspaceDevice(input.deviceId);
+ const removed = await model.deleteWorkspaceDevice(input.deviceId);
+ await reportManagedDevicesRemoved(removed);
return { success: true };
}),
});
diff --git a/apps/server/src/routers/lambda/document.test.ts b/apps/server/src/routers/lambda/document.test.ts
index a44f6a3e521..d4b1ca10007 100644
--- a/apps/server/src/routers/lambda/document.test.ts
+++ b/apps/server/src/routers/lambda/document.test.ts
@@ -250,7 +250,7 @@ describe('HTML document writes', () => {
* the body H1. Only agent documents dropped that heading.
*/
describe('Markdown writes drop the heading that repeats the title', () => {
- const title = 'rc 与 device — 讨论纪要(2026-10-20)';
+ const title = '集群与设备 — 讨论纪要(2026-10-20)';
const content = `# ${title}\n\n来源:eval 频道\n`;
beforeEach(() => {
diff --git a/apps/server/src/services/document/editorData.test.ts b/apps/server/src/services/document/editorData.test.ts
index c836cf2d82a..b443bd686a8 100644
--- a/apps/server/src/services/document/editorData.test.ts
+++ b/apps/server/src/services/document/editorData.test.ts
@@ -71,8 +71,8 @@ describe('resolveDocumentWrite', () => {
it('drops the heading that repeats the title from a Markdown write and its editorData', async () => {
const write = await resolveDocumentWrite({
- content: '# rc 与 device — 讨论纪要\n\n来源:eval 频道\n',
- title: 'rc 与 device — 讨论纪要',
+ content: '# 集群与设备 — 讨论纪要\n\n来源:eval 频道\n',
+ title: '集群与设备 — 讨论纪要',
});
expect(write.content).toBe('来源:eval 频道\n');
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index d5d634d4088..81e3989c526 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -553,6 +553,24 @@
"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.create.button": "Create in cloud",
+ "devices.managed.create.class.label": "Size",
+ "devices.managed.create.class.notIncluded": "Not in your plan",
+ "devices.managed.create.class.placeholder": "Choose a size",
+ "devices.managed.create.desc": "LobeHub runs this device in the cloud for you. It sleeps when idle and wakes when an agent needs it.",
+ "devices.managed.create.failed": "Could not create the cloud device. Try again.",
+ "devices.managed.create.forbidden": "Only workspace members who can add devices can create a cloud device.",
+ "devices.managed.create.loadFailed": "Could not load the cloud device options. Try again.",
+ "devices.managed.create.name.label": "Name",
+ "devices.managed.create.name.placeholder": "My cloud device",
+ "devices.managed.create.noClass": "Your plan includes no cloud device size.",
+ "devices.managed.create.notIncluded": "Your plan does not include cloud devices.",
+ "devices.managed.create.quota": "{{count}} of {{limit}} cloud devices used",
+ "devices.managed.create.quotaExceeded": "You already have {{count}} of {{limit}} cloud devices. Remove one to create another.",
+ "devices.managed.create.quotaRefused": "Your plan does not allow another cloud device right now.",
+ "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.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.json
index 95beea7be3e..ba357a59d3b 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -553,6 +553,24 @@
"devices.keepAwake.desc": "作为设备连接期间阻止电脑自动睡眠,保证它始终可被访问。屏幕仍可正常关闭;未连接外接显示器时合上笔记本屏幕仍会睡眠。",
"devices.keepAwake.title": "连接期间保持唤醒",
"devices.lastSeen": "最后连接于 {{time}}",
+ "devices.managed.create.button": "在云端创建",
+ "devices.managed.create.class.label": "规格",
+ "devices.managed.create.class.notIncluded": "当前套餐不包含",
+ "devices.managed.create.class.placeholder": "选择规格",
+ "devices.managed.create.desc": "LobeHub 在云端为你运行这台设备。空闲时自动休眠,智能体需要时自动唤醒。",
+ "devices.managed.create.failed": "无法创建云端设备,请重试。",
+ "devices.managed.create.forbidden": "只有可以添加设备的工作区成员才能创建云端设备。",
+ "devices.managed.create.loadFailed": "无法加载云端设备选项,请重试。",
+ "devices.managed.create.name.label": "名称",
+ "devices.managed.create.name.placeholder": "我的云端设备",
+ "devices.managed.create.noClass": "当前套餐没有可用的云端设备规格。",
+ "devices.managed.create.notIncluded": "当前套餐不包含云端设备。",
+ "devices.managed.create.quota": "已使用 {{count}} / {{limit}} 台云端设备",
+ "devices.managed.create.quotaExceeded": "你已有 {{count}} / {{limit}} 台云端设备。移除一台后才能再创建。",
+ "devices.managed.create.quotaRefused": "当前套餐暂不允许再创建云端设备。",
+ "devices.managed.create.submit": "创建",
+ "devices.managed.create.success": "云端设备已创建,约一分钟后启动。",
+ "devices.managed.create.title": "创建云端设备",
"devices.remove.confirm": "移除此设备?",
"devices.remove.confirmDesc": "这会断开设备与你账户的关联,但不会让设备登出,下次连接时它可重新注册。",
"devices.remove.currentSessionWarning": "其中包含你当前正在使用的设备,移除后会断开当前会话。",
diff --git a/packages/app-config/src/featureFlags/schema.test.ts b/packages/app-config/src/featureFlags/schema.test.ts
index 9366d9e581f..ef54d0674e4 100644
--- a/packages/app-config/src/featureFlags/schema.test.ts
+++ b/packages/app-config/src/featureFlags/schema.test.ts
@@ -332,6 +332,35 @@ describe('mapFeatureFlagsEnvToState', () => {
expect(mapFeatureFlagsEnvToState(config).enableChannels).toBe(false);
});
+ it('should keep managed cloud device creation off by default and enable it per user or globally', () => {
+ expect(DEFAULT_FEATURE_FLAGS.managed_cloud_device).toBe(false);
+ expect(
+ mapFeatureFlagsEnvToState(DEFAULT_FEATURE_FLAGS, 'user-1').enableManagedCloudDevice,
+ ).toBe(false);
+
+ expect(mapFeatureFlagsEnvToState({ managed_cloud_device: true }).enableManagedCloudDevice).toBe(
+ true,
+ );
+
+ const config = { managed_cloud_device: ['user-123'] };
+ expect(mapFeatureFlagsEnvToState(config, 'user-123').enableManagedCloudDevice).toBe(true);
+ expect(mapFeatureFlagsEnvToState(config, 'user-456').enableManagedCloudDevice).toBe(false);
+ expect(mapFeatureFlagsEnvToState(config).enableManagedCloudDevice).toBe(false);
+ });
+
+ it('should keep allowlisted users on while managed cloud device creation rolls out', () => {
+ const allowlistOnly = { managed_cloud_device: ['rollout:0', 'user-123'] };
+ expect(mapFeatureFlagsEnvToState(allowlistOnly, 'user-123').enableManagedCloudDevice).toBe(
+ true,
+ );
+ expect(mapFeatureFlagsEnvToState(allowlistOnly, 'user-456').enableManagedCloudDevice).toBe(
+ false,
+ );
+
+ const everyone = { managed_cloud_device: ['rollout:100', 'user-123'] };
+ expect(mapFeatureFlagsEnvToState(everyone, 'user-456').enableManagedCloudDevice).toBe(true);
+ });
+
it('should correctly map boolean feature flags to state', () => {
const config = {
provider_settings: true,
diff --git a/packages/app-config/src/featureFlags/schema.ts b/packages/app-config/src/featureFlags/schema.ts
index 19433d8c57b..89ed77bd34a 100644
--- a/packages/app-config/src/featureFlags/schema.ts
+++ b/packages/app-config/src/featureFlags/schema.ts
@@ -80,6 +80,14 @@ export const FeatureFlagsSchema = z.object({
*/
channel: FeatureFlagValue.optional(),
+ /**
+ * Rollout gate for creating managed cloud devices: the "Create in cloud" entry on the device
+ * list and every API that creates one or sets who can create one. Off: the entry does not render
+ * and those APIs refuse the call. Managed devices that already exist keep working: they list,
+ * wake, connect and can be removed. Array values are user ids, checked per member.
+ */
+ managed_cloud_device: FeatureFlagValue.optional(),
+
topic_preview: FeatureFlagValue.optional(),
// internal flag
@@ -191,6 +199,9 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {
// Off until an admin publishes a user allowlist or flips it to true.
channel: false,
+ // Off until an admin publishes a user allowlist or flips it to true.
+ managed_cloud_device: false,
+
// Off until the backend replaces the preview read; allowlist first.
topic_preview: false,
@@ -237,6 +248,11 @@ export const mapFeatureFlagsEnvToState = (
enableDashboard: evaluateFeatureFlag(config.dashboard, userId, 'dashboard'),
enableImLayout: evaluateFeatureFlag(config.im_layout, userId, 'im_layout'),
enableChannels: evaluateFeatureFlag(config.channel, userId, 'channel'),
+ enableManagedCloudDevice: evaluateFeatureFlag(
+ config.managed_cloud_device,
+ userId,
+ 'managed_cloud_device',
+ ),
enableTopicPreview: evaluateFeatureFlag(config.topic_preview, userId, 'topic_preview'),
showProvider: evaluateFeatureFlag(config.provider_settings, userId, 'provider_settings'),
diff --git a/packages/business-server/src/lambda-routers/device.ts b/packages/business-server/src/lambda-routers/device.ts
new file mode 100644
index 00000000000..908a0edd28b
--- /dev/null
+++ b/packages/business-server/src/lambda-routers/device.ts
@@ -0,0 +1,8 @@
+import { router } from '@/libs/trpc/lambda';
+
+/**
+ * Extra procedures merged into the lambda `device` router. Empty in the
+ * open-source build; downstream builds override this module through their own
+ * `@/business/server/...` mapping.
+ */
+export const businessDeviceRouter = router({});
diff --git a/packages/business-server/src/managedDevice.ts b/packages/business-server/src/managedDevice.ts
new file mode 100644
index 00000000000..d29c940cae8
--- /dev/null
+++ b/packages/business-server/src/managedDevice.ts
@@ -0,0 +1,78 @@
+import type { ManagedDevicePhase } from '@lobechat/types';
+
+/**
+ * Managed cloud devices are devices the platform creates and runs in the
+ * cloud. The open-source build has none, so every default below answers as if
+ * the capability does not exist. A deployment that offers managed devices
+ * overrides this module through its own `@/business/server/...` mapping.
+ */
+
+/** Whose managed devices a call is about: a person, or a workspace they act in. */
+export interface ManagedDeviceScope {
+ userId: string;
+ /** Set for a workspace device. Not set for a personal device. */
+ workspaceId?: string;
+}
+
+export interface ManagedDeviceProvider {
+ /** Whether this deployment offers managed cloud devices at all. */
+ isAvailable: () => boolean;
+ /** Phases of the caller's managed devices, keyed by `devices.deviceId`. */
+ listStates: (scope: ManagedDeviceScope) => Promise<Record<string, ManagedDevicePhase>>;
+ /**
+ * Ask a managed device to run. Resolves when the request is accepted, not
+ * when the device is online. Callers watch device presence for that.
+ */
+ wake: (scope: ManagedDeviceScope, deviceId: string) => Promise<void>;
+}
+
+export const managedDeviceProvider: ManagedDeviceProvider = {
+ isAvailable: () => false,
+ listStates: async () => ({}),
+ wake: async () => {},
+};
+
+/** Credentials a managed device presents to get its device-gateway token. */
+export interface ManagedDeviceTokenRequest {
+ deviceId: string;
+ secret: string;
+}
+
+export type ManagedDeviceTokenResult =
+ /** `expiresAt` is an RFC 3339 timestamp. */
+ | { expiresAt: string; status: 'issued'; token: string }
+ /** The device does not exist or the secret does not match. */
+ | { status: 'invalid-credentials' }
+ /** This deployment does not offer managed devices. */
+ | { status: 'unavailable' };
+
+/**
+ * Exchange a managed device's credentials for a short-lived connect token.
+ * Sign the token with `signManagedDeviceToken` (`@/libs/trpc/utils/internalJwt`).
+ * Server login verifiers reject its `purpose`. A token signed in a different
+ * way can pass as a user login.
+ */
+export const exchangeManagedDeviceToken = async (
+ _request: ManagedDeviceTokenRequest,
+): Promise<ManagedDeviceTokenResult> => ({ status: 'unavailable' });
+
+/**
+ * A managed cloud device whose `devices` row was just deleted. `userId` is the
+ * row's own user (for a workspace device, the member who enrolled it), not
+ * necessarily the member who removed it.
+ */
+export interface ManagedDeviceRemoval extends ManagedDeviceScope {
+ deviceId: string;
+}
+
+/**
+ * Called after a user removes a managed cloud device (`removeDevice`,
+ * `removeWorkspaceDevice`), so the deployment can release whatever backs the
+ * device. The row is already gone when this runs. A rejection is logged and
+ * does not fail the removal. It runs inside the request, so return when the
+ * release is recorded, not when it completes.
+ *
+ * Rows deleted in other ways (a member leaves a workspace, a user or
+ * workspace is deleted) do not call it. The deployment reconciles those.
+ */
+export const onManagedDeviceRemoved = async (_removal: ManagedDeviceRemoval): Promise<void> => {};
diff --git a/packages/database/src/models/__tests__/device.coverage.test.ts b/packages/database/src/models/__tests__/device.coverage.test.ts
index d38be83488d..4a7d8ccf9a8 100644
--- a/packages/database/src/models/__tests__/device.coverage.test.ts
+++ b/packages/database/src/models/__tests__/device.coverage.test.ts
@@ -135,8 +135,10 @@ describe('DeviceModel coverage edges', () => {
});
await workspaceModel.register({ deviceId: 'devcov-shared-id', identitySource: 'machine-id' });
- await workspaceModel.deleteWorkspaceDevice('devcov-shared-id');
+ const removed = await workspaceModel.deleteWorkspaceDevice('devcov-shared-id');
+ expect(removed).toHaveLength(1);
+ expect(removed?.[0]).toMatchObject({ deviceId: 'devcov-shared-id', workspaceId });
const remaining = await serverDB.query.devices.findMany({
where: eq(devices.deviceId, 'devcov-shared-id'),
});
diff --git a/packages/database/src/models/__tests__/device.test.ts b/packages/database/src/models/__tests__/device.test.ts
index 06bff1afa4b..3ff3344619c 100644
--- a/packages/database/src/models/__tests__/device.test.ts
+++ b/packages/database/src/models/__tests__/device.test.ts
@@ -691,11 +691,41 @@ describe('DeviceModel', () => {
it('should remove the row', async () => {
await deviceModel.register({ deviceId: 'dev-1', identitySource: 'machine-id' });
- await deviceModel.delete('dev-1');
+ const removed = await deviceModel.delete('dev-1');
+ expect(removed).toHaveLength(1);
+ expect(removed[0]).toMatchObject({ deviceId: 'dev-1', identitySource: 'machine-id', userId });
const row = await deviceModel.findByDeviceId('dev-1');
expect(row).toBeUndefined();
});
+
+ it('should return nothing when no row matches', async () => {
+ await expect(deviceModel.delete('missing-device')).resolves.toEqual([]);
+ });
+
+ it('should keep a workspace device the user enrolled under the same deviceId', async () => {
+ const deleteWsId = 'device-model-ws-delete';
+ await serverDB
+ .insert(workspaces)
+ .values({ id: deleteWsId, name: 'WS', primaryOwnerId: userId, slug: deleteWsId });
+ await deviceModel.register({ deviceId: 'both', identitySource: 'machine-id' });
+ await serverDB.insert(devices).values({
+ deviceId: 'both',
+ identitySource: 'machine-id',
+ userId,
+ workspaceId: deleteWsId,
+ });
+
+ const removed = await deviceModel.delete('both');
+
+ expect(removed).toHaveLength(1);
+ expect(removed[0].workspaceId).toBeNull();
+ const workspaceRows = await serverDB
+ .select()
+ .from(devices)
+ .where(eq(devices.workspaceId, deleteWsId));
+ expect(workspaceRows.map((row) => row.deviceId)).toEqual(['both']);
+ });
});
describe('mutateWorkspaceDeviceWorkingDirs', () => {
diff --git a/packages/database/src/models/device.ts b/packages/database/src/models/device.ts
index 63263c6ab18..602b7581923 100644
--- a/packages/database/src/models/device.ts
+++ b/packages/database/src/models/device.ts
@@ -353,10 +353,21 @@ export class DeviceModel {
return device;
};
- delete = async (deviceId: string) => {
+ /**
+ * Remove a PERSONAL device. Workspace devices the user enrolled keep their
+ * rows; they go through `deleteWorkspaceDevice`. Returns the removed rows.
+ */
+ delete = async (deviceId: string): Promise<DeviceItem[]> => {
return this.db
.delete(devices)
- .where(and(eq(devices.userId, this.userId), eq(devices.deviceId, deviceId)));
+ .where(
+ and(
+ eq(devices.userId, this.userId),
+ eq(devices.deviceId, deviceId),
+ isNull(devices.workspaceId),
+ ),
+ )
+ .returning();
};
/**
@@ -403,13 +414,15 @@ export class DeviceModel {
/**
* Remove a WORKSPACE device, scoped by `workspace_id`. Permission
* (workspace owner, or the enroller acting on their own device) is enforced
- * at the router via `canEditWorkspaceDevice`.
+ * at the router via `canEditWorkspaceDevice`. Returns the removed rows, or
+ * `undefined` without a current workspace.
*/
- deleteWorkspaceDevice = async (deviceId: string) => {
+ deleteWorkspaceDevice = async (deviceId: string): Promise<DeviceItem[] | undefined> => {
if (!this.workspaceId) return;
return this.db
.delete(devices)
- .where(and(eq(devices.workspaceId, this.workspaceId), eq(devices.deviceId, deviceId)));
+ .where(and(eq(devices.workspaceId, this.workspaceId), eq(devices.deviceId, deviceId)))
+ .returning();
};
/**
diff --git a/packages/database/src/schemas/__tests__/environment.test.ts b/packages/database/src/schemas/__tests__/environment.test.ts
index 78b5a2d2c03..c9a6339b773 100644
--- a/packages/database/src/schemas/__tests__/environment.test.ts
+++ b/packages/database/src/schemas/__tests__/environment.test.ts
@@ -2,6 +2,10 @@
import { readFile } from 'node:fs/promises';
import type { EnvironmentConfiguration } from '@lobechat/types';
+import {
+ MANAGED_CLOUD_CLUSTER_PROVIDER_V1,
+ MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE,
+} from '@lobechat/types';
import { eq, inArray, sql } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -237,7 +241,7 @@ const createDevice = async () => {
};
describe('Environment instances', () => {
- it('materializes the same definition on a device, a sandbox and an rc cluster', async () => {
+ it('materializes the same definition on a device, a sandbox and a cluster', async () => {
const environment = await createEnvironment();
const device = await createDevice();
const common = instanceValues(environment.id);
@@ -255,9 +259,9 @@ describe('Environment instances', () => {
{
...common,
kind: 'cluster',
- provider: 'rc',
- providerScope: 'cluster-1',
- providerResourceId: 'allocation-1',
+ provider: MANAGED_CLOUD_CLUSTER_PROVIDER_V1,
+ providerScope: 'region-1',
+ providerResourceId: 'managed-device-1',
},
])
.returning();
@@ -292,8 +296,8 @@ describe('Environment instances', () => {
db.insert(environmentInstances).values({
...common,
kind: 'cluster',
- provider: 'rc',
- providerScope: 'cluster-1',
+ provider: MANAGED_CLOUD_CLUSTER_PROVIDER_V1,
+ providerScope: 'region-1',
providerResourceId: ' ',
}),
).rejects.toThrow();
@@ -309,6 +313,38 @@ describe('Environment instances', () => {
).rejects.toThrow();
});
+ it('maps a managed cloud device to a cluster instance by its managed device id', async () => {
+ const environment = await createEnvironment();
+ const managedDeviceId = '00000000-0000-4000-8000-000000000001';
+ const [device] = await db
+ .insert(devices)
+ .values({
+ deviceId: managedDeviceId,
+ identitySource: MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE,
+ userId,
+ })
+ .returning();
+ expect(device.identitySource).toBe(MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE);
+
+ const [instance] = await db
+ .insert(environmentInstances)
+ .values({
+ ...instanceValues(environment.id),
+ kind: 'cluster',
+ provider: MANAGED_CLOUD_CLUSTER_PROVIDER_V1,
+ providerScope: 'region-1',
+ providerResourceId: device.deviceId,
+ })
+ .returning();
+ expect(instance).toMatchObject({
+ deviceId: null,
+ kind: 'cluster',
+ provider: MANAGED_CLOUD_CLUSTER_PROVIDER_V1,
+ providerResourceId: managedDeviceId,
+ providerScope: 'region-1',
+ });
+ });
+
it('keeps distinct folders on a device and scopes remote identities to the provider account', async () => {
const environment = await createEnvironment();
const device = await createDevice();
diff --git a/packages/database/src/schemas/device.ts b/packages/database/src/schemas/device.ts
index 01298a6ee13..0d6a90317ee 100644
--- a/packages/database/src/schemas/device.ts
+++ b/packages/database/src/schemas/device.ts
@@ -57,9 +57,18 @@ export const devices = pgTable(
// on the machine (`lh connect --workspace`).
sharedFromDeviceId: varchar('shared_from_device_id', { length: 64 }),
- /** Machine-derived id (sha256 truncated to 32 chars; 64 leaves room for fallback randomUUID) */
+ /**
+ * Machine-derived id (sha256 truncated to 32 chars; 64 leaves room for
+ * fallback randomUUID). For a managed cloud device it is the id the
+ * managed device provider assigned.
+ */
deviceId: varchar('device_id', { length: 64 }).notNull(),
- /** 'machine-id' | 'fallback' — validated by zod at the router boundary */
+ /**
+ * 'machine-id' | 'fallback' — reported by the connecting client, validated
+ * by zod at the router boundary — or `MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE`
+ * from `@lobechat/types`, which the server writes when it creates a managed
+ * cloud device. The client registration routers do not accept that value.
+ */
identitySource: varchar('identity_source', { length: 20 }).notNull(),
hostname: text('hostname'),
diff --git a/packages/database/src/schemas/environmentInstance.ts b/packages/database/src/schemas/environmentInstance.ts
index 1519dc2daad..3e0857cc818 100644
--- a/packages/database/src/schemas/environmentInstance.ts
+++ b/packages/database/src/schemas/environmentInstance.ts
@@ -21,7 +21,15 @@ import { timestamps } from './_helpers';
import { devices } from './device';
import { environments } from './environment';
-/** A concrete materialization of an abstract environment, independent of any project or agent. */
+/**
+ * A concrete materialization of an abstract environment, independent of any project or agent.
+ *
+ * A managed cloud device's instance is a `cluster` row: `provider` is
+ * `MANAGED_CLOUD_CLUSTER_PROVIDER_V1`, `providerScope` the region it runs in,
+ * and `providerResourceId` the managed device id (equal to `devices.deviceId`
+ * of its device row, which is unique only within the owner's scope). See
+ * `@lobechat/types` `managedDevice`.
+ */
export const environmentInstances = pgTable(
'environment_instances',
{
@@ -34,11 +42,11 @@ export const environmentInstances = pgTable(
kind: text('kind').$type<EnvironmentInstanceKind>().notNull(),
/** Internal devices.id, including remote machines enrolled through lh connect. */
deviceId: uuid('device_id').references(() => devices.id, { onDelete: 'restrict' }),
- /** Sandbox adapter identifier, or rc for a cluster binding. */
+ /** Sandbox adapter identifier, or the cluster provider (e.g. `MANAGED_CLOUD_CLUSTER_PROVIDER_V1`). */
provider: text('provider'),
- /** Non-secret provider account/cluster scope; external IDs are unique only within this scope. */
+ /** Non-secret provider account, cluster or region scope; external IDs are unique only within this scope. */
providerScope: text('provider_scope'),
- /** Sandbox or rc-controlled resource reference; never an access token or a signed URL. */
+ /** Sandbox or cluster resource reference; never an access token or a signed URL. */
providerResourceId: text('provider_resource_id'),
/** Physical working path in this instance, not a repository URL. */
workingDirectory: text('working_directory').notNull(),
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 13d2eedebab..c7e5c356877 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -854,6 +854,27 @@ export default {
'devices.health.status.pending': 'Not uploaded yet',
'devices.health.title': 'Health · last 12 hours',
'devices.lastSeen': 'Last connected {{time}}',
+ 'devices.managed.create.button': 'Create in cloud',
+ 'devices.managed.create.class.label': 'Size',
+ 'devices.managed.create.class.notIncluded': 'Not in your plan',
+ 'devices.managed.create.class.placeholder': 'Choose a size',
+ 'devices.managed.create.desc':
+ 'LobeHub runs this device in the cloud for you. It sleeps when idle and wakes when an agent needs it.',
+ 'devices.managed.create.failed': 'Could not create the cloud device. Try again.',
+ 'devices.managed.create.forbidden':
+ 'Only workspace members who can add devices can create a cloud device.',
+ 'devices.managed.create.loadFailed': 'Could not load the cloud device options. Try again.',
+ 'devices.managed.create.name.label': 'Name',
+ 'devices.managed.create.name.placeholder': 'My cloud device',
+ 'devices.managed.create.noClass': 'Your plan includes no cloud device size.',
+ 'devices.managed.create.notIncluded': 'Your plan does not include cloud devices.',
+ 'devices.managed.create.quota': '{{count}} of {{limit}} cloud devices used',
+ 'devices.managed.create.quotaExceeded':
+ 'You already have {{count}} of {{limit}} cloud devices. Remove one to create another.',
+ 'devices.managed.create.quotaRefused': 'Your plan does not allow another cloud device right now.',
+ '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.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/trpc/src/utils/internalJwt.ts b/packages/trpc/src/utils/internalJwt.ts
index a3e04f4ed90..77462d1391b 100644
--- a/packages/trpc/src/utils/internalJwt.ts
+++ b/packages/trpc/src/utils/internalJwt.ts
@@ -1,5 +1,10 @@
import { randomUUID } from 'node:crypto';
+import {
+ MANAGED_DEVICE_JWT_PURPOSE,
+ TUNNEL_ACCESS_JWT_PURPOSE,
+ WORKSPACE_DEVICE_CONNECT_JWT_PURPOSE,
+} from '@lobechat/types';
import debug from 'debug';
import type { JSONWebKeySet, JWK, JWK_RSA_Public, JWTVerifyOptions } from 'jose';
import {
@@ -271,7 +276,7 @@ export const signWorkspaceDeviceToken = async (workspaceId: string): Promise<str
const { key, kid } = await getSigningKey();
return (
- new SignJWT({ purpose: 'workspace-device-connect', workspace_id: workspaceId })
+ new SignJWT({ purpose: WORKSPACE_DEVICE_CONNECT_JWT_PURPOSE, workspace_id: workspaceId })
.setProtectedHeader({ alg: 'RS256', kid })
.setSubject(workspaceId)
.setIssuedAt()
@@ -286,6 +291,38 @@ export const signWorkspaceDeviceToken = async (workspaceId: string): Promise<str
);
};
+/**
+ * Sign the device gateway token of a managed cloud device. The gateway accepts
+ * it only for the connection whose `deviceId` equals `device_id`, and every
+ * server login verifier rejects its purpose. `sub` is the owning user, or the
+ * workspace for a workspace device (which also carries `workspace_id`, like
+ * {@link signWorkspaceDeviceToken}).
+ */
+export const signManagedDeviceToken = async (params: {
+ deviceId: string;
+ /** Lifetime in seconds. */
+ expiresIn: number;
+ sub: string;
+ workspaceId?: string;
+}): Promise<{ expiresAt: string; token: string }> => {
+ const { key, kid } = await getSigningKey();
+ const issuedAt = Math.floor(Date.now() / 1000);
+ const expiresAt = issuedAt + params.expiresIn;
+
+ const token = await new SignJWT({
+ device_id: params.deviceId,
+ purpose: MANAGED_DEVICE_JWT_PURPOSE,
+ ...(params.workspaceId ? { workspace_id: params.workspaceId } : {}),
+ })
+ .setProtectedHeader({ alg: 'RS256', kid })
+ .setSubject(params.sub)
+ .setIssuedAt(issuedAt)
+ .setExpirationTime(expiresAt)
+ .sign(key);
+
+ return { expiresAt: new Date(expiresAt * 1000).toISOString(), token };
+};
+
/**
* Sign the one-shot token that opens a tunnel link.
*
@@ -303,7 +340,7 @@ export const signTunnelAccessToken = async (params: {
const { key, kid } = await getSigningKey();
return new SignJWT({
- purpose: 'tunnel-access',
+ purpose: TUNNEL_ACCESS_JWT_PURPOSE,
...(params.workspaceId ? { workspace_id: params.workspaceId } : {}),
})
.setProtectedHeader({ alg: 'RS256', kid })
diff --git a/packages/types/src/deviceGatewayToken.ts b/packages/types/src/deviceGatewayToken.ts
new file mode 100644
index 00000000000..e90d701b995
--- /dev/null
+++ b/packages/types/src/deviceGatewayToken.ts
@@ -0,0 +1,14 @@
+/**
+ * `purpose` claims of tokens that only the device gateway accepts. They are
+ * signed with the same key as access tokens, so every LobeHub server login
+ * verifier must reject them.
+ */
+
+/** A managed cloud device's connect token. */
+export const MANAGED_DEVICE_JWT_PURPOSE = 'managed-device';
+
+/** A workspace device's connect token. */
+export const WORKSPACE_DEVICE_CONNECT_JWT_PURPOSE = 'workspace-device-connect';
+
+/** The one-shot entry ticket of a tunnel link. */
+export const TUNNEL_ACCESS_JWT_PURPOSE = 'tunnel-access';
diff --git a/packages/types/src/environment/index.ts b/packages/types/src/environment/index.ts
index 93152afa850..06badb8b0ae 100644
--- a/packages/types/src/environment/index.ts
+++ b/packages/types/src/environment/index.ts
@@ -79,7 +79,12 @@ export interface EnvironmentConfiguration {
sources?: EnvironmentSource[];
}
-/** Remote hosts connected through lh are devices too. Clusters are controlled through rc. */
+/**
+ * Remote hosts connected through lh are devices too. A cluster instance runs
+ * on infrastructure a cluster provider manages; a managed cloud device is one
+ * (`provider: MANAGED_CLOUD_CLUSTER_PROVIDER_V1`, `providerScope`: region,
+ * `providerResourceId`: managed device id — see `../managedDevice`).
+ */
export type EnvironmentInstanceKind = 'device' | 'sandbox' | 'cluster';
export type EnvironmentInstanceStatus = 'pending' | 'ready' | 'stopped' | 'error';
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index 9238e187de1..d967478aad9 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -22,6 +22,7 @@ export * from './dashboard';
export * from './dbMigration';
export * from './device';
export * from './deviceFilePreviewFailure';
+export * from './deviceGatewayToken';
export * from './deviceMetric';
export * from './discover';
export * from './document';
@@ -53,6 +54,7 @@ export * from './importer';
export * from './knowledgeBase';
export * from './linear';
export * from './llm';
+export * from './managedDevice';
export * from './message';
export * from './meta';
export * from './metric';
diff --git a/packages/types/src/managedDevice.test.ts b/packages/types/src/managedDevice.test.ts
new file mode 100644
index 00000000000..65059b68d0b
--- /dev/null
+++ b/packages/types/src/managedDevice.test.ts
@@ -0,0 +1,15 @@
+import { describe, expect, it } from 'vitest';
+
+import { isManagedCloudDevice, MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE } from './managedDevice';
+
+describe('isManagedCloudDevice', () => {
+ it('recognises only the managed identity source', () => {
+ expect(isManagedCloudDevice({ identitySource: MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE })).toBe(
+ true,
+ );
+ expect(isManagedCloudDevice({ identitySource: 'machine-id' })).toBe(false);
+ expect(isManagedCloudDevice({ identitySource: 'fallback' })).toBe(false);
+ expect(isManagedCloudDevice({ identitySource: null })).toBe(false);
+ expect(isManagedCloudDevice({})).toBe(false);
+ });
+});
diff --git a/packages/types/src/managedDevice.ts b/packages/types/src/managedDevice.ts
new file mode 100644
index 00000000000..c0fbc3fca70
--- /dev/null
+++ b/packages/types/src/managedDevice.ts
@@ -0,0 +1,43 @@
+/**
+ * Managed cloud devices: devices the platform creates and runs in the cloud,
+ * instead of machines a user connects with the desktop app or `lh connect`.
+ *
+ * A managed device is a normal `devices` row, so every device surface (lists,
+ * pickers, bindings, the device gateway) treats it like any other device. Two
+ * values identify it:
+ *
+ * - `devices.identitySource` is {@link MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE},
+ * and `devices.deviceId` is the id the managed device provider assigned.
+ * - Its `environment_instances` row has `kind: 'cluster'`,
+ * `provider: MANAGED_CLOUD_CLUSTER_PROVIDER_V1`, `providerScope` set to the
+ * region the device runs in, and `providerResourceId` set to the same
+ * managed device id.
+ *
+ * `devices.deviceId` is unique only within one user's personal devices or one
+ * workspace's devices, so resolve the device row of a cluster instance within
+ * the environment's owner scope and with the managed identity source, never by
+ * the id alone.
+ */
+
+/** `devices.identitySource` of a managed cloud device. */
+export const MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE = 'managed-cloud-device';
+
+/** `environment_instances.provider` of a managed cloud device's cluster instance. */
+export const MANAGED_CLOUD_CLUSTER_PROVIDER_V1 = 'managed-cloud-cluster-v1';
+
+/** Lifecycle phases of a managed cloud device, as the managed device provider reports them. */
+export const MANAGED_DEVICE_PHASES = [
+ 'pending',
+ 'running',
+ 'waking',
+ 'suspending',
+ 'suspended',
+ 'failed',
+ 'deleting',
+] as const;
+
+export type ManagedDevicePhase = (typeof MANAGED_DEVICE_PHASES)[number];
+
+/** Whether a device row is a managed cloud device. */
+export const isManagedCloudDevice = (device: { identitySource?: string | null }): boolean =>
+ device.identitySource === MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE;
diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.ts
index 502c30fc515..ed34084f3f7 100644
--- a/packages/types/src/serverConfig.ts
+++ b/packages/types/src/serverConfig.ts
@@ -61,6 +61,12 @@ export type IFeatureFlagsState = {
* as an executor only when this is on; the server checks it again.
*/
enableLlmRelay: boolean | undefined;
+ /**
+ * Creating managed cloud devices (`managed_cloud_device`). Off by default: the "Create in
+ * cloud" entry is hidden and the creation APIs answer FORBIDDEN. Existing managed devices keep
+ * working.
+ */
+ enableManagedCloudDevice: boolean | undefined;
enableOnboardingV2: boolean | undefined;
enableRAGEval: boolean | undefined;
enableSTT: boolean | undefined;
diff --git a/src/app/(backend)/api/device/managed/token/route.ts b/src/app/(backend)/api/device/managed/token/route.ts
new file mode 100644
index 00000000000..8e4322e83e9
--- /dev/null
+++ b/src/app/(backend)/api/device/managed/token/route.ts
@@ -0,0 +1,5 @@
+import app from '@/server/router-hono/device';
+
+export const runtime = 'nodejs';
+
+export const POST = (request: Request) => app.fetch(request);
diff --git a/src/business/client/features/ManagedDeviceCreateEntry.tsx b/src/business/client/features/ManagedDeviceCreateEntry.tsx
new file mode 100644
index 00000000000..fe6b7ba0bb2
--- /dev/null
+++ b/src/business/client/features/ManagedDeviceCreateEntry.tsx
@@ -0,0 +1,28 @@
+'use client';
+
+import type { DeviceScope, DeviceVisibility } from '@lobechat/types';
+import { memo } from 'react';
+
+export interface ManagedDeviceCreateEntryProps {
+ /** Where the device list renders the entry: its toolbar, or its empty state. */
+ placement: 'empty' | 'toolbar';
+ /** Which device pool the list manages. */
+ scope: DeviceScope;
+ /** Workspace scope only: the visibility tab the list is filtered to. */
+ visibility?: DeviceVisibility;
+}
+
+/**
+ * An entry for creating a managed cloud device, shown by the device list next
+ * to its connect actions. The list renders it only while the
+ * `managed_cloud_device` flag is on for the user.
+ *
+ * Nothing in the open-source build: it has no managed device provider.
+ * Downstream builds override this module through their own `@/business/...`
+ * mapping.
+ */
+const ManagedDeviceCreateEntry = memo<ManagedDeviceCreateEntryProps>(() => null);
+
+ManagedDeviceCreateEntry.displayName = 'ManagedDeviceCreateEntry';
+
+export default ManagedDeviceCreateEntry;
diff --git a/src/features/DeviceManager/DeviceManager.tsx b/src/features/DeviceManager/DeviceManager.tsx
index f191b8751fd..479f2299192 100644
--- a/src/features/DeviceManager/DeviceManager.tsx
+++ b/src/features/DeviceManager/DeviceManager.tsx
@@ -17,9 +17,11 @@ import {
import { memo, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
+import ManagedDeviceCreateEntry from '@/business/client/features/ManagedDeviceCreateEntry';
import AsyncBoundary from '@/components/AsyncBoundary';
import { useDeviceList } from '@/store/device';
import { useElectronStore } from '@/store/electron';
+import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
import DeviceCard from './DeviceCard';
import DeviceGrid from './DeviceGrid';
@@ -241,6 +243,11 @@ const DeviceManager = memo<DeviceManagerProps>((props) => {
const { onConnect, onOpenDevice, scope, toolbarLeading, visibility } = props;
const { t } = useTranslation('setting');
const isWorkspace = scope === 'workspace';
+ // The `managed_cloud_device` flag gates only the entry that creates a managed
+ // device. Managed devices that already exist still list and open here.
+ const showManagedDeviceCreate = useServerConfigStore(
+ serverConfigSelectors.enableManagedCloudDevice,
+ );
// The device replica every device-listing surface reads (see `useDeviceList`):
// a reload paints the persisted cards first, presence pending.
@@ -297,6 +304,9 @@ const DeviceManager = memo<DeviceManagerProps>((props) => {
{t('devices.empty.methodCli.title')}
</Button>
)}
+ {showManagedDeviceCreate && (
+ <ManagedDeviceCreateEntry placement={'empty'} scope={scope} visibility={visibility} />
+ )}
</Flexbox>
{!isWorkspace && (
@@ -336,6 +346,9 @@ const DeviceManager = memo<DeviceManagerProps>((props) => {
title={t('devices.actions.refresh')}
onClick={() => mutate()}
/>
+ {showManagedDeviceCreate && (
+ <ManagedDeviceCreateEntry placement={'toolbar'} scope={scope} visibility={visibility} />
+ )}
{isWorkspace ? (
<Button
icon={<Icon icon={TerminalIcon} />}
diff --git a/src/libs/oidc-provider/jwt.purpose.test.ts b/src/libs/oidc-provider/jwt.purpose.test.ts
new file mode 100644
index 00000000000..8682a137ab8
--- /dev/null
+++ b/src/libs/oidc-provider/jwt.purpose.test.ts
@@ -0,0 +1,110 @@
+import { generateKeyPairSync } from 'node:crypto';
+
+import { MANAGED_DEVICE_JWT_PURPOSE } from '@lobechat/types';
+import { decodeJwt, decodeProtectedHeader, SignJWT } from 'jose';
+import { beforeAll, describe, expect, it, vi } from 'vitest';
+
+const { authEnvMock } = vi.hoisted(() => ({
+ authEnvMock: { INTERNAL_JWT_EXPIRATION: '30s', JWKS_KEY: '' },
+}));
+
+vi.mock('@/envs/auth', () => ({ authEnv: authEnvMock }));
+
+const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
+const kid = 'test-key';
+
+const sign = (claims: Record<string, unknown>, subject: string) =>
+ new SignJWT(claims)
+ .setProtectedHeader({ alg: 'RS256', kid })
+ .setSubject(subject)
+ .setIssuedAt()
+ .setExpirationTime('5m')
+ .sign(privateKey);
+
+describe('validateOIDCJWT token purposes', () => {
+ beforeAll(() => {
+ authEnvMock.JWKS_KEY = JSON.stringify({
+ keys: [{ ...privateKey.export({ format: 'jwk' }), alg: 'RS256', kid, use: 'sig' }],
+ });
+ });
+
+ it('signs a personal managed device token and rejects it as a login', async () => {
+ const { validateOIDCJWT } = await import('./jwt');
+ const { signManagedDeviceToken } = await import('@/libs/trpc/utils/internalJwt');
+ const { expiresAt, token } = await signManagedDeviceToken({
+ deviceId: 'managed-device-1',
+ expiresIn: 3600,
+ sub: 'user-1',
+ });
+ const claims = decodeJwt(token);
+
+ expect(decodeProtectedHeader(token)).toEqual({ alg: 'RS256', kid });
+ expect(claims).toMatchObject({
+ device_id: 'managed-device-1',
+ purpose: MANAGED_DEVICE_JWT_PURPOSE,
+ sub: 'user-1',
+ });
+ expect(claims).not.toHaveProperty('workspace_id');
+ expect(claims.exp! - claims.iat!).toBe(3600);
+ expect(expiresAt).toBe(new Date(claims.exp! * 1000).toISOString());
+ await expect(validateOIDCJWT(token)).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
+ });
+
+ it('signs a workspace managed device token and rejects it as a login', async () => {
+ const { validateOIDCJWT } = await import('./jwt');
+ const { signManagedDeviceToken } = await import('@/libs/trpc/utils/internalJwt');
+ const { token } = await signManagedDeviceToken({
+ deviceId: 'managed-device-1',
+ expiresIn: 3600,
+ sub: 'workspace-1',
+ workspaceId: 'workspace-1',
+ });
+
+ expect(decodeJwt(token)).toMatchObject({
+ device_id: 'managed-device-1',
+ purpose: MANAGED_DEVICE_JWT_PURPOSE,
+ sub: 'workspace-1',
+ workspace_id: 'workspace-1',
+ });
+ await expect(validateOIDCJWT(token)).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
+ });
+
+ it('rejects the other device gateway tokens as a login', async () => {
+ const { validateOIDCJWT } = await import('./jwt');
+ const { signTunnelAccessToken, signWorkspaceDeviceToken } =
+ await import('@/libs/trpc/utils/internalJwt');
+
+ await expect(
+ validateOIDCJWT(await signTunnelAccessToken({ userId: 'user-1' })),
+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
+ await expect(
+ validateOIDCJWT(await signWorkspaceDeviceToken('workspace-1')),
+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
+ });
+
+ it('still accepts an OIDC access token', async () => {
+ const { validateOIDCJWT } = await import('./jwt');
+ const token = await sign({ client_id: 'lobehub-desktop', scope: 'openid' }, 'user-1');
+
+ await expect(validateOIDCJWT(token)).resolves.toMatchObject({ userId: 'user-1' });
+ });
+
+ it('still accepts the sandbox CLI token and the hetero operation token', async () => {
+ const { validateOIDCJWT } = await import('./jwt');
+ const { signHeteroOperationJWT, signUserJWT } = await import('@/libs/trpc/utils/internalJwt');
+
+ await expect(validateOIDCJWT(await signUserJWT('user-1'))).resolves.toMatchObject({
+ tokenData: { purpose: 'cli-sandbox' },
+ userId: 'user-1',
+ });
+ await expect(
+ validateOIDCJWT(
+ await signHeteroOperationJWT({
+ capabilities: ['hetero:ingest'],
+ operationId: 'operation-1',
+ userId: 'user-1',
+ }),
+ ),
+ ).resolves.toMatchObject({ tokenData: { purpose: 'hetero-operation' }, userId: 'user-1' });
+ });
+});
diff --git a/src/libs/oidc-provider/jwt.ts b/src/libs/oidc-provider/jwt.ts
index 3106ab25b02..1a0f1ad1339 100644
--- a/src/libs/oidc-provider/jwt.ts
+++ b/src/libs/oidc-provider/jwt.ts
@@ -1,4 +1,9 @@
import { acceptanceIdFromReviewResource, siteReviewFromResource } from '@lobechat/const';
+import {
+ MANAGED_DEVICE_JWT_PURPOSE,
+ TUNNEL_ACCESS_JWT_PURPOSE,
+ WORKSPACE_DEVICE_CONNECT_JWT_PURPOSE,
+} from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import debug from 'debug';
import type { JSONWebKeySet, JWK, JWK_RSA_Public } from 'jose';
@@ -10,6 +15,13 @@ import { isAcceptanceReviewClient, isAcceptanceReviewIssued } from './acceptance
const log = debug('oidc-jwt');
+/** See `@lobechat/types` `deviceGatewayToken`: these tokens are not logins. */
+const DEVICE_GATEWAY_ONLY_PURPOSES = new Set<unknown>([
+ MANAGED_DEVICE_JWT_PURPOSE,
+ TUNNEL_ACCESS_JWT_PURPOSE,
+ WORKSPACE_DEVICE_CONNECT_JWT_PURPOSE,
+]);
+
/**
* Get JWKS key string from environment
* Uses JWKS_KEY which already has fallback to OIDC_JWKS_KEY in authEnv
@@ -171,6 +183,13 @@ export const validateOIDCJWT = async (token: string) => {
});
}
+ if (DEVICE_GATEWAY_ONLY_PURPOSES.has(payload.purpose)) {
+ throw new TRPCError({
+ code: 'UNAUTHORIZED',
+ message: 'Device gateway tokens are not accepted here',
+ });
+ }
+
return {
clientId,
payload,
diff --git a/src/store/serverConfig/selectors.test.ts b/src/store/serverConfig/selectors.test.ts
index 4f4373a4fbf..1e97d7b76c1 100644
--- a/src/store/serverConfig/selectors.test.ts
+++ b/src/store/serverConfig/selectors.test.ts
@@ -56,6 +56,20 @@ describe('serverConfigSelectors', () => {
});
});
+ describe('enableManagedCloudDevice', () => {
+ it('is off by default and on only when the flag resolves to true', () => {
+ expect(
+ serverConfigSelectors.enableManagedCloudDevice(initServerConfigStore({}).getState()),
+ ).toBe(false);
+ const on = initServerConfigStore({
+ featureFlags: {
+ ...mapFeatureFlagsEnvToState({ ...DEFAULT_FEATURE_FLAGS, managed_cloud_device: true }),
+ },
+ });
+ expect(serverConfigSelectors.enableManagedCloudDevice(on.getState())).toBe(true);
+ });
+ });
+
describe('enableGatewayMode', () => {
it('should return true when gateway mode is enabled', () => {
const store = initServerConfigStore({
diff --git a/src/store/serverConfig/selectors.ts b/src/store/serverConfig/selectors.ts
index 4d69389850e..6478682b575 100644
--- a/src/store/serverConfig/selectors.ts
+++ b/src/store/serverConfig/selectors.ts
@@ -11,6 +11,9 @@ export const serverConfigSelectors = {
/** Runtime flag `dashboard`: dashboards, widget previews and the builtin-dashboard tool. */
enableChannels: (s: ServerConfigStore) => s.featureFlags.enableChannels === true,
enableDashboard: (s: ServerConfigStore) => s.featureFlags.enableDashboard === true,
+ /** Runtime flag `managed_cloud_device`: the entry that creates a managed cloud device. */
+ enableManagedCloudDevice: (s: ServerConfigStore) =>
+ s.featureFlags.enableManagedCloudDevice === true,
enableGatewayMode: (s: ServerConfigStore) => s.serverConfig.enableGatewayMode || false,
enableTopicPreview: (s: ServerConfigStore) => s.featureFlags.enableTopicPreview === true,
enableLobehubSkill: (s: ServerConfigStore) => s.serverConfig.enableLobehubSkill || false,