🤯 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): add remote CLI maintenance API (#20527)
AmAzing-6d8c8675f748
diff --git a/apps/server/src/routers/lambda/__tests__/deviceAppUpdate.test.ts b/apps/server/src/routers/lambda/__tests__/deviceAppUpdate.test.tsindex ea71664824a..6b6a96b0691 100644--- a/apps/server/src/routers/lambda/__tests__/deviceAppUpdate.test.ts+++ b/apps/server/src/routers/lambda/__tests__/deviceAppUpdate.test.ts@@ -5,9 +5,12 @@ import { deviceRouter } from '../device';const mocks = vi.hoisted(() => ({checkAppUpdate: vi.fn(),+ checkCliUpdate: vi.fn(),findWorkspaceDeviceById: vi.fn(),getAppUpdateState: vi.fn(),+ getCliUpdateState: vi.fn(),installAppUpdate: vi.fn(),+ restartCli: vi.fn(),}));vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn() }));@@ -20,8 +23,11 @@ vi.mock('@/server/services/deviceGateway', async (importOriginal) => ({...(await importOriginal<object>()),deviceGateway: {checkAppUpdate: mocks.checkAppUpdate,+ checkCliUpdate: mocks.checkCliUpdate,getAppUpdateState: mocks.getAppUpdateState,+ getCliUpdateState: mocks.getCliUpdateState,installAppUpdate: mocks.installAppUpdate,+ restartCli: mocks.restartCli,},}));@@ -29,6 +35,69 @@ const workspaceCaller = (userId: string, workspaceRole: 'member' | 'owner') =>deviceRouter.createCaller({ userId, workspaceId: 'workspace', workspaceRole } as never);describe('remote app update', () => {+ const cliInput = {+ deviceId: 'device',+ requestId: '89d177cf-52e5-4d55-b71c-13deef4ea366',+ update: true,+ };++ it.each(['getCliUpdateState', 'checkCliUpdate', 'restartCli'] as const)(+ 'rejects unauthorized workspace CLI request %s',+ async (procedure) => {+ const input = procedure === 'restartCli' ? cliInput : { deviceId: 'device' };+ await expect(+ workspaceCaller('other', 'member')[procedure](input as typeof cliInput),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(mocks[procedure]).not.toHaveBeenCalled();+ },+ );++ it.each(['getCliUpdateState', 'checkCliUpdate', 'restartCli'] as const)(+ 'retains visibility checks for %s',+ async (procedure) => {+ mocks.findWorkspaceDeviceById.mockResolvedValue(undefined);+ await expect(workspaceCaller('owner', 'owner')[procedure](cliInput)).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ expect(mocks[procedure]).not.toHaveBeenCalled();+ },+ );++ it.each([+ ['enroller', 'member'],+ ['owner', 'owner'],+ ] as const)('allows authorized %s CLI maintenance', async (userId, role) => {+ const state = {+ activeTasks: 0,+ currentVersion: '1.0.0',+ instanceId: 'instance',+ supported: true,+ };+ for (const procedure of ['getCliUpdateState', 'checkCliUpdate', 'restartCli'] as const) {+ mocks[procedure].mockResolvedValue({ state, status: 'ok' });+ const input = procedure === 'restartCli' ? cliInput : { deviceId: 'device' };+ await expect(+ workspaceCaller(userId, role)[procedure](input as typeof cliInput),+ ).resolves.toEqual({ state, status: 'ok' });+ }+ expect(mocks.restartCli).toHaveBeenCalledWith({+ ...cliInput,+ userId,+ workspaceId: 'workspace',+ });+ });++ it.each([+ { ...cliInput, requestId: 'not-a-uuid' },+ { ...cliInput, update: 'true' },+ ...['package', 'version', 'command'].map((key) => ({ ...cliInput, [key]: 'untrusted' })),+ ])('rejects invalid or arbitrary restart inputs: %j', async (input) => {+ await expect(+ workspaceCaller('owner', 'owner').restartCli(input as typeof cliInput),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(mocks.restartCli).not.toHaveBeenCalled();+ });+beforeEach(() => {vi.clearAllMocks();mocks.findWorkspaceDeviceById.mockResolvedValue({ deviceId: 'device', userId: 'enroller' });diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.tsindex cfa78912308..e5464ab610a 100644--- a/apps/server/src/routers/lambda/device.ts+++ b/apps/server/src/routers/lambda/device.ts@@ -1431,6 +1431,43 @@ export const deviceRouter = router({});}),+ getCliUpdateState: deviceProcedure+ .input(z.object({ deviceId: z.string() }).strict())+ .query(async ({ ctx, input }) => {+ await assertDeviceOperable(ctx, input.deviceId, 'maintain the CLI');+ return deviceGateway.getCliUpdateState({+ deviceId: input.deviceId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ }),++ checkCliUpdate: deviceProcedure+ .input(z.object({ deviceId: z.string() }).strict())+ .mutation(async ({ ctx, input }) => {+ await assertDeviceOperable(ctx, input.deviceId, 'maintain the CLI');+ return deviceGateway.checkCliUpdate({+ deviceId: input.deviceId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ }),++ restartCli: deviceProcedure+ .input(+ z+ .object({ deviceId: z.string(), requestId: z.string().uuid(), update: z.boolean() })+ .strict(),+ )+ .mutation(async ({ ctx, input }) => {+ await assertDeviceOperable(ctx, input.deviceId, 'maintain the CLI');+ return deviceGateway.restartCli({+ ...input,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ }),+/** Live tunnel links the caller can reach, newest first. */listTunnels: deviceProcedure.input(z.object({ deviceId: z.string().optional() }).optional())diff --git a/apps/server/src/services/deviceGateway/__tests__/index.test.ts b/apps/server/src/services/deviceGateway/__tests__/index.test.tsindex 89cc2e0d06a..119e18d073b 100644--- a/apps/server/src/services/deviceGateway/__tests__/index.test.ts+++ b/apps/server/src/services/deviceGateway/__tests__/index.test.ts@@ -108,6 +108,83 @@ describe('DeviceGateway', () => {});});+ describe('remote CLI maintenance', () => {+ const params = { deviceId: 'device', userId: 'user', workspaceId: 'workspace' };+ const restart = { requestId: '89d177cf-52e5-4d55-b71c-13deef4ea366', update: true };++ beforeEach(() => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ });++ it.each(['getCliUpdateState', 'checkCliUpdate', 'restartCli'] as const)(+ 'targets only the CLI channel for %s',+ async (method) => {+ const state = {+ activeTasks: 0,+ currentVersion: '1.0.0',+ instanceId: 'instance',+ supported: true,+ };+ mockClient.invokeRpc.mockResolvedValue({ data: state, success: true });+ await expect(new DeviceGateway()[method]({ ...params, ...restart })).resolves.toEqual({+ state,+ status: 'ok',+ });+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(+ { ...params, channel: 'cli', timeout: 15_000 },+ { method, ...(method === 'restartCli' ? { params: restart } : {}) },+ );+ },+ );++ it.each([+ 'Unknown device RPC method: checkCliUpdate',+ 'This device client does not support remote CLI updates',+ ])('reports unsupported old clients: %s', async (message) => {+ mockClient.invokeRpc.mockResolvedValue({ error: message, success: false });+ await expect(new DeviceGateway().checkCliUpdate(params)).resolves.toEqual({+ message,+ status: 'unsupported',+ });+ });++ it('reports offline devices as unavailable', async () => {+ mockClient.invokeRpc.mockResolvedValue({ error: 'Device offline', success: false });+ await expect(new DeviceGateway().restartCli({ ...params, ...restart })).resolves.toEqual({+ message: 'Device offline',+ status: 'unavailable',+ });+ });++ it('distinguishes an explicit maintenance refusal from an ambiguous transport failure', async () => {+ mockClient.invokeRpc.mockResolvedValue({+ error: 'CLI_MAINTENANCE_REJECTED: This device has active tasks.',+ success: false,+ });+ await expect(new DeviceGateway().restartCli({ ...params, ...restart })).resolves.toEqual({+ message: 'This device has active tasks.',+ status: 'rejected',+ });+ });++ it('reports timeout as unavailable', async () => {+ mockClient.invokeRpc.mockRejectedValue(new Error('timeout'));+ await expect(new DeviceGateway().getCliUpdateState(params)).resolves.toEqual({+ message: 'timeout',+ status: 'unavailable',+ });+ });++ it('reports an unconfigured gateway as unavailable', async () => {+ mockEnv.DEVICE_GATEWAY_URL = undefined;+ await expect(new DeviceGateway().getCliUpdateState(params)).resolves.toMatchObject({+ status: 'unavailable',+ });+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });+ });+describe('isConfigured', () => {it('should return false when DEVICE_GATEWAY_URL is not set', () => {const proxy = new DeviceGateway();diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.tsindex e7304768ca3..5066fec6844 100644--- a/apps/server/src/services/deviceGateway/index.ts+++ b/apps/server/src/services/deviceGateway/index.ts@@ -19,6 +19,9 @@ import type {DeviceAppUpdateInstallResult,DeviceAppUpdateState,DeviceAppUpdateStateResult,+ DeviceCliRestartParams,+ DeviceCliUpdateState,+ DeviceCliUpdateStateResult,DeviceCopyAssetForPublishResult,DeviceCopyProjectFileItem,DeviceCopyProjectFileResultItem,@@ -2124,6 +2127,59 @@ export class DeviceGateway {}}+ async getCliUpdateState(params: AppUpdateRpcParams): Promise<DeviceCliUpdateStateResult> {+ return this.invokeCliUpdate('getCliUpdateState', params);+ }++ async checkCliUpdate(params: AppUpdateRpcParams): Promise<DeviceCliUpdateStateResult> {+ return this.invokeCliUpdate('checkCliUpdate', params);+ }++ async restartCli(+ params: AppUpdateRpcParams & DeviceCliRestartParams,+ ): Promise<DeviceCliUpdateStateResult> {+ return this.invokeCliUpdate('restartCli', params, {+ requestId: params.requestId,+ update: params.update,+ });+ }++ private async invokeCliUpdate(+ method: 'getCliUpdateState' | 'checkCliUpdate' | 'restartCli',+ params: AppUpdateRpcParams,+ restartParams?: DeviceCliRestartParams,+ ): Promise<DeviceCliUpdateStateResult> {+ const { deviceId, timeout = 15_000, userId, workspaceId } = params;+ const client = this.getClient();+ if (!client) return { message: 'Device Gateway is not configured', status: 'unavailable' };++ try {+ const result = await client.invokeRpc<DeviceCliUpdateState>(+ { channel: 'cli', deviceId, timeout, userId, workspaceId },+ { method, ...(restartParams ? { params: restartParams } : {}) },+ );+ if (result.success && result.data !== undefined) return { state: result.data, status: 'ok' };++ const message = result.error || `${method} failed`;+ const unsupported =+ message.includes('does not support remote CLI updates') ||+ message.includes('Unknown device RPC method');+ log('%s: failed for deviceId=%s — %s', method, deviceId, message);+ return {+ message: message.replace('CLI_MAINTENANCE_REJECTED: ', ''),+ status: unsupported+ ? 'unsupported'+ : message.startsWith('CLI_MAINTENANCE_REJECTED: ')+ ? 'rejected'+ : 'unavailable',+ };+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ log('%s: error for deviceId=%s — %s', method, deviceId, message);+ return { message, status: 'unavailable' };+ }+ }+private getClient(): GatewayHttpClient | null {const url = gatewayEnv.DEVICE_GATEWAY_URL;const token = gatewayEnv.DEVICE_GATEWAY_SERVICE_TOKEN;diff --git a/packages/types/src/device.ts b/packages/types/src/device.tsindex 9b38aaa40c6..ee2eb6496de 100644--- a/packages/types/src/device.ts+++ b/packages/types/src/device.ts@@ -1042,3 +1042,35 @@ export type DeviceAppUpdateStateResult =export type DeviceAppUpdateInstallResult ={ status: 'ok'; targetVersion: string } | { message: string; status: DeviceAppUpdateFailure };++/** A CLI maintenance request is acknowledged before the connection goes away. */+export interface DeviceCliUpdateOperation {+ error?: string;+ fromInstanceId: string;+ id: string;+ kind: 'restart' | 'update';+ stage: 'updating' | 'restarting' | 'failed';+ targetVersion: string;+}++export interface DeviceCliUpdateState {+ activeTasks: number;+ currentVersion: string;+ /** Changes on every process start; reconnecting a socket alone is not a restart. */+ instanceId: string;+ latestVersion?: string;+ operation?: DeviceCliUpdateOperation;+ /** Remote maintenance requires a standalone daemon and a stable installed CLI entry. */+ supported: boolean;+ unsupportedReason?: string;+}++export interface DeviceCliRestartParams {+ /** Idempotency key, retained when retrying an ambiguous request. */+ requestId: string;+ update: boolean;+}++export type DeviceCliUpdateStateResult =+ | { state: DeviceCliUpdateState; status: 'ok' }+ | { message: string; status: 'rejected' | 'unavailable' | 'unsupported' };