π€― 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
β»οΈ refactor(server): split the 2386-line DeviceGateway into cohesive modules (#21150)
Arvin Xud467ab8c6d37
diff --git a/apps/server/src/services/deviceGateway/__tests__/index.test.ts b/apps/server/src/services/deviceGateway/__tests__/index.test.tsdeleted file mode 100644index 685237b39b6..00000000000--- a/apps/server/src/services/deviceGateway/__tests__/index.test.ts+++ /dev/null@@ -1,1908 +0,0 @@-import type * as DeviceGatewayClientModule from '@lobechat/device-gateway-client';-import { describe, expect, it, vi } from 'vitest';--// Import after mocks are set up-import { resolveDeviceClientKinds } from '../clientKinds';-import { DeviceGateway } from '../index';--const mockEnv = vi.hoisted(() => ({- DEVICE_GATEWAY_SERVICE_TOKEN: undefined as string | undefined,- DEVICE_GATEWAY_URL: undefined as string | undefined,-}));--const mockClient = vi.hoisted(() => ({- executeMcpCall: vi.fn(),- executeMessageApi: vi.fn(),- executeToolCall: vi.fn(),- getDeviceMetrics: vi.fn(),- getDeviceSystemInfo: vi.fn(),- invokeRpc: vi.fn(),- queryDeviceList: vi.fn(),- queryDeviceStatus: vi.fn(),-}));--const MockGatewayHttpClient = vi.hoisted(() =>- vi.fn(function () {- return mockClient;- }),-);--// The send-path cache rides on the Redis service; hand its connection seam a-// fake client so the test sees which key and TTL the gateway asked for,-// independent of whether this environment has Redis configured.-const { cacheRedis, getRedisServiceClient } = vi.hoisted(() => {- const cacheRedis = { get: vi.fn(async () => null), set: vi.fn(async () => 'OK') };- return { cacheRedis, getRedisServiceClient: vi.fn(async () => cacheRedis) };-});--vi.mock('@/server/services/redis/client', () => ({ getRedisServiceClient }));--vi.mock('@/envs/gateway', () => ({- gatewayEnv: mockEnv,-}));--// Partial mock: only the HTTP client is swapped. The transport-failure-// describers are pure functions the service calls to phrase its errors, and-// stubbing them would test nothing.-vi.mock('@lobechat/device-gateway-client', async (importOriginal) => ({- ...(await importOriginal<typeof DeviceGatewayClientModule>()),- GatewayHttpClient: MockGatewayHttpClient,-}));--describe('DeviceGateway', () => {- beforeEach(() => {- vi.clearAllMocks();- mockEnv.DEVICE_GATEWAY_URL = undefined;- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = undefined;- });-- describe('remote app update', () => {- const configure = () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- };- const params = { deviceId: 'device-1', userId: 'user-1' };-- it('asks the desktop channel for the update state', async () => {- configure();- const state = { currentVersion: '2.1.0', stage: 'downloaded', targetVersion: '2.2.0' };- mockClient.invokeRpc.mockResolvedValue({ data: state, success: true });-- await expect(new DeviceGateway().getAppUpdateState(params)).resolves.toEqual({- state,- status: 'ok',- });- expect(mockClient.invokeRpc).toHaveBeenCalledWith(- expect.objectContaining({ channel: 'desktop', deviceId: 'device-1', userId: 'user-1' }),- { method: 'getAppUpdateState' },- );- });-- it('returns the version the device restarts into', async () => {- configure();- mockClient.invokeRpc.mockResolvedValue({ data: { targetVersion: '2.2.0' }, success: true });-- await expect(new DeviceGateway().installAppUpdate(params)).resolves.toEqual({- status: 'ok',- targetVersion: '2.2.0',- });- });-- it.each([- 'This device client does not support remote updates',- 'Unknown device RPC method: checkAppUpdate',- ])('reports a client that cannot update remotely as unsupported (%s)', async (error) => {- configure();- mockClient.invokeRpc.mockResolvedValue({ error, success: false });-- await expect(new DeviceGateway().checkAppUpdate(params)).resolves.toEqual({- message: error,- status: 'unsupported',- });- });-- it('reports an unreachable device as unavailable', async () => {- configure();- mockClient.invokeRpc.mockRejectedValue(new Error('timeout'));-- await expect(new DeviceGateway().getAppUpdateState(params)).resolves.toEqual({- message: 'timeout',- status: 'unavailable',- });- });-- it('reports unavailable without a configured gateway', async () => {- await expect(new DeviceGateway().installAppUpdate(params)).resolves.toMatchObject({- status: 'unavailable',- });- expect(mockClient.invokeRpc).not.toHaveBeenCalled();- });- });-- 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();- expect(proxy.isConfigured).toBe(false);- });-- it('should return true when DEVICE_GATEWAY_URL is set', () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- const proxy = new DeviceGateway();- expect(proxy.isConfigured).toBe(true);- });- });-- describe('queryDeviceStatus', () => {- it('should return offline status when not configured', async () => {- const proxy = new DeviceGateway();- const result = await proxy.queryDeviceStatus('user-1');- expect(result).toEqual({ deviceCount: 0, online: false });- });-- it('should return status from client on success', async () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- const expected = { deviceCount: 2, online: true };- mockClient.queryDeviceStatus.mockResolvedValue(expected);-- const proxy = new DeviceGateway();- const result = await proxy.queryDeviceStatus('user-1');-- expect(result).toEqual(expected);- expect(mockClient.queryDeviceStatus).toHaveBeenCalledWith('user-1', undefined);- });-- it('should return offline status on error', async () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- mockClient.queryDeviceStatus.mockRejectedValue(new Error('network error'));-- const proxy = new DeviceGateway();- const result = await proxy.queryDeviceStatus('user-1');-- expect(result).toEqual({ deviceCount: 0, online: false });- });- });-- describe('queryDeviceList', () => {- it('should return empty array when not configured', async () => {- const proxy = new DeviceGateway();- const result = await proxy.queryDeviceList('user-1');- expect(result).toEqual([]);- });-- it('should map device-centric channels to lastSeen + online and flatten channels', async () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- const connectedAt = Date.parse('2025-01-15T10:30:00Z');- const iso = new Date(connectedAt).toISOString();- mockClient.queryDeviceList.mockResolvedValue([- {- channels: [- { channel: 'desktop', connectedAt, connectionId: 'conn-a' },- { channel: 'cli', connectedAt, connectionId: 'conn-b' },- ],- connectedAt,- deviceId: 'dev-1',- hostname: 'my-laptop',- platform: 'darwin',- },- {- channels: [{ channel: 'desktop', connectedAt, connectionId: 'conn-c' }],- connectedAt,- deviceId: 'dev-2',- hostname: 'my-desktop',- platform: 'win32',- },- ]);-- const proxy = new DeviceGateway();- const result = await proxy.queryDeviceList('user-1');-- expect(result).toEqual([- {- channels: [- { channel: 'desktop', connectedAt: iso, connectionId: 'conn-a' },- { channel: 'cli', connectedAt: iso, connectionId: 'conn-b' },- ],- deviceId: 'dev-1',- hostname: 'my-laptop',- lastSeen: iso,- online: true,- platform: 'darwin',- },- {- channels: [{ channel: 'desktop', connectedAt: iso, connectionId: 'conn-c' }],- deviceId: 'dev-2',- hostname: 'my-desktop',- lastSeen: iso,- online: true,- platform: 'win32',- },- ]);- expect(mockClient.queryDeviceList).toHaveBeenCalledWith('user-1', undefined);- });-- /**- * The gateway promises no channel order, but every consumer reads- * `channels[0]` as the device's current connection β the settings row's- * "Connected {time}", a ghost row's `lastSeen`/hostname/platform β while- * `sortDevicesByActivity` ranks by the freshest channel. Leave the pool raw- * and a multi-channel device gets ranked by one connection and labelled- * with another, which reads as a broken sort.- */- it('sorts channels newest-first so channels[0] is the current connection', async () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- const older = Date.parse('2025-01-15T10:30:00Z');- const newest = Date.parse('2025-03-20T08:00:00Z');- const middle = Date.parse('2025-02-01T12:00:00Z');- mockClient.queryDeviceList.mockResolvedValue([- {- // Deliberately unordered, with the newest NOT first.- channels: [- { channel: 'cli', connectedAt: older, connectionId: 'conn-old' },- { channel: 'desktop', connectedAt: newest, connectionId: 'conn-new' },- { channel: 'mobile', connectedAt: middle, connectionId: 'conn-mid' },- ],- connectedAt: older,- deviceId: 'dev-1',- hostname: 'my-laptop',- platform: 'darwin',- },- ]);-- const proxy = new DeviceGateway();- const result = await proxy.queryDeviceList('user-1');-- expect(result[0]?.channels?.map((c) => c.connectionId)).toEqual([- 'conn-new',- 'conn-mid',- 'conn-old',- ]);- });-- it('tolerates a legacy gateway response without channels', async () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- const connectedAt = Date.parse('2025-01-15T10:30:00Z');- mockClient.queryDeviceList.mockResolvedValue([- { connectedAt, deviceId: 'dev-1', hostname: 'my-laptop', platform: 'darwin' },- ]);-- const proxy = new DeviceGateway();- const result = await proxy.queryDeviceList('user-1');-- expect(result).toEqual([- {- channels: [],- deviceId: 'dev-1',- hostname: 'my-laptop',- lastSeen: new Date(connectedAt).toISOString(),- online: true,- platform: 'darwin',- },- ]);- });-- it('absorbs a transient failure instead of reporting an empty pool', async () => {- // The online set decides which devices a run may reach, so one dropped- // connection must not read as "every device is offline".- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- const connectedAt = Date.parse('2025-01-15T10:30:00Z');- mockClient.queryDeviceList- .mockRejectedValueOnce(new Error('fetch failed'))- .mockResolvedValueOnce([- { connectedAt, deviceId: 'dev-1', hostname: 'my-laptop', platform: 'darwin' },- ]);-- const result = await new DeviceGateway().queryDeviceList('user-1');-- expect(mockClient.queryDeviceList).toHaveBeenCalledTimes(2);- expect(result).toHaveLength(1);- expect(result[0]).toMatchObject({ deviceId: 'dev-1', online: true });- });-- it('reports the fallback out loud when the gateway stays unreachable', async () => {- // The old bare `catch {}` made this failure invisible: a device-bound run- // degraded to the cloud sandbox with no breadcrumb in any log.- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- mockClient.queryDeviceList.mockRejectedValue(new Error('fetch failed'));- const warn = vi.spyOn(console, 'warn').mockImplementation(function () {});-- const result = await new DeviceGateway().queryDeviceList('user-1', 'ws-1');-- expect(result).toEqual([]);- expect(warn).toHaveBeenCalledWith(- expect.stringContaining('queryDeviceList'),- expect.objectContaining({ error: 'fetch failed', userId: 'user-1', workspaceId: 'ws-1' }),- );- });-- it('should return empty array on error', async () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- mockClient.queryDeviceList.mockRejectedValue(new Error('fail'));-- const proxy = new DeviceGateway();- const result = await proxy.queryDeviceList('user-1');-- expect(result).toEqual([]);- });- });-- describe('queryDeviceSystemInfo', () => {- it('should return undefined when not configured', async () => {- const proxy = new DeviceGateway();- const result = await proxy.queryDeviceSystemInfo('user-1', 'dev-1');- expect(result).toBeUndefined();- });-- it('should return systemInfo on success', async () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- const systemInfo = { cpuModel: 'Apple M1', os: 'macOS', totalMemory: 16384 };- mockClient.getDeviceSystemInfo.mockResolvedValue({ success: true, systemInfo });-- const proxy = new DeviceGateway();- const result = await proxy.queryDeviceSystemInfo('user-1', 'dev-1');-- expect(result).toEqual(systemInfo);- expect(mockClient.getDeviceSystemInfo).toHaveBeenCalledWith('user-1', 'dev-1', undefined, {- clientKinds: ['desktop'],- });- });-- it('should return undefined when result is not successful', async () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- mockClient.getDeviceSystemInfo.mockResolvedValue({ success: false });-- const proxy = new DeviceGateway();- const result = await proxy.queryDeviceSystemInfo('user-1', 'dev-1');-- expect(result).toBeUndefined();- });-- it('should return undefined on error', async () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- mockClient.getDeviceSystemInfo.mockRejectedValue(new Error('timeout'));-- const proxy = new DeviceGateway();- const result = await proxy.queryDeviceSystemInfo('user-1', 'dev-1');-- expect(result).toBeUndefined();- });-- it('asks the device directly when no maxAge is given', async () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- mockClient.getDeviceSystemInfo.mockResolvedValue({ success: true, systemInfo: {} });-- await new DeviceGateway().queryDeviceSystemInfo('user-1', 'dev-1');-- expect(getRedisServiceClient).not.toHaveBeenCalled();- expect(cacheRedis.get).not.toHaveBeenCalled();- });-- it('serves a recent answer through the cache when maxAge is set', async () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- const systemInfo = { arch: 'arm64' };- mockClient.getDeviceSystemInfo.mockResolvedValue({ success: true, systemInfo });-- const result = await new DeviceGateway().queryDeviceSystemInfo('user-1', 'dev-1', 'ws-1', {- maxAgeMs: 180_000,- });-- expect(result).toEqual(systemInfo);- // The key carries user, pool and device so two principals never share an answer.- expect(cacheRedis.get).toHaveBeenCalledWith('device_system_info:v1:user-1:ws-1:dev-1');- expect(cacheRedis.set).toHaveBeenCalledWith(- 'device_system_info:v1:user-1:ws-1:dev-1',- JSON.stringify(systemInfo),- { px: 180_000 },- );- });- });-- describe('queryDeviceSystemInfo client preference', () => {- const configure = () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- };-- it('falls back to any client when the device has no desktop app', async () => {- configure();- const systemInfo = { arch: 'arm64', userDataPath: '/home/u/.lobehub' };- mockClient.getDeviceSystemInfo- .mockResolvedValueOnce({ error: 'NO_CAPABLE_CONNECTION', success: false })- .mockResolvedValueOnce({ success: true, systemInfo });-- const result = await new DeviceGateway().queryDeviceSystemInfo('user-1', 'dev-1', 'ws-1');-- expect(result).toEqual(systemInfo);- expect(mockClient.getDeviceSystemInfo).toHaveBeenNthCalledWith(1, 'user-1', 'dev-1', 'ws-1', {- clientKinds: ['desktop'],- });- expect(mockClient.getDeviceSystemInfo).toHaveBeenNthCalledWith(- 2,- 'user-1',- 'dev-1',- 'ws-1',- undefined,- );- });-- it.each(['TIMEOUT', 'DEVICE_OFFLINE'])(- 'asks any client when the desktop read fails with %s',- async (error) => {- configure();- const systemInfo = { arch: 'arm64', userDataPath: '/home/u/.lobehub' };- mockClient.getDeviceSystemInfo- .mockResolvedValueOnce({ error, success: false })- .mockResolvedValueOnce({ success: true, systemInfo });-- const result = await new DeviceGateway().queryDeviceSystemInfo('user-1', 'dev-1');-- expect(result).toEqual(systemInfo);- expect(mockClient.getDeviceSystemInfo).toHaveBeenNthCalledWith(- 2,- 'user-1',- 'dev-1',- undefined,- undefined,- );- },- );-- it('asks any client when the desktop read throws', async () => {- configure();- const systemInfo = { arch: 'arm64' };- mockClient.getDeviceSystemInfo- .mockRejectedValueOnce(new Error('fetch failed'))- .mockResolvedValueOnce({ success: true, systemInfo });-- const result = await new DeviceGateway().queryDeviceSystemInfo('user-1', 'dev-1');-- expect(result).toEqual(systemInfo);- });-- it('returns undefined when neither read is answered', async () => {- configure();- mockClient.getDeviceSystemInfo.mockResolvedValue({- error: 'DEVICE_NOT_FOUND',- success: false,- });-- const result = await new DeviceGateway().queryDeviceSystemInfo('user-1', 'dev-1');-- expect(result).toBeUndefined();- expect(mockClient.getDeviceSystemInfo).toHaveBeenCalledTimes(2);- });- });-- describe('readDeviceSystemInfo', () => {- const configure = () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- };-- it('reports an unconfigured gateway', async () => {- const result = await new DeviceGateway().readDeviceSystemInfo('user-1', 'dev-1');- expect(result).toEqual({ ok: false, reason: 'GATEWAY_NOT_CONFIGURED' });- });-- it('returns systemInfo on success', async () => {- configure();- const systemInfo = { arch: 'arm64', supportedTools: ['lobe-computer-use'] };- mockClient.getDeviceSystemInfo.mockResolvedValue({ success: true, systemInfo });-- const result = await new DeviceGateway().readDeviceSystemInfo('user-1', 'dev-1', 'ws-1');-- expect(result).toEqual({ ok: true, systemInfo });- expect(mockClient.getDeviceSystemInfo).toHaveBeenCalledWith(- 'user-1',- 'dev-1',- 'ws-1',- undefined,- );- });-- it("keeps the gateway's reason for an unanswered read", async () => {- configure();- mockClient.getDeviceSystemInfo.mockResolvedValue({ error: 'TIMEOUT', success: false });-- const result = await new DeviceGateway().readDeviceSystemInfo('user-1', 'dev-1');-- expect(result).toEqual({ ok: false, reason: 'TIMEOUT' });- });-- it('classifies a client-side timeout', async () => {- configure();- mockClient.getDeviceSystemInfo.mockRejectedValue(- Object.assign(new Error('The operation timed out.'), { name: 'TimeoutError' }),- );-- const result = await new DeviceGateway().readDeviceSystemInfo('user-1', 'dev-1');-- expect(result).toEqual({ ok: false, reason: 'DEVICE_RESPONSE_TIMEOUT' });- });- });-- describe('queryDeviceMetrics', () => {- const params = { deviceId: 'dev-1', since: 1000, userId: 'user-1', workspaceId: 'ws-1' };- const configure = () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- };-- it('returns the gateway samples', async () => {- configure();- const samples = [{ observedAt: 2000 }];- mockClient.getDeviceMetrics.mockResolvedValue(samples);-- await expect(new DeviceGateway().queryDeviceMetrics(params)).resolves.toEqual(samples);- expect(mockClient.getDeviceMetrics).toHaveBeenCalledWith('user-1', 'dev-1', {- since: 1000,- workspaceId: 'ws-1',- });- });-- it('degrades to no samples when the gateway read fails', async () => {- configure();- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});- mockClient.getDeviceMetrics.mockRejectedValue(- new Error('device metrics read failed: HTTP 500'),- );-- await expect(new DeviceGateway().queryDeviceMetrics(params)).resolves.toEqual([]);- expect(warn).toHaveBeenCalledWith(- expect.stringContaining('device metrics read failed'),- expect.objectContaining({- deviceId: 'dev-1',- error: 'device metrics read failed: HTTP 500',- }),- );- warn.mockRestore();- });- });-- describe('executeToolCall', () => {- const params = { deviceId: 'dev-1', userId: 'user-1' };- const toolCall = { apiName: 'listFiles', arguments: '{}', identifier: 'file-manager' };-- it('should return error when not configured', async () => {- const proxy = new DeviceGateway();- const result = await proxy.executeToolCall(params, toolCall);-- expect(result).toEqual({- content: 'Device Gateway is not configured',- error: 'GATEWAY_NOT_CONFIGURED',- success: false,- });- });-- it('should execute tool call with default timeout', async () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- const expected = { content: 'file list', success: true };- mockClient.executeToolCall.mockResolvedValue(expected);-- const proxy = new DeviceGateway();- const result = await proxy.executeToolCall(params, toolCall);-- expect(result).toEqual(expected);- expect(mockClient.executeToolCall).toHaveBeenCalledWith(- { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },- toolCall,- );- });-- it('should use custom timeout', async () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- mockClient.executeToolCall.mockResolvedValue({ content: 'ok', success: true });-- const proxy = new DeviceGateway();- await proxy.executeToolCall(params, toolCall, 60_000);-- expect(mockClient.executeToolCall).toHaveBeenCalledWith(- { deviceId: 'dev-1', timeout: 60_000, userId: 'user-1' },- toolCall,- );- });-- it('should return error result on Error exception', async () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- mockClient.executeToolCall.mockRejectedValue(new Error('connection refused'));-- const proxy = new DeviceGateway();- const result = await proxy.executeToolCall(params, toolCall);-- // `connection refused` is a network failure, so the model is told the call- // never ran rather than being handed the bare driver message.- expect(result.success).toBe(false);- expect(result.content).toContain('Could not reach the device gateway');- expect(result.error).toBe('DEVICE_GATEWAY_UNREACHABLE: connection refused');- });-- it('should handle non-Error exceptions', async () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- mockClient.executeToolCall.mockRejectedValue('string error');-- const proxy = new DeviceGateway();- const result = await proxy.executeToolCall(params, toolCall);-- // Unrecognised cause: describe the hop without claiming to know whether- // the device ran the call.- expect(result.success).toBe(false);- expect(result.content).toContain('unclear whether the device ran it');- expect(result.error).toBe('DEVICE_GATEWAY_ERROR: string error');- });- });-- describe('executeMcpCall', () => {- const mcpCall = {- apiName: 'getStock',- arguments: '{"symbol":"AAPL"}',- deviceId: 'dev-1',- identifier: 'kimi-datasource',- params: {- args: ['stock-mcp'],- command: 'npx',- env: { TOKEN: 'secret' },- name: 'kimi-datasource',- type: 'stdio' as const,- },- userId: 'user-1',- };-- it('should return error when not configured', async () => {- const proxy = new DeviceGateway();- const result = await proxy.executeMcpCall(mcpCall);-- expect(result).toEqual({- content: 'Device Gateway is not configured',- error: 'GATEWAY_NOT_CONFIGURED',- success: false,- });- });-- it('should forward the mcp call with default timeout', async () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- const expected = { content: 'stock data', state: { rows: 3 }, success: true };- mockClient.executeMcpCall.mockResolvedValue(expected);-- const proxy = new DeviceGateway();- const result = await proxy.executeMcpCall(mcpCall);-- expect(result).toEqual(expected);- expect(mockClient.executeMcpCall).toHaveBeenCalledWith({ ...mcpCall, timeout: 30_000 });- });-- it('should use custom timeout', async () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- mockClient.executeMcpCall.mockResolvedValue({ content: 'ok', success: true });-- const proxy = new DeviceGateway();- await proxy.executeMcpCall(mcpCall, 60_000);-- expect(mockClient.executeMcpCall).toHaveBeenCalledWith({ ...mcpCall, timeout: 60_000 });- });-- it('should return error result on exception', async () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- mockClient.executeMcpCall.mockRejectedValue(new Error('connection refused'));-- const proxy = new DeviceGateway();- const result = await proxy.executeMcpCall(mcpCall);-- // Tunneled MCP calls ride the same relay, so they get the same phrasing.- expect(result.success).toBe(false);- expect(result.content).toContain('Could not reach the device gateway');- expect(result.error).toBe('DEVICE_GATEWAY_UNREACHABLE: connection refused');- });- });-- describe('executeMessageApi', () => {- const params = { deviceId: 'dev-1', userId: 'user-1' };- const api = { apiName: 'sendText', payload: { chatGuid: 'chat-1' }, platform: 'imessage' };-- it('should return error when not configured', async () => {- const proxy = new DeviceGateway();- const result = await proxy.executeMessageApi(params, api);-- expect(result).toEqual({- content: 'Device Gateway is not configured',- error: 'GATEWAY_NOT_CONFIGURED',- success: false,- });- });-- it('should execute message API with default timeout', async () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- const expected = { content: '{"ok":true}', success: true };- mockClient.executeMessageApi.mockResolvedValue(expected);-- const proxy = new DeviceGateway();- const result = await proxy.executeMessageApi(params, api);-- expect(result).toEqual(expected);- expect(mockClient.executeMessageApi).toHaveBeenCalledWith(- { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },- api,- );- });-- it('should use custom timeout', async () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- mockClient.executeMessageApi.mockResolvedValue({ content: 'ok', success: true });-- const proxy = new DeviceGateway();- await proxy.executeMessageApi(params, api, 60_000);-- expect(mockClient.executeMessageApi).toHaveBeenCalledWith(- { deviceId: 'dev-1', timeout: 60_000, userId: 'user-1' },- api,- );- });-- it('should return error result on exception', async () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- mockClient.executeMessageApi.mockRejectedValue(new Error('connection refused'));-- const proxy = new DeviceGateway();- const result = await proxy.executeMessageApi(params, api);-- expect(result).toEqual({- content: 'Device message API error: connection refused',- error: 'connection refused',- success: false,- });- });- });-- describe('initWorkspace', () => {- const configure = () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- };-- it('should return undefined when not configured', async () => {- const proxy = new DeviceGateway();- const result = await proxy.initWorkspace({- deviceId: 'dev-1',- scope: '/proj',- userId: 'user-1',- });- expect(result).toBeUndefined();- expect(mockClient.invokeRpc).not.toHaveBeenCalled();- });-- it('narrows device skills to metadata and passes instructions through', async () => {- configure();- mockClient.invokeRpc.mockResolvedValue({- data: {- instructions: [{ content: '# Rules', source: 'AGENTS.md' }],- // Device returns rich ProjectSkillItems; only prompt metadata survives.- skills: [- {- description: 'spa',- fileCount: 3,- files: ['SKILL.md'],- name: 'spa-routes',- path: '/proj/.agents/skills/spa-routes/SKILL.md',- previewRoot: '/proj',- scope: 'project',- skillDir: '/proj/.agents/skills/spa-routes',- source: '.agents/skills',- },- {- description: 'device',- fileCount: 2,- files: ['SKILL.md', 'refs.md'],- name: 'device-writer',- path: '/home/.agents/skills/device-writer/SKILL.md',- previewRoot: '/home/.agents/skills',- scope: 'device',- skillDir: '/home/.agents/skills/device-writer',- source: '.agents/skills',- },- ],- },- success: true,- });-- const proxy = new DeviceGateway();- const result = await proxy.initWorkspace({- deviceId: 'dev-1',- scope: '/proj',- userId: 'user-1',- });-- expect(result).toEqual({- instructions: [{ content: '# Rules', source: 'AGENTS.md' }],- skills: [- {- description: 'spa',- name: 'spa-routes',- path: '/proj/.agents/skills/spa-routes/SKILL.md',- scope: 'project',- },- {- description: 'device',- name: 'device-writer',- path: '/home/.agents/skills/device-writer/SKILL.md',- scope: 'device',- },- ],- });- expect(mockClient.invokeRpc).toHaveBeenCalledWith(- { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },- { method: 'initWorkspace', params: { scope: '/proj' } },- );- });-- it('defaults instructions and skills to empty arrays when absent', async () => {- configure();- mockClient.invokeRpc.mockResolvedValue({ data: {}, success: true });-- const proxy = new DeviceGateway();- const result = await proxy.initWorkspace({- deviceId: 'dev-1',- scope: '/proj',- userId: 'user-1',- });-- expect(result).toEqual({ instructions: [], skills: [] });- });-- it('returns undefined when the rpc reports failure', async () => {- configure();- mockClient.invokeRpc.mockResolvedValue({ error: 'offline', success: false });-- const proxy = new DeviceGateway();- const result = await proxy.initWorkspace({- deviceId: 'dev-1',- scope: '/proj',- userId: 'user-1',- });-- expect(result).toBeUndefined();- });-- it('returns undefined when the rpc succeeds without data', async () => {- configure();- mockClient.invokeRpc.mockResolvedValue({ success: true });-- const proxy = new DeviceGateway();- const result = await proxy.initWorkspace({- deviceId: 'dev-1',- scope: '/proj',- userId: 'user-1',- });-- expect(result).toBeUndefined();- });-- it('returns undefined on exception', async () => {- configure();- mockClient.invokeRpc.mockRejectedValue(new Error('timeout'));-- const proxy = new DeviceGateway();- const result = await proxy.initWorkspace({- deviceId: 'dev-1',- scope: '/proj',- userId: 'user-1',- });-- expect(result).toBeUndefined();- });-- it('forwards a custom timeout', async () => {- configure();- mockClient.invokeRpc.mockResolvedValue({- data: { instructions: [], skills: [] },- success: true,- });-- const proxy = new DeviceGateway();- await proxy.initWorkspace({- deviceId: 'dev-1',- scope: '/proj',- timeout: 60_000,- userId: 'user-1',- });-- expect(mockClient.invokeRpc).toHaveBeenCalledWith(- { deviceId: 'dev-1', timeout: 60_000, userId: 'user-1' },- { method: 'initWorkspace', params: { scope: '/proj' } },- );- });- });-- describe('listProjectSkills', () => {- const configure = () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- };-- it('should return undefined when not configured', async () => {- const proxy = new DeviceGateway();- const result = await proxy.listProjectSkills({- deviceId: 'dev-1',- scope: '/proj',- userId: 'user-1',- });- expect(result).toBeUndefined();- expect(mockClient.invokeRpc).not.toHaveBeenCalled();- });-- it('passes the device result through and invokes the rpc with scope', async () => {- configure();- const data = {- root: '/proj',- skills: [- {- description: 'spa',- fileCount: 3,- files: ['SKILL.md'],- name: 'spa-routes',- path: '/proj/.agents/skills/spa-routes/SKILL.md',- previewRoot: '/proj',- scope: 'project',- skillDir: '/proj/.agents/skills/spa-routes',- source: '.agents/skills',- },- ],- source: '.agents/skills',- };- mockClient.invokeRpc.mockResolvedValue({ data, success: true });-- const proxy = new DeviceGateway();- const result = await proxy.listProjectSkills({- deviceId: 'dev-1',- scope: '/proj',- userId: 'user-1',- });-- expect(result).toEqual(data);- expect(mockClient.invokeRpc).toHaveBeenCalledWith(- { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },- { method: 'listProjectSkills', params: { scope: '/proj' } },- );- });-- it('returns undefined when the rpc reports failure', async () => {- configure();- mockClient.invokeRpc.mockResolvedValue({ error: 'offline', success: false });-- const proxy = new DeviceGateway();- const result = await proxy.listProjectSkills({- deviceId: 'dev-1',- scope: '/proj',- userId: 'user-1',- });-- expect(result).toBeUndefined();- });-- it('returns undefined when the rpc succeeds without data', async () => {- configure();- mockClient.invokeRpc.mockResolvedValue({ success: true });-- const proxy = new DeviceGateway();- const result = await proxy.listProjectSkills({- deviceId: 'dev-1',- scope: '/proj',- userId: 'user-1',- });-- expect(result).toBeUndefined();- });-- it('returns undefined on exception', async () => {- configure();- mockClient.invokeRpc.mockRejectedValue(new Error('timeout'));-- const proxy = new DeviceGateway();- const result = await proxy.listProjectSkills({- deviceId: 'dev-1',- scope: '/proj',- userId: 'user-1',- });-- expect(result).toBeUndefined();- });-- it('forwards a custom timeout', async () => {- configure();- mockClient.invokeRpc.mockResolvedValue({- data: { root: '/proj', skills: [], source: null },- success: true,- });-- const proxy = new DeviceGateway();- await proxy.listProjectSkills({- deviceId: 'dev-1',- scope: '/proj',- timeout: 60_000,- userId: 'user-1',- });-- expect(mockClient.invokeRpc).toHaveBeenCalledWith(- { deviceId: 'dev-1', timeout: 60_000, userId: 'user-1' },- { method: 'listProjectSkills', params: { scope: '/proj' } },- );- });- });-- describe('getLocalFilePreview', () => {- const configure = () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- };-- it('returns an error result when not configured', async () => {- const proxy = new DeviceGateway();- const result = await proxy.getLocalFilePreview({- deviceId: 'dev-1',- path: '/proj/App.tsx',- userId: 'user-1',- workingDirectory: '/proj',- });-- expect(result).toEqual({ error: 'Device gateway not configured', success: false });- expect(mockClient.invokeRpc).not.toHaveBeenCalled();- });-- it('passes the device preview result through and invokes the rpc', async () => {- configure();- const data = {- preview: {- content: 'const value = 1;',- contentType: 'text/plain',- type: 'text',- },- success: true,- };- mockClient.invokeRpc.mockResolvedValue({ data, success: true });-- const proxy = new DeviceGateway();- const result = await proxy.getLocalFilePreview({- deviceId: 'dev-1',- path: '/proj/App.tsx',- userId: 'user-1',- workingDirectory: '/proj',- });-- expect(result).toEqual(data);- expect(mockClient.invokeRpc).toHaveBeenCalledWith(- { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },- {- method: 'getLocalFilePreview',- params: { accept: undefined, path: '/proj/App.tsx', workingDirectory: '/proj' },- },- );- });-- it('forwards image-only preview constraints to the device rpc', async () => {- configure();- const data = {- preview: {- base64: 'aW1hZ2U=',- contentType: 'image/png',- type: 'image',- },- success: true,- };- mockClient.invokeRpc.mockResolvedValue({ data, success: true });-- const proxy = new DeviceGateway();- await proxy.getLocalFilePreview({- accept: 'image',- deviceId: 'dev-1',- path: '/proj/image.png',- userId: 'user-1',- workingDirectory: '/proj',- });-- expect(mockClient.invokeRpc).toHaveBeenCalledWith(- { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },- {- method: 'getLocalFilePreview',- params: { accept: 'image', path: '/proj/image.png', workingDirectory: '/proj' },- },- );- });-- it('returns an error result when the rpc reports failure', async () => {- configure();- mockClient.invokeRpc.mockResolvedValue({ error: 'offline', success: false });-- const proxy = new DeviceGateway();- const result = await proxy.getLocalFilePreview({- deviceId: 'dev-1',- path: '/proj/App.tsx',- userId: 'user-1',- workingDirectory: '/proj',- });-- expect(result).toEqual({ error: 'offline', success: false });- });- });-- describe('readExternalAssetForPublish', () => {- it('invokes only the dedicated publish RPC method', async () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- const data = { base64: 'AQID', contentType: 'image/png', success: true };- mockClient.invokeRpc.mockResolvedValue({ data, success: true });-- const proxy = new DeviceGateway();- const result = await proxy.readExternalAssetForPublish({- deviceId: 'dev-1',- path: '/outside/image.png',- userId: 'user-1',- workingDirectory: '/proj',- });-- expect(result).toEqual(data);- expect(mockClient.invokeRpc).toHaveBeenCalledWith(- { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },- {- method: 'readExternalAssetForPublish',- params: { path: '/outside/image.png', workingDirectory: '/proj' },- },- );- });- });-- describe('copyAssetForPublish', () => {- it('invokes the copy RPC when the destination is inside the workspace', async () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- mockClient.invokeRpc.mockResolvedValue({ data: { success: true }, success: true });-- const proxy = new DeviceGateway();- const result = await proxy.copyAssetForPublish({- deviceId: 'dev-1',- from: '/outside/image.png',- to: '/proj/.lobe-artifacts/site/image.png',- userId: 'user-1',- workingDirectory: '/proj',- });-- expect(result).toEqual({ success: true });- expect(mockClient.invokeRpc).toHaveBeenCalledWith(- { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },- {- method: 'copyAssetForPublish',- params: {- from: '/outside/image.png',- to: '/proj/.lobe-artifacts/site/image.png',- workingDirectory: '/proj',- },- },- );- });-- it('throws without invoking the rpc when the destination escapes the workspace', async () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- const proxy = new DeviceGateway();-- await expect(- proxy.copyAssetForPublish({- deviceId: 'dev-1',- from: '/outside/image.png',- to: '/proj/../image.png',- userId: 'user-1',- workingDirectory: '/proj',- }),- ).rejects.toThrow(/outside the approved workspace/);- expect(mockClient.invokeRpc).not.toHaveBeenCalled();- });- });-- describe('file mutation containment', () => {- const configure = () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- };-- describe('writeProjectFile', () => {- it('invokes the rpc when the path is inside the workspace', async () => {- configure();- mockClient.invokeRpc.mockResolvedValue({ data: { success: true }, success: true });-- const proxy = new DeviceGateway();- const result = await proxy.writeProjectFile({- content: 'next',- deviceId: 'dev-1',- path: '/proj/src/App.tsx',- userId: 'user-1',- workingDirectory: '/proj',- });-- expect(result).toEqual({ success: true });- expect(mockClient.invokeRpc).toHaveBeenCalledWith(- { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },- {- method: 'writeLocalFile',- params: { content: 'next', path: '/proj/src/App.tsx', workspaceRoot: '/proj' },- },- );- });-- it('throws without invoking the rpc when the path escapes the workspace', async () => {- configure();- const proxy = new DeviceGateway();-- await expect(- proxy.writeProjectFile({- content: 'pwned',- deviceId: 'dev-1',- path: '/etc/passwd',- userId: 'user-1',- workingDirectory: '/proj',- }),- ).rejects.toThrow(/outside the approved workspace/);- expect(mockClient.invokeRpc).not.toHaveBeenCalled();- });-- it('rejects a `..` traversal that resolves outside the workspace', async () => {- configure();- const proxy = new DeviceGateway();-- await expect(- proxy.writeProjectFile({- content: 'pwned',- deviceId: 'dev-1',- path: '/proj/../secrets.env',- userId: 'user-1',- workingDirectory: '/proj',- }),- ).rejects.toThrow(/outside the approved workspace/);- expect(mockClient.invokeRpc).not.toHaveBeenCalled();- });-- it('contains Windows device paths using Windows path semantics', async () => {- configure();- const proxy = new DeviceGateway();-- await expect(- proxy.writeProjectFile({- content: 'pwned',- deviceId: 'dev-1',- path: 'C:\\Windows\\System32\\drivers\\etc\\hosts',- userId: 'user-1',- workingDirectory: 'C:\\proj',- }),- ).rejects.toThrow(/outside the approved workspace/);- expect(mockClient.invokeRpc).not.toHaveBeenCalled();- });- });-- describe('renameProjectFile', () => {- it('throws without invoking the rpc when the path escapes the workspace', async () => {- configure();- const proxy = new DeviceGateway();-- await expect(- proxy.renameProjectFile({- deviceId: 'dev-1',- newName: 'evil.ts',- path: '/etc/hosts',- userId: 'user-1',- workingDirectory: '/proj',- }),- ).rejects.toThrow(/outside the approved workspace/);- expect(mockClient.invokeRpc).not.toHaveBeenCalled();- });- });-- describe('createProjectFile', () => {- it('invokes createLocalFile when the path is inside the workspace', async () => {- configure();- mockClient.invokeRpc.mockResolvedValue({- data: { path: '/proj/new.ts', success: true },- success: true,- });-- const proxy = new DeviceGateway();- const result = await proxy.createProjectFile({- deviceId: 'dev-1',- path: '/proj/new.ts',- userId: 'user-1',- workingDirectory: '/proj',- });-- expect(result).toEqual({ path: '/proj/new.ts', success: true });- expect(mockClient.invokeRpc).toHaveBeenCalledWith(- { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },- {- method: 'createLocalFile',- params: { content: undefined, path: '/proj/new.ts', workspaceRoot: '/proj' },- },- );- });-- it('throws without invoking the rpc when the path escapes the workspace', async () => {- configure();- const proxy = new DeviceGateway();-- await expect(- proxy.createProjectFile({- deviceId: 'dev-1',- path: '/proj/../evil.sh',- userId: 'user-1',- workingDirectory: '/proj',- }),- ).rejects.toThrow(/outside the approved workspace/);- expect(mockClient.invokeRpc).not.toHaveBeenCalled();- });-- it('surfaces a device that has not shipped the rpc yet as an error', async () => {- configure();- mockClient.invokeRpc.mockResolvedValue({- error: 'Unknown device RPC method: createLocalFile',- success: false,- });-- const proxy = new DeviceGateway();- await expect(- proxy.createProjectFile({- deviceId: 'dev-1',- path: '/proj/new.ts',- userId: 'user-1',- workingDirectory: '/proj',- }),- ).rejects.toThrow('Unknown device RPC method: createLocalFile');- });- });-- describe('createProjectDirectory', () => {- it('invokes createLocalDirectory when the path is inside the workspace', async () => {- configure();- mockClient.invokeRpc.mockResolvedValue({- data: { path: '/proj/src/new', success: true },- success: true,- });-- const proxy = new DeviceGateway();- await expect(- proxy.createProjectDirectory({- deviceId: 'dev-1',- path: '/proj/src/new',- userId: 'user-1',- workingDirectory: '/proj',- }),- ).resolves.toEqual({ path: '/proj/src/new', success: true });- expect(mockClient.invokeRpc).toHaveBeenCalledWith(- { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },- {- method: 'createLocalDirectory',- params: { path: '/proj/src/new', workspaceRoot: '/proj' },- },- );- });-- it('throws without invoking the rpc when the path escapes the workspace', async () => {- configure();- const proxy = new DeviceGateway();-- await expect(- proxy.createProjectDirectory({- deviceId: 'dev-1',- path: '/tmp/outside',- userId: 'user-1',- workingDirectory: '/proj',- }),- ).rejects.toThrow(/outside the approved workspace/);- expect(mockClient.invokeRpc).not.toHaveBeenCalled();- });- });-- describe('createDirectory', () => {- it('creates one child of the browsed folder, scoped to that folder', async () => {- configure();- mockClient.invokeRpc.mockResolvedValue({- data: { path: '/home/me/new-project', success: true },- success: true,- });-- const proxy = new DeviceGateway();- await expect(- proxy.createDirectory({- deviceId: 'dev-1',- name: ' new-project ',- parentPath: '/home/me/',- userId: 'user-1',- }),- ).resolves.toEqual({ path: '/home/me/new-project', success: true });- expect(mockClient.invokeRpc).toHaveBeenCalledWith(- { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },- {- method: 'createLocalDirectory',- params: { path: '/home/me/new-project', workspaceRoot: '/home/me/' },- },- );- });-- it.each([- ['/', '/new'],- ['C:\\Users\\me', 'C:\\Users\\me\\new'],- ['C:\\', 'C:\\new'],- ])('joins %s with the device separator', async (parentPath, expected) => {- configure();- mockClient.invokeRpc.mockResolvedValue({- data: { path: expected, success: true },- success: true,- });-- await new DeviceGateway().createDirectory({- deviceId: 'dev-1',- name: 'new',- parentPath,- userId: 'user-1',- });- expect(mockClient.invokeRpc).toHaveBeenCalledWith(expect.anything(), {- method: 'createLocalDirectory',- params: { path: expected, workspaceRoot: parentPath },- });- });-- it.each(['', '.', '..', 'a/b', 'a\\b'])(- 'rejects the folder name %j without invoking the rpc',- async (name) => {- configure();-- await expect(- new DeviceGateway().createDirectory({- deviceId: 'dev-1',- name,- parentPath: '/home/me',- userId: 'user-1',- }),- ).rejects.toThrow(/Invalid folder name/);- expect(mockClient.invokeRpc).not.toHaveBeenCalled();- },- );-- it.each(['a:b', 'CON.txt', 'project.', 'project '])(- 'rejects invalid Windows name %j before invoking the device',- async (name) => {- configure();- await expect(- new DeviceGateway().createDirectory({- deviceId: 'dev-1',- name,- parentPath: 'C:\\Users\\me',- userId: 'user-1',- }),- ).rejects.toThrow(/Invalid folder name/);- expect(mockClient.invokeRpc).not.toHaveBeenCalled();- },- );-- it('rejects a relative parent path without invoking the rpc', async () => {- configure();-- await expect(- new DeviceGateway().createDirectory({- deviceId: 'dev-1',- name: 'new',- parentPath: 'relative/dir',- userId: 'user-1',- }),- ).rejects.toThrow(/must be absolute/);- expect(mockClient.invokeRpc).not.toHaveBeenCalled();- });-- it('returns a device-reported failure instead of throwing', async () => {- configure();- const failure = {- error: 'An item already exists at /home/me/new.',- path: '/home/me/new',- success: false,- };- mockClient.invokeRpc.mockResolvedValue({ data: failure, success: true });-- await expect(- new DeviceGateway().createDirectory({- deviceId: 'dev-1',- name: 'new',- parentPath: '/home/me',- userId: 'user-1',- }),- ).resolves.toEqual(failure);- });-- it('throws when the rpc itself fails', async () => {- configure();- mockClient.invokeRpc.mockResolvedValue({ error: 'Device offline', success: false });-- await expect(- new DeviceGateway().createDirectory({- deviceId: 'dev-1',- name: 'new',- parentPath: '/home/me',- userId: 'user-1',- }),- ).rejects.toThrow('Device offline');- });- });-- describe('copyProjectFiles', () => {- it('invokes copyLocalFiles when source and target stay inside the workspace', async () => {- configure();- mockClient.invokeRpc.mockResolvedValue({- data: [{ sourcePath: '/proj/a.ts', success: true, targetPath: '/proj/a copy.ts' }],- success: true,- });-- const proxy = new DeviceGateway();- const items = [- { sourcePath: '/proj/a.ts' },- { sourcePath: '/proj/b', targetPath: '/proj/c' },- ];- await proxy.copyProjectFiles({- deviceId: 'dev-1',- items,- userId: 'user-1',- workingDirectory: '/proj',- });-- expect(mockClient.invokeRpc).toHaveBeenCalledWith(- { deviceId: 'dev-1', timeout: 60_000, userId: 'user-1' },- { method: 'copyLocalFiles', params: { items, workspaceRoot: '/proj' } },- );- });-- it('throws when a source lies outside the workspace', async () => {- configure();- const proxy = new DeviceGateway();-- await expect(- proxy.copyProjectFiles({- deviceId: 'dev-1',- items: [{ sourcePath: '/Users/me/.ssh/id_rsa', targetPath: '/proj/key' }],- userId: 'user-1',- workingDirectory: '/proj',- }),- ).rejects.toThrow(/outside the approved workspace/);- expect(mockClient.invokeRpc).not.toHaveBeenCalled();- });-- it('throws when a target lies outside the workspace', async () => {- configure();- const proxy = new DeviceGateway();-- await expect(- proxy.copyProjectFiles({- deviceId: 'dev-1',- items: [{ sourcePath: '/proj/secrets.env', targetPath: '/tmp/exfil.env' }],- userId: 'user-1',- workingDirectory: '/proj',- }),- ).rejects.toThrow(/outside the approved workspace/);- expect(mockClient.invokeRpc).not.toHaveBeenCalled();- });-- it('refuses to duplicate the workspace root (the copy would land outside it)', async () => {- configure();- const proxy = new DeviceGateway();-- await expect(- proxy.copyProjectFiles({- deviceId: 'dev-1',- items: [{ sourcePath: '/proj' }],- userId: 'user-1',- workingDirectory: '/proj',- }),- ).rejects.toThrow(/workspace root/);- expect(mockClient.invokeRpc).not.toHaveBeenCalled();- });- });-- describe('trashProjectFiles', () => {- it('invokes trashLocalFiles when every path is inside the workspace', async () => {- configure();- mockClient.invokeRpc.mockResolvedValue({- data: { items: [{ path: '/proj/a.ts', success: true }], success: true },- success: true,- });-- const proxy = new DeviceGateway();- await expect(- proxy.trashProjectFiles({- deviceId: 'dev-1',- paths: ['/proj/a.ts'],- userId: 'user-1',- workingDirectory: '/proj',- }),- ).resolves.toEqual({ items: [{ path: '/proj/a.ts', success: true }], success: true });- expect(mockClient.invokeRpc).toHaveBeenCalledWith(- { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },- { method: 'trashLocalFiles', params: { paths: ['/proj/a.ts'], workspaceRoot: '/proj' } },- );- });-- it('throws when any path escapes the workspace', async () => {- configure();- const proxy = new DeviceGateway();-- await expect(- proxy.trashProjectFiles({- deviceId: 'dev-1',- paths: ['/proj/a.ts', '/Users/me/Documents'],- userId: 'user-1',- workingDirectory: '/proj',- }),- ).rejects.toThrow(/outside the approved workspace/);- expect(mockClient.invokeRpc).not.toHaveBeenCalled();- });-- it.each(['/proj', '/proj/', '/proj/src/..'])(- 'refuses to trash the workspace root itself (%s)',- async (rootPath) => {- configure();- const proxy = new DeviceGateway();-- await expect(- proxy.trashProjectFiles({- deviceId: 'dev-1',- paths: [rootPath],- userId: 'user-1',- workingDirectory: '/proj',- }),- ).rejects.toThrow(/workspace root/);- expect(mockClient.invokeRpc).not.toHaveBeenCalled();- },- );-- it('surfaces a device without a trash as an error, not a delete', async () => {- configure();- mockClient.invokeRpc.mockResolvedValue({- error: 'This device does not support moving files to the trash',- success: false,- });-- const proxy = new DeviceGateway();- await expect(- proxy.trashProjectFiles({- deviceId: 'dev-1',- paths: ['/proj/a.ts'],- userId: 'user-1',- workingDirectory: '/proj',- }),- ).rejects.toThrow('This device does not support moving files to the trash');- expect(mockClient.invokeRpc).toHaveBeenCalledTimes(1);- });- });-- describe('workspace root guard on rename / move', () => {- it('refuses to rename the workspace root itself', async () => {- configure();- const proxy = new DeviceGateway();-- await expect(- proxy.renameProjectFile({- deviceId: 'dev-1',- newName: 'renamed',- path: '/proj',- userId: 'user-1',- workingDirectory: '/proj',- }),- ).rejects.toThrow(/workspace root/);- expect(mockClient.invokeRpc).not.toHaveBeenCalled();- });-- it('refuses to move the workspace root itself', async () => {- configure();- const proxy = new DeviceGateway();-- await expect(- proxy.moveProjectFiles({- deviceId: 'dev-1',- items: [{ newPath: '/proj/inner', oldPath: '/proj' }],- userId: 'user-1',- workingDirectory: '/proj',- }),- ).rejects.toThrow(/workspace root/);- expect(mockClient.invokeRpc).not.toHaveBeenCalled();- });-- it('contains Windows workspace roots with Windows semantics', async () => {- configure();- const proxy = new DeviceGateway();-- await expect(- proxy.trashProjectFiles({- deviceId: 'dev-1',- paths: ['C:\\proj\\'],- userId: 'user-1',- workingDirectory: 'C:\\proj',- }),- ).rejects.toThrow(/workspace root/);- });- });-- describe('moveProjectFiles', () => {- it('throws when any item moves out of the workspace', async () => {- configure();- const proxy = new DeviceGateway();-- await expect(- proxy.moveProjectFiles({- deviceId: 'dev-1',- items: [- { newPath: '/proj/b.ts', oldPath: '/proj/a.ts' },- { newPath: '/tmp/exfil.ts', oldPath: '/proj/c.ts' },- ],- userId: 'user-1',- workingDirectory: '/proj',- }),- ).rejects.toThrow(/outside the approved workspace/);- expect(mockClient.invokeRpc).not.toHaveBeenCalled();- });-- it('invokes the rpc when every item stays inside the workspace', async () => {- configure();- mockClient.invokeRpc.mockResolvedValue({- data: [{ newPath: '/proj/b.ts', sourcePath: '/proj/a.ts', success: true }],- success: true,- });-- const proxy = new DeviceGateway();- const result = await proxy.moveProjectFiles({- deviceId: 'dev-1',- items: [{ newPath: '/proj/b.ts', oldPath: '/proj/a.ts' }],- userId: 'user-1',- workingDirectory: '/proj',- });-- expect(result).toEqual([- { newPath: '/proj/b.ts', sourcePath: '/proj/a.ts', success: true },- ]);- expect(mockClient.invokeRpc).toHaveBeenCalledWith(- { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },- {- method: 'moveLocalFiles',- params: {- items: [{ newPath: '/proj/b.ts', oldPath: '/proj/a.ts' }],- workspaceRoot: '/proj',- },- },- );- });- });- });-- describe('getClient (lazy initialization)', () => {- it('should return null when URL is missing', async () => {- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- const proxy = new DeviceGateway();- const result = await proxy.queryDeviceStatus('user-1');-- expect(result).toEqual({ deviceCount: 0, online: false });- expect(MockGatewayHttpClient).not.toHaveBeenCalled();- });-- it('should return null when token is missing', async () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- const proxy = new DeviceGateway();- const result = await proxy.queryDeviceStatus('user-1');-- expect(result).toEqual({ deviceCount: 0, online: false });- expect(MockGatewayHttpClient).not.toHaveBeenCalled();- });-- it('should create client only once across multiple calls', async () => {- mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';- mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';- mockClient.queryDeviceStatus.mockResolvedValue({ deviceCount: 1, online: true });-- const proxy = new DeviceGateway();- await proxy.queryDeviceStatus('user-1');- await proxy.queryDeviceStatus('user-2');-- expect(MockGatewayHttpClient).toHaveBeenCalledTimes(1);- expect(MockGatewayHttpClient).toHaveBeenCalledWith({- gatewayUrl: 'https://gateway.example.com',- resolveClientKinds: resolveDeviceClientKinds,- serviceToken: 'token',- });- });- });-});diff --git a/apps/server/src/services/deviceGateway/agents.ts b/apps/server/src/services/deviceGateway/agents.tsnew file mode 100644index 00000000000..34731e8eae4--- /dev/null+++ b/apps/server/src/services/deviceGateway/agents.ts@@ -0,0 +1,317 @@+/**+ * Agent-facing device RPCs: CLI quotas and model catalogs, agent run dispatch,+ * and tool / MCP / message-API calls.+ */+import {+ describeGatewayRequestFailure,+ type DeviceMessageApiResult,+ type DeviceToolCallResult,+ type GatewayMcpParams,+} from '@lobechat/device-gateway-client';+import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';+import type {+ ClaudeCodeQuotaSnapshot,+ CodexQuotaSnapshot,+ KimiCodeQuotaSnapshot,+} from '@lobechat/heterogeneous-agents/quota';+import type {+ DeviceClient,+ DeviceUnavailableErrorData,+ HeterogeneousAgentModelCatalog,+} from '@lobechat/types';+import debug from 'debug';++import { invokeDeviceRead } from './deviceRead';+import type { DeviceClientGetter } from './types';++const log = debug('lobe-server:device-gateway');++/**+ * Claude Code subscription quota of the login on a remote device. The device+ * samples the Anthropic usage API with its local credentials β same sampler+ * as the desktop IPC path. `undefined` also covers older device clients that+ * don't know this RPC yet.+ */+export function claudeCodeQuota(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ env?: Record<string, string>;+ force?: boolean;+ userId: string;+ workspaceId?: string;+ },+) {+ return invokeDeviceRead<ClaudeCodeQuotaSnapshot>(getClient, 'getClaudeCodeQuota', params, {+ env: params.env,+ force: params.force,+ });+}++/** Codex subscription quota sampled from the login on a remote device. */+export function codexQuota(+ getClient: DeviceClientGetter,+ params: {+ command?: string;+ deviceId: string;+ env?: Record<string, string>;+ force?: boolean;+ userId: string;+ workspaceId?: string;+ },+) {+ return invokeDeviceRead<CodexQuotaSnapshot>(getClient, 'getCodexQuota', params, {+ command: params.command,+ env: params.env,+ force: params.force,+ });+}++/** Kimi Code subscription quota sampled from the login on a remote device. */+export function kimiCodeQuota(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ env?: Record<string, string>;+ force?: boolean;+ userId: string;+ workspaceId?: string;+ },+) {+ return invokeDeviceRead<KimiCodeQuotaSnapshot>(getClient, 'getKimiCodeQuota', params, {+ env: params.env,+ force: params.force,+ });+}++/** Query a heterogeneous CLI's model catalog on the device that will execute it. */+export async function listHeterogeneousAgentModels(+ getClient: DeviceClientGetter,+ params: {+ args?: string[];+ command?: string;+ cwd?: string;+ deviceId: string;+ env?: Record<string, string>;+ timeout?: number;+ type:+ | 'codebuddy'+ | 'codex'+ | 'cursor'+ | 'devin'+ | 'droid'+ | 'grok-build'+ | 'kimi-code'+ | 'opencode'+ | 'pi'+ | 'qoder'+ | 'trae';+ userId: string;+ workspaceId?: string;+ },+): Promise<HeterogeneousAgentModelCatalog> {+ const { args, command, cwd, deviceId, env, timeout = 20_000, type, userId, workspaceId } = params;+ const client = getClient();+ const unavailable = (message: string): HeterogeneousAgentModelCatalog => ({+ error: { code: 'device_unavailable', message },+ status: 'error',+ updatedAt: Date.now(),+ });+ if (!client) return unavailable('Device gateway is not configured');++ try {+ const result = await client.invokeRpc<HeterogeneousAgentModelCatalog>(+ { deviceId, timeout, userId, workspaceId },+ {+ method: 'listHeterogeneousAgentModels',+ params: { args, command, cwd, env, type },+ },+ );++ if (!result.success || !result.data) {+ const message = result.error || 'The device did not return a model catalog';+ const unsupported =+ message.includes('does not support heterogeneous agent model discovery') ||+ message.includes('Unknown device RPC method');+ log('listHeterogeneousAgentModels: failed for deviceId=%s β %s', deviceId, message);+ return {+ error: { code: unsupported ? 'unsupported_client' : 'device_unavailable', message },+ status: 'error',+ updatedAt: Date.now(),+ };+ }++ return result.data;+ } catch (error) {+ log('listHeterogeneousAgentModels: error for deviceId=%s β %O', deviceId, error);+ return unavailable(error instanceof Error ? error.message : 'Device model discovery failed');+ }+}++export async function dispatchAgentRun(+ getClient: DeviceClientGetter,+ params: {+ agentId?: string;+ agentType: HeterogeneousAgentType;+ assistantMessageId: string;+ /** Resolved `lh hetero exec` wrapper args. */+ args?: string[];+ /** Restricts the run to connections of these clients; omitted means any client. */+ clientKinds?: DeviceClient[];+ cwd?: string;+ deviceId?: string;+ /** Image attachments forwarded to the device as fetchable (signed) URLs. */+ imageList?: Array<{ id?: string; url: string }>;+ jwt: string;+ operationId: string;+ prompt: string;+ resumeFallbackSystemContext?: string;+ resumeSessionId?: string;+ systemContext?: string;+ topicId: string;+ userId: string;+ workspaceId?: string;+ /** Topic/run workspace forwarded to the device for hetero ingest. */+ ingestWorkspaceId?: string;+ },+): Promise<{ error?: string; errorData?: DeviceUnavailableErrorData; success: boolean }> {+ const client = getClient();+ if (!client) return { error: 'GATEWAY_NOT_CONFIGURED', success: false };++ try {+ return await client.dispatchAgentRun(params);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ log('dispatchAgentRun: error β %s', message);+ return { error: message, success: false };+ }+}++export async function executeToolCall(+ getClient: DeviceClientGetter,+ params: {+ clientKinds?: DeviceClient[];+ deviceId: string;+ operationId?: string;+ userId: string;+ workspaceId?: string;+ },+ toolCall: { apiName: string; arguments: string; identifier: string },+ timeout = 30_000,+): Promise<DeviceToolCallResult> {+ const client = getClient();+ if (!client) {+ return {+ content: 'Device Gateway is not configured',+ error: 'GATEWAY_NOT_CONFIGURED',+ success: false,+ };+ }++ log(+ 'executeToolCall: operationId=%s, userId=%s, deviceId=%s, tool=%s/%s',+ params.operationId ?? 'N/A',+ params.userId,+ params.deviceId,+ toolCall.identifier,+ toolCall.apiName,+ );++ try {+ return await client.executeToolCall({ ...params, timeout }, toolCall);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ log('executeToolCall: error β %s', message);+ // Backstop for anything the http client did not already describe. A raw+ // `TimeoutError` / driver message here reads to the model as if the tool+ // itself blew up; name the failing hop and its recovery instead.+ const failure = describeGatewayRequestFailure(error, 'tool call');+ return { content: failure.content, error: failure.error, success: false };+ }+}++/**+ * Tunnel an MCP tool call to a connected device, for MCP servers only the+ * device can reach: stdio (the cloud can't spawn the user's local binary)+ * and localhost / LAN HTTP endpoints (the cloud's fetch can't reach them).+ * The connection params are forwarded so the device runs the call locally.+ */+export async function executeMcpCall(+ getClient: DeviceClientGetter,+ mcpCall: {+ apiName: string;+ arguments: string;+ deviceId: string;+ identifier: string;+ params: GatewayMcpParams;+ userId: string;+ workspaceId?: string;+ },+ timeout = 30_000,+): Promise<DeviceToolCallResult> {+ const client = getClient();+ if (!client) {+ return {+ content: 'Device Gateway is not configured',+ error: 'GATEWAY_NOT_CONFIGURED',+ success: false,+ };+ }++ log(+ 'executeMcpCall: userId=%s, deviceId=%s, mcp=%s/%s',+ mcpCall.userId,+ mcpCall.deviceId,+ mcpCall.identifier,+ mcpCall.apiName,+ );++ try {+ return await client.executeMcpCall({ ...mcpCall, timeout });+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ log('executeMcpCall: error β %s', message);+ const failure = describeGatewayRequestFailure(error, 'tool call');+ return { content: failure.content, error: failure.error, success: false };+ }+}++export async function executeMessageApi(+ getClient: DeviceClientGetter,+ params: { deviceId: string; userId: string; workspaceId?: string },+ api: { apiName: string; payload: Record<string, unknown>; platform: string },+ timeout = 30_000,+): Promise<DeviceMessageApiResult> {+ const client = getClient();+ if (!client) {+ return {+ content: 'Device Gateway is not configured',+ error: 'GATEWAY_NOT_CONFIGURED',+ success: false,+ };+ }++ log(+ 'executeMessageApi: userId=%s, deviceId=%s, api=%s/%s',+ params.userId,+ params.deviceId,+ api.platform,+ api.apiName,+ );++ try {+ return await client.executeMessageApi(+ {+ deviceId: params.deviceId,+ timeout,+ userId: params.userId,+ workspaceId: params.workspaceId,+ },+ api,+ );+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ log('executeMessageApi: error β %s', message);+ return { content: `Device message API error: ${message}`, error: message, success: false };+ }+}diff --git a/apps/server/src/services/deviceGateway/clientUpdate.ts b/apps/server/src/services/deviceGateway/clientUpdate.tsnew file mode 100644index 00000000000..6d41a4b15c6--- /dev/null+++ b/apps/server/src/services/deviceGateway/clientUpdate.ts@@ -0,0 +1,158 @@+/**+ * Remote desktop-app and CLI update RPCs.+ */+import type {+ DeviceAppUpdateFailure,+ DeviceAppUpdateInstallResult,+ DeviceAppUpdateState,+ DeviceAppUpdateStateResult,+ DeviceCliRestartParams,+ DeviceCliUpdateState,+ DeviceCliUpdateStateResult,+} from '@lobechat/types';+import debug from 'debug';++import type { DeviceClientGetter } from './types';++const log = debug('lobe-server:device-gateway');++/** Scope every remote update RPC carries. */+export interface AppUpdateRpcParams {+ deviceId: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+}++/** Where the device's desktop app update stands; never checks on its own. */+export async function getAppUpdateState(+ getClient: DeviceClientGetter,+ params: AppUpdateRpcParams,+): Promise<DeviceAppUpdateStateResult> {+ const result = await invokeAppUpdate<DeviceAppUpdateState>(+ getClient,+ 'getAppUpdateState',+ params,+ );+ return result.status === 'ok' ? { state: result.data, status: 'ok' } : result;+}++/** Start an update check on the device; a found update downloads on its own. */+export async function checkAppUpdate(+ getClient: DeviceClientGetter,+ params: AppUpdateRpcParams,+): Promise<DeviceAppUpdateStateResult> {+ const result = await invokeAppUpdate<DeviceAppUpdateState>(getClient, 'checkAppUpdate', params);+ return result.status === 'ok' ? { state: result.data, status: 'ok' } : result;+}++/** Restart the device's desktop app into its downloaded update. */+export async function installAppUpdate(+ getClient: DeviceClientGetter,+ params: AppUpdateRpcParams,+): Promise<DeviceAppUpdateInstallResult> {+ const result = await invokeAppUpdate<{ targetVersion: string }>(+ getClient,+ 'installAppUpdate',+ params,+ );+ return result.status === 'ok'+ ? { status: 'ok', targetVersion: result.data.targetVersion }+ : result;+}++/**+ * Shared relay for the remote app-update RPCs. Only the desktop app can+ * update itself, so the call asks for the `desktop` channel; an older gateway+ * may still hand it to `lh connect` on the same machine, whose rejection is+ * reported as `unsupported` like an outdated desktop's.+ */+export async function invokeAppUpdate<T>(+ getClient: DeviceClientGetter,+ method: 'checkAppUpdate' | 'getAppUpdateState' | 'installAppUpdate',+ params: AppUpdateRpcParams,+): Promise<{ data: T; status: 'ok' } | { message: string; status: DeviceAppUpdateFailure }> {+ const { deviceId, timeout = 15_000, userId, workspaceId } = params;+ const client = getClient();+ if (!client) return { message: 'Device Gateway is not configured', status: 'unavailable' };++ try {+ const result = await client.invokeRpc<T>(+ { channel: 'desktop', deviceId, timeout, userId, workspaceId },+ { method },+ );+ if (result.success && result.data !== undefined) return { data: result.data, status: 'ok' };++ const message = result.error || `${method} failed`;+ log('%s: failed for deviceId=%s β %s', method, deviceId, message);+ const unsupported =+ message.includes('does not support remote updates') ||+ message.includes('Unknown device RPC method');+ return { message, status: unsupported ? 'unsupported' : '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' };+ }+}++export async function getCliUpdateState(+ getClient: DeviceClientGetter,+ params: AppUpdateRpcParams,+): Promise<DeviceCliUpdateStateResult> {+ return invokeCliUpdate(getClient, 'getCliUpdateState', params);+}++export async function checkCliUpdate(+ getClient: DeviceClientGetter,+ params: AppUpdateRpcParams,+): Promise<DeviceCliUpdateStateResult> {+ return invokeCliUpdate(getClient, 'checkCliUpdate', params);+}++export async function restartCli(+ getClient: DeviceClientGetter,+ params: AppUpdateRpcParams & DeviceCliRestartParams,+): Promise<DeviceCliUpdateStateResult> {+ return invokeCliUpdate(getClient, 'restartCli', params, {+ requestId: params.requestId,+ update: params.update,+ });+}++export async function invokeCliUpdate(+ getClient: DeviceClientGetter,+ method: 'getCliUpdateState' | 'checkCliUpdate' | 'restartCli',+ params: AppUpdateRpcParams,+ restartParams?: DeviceCliRestartParams,+): Promise<DeviceCliUpdateStateResult> {+ const { deviceId, timeout = 15_000, userId, workspaceId } = params;+ const client = 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' };+ }+}diff --git a/apps/server/src/services/deviceGateway/deviceRead.ts b/apps/server/src/services/deviceGateway/deviceRead.tsnew file mode 100644index 00000000000..3d80ed43a9c--- /dev/null+++ b/apps/server/src/services/deviceGateway/deviceRead.ts@@ -0,0 +1,42 @@+/**+ * Shared relay for the best-effort granular device reads (git, quota).+ */+import debug from 'debug';++import type { DeviceClientGetter } from './types';++const log = debug('lobe-server:device-gateway');++/**+ * Generic helper for granular device read RPCs (git branch / PR /+ * working-tree / ahead-behind / Claude quota). Returns `undefined` when the+ * gateway is unconfigured, the device is offline, or the call fails β+ * callers treat that as "unknown".+ */+export async function invokeDeviceRead<T>(+ getClient: DeviceClientGetter,+ method: string,+ params: { deviceId: string; timeout?: number; userId: string; workspaceId?: string },+ rpcParams: Record<string, unknown>,+): Promise<T | undefined> {+ const { userId, deviceId, timeout = 15_000, workspaceId } = params;+ const client = getClient();+ if (!client) return undefined;++ try {+ const result = await client.invokeRpc<T>(+ { deviceId, timeout, userId, workspaceId },+ { method, params: rpcParams },+ );++ if (!result.success || result.data === undefined) {+ log('%s: failed for deviceId=%s β %s', method, deviceId, result.error);+ return undefined;+ }++ return result.data;+ } catch (error) {+ log('%s: error for deviceId=%s β %O', method, deviceId, error);+ return undefined;+ }+}diff --git a/apps/server/src/services/deviceGateway/gitRead.ts b/apps/server/src/services/deviceGateway/gitRead.tsnew file mode 100644index 00000000000..5665b20df51--- /dev/null+++ b/apps/server/src/services/deviceGateway/gitRead.ts@@ -0,0 +1,361 @@+/**+ * Best-effort git reads on a remote device; a failure reads as "unknown" (`undefined`).+ */+import type {+ DeviceGitAheadBehind,+ DeviceGitBranchDiffPatches,+ DeviceGitBranchInfo,+ DeviceGitBranchListItem,+ DeviceGitLinkedPullRequestResult,+ DeviceGitPullRequestActivity,+ DeviceGitPullRequestDetailResult,+ DeviceGitPullRequestMergeContext,+ DeviceGitRemoteBranchListItem,+ DeviceGitWorkingTreeFiles,+ DeviceGitWorkingTreePatches,+ DeviceGitWorkingTreeStatus,+ DeviceGitWorktreeListItem,+} from '@lobechat/types';+import debug from 'debug';++import { invokeDeviceRead } from './deviceRead';+import type { DeviceClientGetter } from './types';++const log = debug('lobe-server:device-gateway');++/** Branch name + detached flag for a directory on a remote device. */+export function gitBranch(+ getClient: DeviceClientGetter,+ params: { deviceId: string; path: string; userId: string; workspaceId?: string },+) {+ return invokeDeviceRead<DeviceGitBranchInfo>(getClient, 'getGitBranch', params, {+ path: params.path,+ });+}++/** The GitHub PR linked to a branch in a directory on a remote device. */+export function gitLinkedPullRequest(+ getClient: DeviceClientGetter,+ params: {+ branch: string;+ deviceId: string;+ path: string;+ pullRequestNumber?: number;+ userId: string;+ workspaceId?: string;+ },+) {+ return invokeDeviceRead<DeviceGitLinkedPullRequestResult>(+ getClient,+ 'getLinkedPullRequest',+ params,+ {+ branch: params.branch,+ path: params.path,+ pullRequestNumber: params.pullRequestNumber,+ },+ );+}++/** Full detail of a pull request in a directory on a remote device. */+export function gitPullRequestDetail(+ getClient: DeviceClientGetter,+ params: {+ coreOnly?: boolean;+ deviceId: string;+ number: number;+ path: string;+ userId: string;+ workspaceId?: string;+ },+) {+ return invokeDeviceRead<DeviceGitPullRequestDetailResult>(+ getClient,+ 'getPullRequestDetail',+ { ...params, timeout: 20_000 },+ {+ coreOnly: params.coreOnly,+ number: params.number,+ path: params.path,+ },+ );+}++export function gitPullRequestActivity(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ number: number;+ path: string;+ userId: string;+ workspaceId?: string;+ },+) {+ return invokeDeviceRead<DeviceGitPullRequestActivity>(+ getClient,+ 'getPullRequestActivity',+ { ...params, timeout: 20_000 },+ {+ number: params.number,+ path: params.path,+ },+ );+}++/** Branch-protection / permission context for a pull request on a remote device. */+export function gitPullRequestMergeContext(+ getClient: DeviceClientGetter,+ params: {+ baseRefName: string;+ deviceId: string;+ headRefOid: string;+ number: number;+ path: string;+ repo: { name: string; owner: string };+ userId: string;+ workspaceId?: string;+ },+) {+ return invokeDeviceRead<DeviceGitPullRequestMergeContext>(+ getClient,+ 'getPullRequestMergeContext',+ { ...params, timeout: 20_000 },+ {+ baseRefName: params.baseRefName,+ headRefOid: params.headRefOid,+ number: params.number,+ path: params.path,+ repo: params.repo,+ },+ );+}++/** Working-tree dirty-file counts for a directory on a remote device. */+export function gitWorkingTreeStatus(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ path: string;+ userId: string;+ workspaceId?: string;+ },+) {+ return invokeDeviceRead<DeviceGitWorkingTreeStatus>(+ getClient,+ 'getGitWorkingTreeStatus',+ params,+ {+ path: params.path,+ },+ );+}++/** Ahead/behind commit counts for a directory on a remote device. */+export function gitAheadBehind(+ getClient: DeviceClientGetter,+ params: { deviceId: string; path: string; userId: string; workspaceId?: string },+) {+ return invokeDeviceRead<DeviceGitAheadBehind>(getClient, 'getGitAheadBehind', params, {+ path: params.path,+ });+}++/** Git worktrees attached to the same repository as a directory on a remote device. */+export function listGitWorktrees(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ path: string;+ userId: string;+ workspaceId?: string;+ },+) {+ return invokeDeviceRead<DeviceGitWorktreeListItem[]>(getClient, 'listGitWorktrees', params, {+ path: params.path,+ });+}++/**+ * List the local branches of a directory on a remote device via the+ * `listGitBranches` device RPC, so the web/remote branch switcher can populate+ * the same dropdown the local desktop renders over IPC.+ */+export async function listGitBranches(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ path: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+ },+): Promise<DeviceGitBranchListItem[] | undefined> {+ const { userId, deviceId, path, timeout = 15_000, workspaceId } = params;+ const client = getClient();+ if (!client) return undefined;++ try {+ const result = await client.invokeRpc<DeviceGitBranchListItem[]>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'listGitBranches', params: { path } },+ );++ if (!result.success || !result.data) {+ log('listGitBranches: failed for deviceId=%s β %s', deviceId, result.error);+ return undefined;+ }++ return result.data;+ } catch (error) {+ log('listGitBranches: error for deviceId=%s β %O', deviceId, error);+ return undefined;+ }+}++/**+ * Working-tree (unstaged) per-file patches for a directory on a remote device+ * via the `getGitWorkingTreePatches` device RPC, so the web/remote Review panel+ * renders the same diffs the local desktop shows over IPC.+ */+export async function getGitWorkingTreePatches(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ path: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+ },+): Promise<DeviceGitWorkingTreePatches | undefined> {+ const { userId, deviceId, path, timeout = 30_000, workspaceId } = params;+ const client = getClient();+ if (!client) return undefined;++ try {+ const result = await client.invokeRpc<DeviceGitWorkingTreePatches>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'getGitWorkingTreePatches', params: { path } },+ );++ if (!result.success || !result.data) {+ log('getGitWorkingTreePatches: failed for deviceId=%s β %s', deviceId, result.error);+ return undefined;+ }++ return result.data;+ } catch (error) {+ log('getGitWorkingTreePatches: error for deviceId=%s β %O', deviceId, error);+ return undefined;+ }+}++/**+ * Branch diff (current branch vs base ref) per-file patches for a directory on+ * a remote device via the `getGitBranchDiff` device RPC.+ */+export async function getGitBranchDiff(+ getClient: DeviceClientGetter,+ params: {+ baseRef?: string;+ deviceId: string;+ path: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+ },+): Promise<DeviceGitBranchDiffPatches | undefined> {+ const { userId, deviceId, baseRef, path, timeout = 30_000, workspaceId } = params;+ const client = getClient();+ if (!client) return undefined;++ try {+ const result = await client.invokeRpc<DeviceGitBranchDiffPatches>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'getGitBranchDiff', params: { baseRef, path } },+ );++ if (!result.success || !result.data) {+ log('getGitBranchDiff: failed for deviceId=%s β %s', deviceId, result.error);+ return undefined;+ }++ return result.data;+ } catch (error) {+ log('getGitBranchDiff: error for deviceId=%s β %O', deviceId, error);+ return undefined;+ }+}++/**+ * Repo-relative paths of dirty working-tree files for a directory on a remote+ * device via the `getGitWorkingTreeFiles` device RPC β the Files tab's git+ * status overlay.+ */+export async function getGitWorkingTreeFiles(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ path: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+ },+): Promise<DeviceGitWorkingTreeFiles | undefined> {+ const { userId, deviceId, path, timeout = 15_000, workspaceId } = params;+ const client = getClient();+ if (!client) return undefined;++ try {+ const result = await client.invokeRpc<DeviceGitWorkingTreeFiles>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'getGitWorkingTreeFiles', params: { path } },+ );++ if (!result.success || !result.data) {+ log('getGitWorkingTreeFiles: failed for deviceId=%s β %s', deviceId, result.error);+ return undefined;+ }++ return result.data;+ } catch (error) {+ log('getGitWorkingTreeFiles: error for deviceId=%s β %O', deviceId, error);+ return undefined;+ }+}++/**+ * List the remote branches (`refs/remotes/origin/*`) of a directory on a+ * remote device via the `listGitRemoteBranches` device RPC, so the web/remote+ * Review base-ref picker mirrors the local desktop's.+ */+export async function listGitRemoteBranches(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ path: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+ },+): Promise<DeviceGitRemoteBranchListItem[] | undefined> {+ const { userId, deviceId, path, timeout = 15_000, workspaceId } = params;+ const client = getClient();+ if (!client) return undefined;++ try {+ const result = await client.invokeRpc<DeviceGitRemoteBranchListItem[]>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'listGitRemoteBranches', params: { path } },+ );++ if (!result.success || !result.data) {+ log('listGitRemoteBranches: failed for deviceId=%s β %s', deviceId, result.error);+ return undefined;+ }++ return result.data;+ } catch (error) {+ log('listGitRemoteBranches: error for deviceId=%s β %O', deviceId, error);+ return undefined;+ }+}diff --git a/apps/server/src/services/deviceGateway/gitWrite.ts b/apps/server/src/services/deviceGateway/gitWrite.tsnew file mode 100644index 00000000000..8529d82fbc4--- /dev/null+++ b/apps/server/src/services/deviceGateway/gitWrite.ts@@ -0,0 +1,355 @@+/**+ * Git mutations on a remote device; failures come back as `{ error, success: false }`.+ */+import type {+ DeviceGitAddWorktreeResult,+ DeviceGitCheckoutResult,+ DeviceGitDeleteBranchResult,+ DeviceGitFileRevertResult,+ DeviceGitPullRequestAction,+ DeviceGitPullRequestActionResult,+ DeviceGitRemoveWorktreeResult,+ DeviceGitRenameBranchResult,+ DeviceGitSyncResult,+} from '@lobechat/types';+import debug from 'debug';++import type { DeviceClientGetter } from './types';++const log = debug('lobe-server:device-gateway');++/**+ * Checkout (or create) a branch in a directory on a remote device via the+ * `checkoutGitBranch` device RPC.+ */+export async function checkoutGitBranch(+ getClient: DeviceClientGetter,+ params: {+ branch: string;+ create?: boolean;+ deviceId: string;+ path: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+ },+): Promise<DeviceGitCheckoutResult> {+ const { userId, deviceId, branch, create, path, timeout = 30_000, workspaceId } = params;+ const client = getClient();+ if (!client) return { error: 'Device gateway not configured', success: false };++ try {+ const result = await client.invokeRpc<DeviceGitCheckoutResult>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'checkoutGitBranch', params: { branch, create, path } },+ );++ if (!result.success || !result.data) {+ log('checkoutGitBranch: failed for deviceId=%s β %s', deviceId, result.error);+ return { error: result.error || 'Checkout failed', success: false };+ }++ return result.data;+ } catch (error) {+ log('checkoutGitBranch: error for deviceId=%s β %O', deviceId, error);+ return { error: (error as Error)?.message || 'Checkout failed', success: false };+ }+}++/**+ * Rename a branch in a directory on a remote device via the `renameGitBranch`+ * device RPC.+ */+export async function renameGitBranch(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ from: string;+ path: string;+ timeout?: number;+ to: string;+ userId: string;+ workspaceId?: string;+ },+): Promise<DeviceGitRenameBranchResult> {+ const { userId, deviceId, from, to, path, timeout = 30_000, workspaceId } = params;+ const client = getClient();+ if (!client) return { error: 'Device gateway not configured', success: false };++ try {+ const result = await client.invokeRpc<DeviceGitRenameBranchResult>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'renameGitBranch', params: { from, path, to } },+ );++ if (!result.success || !result.data) {+ log('renameGitBranch: failed for deviceId=%s β %s', deviceId, result.error);+ return { error: result.error || 'Rename failed', success: false };+ }++ return result.data;+ } catch (error) {+ log('renameGitBranch: error for deviceId=%s β %O', deviceId, error);+ return { error: (error as Error)?.message || 'Rename failed', success: false };+ }+}++/**+ * Delete a branch in a directory on a remote device via the `deleteGitBranch`+ * device RPC.+ */+export async function deleteGitBranch(+ getClient: DeviceClientGetter,+ params: {+ branch: string;+ deviceId: string;+ path: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+ },+): Promise<DeviceGitDeleteBranchResult> {+ const { userId, deviceId, branch, path, timeout = 30_000, workspaceId } = params;+ const client = getClient();+ if (!client) return { error: 'Device gateway not configured', success: false };++ try {+ const result = await client.invokeRpc<DeviceGitDeleteBranchResult>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'deleteGitBranch', params: { branch, path } },+ );++ if (!result.success || !result.data) {+ log('deleteGitBranch: failed for deviceId=%s β %s', deviceId, result.error);+ return { error: result.error || 'Delete failed', success: false };+ }++ return result.data;+ } catch (error) {+ log('deleteGitBranch: error for deviceId=%s β %O', deviceId, error);+ return { error: (error as Error)?.message || 'Delete failed', success: false };+ }+}++/**+ * Remove a worktree in a directory's repository on a remote device via+ * the `removeGitWorktree` device RPC.+ */+export async function removeGitWorktree(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ path: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+ worktreePath: string;+ },+): Promise<DeviceGitRemoveWorktreeResult> {+ const { userId, deviceId, path, worktreePath, workspaceId, timeout = 30_000 } = params;+ const client = getClient();+ if (!client) return { error: 'Device gateway not configured', success: false };++ try {+ const result = await client.invokeRpc<DeviceGitRemoveWorktreeResult>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'removeGitWorktree', params: { path, worktreePath } },+ );++ if (!result.success || !result.data) {+ log('removeGitWorktree: failed for deviceId=%s β %s', deviceId, result.error);+ return { error: result.error || 'Remove worktree failed', success: false };+ }++ return result.data;+ } catch (error) {+ log('removeGitWorktree: error for deviceId=%s β %O', deviceId, error);+ return { error: (error as Error)?.message || 'Remove worktree failed', success: false };+ }+}++/**+ * Add a linked worktree on a fresh branch in a directory's repository on a+ * remote device via the `addGitWorktree` device RPC.+ */+export async function addGitWorktree(+ getClient: DeviceClientGetter,+ params: {+ branch: string;+ deviceId: string;+ path: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+ worktreePath: string;+ },+): Promise<DeviceGitAddWorktreeResult> {+ const { userId, deviceId, branch, path, worktreePath, workspaceId, timeout = 30_000 } = params;+ const client = getClient();+ if (!client) return { error: 'Device gateway not configured', success: false };++ try {+ const result = await client.invokeRpc<DeviceGitAddWorktreeResult>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'addGitWorktree', params: { branch, path, worktreePath } },+ );++ if (!result.success || !result.data) {+ log('addGitWorktree: failed for deviceId=%s β %s', deviceId, result.error);+ return { error: result.error || 'Add worktree failed', success: false };+ }++ return result.data;+ } catch (error) {+ log('addGitWorktree: error for deviceId=%s β %O', deviceId, error);+ return { error: (error as Error)?.message || 'Add worktree failed', success: false };+ }+}++/**+ * Pull (`--ff-only`) the current branch of a directory on a remote device via+ * the `pullGitBranch` device RPC.+ */+export async function pullGitBranch(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ path: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+ },+): Promise<DeviceGitSyncResult> {+ const { userId, deviceId, path, timeout = 65_000, workspaceId } = params;+ const client = getClient();+ if (!client) return { error: 'Device gateway not configured', success: false };++ try {+ const result = await client.invokeRpc<DeviceGitSyncResult>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'pullGitBranch', params: { path } },+ );++ if (!result.success || !result.data) {+ log('pullGitBranch: failed for deviceId=%s β %s', deviceId, result.error);+ return { error: result.error || 'Pull failed', success: false };+ }++ return result.data;+ } catch (error) {+ log('pullGitBranch: error for deviceId=%s β %O', deviceId, error);+ return { error: (error as Error)?.message || 'Pull failed', success: false };+ }+}++/**+ * Push the current branch of a directory on a remote device via the+ * `pushGitBranch` device RPC.+ */+export async function pushGitBranch(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ path: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+ },+): Promise<DeviceGitSyncResult> {+ const { userId, deviceId, path, timeout = 65_000, workspaceId } = params;+ const client = getClient();+ if (!client) return { error: 'Device gateway not configured', success: false };++ try {+ const result = await client.invokeRpc<DeviceGitSyncResult>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'pushGitBranch', params: { path } },+ );++ if (!result.success || !result.data) {+ log('pushGitBranch: failed for deviceId=%s β %s', deviceId, result.error);+ return { error: result.error || 'Push failed', success: false };+ }++ return result.data;+ } catch (error) {+ log('pushGitBranch: error for deviceId=%s β %O', deviceId, error);+ return { error: (error as Error)?.message || 'Push failed', success: false };+ }+}++/**+ * Run a `gh pr` mutation (merge, auto-merge, ready, comment, close, ...) on a+ * directory on a remote device via the `runPullRequestAction` device RPC.+ * Merge can take a while, so it gets the same 65s budget as push/pull.+ */+export async function runGitPullRequestAction(+ getClient: DeviceClientGetter,+ params: {+ action: DeviceGitPullRequestAction;+ deviceId: string;+ number: number;+ path: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+ },+): Promise<DeviceGitPullRequestActionResult> {+ const { userId, deviceId, path, number, action, timeout = 65_000, workspaceId } = params;+ const client = getClient();+ if (!client) return { error: 'Device gateway not configured', success: false };++ try {+ const result = await client.invokeRpc<DeviceGitPullRequestActionResult>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'runPullRequestAction', params: { action, number, path } },+ );++ if (!result.success || !result.data) {+ log('runGitPullRequestAction: failed for deviceId=%s β %s', deviceId, result.error);+ return { error: result.error || 'Pull request action failed', success: false };+ }++ return result.data;+ } catch (error) {+ log('runGitPullRequestAction: error for deviceId=%s β %O', deviceId, error);+ return { error: (error as Error)?.message || 'Pull request action failed', success: false };+ }+}++/**+ * Revert (discard working-tree changes to) a single file in a directory on a+ * remote device via the `revertGitFile` device RPC.+ */+export async function revertGitFile(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ filePath: string;+ path: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+ },+): Promise<DeviceGitFileRevertResult> {+ const { userId, deviceId, filePath, path, timeout = 15_000, workspaceId } = params;+ const client = getClient();+ if (!client) return { error: 'Device gateway not configured', success: false };++ try {+ const result = await client.invokeRpc<DeviceGitFileRevertResult>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'revertGitFile', params: { filePath, path } },+ );++ if (!result.success || !result.data) {+ log('revertGitFile: failed for deviceId=%s β %s', deviceId, result.error);+ return { error: result.error || 'Revert failed', success: false };+ }++ return result.data;+ } catch (error) {+ log('revertGitFile: error for deviceId=%s β %O', deviceId, error);+ return { error: (error as Error)?.message || 'Revert failed', success: false };+ }+}diff --git a/apps/server/src/services/deviceGateway/index.devices.test.ts b/apps/server/src/services/deviceGateway/index.devices.test.tsnew file mode 100644index 00000000000..637504f3583--- /dev/null+++ b/apps/server/src/services/deviceGateway/index.devices.test.ts@@ -0,0 +1,522 @@+import type * as DeviceGatewayClientModule from '@lobechat/device-gateway-client';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { DeviceGateway } from '.';+import { resolveDeviceClientKinds } from './clientKinds';+import {+ cacheRedis,+ getRedisServiceClient,+ mockClient,+ mockEnv,+ MockGatewayHttpClient,+ resetGatewayMocks,+} from './testUtils';++vi.mock('@/server/services/redis/client', () =>+ import('./testUtils').then((m) => ({ getRedisServiceClient: m.getRedisServiceClient })),+);++vi.mock('@/envs/gateway', () => import('./testUtils').then((m) => ({ gatewayEnv: m.mockEnv })));++// Partial mock: only the HTTP client is swapped. The transport-failure+// describers are pure functions the service calls to phrase its errors, and+// stubbing them would test nothing.+vi.mock('@lobechat/device-gateway-client', async (importOriginal) => ({+ ...(await importOriginal<typeof DeviceGatewayClientModule>()),+ GatewayHttpClient: (await import('./testUtils')).MockGatewayHttpClient,+}));++describe('DeviceGateway', () => {+ beforeEach(() => {+ resetGatewayMocks();+ });++ describe('isConfigured', () => {+ it('should return false when DEVICE_GATEWAY_URL is not set', () => {+ const proxy = new DeviceGateway();+ expect(proxy.isConfigured).toBe(false);+ });++ it('should return true when DEVICE_GATEWAY_URL is set', () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ const proxy = new DeviceGateway();+ expect(proxy.isConfigured).toBe(true);+ });+ });++ describe('queryDeviceStatus', () => {+ it('should return offline status when not configured', async () => {+ const proxy = new DeviceGateway();+ const result = await proxy.queryDeviceStatus('user-1');+ expect(result).toEqual({ deviceCount: 0, online: false });+ });++ it('should return status from client on success', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ const expected = { deviceCount: 2, online: true };+ mockClient.queryDeviceStatus.mockResolvedValue(expected);++ const proxy = new DeviceGateway();+ const result = await proxy.queryDeviceStatus('user-1');++ expect(result).toEqual(expected);+ expect(mockClient.queryDeviceStatus).toHaveBeenCalledWith('user-1', undefined);+ });++ it('should return offline status on error', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ mockClient.queryDeviceStatus.mockRejectedValue(new Error('network error'));++ const proxy = new DeviceGateway();+ const result = await proxy.queryDeviceStatus('user-1');++ expect(result).toEqual({ deviceCount: 0, online: false });+ });+ });++ describe('queryDeviceList', () => {+ it('should return empty array when not configured', async () => {+ const proxy = new DeviceGateway();+ const result = await proxy.queryDeviceList('user-1');+ expect(result).toEqual([]);+ });++ it('should map device-centric channels to lastSeen + online and flatten channels', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ const connectedAt = Date.parse('2025-01-15T10:30:00Z');+ const iso = new Date(connectedAt).toISOString();+ mockClient.queryDeviceList.mockResolvedValue([+ {+ channels: [+ { channel: 'desktop', connectedAt, connectionId: 'conn-a' },+ { channel: 'cli', connectedAt, connectionId: 'conn-b' },+ ],+ connectedAt,+ deviceId: 'dev-1',+ hostname: 'my-laptop',+ platform: 'darwin',+ },+ {+ channels: [{ channel: 'desktop', connectedAt, connectionId: 'conn-c' }],+ connectedAt,+ deviceId: 'dev-2',+ hostname: 'my-desktop',+ platform: 'win32',+ },+ ]);++ const proxy = new DeviceGateway();+ const result = await proxy.queryDeviceList('user-1');++ expect(result).toEqual([+ {+ channels: [+ { channel: 'desktop', connectedAt: iso, connectionId: 'conn-a' },+ { channel: 'cli', connectedAt: iso, connectionId: 'conn-b' },+ ],+ deviceId: 'dev-1',+ hostname: 'my-laptop',+ lastSeen: iso,+ online: true,+ platform: 'darwin',+ },+ {+ channels: [{ channel: 'desktop', connectedAt: iso, connectionId: 'conn-c' }],+ deviceId: 'dev-2',+ hostname: 'my-desktop',+ lastSeen: iso,+ online: true,+ platform: 'win32',+ },+ ]);+ expect(mockClient.queryDeviceList).toHaveBeenCalledWith('user-1', undefined);+ });++ /**+ * The gateway promises no channel order, but every consumer reads+ * `channels[0]` as the device's current connection β the settings row's+ * "Connected {time}", a ghost row's `lastSeen`/hostname/platform β while+ * `sortDevicesByActivity` ranks by the freshest channel. Leave the pool raw+ * and a multi-channel device gets ranked by one connection and labelled+ * with another, which reads as a broken sort.+ */+ it('sorts channels newest-first so channels[0] is the current connection', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ const older = Date.parse('2025-01-15T10:30:00Z');+ const newest = Date.parse('2025-03-20T08:00:00Z');+ const middle = Date.parse('2025-02-01T12:00:00Z');+ mockClient.queryDeviceList.mockResolvedValue([+ {+ // Deliberately unordered, with the newest NOT first.+ channels: [+ { channel: 'cli', connectedAt: older, connectionId: 'conn-old' },+ { channel: 'desktop', connectedAt: newest, connectionId: 'conn-new' },+ { channel: 'mobile', connectedAt: middle, connectionId: 'conn-mid' },+ ],+ connectedAt: older,+ deviceId: 'dev-1',+ hostname: 'my-laptop',+ platform: 'darwin',+ },+ ]);++ const proxy = new DeviceGateway();+ const result = await proxy.queryDeviceList('user-1');++ expect(result[0]?.channels?.map((c) => c.connectionId)).toEqual([+ 'conn-new',+ 'conn-mid',+ 'conn-old',+ ]);+ });++ it('tolerates a legacy gateway response without channels', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ const connectedAt = Date.parse('2025-01-15T10:30:00Z');+ mockClient.queryDeviceList.mockResolvedValue([+ { connectedAt, deviceId: 'dev-1', hostname: 'my-laptop', platform: 'darwin' },+ ]);++ const proxy = new DeviceGateway();+ const result = await proxy.queryDeviceList('user-1');++ expect(result).toEqual([+ {+ channels: [],+ deviceId: 'dev-1',+ hostname: 'my-laptop',+ lastSeen: new Date(connectedAt).toISOString(),+ online: true,+ platform: 'darwin',+ },+ ]);+ });++ it('absorbs a transient failure instead of reporting an empty pool', async () => {+ // The online set decides which devices a run may reach, so one dropped+ // connection must not read as "every device is offline".+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ const connectedAt = Date.parse('2025-01-15T10:30:00Z');+ mockClient.queryDeviceList+ .mockRejectedValueOnce(new Error('fetch failed'))+ .mockResolvedValueOnce([+ { connectedAt, deviceId: 'dev-1', hostname: 'my-laptop', platform: 'darwin' },+ ]);++ const result = await new DeviceGateway().queryDeviceList('user-1');++ expect(mockClient.queryDeviceList).toHaveBeenCalledTimes(2);+ expect(result).toHaveLength(1);+ expect(result[0]).toMatchObject({ deviceId: 'dev-1', online: true });+ });++ it('reports the fallback out loud when the gateway stays unreachable', async () => {+ // The old bare `catch {}` made this failure invisible: a device-bound run+ // degraded to the cloud sandbox with no breadcrumb in any log.+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ mockClient.queryDeviceList.mockRejectedValue(new Error('fetch failed'));+ const warn = vi.spyOn(console, 'warn').mockImplementation(function () {});++ const result = await new DeviceGateway().queryDeviceList('user-1', 'ws-1');++ expect(result).toEqual([]);+ expect(warn).toHaveBeenCalledWith(+ expect.stringContaining('queryDeviceList'),+ expect.objectContaining({ error: 'fetch failed', userId: 'user-1', workspaceId: 'ws-1' }),+ );+ });++ it('should return empty array on error', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ mockClient.queryDeviceList.mockRejectedValue(new Error('fail'));++ const proxy = new DeviceGateway();+ const result = await proxy.queryDeviceList('user-1');++ expect(result).toEqual([]);+ });+ });++ describe('queryDeviceSystemInfo', () => {+ it('should return undefined when not configured', async () => {+ const proxy = new DeviceGateway();+ const result = await proxy.queryDeviceSystemInfo('user-1', 'dev-1');+ expect(result).toBeUndefined();+ });++ it('should return systemInfo on success', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ const systemInfo = { cpuModel: 'Apple M1', os: 'macOS', totalMemory: 16384 };+ mockClient.getDeviceSystemInfo.mockResolvedValue({ success: true, systemInfo });++ const proxy = new DeviceGateway();+ const result = await proxy.queryDeviceSystemInfo('user-1', 'dev-1');++ expect(result).toEqual(systemInfo);+ expect(mockClient.getDeviceSystemInfo).toHaveBeenCalledWith('user-1', 'dev-1', undefined, {+ clientKinds: ['desktop'],+ });+ });++ it('should return undefined when result is not successful', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ mockClient.getDeviceSystemInfo.mockResolvedValue({ success: false });++ const proxy = new DeviceGateway();+ const result = await proxy.queryDeviceSystemInfo('user-1', 'dev-1');++ expect(result).toBeUndefined();+ });++ it('should return undefined on error', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ mockClient.getDeviceSystemInfo.mockRejectedValue(new Error('timeout'));++ const proxy = new DeviceGateway();+ const result = await proxy.queryDeviceSystemInfo('user-1', 'dev-1');++ expect(result).toBeUndefined();+ });++ it('asks the device directly when no maxAge is given', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ mockClient.getDeviceSystemInfo.mockResolvedValue({ success: true, systemInfo: {} });++ await new DeviceGateway().queryDeviceSystemInfo('user-1', 'dev-1');++ expect(getRedisServiceClient).not.toHaveBeenCalled();+ expect(cacheRedis.get).not.toHaveBeenCalled();+ });++ it('serves a recent answer through the cache when maxAge is set', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ const systemInfo = { arch: 'arm64' };+ mockClient.getDeviceSystemInfo.mockResolvedValue({ success: true, systemInfo });++ const result = await new DeviceGateway().queryDeviceSystemInfo('user-1', 'dev-1', 'ws-1', {+ maxAgeMs: 180_000,+ });++ expect(result).toEqual(systemInfo);+ // The key carries user, pool and device so two principals never share an answer.+ expect(cacheRedis.get).toHaveBeenCalledWith('device_system_info:v1:user-1:ws-1:dev-1');+ expect(cacheRedis.set).toHaveBeenCalledWith(+ 'device_system_info:v1:user-1:ws-1:dev-1',+ JSON.stringify(systemInfo),+ { px: 180_000 },+ );+ });+ });++ describe('queryDeviceSystemInfo client preference', () => {+ const configure = () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ };++ it('falls back to any client when the device has no desktop app', async () => {+ configure();+ const systemInfo = { arch: 'arm64', userDataPath: '/home/u/.lobehub' };+ mockClient.getDeviceSystemInfo+ .mockResolvedValueOnce({ error: 'NO_CAPABLE_CONNECTION', success: false })+ .mockResolvedValueOnce({ success: true, systemInfo });++ const result = await new DeviceGateway().queryDeviceSystemInfo('user-1', 'dev-1', 'ws-1');++ expect(result).toEqual(systemInfo);+ expect(mockClient.getDeviceSystemInfo).toHaveBeenNthCalledWith(1, 'user-1', 'dev-1', 'ws-1', {+ clientKinds: ['desktop'],+ });+ expect(mockClient.getDeviceSystemInfo).toHaveBeenNthCalledWith(+ 2,+ 'user-1',+ 'dev-1',+ 'ws-1',+ undefined,+ );+ });++ it.each(['TIMEOUT', 'DEVICE_OFFLINE'])(+ 'asks any client when the desktop read fails with %s',+ async (error) => {+ configure();+ const systemInfo = { arch: 'arm64', userDataPath: '/home/u/.lobehub' };+ mockClient.getDeviceSystemInfo+ .mockResolvedValueOnce({ error, success: false })+ .mockResolvedValueOnce({ success: true, systemInfo });++ const result = await new DeviceGateway().queryDeviceSystemInfo('user-1', 'dev-1');++ expect(result).toEqual(systemInfo);+ expect(mockClient.getDeviceSystemInfo).toHaveBeenNthCalledWith(+ 2,+ 'user-1',+ 'dev-1',+ undefined,+ undefined,+ );+ },+ );++ it('asks any client when the desktop read throws', async () => {+ configure();+ const systemInfo = { arch: 'arm64' };+ mockClient.getDeviceSystemInfo+ .mockRejectedValueOnce(new Error('fetch failed'))+ .mockResolvedValueOnce({ success: true, systemInfo });++ const result = await new DeviceGateway().queryDeviceSystemInfo('user-1', 'dev-1');++ expect(result).toEqual(systemInfo);+ });++ it('returns undefined when neither read is answered', async () => {+ configure();+ mockClient.getDeviceSystemInfo.mockResolvedValue({+ error: 'DEVICE_NOT_FOUND',+ success: false,+ });++ const result = await new DeviceGateway().queryDeviceSystemInfo('user-1', 'dev-1');++ expect(result).toBeUndefined();+ expect(mockClient.getDeviceSystemInfo).toHaveBeenCalledTimes(2);+ });+ });++ describe('readDeviceSystemInfo', () => {+ const configure = () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ };++ it('reports an unconfigured gateway', async () => {+ const result = await new DeviceGateway().readDeviceSystemInfo('user-1', 'dev-1');+ expect(result).toEqual({ ok: false, reason: 'GATEWAY_NOT_CONFIGURED' });+ });++ it('returns systemInfo on success', async () => {+ configure();+ const systemInfo = { arch: 'arm64', supportedTools: ['lobe-computer-use'] };+ mockClient.getDeviceSystemInfo.mockResolvedValue({ success: true, systemInfo });++ const result = await new DeviceGateway().readDeviceSystemInfo('user-1', 'dev-1', 'ws-1');++ expect(result).toEqual({ ok: true, systemInfo });+ expect(mockClient.getDeviceSystemInfo).toHaveBeenCalledWith(+ 'user-1',+ 'dev-1',+ 'ws-1',+ undefined,+ );+ });++ it("keeps the gateway's reason for an unanswered read", async () => {+ configure();+ mockClient.getDeviceSystemInfo.mockResolvedValue({ error: 'TIMEOUT', success: false });++ const result = await new DeviceGateway().readDeviceSystemInfo('user-1', 'dev-1');++ expect(result).toEqual({ ok: false, reason: 'TIMEOUT' });+ });++ it('classifies a client-side timeout', async () => {+ configure();+ mockClient.getDeviceSystemInfo.mockRejectedValue(+ Object.assign(new Error('The operation timed out.'), { name: 'TimeoutError' }),+ );++ const result = await new DeviceGateway().readDeviceSystemInfo('user-1', 'dev-1');++ expect(result).toEqual({ ok: false, reason: 'DEVICE_RESPONSE_TIMEOUT' });+ });+ });++ describe('queryDeviceMetrics', () => {+ const params = { deviceId: 'dev-1', since: 1000, userId: 'user-1', workspaceId: 'ws-1' };+ const configure = () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ };++ it('returns the gateway samples', async () => {+ configure();+ const samples = [{ observedAt: 2000 }];+ mockClient.getDeviceMetrics.mockResolvedValue(samples);++ await expect(new DeviceGateway().queryDeviceMetrics(params)).resolves.toEqual(samples);+ expect(mockClient.getDeviceMetrics).toHaveBeenCalledWith('user-1', 'dev-1', {+ since: 1000,+ workspaceId: 'ws-1',+ });+ });++ it('degrades to no samples when the gateway read fails', async () => {+ configure();+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ mockClient.getDeviceMetrics.mockRejectedValue(+ new Error('device metrics read failed: HTTP 500'),+ );++ await expect(new DeviceGateway().queryDeviceMetrics(params)).resolves.toEqual([]);+ expect(warn).toHaveBeenCalledWith(+ expect.stringContaining('device metrics read failed'),+ expect.objectContaining({+ deviceId: 'dev-1',+ error: 'device metrics read failed: HTTP 500',+ }),+ );+ warn.mockRestore();+ });+ });++ describe('getClient (lazy initialization)', () => {+ it('should return null when URL is missing', async () => {+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ const proxy = new DeviceGateway();+ const result = await proxy.queryDeviceStatus('user-1');++ expect(result).toEqual({ deviceCount: 0, online: false });+ expect(MockGatewayHttpClient).not.toHaveBeenCalled();+ });++ it('should return null when token is missing', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ const proxy = new DeviceGateway();+ const result = await proxy.queryDeviceStatus('user-1');++ expect(result).toEqual({ deviceCount: 0, online: false });+ expect(MockGatewayHttpClient).not.toHaveBeenCalled();+ });++ it('should create client only once across multiple calls', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ mockClient.queryDeviceStatus.mockResolvedValue({ deviceCount: 1, online: true });++ const proxy = new DeviceGateway();+ await proxy.queryDeviceStatus('user-1');+ await proxy.queryDeviceStatus('user-2');++ expect(MockGatewayHttpClient).toHaveBeenCalledTimes(1);+ expect(MockGatewayHttpClient).toHaveBeenCalledWith({+ gatewayUrl: 'https://gateway.example.com',+ resolveClientKinds: resolveDeviceClientKinds,+ serviceToken: 'token',+ });+ });+ });+});diff --git a/apps/server/src/services/deviceGateway/index.execution.test.ts b/apps/server/src/services/deviceGateway/index.execution.test.tsnew file mode 100644index 00000000000..51ca0b186a9--- /dev/null+++ b/apps/server/src/services/deviceGateway/index.execution.test.ts@@ -0,0 +1,228 @@+import type * as DeviceGatewayClientModule from '@lobechat/device-gateway-client';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { DeviceGateway } from '.';+import { mockClient, mockEnv, resetGatewayMocks } from './testUtils';++vi.mock('@/server/services/redis/client', () =>+ import('./testUtils').then((m) => ({ getRedisServiceClient: m.getRedisServiceClient })),+);++vi.mock('@/envs/gateway', () => import('./testUtils').then((m) => ({ gatewayEnv: m.mockEnv })));++// Partial mock: only the HTTP client is swapped. The transport-failure+// describers are pure functions the service calls to phrase its errors, and+// stubbing them would test nothing.+vi.mock('@lobechat/device-gateway-client', async (importOriginal) => ({+ ...(await importOriginal<typeof DeviceGatewayClientModule>()),+ GatewayHttpClient: (await import('./testUtils')).MockGatewayHttpClient,+}));++describe('DeviceGateway', () => {+ beforeEach(() => {+ resetGatewayMocks();+ });++ describe('executeToolCall', () => {+ const params = { deviceId: 'dev-1', userId: 'user-1' };+ const toolCall = { apiName: 'listFiles', arguments: '{}', identifier: 'file-manager' };++ it('should return error when not configured', async () => {+ const proxy = new DeviceGateway();+ const result = await proxy.executeToolCall(params, toolCall);++ expect(result).toEqual({+ content: 'Device Gateway is not configured',+ error: 'GATEWAY_NOT_CONFIGURED',+ success: false,+ });+ });++ it('should execute tool call with default timeout', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ const expected = { content: 'file list', success: true };+ mockClient.executeToolCall.mockResolvedValue(expected);++ const proxy = new DeviceGateway();+ const result = await proxy.executeToolCall(params, toolCall);++ expect(result).toEqual(expected);+ expect(mockClient.executeToolCall).toHaveBeenCalledWith(+ { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },+ toolCall,+ );+ });++ it('should use custom timeout', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ mockClient.executeToolCall.mockResolvedValue({ content: 'ok', success: true });++ const proxy = new DeviceGateway();+ await proxy.executeToolCall(params, toolCall, 60_000);++ expect(mockClient.executeToolCall).toHaveBeenCalledWith(+ { deviceId: 'dev-1', timeout: 60_000, userId: 'user-1' },+ toolCall,+ );+ });++ it('should return error result on Error exception', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ mockClient.executeToolCall.mockRejectedValue(new Error('connection refused'));++ const proxy = new DeviceGateway();+ const result = await proxy.executeToolCall(params, toolCall);++ // `connection refused` is a network failure, so the model is told the call+ // never ran rather than being handed the bare driver message.+ expect(result.success).toBe(false);+ expect(result.content).toContain('Could not reach the device gateway');+ expect(result.error).toBe('DEVICE_GATEWAY_UNREACHABLE: connection refused');+ });++ it('should handle non-Error exceptions', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ mockClient.executeToolCall.mockRejectedValue('string error');++ const proxy = new DeviceGateway();+ const result = await proxy.executeToolCall(params, toolCall);++ // Unrecognised cause: describe the hop without claiming to know whether+ // the device ran the call.+ expect(result.success).toBe(false);+ expect(result.content).toContain('unclear whether the device ran it');+ expect(result.error).toBe('DEVICE_GATEWAY_ERROR: string error');+ });+ });++ describe('executeMcpCall', () => {+ const mcpCall = {+ apiName: 'getStock',+ arguments: '{"symbol":"AAPL"}',+ deviceId: 'dev-1',+ identifier: 'kimi-datasource',+ params: {+ args: ['stock-mcp'],+ command: 'npx',+ env: { TOKEN: 'secret' },+ name: 'kimi-datasource',+ type: 'stdio' as const,+ },+ userId: 'user-1',+ };++ it('should return error when not configured', async () => {+ const proxy = new DeviceGateway();+ const result = await proxy.executeMcpCall(mcpCall);++ expect(result).toEqual({+ content: 'Device Gateway is not configured',+ error: 'GATEWAY_NOT_CONFIGURED',+ success: false,+ });+ });++ it('should forward the mcp call with default timeout', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ const expected = { content: 'stock data', state: { rows: 3 }, success: true };+ mockClient.executeMcpCall.mockResolvedValue(expected);++ const proxy = new DeviceGateway();+ const result = await proxy.executeMcpCall(mcpCall);++ expect(result).toEqual(expected);+ expect(mockClient.executeMcpCall).toHaveBeenCalledWith({ ...mcpCall, timeout: 30_000 });+ });++ it('should use custom timeout', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ mockClient.executeMcpCall.mockResolvedValue({ content: 'ok', success: true });++ const proxy = new DeviceGateway();+ await proxy.executeMcpCall(mcpCall, 60_000);++ expect(mockClient.executeMcpCall).toHaveBeenCalledWith({ ...mcpCall, timeout: 60_000 });+ });++ it('should return error result on exception', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ mockClient.executeMcpCall.mockRejectedValue(new Error('connection refused'));++ const proxy = new DeviceGateway();+ const result = await proxy.executeMcpCall(mcpCall);++ // Tunneled MCP calls ride the same relay, so they get the same phrasing.+ expect(result.success).toBe(false);+ expect(result.content).toContain('Could not reach the device gateway');+ expect(result.error).toBe('DEVICE_GATEWAY_UNREACHABLE: connection refused');+ });+ });++ describe('executeMessageApi', () => {+ const params = { deviceId: 'dev-1', userId: 'user-1' };+ const api = { apiName: 'sendText', payload: { chatGuid: 'chat-1' }, platform: 'imessage' };++ it('should return error when not configured', async () => {+ const proxy = new DeviceGateway();+ const result = await proxy.executeMessageApi(params, api);++ expect(result).toEqual({+ content: 'Device Gateway is not configured',+ error: 'GATEWAY_NOT_CONFIGURED',+ success: false,+ });+ });++ it('should execute message API with default timeout', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ const expected = { content: '{"ok":true}', success: true };+ mockClient.executeMessageApi.mockResolvedValue(expected);++ const proxy = new DeviceGateway();+ const result = await proxy.executeMessageApi(params, api);++ expect(result).toEqual(expected);+ expect(mockClient.executeMessageApi).toHaveBeenCalledWith(+ { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },+ api,+ );+ });++ it('should use custom timeout', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ mockClient.executeMessageApi.mockResolvedValue({ content: 'ok', success: true });++ const proxy = new DeviceGateway();+ await proxy.executeMessageApi(params, api, 60_000);++ expect(mockClient.executeMessageApi).toHaveBeenCalledWith(+ { deviceId: 'dev-1', timeout: 60_000, userId: 'user-1' },+ api,+ );+ });++ it('should return error result on exception', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ mockClient.executeMessageApi.mockRejectedValue(new Error('connection refused'));++ const proxy = new DeviceGateway();+ const result = await proxy.executeMessageApi(params, api);++ expect(result).toEqual({+ content: 'Device message API error: connection refused',+ error: 'connection refused',+ success: false,+ });+ });+ });+});diff --git a/apps/server/src/services/deviceGateway/index.fileMutations.test.ts b/apps/server/src/services/deviceGateway/index.fileMutations.test.tsnew file mode 100644index 00000000000..9117f295077--- /dev/null+++ b/apps/server/src/services/deviceGateway/index.fileMutations.test.ts@@ -0,0 +1,600 @@+import type * as DeviceGatewayClientModule from '@lobechat/device-gateway-client';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { DeviceGateway } from '.';+import { mockClient, mockEnv, resetGatewayMocks } from './testUtils';++vi.mock('@/server/services/redis/client', () =>+ import('./testUtils').then((m) => ({ getRedisServiceClient: m.getRedisServiceClient })),+);++vi.mock('@/envs/gateway', () => import('./testUtils').then((m) => ({ gatewayEnv: m.mockEnv })));++// Partial mock: only the HTTP client is swapped. The transport-failure+// describers are pure functions the service calls to phrase its errors, and+// stubbing them would test nothing.+vi.mock('@lobechat/device-gateway-client', async (importOriginal) => ({+ ...(await importOriginal<typeof DeviceGatewayClientModule>()),+ GatewayHttpClient: (await import('./testUtils')).MockGatewayHttpClient,+}));++describe('DeviceGateway', () => {+ beforeEach(() => {+ resetGatewayMocks();+ });++ describe('file mutation containment', () => {+ const configure = () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ };++ describe('writeProjectFile', () => {+ it('invokes the rpc when the path is inside the workspace', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({ data: { success: true }, success: true });++ const proxy = new DeviceGateway();+ const result = await proxy.writeProjectFile({+ content: 'next',+ deviceId: 'dev-1',+ path: '/proj/src/App.tsx',+ userId: 'user-1',+ workingDirectory: '/proj',+ });++ expect(result).toEqual({ success: true });+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(+ { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },+ {+ method: 'writeLocalFile',+ params: { content: 'next', path: '/proj/src/App.tsx', workspaceRoot: '/proj' },+ },+ );+ });++ it('throws without invoking the rpc when the path escapes the workspace', async () => {+ configure();+ const proxy = new DeviceGateway();++ await expect(+ proxy.writeProjectFile({+ content: 'pwned',+ deviceId: 'dev-1',+ path: '/etc/passwd',+ userId: 'user-1',+ workingDirectory: '/proj',+ }),+ ).rejects.toThrow(/outside the approved workspace/);+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });++ it('rejects a `..` traversal that resolves outside the workspace', async () => {+ configure();+ const proxy = new DeviceGateway();++ await expect(+ proxy.writeProjectFile({+ content: 'pwned',+ deviceId: 'dev-1',+ path: '/proj/../secrets.env',+ userId: 'user-1',+ workingDirectory: '/proj',+ }),+ ).rejects.toThrow(/outside the approved workspace/);+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });++ it('contains Windows device paths using Windows path semantics', async () => {+ configure();+ const proxy = new DeviceGateway();++ await expect(+ proxy.writeProjectFile({+ content: 'pwned',+ deviceId: 'dev-1',+ path: 'C:\\Windows\\System32\\drivers\\etc\\hosts',+ userId: 'user-1',+ workingDirectory: 'C:\\proj',+ }),+ ).rejects.toThrow(/outside the approved workspace/);+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });+ });++ describe('renameProjectFile', () => {+ it('throws without invoking the rpc when the path escapes the workspace', async () => {+ configure();+ const proxy = new DeviceGateway();++ await expect(+ proxy.renameProjectFile({+ deviceId: 'dev-1',+ newName: 'evil.ts',+ path: '/etc/hosts',+ userId: 'user-1',+ workingDirectory: '/proj',+ }),+ ).rejects.toThrow(/outside the approved workspace/);+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });+ });++ describe('createProjectFile', () => {+ it('invokes createLocalFile when the path is inside the workspace', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({+ data: { path: '/proj/new.ts', success: true },+ success: true,+ });++ const proxy = new DeviceGateway();+ const result = await proxy.createProjectFile({+ deviceId: 'dev-1',+ path: '/proj/new.ts',+ userId: 'user-1',+ workingDirectory: '/proj',+ });++ expect(result).toEqual({ path: '/proj/new.ts', success: true });+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(+ { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },+ {+ method: 'createLocalFile',+ params: { content: undefined, path: '/proj/new.ts', workspaceRoot: '/proj' },+ },+ );+ });++ it('throws without invoking the rpc when the path escapes the workspace', async () => {+ configure();+ const proxy = new DeviceGateway();++ await expect(+ proxy.createProjectFile({+ deviceId: 'dev-1',+ path: '/proj/../evil.sh',+ userId: 'user-1',+ workingDirectory: '/proj',+ }),+ ).rejects.toThrow(/outside the approved workspace/);+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });++ it('surfaces a device that has not shipped the rpc yet as an error', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({+ error: 'Unknown device RPC method: createLocalFile',+ success: false,+ });++ const proxy = new DeviceGateway();+ await expect(+ proxy.createProjectFile({+ deviceId: 'dev-1',+ path: '/proj/new.ts',+ userId: 'user-1',+ workingDirectory: '/proj',+ }),+ ).rejects.toThrow('Unknown device RPC method: createLocalFile');+ });+ });++ describe('createProjectDirectory', () => {+ it('invokes createLocalDirectory when the path is inside the workspace', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({+ data: { path: '/proj/src/new', success: true },+ success: true,+ });++ const proxy = new DeviceGateway();+ await expect(+ proxy.createProjectDirectory({+ deviceId: 'dev-1',+ path: '/proj/src/new',+ userId: 'user-1',+ workingDirectory: '/proj',+ }),+ ).resolves.toEqual({ path: '/proj/src/new', success: true });+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(+ { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },+ {+ method: 'createLocalDirectory',+ params: { path: '/proj/src/new', workspaceRoot: '/proj' },+ },+ );+ });++ it('throws without invoking the rpc when the path escapes the workspace', async () => {+ configure();+ const proxy = new DeviceGateway();++ await expect(+ proxy.createProjectDirectory({+ deviceId: 'dev-1',+ path: '/tmp/outside',+ userId: 'user-1',+ workingDirectory: '/proj',+ }),+ ).rejects.toThrow(/outside the approved workspace/);+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });+ });++ describe('createDirectory', () => {+ it('creates one child of the browsed folder, scoped to that folder', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({+ data: { path: '/home/me/new-project', success: true },+ success: true,+ });++ const proxy = new DeviceGateway();+ await expect(+ proxy.createDirectory({+ deviceId: 'dev-1',+ name: ' new-project ',+ parentPath: '/home/me/',+ userId: 'user-1',+ }),+ ).resolves.toEqual({ path: '/home/me/new-project', success: true });+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(+ { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },+ {+ method: 'createLocalDirectory',+ params: { path: '/home/me/new-project', workspaceRoot: '/home/me/' },+ },+ );+ });++ it.each([+ ['/', '/new'],+ ['C:\\Users\\me', 'C:\\Users\\me\\new'],+ ['C:\\', 'C:\\new'],+ ])('joins %s with the device separator', async (parentPath, expected) => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({+ data: { path: expected, success: true },+ success: true,+ });++ await new DeviceGateway().createDirectory({+ deviceId: 'dev-1',+ name: 'new',+ parentPath,+ userId: 'user-1',+ });+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(expect.anything(), {+ method: 'createLocalDirectory',+ params: { path: expected, workspaceRoot: parentPath },+ });+ });++ it.each(['', '.', '..', 'a/b', 'a\\b'])(+ 'rejects the folder name %j without invoking the rpc',+ async (name) => {+ configure();++ await expect(+ new DeviceGateway().createDirectory({+ deviceId: 'dev-1',+ name,+ parentPath: '/home/me',+ userId: 'user-1',+ }),+ ).rejects.toThrow(/Invalid folder name/);+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ },+ );++ it.each(['a:b', 'CON.txt', 'project.', 'project '])(+ 'rejects invalid Windows name %j before invoking the device',+ async (name) => {+ configure();+ await expect(+ new DeviceGateway().createDirectory({+ deviceId: 'dev-1',+ name,+ parentPath: 'C:\\Users\\me',+ userId: 'user-1',+ }),+ ).rejects.toThrow(/Invalid folder name/);+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ },+ );++ it('rejects a relative parent path without invoking the rpc', async () => {+ configure();++ await expect(+ new DeviceGateway().createDirectory({+ deviceId: 'dev-1',+ name: 'new',+ parentPath: 'relative/dir',+ userId: 'user-1',+ }),+ ).rejects.toThrow(/must be absolute/);+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });++ it('returns a device-reported failure instead of throwing', async () => {+ configure();+ const failure = {+ error: 'An item already exists at /home/me/new.',+ path: '/home/me/new',+ success: false,+ };+ mockClient.invokeRpc.mockResolvedValue({ data: failure, success: true });++ await expect(+ new DeviceGateway().createDirectory({+ deviceId: 'dev-1',+ name: 'new',+ parentPath: '/home/me',+ userId: 'user-1',+ }),+ ).resolves.toEqual(failure);+ });++ it('throws when the rpc itself fails', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({ error: 'Device offline', success: false });++ await expect(+ new DeviceGateway().createDirectory({+ deviceId: 'dev-1',+ name: 'new',+ parentPath: '/home/me',+ userId: 'user-1',+ }),+ ).rejects.toThrow('Device offline');+ });+ });++ describe('copyProjectFiles', () => {+ it('invokes copyLocalFiles when source and target stay inside the workspace', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({+ data: [{ sourcePath: '/proj/a.ts', success: true, targetPath: '/proj/a copy.ts' }],+ success: true,+ });++ const proxy = new DeviceGateway();+ const items = [+ { sourcePath: '/proj/a.ts' },+ { sourcePath: '/proj/b', targetPath: '/proj/c' },+ ];+ await proxy.copyProjectFiles({+ deviceId: 'dev-1',+ items,+ userId: 'user-1',+ workingDirectory: '/proj',+ });++ expect(mockClient.invokeRpc).toHaveBeenCalledWith(+ { deviceId: 'dev-1', timeout: 60_000, userId: 'user-1' },+ { method: 'copyLocalFiles', params: { items, workspaceRoot: '/proj' } },+ );+ });++ it('throws when a source lies outside the workspace', async () => {+ configure();+ const proxy = new DeviceGateway();++ await expect(+ proxy.copyProjectFiles({+ deviceId: 'dev-1',+ items: [{ sourcePath: '/Users/me/.ssh/id_rsa', targetPath: '/proj/key' }],+ userId: 'user-1',+ workingDirectory: '/proj',+ }),+ ).rejects.toThrow(/outside the approved workspace/);+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });++ it('throws when a target lies outside the workspace', async () => {+ configure();+ const proxy = new DeviceGateway();++ await expect(+ proxy.copyProjectFiles({+ deviceId: 'dev-1',+ items: [{ sourcePath: '/proj/secrets.env', targetPath: '/tmp/exfil.env' }],+ userId: 'user-1',+ workingDirectory: '/proj',+ }),+ ).rejects.toThrow(/outside the approved workspace/);+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });++ it('refuses to duplicate the workspace root (the copy would land outside it)', async () => {+ configure();+ const proxy = new DeviceGateway();++ await expect(+ proxy.copyProjectFiles({+ deviceId: 'dev-1',+ items: [{ sourcePath: '/proj' }],+ userId: 'user-1',+ workingDirectory: '/proj',+ }),+ ).rejects.toThrow(/workspace root/);+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });+ });++ describe('trashProjectFiles', () => {+ it('invokes trashLocalFiles when every path is inside the workspace', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({+ data: { items: [{ path: '/proj/a.ts', success: true }], success: true },+ success: true,+ });++ const proxy = new DeviceGateway();+ await expect(+ proxy.trashProjectFiles({+ deviceId: 'dev-1',+ paths: ['/proj/a.ts'],+ userId: 'user-1',+ workingDirectory: '/proj',+ }),+ ).resolves.toEqual({ items: [{ path: '/proj/a.ts', success: true }], success: true });+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(+ { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },+ { method: 'trashLocalFiles', params: { paths: ['/proj/a.ts'], workspaceRoot: '/proj' } },+ );+ });++ it('throws when any path escapes the workspace', async () => {+ configure();+ const proxy = new DeviceGateway();++ await expect(+ proxy.trashProjectFiles({+ deviceId: 'dev-1',+ paths: ['/proj/a.ts', '/Users/me/Documents'],+ userId: 'user-1',+ workingDirectory: '/proj',+ }),+ ).rejects.toThrow(/outside the approved workspace/);+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });++ it.each(['/proj', '/proj/', '/proj/src/..'])(+ 'refuses to trash the workspace root itself (%s)',+ async (rootPath) => {+ configure();+ const proxy = new DeviceGateway();++ await expect(+ proxy.trashProjectFiles({+ deviceId: 'dev-1',+ paths: [rootPath],+ userId: 'user-1',+ workingDirectory: '/proj',+ }),+ ).rejects.toThrow(/workspace root/);+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ },+ );++ it('surfaces a device without a trash as an error, not a delete', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({+ error: 'This device does not support moving files to the trash',+ success: false,+ });++ const proxy = new DeviceGateway();+ await expect(+ proxy.trashProjectFiles({+ deviceId: 'dev-1',+ paths: ['/proj/a.ts'],+ userId: 'user-1',+ workingDirectory: '/proj',+ }),+ ).rejects.toThrow('This device does not support moving files to the trash');+ expect(mockClient.invokeRpc).toHaveBeenCalledTimes(1);+ });+ });++ describe('workspace root guard on rename / move', () => {+ it('refuses to rename the workspace root itself', async () => {+ configure();+ const proxy = new DeviceGateway();++ await expect(+ proxy.renameProjectFile({+ deviceId: 'dev-1',+ newName: 'renamed',+ path: '/proj',+ userId: 'user-1',+ workingDirectory: '/proj',+ }),+ ).rejects.toThrow(/workspace root/);+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });++ it('refuses to move the workspace root itself', async () => {+ configure();+ const proxy = new DeviceGateway();++ await expect(+ proxy.moveProjectFiles({+ deviceId: 'dev-1',+ items: [{ newPath: '/proj/inner', oldPath: '/proj' }],+ userId: 'user-1',+ workingDirectory: '/proj',+ }),+ ).rejects.toThrow(/workspace root/);+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });++ it('contains Windows workspace roots with Windows semantics', async () => {+ configure();+ const proxy = new DeviceGateway();++ await expect(+ proxy.trashProjectFiles({+ deviceId: 'dev-1',+ paths: ['C:\\proj\\'],+ userId: 'user-1',+ workingDirectory: 'C:\\proj',+ }),+ ).rejects.toThrow(/workspace root/);+ });+ });++ describe('moveProjectFiles', () => {+ it('throws when any item moves out of the workspace', async () => {+ configure();+ const proxy = new DeviceGateway();++ await expect(+ proxy.moveProjectFiles({+ deviceId: 'dev-1',+ items: [+ { newPath: '/proj/b.ts', oldPath: '/proj/a.ts' },+ { newPath: '/tmp/exfil.ts', oldPath: '/proj/c.ts' },+ ],+ userId: 'user-1',+ workingDirectory: '/proj',+ }),+ ).rejects.toThrow(/outside the approved workspace/);+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });++ it('invokes the rpc when every item stays inside the workspace', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({+ data: [{ newPath: '/proj/b.ts', sourcePath: '/proj/a.ts', success: true }],+ success: true,+ });++ const proxy = new DeviceGateway();+ const result = await proxy.moveProjectFiles({+ deviceId: 'dev-1',+ items: [{ newPath: '/proj/b.ts', oldPath: '/proj/a.ts' }],+ userId: 'user-1',+ workingDirectory: '/proj',+ });++ expect(result).toEqual([+ { newPath: '/proj/b.ts', sourcePath: '/proj/a.ts', success: true },+ ]);+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(+ { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },+ {+ method: 'moveLocalFiles',+ params: {+ items: [{ newPath: '/proj/b.ts', oldPath: '/proj/a.ts' }],+ workspaceRoot: '/proj',+ },+ },+ );+ });+ });+ });+});diff --git a/apps/server/src/services/deviceGateway/index.maintenance.test.ts b/apps/server/src/services/deviceGateway/index.maintenance.test.tsnew file mode 100644index 00000000000..31a20987d22--- /dev/null+++ b/apps/server/src/services/deviceGateway/index.maintenance.test.ts@@ -0,0 +1,165 @@+import type * as DeviceGatewayClientModule from '@lobechat/device-gateway-client';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { DeviceGateway } from '.';+import { mockClient, mockEnv, resetGatewayMocks } from './testUtils';++vi.mock('@/server/services/redis/client', () =>+ import('./testUtils').then((m) => ({ getRedisServiceClient: m.getRedisServiceClient })),+);++vi.mock('@/envs/gateway', () => import('./testUtils').then((m) => ({ gatewayEnv: m.mockEnv })));++// Partial mock: only the HTTP client is swapped. The transport-failure+// describers are pure functions the service calls to phrase its errors, and+// stubbing them would test nothing.+vi.mock('@lobechat/device-gateway-client', async (importOriginal) => ({+ ...(await importOriginal<typeof DeviceGatewayClientModule>()),+ GatewayHttpClient: (await import('./testUtils')).MockGatewayHttpClient,+}));++describe('DeviceGateway', () => {+ beforeEach(() => {+ resetGatewayMocks();+ });++ describe('remote app update', () => {+ const configure = () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ };+ const params = { deviceId: 'device-1', userId: 'user-1' };++ it('asks the desktop channel for the update state', async () => {+ configure();+ const state = { currentVersion: '2.1.0', stage: 'downloaded', targetVersion: '2.2.0' };+ mockClient.invokeRpc.mockResolvedValue({ data: state, success: true });++ await expect(new DeviceGateway().getAppUpdateState(params)).resolves.toEqual({+ state,+ status: 'ok',+ });+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(+ expect.objectContaining({ channel: 'desktop', deviceId: 'device-1', userId: 'user-1' }),+ { method: 'getAppUpdateState' },+ );+ });++ it('returns the version the device restarts into', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({ data: { targetVersion: '2.2.0' }, success: true });++ await expect(new DeviceGateway().installAppUpdate(params)).resolves.toEqual({+ status: 'ok',+ targetVersion: '2.2.0',+ });+ });++ it.each([+ 'This device client does not support remote updates',+ 'Unknown device RPC method: checkAppUpdate',+ ])('reports a client that cannot update remotely as unsupported (%s)', async (error) => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({ error, success: false });++ await expect(new DeviceGateway().checkAppUpdate(params)).resolves.toEqual({+ message: error,+ status: 'unsupported',+ });+ });++ it('reports an unreachable device as unavailable', async () => {+ configure();+ mockClient.invokeRpc.mockRejectedValue(new Error('timeout'));++ await expect(new DeviceGateway().getAppUpdateState(params)).resolves.toEqual({+ message: 'timeout',+ status: 'unavailable',+ });+ });++ it('reports unavailable without a configured gateway', async () => {+ await expect(new DeviceGateway().installAppUpdate(params)).resolves.toMatchObject({+ status: 'unavailable',+ });+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });+ });++ 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();+ });+ });+});diff --git a/apps/server/src/services/deviceGateway/index.projectFiles.test.ts b/apps/server/src/services/deviceGateway/index.projectFiles.test.tsnew file mode 100644index 00000000000..59a5d05557a--- /dev/null+++ b/apps/server/src/services/deviceGateway/index.projectFiles.test.ts@@ -0,0 +1,468 @@+import type * as DeviceGatewayClientModule from '@lobechat/device-gateway-client';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { DeviceGateway } from '.';+import { mockClient, mockEnv, resetGatewayMocks } from './testUtils';++vi.mock('@/server/services/redis/client', () =>+ import('./testUtils').then((m) => ({ getRedisServiceClient: m.getRedisServiceClient })),+);++vi.mock('@/envs/gateway', () => import('./testUtils').then((m) => ({ gatewayEnv: m.mockEnv })));++// Partial mock: only the HTTP client is swapped. The transport-failure+// describers are pure functions the service calls to phrase its errors, and+// stubbing them would test nothing.+vi.mock('@lobechat/device-gateway-client', async (importOriginal) => ({+ ...(await importOriginal<typeof DeviceGatewayClientModule>()),+ GatewayHttpClient: (await import('./testUtils')).MockGatewayHttpClient,+}));++describe('DeviceGateway', () => {+ beforeEach(() => {+ resetGatewayMocks();+ });++ describe('initWorkspace', () => {+ const configure = () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ };++ it('should return undefined when not configured', async () => {+ const proxy = new DeviceGateway();+ const result = await proxy.initWorkspace({+ deviceId: 'dev-1',+ scope: '/proj',+ userId: 'user-1',+ });+ expect(result).toBeUndefined();+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });++ it('narrows device skills to metadata and passes instructions through', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({+ data: {+ instructions: [{ content: '# Rules', source: 'AGENTS.md' }],+ // Device returns rich ProjectSkillItems; only prompt metadata survives.+ skills: [+ {+ description: 'spa',+ fileCount: 3,+ files: ['SKILL.md'],+ name: 'spa-routes',+ path: '/proj/.agents/skills/spa-routes/SKILL.md',+ previewRoot: '/proj',+ scope: 'project',+ skillDir: '/proj/.agents/skills/spa-routes',+ source: '.agents/skills',+ },+ {+ description: 'device',+ fileCount: 2,+ files: ['SKILL.md', 'refs.md'],+ name: 'device-writer',+ path: '/home/.agents/skills/device-writer/SKILL.md',+ previewRoot: '/home/.agents/skills',+ scope: 'device',+ skillDir: '/home/.agents/skills/device-writer',+ source: '.agents/skills',+ },+ ],+ },+ success: true,+ });++ const proxy = new DeviceGateway();+ const result = await proxy.initWorkspace({+ deviceId: 'dev-1',+ scope: '/proj',+ userId: 'user-1',+ });++ expect(result).toEqual({+ instructions: [{ content: '# Rules', source: 'AGENTS.md' }],+ skills: [+ {+ description: 'spa',+ name: 'spa-routes',+ path: '/proj/.agents/skills/spa-routes/SKILL.md',+ scope: 'project',+ },+ {+ description: 'device',+ name: 'device-writer',+ path: '/home/.agents/skills/device-writer/SKILL.md',+ scope: 'device',+ },+ ],+ });+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(+ { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },+ { method: 'initWorkspace', params: { scope: '/proj' } },+ );+ });++ it('defaults instructions and skills to empty arrays when absent', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({ data: {}, success: true });++ const proxy = new DeviceGateway();+ const result = await proxy.initWorkspace({+ deviceId: 'dev-1',+ scope: '/proj',+ userId: 'user-1',+ });++ expect(result).toEqual({ instructions: [], skills: [] });+ });++ it('returns undefined when the rpc reports failure', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({ error: 'offline', success: false });++ const proxy = new DeviceGateway();+ const result = await proxy.initWorkspace({+ deviceId: 'dev-1',+ scope: '/proj',+ userId: 'user-1',+ });++ expect(result).toBeUndefined();+ });++ it('returns undefined when the rpc succeeds without data', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({ success: true });++ const proxy = new DeviceGateway();+ const result = await proxy.initWorkspace({+ deviceId: 'dev-1',+ scope: '/proj',+ userId: 'user-1',+ });++ expect(result).toBeUndefined();+ });++ it('returns undefined on exception', async () => {+ configure();+ mockClient.invokeRpc.mockRejectedValue(new Error('timeout'));++ const proxy = new DeviceGateway();+ const result = await proxy.initWorkspace({+ deviceId: 'dev-1',+ scope: '/proj',+ userId: 'user-1',+ });++ expect(result).toBeUndefined();+ });++ it('forwards a custom timeout', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({+ data: { instructions: [], skills: [] },+ success: true,+ });++ const proxy = new DeviceGateway();+ await proxy.initWorkspace({+ deviceId: 'dev-1',+ scope: '/proj',+ timeout: 60_000,+ userId: 'user-1',+ });++ expect(mockClient.invokeRpc).toHaveBeenCalledWith(+ { deviceId: 'dev-1', timeout: 60_000, userId: 'user-1' },+ { method: 'initWorkspace', params: { scope: '/proj' } },+ );+ });+ });++ describe('listProjectSkills', () => {+ const configure = () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ };++ it('should return undefined when not configured', async () => {+ const proxy = new DeviceGateway();+ const result = await proxy.listProjectSkills({+ deviceId: 'dev-1',+ scope: '/proj',+ userId: 'user-1',+ });+ expect(result).toBeUndefined();+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });++ it('passes the device result through and invokes the rpc with scope', async () => {+ configure();+ const data = {+ root: '/proj',+ skills: [+ {+ description: 'spa',+ fileCount: 3,+ files: ['SKILL.md'],+ name: 'spa-routes',+ path: '/proj/.agents/skills/spa-routes/SKILL.md',+ previewRoot: '/proj',+ scope: 'project',+ skillDir: '/proj/.agents/skills/spa-routes',+ source: '.agents/skills',+ },+ ],+ source: '.agents/skills',+ };+ mockClient.invokeRpc.mockResolvedValue({ data, success: true });++ const proxy = new DeviceGateway();+ const result = await proxy.listProjectSkills({+ deviceId: 'dev-1',+ scope: '/proj',+ userId: 'user-1',+ });++ expect(result).toEqual(data);+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(+ { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },+ { method: 'listProjectSkills', params: { scope: '/proj' } },+ );+ });++ it('returns undefined when the rpc reports failure', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({ error: 'offline', success: false });++ const proxy = new DeviceGateway();+ const result = await proxy.listProjectSkills({+ deviceId: 'dev-1',+ scope: '/proj',+ userId: 'user-1',+ });++ expect(result).toBeUndefined();+ });++ it('returns undefined when the rpc succeeds without data', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({ success: true });++ const proxy = new DeviceGateway();+ const result = await proxy.listProjectSkills({+ deviceId: 'dev-1',+ scope: '/proj',+ userId: 'user-1',+ });++ expect(result).toBeUndefined();+ });++ it('returns undefined on exception', async () => {+ configure();+ mockClient.invokeRpc.mockRejectedValue(new Error('timeout'));++ const proxy = new DeviceGateway();+ const result = await proxy.listProjectSkills({+ deviceId: 'dev-1',+ scope: '/proj',+ userId: 'user-1',+ });++ expect(result).toBeUndefined();+ });++ it('forwards a custom timeout', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({+ data: { root: '/proj', skills: [], source: null },+ success: true,+ });++ const proxy = new DeviceGateway();+ await proxy.listProjectSkills({+ deviceId: 'dev-1',+ scope: '/proj',+ timeout: 60_000,+ userId: 'user-1',+ });++ expect(mockClient.invokeRpc).toHaveBeenCalledWith(+ { deviceId: 'dev-1', timeout: 60_000, userId: 'user-1' },+ { method: 'listProjectSkills', params: { scope: '/proj' } },+ );+ });+ });++ describe('getLocalFilePreview', () => {+ const configure = () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ };++ it('returns an error result when not configured', async () => {+ const proxy = new DeviceGateway();+ const result = await proxy.getLocalFilePreview({+ deviceId: 'dev-1',+ path: '/proj/App.tsx',+ userId: 'user-1',+ workingDirectory: '/proj',+ });++ expect(result).toEqual({ error: 'Device gateway not configured', success: false });+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });++ it('passes the device preview result through and invokes the rpc', async () => {+ configure();+ const data = {+ preview: {+ content: 'const value = 1;',+ contentType: 'text/plain',+ type: 'text',+ },+ success: true,+ };+ mockClient.invokeRpc.mockResolvedValue({ data, success: true });++ const proxy = new DeviceGateway();+ const result = await proxy.getLocalFilePreview({+ deviceId: 'dev-1',+ path: '/proj/App.tsx',+ userId: 'user-1',+ workingDirectory: '/proj',+ });++ expect(result).toEqual(data);+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(+ { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },+ {+ method: 'getLocalFilePreview',+ params: { accept: undefined, path: '/proj/App.tsx', workingDirectory: '/proj' },+ },+ );+ });++ it('forwards image-only preview constraints to the device rpc', async () => {+ configure();+ const data = {+ preview: {+ base64: 'aW1hZ2U=',+ contentType: 'image/png',+ type: 'image',+ },+ success: true,+ };+ mockClient.invokeRpc.mockResolvedValue({ data, success: true });++ const proxy = new DeviceGateway();+ await proxy.getLocalFilePreview({+ accept: 'image',+ deviceId: 'dev-1',+ path: '/proj/image.png',+ userId: 'user-1',+ workingDirectory: '/proj',+ });++ expect(mockClient.invokeRpc).toHaveBeenCalledWith(+ { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },+ {+ method: 'getLocalFilePreview',+ params: { accept: 'image', path: '/proj/image.png', workingDirectory: '/proj' },+ },+ );+ });++ it('returns an error result when the rpc reports failure', async () => {+ configure();+ mockClient.invokeRpc.mockResolvedValue({ error: 'offline', success: false });++ const proxy = new DeviceGateway();+ const result = await proxy.getLocalFilePreview({+ deviceId: 'dev-1',+ path: '/proj/App.tsx',+ userId: 'user-1',+ workingDirectory: '/proj',+ });++ expect(result).toEqual({ error: 'offline', success: false });+ });+ });++ describe('readExternalAssetForPublish', () => {+ it('invokes only the dedicated publish RPC method', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ const data = { base64: 'AQID', contentType: 'image/png', success: true };+ mockClient.invokeRpc.mockResolvedValue({ data, success: true });++ const proxy = new DeviceGateway();+ const result = await proxy.readExternalAssetForPublish({+ deviceId: 'dev-1',+ path: '/outside/image.png',+ userId: 'user-1',+ workingDirectory: '/proj',+ });++ expect(result).toEqual(data);+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(+ { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },+ {+ method: 'readExternalAssetForPublish',+ params: { path: '/outside/image.png', workingDirectory: '/proj' },+ },+ );+ });+ });++ describe('copyAssetForPublish', () => {+ it('invokes the copy RPC when the destination is inside the workspace', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ mockClient.invokeRpc.mockResolvedValue({ data: { success: true }, success: true });++ const proxy = new DeviceGateway();+ const result = await proxy.copyAssetForPublish({+ deviceId: 'dev-1',+ from: '/outside/image.png',+ to: '/proj/.lobe-artifacts/site/image.png',+ userId: 'user-1',+ workingDirectory: '/proj',+ });++ expect(result).toEqual({ success: true });+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(+ { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },+ {+ method: 'copyAssetForPublish',+ params: {+ from: '/outside/image.png',+ to: '/proj/.lobe-artifacts/site/image.png',+ workingDirectory: '/proj',+ },+ },+ );+ });++ it('throws without invoking the rpc when the destination escapes the workspace', async () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+ const proxy = new DeviceGateway();++ await expect(+ proxy.copyAssetForPublish({+ deviceId: 'dev-1',+ from: '/outside/image.png',+ to: '/proj/../image.png',+ userId: 'user-1',+ workingDirectory: '/proj',+ }),+ ).rejects.toThrow(/outside the approved workspace/);+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });+ });+});diff --git a/apps/server/src/services/deviceGateway/index.rpcSurface.test.ts b/apps/server/src/services/deviceGateway/index.rpcSurface.test.tsnew file mode 100644index 00000000000..0e82469dc92--- /dev/null+++ b/apps/server/src/services/deviceGateway/index.rpcSurface.test.ts@@ -0,0 +1,685 @@+/**+ * Characterization of every DeviceGateway method that relays one device RPC:+ * the RPC address (default timeout, channel, scope), the method name and+ * params, and what each method returns when the gateway is unconfigured, when+ * the device answers `success: false`, and when the transport throws.+ */+import type * as DeviceGatewayClientModule from '@lobechat/device-gateway-client';+import type { DeviceGitPullRequestAction } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { DeviceGateway } from '.';+import { configureGateway, mockClient, resetGatewayMocks } from './testUtils';++vi.mock('@/server/services/redis/client', () =>+ import('./testUtils').then((m) => ({ getRedisServiceClient: m.getRedisServiceClient })),+);++vi.mock('@/envs/gateway', () => import('./testUtils').then((m) => ({ gatewayEnv: m.mockEnv })));++vi.mock('@lobechat/device-gateway-client', async (importOriginal) => ({+ ...(await importOriginal<typeof DeviceGatewayClientModule>()),+ GatewayHttpClient: (await import('./testUtils')).MockGatewayHttpClient,+}));++const base = { deviceId: 'device-1', userId: 'user-1', workspaceId: 'ws-1' };+const address = (timeout: number, extra: Record<string, unknown> = {}) => ({+ ...extra,+ deviceId: 'device-1',+ timeout,+ userId: 'user-1',+ workspaceId: 'ws-1',+});+const DATA = { answered: true };+const NET_DOWN = 'net down';++/**+ * - `undefined`: every failure degrades to `undefined`.+ * - `errorResult`: failures come back as `{ error, success: false }`.+ * - `throws`: failures reject.+ */+type FailureMode =+ | { kind: 'undefined' }+ | { defaultError: string; kind: 'errorResult'; unconfigured: string }+ | { defaultError: string; kind: 'throws'; unconfigured: string };++interface RpcCase {+ address: Record<string, unknown>;+ call: (gateway: DeviceGateway) => Promise<unknown>;+ failure: FailureMode;+ name: string;+ payload: Record<string, unknown>;+ /** Expected result for a successful `{ data: DATA }` answer; defaults to `DATA`. */+ success?: unknown;+}++const UNDEFINED: FailureMode = { kind: 'undefined' };+const errorResult = (defaultError: string): FailureMode => ({+ defaultError,+ kind: 'errorResult',+ unconfigured: 'Device gateway not configured',+});+const fileThrow = (defaultError: string): FailureMode => ({+ defaultError,+ kind: 'throws',+ unconfigured: 'Device gateway not configured',+});+const terminalThrow = (method: string): FailureMode => ({+ defaultError: `${method} failed`,+ kind: 'throws',+ unconfigured: 'Device gateway is not configured on this deployment.',+});++const prAction = { type: 'ready' } as unknown as DeviceGitPullRequestAction;+const repo = { name: 'repo', owner: 'owner' };+const env = { TOKEN: 'x' };++const cases: RpcCase[] = [+ // βββ git reads βββ+ {+ address: address(15_000),+ call: (g) => g.gitBranch({ ...base, path: '/p' }),+ failure: UNDEFINED,+ name: 'gitBranch',+ payload: { method: 'getGitBranch', params: { path: '/p' } },+ },+ {+ address: address(15_000),+ call: (g) => g.gitLinkedPullRequest({ ...base, branch: 'b', path: '/p', pullRequestNumber: 3 }),+ failure: UNDEFINED,+ name: 'gitLinkedPullRequest',+ payload: {+ method: 'getLinkedPullRequest',+ params: { branch: 'b', path: '/p', pullRequestNumber: 3 },+ },+ },+ {+ address: address(20_000),+ call: (g) => g.gitPullRequestDetail({ ...base, coreOnly: true, number: 5, path: '/p' }),+ failure: UNDEFINED,+ name: 'gitPullRequestDetail',+ payload: { method: 'getPullRequestDetail', params: { coreOnly: true, number: 5, path: '/p' } },+ },+ {+ address: address(20_000),+ call: (g) => g.gitPullRequestActivity({ ...base, number: 5, path: '/p' }),+ failure: UNDEFINED,+ name: 'gitPullRequestActivity',+ payload: { method: 'getPullRequestActivity', params: { number: 5, path: '/p' } },+ },+ {+ address: address(20_000),+ call: (g) =>+ g.gitPullRequestMergeContext({+ ...base,+ baseRefName: 'main',+ headRefOid: 'abc',+ number: 5,+ path: '/p',+ repo,+ }),+ failure: UNDEFINED,+ name: 'gitPullRequestMergeContext',+ payload: {+ method: 'getPullRequestMergeContext',+ params: { baseRefName: 'main', headRefOid: 'abc', number: 5, path: '/p', repo },+ },+ },+ {+ address: address(15_000),+ call: (g) => g.gitWorkingTreeStatus({ ...base, path: '/p' }),+ failure: UNDEFINED,+ name: 'gitWorkingTreeStatus',+ payload: { method: 'getGitWorkingTreeStatus', params: { path: '/p' } },+ },+ {+ address: address(15_000),+ call: (g) => g.gitAheadBehind({ ...base, path: '/p' }),+ failure: UNDEFINED,+ name: 'gitAheadBehind',+ payload: { method: 'getGitAheadBehind', params: { path: '/p' } },+ },+ {+ address: address(15_000),+ call: (g) => g.listGitWorktrees({ ...base, path: '/p' }),+ failure: UNDEFINED,+ name: 'listGitWorktrees',+ payload: { method: 'listGitWorktrees', params: { path: '/p' } },+ },+ {+ address: address(15_000),+ call: (g) => g.listGitBranches({ ...base, path: '/p' }),+ failure: UNDEFINED,+ name: 'listGitBranches',+ payload: { method: 'listGitBranches', params: { path: '/p' } },+ },+ {+ address: address(15_000),+ call: (g) => g.listGitRemoteBranches({ ...base, path: '/p' }),+ failure: UNDEFINED,+ name: 'listGitRemoteBranches',+ payload: { method: 'listGitRemoteBranches', params: { path: '/p' } },+ },+ {+ address: address(30_000),+ call: (g) => g.getGitWorkingTreePatches({ ...base, path: '/p' }),+ failure: UNDEFINED,+ name: 'getGitWorkingTreePatches',+ payload: { method: 'getGitWorkingTreePatches', params: { path: '/p' } },+ },+ {+ address: address(30_000),+ call: (g) => g.getGitBranchDiff({ ...base, baseRef: 'main', path: '/p' }),+ failure: UNDEFINED,+ name: 'getGitBranchDiff',+ payload: { method: 'getGitBranchDiff', params: { baseRef: 'main', path: '/p' } },+ },+ {+ address: address(15_000),+ call: (g) => g.getGitWorkingTreeFiles({ ...base, path: '/p' }),+ failure: UNDEFINED,+ name: 'getGitWorkingTreeFiles',+ payload: { method: 'getGitWorkingTreeFiles', params: { path: '/p' } },+ },+ // βββ git mutations βββ+ {+ address: address(30_000),+ call: (g) => g.checkoutGitBranch({ ...base, branch: 'b', create: true, path: '/p' }),+ failure: errorResult('Checkout failed'),+ name: 'checkoutGitBranch',+ payload: { method: 'checkoutGitBranch', params: { branch: 'b', create: true, path: '/p' } },+ },+ {+ address: address(30_000),+ call: (g) => g.renameGitBranch({ ...base, from: 'a', path: '/p', to: 'b' }),+ failure: errorResult('Rename failed'),+ name: 'renameGitBranch',+ payload: { method: 'renameGitBranch', params: { from: 'a', path: '/p', to: 'b' } },+ },+ {+ address: address(30_000),+ call: (g) => g.deleteGitBranch({ ...base, branch: 'b', path: '/p' }),+ failure: errorResult('Delete failed'),+ name: 'deleteGitBranch',+ payload: { method: 'deleteGitBranch', params: { branch: 'b', path: '/p' } },+ },+ {+ address: address(30_000),+ call: (g) => g.removeGitWorktree({ ...base, path: '/p', worktreePath: '/w' }),+ failure: errorResult('Remove worktree failed'),+ name: 'removeGitWorktree',+ payload: { method: 'removeGitWorktree', params: { path: '/p', worktreePath: '/w' } },+ },+ {+ address: address(30_000),+ call: (g) => g.addGitWorktree({ ...base, branch: 'b', path: '/p', worktreePath: '/w' }),+ failure: errorResult('Add worktree failed'),+ name: 'addGitWorktree',+ payload: {+ method: 'addGitWorktree',+ params: { branch: 'b', path: '/p', worktreePath: '/w' },+ },+ },+ {+ address: address(65_000),+ call: (g) => g.pullGitBranch({ ...base, path: '/p' }),+ failure: errorResult('Pull failed'),+ name: 'pullGitBranch',+ payload: { method: 'pullGitBranch', params: { path: '/p' } },+ },+ {+ address: address(65_000),+ call: (g) => g.pushGitBranch({ ...base, path: '/p' }),+ failure: errorResult('Push failed'),+ name: 'pushGitBranch',+ payload: { method: 'pushGitBranch', params: { path: '/p' } },+ },+ {+ address: address(65_000),+ call: (g) => g.runGitPullRequestAction({ ...base, action: prAction, number: 5, path: '/p' }),+ failure: errorResult('Pull request action failed'),+ name: 'runGitPullRequestAction',+ payload: {+ method: 'runPullRequestAction',+ params: { action: prAction, number: 5, path: '/p' },+ },+ },+ {+ address: address(15_000),+ call: (g) => g.revertGitFile({ ...base, filePath: 'a.ts', path: '/p' }),+ failure: errorResult('Revert failed'),+ name: 'revertGitFile',+ payload: { method: 'revertGitFile', params: { filePath: 'a.ts', path: '/p' } },+ },+ // βββ agent CLIs βββ+ {+ address: address(15_000),+ call: (g) => g.claudeCodeQuota({ ...base, env, force: true }),+ failure: UNDEFINED,+ name: 'claudeCodeQuota',+ payload: { method: 'getClaudeCodeQuota', params: { env, force: true } },+ },+ {+ address: address(15_000),+ call: (g) => g.codexQuota({ ...base, command: 'codex', env, force: true }),+ failure: UNDEFINED,+ name: 'codexQuota',+ payload: { method: 'getCodexQuota', params: { command: 'codex', env, force: true } },+ },+ {+ address: address(15_000),+ call: (g) => g.kimiCodeQuota({ ...base, env, force: true }),+ failure: UNDEFINED,+ name: 'kimiCodeQuota',+ payload: { method: 'getKimiCodeQuota', params: { env, force: true } },+ },+ // βββ workspace βββ+ {+ address: address(60_000),+ call: (g) =>+ g.prepareSkillDirectory({ ...base, forceRefresh: true, url: 'https://x', zipHash: 'h' }),+ failure: {+ defaultError: 'prepareSkillDirectory failed',+ kind: 'errorResult',+ unconfigured: 'Device Gateway is not configured',+ },+ name: 'prepareSkillDirectory',+ payload: {+ method: 'prepareSkillDirectory',+ params: { forceRefresh: true, url: 'https://x', zipHash: 'h' },+ },+ },+ {+ address: { deviceId: 'device-1', timeout: 30_000, userId: 'user-1' },+ call: (g) => g.enrollWorkspace({ ...base, identityOnly: true, token: 't' }),+ failure: {+ defaultError: 'enrollWorkspace failed',+ kind: 'errorResult',+ unconfigured: 'Device Gateway is not configured',+ },+ name: 'enrollWorkspace',+ payload: {+ method: 'enrollWorkspace',+ params: { identityOnly: true, token: 't', workspaceId: 'ws-1' },+ },+ success: { identity: DATA, success: true },+ },+ {+ address: address(10_000),+ call: (g) => g.unenrollWorkspace(base),+ failure: {+ defaultError: 'unenrollWorkspace failed',+ kind: 'errorResult',+ unconfigured: 'Device Gateway is not configured',+ },+ name: 'unenrollWorkspace',+ payload: { method: 'unenrollWorkspace', params: { workspaceId: 'ws-1' } },+ success: { success: true },+ },+ {+ address: address(8000),+ call: (g) => g.statPath({ ...base, path: '/p' }),+ failure: UNDEFINED,+ name: 'statPath',+ payload: { method: 'statPath', params: { path: '/p' } },+ },+ {+ address: address(10_000),+ call: (g) => g.listListeningPorts({ ...base, cwd: '/p' }),+ failure: UNDEFINED,+ name: 'listListeningPorts',+ payload: { method: 'listListeningPorts', params: { cwd: '/p' } },+ },+ // βββ project files (reads) βββ+ {+ address: address(30_000),+ call: (g) => g.getProjectFileIndex({ ...base, scope: '/p' }),+ failure: UNDEFINED,+ name: 'getProjectFileIndex',+ payload: { method: 'getProjectFileIndex', params: { scope: '/p' } },+ },+ {+ address: address(30_000),+ call: (g) => g.listProjectDirectory({ ...base, relativePath: 'src', root: '/p' }),+ failure: UNDEFINED,+ name: 'listProjectDirectory',+ payload: { method: 'listProjectDirectory', params: { relativePath: 'src', root: '/p' } },+ },+ {+ address: address(10_000),+ call: (g) => g.browseDirectory({ ...base, cursor: 'c', limit: 10, path: '/p' }),+ failure: UNDEFINED,+ name: 'browseDirectory',+ payload: { method: 'browseDirectory', params: { cursor: 'c', limit: 10, path: '/p' } },+ },+ {+ address: address(30_000),+ call: (g) =>+ g.searchProjectFiles({+ ...base,+ changedOnly: true,+ excludeIgnored: true,+ limit: 5,+ query: 'q',+ scope: '/p',+ }),+ failure: UNDEFINED,+ name: 'searchProjectFiles',+ payload: {+ method: 'searchProjectFiles',+ params: { changedOnly: true, excludeIgnored: true, limit: 5, query: 'q', scope: '/p' },+ },+ },+ {+ address: address(30_000),+ call: (g) => g.listProjectSkills({ ...base, scope: '/p' }),+ failure: UNDEFINED,+ name: 'listProjectSkills',+ payload: { method: 'listProjectSkills', params: { scope: '/p' } },+ },+ {+ address: address(30_000),+ call: (g) =>+ g.copyAssetForPublish({ ...base, from: '/x/a.png', to: '/p/a.png', workingDirectory: '/p' }),+ failure: errorResult('Failed to copy publish asset'),+ name: 'copyAssetForPublish',+ payload: {+ method: 'copyAssetForPublish',+ params: { from: '/x/a.png', to: '/p/a.png', workingDirectory: '/p' },+ },+ },+ {+ address: address(30_000),+ call: (g) =>+ g.readExternalAssetForPublish({ ...base, path: '/x/a.png', workingDirectory: '/p' }),+ failure: errorResult('Failed to read external publish asset'),+ name: 'readExternalAssetForPublish',+ payload: {+ method: 'readExternalAssetForPublish',+ params: { path: '/x/a.png', workingDirectory: '/p' },+ },+ },+ // βββ project files (mutations) βββ+ {+ address: address(30_000),+ call: (g) =>+ g.moveProjectFiles({+ ...base,+ items: [{ newPath: '/p/b.ts', oldPath: '/p/a.ts' }],+ workingDirectory: '/p',+ }),+ failure: fileThrow('Move failed'),+ name: 'moveProjectFiles',+ payload: {+ method: 'moveLocalFiles',+ params: { items: [{ newPath: '/p/b.ts', oldPath: '/p/a.ts' }], workspaceRoot: '/p' },+ },+ },+ {+ address: address(30_000),+ call: (g) =>+ g.renameProjectFile({ ...base, newName: 'b.ts', path: '/p/a.ts', workingDirectory: '/p' }),+ failure: fileThrow('Rename failed'),+ name: 'renameProjectFile',+ payload: {+ method: 'renameLocalFile',+ params: { newName: 'b.ts', path: '/p/a.ts', workspaceRoot: '/p' },+ },+ },+ {+ address: address(30_000),+ call: (g) =>+ g.writeProjectFile({ ...base, content: 'x', path: '/p/a.ts', workingDirectory: '/p' }),+ failure: fileThrow('Write failed'),+ name: 'writeProjectFile',+ payload: {+ method: 'writeLocalFile',+ params: { content: 'x', path: '/p/a.ts', workspaceRoot: '/p' },+ },+ },+ {+ address: address(30_000),+ call: (g) =>+ g.createProjectFile({ ...base, content: 'x', path: '/p/a.ts', workingDirectory: '/p' }),+ failure: fileThrow('Create file failed'),+ name: 'createProjectFile',+ payload: {+ method: 'createLocalFile',+ params: { content: 'x', path: '/p/a.ts', workspaceRoot: '/p' },+ },+ },+ {+ address: address(30_000),+ call: (g) => g.createProjectDirectory({ ...base, path: '/p/dir', workingDirectory: '/p' }),+ failure: fileThrow('Create folder failed'),+ name: 'createProjectDirectory',+ payload: { method: 'createLocalDirectory', params: { path: '/p/dir', workspaceRoot: '/p' } },+ },+ {+ address: address(30_000),+ call: (g) => g.createDirectory({ ...base, name: 'dir', parentPath: '/p' }),+ failure: fileThrow('Create folder failed'),+ name: 'createDirectory',+ payload: { method: 'createLocalDirectory', params: { path: '/p/dir', workspaceRoot: '/p' } },+ },+ {+ address: address(60_000),+ call: (g) =>+ g.copyProjectFiles({ ...base, items: [{ sourcePath: '/p/a.ts' }], workingDirectory: '/p' }),+ failure: fileThrow('Copy failed'),+ name: 'copyProjectFiles',+ payload: {+ method: 'copyLocalFiles',+ params: { items: [{ sourcePath: '/p/a.ts' }], workspaceRoot: '/p' },+ },+ },+ {+ address: address(30_000),+ call: (g) => g.trashProjectFiles({ ...base, paths: ['/p/a.ts'], workingDirectory: '/p' }),+ failure: fileThrow('Move to trash failed'),+ name: 'trashProjectFiles',+ payload: { method: 'trashLocalFiles', params: { paths: ['/p/a.ts'], workspaceRoot: '/p' } },+ },+ // βββ terminal βββ+ {+ address: address(15_000, { channel: 'cli' }),+ call: (g) => g.createTerminalSession({ ...base, cols: 80, cwd: '/p', rows: 24 }),+ failure: terminalThrow('createTerminalSession'),+ name: 'createTerminalSession',+ payload: { method: 'createTerminalSession', params: { cols: 80, cwd: '/p', rows: 24 } },+ },+ {+ address: address(15_000, { channel: 'cli' }),+ call: (g) => g.writeTerminal({ ...base, data: 'ls', id: 't1' }),+ failure: terminalThrow('writeTerminal'),+ name: 'writeTerminal',+ payload: { method: 'writeTerminal', params: { data: 'ls', id: 't1' } },+ success: undefined,+ },+ {+ address: address(15_000, { channel: 'cli' }),+ call: (g) => g.readTerminal({ ...base, cursor: 0, id: 't1' }),+ failure: terminalThrow('readTerminal'),+ name: 'readTerminal',+ payload: { method: 'readTerminal', params: { cursor: 0, id: 't1' } },+ },+ {+ address: address(15_000, { channel: 'cli' }),+ call: (g) => g.resizeTerminal({ ...base, cols: 100, id: 't1', rows: 30 }),+ failure: terminalThrow('resizeTerminal'),+ name: 'resizeTerminal',+ payload: { method: 'resizeTerminal', params: { cols: 100, id: 't1', rows: 30 } },+ success: undefined,+ },+ {+ address: address(15_000, { channel: 'cli' }),+ call: (g) => g.closeTerminal({ ...base, id: 't1' }),+ failure: terminalThrow('closeTerminal'),+ name: 'closeTerminal',+ payload: { method: 'closeTerminal', params: { id: 't1' } },+ },+];++const expectFailure = async (+ promise: Promise<unknown>,+ failure: FailureMode,+ message: string | undefined,+) => {+ switch (failure.kind) {+ case 'undefined': {+ await expect(promise).resolves.toBeUndefined();+ break;+ }+ case 'errorResult': {+ await expect(promise).resolves.toEqual({ error: message, success: false });+ break;+ }+ case 'throws': {+ await expect(promise).rejects.toThrow(message);+ break;+ }+ }+};++describe('DeviceGateway RPC surface', () => {+ beforeEach(() => {+ resetGatewayMocks();+ });++ it.each(cases)('$name relays its RPC and unwraps the answer', async (c) => {+ configureGateway();+ mockClient.invokeRpc.mockResolvedValue({ data: DATA, success: true });++ const result = await c.call(new DeviceGateway());++ expect(mockClient.invokeRpc).toHaveBeenCalledTimes(1);+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(c.address, c.payload);+ expect(result).toEqual('success' in c ? c.success : DATA);+ });++ it.each(cases)('$name without a configured gateway', async (c) => {+ const promise = c.call(new DeviceGateway());++ await expectFailure(+ promise,+ c.failure,+ c.failure.kind === 'undefined' ? undefined : c.failure.unconfigured,+ );+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();+ });++ it.each(cases)('$name when the device answers success: false', async (c) => {+ configureGateway();+ mockClient.invokeRpc.mockResolvedValue({ success: false });++ await expectFailure(+ c.call(new DeviceGateway()),+ c.failure,+ c.failure.kind === 'undefined' ? undefined : c.failure.defaultError,+ );+ });++ it.each(cases)('$name when the transport throws', async (c) => {+ configureGateway();+ mockClient.invokeRpc.mockRejectedValue(new Error(NET_DOWN));++ await expectFailure(c.call(new DeviceGateway()), c.failure, NET_DOWN);+ });++ describe('listHeterogeneousAgentModels', () => {+ const call = () =>+ new DeviceGateway().listHeterogeneousAgentModels({+ ...base,+ args: ['--x'],+ command: 'codex',+ cwd: '/p',+ env,+ type: 'codex',+ });++ it('relays the catalog RPC with a 20s budget', async () => {+ configureGateway();+ mockClient.invokeRpc.mockResolvedValue({ data: DATA, success: true });++ await expect(call()).resolves.toEqual(DATA);+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(address(20_000), {+ method: 'listHeterogeneousAgentModels',+ params: { args: ['--x'], command: 'codex', cwd: '/p', env, type: 'codex' },+ });+ });++ it.each([+ ['unconfigured', undefined, 'device_unavailable', 'Device gateway is not configured'],+ ['an outdated client', 'Unknown device RPC method: x', 'unsupported_client', undefined],+ [+ 'a client without discovery',+ 'does not support heterogeneous agent model discovery',+ 'unsupported_client',+ undefined,+ ],+ ['a device error', 'boom', 'device_unavailable', undefined],+ ['a silent failure', '', 'device_unavailable', 'The device did not return a model catalog'],+ ])('reports %s', async (_label, error, code, message) => {+ if (error !== undefined) {+ configureGateway();+ mockClient.invokeRpc.mockResolvedValue({ error, success: false });+ }++ await expect(call()).resolves.toEqual({+ error: { code, message: message ?? error },+ status: 'error',+ updatedAt: expect.any(Number),+ });+ });++ it('reports a transport failure as unavailable', async () => {+ configureGateway();+ mockClient.invokeRpc.mockRejectedValue(new Error(NET_DOWN));++ await expect(call()).resolves.toEqual({+ error: { code: 'device_unavailable', message: NET_DOWN },+ status: 'error',+ updatedAt: expect.any(Number),+ });+ });+ });++ describe('dispatchAgentRun', () => {+ const params = {+ agentType: 'codex' as const,+ assistantMessageId: 'msg-1',+ jwt: 'jwt',+ operationId: 'op-1',+ prompt: 'hi',+ topicId: 'topic-1',+ userId: 'user-1',+ };++ it('passes the run straight to the gateway client', async () => {+ configureGateway();+ mockClient.dispatchAgentRun.mockResolvedValue({ success: true });++ await expect(new DeviceGateway().dispatchAgentRun(params)).resolves.toEqual({+ success: true,+ });+ expect(mockClient.dispatchAgentRun).toHaveBeenCalledWith(params);+ });++ it('reports an unconfigured gateway', async () => {+ await expect(new DeviceGateway().dispatchAgentRun(params)).resolves.toEqual({+ error: 'GATEWAY_NOT_CONFIGURED',+ success: false,+ });+ });++ it('reports a transport failure', async () => {+ configureGateway();+ mockClient.dispatchAgentRun.mockRejectedValue(new Error(NET_DOWN));++ await expect(new DeviceGateway().dispatchAgentRun(params)).resolves.toEqual({+ error: NET_DOWN,+ success: false,+ });+ });+ });+});diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.tsindex 9d34702e58c..847044d5d25 100644--- a/apps/server/src/services/deviceGateway/index.ts+++ b/apps/server/src/services/deviceGateway/index.ts@@ -1,156 +1,32 @@import { type DeviceAttachment } from '@lobechat/builtin-tool-remote-device';import {describeGatewayRequestFailure,- type DeviceMessageApiResult,type DeviceStatusResult,type DeviceSystemInfo,- type DeviceToolCallResult,GatewayHttpClient,- type GatewayMcpParams,} from '@lobechat/device-gateway-client';-import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';-import type {- ClaudeCodeQuotaSnapshot,- CodexQuotaSnapshot,- KimiCodeQuotaSnapshot,-} from '@lobechat/heterogeneous-agents/quota';-import type {- DeviceAppUpdateFailure,- DeviceAppUpdateInstallResult,- DeviceAppUpdateState,- DeviceAppUpdateStateResult,- DeviceClient,- DeviceCliRestartParams,- DeviceCliUpdateState,- DeviceCliUpdateStateResult,- DeviceCloseTerminalResult,- DeviceCopyAssetForPublishResult,- DeviceCopyProjectFileItem,- DeviceCopyProjectFileResultItem,- DeviceCreateProjectEntryResult,- DeviceCreateTerminalSessionResult,- DeviceDirectoryBrowseResult,- DeviceExternalAssetForPublishResult,- DeviceGitAddWorktreeResult,- DeviceGitAheadBehind,- DeviceGitBranchDiffPatches,- DeviceGitBranchInfo,- DeviceGitBranchListItem,- DeviceGitCheckoutResult,- DeviceGitDeleteBranchResult,- DeviceGitFileRevertResult,- DeviceGitLinkedPullRequestResult,- DeviceGitPullRequestAction,- DeviceGitPullRequestActionResult,- DeviceGitPullRequestActivity,- DeviceGitPullRequestDetailResult,- DeviceGitPullRequestMergeContext,- DeviceGitRemoteBranchListItem,- DeviceGitRemoveWorktreeResult,- DeviceGitRenameBranchResult,- DeviceGitSyncResult,- DeviceGitWorkingTreeFiles,- DeviceGitWorkingTreePatches,- DeviceGitWorkingTreeStatus,- DeviceGitWorktreeListItem,- DeviceListeningPortsResult,- DeviceListProjectSkillsResult,- DeviceLocalFilePreviewResult,- DeviceMetricSample,- DeviceMoveProjectFileItem,- DeviceMoveProjectFileResultItem,- DeviceProjectDirectoryListResult,- DeviceProjectFileIndexResult,- DeviceProjectFileSearchResult,- DeviceReadTerminalResult,- DeviceRenameProjectFileResult,- DeviceTrashProjectFilesResult,- DeviceUnavailableErrorData,- DeviceWriteProjectFileResult,- HeterogeneousAgentModelCatalog,- ProjectSkillMeta,- WorkspaceInitResult,-} from '@lobechat/types';-import { isValidDirectoryName } from '@lobechat/utils/directoryName';+import type { DeviceClient, DeviceMetricSample } from '@lobechat/types';import debug from 'debug';-import { isAbsolute, relative, resolve } from 'pathe';import { gatewayEnv } from '@/envs/gateway';import { redisService } from '@/server/services/redis';+import * as agents from './agents';import { resolveDeviceClientKinds } from './clientKinds';+import * as clientUpdate from './clientUpdate';+import * as gitRead from './gitRead';+import * as gitWrite from './gitWrite';+import * as projectFileMutations from './projectFileMutations';+import * as projectFiles from './projectFiles';+import * as terminal from './terminal';+import type { DeviceClientGetter, DeviceRpcArgs } from './types';+import * as workspace from './workspace';const log = debug('lobe-server:device-gateway');-/**- * Is `target` the same as, or nested inside, `root`?- *- * The device's working directory may be a POSIX path (`/Users/β¦`) or a Windows- * path (`C:\β¦` / `\\server\share`) while this check runs on the cloud server- * (POSIX). `pathe` auto-detects the path flavour per argument, so Windows- * device paths are resolved with Windows semantics without us branching on- * `path.win32` / `path.posix`.- */-export const isPathWithinRoot = (root: string, target: string): boolean => {- if (!isAbsolute(root) || !isAbsolute(target)) return false;- const rel = relative(resolve(root), resolve(target));- return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));-};--/**- * Guard the web/remote file mutations (move / rename / write) against escaping- * the project root. These routes accept absolute paths straight from an- * untrusted browser session, so before forwarding them to a device we confirm- * every path stays inside the workspace the UI is operating in β otherwise a- * caller could bypass the Files tree and mutate arbitrary locations on the- * device. Mirrors the read path's `workspaceRoot` containment check.- */-const assertPathsWithinWorkspace = (- workspaceRoot: string,- candidates: Array<string | undefined>,-): void => {- if (!workspaceRoot) throw new Error('A workspace root is required for file mutations');-- for (const candidate of candidates) {- if (!candidate || !isPathWithinRoot(workspaceRoot, candidate)) {- throw new Error(`Path is outside the approved workspace: ${candidate ?? '(empty)'}`);- }- }-};-+export { isPathWithinRoot, joinDevicePath } from './paths';export { isValidDirectoryName } from '@lobechat/utils/directoryName';-/**- * Append one segment to a device path, keeping the device's own separator. The- * folder picker browses Windows devices too (`C:\Users`), and `pathe.join`- * would rewrite those to forward slashes.- */-export const joinDevicePath = (parentPath: string, name: string): string => {- const separator = /^[A-Z]:\\/i.test(parentPath) || parentPath.startsWith('\\\\') ? '\\' : '/';- return `${parentPath.replace(/[\\/]+$/, '')}${separator}${name}`;-};--/**- * Refuse to trash / rename / move / duplicate the workspace root itself. It- * passes the containment check (a root is "within" itself), but removing or- * renaming it pulls the whole Files tree out from under the UI, and a duplicate- * of the root would land in its parent β outside the workspace.- */-const assertNotWorkspaceRoot = (- workspaceRoot: string,- candidates: Array<string | undefined>,-): void => {- for (const candidate of candidates) {- if (- candidate &&- isAbsolute(candidate) &&- relative(resolve(workspaceRoot), resolve(candidate)) === ''- ) {- throw new Error(`This operation is not allowed on the workspace root: ${candidate}`);- }- }-};-export type { DeviceAttachment, DeviceStatusResult, DeviceSystemInfo };/**@@ -160,32 +36,20 @@ export type { DeviceAttachment, DeviceStatusResult, DeviceSystemInfo };export type DeviceSystemInfoRead ={ ok: true; systemInfo: DeviceSystemInfo } | { ok: false; reason: string };-interface AppUpdateRpcParams {- deviceId: string;- timeout?: number;- userId: string;- workspaceId?: string;-}-/** One extra attempt for a device read; see `readDevices`. */const DEVICE_READ_ATTEMPTS = 2;const DEVICE_READ_RETRY_DELAY_MS = 250;-/** Scope every terminal RPC carries; mirrors {@link AppUpdateRpcParams}. */-interface TerminalRpcScope {- deviceId: string;- timeout?: number;- userId: string;- workspaceId?: string;-}--/** The five device RPCs that make up one interactive terminal session. */-type TerminalRpcMethod =- 'closeTerminal' | 'createTerminalSession' | 'readTerminal' | 'resizeTerminal' | 'writeTerminal';-+/**+ * The gateway service. Device presence reads live here; every other device RPC+ * is a module function (`gitRead`, `projectFiles`, `terminal`, β¦) that this+ * class exposes under its original method name, handing it the lazy client.+ */export class DeviceGateway {private client: GatewayHttpClient | null = null;+ private readonly clientGetter: DeviceClientGetter = () => this.getClient();+/*** Run a device READ, retrying once and reporting the fallback out loud.*@@ -391,1980 +255,260 @@ export class DeviceGateway {}}- /**- * Scan a bound project directory on the device in a single round-trip:- * project skills (`.agents/skills` + `.claude/skills`) plus the root- * `AGENTS.md` / `CLAUDE.md`. Routed through the generic device RPC relay- * (`invokeRpc`) β a server-internal channel the agent never sees, distinct- * from the LLM-facing tool-call path.- *- * Returns `undefined` when the gateway is unconfigured, the device is offline,- * or the call fails β callers fall back to the cached scan.- */- async initWorkspace(params: {- deviceId: string;- scope: string;- timeout?: number;- userId: string;- workspaceId?: string;- }): Promise<WorkspaceInitResult | undefined> {- const { userId, deviceId, scope, timeout = 30_000, workspaceId } = params;- const client = this.getClient();- if (!client) return undefined;-- try {- // The device returns rich `ProjectSkillItem`s; narrow to metadata only so- // the cached `workingDirs` payload stays small (SKILL.md bodies are still- // read lazily at activation time). Keep scope so project/device skills can- // be displayed and activated with the correct origin.- const result = await client.invokeRpc<{- instructions?: WorkspaceInitResult['instructions'];- skills?: (ProjectSkillMeta & Record<string, unknown>)[];- }>(- { deviceId, timeout, userId, workspaceId },- { method: 'initWorkspace', params: { scope } },- );-- if (!result.success || !result.data) {- log('initWorkspace: failed for deviceId=%s β %s', deviceId, result.error);- return undefined;- }-- const { instructions, skills } = result.data;- return {- instructions: instructions ?? [],- skills: (skills ?? []).map(({ description, name, path, scope }) => ({- description,- name,- path,- scope,- })),- };- } catch (error) {- log('initWorkspace: error for deviceId=%s β %O', deviceId, error);- return undefined;- }+ initWorkspace(...args: DeviceRpcArgs<typeof workspace.initWorkspace>) {+ return workspace.initWorkspace(this.clientGetter, ...args);}- /**- * Prepare a skill archive on the device: download the presigned zip and- * extract it into the device-local cache (idempotent by `zipHash`). Runs on- * the generic device RPC relay like `initWorkspace`, but unlike the- * read-oriented helpers, failures are RETURNED with their reason instead of- * collapsing to `undefined` β the skills exec path must tell the model why- * the device can't run the skill (offline, outdated client, download- * failure) rather than silently degrading to the sandbox.- */- async prepareSkillDirectory(params: {- deviceId: string;- forceRefresh?: boolean;- timeout?: number;- url: string;- userId: string;- workspaceId?: string;- zipHash: string;- }): Promise<{ error?: string; extractedDir?: string; success: boolean }> {- const { deviceId, forceRefresh, timeout = 60_000, url, userId, workspaceId, zipHash } = params;- const client = this.getClient();- if (!client) return { error: 'Device Gateway is not configured', success: false };-- try {- const result = await client.invokeRpc<{- error?: string;- extractedDir: string;- success: boolean;- }>(- { deviceId, timeout, userId, workspaceId },- { method: 'prepareSkillDirectory', params: { forceRefresh, url, zipHash } },- );-- if (!result.success || !result.data) {- return { error: result.error || 'prepareSkillDirectory failed', success: false };- }+ prepareSkillDirectory(...args: DeviceRpcArgs<typeof workspace.prepareSkillDirectory>) {+ return workspace.prepareSkillDirectory(this.clientGetter, ...args);+ }- return result.data;- } catch (error) {- const message = error instanceof Error ? error.message : String(error);- log('prepareSkillDirectory: error for deviceId=%s β %s', deviceId, message);- return { error: message, success: false };- }+ enrollWorkspace(...args: DeviceRpcArgs<typeof workspace.enrollWorkspace>) {+ return workspace.enrollWorkspace(this.clientGetter, ...args);}- /**- * Instruct an ONLINE personal device to enroll itself into a workspace: the- * device derives its workspace-scoped deviceId and opens a second gateway- * connection under the `workspace:<id>` principal using the short-lived- * `token` (a signed workspace-device connect token), then returns the derived- * identity so the caller can register the workspace row server-side. Rides- * the generic device RPC relay over the PERSONAL pool (no `workspaceId` in- * the address β the workspace connection doesn't exist yet). Failures are- * RETURNED with their reason β the share flow must tell the user why the- * device couldn't enroll (offline, outdated client) instead of silently- * doing nothing.- */- async enrollWorkspace(params: {- deviceId: string;- /**- * Dry-run: the device only derives and returns its workspace identity,- * without opening a share connection or persisting enrollment state.- * Older clients ignore the flag and enroll on the probe (pre-flag- * behaviour), so callers must treat the probe as possibly-enrolling.- */- identityOnly?: boolean;- timeout?: number;- token: string;- userId: string;- workspaceId: string;- }): Promise<{- error?: string;- identity?: { deviceId: string; identitySource: 'fallback' | 'machine-id' };- success: boolean;- }> {- const { deviceId, identityOnly, timeout = 30_000, token, userId, workspaceId } = params;- const client = this.getClient();- if (!client) return { error: 'Device Gateway is not configured', success: false };+ unenrollWorkspace(...args: DeviceRpcArgs<typeof workspace.unenrollWorkspace>) {+ return workspace.unenrollWorkspace(this.clientGetter, ...args);+ }- try {- const result = await client.invokeRpc<{- deviceId: string;- identitySource: 'fallback' | 'machine-id';- }>(- { deviceId, timeout, userId },- {- method: 'enrollWorkspace',- params: { ...(identityOnly ? { identityOnly } : {}), token, workspaceId },- },- );+ gitBranch(...args: DeviceRpcArgs<typeof gitRead.gitBranch>) {+ return gitRead.gitBranch(this.clientGetter, ...args);+ }- if (!result.success || !result.data) {- return { error: result.error || 'enrollWorkspace failed', success: false };- }+ gitLinkedPullRequest(...args: DeviceRpcArgs<typeof gitRead.gitLinkedPullRequest>) {+ return gitRead.gitLinkedPullRequest(this.clientGetter, ...args);+ }- return { identity: result.data, success: true };- } catch (error) {- const message = error instanceof Error ? error.message : String(error);- log('enrollWorkspace: error for deviceId=%s β %s', deviceId, message);- return { error: message, success: false };- }+ gitPullRequestDetail(...args: DeviceRpcArgs<typeof gitRead.gitPullRequestDetail>) {+ return gitRead.gitPullRequestDetail(this.clientGetter, ...args);}- /**- * Instruct an ONLINE workspace device to drop its enrollment: close the- * workspace-principal connection and clear any persisted auto-reconnect state- * on the machine. Addressed over the WORKSPACE pool (the connection being- * killed), so it works regardless of who enrolled the device or whether a- * personal connection exists. Best-effort β callers delete the DB row either- * way, so an offline device simply loses its row and stops resolving.- */- async unenrollWorkspace(params: {- deviceId: string;- timeout?: number;- userId: string;- workspaceId: string;- }): Promise<{ error?: string; success: boolean }> {- const { deviceId, timeout = 10_000, userId, workspaceId } = params;- const client = this.getClient();- if (!client) return { error: 'Device Gateway is not configured', success: false };+ gitPullRequestActivity(...args: DeviceRpcArgs<typeof gitRead.gitPullRequestActivity>) {+ return gitRead.gitPullRequestActivity(this.clientGetter, ...args);+ }- try {- const result = await client.invokeRpc<{ success: boolean }>(- { deviceId, timeout, userId, workspaceId },- { method: 'unenrollWorkspace', params: { workspaceId } },- );- if (!result.success)- return { error: result.error || 'unenrollWorkspace failed', success: false };- return { success: true };- } catch (error) {- const message = error instanceof Error ? error.message : String(error);- log('unenrollWorkspace: error for deviceId=%s β %s', deviceId, message);- return { error: message, success: false };- }+ gitPullRequestMergeContext(...args: DeviceRpcArgs<typeof gitRead.gitPullRequestMergeContext>) {+ return gitRead.gitPullRequestMergeContext(this.clientGetter, ...args);}- /**- * Generic helper for granular device read RPCs (git branch / PR /- * working-tree / ahead-behind / Claude quota). Returns `undefined` when the- * gateway is unconfigured, the device is offline, or the call fails β- * callers treat that as "unknown".- */- private async invokeDeviceRead<T>(- method: string,- params: { deviceId: string; timeout?: number; userId: string; workspaceId?: string },- rpcParams: Record<string, unknown>,- ): Promise<T | undefined> {- const { userId, deviceId, timeout = 15_000, workspaceId } = params;- const client = this.getClient();- if (!client) return undefined;+ gitWorkingTreeStatus(...args: DeviceRpcArgs<typeof gitRead.gitWorkingTreeStatus>) {+ return gitRead.gitWorkingTreeStatus(this.clientGetter, ...args);+ }- try {- const result = await client.invokeRpc<T>(- { deviceId, timeout, userId, workspaceId },- { method, params: rpcParams },- );+ gitAheadBehind(...args: DeviceRpcArgs<typeof gitRead.gitAheadBehind>) {+ return gitRead.gitAheadBehind(this.clientGetter, ...args);+ }- if (!result.success || result.data === undefined) {- log('%s: failed for deviceId=%s β %s', method, deviceId, result.error);- return undefined;- }+ claudeCodeQuota(...args: DeviceRpcArgs<typeof agents.claudeCodeQuota>) {+ return agents.claudeCodeQuota(this.clientGetter, ...args);+ }- return result.data;- } catch (error) {- log('%s: error for deviceId=%s β %O', method, deviceId, error);- return undefined;- }+ codexQuota(...args: DeviceRpcArgs<typeof agents.codexQuota>) {+ return agents.codexQuota(this.clientGetter, ...args);}- /** Branch name + detached flag for a directory on a remote device. */- gitBranch(params: { deviceId: string; path: string; userId: string; workspaceId?: string }) {- return this.invokeDeviceRead<DeviceGitBranchInfo>('getGitBranch', params, {- path: params.path,- });+ kimiCodeQuota(...args: DeviceRpcArgs<typeof agents.kimiCodeQuota>) {+ return agents.kimiCodeQuota(this.clientGetter, ...args);}- /** The GitHub PR linked to a branch in a directory on a remote device. */- gitLinkedPullRequest(params: {- branch: string;- deviceId: string;- path: string;- pullRequestNumber?: number;- userId: string;- workspaceId?: string;- }) {- return this.invokeDeviceRead<DeviceGitLinkedPullRequestResult>('getLinkedPullRequest', params, {- branch: params.branch,- path: params.path,- pullRequestNumber: params.pullRequestNumber,- });+ listGitWorktrees(...args: DeviceRpcArgs<typeof gitRead.listGitWorktrees>) {+ return gitRead.listGitWorktrees(this.clientGetter, ...args);}- /** Full detail of a pull request in a directory on a remote device. */- gitPullRequestDetail(params: {- coreOnly?: boolean;- deviceId: string;- number: number;- path: string;- userId: string;- workspaceId?: string;- }) {- return this.invokeDeviceRead<DeviceGitPullRequestDetailResult>(- 'getPullRequestDetail',- { ...params, timeout: 20_000 },- {- coreOnly: params.coreOnly,- number: params.number,- path: params.path,- },- );+ listHeterogeneousAgentModels(...args: DeviceRpcArgs<typeof agents.listHeterogeneousAgentModels>) {+ return agents.listHeterogeneousAgentModels(this.clientGetter, ...args);}- gitPullRequestActivity(params: {- deviceId: string;- number: number;- path: string;- userId: string;- workspaceId?: string;- }) {- return this.invokeDeviceRead<DeviceGitPullRequestActivity>(- 'getPullRequestActivity',- { ...params, timeout: 20_000 },- {- number: params.number,- path: params.path,- },- );+ listGitBranches(...args: DeviceRpcArgs<typeof gitRead.listGitBranches>) {+ return gitRead.listGitBranches(this.clientGetter, ...args);}- /** Branch-protection / permission context for a pull request on a remote device. */- gitPullRequestMergeContext(params: {- baseRefName: string;- deviceId: string;- headRefOid: string;- number: number;- path: string;- repo: { name: string; owner: string };- userId: string;- workspaceId?: string;- }) {- return this.invokeDeviceRead<DeviceGitPullRequestMergeContext>(- 'getPullRequestMergeContext',- { ...params, timeout: 20_000 },- {- baseRefName: params.baseRefName,- headRefOid: params.headRefOid,- number: params.number,- path: params.path,- repo: params.repo,- },- );+ checkoutGitBranch(...args: DeviceRpcArgs<typeof gitWrite.checkoutGitBranch>) {+ return gitWrite.checkoutGitBranch(this.clientGetter, ...args);}- /** Working-tree dirty-file counts for a directory on a remote device. */- gitWorkingTreeStatus(params: {- deviceId: string;- path: string;- userId: string;- workspaceId?: string;- }) {- return this.invokeDeviceRead<DeviceGitWorkingTreeStatus>('getGitWorkingTreeStatus', params, {- path: params.path,- });+ renameGitBranch(...args: DeviceRpcArgs<typeof gitWrite.renameGitBranch>) {+ return gitWrite.renameGitBranch(this.clientGetter, ...args);}- /** Ahead/behind commit counts for a directory on a remote device. */- gitAheadBehind(params: { deviceId: string; path: string; userId: string; workspaceId?: string }) {- return this.invokeDeviceRead<DeviceGitAheadBehind>('getGitAheadBehind', params, {- path: params.path,- });+ deleteGitBranch(...args: DeviceRpcArgs<typeof gitWrite.deleteGitBranch>) {+ return gitWrite.deleteGitBranch(this.clientGetter, ...args);}- /**- * Claude Code subscription quota of the login on a remote device. The device- * samples the Anthropic usage API with its local credentials β same sampler- * as the desktop IPC path. `undefined` also covers older device clients that- * don't know this RPC yet.- */- claudeCodeQuota(params: {- deviceId: string;- env?: Record<string, string>;- force?: boolean;- userId: string;- workspaceId?: string;- }) {- return this.invokeDeviceRead<ClaudeCodeQuotaSnapshot>('getClaudeCodeQuota', params, {- env: params.env,- force: params.force,- });+ removeGitWorktree(...args: DeviceRpcArgs<typeof gitWrite.removeGitWorktree>) {+ return gitWrite.removeGitWorktree(this.clientGetter, ...args);}- /** Codex subscription quota sampled from the login on a remote device. */- codexQuota(params: {- command?: string;- deviceId: string;- env?: Record<string, string>;- force?: boolean;- userId: string;- workspaceId?: string;- }) {- return this.invokeDeviceRead<CodexQuotaSnapshot>('getCodexQuota', params, {- command: params.command,- env: params.env,- force: params.force,- });+ addGitWorktree(...args: DeviceRpcArgs<typeof gitWrite.addGitWorktree>) {+ return gitWrite.addGitWorktree(this.clientGetter, ...args);}- /** Kimi Code subscription quota sampled from the login on a remote device. */- kimiCodeQuota(params: {- deviceId: string;- env?: Record<string, string>;- force?: boolean;- userId: string;- workspaceId?: string;- }) {- return this.invokeDeviceRead<KimiCodeQuotaSnapshot>('getKimiCodeQuota', params, {- env: params.env,- force: params.force,- });+ pullGitBranch(...args: DeviceRpcArgs<typeof gitWrite.pullGitBranch>) {+ return gitWrite.pullGitBranch(this.clientGetter, ...args);}- /** Git worktrees attached to the same repository as a directory on a remote device. */- listGitWorktrees(params: {- deviceId: string;- path: string;- userId: string;- workspaceId?: string;- }) {- return this.invokeDeviceRead<DeviceGitWorktreeListItem[]>('listGitWorktrees', params, {- path: params.path,- });+ pushGitBranch(...args: DeviceRpcArgs<typeof gitWrite.pushGitBranch>) {+ return gitWrite.pushGitBranch(this.clientGetter, ...args);}- /** Query a heterogeneous CLI's model catalog on the device that will execute it. */- async listHeterogeneousAgentModels(params: {- args?: string[];- command?: string;- cwd?: string;- deviceId: string;- env?: Record<string, string>;- timeout?: number;- type:- | 'codebuddy'- | 'codex'- | 'cursor'- | 'devin'- | 'droid'- | 'grok-build'- | 'kimi-code'- | 'opencode'- | 'pi'- | 'qoder'- | 'trae';- userId: string;- workspaceId?: string;- }): Promise<HeterogeneousAgentModelCatalog> {- const {- args,- command,- cwd,- deviceId,- env,- timeout = 20_000,- type,- userId,- workspaceId,- } = params;- const client = this.getClient();- const unavailable = (message: string): HeterogeneousAgentModelCatalog => ({- error: { code: 'device_unavailable', message },- status: 'error',- updatedAt: Date.now(),- });- if (!client) return unavailable('Device gateway is not configured');+ runGitPullRequestAction(...args: DeviceRpcArgs<typeof gitWrite.runGitPullRequestAction>) {+ return gitWrite.runGitPullRequestAction(this.clientGetter, ...args);+ }- try {- const result = await client.invokeRpc<HeterogeneousAgentModelCatalog>(- { deviceId, timeout, userId, workspaceId },- {- method: 'listHeterogeneousAgentModels',- params: { args, command, cwd, env, type },- },- );+ getGitWorkingTreePatches(...args: DeviceRpcArgs<typeof gitRead.getGitWorkingTreePatches>) {+ return gitRead.getGitWorkingTreePatches(this.clientGetter, ...args);+ }- if (!result.success || !result.data) {- const message = result.error || 'The device did not return a model catalog';- const unsupported =- message.includes('does not support heterogeneous agent model discovery') ||- message.includes('Unknown device RPC method');- log('listHeterogeneousAgentModels: failed for deviceId=%s β %s', deviceId, message);- return {- error: { code: unsupported ? 'unsupported_client' : 'device_unavailable', message },- status: 'error',- updatedAt: Date.now(),- };- }+ getGitBranchDiff(...args: DeviceRpcArgs<typeof gitRead.getGitBranchDiff>) {+ return gitRead.getGitBranchDiff(this.clientGetter, ...args);+ }- return result.data;- } catch (error) {- log('listHeterogeneousAgentModels: error for deviceId=%s β %O', deviceId, error);- return unavailable(error instanceof Error ? error.message : 'Device model discovery failed');- }+ getGitWorkingTreeFiles(...args: DeviceRpcArgs<typeof gitRead.getGitWorkingTreeFiles>) {+ return gitRead.getGitWorkingTreeFiles(this.clientGetter, ...args);}- /**- * List the local branches of a directory on a remote device via the- * `listGitBranches` device RPC, so the web/remote branch switcher can populate- * the same dropdown the local desktop renders over IPC.- */- async listGitBranches(params: {- deviceId: string;- path: string;- timeout?: number;- userId: string;- workspaceId?: string;- }): Promise<DeviceGitBranchListItem[] | undefined> {- const { userId, deviceId, path, timeout = 15_000, workspaceId } = params;- const client = this.getClient();- if (!client) return undefined;+ getProjectFileIndex(...args: DeviceRpcArgs<typeof projectFiles.getProjectFileIndex>) {+ return projectFiles.getProjectFileIndex(this.clientGetter, ...args);+ }- try {- const result = await client.invokeRpc<DeviceGitBranchListItem[]>(- { deviceId, timeout, userId, workspaceId },- { method: 'listGitBranches', params: { path } },- );+ listProjectDirectory(...args: DeviceRpcArgs<typeof projectFiles.listProjectDirectory>) {+ return projectFiles.listProjectDirectory(this.clientGetter, ...args);+ }- if (!result.success || !result.data) {- log('listGitBranches: failed for deviceId=%s β %s', deviceId, result.error);- return undefined;- }+ browseDirectory(...args: DeviceRpcArgs<typeof projectFiles.browseDirectory>) {+ return projectFiles.browseDirectory(this.clientGetter, ...args);+ }- return result.data;- } catch (error) {- log('listGitBranches: error for deviceId=%s β %O', deviceId, error);- return undefined;- }+ searchProjectFiles(...args: DeviceRpcArgs<typeof projectFiles.searchProjectFiles>) {+ return projectFiles.searchProjectFiles(this.clientGetter, ...args);}- /**- * Checkout (or create) a branch in a directory on a remote device via the- * `checkoutGitBranch` device RPC.- */- async checkoutGitBranch(params: {- branch: string;- create?: boolean;- deviceId: string;- path: string;- timeout?: number;- userId: string;- workspaceId?: string;- }): Promise<DeviceGitCheckoutResult> {- const { userId, deviceId, branch, create, path, timeout = 30_000, workspaceId } = params;- const client = this.getClient();- if (!client) return { error: 'Device gateway not configured', success: false };+ getLocalFilePreview(...args: DeviceRpcArgs<typeof projectFiles.getLocalFilePreview>) {+ return projectFiles.getLocalFilePreview(this.clientGetter, ...args);+ }- try {- const result = await client.invokeRpc<DeviceGitCheckoutResult>(- { deviceId, timeout, userId, workspaceId },- { method: 'checkoutGitBranch', params: { branch, create, path } },- );+ copyAssetForPublish(...args: DeviceRpcArgs<typeof projectFiles.copyAssetForPublish>) {+ return projectFiles.copyAssetForPublish(this.clientGetter, ...args);+ }- if (!result.success || !result.data) {- log('checkoutGitBranch: failed for deviceId=%s β %s', deviceId, result.error);- return { error: result.error || 'Checkout failed', success: false };- }+ readExternalAssetForPublish(+ ...args: DeviceRpcArgs<typeof projectFiles.readExternalAssetForPublish>+ ) {+ return projectFiles.readExternalAssetForPublish(this.clientGetter, ...args);+ }- return result.data;- } catch (error) {- log('checkoutGitBranch: error for deviceId=%s β %O', deviceId, error);- return { error: (error as Error)?.message || 'Checkout failed', success: false };- }+ listProjectSkills(...args: DeviceRpcArgs<typeof projectFiles.listProjectSkills>) {+ return projectFiles.listProjectSkills(this.clientGetter, ...args);}- /**- * Rename a branch in a directory on a remote device via the `renameGitBranch`- * device RPC.- */- async renameGitBranch(params: {- deviceId: string;- from: string;- path: string;- timeout?: number;- to: string;- userId: string;- workspaceId?: string;- }): Promise<DeviceGitRenameBranchResult> {- const { userId, deviceId, from, to, path, timeout = 30_000, workspaceId } = params;- const client = this.getClient();- if (!client) return { error: 'Device gateway not configured', success: false };+ listGitRemoteBranches(...args: DeviceRpcArgs<typeof gitRead.listGitRemoteBranches>) {+ return gitRead.listGitRemoteBranches(this.clientGetter, ...args);+ }- try {- const result = await client.invokeRpc<DeviceGitRenameBranchResult>(- { deviceId, timeout, userId, workspaceId },- { method: 'renameGitBranch', params: { from, path, to } },- );+ revertGitFile(...args: DeviceRpcArgs<typeof gitWrite.revertGitFile>) {+ return gitWrite.revertGitFile(this.clientGetter, ...args);+ }- if (!result.success || !result.data) {- log('renameGitBranch: failed for deviceId=%s β %s', deviceId, result.error);- return { error: result.error || 'Rename failed', success: false };- }+ moveProjectFiles(...args: DeviceRpcArgs<typeof projectFileMutations.moveProjectFiles>) {+ return projectFileMutations.moveProjectFiles(this.clientGetter, ...args);+ }- return result.data;- } catch (error) {- log('renameGitBranch: error for deviceId=%s β %O', deviceId, error);- return { error: (error as Error)?.message || 'Rename failed', success: false };- }+ renameProjectFile(...args: DeviceRpcArgs<typeof projectFileMutations.renameProjectFile>) {+ return projectFileMutations.renameProjectFile(this.clientGetter, ...args);}- /**- * Delete a branch in a directory on a remote device via the `deleteGitBranch`- * device RPC.- */- async deleteGitBranch(params: {- branch: string;- deviceId: string;- path: string;- timeout?: number;- userId: string;- workspaceId?: string;- }): Promise<DeviceGitDeleteBranchResult> {- const { userId, deviceId, branch, path, timeout = 30_000, workspaceId } = params;- const client = this.getClient();- if (!client) return { error: 'Device gateway not configured', success: false };+ writeProjectFile(...args: DeviceRpcArgs<typeof projectFileMutations.writeProjectFile>) {+ return projectFileMutations.writeProjectFile(this.clientGetter, ...args);+ }- try {- const result = await client.invokeRpc<DeviceGitDeleteBranchResult>(- { deviceId, timeout, userId, workspaceId },- { method: 'deleteGitBranch', params: { branch, path } },- );+ createProjectFile(...args: DeviceRpcArgs<typeof projectFileMutations.createProjectFile>) {+ return projectFileMutations.createProjectFile(this.clientGetter, ...args);+ }- if (!result.success || !result.data) {- log('deleteGitBranch: failed for deviceId=%s β %s', deviceId, result.error);- return { error: result.error || 'Delete failed', success: false };- }+ createProjectDirectory(+ ...args: DeviceRpcArgs<typeof projectFileMutations.createProjectDirectory>+ ) {+ return projectFileMutations.createProjectDirectory(this.clientGetter, ...args);+ }- return result.data;- } catch (error) {- log('deleteGitBranch: error for deviceId=%s β %O', deviceId, error);- return { error: (error as Error)?.message || 'Delete failed', success: false };- }+ createDirectory(...args: DeviceRpcArgs<typeof projectFileMutations.createDirectory>) {+ return projectFileMutations.createDirectory(this.clientGetter, ...args);}- /**- * Remove a worktree in a directory's repository on a remote device via- * the `removeGitWorktree` device RPC.- */- async removeGitWorktree(params: {- deviceId: string;- path: string;- timeout?: number;- userId: string;- workspaceId?: string;- worktreePath: string;- }): Promise<DeviceGitRemoveWorktreeResult> {- const { userId, deviceId, path, worktreePath, workspaceId, timeout = 30_000 } = params;- const client = this.getClient();- if (!client) return { error: 'Device gateway not configured', success: false };+ copyProjectFiles(...args: DeviceRpcArgs<typeof projectFileMutations.copyProjectFiles>) {+ return projectFileMutations.copyProjectFiles(this.clientGetter, ...args);+ }- try {- const result = await client.invokeRpc<DeviceGitRemoveWorktreeResult>(- { deviceId, timeout, userId, workspaceId },- { method: 'removeGitWorktree', params: { path, worktreePath } },- );+ trashProjectFiles(...args: DeviceRpcArgs<typeof projectFileMutations.trashProjectFiles>) {+ return projectFileMutations.trashProjectFiles(this.clientGetter, ...args);+ }- if (!result.success || !result.data) {- log('removeGitWorktree: failed for deviceId=%s β %s', deviceId, result.error);- return { error: result.error || 'Remove worktree failed', success: false };- }+ statPath(...args: DeviceRpcArgs<typeof workspace.statPath>) {+ return workspace.statPath(this.clientGetter, ...args);+ }- return result.data;- } catch (error) {- log('removeGitWorktree: error for deviceId=%s β %O', deviceId, error);- return { error: (error as Error)?.message || 'Remove worktree failed', success: false };- }+ dispatchAgentRun(...args: DeviceRpcArgs<typeof agents.dispatchAgentRun>) {+ return agents.dispatchAgentRun(this.clientGetter, ...args);}- /**- * Add a linked worktree on a fresh branch in a directory's repository on a- * remote device via the `addGitWorktree` device RPC.- */- async addGitWorktree(params: {- branch: string;- deviceId: string;- path: string;- timeout?: number;- userId: string;- workspaceId?: string;- worktreePath: string;- }): Promise<DeviceGitAddWorktreeResult> {- const { userId, deviceId, branch, path, worktreePath, workspaceId, timeout = 30_000 } = params;- const client = this.getClient();- if (!client) return { error: 'Device gateway not configured', success: false };+ executeToolCall(...args: DeviceRpcArgs<typeof agents.executeToolCall>) {+ return agents.executeToolCall(this.clientGetter, ...args);+ }- try {- const result = await client.invokeRpc<DeviceGitAddWorktreeResult>(- { deviceId, timeout, userId, workspaceId },- { method: 'addGitWorktree', params: { branch, path, worktreePath } },- );+ executeMcpCall(...args: DeviceRpcArgs<typeof agents.executeMcpCall>) {+ return agents.executeMcpCall(this.clientGetter, ...args);+ }- if (!result.success || !result.data) {- log('addGitWorktree: failed for deviceId=%s β %s', deviceId, result.error);- return { error: result.error || 'Add worktree failed', success: false };- }+ executeMessageApi(...args: DeviceRpcArgs<typeof agents.executeMessageApi>) {+ return agents.executeMessageApi(this.clientGetter, ...args);+ }- return result.data;- } catch (error) {- log('addGitWorktree: error for deviceId=%s β %O', deviceId, error);- return { error: (error as Error)?.message || 'Add worktree failed', success: false };- }+ listListeningPorts(...args: DeviceRpcArgs<typeof workspace.listListeningPorts>) {+ return workspace.listListeningPorts(this.clientGetter, ...args);}- /**- * Pull (`--ff-only`) the current branch of a directory on a remote device via- * the `pullGitBranch` device RPC.- */- async pullGitBranch(params: {- deviceId: string;- path: string;- timeout?: number;- userId: string;- workspaceId?: string;- }): Promise<DeviceGitSyncResult> {- const { userId, deviceId, path, timeout = 65_000, workspaceId } = params;- const client = this.getClient();- if (!client) return { error: 'Device gateway not configured', success: false };+ getAppUpdateState(...args: DeviceRpcArgs<typeof clientUpdate.getAppUpdateState>) {+ return clientUpdate.getAppUpdateState(this.clientGetter, ...args);+ }- try {- const result = await client.invokeRpc<DeviceGitSyncResult>(- { deviceId, timeout, userId, workspaceId },- { method: 'pullGitBranch', params: { path } },- );+ checkAppUpdate(...args: DeviceRpcArgs<typeof clientUpdate.checkAppUpdate>) {+ return clientUpdate.checkAppUpdate(this.clientGetter, ...args);+ }- if (!result.success || !result.data) {- log('pullGitBranch: failed for deviceId=%s β %s', deviceId, result.error);- return { error: result.error || 'Pull failed', success: false };- }+ installAppUpdate(...args: DeviceRpcArgs<typeof clientUpdate.installAppUpdate>) {+ return clientUpdate.installAppUpdate(this.clientGetter, ...args);+ }- return result.data;- } catch (error) {- log('pullGitBranch: error for deviceId=%s β %O', deviceId, error);- return { error: (error as Error)?.message || 'Pull failed', success: false };- }+ createTerminalSession(...args: DeviceRpcArgs<typeof terminal.createTerminalSession>) {+ return terminal.createTerminalSession(this.clientGetter, ...args);}- /**- * Push the current branch of a directory on a remote device via the- * `pushGitBranch` device RPC.- */- async pushGitBranch(params: {- deviceId: string;- path: string;- timeout?: number;- userId: string;- workspaceId?: string;- }): Promise<DeviceGitSyncResult> {- const { userId, deviceId, path, timeout = 65_000, workspaceId } = params;- const client = this.getClient();- if (!client) return { error: 'Device gateway not configured', success: false };+ writeTerminal(...args: DeviceRpcArgs<typeof terminal.writeTerminal>) {+ return terminal.writeTerminal(this.clientGetter, ...args);+ }- try {- const result = await client.invokeRpc<DeviceGitSyncResult>(- { deviceId, timeout, userId, workspaceId },- { method: 'pushGitBranch', params: { path } },- );+ readTerminal(...args: DeviceRpcArgs<typeof terminal.readTerminal>) {+ return terminal.readTerminal(this.clientGetter, ...args);+ }- if (!result.success || !result.data) {- log('pushGitBranch: failed for deviceId=%s β %s', deviceId, result.error);- return { error: result.error || 'Push failed', success: false };- }+ resizeTerminal(...args: DeviceRpcArgs<typeof terminal.resizeTerminal>) {+ return terminal.resizeTerminal(this.clientGetter, ...args);+ }- return result.data;- } catch (error) {- log('pushGitBranch: error for deviceId=%s β %O', deviceId, error);- return { error: (error as Error)?.message || 'Push failed', success: false };- }+ closeTerminal(...args: DeviceRpcArgs<typeof terminal.closeTerminal>) {+ return terminal.closeTerminal(this.clientGetter, ...args);}- /**- * Run a `gh pr` mutation (merge, auto-merge, ready, comment, close, ...) on a- * directory on a remote device via the `runPullRequestAction` device RPC.- * Merge can take a while, so it gets the same 65s budget as push/pull.- */- async runGitPullRequestAction(params: {- action: DeviceGitPullRequestAction;- deviceId: string;- number: number;- path: string;- timeout?: number;- userId: string;- workspaceId?: string;- }): Promise<DeviceGitPullRequestActionResult> {- const { userId, deviceId, path, number, action, timeout = 65_000, workspaceId } = params;- const client = this.getClient();- if (!client) return { error: 'Device gateway not configured', success: false };+ getCliUpdateState(...args: DeviceRpcArgs<typeof clientUpdate.getCliUpdateState>) {+ return clientUpdate.getCliUpdateState(this.clientGetter, ...args);+ }- try {- const result = await client.invokeRpc<DeviceGitPullRequestActionResult>(- { deviceId, timeout, userId, workspaceId },- { method: 'runPullRequestAction', params: { action, number, path } },- );+ checkCliUpdate(...args: DeviceRpcArgs<typeof clientUpdate.checkCliUpdate>) {+ return clientUpdate.checkCliUpdate(this.clientGetter, ...args);+ }- if (!result.success || !result.data) {- log('runGitPullRequestAction: failed for deviceId=%s β %s', deviceId, result.error);- return { error: result.error || 'Pull request action failed', success: false };- }-- return result.data;- } catch (error) {- log('runGitPullRequestAction: error for deviceId=%s β %O', deviceId, error);- return { error: (error as Error)?.message || 'Pull request action failed', success: false };- }- }-- /**- * Working-tree (unstaged) per-file patches for a directory on a remote device- * via the `getGitWorkingTreePatches` device RPC, so the web/remote Review panel- * renders the same diffs the local desktop shows over IPC.- */- async getGitWorkingTreePatches(params: {- deviceId: string;- path: string;- timeout?: number;- userId: string;- workspaceId?: string;- }): Promise<DeviceGitWorkingTreePatches | undefined> {- const { userId, deviceId, path, timeout = 30_000, workspaceId } = params;- const client = this.getClient();- if (!client) return undefined;-- try {- const result = await client.invokeRpc<DeviceGitWorkingTreePatches>(- { deviceId, timeout, userId, workspaceId },- { method: 'getGitWorkingTreePatches', params: { path } },- );-- if (!result.success || !result.data) {- log('getGitWorkingTreePatches: failed for deviceId=%s β %s', deviceId, result.error);- return undefined;- }-- return result.data;- } catch (error) {- log('getGitWorkingTreePatches: error for deviceId=%s β %O', deviceId, error);- return undefined;- }- }-- /**- * Branch diff (current branch vs base ref) per-file patches for a directory on- * a remote device via the `getGitBranchDiff` device RPC.- */- async getGitBranchDiff(params: {- baseRef?: string;- deviceId: string;- path: string;- timeout?: number;- userId: string;- workspaceId?: string;- }): Promise<DeviceGitBranchDiffPatches | undefined> {- const { userId, deviceId, baseRef, path, timeout = 30_000, workspaceId } = params;- const client = this.getClient();- if (!client) return undefined;-- try {- const result = await client.invokeRpc<DeviceGitBranchDiffPatches>(- { deviceId, timeout, userId, workspaceId },- { method: 'getGitBranchDiff', params: { baseRef, path } },- );-- if (!result.success || !result.data) {- log('getGitBranchDiff: failed for deviceId=%s β %s', deviceId, result.error);- return undefined;- }-- return result.data;- } catch (error) {- log('getGitBranchDiff: error for deviceId=%s β %O', deviceId, error);- return undefined;- }- }-- /**- * Repo-relative paths of dirty working-tree files for a directory on a remote- * device via the `getGitWorkingTreeFiles` device RPC β the Files tab's git- * status overlay.- */- async getGitWorkingTreeFiles(params: {- deviceId: string;- path: string;- timeout?: number;- userId: string;- workspaceId?: string;- }): Promise<DeviceGitWorkingTreeFiles | undefined> {- const { userId, deviceId, path, timeout = 15_000, workspaceId } = params;- const client = this.getClient();- if (!client) return undefined;-- try {- const result = await client.invokeRpc<DeviceGitWorkingTreeFiles>(- { deviceId, timeout, userId, workspaceId },- { method: 'getGitWorkingTreeFiles', params: { path } },- );-- if (!result.success || !result.data) {- log('getGitWorkingTreeFiles: failed for deviceId=%s β %s', deviceId, result.error);- return undefined;- }-- return result.data;- } catch (error) {- log('getGitWorkingTreeFiles: error for deviceId=%s β %O', deviceId, error);- return undefined;- }- }-- /**- * Project file index (tree) for a directory on a remote device via the- * `getProjectFileIndex` device RPC β the Files tab's tree.- */- async getProjectFileIndex(params: {- deviceId: string;- scope: string;- timeout?: number;- userId: string;- workspaceId?: string;- }): Promise<DeviceProjectFileIndexResult | undefined> {- const { userId, deviceId, scope, timeout = 30_000, workspaceId } = params;- const client = this.getClient();- if (!client) return undefined;-- try {- const result = await client.invokeRpc<DeviceProjectFileIndexResult>(- { deviceId, timeout, userId, workspaceId },- { method: 'getProjectFileIndex', params: { scope } },- );-- if (!result.success || !result.data) {- log('getProjectFileIndex: failed for deviceId=%s β %s', deviceId, result.error);- return undefined;- }-- return result.data;- } catch (error) {- log('getProjectFileIndex: error for deviceId=%s β %O', deviceId, error);- return undefined;- }- }-- /**- * Children of one directory inside a project on a remote device via the- * `listProjectDirectory` device RPC β expands a row the index collapsed.- */- async listProjectDirectory(params: {- deviceId: string;- relativePath: string;- root: string;- timeout?: number;- userId: string;- workspaceId?: string;- }): Promise<DeviceProjectDirectoryListResult | undefined> {- const { userId, deviceId, relativePath, root, timeout = 30_000, workspaceId } = params;- const client = this.getClient();- if (!client) return undefined;-- try {- const result = await client.invokeRpc<DeviceProjectDirectoryListResult>(- { deviceId, timeout, userId, workspaceId },- { method: 'listProjectDirectory', params: { relativePath, root } },- );-- if (!result.success || !result.data) {- log('listProjectDirectory: failed for deviceId=%s β %s', deviceId, result.error);- return undefined;- }-- return result.data;- } catch (error) {- log('listProjectDirectory: error for deviceId=%s β %O', deviceId, error);- return undefined;- }- }-- /** List one directory level on a remote execution device for folder pickers. */- async browseDirectory(params: {- cursor?: string;- deviceId: string;- limit?: number;- path?: string;- timeout?: number;- userId: string;- workspaceId?: string;- }): Promise<DeviceDirectoryBrowseResult | undefined> {- const {- cursor,- deviceId,- limit,- path: directoryPath,- timeout = 10_000,- userId,- workspaceId,- } = params;- const client = this.getClient();- if (!client) return undefined;-- try {- const result = await client.invokeRpc<DeviceDirectoryBrowseResult>(- { deviceId, timeout, userId, workspaceId },- {- method: 'browseDirectory',- params: { cursor, limit, path: directoryPath },- },- );-- if (!result.success || !result.data) {- log('browseDirectory: failed for deviceId=%s', deviceId);- return undefined;- }-- return result.data;- } catch (error) {- const errorType = error instanceof Error ? error.name : typeof error;- log('browseDirectory: error for deviceId=%s (%s)', deviceId, errorType);- return undefined;- }- }-- /**- * Project file search for a directory on a remote device via the- * `searchProjectFiles` device RPC. The device performs matching and returns a- * compact tree subset with ancestor directories.- */- async searchProjectFiles(params: {- changedOnly?: boolean;- deviceId: string;- excludeIgnored?: boolean;- limit?: number;- query: string;- scope: string;- timeout?: number;- userId: string;- workspaceId?: string;- }): Promise<DeviceProjectFileSearchResult | undefined> {- const {- changedOnly,- userId,- deviceId,- excludeIgnored,- limit,- query,- scope,- timeout = 30_000,- workspaceId,- } = params;- const client = this.getClient();- if (!client) return undefined;-- try {- const result = await client.invokeRpc<DeviceProjectFileSearchResult>(- { deviceId, timeout, userId, workspaceId },- {- method: 'searchProjectFiles',- params: { changedOnly, excludeIgnored, limit, query, scope },- },- );-- if (!result.success || !result.data) {- log('searchProjectFiles: failed for deviceId=%s β %s', deviceId, result.error);- return undefined;- }-- return result.data;- } catch (error) {- log('searchProjectFiles: error for deviceId=%s β %O', deviceId, error);- return undefined;- }- }-- /**- * Read a preview payload for a file on a remote device. This is read-only and- * deliberately mirrors the desktop local-file preview contract without- * exposing a `localfile://` URL to web callers.- */- async getLocalFilePreview(params: {- accept?: 'image';- deviceId: string;- path: string;- timeout?: number;- userId: string;- workingDirectory: string;- workspaceId?: string;- }): Promise<DeviceLocalFilePreviewResult> {- const {- accept,- userId,- deviceId,- path,- workingDirectory,- timeout = 30_000,- workspaceId,- } = params;- const client = this.getClient();- if (!client) return { error: 'Device gateway not configured', success: false };-- try {- const result = await client.invokeRpc<DeviceLocalFilePreviewResult>(- { deviceId, timeout, userId, workspaceId },- {- method: 'getLocalFilePreview',- params: { accept, path, workingDirectory },- },- );-- if (!result.success || !result.data) {- log('getLocalFilePreview: failed for deviceId=%s β %s', deviceId, result.error);- return { error: result.error || 'Failed to load local file preview', success: false };- }-- return result.data;- } catch (error) {- log('getLocalFilePreview: error for deviceId=%s β %O', deviceId, error);- return { error: (error as Error).message, success: false };- }- }-- async copyAssetForPublish(params: {- deviceId: string;- from: string;- timeout?: number;- to: string;- userId: string;- workingDirectory: string;- workspaceId?: string;- }): Promise<DeviceCopyAssetForPublishResult> {- const { userId, deviceId, from, to, workingDirectory, timeout = 30_000, workspaceId } = params;- const client = this.getClient();- if (!client) return { error: 'Device gateway not configured', success: false };-- assertPathsWithinWorkspace(workingDirectory, [to]);-- try {- const result = await client.invokeRpc<DeviceCopyAssetForPublishResult>(- { deviceId, timeout, userId, workspaceId },- { method: 'copyAssetForPublish', params: { from, to, workingDirectory } },- );- if (!result.success || !result.data) {- return { error: result.error || 'Failed to copy publish asset', success: false };- }- return result.data;- } catch (error) {- log('copyAssetForPublish: error for deviceId=%s β %O', deviceId, error);- return { error: (error as Error).message, success: false };- }- }-- async readExternalAssetForPublish(params: {- deviceId: string;- path: string;- timeout?: number;- userId: string;- workingDirectory: string;- workspaceId?: string;- }): Promise<DeviceExternalAssetForPublishResult> {- const { userId, deviceId, path, workingDirectory, timeout = 30_000, workspaceId } = params;- const client = this.getClient();- if (!client) return { error: 'Device gateway not configured', success: false };-- try {- const result = await client.invokeRpc<DeviceExternalAssetForPublishResult>(- { deviceId, timeout, userId, workspaceId },- { method: 'readExternalAssetForPublish', params: { path, workingDirectory } },- );- if (!result.success || !result.data) {- return { error: result.error || 'Failed to read external publish asset', success: false };- }- return result.data;- } catch (error) {- log('readExternalAssetForPublish: error for deviceId=%s β %O', deviceId, error);- return { error: (error as Error).message, success: false };- }- }-- /**- * Project skills (`.agents/skills` / `.claude/skills`) for a directory on a- * remote device via the `listProjectSkills` device RPC β the Resources tab's- * skills group in device mode. Mirrors `getProjectFileIndex`; returns- * `undefined` when the gateway is unconfigured, the device is offline, or the- * call fails so the UI degrades to "no skills".- */- async listProjectSkills(params: {- deviceId: string;- scope: string;- timeout?: number;- userId: string;- workspaceId?: string;- }): Promise<DeviceListProjectSkillsResult | undefined> {- const { userId, deviceId, scope, timeout = 30_000, workspaceId } = params;- const client = this.getClient();- if (!client) return undefined;-- try {- const result = await client.invokeRpc<DeviceListProjectSkillsResult>(- { deviceId, timeout, userId, workspaceId },- { method: 'listProjectSkills', params: { scope } },- );-- if (!result.success || !result.data) {- log('listProjectSkills: failed for deviceId=%s β %s', deviceId, result.error);- return undefined;- }-- return result.data;- } catch (error) {- log('listProjectSkills: error for deviceId=%s β %O', deviceId, error);- return undefined;- }- }-- /**- * List the remote branches (`refs/remotes/origin/*`) of a directory on a- * remote device via the `listGitRemoteBranches` device RPC, so the web/remote- * Review base-ref picker mirrors the local desktop's.- */- async listGitRemoteBranches(params: {- deviceId: string;- path: string;- timeout?: number;- userId: string;- workspaceId?: string;- }): Promise<DeviceGitRemoteBranchListItem[] | undefined> {- const { userId, deviceId, path, timeout = 15_000, workspaceId } = params;- const client = this.getClient();- if (!client) return undefined;-- try {- const result = await client.invokeRpc<DeviceGitRemoteBranchListItem[]>(- { deviceId, timeout, userId, workspaceId },- { method: 'listGitRemoteBranches', params: { path } },- );-- if (!result.success || !result.data) {- log('listGitRemoteBranches: failed for deviceId=%s β %s', deviceId, result.error);- return undefined;- }-- return result.data;- } catch (error) {- log('listGitRemoteBranches: error for deviceId=%s β %O', deviceId, error);- return undefined;- }- }-- /**- * Revert (discard working-tree changes to) a single file in a directory on a- * remote device via the `revertGitFile` device RPC.- */- async revertGitFile(params: {- deviceId: string;- filePath: string;- path: string;- timeout?: number;- userId: string;- workspaceId?: string;- }): Promise<DeviceGitFileRevertResult> {- const { userId, deviceId, filePath, path, timeout = 15_000, workspaceId } = params;- const client = this.getClient();- if (!client) return { error: 'Device gateway not configured', success: false };-- try {- const result = await client.invokeRpc<DeviceGitFileRevertResult>(- { deviceId, timeout, userId, workspaceId },- { method: 'revertGitFile', params: { filePath, path } },- );-- if (!result.success || !result.data) {- log('revertGitFile: failed for deviceId=%s β %s', deviceId, result.error);- return { error: result.error || 'Revert failed', success: false };- }-- return result.data;- } catch (error) {- log('revertGitFile: error for deviceId=%s β %O', deviceId, error);- return { error: (error as Error)?.message || 'Revert failed', success: false };- }- }-- /**- * Move one or more files/folders within a directory on a remote device, via- * the device's `moveLocalFiles` RPC. Powers the Files tree's move in device- * mode. Unlike the read RPCs this is a user-initiated mutation, so a missing- * gateway / offline device / failed call throws rather than degrading to- * `undefined` β the UI surfaces the error instead of silently no-op'ing.- */- async moveProjectFiles(params: {- deviceId: string;- items: DeviceMoveProjectFileItem[];- timeout?: number;- userId: string;- workingDirectory: string;- workspaceId?: string;- }): Promise<DeviceMoveProjectFileResultItem[]> {- const { userId, deviceId, items, workingDirectory, timeout = 30_000, workspaceId } = params;- const client = this.getClient();- if (!client) throw new Error('Device gateway not configured');-- assertPathsWithinWorkspace(- workingDirectory,- items.flatMap((item) => [item.oldPath, item.newPath]),- );- assertNotWorkspaceRoot(- workingDirectory,- items.map((item) => item.oldPath),- );-- const result = await client.invokeRpc<DeviceMoveProjectFileResultItem[]>(- { deviceId, timeout, userId, workspaceId },- { method: 'moveLocalFiles', params: { items, workspaceRoot: workingDirectory } },- );-- if (!result.success || !result.data) {- log('moveProjectFiles: failed for deviceId=%s β %s', deviceId, result.error);- throw new Error(result.error || 'Move failed');- }-- return result.data;- }-- /**- * Rename a single file/folder in a directory on a remote device, via the- * device's `renameLocalFile` RPC. Like `moveProjectFiles`, a transport failure- * throws rather than degrading silently.- */- async renameProjectFile(params: {- deviceId: string;- newName: string;- path: string;- timeout?: number;- userId: string;- workingDirectory: string;- workspaceId?: string;- }): Promise<DeviceRenameProjectFileResult> {- const {- userId,- deviceId,- path,- newName,- workingDirectory,- timeout = 30_000,- workspaceId,- } = params;- const client = this.getClient();- if (!client) throw new Error('Device gateway not configured');-- // The rename stays in the same directory (the device rejects separators in- // `newName`), so containing the source path also contains the target.- assertPathsWithinWorkspace(workingDirectory, [path]);- assertNotWorkspaceRoot(workingDirectory, [path]);-- const result = await client.invokeRpc<DeviceRenameProjectFileResult>(- { deviceId, timeout, userId, workspaceId },- { method: 'renameLocalFile', params: { newName, path, workspaceRoot: workingDirectory } },- );-- if (!result.success || !result.data) {- log('renameProjectFile: failed for deviceId=%s β %s', deviceId, result.error);- throw new Error(result.error || 'Rename failed');- }-- return result.data;- }-- /**- * Save edited content back to a file on a remote device, via the device's- * `writeLocalFile` RPC. Powers remote save in the LocalFile editor. Like the- * other file mutations, a transport failure throws rather than degrading.- */- async writeProjectFile(params: {- content: string;- deviceId: string;- path: string;- timeout?: number;- userId: string;- workingDirectory: string;- workspaceId?: string;- }): Promise<DeviceWriteProjectFileResult> {- const {- userId,- deviceId,- path,- content,- workingDirectory,- timeout = 30_000,- workspaceId,- } = params;- const client = this.getClient();- if (!client) throw new Error('Device gateway not configured');-- assertPathsWithinWorkspace(workingDirectory, [path]);-- const result = await client.invokeRpc<DeviceWriteProjectFileResult>(- { deviceId, timeout, userId, workspaceId },- { method: 'writeLocalFile', params: { content, path, workspaceRoot: workingDirectory } },- );-- if (!result.success || !result.data) {- log('writeProjectFile: failed for deviceId=%s β %s', deviceId, result.error);- throw new Error(result.error || 'Write failed');- }-- return result.data;- }-- /**- * Create a new, empty (or seeded) file on a remote device via the device's- * `createLocalFile` RPC. Never overwrites: an existing entry comes back as- * `{ success: false, error }`. A transport failure throws.- */- async createProjectFile(params: {- content?: string;- deviceId: string;- path: string;- timeout?: number;- userId: string;- workingDirectory: string;- workspaceId?: string;- }): Promise<DeviceCreateProjectEntryResult> {- const {- userId,- deviceId,- path,- content,- workingDirectory,- timeout = 30_000,- workspaceId,- } = params;- const client = this.getClient();- if (!client) throw new Error('Device gateway not configured');-- assertPathsWithinWorkspace(workingDirectory, [path]);-- const result = await client.invokeRpc<DeviceCreateProjectEntryResult>(- { deviceId, timeout, userId, workspaceId },- { method: 'createLocalFile', params: { content, path, workspaceRoot: workingDirectory } },- );-- if (!result.success || !result.data) {- log('createProjectFile: failed for deviceId=%s β %s', deviceId, result.error);- throw new Error(result.error || 'Create file failed');- }-- return result.data;- }-- /**- * Create a new folder on a remote device via the device's- * `createLocalDirectory` RPC. An existing entry fails instead of being reused.- */- async createProjectDirectory(params: {- deviceId: string;- path: string;- timeout?: number;- userId: string;- workingDirectory: string;- workspaceId?: string;- }): Promise<DeviceCreateProjectEntryResult> {- const { userId, deviceId, path, workingDirectory, timeout = 30_000, workspaceId } = params;- const client = this.getClient();- if (!client) throw new Error('Device gateway not configured');-- assertPathsWithinWorkspace(workingDirectory, [path]);-- const result = await client.invokeRpc<DeviceCreateProjectEntryResult>(- { deviceId, timeout, userId, workspaceId },- { method: 'createLocalDirectory', params: { path, workspaceRoot: workingDirectory } },- );-- if (!result.success || !result.data) {- log('createProjectDirectory: failed for deviceId=%s β %s', deviceId, result.error);- throw new Error(result.error || 'Create folder failed');- }-- return result.data;- }-- /**- * Create one folder directly inside `parentPath` for the remote folder picker,- * via the device's `createLocalDirectory` RPC. `parentPath` doubles as the- * device-side workspace root, so the device guard confines the write to a- * single new child of the folder being browsed. A device-reported failure- * (e.g. the name is taken) is returned as `success: false`, not thrown.- */- async createDirectory(params: {- deviceId: string;- name: string;- parentPath: string;- timeout?: number;- userId: string;- workspaceId?: string;- }): Promise<DeviceCreateProjectEntryResult> {- const { deviceId, parentPath, timeout = 30_000, userId, workspaceId } = params;- const name = params.name.trim();- if (!isValidDirectoryName(params.name, parentPath) || !isValidDirectoryName(name, parentPath))- throw new Error(`Invalid folder name: ${params.name}`);- if (!isAbsolute(parentPath)) throw new Error(`Parent path must be absolute: ${parentPath}`);-- const client = this.getClient();- if (!client) throw new Error('Device gateway not configured');-- const path = joinDevicePath(parentPath, name);- assertPathsWithinWorkspace(parentPath, [path]);- assertNotWorkspaceRoot(parentPath, [path]);-- const result = await client.invokeRpc<DeviceCreateProjectEntryResult>(- { deviceId, timeout, userId, workspaceId },- { method: 'createLocalDirectory', params: { path, workspaceRoot: parentPath } },- );-- if (!result.success || !result.data) {- log('createDirectory: failed for deviceId=%s β %s', deviceId, result.error);- throw new Error(result.error || 'Create folder failed');- }-- return result.data;- }-- /**- * Copy (or, without `targetPath`, duplicate in place) files/folders on a- * remote device via the device's `copyLocalFiles` RPC. Both ends of every item- * must stay inside the workspace. A duplicate lands next to its source, so- * containing the source (and refusing the root itself) contains the copy.- */- async copyProjectFiles(params: {- deviceId: string;- items: DeviceCopyProjectFileItem[];- timeout?: number;- userId: string;- workingDirectory: string;- workspaceId?: string;- }): Promise<DeviceCopyProjectFileResultItem[]> {- const { userId, deviceId, items, workingDirectory, timeout = 60_000, workspaceId } = params;- const client = this.getClient();- if (!client) throw new Error('Device gateway not configured');-- assertPathsWithinWorkspace(- workingDirectory,- items.flatMap((item) =>- item.targetPath === undefined ? [item.sourcePath] : [item.sourcePath, item.targetPath],- ),- );- assertNotWorkspaceRoot(- workingDirectory,- items.map((item) => item.sourcePath),- );-- const result = await client.invokeRpc<DeviceCopyProjectFileResultItem[]>(- { deviceId, timeout, userId, workspaceId },- { method: 'copyLocalFiles', params: { items, workspaceRoot: workingDirectory } },- );-- if (!result.success || !result.data) {- log('copyProjectFiles: failed for deviceId=%s β %s', deviceId, result.error);- throw new Error(result.error || 'Copy failed');- }-- return result.data;- }-- /**- * Move files/folders to the remote device's trash via its `trashLocalFiles`- * RPC. A device without a recoverable trash (the CLI daemon) rejects the RPC,- * which surfaces here as a thrown error β never as a permanent delete.- */- async trashProjectFiles(params: {- deviceId: string;- paths: string[];- timeout?: number;- userId: string;- workingDirectory: string;- workspaceId?: string;- }): Promise<DeviceTrashProjectFilesResult> {- const { userId, deviceId, paths, workingDirectory, timeout = 30_000, workspaceId } = params;- const client = this.getClient();- if (!client) throw new Error('Device gateway not configured');-- assertPathsWithinWorkspace(workingDirectory, paths);- assertNotWorkspaceRoot(workingDirectory, paths);-- const result = await client.invokeRpc<DeviceTrashProjectFilesResult>(- { deviceId, timeout, userId, workspaceId },- { method: 'trashLocalFiles', params: { paths, workspaceRoot: workingDirectory } },- );-- if (!result.success || !result.data) {- log('trashProjectFiles: failed for deviceId=%s β %s', deviceId, result.error);- throw new Error(result.error || 'Move to trash failed');- }-- return result.data;- }-- /**- * Check whether a path exists on the device and is a directory, via the same- * generic `invokeRpc` channel as `gitInfo`. Lets a web / remote client- * validate a manually-entered working directory before binding it. Returns- * `undefined` when the gateway is unconfigured or the device is unreachable- * (the caller treats "can't verify" as non-blocking).- */- async statPath(params: {- deviceId: string;- path: string;- timeout?: number;- userId: string;- workspaceId?: string;- }): Promise<- | { exists: boolean; isDirectory: boolean; repositoryUrl?: string; repoType?: 'git' | 'github' }- | undefined- > {- const { userId, deviceId, path, timeout = 8000, workspaceId } = params;- const client = this.getClient();- if (!client) return undefined;-- try {- const result = await client.invokeRpc<{- exists: boolean;- isDirectory: boolean;- repoType?: 'git' | 'github';- }>({ deviceId, timeout, userId, workspaceId }, { method: 'statPath', params: { path } });-- if (!result.success || !result.data) {- log('statPath: failed for deviceId=%s β %s', deviceId, result.error);- return undefined;- }-- return result.data;- } catch (error) {- log('statPath: error for deviceId=%s β %O', deviceId, error);- return undefined;- }- }-- async dispatchAgentRun(params: {- agentId?: string;- agentType: HeterogeneousAgentType;- assistantMessageId: string;- /** Resolved `lh hetero exec` wrapper args. */- args?: string[];- /** Restricts the run to connections of these clients; omitted means any client. */- clientKinds?: DeviceClient[];- cwd?: string;- deviceId?: string;- /** Image attachments forwarded to the device as fetchable (signed) URLs. */- imageList?: Array<{ id?: string; url: string }>;- jwt: string;- operationId: string;- prompt: string;- resumeFallbackSystemContext?: string;- resumeSessionId?: string;- systemContext?: string;- topicId: string;- userId: string;- workspaceId?: string;- /** Topic/run workspace forwarded to the device for hetero ingest. */- ingestWorkspaceId?: string;- }): Promise<{ error?: string; errorData?: DeviceUnavailableErrorData; success: boolean }> {- const client = this.getClient();- if (!client) return { error: 'GATEWAY_NOT_CONFIGURED', success: false };-- try {- return await client.dispatchAgentRun(params);- } catch (error) {- const message = error instanceof Error ? error.message : String(error);- log('dispatchAgentRun: error β %s', message);- return { error: message, success: false };- }- }-- async executeToolCall(- params: {- clientKinds?: DeviceClient[];- deviceId: string;- operationId?: string;- userId: string;- workspaceId?: string;- },- toolCall: { apiName: string; arguments: string; identifier: string },- timeout = 30_000,- ): Promise<DeviceToolCallResult> {- const client = this.getClient();- if (!client) {- return {- content: 'Device Gateway is not configured',- error: 'GATEWAY_NOT_CONFIGURED',- success: false,- };- }-- log(- 'executeToolCall: operationId=%s, userId=%s, deviceId=%s, tool=%s/%s',- params.operationId ?? 'N/A',- params.userId,- params.deviceId,- toolCall.identifier,- toolCall.apiName,- );-- try {- return await client.executeToolCall({ ...params, timeout }, toolCall);- } catch (error) {- const message = error instanceof Error ? error.message : String(error);- log('executeToolCall: error β %s', message);- // Backstop for anything the http client did not already describe. A raw- // `TimeoutError` / driver message here reads to the model as if the tool- // itself blew up; name the failing hop and its recovery instead.- const failure = describeGatewayRequestFailure(error, 'tool call');- return { content: failure.content, error: failure.error, success: false };- }- }-- /**- * Tunnel an MCP tool call to a connected device, for MCP servers only the- * device can reach: stdio (the cloud can't spawn the user's local binary)- * and localhost / LAN HTTP endpoints (the cloud's fetch can't reach them).- * The connection params are forwarded so the device runs the call locally.- */- async executeMcpCall(- mcpCall: {- apiName: string;- arguments: string;- deviceId: string;- identifier: string;- params: GatewayMcpParams;- userId: string;- workspaceId?: string;- },- timeout = 30_000,- ): Promise<DeviceToolCallResult> {- const client = this.getClient();- if (!client) {- return {- content: 'Device Gateway is not configured',- error: 'GATEWAY_NOT_CONFIGURED',- success: false,- };- }-- log(- 'executeMcpCall: userId=%s, deviceId=%s, mcp=%s/%s',- mcpCall.userId,- mcpCall.deviceId,- mcpCall.identifier,- mcpCall.apiName,- );-- try {- return await client.executeMcpCall({ ...mcpCall, timeout });- } catch (error) {- const message = error instanceof Error ? error.message : String(error);- log('executeMcpCall: error β %s', message);- const failure = describeGatewayRequestFailure(error, 'tool call');- return { content: failure.content, error: failure.error, success: false };- }- }-- async executeMessageApi(- params: { deviceId: string; userId: string; workspaceId?: string },- api: { apiName: string; payload: Record<string, unknown>; platform: string },- timeout = 30_000,- ): Promise<DeviceMessageApiResult> {- const client = this.getClient();- if (!client) {- return {- content: 'Device Gateway is not configured',- error: 'GATEWAY_NOT_CONFIGURED',- success: false,- };- }-- log(- 'executeMessageApi: userId=%s, deviceId=%s, api=%s/%s',- params.userId,- params.deviceId,- api.platform,- api.apiName,- );-- try {- return await client.executeMessageApi(- {- deviceId: params.deviceId,- timeout,- userId: params.userId,- workspaceId: params.workspaceId,- },- api,- );- } catch (error) {- const message = error instanceof Error ? error.message : String(error);- log('executeMessageApi: error β %s', message);- return { content: `Device message API error: ${message}`, error: message, success: false };- }- }-- /**- * TCP ports the device is listening on that a tunnel can reach, with the- * project's own ports marked. Resolves undefined when the device is- * offline or predates the RPC β the UI then says it can't read the ports.- */- async listListeningPorts(params: {- cwd?: string;- deviceId: string;- timeout?: number;- userId: string;- workspaceId?: string;- }): Promise<DeviceListeningPortsResult | undefined> {- const { cwd, deviceId, timeout = 10_000, userId, workspaceId } = params;- const client = this.getClient();- if (!client) return undefined;-- try {- const result = await client.invokeRpc<DeviceListeningPortsResult>(- { deviceId, timeout, userId, workspaceId },- { method: 'listListeningPorts', params: { cwd } },- );- if (!result.success || !result.data) {- log('listListeningPorts: failed for deviceId=%s', deviceId);- return undefined;- }- return result.data;- } catch (error) {- log(- 'listListeningPorts: error for deviceId=%s (%s)',- deviceId,- error instanceof Error ? error.name : typeof error,- );- return undefined;- }- }-- /** Where the device's desktop app update stands; never checks on its own. */- async getAppUpdateState(params: AppUpdateRpcParams): Promise<DeviceAppUpdateStateResult> {- const result = await this.invokeAppUpdate<DeviceAppUpdateState>('getAppUpdateState', params);- return result.status === 'ok' ? { state: result.data, status: 'ok' } : result;- }-- /** Start an update check on the device; a found update downloads on its own. */- async checkAppUpdate(params: AppUpdateRpcParams): Promise<DeviceAppUpdateStateResult> {- const result = await this.invokeAppUpdate<DeviceAppUpdateState>('checkAppUpdate', params);- return result.status === 'ok' ? { state: result.data, status: 'ok' } : result;- }-- /** Restart the device's desktop app into its downloaded update. */- async installAppUpdate(params: AppUpdateRpcParams): Promise<DeviceAppUpdateInstallResult> {- const result = await this.invokeAppUpdate<{ targetVersion: string }>(- 'installAppUpdate',- params,- );- return result.status === 'ok'- ? { status: 'ok', targetVersion: result.data.targetVersion }- : result;- }-- // βββ Interactive terminal (PTY) βββ- //- // A terminal is a session the caller drives, not a one-shot read, so these- // deliberately THROW on failure instead of returning `undefined` the way the- // best-effort readers above do: the panel has to say why a shell did not open- // (device offline, a client without PTY support) rather than wait forever on- // one that will never exist.-- async createTerminalSession(- params: TerminalRpcScope & { cols: number; cwd?: string; rows: number },- ): Promise<DeviceCreateTerminalSessionResult> {- return this.invokeTerminalRpc('createTerminalSession', params, {- cols: params.cols,- cwd: params.cwd,- rows: params.rows,- });- }-- async writeTerminal(params: TerminalRpcScope & { data: string; id: string }): Promise<void> {- await this.invokeTerminalRpc('writeTerminal', params, { data: params.data, id: params.id });- }-- async readTerminal(- params: TerminalRpcScope & { cursor: number; id: string },- ): Promise<DeviceReadTerminalResult> {- return this.invokeTerminalRpc('readTerminal', params, {- cursor: params.cursor,- id: params.id,- });- }-- async resizeTerminal(- params: TerminalRpcScope & { cols: number; id: string; rows: number },- ): Promise<void> {- await this.invokeTerminalRpc('resizeTerminal', params, {- cols: params.cols,- id: params.id,- rows: params.rows,- });- }-- async closeTerminal(- params: TerminalRpcScope & { id: string },- ): Promise<DeviceCloseTerminalResult> {- return this.invokeTerminalRpc('closeTerminal', params, { id: params.id });- }-- /**- * Relay one terminal RPC and unwrap its result.- *- * Every call carries the `cli` channel hint: the PTY lives in the `lh- * connect` process, so on a machine also running the desktop app the RPC has- * to reach that connection β the desktop's own terminal is local-only and- * would refuse these. A gateway that predates the hint ignores it, which is- * why the refusal below still has to surface as an error.- */- private async invokeTerminalRpc<T>(- method: TerminalRpcMethod,- params: TerminalRpcScope,- rpcParams: Record<string, unknown>,- ): Promise<T> {- const { deviceId, timeout = 15_000, userId, workspaceId } = params;- const client = this.getClient();- if (!client) throw new Error('Device gateway is not configured on this deployment.');-- const result = await client.invokeRpc<T>(- { channel: 'cli', deviceId, timeout, userId, workspaceId },- { method, params: rpcParams },- );- // `writeTerminal` / `resizeTerminal` answer with no payload, so absence of- // `data` is not a failure β only an explicit `success: false` is.- if (!result.success) throw new Error(result.error || `${method} failed`);- return result.data as T;- }-- /**- * Shared relay for the remote app-update RPCs. Only the desktop app can- * update itself, so the call asks for the `desktop` channel; an older gateway- * may still hand it to `lh connect` on the same machine, whose rejection is- * reported as `unsupported` like an outdated desktop's.- */- private async invokeAppUpdate<T>(- method: 'checkAppUpdate' | 'getAppUpdateState' | 'installAppUpdate',- params: AppUpdateRpcParams,- ): Promise<{ data: T; status: 'ok' } | { message: string; status: DeviceAppUpdateFailure }> {- 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<T>(- { channel: 'desktop', deviceId, timeout, userId, workspaceId },- { method },- );- if (result.success && result.data !== undefined) return { data: result.data, status: 'ok' };-- const message = result.error || `${method} failed`;- log('%s: failed for deviceId=%s β %s', method, deviceId, message);- const unsupported =- message.includes('does not support remote updates') ||- message.includes('Unknown device RPC method');- return { message, status: unsupported ? 'unsupported' : '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' };- }- }-- 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' };- }+ restartCli(...args: DeviceRpcArgs<typeof clientUpdate.restartCli>) {+ return clientUpdate.restartCli(this.clientGetter, ...args);}private getClient(): GatewayHttpClient | null {diff --git a/apps/server/src/services/deviceGateway/paths.ts b/apps/server/src/services/deviceGateway/paths.tsnew file mode 100644index 00000000000..10eddcd7865--- /dev/null+++ b/apps/server/src/services/deviceGateway/paths.ts@@ -0,0 +1,72 @@+/**+ * Path containment for device file operations. Device paths may be POSIX or+ * Windows while this runs on the (POSIX) server.+ */+import { isAbsolute, relative, resolve } from 'pathe';++/**+ * Is `target` the same as, or nested inside, `root`?+ *+ * The device's working directory may be a POSIX path (`/Users/β¦`) or a Windows+ * path (`C:\β¦` / `\\server\share`) while this check runs on the cloud server+ * (POSIX). `pathe` auto-detects the path flavour per argument, so Windows+ * device paths are resolved with Windows semantics without us branching on+ * `path.win32` / `path.posix`.+ */+export const isPathWithinRoot = (root: string, target: string): boolean => {+ if (!isAbsolute(root) || !isAbsolute(target)) return false;+ const rel = relative(resolve(root), resolve(target));+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));+};++/**+ * Guard the web/remote file mutations (move / rename / write) against escaping+ * the project root. These routes accept absolute paths straight from an+ * untrusted browser session, so before forwarding them to a device we confirm+ * every path stays inside the workspace the UI is operating in β otherwise a+ * caller could bypass the Files tree and mutate arbitrary locations on the+ * device. Mirrors the read path's `workspaceRoot` containment check.+ */+export const assertPathsWithinWorkspace = (+ workspaceRoot: string,+ candidates: Array<string | undefined>,+): void => {+ if (!workspaceRoot) throw new Error('A workspace root is required for file mutations');++ for (const candidate of candidates) {+ if (!candidate || !isPathWithinRoot(workspaceRoot, candidate)) {+ throw new Error(`Path is outside the approved workspace: ${candidate ?? '(empty)'}`);+ }+ }+};++/**+ * Append one segment to a device path, keeping the device's own separator. The+ * folder picker browses Windows devices too (`C:\Users`), and `pathe.join`+ * would rewrite those to forward slashes.+ */+export const joinDevicePath = (parentPath: string, name: string): string => {+ const separator = /^[A-Z]:\\/i.test(parentPath) || parentPath.startsWith('\\\\') ? '\\' : '/';+ return `${parentPath.replace(/[\\/]+$/, '')}${separator}${name}`;+};++/**+ * Refuse to trash / rename / move / duplicate the workspace root itself. It+ * passes the containment check (a root is "within" itself), but removing or+ * renaming it pulls the whole Files tree out from under the UI, and a duplicate+ * of the root would land in its parent β outside the workspace.+ */+export const assertNotWorkspaceRoot = (+ workspaceRoot: string,+ candidates: Array<string | undefined>,+): void => {+ for (const candidate of candidates) {+ if (+ candidate &&+ isAbsolute(candidate) &&+ relative(resolve(workspaceRoot), resolve(candidate)) === ''+ ) {+ throw new Error(`This operation is not allowed on the workspace root: ${candidate}`);+ }+ }+};diff --git a/apps/server/src/services/deviceGateway/projectFileMutations.ts b/apps/server/src/services/deviceGateway/projectFileMutations.tsnew file mode 100644index 00000000000..d72d431ef92--- /dev/null+++ b/apps/server/src/services/deviceGateway/projectFileMutations.ts@@ -0,0 +1,360 @@+/**+ * Files-tab mutations on a remote device. Every path is confined to the+ * workspace, and a failure throws.+ */+import type {+ DeviceCopyProjectFileItem,+ DeviceCopyProjectFileResultItem,+ DeviceCreateProjectEntryResult,+ DeviceMoveProjectFileItem,+ DeviceMoveProjectFileResultItem,+ DeviceRenameProjectFileResult,+ DeviceTrashProjectFilesResult,+ DeviceWriteProjectFileResult,+} from '@lobechat/types';+import { isValidDirectoryName } from '@lobechat/utils/directoryName';+import debug from 'debug';+import { isAbsolute } from 'pathe';++import { assertNotWorkspaceRoot, assertPathsWithinWorkspace, joinDevicePath } from './paths';+import type { DeviceClientGetter } from './types';++const log = debug('lobe-server:device-gateway');++/**+ * Move one or more files/folders within a directory on a remote device, via+ * the device's `moveLocalFiles` RPC. Powers the Files tree's move in device+ * mode. Unlike the read RPCs this is a user-initiated mutation, so a missing+ * gateway / offline device / failed call throws rather than degrading to+ * `undefined` β the UI surfaces the error instead of silently no-op'ing.+ */+export async function moveProjectFiles(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ items: DeviceMoveProjectFileItem[];+ timeout?: number;+ userId: string;+ workingDirectory: string;+ workspaceId?: string;+ },+): Promise<DeviceMoveProjectFileResultItem[]> {+ const { userId, deviceId, items, workingDirectory, timeout = 30_000, workspaceId } = params;+ const client = getClient();+ if (!client) throw new Error('Device gateway not configured');++ assertPathsWithinWorkspace(+ workingDirectory,+ items.flatMap((item) => [item.oldPath, item.newPath]),+ );+ assertNotWorkspaceRoot(+ workingDirectory,+ items.map((item) => item.oldPath),+ );++ const result = await client.invokeRpc<DeviceMoveProjectFileResultItem[]>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'moveLocalFiles', params: { items, workspaceRoot: workingDirectory } },+ );++ if (!result.success || !result.data) {+ log('moveProjectFiles: failed for deviceId=%s β %s', deviceId, result.error);+ throw new Error(result.error || 'Move failed');+ }++ return result.data;+}++/**+ * Rename a single file/folder in a directory on a remote device, via the+ * device's `renameLocalFile` RPC. Like `moveProjectFiles`, a transport failure+ * throws rather than degrading silently.+ */+export async function renameProjectFile(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ newName: string;+ path: string;+ timeout?: number;+ userId: string;+ workingDirectory: string;+ workspaceId?: string;+ },+): Promise<DeviceRenameProjectFileResult> {+ const {+ userId,+ deviceId,+ path,+ newName,+ workingDirectory,+ timeout = 30_000,+ workspaceId,+ } = params;+ const client = getClient();+ if (!client) throw new Error('Device gateway not configured');++ // The rename stays in the same directory (the device rejects separators in+ // `newName`), so containing the source path also contains the target.+ assertPathsWithinWorkspace(workingDirectory, [path]);+ assertNotWorkspaceRoot(workingDirectory, [path]);++ const result = await client.invokeRpc<DeviceRenameProjectFileResult>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'renameLocalFile', params: { newName, path, workspaceRoot: workingDirectory } },+ );++ if (!result.success || !result.data) {+ log('renameProjectFile: failed for deviceId=%s β %s', deviceId, result.error);+ throw new Error(result.error || 'Rename failed');+ }++ return result.data;+}++/**+ * Save edited content back to a file on a remote device, via the device's+ * `writeLocalFile` RPC. Powers remote save in the LocalFile editor. Like the+ * other file mutations, a transport failure throws rather than degrading.+ */+export async function writeProjectFile(+ getClient: DeviceClientGetter,+ params: {+ content: string;+ deviceId: string;+ path: string;+ timeout?: number;+ userId: string;+ workingDirectory: string;+ workspaceId?: string;+ },+): Promise<DeviceWriteProjectFileResult> {+ const {+ userId,+ deviceId,+ path,+ content,+ workingDirectory,+ timeout = 30_000,+ workspaceId,+ } = params;+ const client = getClient();+ if (!client) throw new Error('Device gateway not configured');++ assertPathsWithinWorkspace(workingDirectory, [path]);++ const result = await client.invokeRpc<DeviceWriteProjectFileResult>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'writeLocalFile', params: { content, path, workspaceRoot: workingDirectory } },+ );++ if (!result.success || !result.data) {+ log('writeProjectFile: failed for deviceId=%s β %s', deviceId, result.error);+ throw new Error(result.error || 'Write failed');+ }++ return result.data;+}++/**+ * Create a new, empty (or seeded) file on a remote device via the device's+ * `createLocalFile` RPC. Never overwrites: an existing entry comes back as+ * `{ success: false, error }`. A transport failure throws.+ */+export async function createProjectFile(+ getClient: DeviceClientGetter,+ params: {+ content?: string;+ deviceId: string;+ path: string;+ timeout?: number;+ userId: string;+ workingDirectory: string;+ workspaceId?: string;+ },+): Promise<DeviceCreateProjectEntryResult> {+ const {+ userId,+ deviceId,+ path,+ content,+ workingDirectory,+ timeout = 30_000,+ workspaceId,+ } = params;+ const client = getClient();+ if (!client) throw new Error('Device gateway not configured');++ assertPathsWithinWorkspace(workingDirectory, [path]);++ const result = await client.invokeRpc<DeviceCreateProjectEntryResult>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'createLocalFile', params: { content, path, workspaceRoot: workingDirectory } },+ );++ if (!result.success || !result.data) {+ log('createProjectFile: failed for deviceId=%s β %s', deviceId, result.error);+ throw new Error(result.error || 'Create file failed');+ }++ return result.data;+}++/**+ * Create a new folder on a remote device via the device's+ * `createLocalDirectory` RPC. An existing entry fails instead of being reused.+ */+export async function createProjectDirectory(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ path: string;+ timeout?: number;+ userId: string;+ workingDirectory: string;+ workspaceId?: string;+ },+): Promise<DeviceCreateProjectEntryResult> {+ const { userId, deviceId, path, workingDirectory, timeout = 30_000, workspaceId } = params;+ const client = getClient();+ if (!client) throw new Error('Device gateway not configured');++ assertPathsWithinWorkspace(workingDirectory, [path]);++ const result = await client.invokeRpc<DeviceCreateProjectEntryResult>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'createLocalDirectory', params: { path, workspaceRoot: workingDirectory } },+ );++ if (!result.success || !result.data) {+ log('createProjectDirectory: failed for deviceId=%s β %s', deviceId, result.error);+ throw new Error(result.error || 'Create folder failed');+ }++ return result.data;+}++/**+ * Create one folder directly inside `parentPath` for the remote folder picker,+ * via the device's `createLocalDirectory` RPC. `parentPath` doubles as the+ * device-side workspace root, so the device guard confines the write to a+ * single new child of the folder being browsed. A device-reported failure+ * (e.g. the name is taken) is returned as `success: false`, not thrown.+ */+export async function createDirectory(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ name: string;+ parentPath: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+ },+): Promise<DeviceCreateProjectEntryResult> {+ const { deviceId, parentPath, timeout = 30_000, userId, workspaceId } = params;+ const name = params.name.trim();+ if (!isValidDirectoryName(params.name, parentPath) || !isValidDirectoryName(name, parentPath))+ throw new Error(`Invalid folder name: ${params.name}`);+ if (!isAbsolute(parentPath)) throw new Error(`Parent path must be absolute: ${parentPath}`);++ const client = getClient();+ if (!client) throw new Error('Device gateway not configured');++ const path = joinDevicePath(parentPath, name);+ assertPathsWithinWorkspace(parentPath, [path]);+ assertNotWorkspaceRoot(parentPath, [path]);++ const result = await client.invokeRpc<DeviceCreateProjectEntryResult>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'createLocalDirectory', params: { path, workspaceRoot: parentPath } },+ );++ if (!result.success || !result.data) {+ log('createDirectory: failed for deviceId=%s β %s', deviceId, result.error);+ throw new Error(result.error || 'Create folder failed');+ }++ return result.data;+}++/**+ * Copy (or, without `targetPath`, duplicate in place) files/folders on a+ * remote device via the device's `copyLocalFiles` RPC. Both ends of every item+ * must stay inside the workspace. A duplicate lands next to its source, so+ * containing the source (and refusing the root itself) contains the copy.+ */+export async function copyProjectFiles(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ items: DeviceCopyProjectFileItem[];+ timeout?: number;+ userId: string;+ workingDirectory: string;+ workspaceId?: string;+ },+): Promise<DeviceCopyProjectFileResultItem[]> {+ const { userId, deviceId, items, workingDirectory, timeout = 60_000, workspaceId } = params;+ const client = getClient();+ if (!client) throw new Error('Device gateway not configured');++ assertPathsWithinWorkspace(+ workingDirectory,+ items.flatMap((item) =>+ item.targetPath === undefined ? [item.sourcePath] : [item.sourcePath, item.targetPath],+ ),+ );+ assertNotWorkspaceRoot(+ workingDirectory,+ items.map((item) => item.sourcePath),+ );++ const result = await client.invokeRpc<DeviceCopyProjectFileResultItem[]>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'copyLocalFiles', params: { items, workspaceRoot: workingDirectory } },+ );++ if (!result.success || !result.data) {+ log('copyProjectFiles: failed for deviceId=%s β %s', deviceId, result.error);+ throw new Error(result.error || 'Copy failed');+ }++ return result.data;+}++/**+ * Move files/folders to the remote device's trash via its `trashLocalFiles`+ * RPC. A device without a recoverable trash (the CLI daemon) rejects the RPC,+ * which surfaces here as a thrown error β never as a permanent delete.+ */+export async function trashProjectFiles(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ paths: string[];+ timeout?: number;+ userId: string;+ workingDirectory: string;+ workspaceId?: string;+ },+): Promise<DeviceTrashProjectFilesResult> {+ const { userId, deviceId, paths, workingDirectory, timeout = 30_000, workspaceId } = params;+ const client = getClient();+ if (!client) throw new Error('Device gateway not configured');++ assertPathsWithinWorkspace(workingDirectory, paths);+ assertNotWorkspaceRoot(workingDirectory, paths);++ const result = await client.invokeRpc<DeviceTrashProjectFilesResult>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'trashLocalFiles', params: { paths, workspaceRoot: workingDirectory } },+ );++ if (!result.success || !result.data) {+ log('trashProjectFiles: failed for deviceId=%s β %s', deviceId, result.error);+ throw new Error(result.error || 'Move to trash failed');+ }++ return result.data;+}diff --git a/apps/server/src/services/deviceGateway/projectFiles.ts b/apps/server/src/services/deviceGateway/projectFiles.tsnew file mode 100644index 00000000000..6df0a3118e0--- /dev/null+++ b/apps/server/src/services/deviceGateway/projectFiles.ts@@ -0,0 +1,346 @@+/**+ * Files-tab reads on a remote device (index, directory, search, preview,+ * skills) and publish-asset copies.+ */+import type {+ DeviceCopyAssetForPublishResult,+ DeviceDirectoryBrowseResult,+ DeviceExternalAssetForPublishResult,+ DeviceListProjectSkillsResult,+ DeviceLocalFilePreviewResult,+ DeviceProjectDirectoryListResult,+ DeviceProjectFileIndexResult,+ DeviceProjectFileSearchResult,+} from '@lobechat/types';+import debug from 'debug';++import { assertPathsWithinWorkspace } from './paths';+import type { DeviceClientGetter } from './types';++const log = debug('lobe-server:device-gateway');++/**+ * Project file index (tree) for a directory on a remote device via the+ * `getProjectFileIndex` device RPC β the Files tab's tree.+ */+export async function getProjectFileIndex(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ scope: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+ },+): Promise<DeviceProjectFileIndexResult | undefined> {+ const { userId, deviceId, scope, timeout = 30_000, workspaceId } = params;+ const client = getClient();+ if (!client) return undefined;++ try {+ const result = await client.invokeRpc<DeviceProjectFileIndexResult>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'getProjectFileIndex', params: { scope } },+ );++ if (!result.success || !result.data) {+ log('getProjectFileIndex: failed for deviceId=%s β %s', deviceId, result.error);+ return undefined;+ }++ return result.data;+ } catch (error) {+ log('getProjectFileIndex: error for deviceId=%s β %O', deviceId, error);+ return undefined;+ }+}++/**+ * Children of one directory inside a project on a remote device via the+ * `listProjectDirectory` device RPC β expands a row the index collapsed.+ */+export async function listProjectDirectory(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ relativePath: string;+ root: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+ },+): Promise<DeviceProjectDirectoryListResult | undefined> {+ const { userId, deviceId, relativePath, root, timeout = 30_000, workspaceId } = params;+ const client = getClient();+ if (!client) return undefined;++ try {+ const result = await client.invokeRpc<DeviceProjectDirectoryListResult>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'listProjectDirectory', params: { relativePath, root } },+ );++ if (!result.success || !result.data) {+ log('listProjectDirectory: failed for deviceId=%s β %s', deviceId, result.error);+ return undefined;+ }++ return result.data;+ } catch (error) {+ log('listProjectDirectory: error for deviceId=%s β %O', deviceId, error);+ return undefined;+ }+}++/** List one directory level on a remote execution device for folder pickers. */+export async function browseDirectory(+ getClient: DeviceClientGetter,+ params: {+ cursor?: string;+ deviceId: string;+ limit?: number;+ path?: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+ },+): Promise<DeviceDirectoryBrowseResult | undefined> {+ const {+ cursor,+ deviceId,+ limit,+ path: directoryPath,+ timeout = 10_000,+ userId,+ workspaceId,+ } = params;+ const client = getClient();+ if (!client) return undefined;++ try {+ const result = await client.invokeRpc<DeviceDirectoryBrowseResult>(+ { deviceId, timeout, userId, workspaceId },+ {+ method: 'browseDirectory',+ params: { cursor, limit, path: directoryPath },+ },+ );++ if (!result.success || !result.data) {+ log('browseDirectory: failed for deviceId=%s', deviceId);+ return undefined;+ }++ return result.data;+ } catch (error) {+ const errorType = error instanceof Error ? error.name : typeof error;+ log('browseDirectory: error for deviceId=%s (%s)', deviceId, errorType);+ return undefined;+ }+}++/**+ * Project file search for a directory on a remote device via the+ * `searchProjectFiles` device RPC. The device performs matching and returns a+ * compact tree subset with ancestor directories.+ */+export async function searchProjectFiles(+ getClient: DeviceClientGetter,+ params: {+ changedOnly?: boolean;+ deviceId: string;+ excludeIgnored?: boolean;+ limit?: number;+ query: string;+ scope: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+ },+): Promise<DeviceProjectFileSearchResult | undefined> {+ const {+ changedOnly,+ userId,+ deviceId,+ excludeIgnored,+ limit,+ query,+ scope,+ timeout = 30_000,+ workspaceId,+ } = params;+ const client = getClient();+ if (!client) return undefined;++ try {+ const result = await client.invokeRpc<DeviceProjectFileSearchResult>(+ { deviceId, timeout, userId, workspaceId },+ {+ method: 'searchProjectFiles',+ params: { changedOnly, excludeIgnored, limit, query, scope },+ },+ );++ if (!result.success || !result.data) {+ log('searchProjectFiles: failed for deviceId=%s β %s', deviceId, result.error);+ return undefined;+ }++ return result.data;+ } catch (error) {+ log('searchProjectFiles: error for deviceId=%s β %O', deviceId, error);+ return undefined;+ }+}++/**+ * Read a preview payload for a file on a remote device. This is read-only and+ * deliberately mirrors the desktop local-file preview contract without+ * exposing a `localfile://` URL to web callers.+ */+export async function getLocalFilePreview(+ getClient: DeviceClientGetter,+ params: {+ accept?: 'image';+ deviceId: string;+ path: string;+ timeout?: number;+ userId: string;+ workingDirectory: string;+ workspaceId?: string;+ },+): Promise<DeviceLocalFilePreviewResult> {+ const {+ accept,+ userId,+ deviceId,+ path,+ workingDirectory,+ timeout = 30_000,+ workspaceId,+ } = params;+ const client = getClient();+ if (!client) return { error: 'Device gateway not configured', success: false };++ try {+ const result = await client.invokeRpc<DeviceLocalFilePreviewResult>(+ { deviceId, timeout, userId, workspaceId },+ {+ method: 'getLocalFilePreview',+ params: { accept, path, workingDirectory },+ },+ );++ if (!result.success || !result.data) {+ log('getLocalFilePreview: failed for deviceId=%s β %s', deviceId, result.error);+ return { error: result.error || 'Failed to load local file preview', success: false };+ }++ return result.data;+ } catch (error) {+ log('getLocalFilePreview: error for deviceId=%s β %O', deviceId, error);+ return { error: (error as Error).message, success: false };+ }+}++export async function copyAssetForPublish(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ from: string;+ timeout?: number;+ to: string;+ userId: string;+ workingDirectory: string;+ workspaceId?: string;+ },+): Promise<DeviceCopyAssetForPublishResult> {+ const { userId, deviceId, from, to, workingDirectory, timeout = 30_000, workspaceId } = params;+ const client = getClient();+ if (!client) return { error: 'Device gateway not configured', success: false };++ assertPathsWithinWorkspace(workingDirectory, [to]);++ try {+ const result = await client.invokeRpc<DeviceCopyAssetForPublishResult>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'copyAssetForPublish', params: { from, to, workingDirectory } },+ );+ if (!result.success || !result.data) {+ return { error: result.error || 'Failed to copy publish asset', success: false };+ }+ return result.data;+ } catch (error) {+ log('copyAssetForPublish: error for deviceId=%s β %O', deviceId, error);+ return { error: (error as Error).message, success: false };+ }+}++export async function readExternalAssetForPublish(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ path: string;+ timeout?: number;+ userId: string;+ workingDirectory: string;+ workspaceId?: string;+ },+): Promise<DeviceExternalAssetForPublishResult> {+ const { userId, deviceId, path, workingDirectory, timeout = 30_000, workspaceId } = params;+ const client = getClient();+ if (!client) return { error: 'Device gateway not configured', success: false };++ try {+ const result = await client.invokeRpc<DeviceExternalAssetForPublishResult>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'readExternalAssetForPublish', params: { path, workingDirectory } },+ );+ if (!result.success || !result.data) {+ return { error: result.error || 'Failed to read external publish asset', success: false };+ }+ return result.data;+ } catch (error) {+ log('readExternalAssetForPublish: error for deviceId=%s β %O', deviceId, error);+ return { error: (error as Error).message, success: false };+ }+}++/**+ * Project skills (`.agents/skills` / `.claude/skills`) for a directory on a+ * remote device via the `listProjectSkills` device RPC β the Resources tab's+ * skills group in device mode. Mirrors `getProjectFileIndex`; returns+ * `undefined` when the gateway is unconfigured, the device is offline, or the+ * call fails so the UI degrades to "no skills".+ */+export async function listProjectSkills(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ scope: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+ },+): Promise<DeviceListProjectSkillsResult | undefined> {+ const { userId, deviceId, scope, timeout = 30_000, workspaceId } = params;+ const client = getClient();+ if (!client) return undefined;++ try {+ const result = await client.invokeRpc<DeviceListProjectSkillsResult>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'listProjectSkills', params: { scope } },+ );++ if (!result.success || !result.data) {+ log('listProjectSkills: failed for deviceId=%s β %s', deviceId, result.error);+ return undefined;+ }++ return result.data;+ } catch (error) {+ log('listProjectSkills: error for deviceId=%s β %O', deviceId, error);+ return undefined;+ }+}diff --git a/apps/server/src/services/deviceGateway/terminal.ts b/apps/server/src/services/deviceGateway/terminal.tsnew file mode 100644index 00000000000..e47dae3122d--- /dev/null+++ b/apps/server/src/services/deviceGateway/terminal.ts@@ -0,0 +1,103 @@+/**+ * Interactive terminal (PTY) RPCs, relayed to the `lh connect` process.+ */+import type {+ DeviceCloseTerminalResult,+ DeviceCreateTerminalSessionResult,+ DeviceReadTerminalResult,+} from '@lobechat/types';++import type { DeviceClientGetter } from './types';++/** Scope every terminal RPC carries; mirrors `AppUpdateRpcParams`. */+interface TerminalRpcScope {+ deviceId: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+}++/** The five device RPCs that make up one interactive terminal session. */+type TerminalRpcMethod =+ 'closeTerminal' | 'createTerminalSession' | 'readTerminal' | 'resizeTerminal' | 'writeTerminal';++// A terminal is a session the caller drives, not a one-shot read, so these+// deliberately THROW on failure instead of returning `undefined` the way the+// best-effort readers do: the panel has to say why a shell did not open+// (device offline, a client without PTY support) rather than wait forever on+// one that will never exist.++export async function createTerminalSession(+ getClient: DeviceClientGetter,+ params: TerminalRpcScope & { cols: number; cwd?: string; rows: number },+): Promise<DeviceCreateTerminalSessionResult> {+ return invokeTerminalRpc(getClient, 'createTerminalSession', params, {+ cols: params.cols,+ cwd: params.cwd,+ rows: params.rows,+ });+}++export async function writeTerminal(+ getClient: DeviceClientGetter,+ params: TerminalRpcScope & { data: string; id: string },+): Promise<void> {+ await invokeTerminalRpc(getClient, 'writeTerminal', params, { data: params.data, id: params.id });+}++export async function readTerminal(+ getClient: DeviceClientGetter,+ params: TerminalRpcScope & { cursor: number; id: string },+): Promise<DeviceReadTerminalResult> {+ return invokeTerminalRpc(getClient, 'readTerminal', params, {+ cursor: params.cursor,+ id: params.id,+ });+}++export async function resizeTerminal(+ getClient: DeviceClientGetter,+ params: TerminalRpcScope & { cols: number; id: string; rows: number },+): Promise<void> {+ await invokeTerminalRpc(getClient, 'resizeTerminal', params, {+ cols: params.cols,+ id: params.id,+ rows: params.rows,+ });+}++export async function closeTerminal(+ getClient: DeviceClientGetter,+ params: TerminalRpcScope & { id: string },+): Promise<DeviceCloseTerminalResult> {+ return invokeTerminalRpc(getClient, 'closeTerminal', params, { id: params.id });+}++/**+ * Relay one terminal RPC and unwrap its result.+ *+ * Every call carries the `cli` channel hint: the PTY lives in the `lh+ * connect` process, so on a machine also running the desktop app the RPC has+ * to reach that connection β the desktop's own terminal is local-only and+ * would refuse these. A gateway that predates the hint ignores it, which is+ * why the refusal below still has to surface as an error.+ */+export async function invokeTerminalRpc<T>(+ getClient: DeviceClientGetter,+ method: TerminalRpcMethod,+ params: TerminalRpcScope,+ rpcParams: Record<string, unknown>,+): Promise<T> {+ const { deviceId, timeout = 15_000, userId, workspaceId } = params;+ const client = getClient();+ if (!client) throw new Error('Device gateway is not configured on this deployment.');++ const result = await client.invokeRpc<T>(+ { channel: 'cli', deviceId, timeout, userId, workspaceId },+ { method, params: rpcParams },+ );+ // `writeTerminal` / `resizeTerminal` answer with no payload, so absence of+ // `data` is not a failure β only an explicit `success: false` is.+ if (!result.success) throw new Error(result.error || `${method} failed`);+ return result.data as T;+}diff --git a/apps/server/src/services/deviceGateway/testUtils.ts b/apps/server/src/services/deviceGateway/testUtils.tsnew file mode 100644index 00000000000..868a9ef5882--- /dev/null+++ b/apps/server/src/services/deviceGateway/testUtils.ts@@ -0,0 +1,46 @@+/**+ * Shared fakes for the DeviceGateway scenario tests. Each test file keeps its+ * own `vi.mock` calls (Vitest hoists them per file) and points the factories+ * here, so every file drives the same fake gateway client and env.+ */+import { vi } from 'vitest';++export const mockEnv = {+ DEVICE_GATEWAY_SERVICE_TOKEN: undefined as string | undefined,+ DEVICE_GATEWAY_URL: undefined as string | undefined,+};++export const mockClient = {+ dispatchAgentRun: vi.fn(),+ executeMcpCall: vi.fn(),+ executeMessageApi: vi.fn(),+ executeToolCall: vi.fn(),+ getDeviceMetrics: vi.fn(),+ getDeviceSystemInfo: vi.fn(),+ invokeRpc: vi.fn(),+ queryDeviceList: vi.fn(),+ queryDeviceStatus: vi.fn(),+};++export const MockGatewayHttpClient = vi.fn(function () {+ return mockClient;+});++// The send-path cache rides on the Redis service; hand its connection seam a+// fake client so the test sees which key and TTL the gateway asked for,+// independent of whether this environment has Redis configured.+export const cacheRedis = { get: vi.fn(async () => null), set: vi.fn(async () => 'OK') };+export const getRedisServiceClient = vi.fn(async () => cacheRedis);++/** Point the gateway env at a fake deployment so `getClient()` builds a client. */+export const configureGateway = () => {+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';+};++/** Per-test reset: clear call history and leave the gateway unconfigured. */+export const resetGatewayMocks = () => {+ vi.clearAllMocks();+ mockEnv.DEVICE_GATEWAY_URL = undefined;+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = undefined;+};diff --git a/apps/server/src/services/deviceGateway/types.ts b/apps/server/src/services/deviceGateway/types.tsnew file mode 100644index 00000000000..0183e86c735--- /dev/null+++ b/apps/server/src/services/deviceGateway/types.ts@@ -0,0 +1,12 @@+import type { GatewayHttpClient } from '@lobechat/device-gateway-client';++/** Returns the lazily built gateway client, or `null` when the gateway is not configured. */+export type DeviceClientGetter = () => GatewayHttpClient | null;++/** A module function's arguments after its leading `getClient`. */+export type DeviceRpcArgs<F> = F extends (+ getClient: DeviceClientGetter,+ ...args: infer A+) => unknown+ ? A+ : never;diff --git a/apps/server/src/services/deviceGateway/workspace.ts b/apps/server/src/services/deviceGateway/workspace.tsnew file mode 100644index 00000000000..857c49e394d--- /dev/null+++ b/apps/server/src/services/deviceGateway/workspace.ts@@ -0,0 +1,295 @@+/**+ * Workspace-level device RPCs: project scan, skill cache, workspace+ * enrollment, and path / port probes.+ */+import type {+ DeviceListeningPortsResult,+ ProjectSkillMeta,+ WorkspaceInitResult,+} from '@lobechat/types';+import debug from 'debug';++import type { DeviceClientGetter } from './types';++const log = debug('lobe-server:device-gateway');++/**+ * Scan a bound project directory on the device in a single round-trip:+ * project skills (`.agents/skills` + `.claude/skills`) plus the root+ * `AGENTS.md` / `CLAUDE.md`. Routed through the generic device RPC relay+ * (`invokeRpc`) β a server-internal channel the agent never sees, distinct+ * from the LLM-facing tool-call path.+ *+ * Returns `undefined` when the gateway is unconfigured, the device is offline,+ * or the call fails β callers fall back to the cached scan.+ */+export async function initWorkspace(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ scope: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+ },+): Promise<WorkspaceInitResult | undefined> {+ const { userId, deviceId, scope, timeout = 30_000, workspaceId } = params;+ const client = getClient();+ if (!client) return undefined;++ try {+ // The device returns rich `ProjectSkillItem`s; narrow to metadata only so+ // the cached `workingDirs` payload stays small (SKILL.md bodies are still+ // read lazily at activation time). Keep scope so project/device skills can+ // be displayed and activated with the correct origin.+ const result = await client.invokeRpc<{+ instructions?: WorkspaceInitResult['instructions'];+ skills?: (ProjectSkillMeta & Record<string, unknown>)[];+ }>({ deviceId, timeout, userId, workspaceId }, { method: 'initWorkspace', params: { scope } });++ if (!result.success || !result.data) {+ log('initWorkspace: failed for deviceId=%s β %s', deviceId, result.error);+ return undefined;+ }++ const { instructions, skills } = result.data;+ return {+ instructions: instructions ?? [],+ skills: (skills ?? []).map(({ description, name, path, scope }) => ({+ description,+ name,+ path,+ scope,+ })),+ };+ } catch (error) {+ log('initWorkspace: error for deviceId=%s β %O', deviceId, error);+ return undefined;+ }+}++/**+ * Prepare a skill archive on the device: download the presigned zip and+ * extract it into the device-local cache (idempotent by `zipHash`). Runs on+ * the generic device RPC relay like `initWorkspace`, but unlike the+ * read-oriented helpers, failures are RETURNED with their reason instead of+ * collapsing to `undefined` β the skills exec path must tell the model why+ * the device can't run the skill (offline, outdated client, download+ * failure) rather than silently degrading to the sandbox.+ */+export async function prepareSkillDirectory(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ forceRefresh?: boolean;+ timeout?: number;+ url: string;+ userId: string;+ workspaceId?: string;+ zipHash: string;+ },+): Promise<{ error?: string; extractedDir?: string; success: boolean }> {+ const { deviceId, forceRefresh, timeout = 60_000, url, userId, workspaceId, zipHash } = params;+ const client = getClient();+ if (!client) return { error: 'Device Gateway is not configured', success: false };++ try {+ const result = await client.invokeRpc<{+ error?: string;+ extractedDir: string;+ success: boolean;+ }>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'prepareSkillDirectory', params: { forceRefresh, url, zipHash } },+ );++ if (!result.success || !result.data) {+ return { error: result.error || 'prepareSkillDirectory failed', success: false };+ }++ return result.data;+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ log('prepareSkillDirectory: error for deviceId=%s β %s', deviceId, message);+ return { error: message, success: false };+ }+}++/**+ * Instruct an ONLINE personal device to enroll itself into a workspace: the+ * device derives its workspace-scoped deviceId and opens a second gateway+ * connection under the `workspace:<id>` principal using the short-lived+ * `token` (a signed workspace-device connect token), then returns the derived+ * identity so the caller can register the workspace row server-side. Rides+ * the generic device RPC relay over the PERSONAL pool (no `workspaceId` in+ * the address β the workspace connection doesn't exist yet). Failures are+ * RETURNED with their reason β the share flow must tell the user why the+ * device couldn't enroll (offline, outdated client) instead of silently+ * doing nothing.+ */+export async function enrollWorkspace(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ /**+ * Dry-run: the device only derives and returns its workspace identity,+ * without opening a share connection or persisting enrollment state.+ * Older clients ignore the flag and enroll on the probe (pre-flag+ * behaviour), so callers must treat the probe as possibly-enrolling.+ */+ identityOnly?: boolean;+ timeout?: number;+ token: string;+ userId: string;+ workspaceId: string;+ },+): Promise<{+ error?: string;+ identity?: { deviceId: string; identitySource: 'fallback' | 'machine-id' };+ success: boolean;+}> {+ const { deviceId, identityOnly, timeout = 30_000, token, userId, workspaceId } = params;+ const client = getClient();+ if (!client) return { error: 'Device Gateway is not configured', success: false };++ try {+ const result = await client.invokeRpc<{+ deviceId: string;+ identitySource: 'fallback' | 'machine-id';+ }>(+ { deviceId, timeout, userId },+ {+ method: 'enrollWorkspace',+ params: { ...(identityOnly ? { identityOnly } : {}), token, workspaceId },+ },+ );++ if (!result.success || !result.data) {+ return { error: result.error || 'enrollWorkspace failed', success: false };+ }++ return { identity: result.data, success: true };+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ log('enrollWorkspace: error for deviceId=%s β %s', deviceId, message);+ return { error: message, success: false };+ }+}++/**+ * Instruct an ONLINE workspace device to drop its enrollment: close the+ * workspace-principal connection and clear any persisted auto-reconnect state+ * on the machine. Addressed over the WORKSPACE pool (the connection being+ * killed), so it works regardless of who enrolled the device or whether a+ * personal connection exists. Best-effort β callers delete the DB row either+ * way, so an offline device simply loses its row and stops resolving.+ */+export async function unenrollWorkspace(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ timeout?: number;+ userId: string;+ workspaceId: string;+ },+): Promise<{ error?: string; success: boolean }> {+ const { deviceId, timeout = 10_000, userId, workspaceId } = params;+ const client = getClient();+ if (!client) return { error: 'Device Gateway is not configured', success: false };++ try {+ const result = await client.invokeRpc<{ success: boolean }>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'unenrollWorkspace', params: { workspaceId } },+ );+ if (!result.success)+ return { error: result.error || 'unenrollWorkspace failed', success: false };+ return { success: true };+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ log('unenrollWorkspace: error for deviceId=%s β %s', deviceId, message);+ return { error: message, success: false };+ }+}++/**+ * Check whether a path exists on the device and is a directory, via the same+ * generic `invokeRpc` channel as `gitInfo`. Lets a web / remote client+ * validate a manually-entered working directory before binding it. Returns+ * `undefined` when the gateway is unconfigured or the device is unreachable+ * (the caller treats "can't verify" as non-blocking).+ */+export async function statPath(+ getClient: DeviceClientGetter,+ params: {+ deviceId: string;+ path: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+ },+): Promise<+ | { exists: boolean; isDirectory: boolean; repositoryUrl?: string; repoType?: 'git' | 'github' }+ | undefined+> {+ const { userId, deviceId, path, timeout = 8000, workspaceId } = params;+ const client = getClient();+ if (!client) return undefined;++ try {+ const result = await client.invokeRpc<{+ exists: boolean;+ isDirectory: boolean;+ repoType?: 'git' | 'github';+ }>({ deviceId, timeout, userId, workspaceId }, { method: 'statPath', params: { path } });++ if (!result.success || !result.data) {+ log('statPath: failed for deviceId=%s β %s', deviceId, result.error);+ return undefined;+ }++ return result.data;+ } catch (error) {+ log('statPath: error for deviceId=%s β %O', deviceId, error);+ return undefined;+ }+}++/**+ * TCP ports the device is listening on that a tunnel can reach, with the+ * project's own ports marked. Resolves undefined when the device is+ * offline or predates the RPC β the UI then says it can't read the ports.+ */+export async function listListeningPorts(+ getClient: DeviceClientGetter,+ params: {+ cwd?: string;+ deviceId: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+ },+): Promise<DeviceListeningPortsResult | undefined> {+ const { cwd, deviceId, timeout = 10_000, userId, workspaceId } = params;+ const client = getClient();+ if (!client) return undefined;++ try {+ const result = await client.invokeRpc<DeviceListeningPortsResult>(+ { deviceId, timeout, userId, workspaceId },+ { method: 'listListeningPorts', params: { cwd } },+ );+ if (!result.success || !result.data) {+ log('listListeningPorts: failed for deviceId=%s', deviceId);+ return undefined;+ }+ return result.data;+ } catch (error) {+ log(+ 'listListeningPorts: error for deviceId=%s (%s)',+ deviceId,+ error instanceof Error ? error.name : typeof error,+ );+ return undefined;+ }+}