🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(device): update a device's desktop app remotely (#19939)
Arvin Xua6a93fe2caf6
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.tsindex 19e175381c4..5550ff0b1b2 100644--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts@@ -13,7 +13,10 @@ import {resolveRemotePlatformRuntime,} from '@lobechat/heterogeneous-agents/scanHost';import { type ILocalSystemService, LocalSystemExecutionRuntime } from '@lobechat/tool-runtime';+import { app as electronApp } from 'electron';+import { updaterConfig } from '@/modules/updater/configs';+import { createRemoteAppUpdateDeps } from '@/modules/updater/remoteUpdate';import AuvService, { type AuvRunCommandParams } from '@/services/auvSrv';import { backfillDeviceArchitecture } from '@/services/deviceArchitectureBackfill';import GatewayConnectionService from '@/services/gatewayConnectionSrv';@@ -462,6 +465,13 @@ export default class GatewayConnectionCtr extends ControllerModule {// Skill-archive cache (`prepareSkillDirectory` RPC): reuse LocalFileCtr's// deps so gateway-prepared skills share one cache with the renderer-IPC path....this.localFileCtr.getSkillDirectoryDeps(),+ // Remote app update from the web device page, over the same updater the+ // local "Check for updates" menu drives.+ ...createRemoteAppUpdateDeps({+ currentVersion: electronApp.getVersion(),+ enabled: updaterConfig.enableAppUpdate,+ getUpdater: () => this.app.getUpdaterManager(),+ }),};}diff --git a/apps/desktop/src/main/core/infrastructure/UpdaterManager.ts b/apps/desktop/src/main/core/infrastructure/UpdaterManager.tsindex 5e270da4bce..06f47f410a1 100644--- a/apps/desktop/src/main/core/infrastructure/UpdaterManager.ts+++ b/apps/desktop/src/main/core/infrastructure/UpdaterManager.ts@@ -230,6 +230,22 @@ export class UpdaterManager {}};+ /**+ * Check for updates because someone explicitly asked to update this app from+ * another device. An earlier local "install later" would keep the found+ * update from downloading, so the explicit request overrides it.+ */+ public checkForUpdatesOnRequest = () => {+ if (this.installLaterVersion) {+ logger.info(+ `Remote update requested; clearing install-later for v${this.installLaterVersion}`,+ );+ this.installLaterVersion = null;+ }++ void this.checkForUpdates({ manual: true });+ };+/*** Download update*/diff --git a/apps/desktop/src/main/modules/updater/__tests__/remoteUpdate.test.ts b/apps/desktop/src/main/modules/updater/__tests__/remoteUpdate.test.tsnew file mode 100644index 00000000000..fecafeb9765--- /dev/null+++ b/apps/desktop/src/main/modules/updater/__tests__/remoteUpdate.test.ts@@ -0,0 +1,122 @@+import type { UpdaterState } from '@lobechat/electron-client-ipc';+import { describe, expect, it, vi } from 'vitest';++import {+ createRemoteAppUpdateDeps,+ REMOTE_INSTALL_DELAY_MS,+ type RemoteUpdaterTarget,+ toAppUpdateState,+} from '../remoteUpdate';++const updateInfo = { kind: 'app' as const, releaseDate: '2026-09-25', version: '2.2.0' };++const makeUpdater = (initial: UpdaterState) => {+ let state = initial;+ const updater: RemoteUpdaterTarget = {+ checkForUpdatesOnRequest: vi.fn(() => {+ state = { stage: 'checking' };+ }),+ getUpdaterState: () => state,+ installNow: vi.fn(),+ };+ return updater;+};++const setup = (initial: UpdaterState, enabled = true) => {+ const updater = makeUpdater(initial);+ const schedule = vi.fn();+ const deps = createRemoteAppUpdateDeps({+ currentVersion: '2.1.0',+ enabled,+ getUpdater: async () => updater,+ schedule,+ });+ return { deps, schedule, updater };+};++describe('toAppUpdateState', () => {+ it('reports progress and target while downloading', () => {+ expect(+ toAppUpdateState(+ {+ progress: { bytesPerSecond: 1, percent: 42.6, total: 100, transferred: 42 },+ stage: 'downloading',+ updateInfo,+ },+ '2.1.0',+ ),+ ).toEqual({+ currentVersion: '2.1.0',+ progress: 43,+ stage: 'downloading',+ targetVersion: '2.2.0',+ });+ });++ it('drops the stale update info once the updater has settled', () => {+ expect(toAppUpdateState({ stage: 'latest', updateInfo }, '2.1.0')).toEqual({+ currentVersion: '2.1.0',+ stage: 'latest',+ });+ });++ it('carries the error message on failure', () => {+ expect(toAppUpdateState({ errorMessage: 'net down', stage: 'error' }, '2.1.0')).toEqual({+ currentVersion: '2.1.0',+ errorMessage: 'net down',+ stage: 'error',+ });+ });+});++describe('createRemoteAppUpdateDeps', () => {+ it('reports unsupported on a build that cannot update itself', async () => {+ const { deps, updater } = setup({ stage: 'idle' }, false);++ await expect(deps.getAppUpdateState()).resolves.toEqual({+ currentVersion: '2.1.0',+ stage: 'unsupported',+ });+ await expect(deps.checkAppUpdate()).resolves.toMatchObject({ stage: 'unsupported' });+ await expect(deps.installAppUpdate()).rejects.toThrow('cannot install updates');+ expect(updater.checkForUpdatesOnRequest).not.toHaveBeenCalled();+ });++ it('starts a check and returns the checking state', async () => {+ const { deps, updater } = setup({ stage: 'idle' });++ await expect(deps.checkAppUpdate()).resolves.toEqual({+ currentVersion: '2.1.0',+ stage: 'checking',+ });+ expect(updater.checkForUpdatesOnRequest).toHaveBeenCalledOnce();+ });++ it('does not check again when an update is already downloaded', async () => {+ const { deps, updater } = setup({ stage: 'downloaded', updateInfo });++ await expect(deps.checkAppUpdate()).resolves.toMatchObject({+ stage: 'downloaded',+ targetVersion: '2.2.0',+ });+ expect(updater.checkForUpdatesOnRequest).not.toHaveBeenCalled();+ });++ it('answers before restarting into a downloaded update', async () => {+ const { deps, schedule, updater } = setup({ stage: 'downloaded', updateInfo });++ await expect(deps.installAppUpdate()).resolves.toEqual({ targetVersion: '2.2.0' });+ expect(updater.installNow).not.toHaveBeenCalled();+ expect(schedule).toHaveBeenCalledWith(expect.any(Function), REMOTE_INSTALL_DELAY_MS);++ schedule.mock.calls[0][0]();+ expect(updater.installNow).toHaveBeenCalledOnce();+ });++ it('refuses to install while nothing is downloaded', async () => {+ const { deps, schedule } = setup({ stage: 'downloading', updateInfo });++ await expect(deps.installAppUpdate()).rejects.toThrow('No downloaded update to install');+ expect(schedule).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/modules/updater/remoteUpdate.ts b/apps/desktop/src/main/modules/updater/remoteUpdate.tsnew file mode 100644index 00000000000..b3a871778e7--- /dev/null+++ b/apps/desktop/src/main/modules/updater/remoteUpdate.ts@@ -0,0 +1,94 @@+import type {+ AppUpdateState,+ DeviceControlDeps,+ InstallAppUpdateResult,+} from '@lobechat/device-control';+import type { UpdaterState } from '@lobechat/electron-client-ipc';++/**+ * How long `installAppUpdate` waits before quitting: long enough for the RPC+ * response to leave over the gateway socket, which closes with the app.+ */+export const REMOTE_INSTALL_DELAY_MS = 1500;++/** The slice of `UpdaterManager` a remote update drives. */+export interface RemoteUpdaterTarget {+ checkForUpdatesOnRequest: () => void;+ getUpdaterState: () => UpdaterState;+ installNow: () => void;+}++interface RemoteAppUpdateOptions {+ currentVersion: string;+ /** False when this build can't update itself (dev builds). */+ enabled: boolean;+ getUpdater: () => Promise<RemoteUpdaterTarget>;+ /** Injectable for tests; defaults to `setTimeout`. */+ schedule?: (run: () => void, delayMs: number) => void;+}++/** Project the updater's local state onto the remote-update wire shape. */+export const toAppUpdateState = (state: UpdaterState, currentVersion: string): AppUpdateState => {+ const inFlight = state.stage === 'downloading' || state.stage === 'downloaded';++ return {+ currentVersion,+ stage: state.stage,+ // The updater keeps the last `updateInfo` after it settles; only a download+ // in flight or ready to install has a real target.+ ...(inFlight && state.updateInfo?.version ? { targetVersion: state.updateInfo.version } : {}),+ ...(state.stage === 'downloading' && state.progress+ ? { progress: Math.round(state.progress.percent) }+ : {}),+ ...(state.stage === 'error' && state.errorMessage ? { errorMessage: state.errorMessage } : {}),+ };+};++/**+ * The desktop's app-update handlers for the device-control RPC dispatcher, so+ * the web device page can update this app remotely: check (an available update+ * downloads on its own), poll progress, then restart into it.+ */+export const createRemoteAppUpdateDeps = ({+ currentVersion,+ enabled,+ getUpdater,+ schedule = (run, delayMs) => setTimeout(run, delayMs),+}: RemoteAppUpdateOptions): Required<+ Pick<DeviceControlDeps, 'checkAppUpdate' | 'getAppUpdateState' | 'installAppUpdate'>+> => {+ const unsupported: AppUpdateState = { currentVersion, stage: 'unsupported' };++ const getAppUpdateState = async (): Promise<AppUpdateState> => {+ if (!enabled) return unsupported;+ return toAppUpdateState((await getUpdater()).getUpdaterState(), currentVersion);+ };++ return {+ checkAppUpdate: async () => {+ if (!enabled) return unsupported;++ const updater = await getUpdater();+ // A downloaded update is already what the caller is after — checking+ // again would download it a second time.+ if (updater.getUpdaterState().stage !== 'downloaded') updater.checkForUpdatesOnRequest();++ return toAppUpdateState(updater.getUpdaterState(), currentVersion);+ },++ getAppUpdateState,++ installAppUpdate: async (): Promise<InstallAppUpdateResult> => {+ if (!enabled) throw new Error('This build cannot install updates');++ const updater = await getUpdater();+ const state = updater.getUpdaterState();+ const targetVersion = state.updateInfo?.version;+ if (state.stage !== 'downloaded' || !targetVersion)+ throw new Error('No downloaded update to install');++ schedule(() => updater.installNow(), REMOTE_INSTALL_DELAY_MS);+ return { targetVersion };+ },+ };+};diff --git a/apps/server/src/routers/lambda/__tests__/deviceAppUpdate.test.ts b/apps/server/src/routers/lambda/__tests__/deviceAppUpdate.test.tsnew file mode 100644index 00000000000..ea71664824a--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/deviceAppUpdate.test.ts@@ -0,0 +1,65 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { deviceRouter } from '../device';++const mocks = vi.hoisted(() => ({+ checkAppUpdate: vi.fn(),+ findWorkspaceDeviceById: vi.fn(),+ getAppUpdateState: vi.fn(),+ installAppUpdate: vi.fn(),+}));++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn() }));+vi.mock('@/database/models/device', () => ({+ DeviceModel: class {+ findWorkspaceDeviceById = mocks.findWorkspaceDeviceById;+ },+}));+vi.mock('@/server/services/deviceGateway', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ deviceGateway: {+ checkAppUpdate: mocks.checkAppUpdate,+ getAppUpdateState: mocks.getAppUpdateState,+ installAppUpdate: mocks.installAppUpdate,+ },+}));++const workspaceCaller = (userId: string, workspaceRole: 'member' | 'owner') =>+ deviceRouter.createCaller({ userId, workspaceId: 'workspace', workspaceRole } as never);++describe('remote app update', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.findWorkspaceDeviceById.mockResolvedValue({ deviceId: 'device', userId: 'enroller' });+ mocks.installAppUpdate.mockResolvedValue({ status: 'ok', targetVersion: '2.2.0' });+ });++ it('lets the enrolling member restart a workspace device into its update', async () => {+ await expect(+ workspaceCaller('enroller', 'member').installAppUpdate({ deviceId: 'device' }),+ ).resolves.toEqual({ status: 'ok', targetVersion: '2.2.0' });+ expect(mocks.installAppUpdate).toHaveBeenCalledWith({+ deviceId: 'device',+ userId: 'enroller',+ workspaceId: 'workspace',+ });+ });++ it('lets a workspace owner update a device another member enrolled', async () => {+ await expect(+ workspaceCaller('owner', 'owner').installAppUpdate({ deviceId: 'device' }),+ ).resolves.toMatchObject({ status: 'ok' });+ });++ it.each(['getAppUpdateState', 'checkAppUpdate', 'installAppUpdate'] as const)(+ "rejects %s from a member on someone else's workspace device",+ async (procedure) => {+ const caller = workspaceCaller('member', 'member');+ await expect(caller[procedure]({ deviceId: 'device' })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ expect(mocks[procedure]).not.toHaveBeenCalled();+ },+ );+});diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.tsindex d81005afcae..6574ba1a5c4 100644--- a/apps/server/src/routers/lambda/device.ts+++ b/apps/server/src/routers/lambda/device.ts@@ -63,11 +63,11 @@ const SCAN_TIMEOUT_MS = 10_000;* else's enrollment, while shared cleanup remains an owner action.*//**- * Exposing a port is at least as sensitive as reading the filesystem, so a- * workspace device is gated the same way `browseDirectory` gates new paths:- * only the enrolling member or a workspace owner.+ * Gate an action that operates the machine itself — exposing a port, updating+ * its app — the same way `browseDirectory` gates new paths: on a workspace+ * device, only the enrolling member or a workspace owner.*/-const assertTunnelDeviceWritable = async (+const assertDeviceOperable = async (ctx: {deviceModel: DeviceModel;userId: string;@@ -75,6 +75,7 @@ const assertTunnelDeviceWritable = async (workspaceRole?: WorkspaceRole;},deviceId: string,+ action: string,) => {if (!ctx.workspaceId) return;@@ -83,11 +84,17 @@ const assertTunnelDeviceWritable = async (if (!canEditWorkspaceDevice(ctx.workspaceRole, ctx.userId, row.userId)) {throw new TRPCError({code: 'FORBIDDEN',- message: 'Only the enrolling member or a workspace owner can expose a port on this device.',+ message: `Only the enrolling member or a workspace owner can ${action} on this device.`,});}};+/** Exposing a port is at least as sensitive as reading the filesystem. */+const assertTunnelDeviceWritable = (+ ctx: Parameters<typeof assertDeviceOperable>[0],+ deviceId: string,+) => assertDeviceOperable(ctx, deviceId, 'expose a port');+/** Append a freshly minted access token to a tunnel URL. */const buildTunnelOpenUrl = async (url: string,@@ -1179,6 +1186,7 @@ export const deviceRouter = router({hostname: d.hostname ?? live?.hostname ?? null,identitySource: d.identitySource,lastSeen: d.lastSeenAt.toISOString(),+ metadata: d.metadata,online: channels.length > 0,platform: d.platform ?? live?.platform ?? null,registered: true,@@ -1296,6 +1304,46 @@ export const deviceRouter = router({return result ?? null;}),+ // ─── Remote app update ───+ //+ // Update the desktop app on a device from anywhere: check (a found update+ // downloads on its own), poll progress, then restart into it. Restarting+ // interrupts whatever the machine is running, so every step is gated like+ // exposing a port.++ getAppUpdateState: deviceProcedure+ .input(z.object({ deviceId: z.string() }))+ .query(async ({ ctx, input }) => {+ await assertDeviceOperable(ctx, input.deviceId, 'update the app');+ return deviceGateway.getAppUpdateState({+ deviceId: input.deviceId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ }),++ checkAppUpdate: deviceProcedure+ .input(z.object({ deviceId: z.string() }))+ .mutation(async ({ ctx, input }) => {+ await assertDeviceOperable(ctx, input.deviceId, 'update the app');+ return deviceGateway.checkAppUpdate({+ deviceId: input.deviceId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ }),++ installAppUpdate: deviceProcedure+ .input(z.object({ deviceId: z.string() }))+ .mutation(async ({ ctx, input }) => {+ await assertDeviceOperable(ctx, input.deviceId, 'update the app');+ return deviceGateway.installAppUpdate({+ deviceId: input.deviceId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ }),+/** Live tunnel links the caller can reach, newest first. */listTunnels: deviceProcedure.input(z.object({ deviceId: z.string().optional() }).optional())diff --git a/apps/server/src/services/deviceGateway/__tests__/index.test.ts b/apps/server/src/services/deviceGateway/__tests__/index.test.tsindex 12a5bf86006..35bb036b0c3 100644--- a/apps/server/src/services/deviceGateway/__tests__/index.test.ts+++ b/apps/server/src/services/deviceGateway/__tests__/index.test.ts@@ -44,6 +44,69 @@ describe('DeviceGateway', () => {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('isConfigured', () => {it('should return false when DEVICE_GATEWAY_URL is not set', () => {const proxy = new DeviceGateway();diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.tsindex de4ebb94f07..cbe7c8bf4c4 100644--- a/apps/server/src/services/deviceGateway/index.ts+++ b/apps/server/src/services/deviceGateway/index.ts@@ -15,6 +15,10 @@ import type {KimiCodeQuotaSnapshot,} from '@lobechat/heterogeneous-agents/quota';import type {+ DeviceAppUpdateFailure,+ DeviceAppUpdateInstallResult,+ DeviceAppUpdateState,+ DeviceAppUpdateStateResult,DeviceCopyAssetForPublishResult,DeviceDirectoryBrowseResult,DeviceExternalAssetForPublishResult,@@ -100,6 +104,13 @@ const assertPathsWithinWorkspace = (export type { DeviceAttachment, DeviceStatusResult, DeviceSystemInfo };+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;@@ -1815,6 +1826,63 @@ export class DeviceGateway {}}+ /** 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;+ }++ /**+ * 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' };+ }+ }+private getClient(): GatewayHttpClient | null {const url = gatewayEnv.DEVICE_GATEWAY_URL;const token = gatewayEnv.DEVICE_GATEWAY_SERVICE_TOKEN;diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 33e4005e374..34c48d22b9b 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -383,6 +383,20 @@"devices.actions.edit": "Edit","devices.actions.refresh": "Refresh","devices.actions.remove": "Remove",+ "devices.appUpdate.checkFailed": "Couldn't check for updates: {{message}}",+ "devices.appUpdate.confirmDesc": "LobeHub on this device will quit and restart. Anything it is running, including agent tasks, will be interrupted.",+ "devices.appUpdate.confirmTitle": "Restart and update to v{{version}}?",+ "devices.appUpdate.downloading": "Downloading v{{version}}",+ "devices.appUpdate.installFailed": "The device came back on v{{version}}, so the update didn't apply. Check for updates to try again.",+ "devices.appUpdate.ready": "v{{version}} is downloaded and ready to install",+ "devices.appUpdate.restarting": "Restarting…",+ "devices.appUpdate.restartingHint": "Waiting for the device to come back on v{{version}}",+ "devices.appUpdate.timedOut": "The device hasn't come back online. Check the app on that machine.",+ "devices.appUpdate.unavailable": "Couldn't read the desktop app's update status. Try again.",+ "devices.appUpdate.unsupported.cli": "lh connect answered instead of the desktop app. Stop lh connect on this device, then try again.",+ "devices.appUpdate.unsupported.devBuild": "Development builds can't update themselves.",+ "devices.appUpdate.unsupported.outdated": "This app version can't be updated remotely. Update it once on the device to enable remote updates.",+ "devices.appUpdate.updated": "Updated to v{{version}}","devices.capabilities.commands.desc": "Safely execute terminal commands in your environment.","devices.capabilities.commands.title": "Run commands","devices.capabilities.files.desc": "Let agents directly access and organize the files on your computer.",@@ -391,6 +405,7 @@"devices.capabilities.tools.desc": "Connect local tools to extend what agents can do.","devices.capabilities.tools.title": "Call system tools","devices.channel.connected": "Connected {{time}}",+ "devices.channel.unknown": "Unknown client","devices.connectWizard.button": "Connect Device","devices.connectWizard.cli.connectDesc": "Start the background daemon to keep the device online and listening for remote operations.","devices.connectWizard.cli.connectTitle": "Start the daemon",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 8f1eb220c28..4742088d6e9 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -383,6 +383,20 @@"devices.actions.edit": "编辑","devices.actions.refresh": "刷新","devices.actions.remove": "移除",+ "devices.appUpdate.checkFailed": "检查更新失败:{{message}}",+ "devices.appUpdate.confirmDesc": "该设备上的 LobeHub 会退出并重启,正在运行的内容(包括助理任务)都会被中断。",+ "devices.appUpdate.confirmTitle": "重启并更新到 v{{version}}?",+ "devices.appUpdate.downloading": "正在下载 v{{version}}",+ "devices.appUpdate.installFailed": "设备重启后仍是 v{{version}},更新没有生效。可以重新检查更新再试一次。",+ "devices.appUpdate.ready": "v{{version}} 已下载,可以安装",+ "devices.appUpdate.restarting": "正在重启…",+ "devices.appUpdate.restartingHint": "等待设备以 v{{version}} 重新上线",+ "devices.appUpdate.timedOut": "设备还没有重新上线,请到这台电脑上查看应用状态。",+ "devices.appUpdate.unavailable": "没能读取桌面端的更新状态,请重试。",+ "devices.appUpdate.unsupported.cli": "请求被 lh connect 接收了,而不是桌面端。请先在这台设备上停止 lh connect 后重试。",+ "devices.appUpdate.unsupported.devBuild": "开发版无法自行更新。",+ "devices.appUpdate.unsupported.outdated": "当前应用版本不支持远程更新。请先在设备上手动更新一次,之后即可远程更新。",+ "devices.appUpdate.updated": "已更新到 v{{version}}","devices.capabilities.commands.desc": "在你的环境中安全地执行终端命令。","devices.capabilities.commands.title": "运行命令","devices.capabilities.files.desc": "让智能体直接访问并整理你电脑上的文件。",@@ -391,6 +405,7 @@"devices.capabilities.tools.desc": "连接本地工具,扩展智能体的能力边界。","devices.capabilities.tools.title": "调用系统工具","devices.channel.connected": "已连接 {{time}}",+ "devices.channel.unknown": "未知客户端","devices.connectWizard.button": "连接设备","devices.connectWizard.cli.connectDesc": "启动后台守护进程,保持设备在线并等待远程操作。","devices.connectWizard.cli.connectTitle": "启动守护进程",diff --git a/packages/database/src/models/__tests__/device.test.ts b/packages/database/src/models/__tests__/device.test.tsindex b29ad5ef65b..c3cd8c147d4 100644--- a/packages/database/src/models/__tests__/device.test.ts+++ b/packages/database/src/models/__tests__/device.test.ts@@ -113,6 +113,47 @@ describe('DeviceModel', () => {});});+ it('keeps the desktop and CLI versions when both clients register the same device', async () => {+ await deviceModel.register({+ deviceId: 'dev-shared',+ identitySource: 'machine-id',+ metadata: { appVersion: '2.0.0', node: '22.0.0' },+ });+ await deviceModel.register({+ deviceId: 'dev-shared',+ identitySource: 'machine-id',+ metadata: { cliVersion: '1.2.3', node: '24.0.0' },+ });+ await deviceModel.register({ deviceId: 'dev-shared', identitySource: 'machine-id' });++ expect((await deviceModel.findByDeviceId('dev-shared'))?.metadata).toEqual({+ appVersion: '2.0.0',+ cliVersion: '1.2.3',+ node: '24.0.0',+ });+ });++ it('keeps both client versions on a workspace enrollment', async () => {+ const mergeWsId = 'device-model-ws-metadata-merge';+ await serverDB+ .insert(workspaces)+ .values({ id: mergeWsId, name: 'WS', primaryOwnerId: userId, slug: mergeWsId });+ const model = new DeviceModel(serverDB, userId, mergeWsId);+ const base = {+ deviceId: 'ws-dev-shared',+ identitySource: 'machine-id',+ workspaceId: mergeWsId,+ };++ await model.registerWorkspaceDevice({ ...base, metadata: { appVersion: '2.0.0' } });+ const result = await model.registerWorkspaceDevice({+ ...base,+ metadata: { cliVersion: '1.2.3' },+ });++ expect(result.metadata).toEqual({ appVersion: '2.0.0', cliVersion: '1.2.3' });+ });+it('should upsert on (userId, deviceId) and refresh machine fields', async () => {await deviceModel.register({architecture: 'x64',diff --git a/packages/database/src/models/device.ts b/packages/database/src/models/device.tsindex 73c24cc4f7d..6dc43545be6 100644--- a/packages/database/src/models/device.ts+++ b/packages/database/src/models/device.ts@@ -36,6 +36,15 @@ export interface RegisterDeviceParams {platform?: string | null;}+/**+ * Re-registration merges the reported bag instead of replacing it: the desktop+ * app (`appVersion`) and `lh connect` (`cliVersion`) share one row on the same+ * machine, and whichever connects last must not erase the other's version.+ * Keys a client reports again are overwritten; `undefined` leaves the bag alone.+ */+const mergeReportedMetadata = (metadata: RegisterDeviceParams['metadata']) =>+ metadata ? sql`coalesce(${devices.metadata}, '{}'::jsonb) || excluded.metadata` : undefined;+/** Columns the user owns — never overwritten by an auto-register upsert. */export interface UpdateDeviceParams {defaultCwd?: string | null;@@ -121,7 +130,7 @@ export class DeviceModel {hostname: params.hostname,identitySource: params.identitySource,lastSeenAt: now,- metadata: params.metadata,+ metadata: mergeReportedMetadata(params.metadata),platform: params.platform,},target: [devices.userId, devices.deviceId],@@ -217,7 +226,7 @@ export class DeviceModel {hostname: params.hostname,identitySource: params.identitySource,lastSeenAt: now,- metadata: params.metadata,+ metadata: mergeReportedMetadata(params.metadata),platform: params.platform,visibility: params.visibility === 'public' ? 'public' : sql`${devices.visibility}`,},diff --git a/packages/device-control/src/__tests__/dispatch.test.ts b/packages/device-control/src/__tests__/dispatch.test.tsindex 0db7f958879..d961b4d452f 100644--- a/packages/device-control/src/__tests__/dispatch.test.ts+++ b/packages/device-control/src/__tests__/dispatch.test.ts@@ -4,7 +4,7 @@ import path from 'node:path';import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';-import { executeDeviceRpc } from '../dispatch';+import { APP_UPDATE_UNSUPPORTED_MESSAGE, executeDeviceRpc } from '../dispatch';import type { DeviceControlDeps } from '../types';let root: string;@@ -59,6 +59,36 @@ describe('executeDeviceRpc', () => {);});+ describe('app update', () => {+ const state = { currentVersion: '2.1.0', stage: 'downloaded' as const, targetVersion: '2.2.0' };++ it('routes each app-update method to its host handler', async () => {+ const deps: DeviceControlDeps = {+ ...makeDeps(),+ checkAppUpdate: vi.fn(async () => ({ ...state, stage: 'checking' as const })),+ getAppUpdateState: vi.fn(async () => state),+ installAppUpdate: vi.fn(async () => ({ targetVersion: '2.2.0' })),+ };++ await expect(executeDeviceRpc('getAppUpdateState', undefined, deps)).resolves.toEqual(state);+ await expect(executeDeviceRpc('checkAppUpdate', undefined, deps)).resolves.toMatchObject({+ stage: 'checking',+ });+ await expect(executeDeviceRpc('installAppUpdate', undefined, deps)).resolves.toEqual({+ targetVersion: '2.2.0',+ });+ });++ it.each(['getAppUpdateState', 'checkAppUpdate', 'installAppUpdate'])(+ 'rejects %s with a stable reason on a host that cannot update itself',+ async (method) => {+ await expect(executeDeviceRpc(method, undefined, makeDeps())).rejects.toThrow(+ APP_UPDATE_UNSUPPORTED_MESSAGE,+ );+ },+ );+ });+it('routes initWorkspace through the shared workspace scan and approves the root', async () => {const deps = makeDeps();const result = (await executeDeviceRpc('initWorkspace', { scope: root }, deps)) as {diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.tsindex f422f6a0f5b..81c202dd68c 100644--- a/packages/device-control/src/dispatch.ts+++ b/packages/device-control/src/dispatch.ts@@ -100,10 +100,16 @@ export const DEVICE_RPC_METHODS = ['pushGitBranch','revertGitFile','listListeningPorts',+ 'getAppUpdateState',+ 'checkAppUpdate',+ 'installAppUpdate',] as const;export type DeviceRpcMethod = (typeof DEVICE_RPC_METHODS)[number];+/** Why a client without the app-update handlers rejects those RPCs. */+export const APP_UPDATE_UNSUPPORTED_MESSAGE = 'This device client does not support remote updates';+/*** Dispatch a generic server-internal device RPC by method name. This is the* single device-control entry point shared by the desktop main process@@ -318,6 +324,23 @@ export const executeDeviceRpc = async (return revertGitFile(params as { filePath: string; path: string });}+ // Remote app update: only a client that can update itself (the desktop+ // app) injects these, so the CLI answers with a stable reason instead.+ case 'getAppUpdateState': {+ if (!deps.getAppUpdateState) throw new Error(APP_UPDATE_UNSUPPORTED_MESSAGE);+ return deps.getAppUpdateState();+ }++ case 'checkAppUpdate': {+ if (!deps.checkAppUpdate) throw new Error(APP_UPDATE_UNSUPPORTED_MESSAGE);+ return deps.checkAppUpdate();+ }++ case 'installAppUpdate': {+ if (!deps.installAppUpdate) throw new Error(APP_UPDATE_UNSUPPORTED_MESSAGE);+ return deps.installAppUpdate();+ }+default: {throw new Error(`Unknown device RPC method: ${method}`);}diff --git a/packages/device-control/src/index.ts b/packages/device-control/src/index.tsindex 3237d73960e..10a14fbae4d 100644--- a/packages/device-control/src/index.ts+++ b/packages/device-control/src/index.ts@@ -1,5 +1,10 @@export { getCodexQuota, type GetCodexQuotaParams } from './codexQuota';-export { DEVICE_RPC_METHODS, type DeviceRpcMethod, executeDeviceRpc } from './dispatch';+export {+ APP_UPDATE_UNSUPPORTED_MESSAGE,+ DEVICE_RPC_METHODS,+ type DeviceRpcMethod,+ executeDeviceRpc,+} from './dispatch';export {defaultCopyAssetForPublish,defaultGetLocalFilePreview,diff --git a/packages/device-control/src/types.ts b/packages/device-control/src/types.tsindex c29d26b6ca7..2abe2b50210 100644--- a/packages/device-control/src/types.ts+++ b/packages/device-control/src/types.ts@@ -273,6 +273,14 @@ export interface WorkspaceScanDeps {* (`defaultGetLocalFilePreview`, `defaultGetProjectFileIndex`).*/export interface DeviceControlDeps extends SkillDirectoryDeps, WorkspaceScanDeps {+ /**+ * Start an app update check on this client; an available update downloads+ * automatically. Returns right away with the updated state — callers poll+ * {@link DeviceControlDeps.getAppUpdateState} for progress. Optional: only+ * the desktop app can update itself, so the CLI omits the three app-update+ * handlers and the dispatcher fails the RPC with a stable reason.+ */+ checkAppUpdate?: () => Promise<AppUpdateState>;/** Copy a publish asset (possibly outside the workspace) to a path inside the workspace. */copyAssetForPublish?: (params: CopyAssetForPublishParams) => Promise<CopyAssetForPublishResult>;/**@@ -285,10 +293,17 @@ export interface DeviceControlDeps extends SkillDirectoryDeps, WorkspaceScanDeps* the RPC with a clear reason.*/enrollWorkspace?: (params: EnrollWorkspaceParams) => Promise<EnrollWorkspaceResult>;+ /** Where this client's app update stands: current version, stage, progress. */+ getAppUpdateState?: () => Promise<AppUpdateState>;/** Read a local file preview (host-gated on desktop; disk read on CLI). */getLocalFilePreview: (params: LocalFilePreviewUrlParams) => Promise<LocalFilePreviewResult>;/** Build the project file index. */getProjectFileIndex: (params: ProjectFileIndexParams) => Promise<ProjectFileIndexResult>;+ /**+ * Restart into a downloaded update. Resolves before the app quits so the+ * response still reaches the caller; rejects when nothing is downloaded.+ */+ installAppUpdate?: () => Promise<InstallAppUpdateResult>;/** Query a heterogeneous CLI's model catalog on this execution host. */listHeterogeneousAgentModels?: (params: ListHeterogeneousAgentModelsParams,@@ -383,3 +398,28 @@ export interface EnrollWorkspaceResult {export interface UnenrollWorkspaceParams {workspaceId: string;}++// ─── Remote app update ───++/**+ * Structural mirror of the desktop updater's stage, plus `unsupported` for a+ * client that can't update itself (a dev build, or updates turned off).+ */+export type AppUpdateStage =+ 'checking' | 'downloaded' | 'downloading' | 'error' | 'idle' | 'latest' | 'unsupported';++export interface AppUpdateState {+ /** Version the client is running right now. */+ currentVersion: string;+ errorMessage?: string;+ /** Download progress, 0–100. Present while `stage` is `downloading`. */+ progress?: number;+ stage: AppUpdateStage;+ /** Version being downloaded or ready to install. */+ targetVersion?: string;+}++export interface InstallAppUpdateResult {+ /** Version the client restarts into. */+ targetVersion: string;+}diff --git a/packages/device-gateway-client/src/http.test.ts b/packages/device-gateway-client/src/http.test.tsindex ac81cb7713b..9a332cb6b9d 100644--- a/packages/device-gateway-client/src/http.test.ts+++ b/packages/device-gateway-client/src/http.test.ts@@ -817,6 +817,21 @@ describe('GatewayHttpClient', () => {});});+ it('forwards the preferred channel when one is given', async () => {+ mockFetch({ json: vi.fn().mockResolvedValue({ data: {}, success: true }), ok: true });++ await client.invokeRpc(+ { channel: 'desktop', deviceId: 'device-1', userId: 'user-1' },+ { method: 'getAppUpdateState' },+ );++ const [, init] = vi.mocked(fetch).mock.calls[0];+ expect(JSON.parse((init as any).body)).toMatchObject({+ channel: 'desktop',+ method: 'getAppUpdateState',+ });+ });+it('returns failure on non-ok response', async () => {mockFetch({ ok: false, status: 503, text: vi.fn().mockResolvedValue('offline') });diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.tsindex 2b6a953d1f0..c2a385fc74f 100644--- a/packages/device-gateway-client/src/http.ts+++ b/packages/device-gateway-client/src/http.ts@@ -315,9 +315,20 @@ export class GatewayHttpClient {* dispatcher and correlates the response by `requestId`, so new methods need* no per-method gateway route. Distinct from {@link executeToolCall}, which is* the LLM-facing tool channel.+ *+ * `channel` names the connection to prefer when one device holds several+ * (e.g. `desktop` alongside `cli`). A gateway that predates the hint ignores+ * it and picks by its own channel priority, so callers must still handle an+ * answer from another channel.*/async invokeRpc<T = unknown>(- params: { deviceId?: string; timeout?: number; userId: string; workspaceId?: string },+ params: {+ channel?: string;+ deviceId?: string;+ timeout?: number;+ userId: string;+ workspaceId?: string;+ },rpc: { method: string; params?: unknown },): Promise<DeviceRpcResult<T>> {const timeout =@@ -327,6 +338,7 @@ export class GatewayHttpClient {const res = await this.post('/api/device/rpc',{+ channel: params.channel,deviceId: params.deviceId,method: rpc.method,params: rpc.params,diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 9136646188e..c5a5ff2a66f 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -610,7 +610,27 @@ export default {'devices.actions.edit': 'Edit','devices.actions.refresh': 'Refresh','devices.actions.remove': 'Remove',+ 'devices.appUpdate.checkFailed': "Couldn't check for updates: {{message}}",+ 'devices.appUpdate.confirmDesc':+ 'LobeHub on this device will quit and restart. Anything it is running, including agent tasks, will be interrupted.',+ 'devices.appUpdate.confirmTitle': 'Restart and update to v{{version}}?',+ 'devices.appUpdate.downloading': 'Downloading v{{version}}',+ 'devices.appUpdate.installFailed':+ "The device came back on v{{version}}, so the update didn't apply. Check for updates to try again.",+ 'devices.appUpdate.ready': 'v{{version}} is downloaded and ready to install',+ 'devices.appUpdate.restarting': 'Restarting…',+ 'devices.appUpdate.restartingHint': 'Waiting for the device to come back on v{{version}}',+ 'devices.appUpdate.timedOut':+ "The device hasn't come back online. Check the app on that machine.",+ 'devices.appUpdate.unavailable': "Couldn't read the desktop app's update status. Try again.",+ 'devices.appUpdate.unsupported.cli':+ 'lh connect answered instead of the desktop app. Stop lh connect on this device, then try again.',+ 'devices.appUpdate.unsupported.devBuild': "Development builds can't update themselves.",+ 'devices.appUpdate.unsupported.outdated':+ "This app version can't be updated remotely. Update it once on the device to enable remote updates.",+ 'devices.appUpdate.updated': 'Updated to v{{version}}','devices.channel.connected': 'Connected {{time}}',+ 'devices.channel.unknown': 'Unknown client','devices.currentBadge': 'This device','devices.detail.addDir': 'Add directory','devices.detail.connections': 'Connections',diff --git a/packages/types/src/device.ts b/packages/types/src/device.tsindex 232b3e99d2c..695b3b1f6bc 100644--- a/packages/types/src/device.ts+++ b/packages/types/src/device.ts@@ -372,6 +372,12 @@ export interface DeviceListItem {hostname: string | null;identitySource: string | null;lastSeen: string;+ /**+ * What the client reported about itself on its last connect — the desktop+ * app sends `appVersion` (plus runtime versions), the CLI `cliVersion`.+ * `undefined` for ghost rows.+ */+ metadata?: Record<string, string> | null;online: boolean;platform: string | null;registered: boolean;@@ -970,3 +976,35 @@ export interface DeviceListeningPortsResult {/** False when the device has no detector for its platform. */supported: boolean;}++// ─── Remote app update ───++/** Mirrors `@lobechat/device-control`'s `AppUpdateStage`. */+export type DeviceAppUpdateStage =+ 'checking' | 'downloaded' | 'downloading' | 'error' | 'idle' | 'latest' | 'unsupported';++/** Where a device's desktop app update stands, as the device reports it. */+export interface DeviceAppUpdateState {+ currentVersion: string;+ errorMessage?: string;+ /** Download progress, 0–100, while `stage` is `downloading`. */+ progress?: number;+ stage: DeviceAppUpdateStage;+ /** Version being downloaded or ready to install. */+ targetVersion?: string;+}++/**+ * Why a device couldn't take part in a remote update:+ * - `unsupported` — the connected client can't update itself remotely (an+ * older desktop build, or the CLI answered in the desktop app's place).+ * - `unavailable` — the device didn't answer (offline, restarting, timeout).+ */+export type DeviceAppUpdateFailure = 'unavailable' | 'unsupported';++export type DeviceAppUpdateStateResult =+ | { state: DeviceAppUpdateState; status: 'ok' }+ | { message: string; status: DeviceAppUpdateFailure };++export type DeviceAppUpdateInstallResult =+ { status: 'ok'; targetVersion: string } | { message: string; status: DeviceAppUpdateFailure };diff --git a/src/features/DeviceManager/AppUpdate/deriveAppUpdateView.test.ts b/src/features/DeviceManager/AppUpdate/deriveAppUpdateView.test.tsnew file mode 100644index 00000000000..0fafcc428df--- /dev/null+++ b/src/features/DeviceManager/AppUpdate/deriveAppUpdateView.test.ts@@ -0,0 +1,124 @@+import type { DeviceAppUpdateState, DeviceAppUpdateStateResult } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { deriveAppUpdateView, getAppUpdateAction, isAppUpdatePolling } from './deriveAppUpdateView';++const ok = (state: Partial<DeviceAppUpdateState>): DeviceAppUpdateStateResult => ({+ state: { currentVersion: '2.1.0', stage: 'idle', ...state },+ status: 'ok',+});++const install = { targetVersion: '2.2.0', timedOut: false };++describe('deriveAppUpdateView', () => {+ it('shows download progress toward the target version', () => {+ expect(+ deriveAppUpdateView(+ ok({ progress: 40, stage: 'downloading', targetVersion: '2.2.0' }),+ null,+ false,+ ),+ ).toEqual({ kind: 'downloading', progress: 40, targetVersion: '2.2.0' });+ });++ it('offers the install once the update is downloaded', () => {+ expect(+ deriveAppUpdateView(ok({ stage: 'downloaded', targetVersion: '2.2.0' }), null, false),+ ).toEqual({ kind: 'ready', targetVersion: '2.2.0' });+ });++ it('keeps the check outcome so the user sees the answer', () => {+ expect(deriveAppUpdateView(ok({ stage: 'latest' }), null, false)).toEqual({+ kind: 'idle',+ outcome: 'latest',+ });+ expect(+ deriveAppUpdateView(ok({ errorMessage: 'net down', stage: 'error' }), null, false),+ ).toEqual({ kind: 'idle', outcome: { error: 'net down' } });+ });++ it('tells a dev build apart from an outdated client', () => {+ expect(deriveAppUpdateView(ok({ stage: 'unsupported' }), null, false)).toEqual({+ kind: 'unsupported',+ reason: 'devBuild',+ });+ const rejected: DeviceAppUpdateStateResult = { message: 'x', status: 'unsupported' };+ expect(deriveAppUpdateView(rejected, null, false)).toEqual({+ kind: 'unsupported',+ reason: 'outdated',+ });+ });++ it('blames lh connect when the CLI answered for a device that runs both', () => {+ expect(deriveAppUpdateView({ message: 'x', status: 'unsupported' }, null, true)).toEqual({+ kind: 'unsupported',+ reason: 'cli',+ });+ });++ describe('while restarting into an update', () => {+ it('waits while the old process is still answering before it quits', () => {+ expect(+ deriveAppUpdateView(ok({ stage: 'downloaded', targetVersion: '2.2.0' }), install, false),+ ).toEqual({ kind: 'restarting', targetVersion: '2.2.0' });+ });++ it('waits while the device is offline', () => {+ expect(+ deriveAppUpdateView({ message: 'offline', status: 'unavailable' }, install, false),+ ).toEqual({ kind: 'restarting', targetVersion: '2.2.0' });+ });++ it('succeeds only when the device comes back on the target version', () => {+ expect(deriveAppUpdateView(ok({ currentVersion: '2.2.0' }), install, false)).toEqual({+ kind: 'updated',+ version: '2.2.0',+ });+ });++ it('fails when the device comes back on another version', () => {+ expect(deriveAppUpdateView(ok({ currentVersion: '2.1.0' }), install, false)).toEqual({+ currentVersion: '2.1.0',+ kind: 'installFailed',+ });+ });++ it('gives up after the wait window', () => {+ expect(+ deriveAppUpdateView(+ { message: 'offline', status: 'unavailable' },+ { ...install, timedOut: true },+ false,+ ),+ ).toEqual({ kind: 'timedOut', targetVersion: '2.2.0' });+ });+ });+});++describe('isAppUpdatePolling', () => {+ it('polls only while the device owns the next state', () => {+ expect(isAppUpdatePolling({ kind: 'checking' })).toBe(true);+ expect(isAppUpdatePolling({ kind: 'downloading' })).toBe(true);+ expect(isAppUpdatePolling({ kind: 'restarting', targetVersion: '2.2.0' })).toBe(true);+ expect(isAppUpdatePolling({ kind: 'ready', targetVersion: '2.2.0' })).toBe(false);+ expect(isAppUpdatePolling({ kind: 'idle', outcome: 'latest' })).toBe(false);+ });+});++describe('getAppUpdateAction', () => {+ it('offers a retry when the device state could not be read', () => {+ expect(getAppUpdateAction({ kind: 'unavailable' })).toBe('retry');+ });++ it('offers a fresh check after an idle, failed or timed-out update', () => {+ expect(getAppUpdateAction({ kind: 'idle' })).toBe('check');+ expect(getAppUpdateAction({ currentVersion: '2.1.0', kind: 'installFailed' })).toBe('check');+ expect(getAppUpdateAction({ kind: 'timedOut', targetVersion: '2.2.0' })).toBe('check');+ });++ it('offers nothing once the outcome is settled or unsupported', () => {+ expect(getAppUpdateAction({ kind: 'updated', version: '2.2.0' })).toBeUndefined();+ expect(getAppUpdateAction({ kind: 'unsupported', reason: 'cli' })).toBeUndefined();+ expect(getAppUpdateAction({ kind: 'loading' })).toBeUndefined();+ });+});diff --git a/src/features/DeviceManager/AppUpdate/deriveAppUpdateView.ts b/src/features/DeviceManager/AppUpdate/deriveAppUpdateView.tsnew file mode 100644index 00000000000..f9ad354f9fe--- /dev/null+++ b/src/features/DeviceManager/AppUpdate/deriveAppUpdateView.ts@@ -0,0 +1,123 @@+import type { DeviceAppUpdateStateResult } from '@lobechat/types';++/** A restart the user asked for, followed until the device comes back. */+export interface AppUpdateInstall {+ targetVersion: string;+ /** No answer on the target version within the wait window. */+ timedOut: boolean;+}++export type AppUpdateUnsupportedReason = 'cli' | 'devBuild' | 'outdated';++export type AppUpdateView =+ | { kind: 'loading' }+ | { kind: 'unavailable' }+ | { kind: 'unsupported'; reason: AppUpdateUnsupportedReason }+ | { kind: 'idle'; outcome?: 'latest' | { error: string } }+ | { kind: 'checking' }+ | { kind: 'downloading'; progress?: number; targetVersion?: string }+ | { kind: 'ready'; targetVersion: string }+ | { kind: 'restarting'; targetVersion: string }+ | { kind: 'updated'; version: string }+ | { kind: 'installFailed'; currentVersion: string }+ | { kind: 'timedOut'; targetVersion: string };++/**+ * Turn the device's latest answer (plus a restart in flight) into what the+ * version section shows.+ *+ * During a restart the device first stays on the old version (it quits after+ * answering), then drops offline, then reconnects. Only a reconnect on the+ * target version is success; a reconnect on anything else — the fresh process+ * no longer holds a downloaded update — means the install didn't apply.+ */+export const deriveAppUpdateView = (+ result: DeviceAppUpdateStateResult | undefined,+ install: AppUpdateInstall | null,+ hasCliChannel: boolean,+): AppUpdateView => {+ if (install) {+ if (result?.status === 'ok') {+ const { currentVersion, stage } = result.state;+ if (currentVersion === install.targetVersion)+ return { kind: 'updated', version: currentVersion };+ if (stage !== 'downloaded') return { currentVersion, kind: 'installFailed' };+ }+ return install.timedOut+ ? { kind: 'timedOut', targetVersion: install.targetVersion }+ : { kind: 'restarting', targetVersion: install.targetVersion };+ }++ if (!result) return { kind: 'loading' };+ if (result.status !== 'ok') {+ if (result.status === 'unavailable') return { kind: 'unavailable' };+ // One device can hold both the desktop app and `lh connect`; when the CLI+ // answers, the desktop app is not the outdated party.+ return { kind: 'unsupported', reason: hasCliChannel ? 'cli' : 'outdated' };+ }++ const { errorMessage, progress, stage, targetVersion } = result.state;+ switch (stage) {+ case 'unsupported': {+ return { kind: 'unsupported', reason: 'devBuild' };+ }+ case 'checking': {+ return { kind: 'checking' };+ }+ case 'downloading': {+ return { kind: 'downloading', progress, targetVersion };+ }+ case 'downloaded': {+ return targetVersion ? { kind: 'ready', targetVersion } : { kind: 'idle' };+ }+ case 'latest': {+ return { kind: 'idle', outcome: 'latest' };+ }+ case 'error': {+ return { kind: 'idle', outcome: { error: errorMessage ?? '' } };+ }+ default: {+ return { kind: 'idle' };+ }+ }+};++/** Views whose next state only the device can tell us, so the section polls. */+export const isAppUpdatePolling = (view: AppUpdateView): boolean =>+ view.kind === 'checking' || view.kind === 'downloading' || view.kind === 'restarting';++/**+ * Which button the desktop app's row offers. Every state the user can act on+ * keeps one — `unavailable` isn't polled, so without a retry the section would+ * stay stuck until the panel is reopened.+ */+export type AppUpdateAction =+ 'check' | 'retry' | 'checking' | 'downloading' | 'install' | 'restarting';++export const getAppUpdateAction = (view: AppUpdateView): AppUpdateAction | undefined => {+ switch (view.kind) {+ case 'idle':+ case 'installFailed':+ case 'timedOut': {+ return 'check';+ }+ case 'unavailable': {+ return 'retry';+ }+ case 'checking': {+ return 'checking';+ }+ case 'downloading': {+ return 'downloading';+ }+ case 'ready': {+ return 'install';+ }+ case 'restarting': {+ return 'restarting';+ }+ default: {+ return undefined;+ }+ }+};diff --git a/src/features/DeviceManager/AppUpdate/index.tsx b/src/features/DeviceManager/AppUpdate/index.tsxnew file mode 100644index 00000000000..f071863b04a--- /dev/null+++ b/src/features/DeviceManager/AppUpdate/index.tsx@@ -0,0 +1,154 @@+'use client';++import { Button, confirmModal, Text } from '@lobehub/ui/base-ui';+import type { CSSProperties, ReactNode } from 'react';+import { useTranslation } from 'react-i18next';++import { type AppUpdateView, getAppUpdateAction } from './deriveAppUpdateView';+import type { DeviceAppUpdate } from './useDeviceAppUpdate';++export { useDeviceAppUpdate } from './useDeviceAppUpdate';++interface AppUpdateProps {+ update: DeviceAppUpdate;+}++/**+ * The remote-update button on the desktop app's connection row: check →+ * download (with progress) → restart into the new version.+ */+export const AppUpdateAction = ({ update }: AppUpdateProps) => {+ const { t } = useTranslation(['setting', 'common']);+ const { check, install, refreshing, requesting, retry, view } = update;++ const confirmInstall = (targetVersion: string) =>+ confirmModal({+ cancelText: t('common:cancel'),+ content: t('devices.appUpdate.confirmDesc'),+ okText: t('common:restartToUpdate'),+ onOk: install,+ title: t('devices.appUpdate.confirmTitle', { version: targetVersion }),+ });++ switch (getAppUpdateAction(view)) {+ case 'check': {+ return (+ <Button loading={requesting} size={'small'} type={'text'} onClick={check}>+ {t('common:checkForUpdates')}+ </Button>+ );+ }+ case 'retry': {+ return (+ <Button loading={refreshing} size={'small'} type={'text'} onClick={retry}>+ {t('common:retry')}+ </Button>+ );+ }+ case 'checking': {+ return (+ <Button loading size={'small'} type={'text'}>+ {t('common:checkForUpdates')}+ </Button>+ );+ }+ case 'downloading': {+ return (+ <Button loading size={'small'} type={'text'}>+ {t('common:downloadingUpdate', {+ percent: view.kind === 'downloading' ? (view.progress ?? 0) : 0,+ })}+ </Button>+ );+ }+ case 'install': {+ return (+ view.kind === 'ready' && (+ <Button+ loading={requesting}+ size={'small'}+ type={'fill'}+ onClick={() => confirmInstall(view.targetVersion)}+ >+ {t('common:restartToUpdate')}+ </Button>+ )+ );+ }+ case 'restarting': {+ return (+ <Button loading size={'small'} type={'text'}>+ {t('devices.appUpdate.restarting')}+ </Button>+ );+ }+ default: {+ return null;+ }+ }+};++interface AppUpdateHintProps extends AppUpdateProps {+ style?: CSSProperties;+}++/** Where the update stands, on its own line under the desktop app's connection. */+export const AppUpdateHint = ({ style, update }: AppUpdateHintProps) => {+ const { t } = useTranslation(['setting', 'common']);+ const { view } = update;++ const renderHint = (current: AppUpdateView): ReactNode => {+ switch (current.kind) {+ case 'idle': {+ if (current.outcome === 'latest') return t('common:alreadyUpToDate');+ if (current.outcome)+ return t('devices.appUpdate.checkFailed', { message: current.outcome.error });+ return null;+ }+ case 'unavailable': {+ return t('devices.appUpdate.unavailable');+ }+ case 'downloading': {+ return current.targetVersion+ ? t('devices.appUpdate.downloading', { version: current.targetVersion })+ : null;+ }+ case 'ready': {+ return t('devices.appUpdate.ready', { version: current.targetVersion });+ }+ case 'restarting': {+ return t('devices.appUpdate.restartingHint', { version: current.targetVersion });+ }+ case 'updated': {+ return t('devices.appUpdate.updated', { version: current.version });+ }+ case 'installFailed': {+ return t('devices.appUpdate.installFailed', { version: current.currentVersion });+ }+ case 'timedOut': {+ return t('devices.appUpdate.timedOut');+ }+ case 'unsupported': {+ return t(`devices.appUpdate.unsupported.${current.reason}`);+ }+ default: {+ return null;+ }+ }+ };++ const hint = renderHint(view);+ if (!hint) return null;++ const failed =+ view.kind === 'installFailed' ||+ view.kind === 'timedOut' ||+ view.kind === 'unavailable' ||+ (view.kind === 'idle' && typeof view.outcome === 'object');++ return (+ <Text fontSize={12} style={style} type={failed ? 'danger' : 'secondary'}>+ {hint}+ </Text>+ );+};diff --git a/src/features/DeviceManager/AppUpdate/useDeviceAppUpdate.ts b/src/features/DeviceManager/AppUpdate/useDeviceAppUpdate.tsnew file mode 100644index 00000000000..705072a74bb--- /dev/null+++ b/src/features/DeviceManager/AppUpdate/useDeviceAppUpdate.ts@@ -0,0 +1,119 @@+import type { DeviceAppUpdateStateResult } from '@lobechat/types';+import { toast } from '@lobehub/ui/base-ui';+import { useEffect, useState } from 'react';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { useClientDataSWR } from '@/libs/swr';+import { deviceKeys } from '@/libs/swr/keys';+import { deviceService } from '@/services/device';++import { refreshDeviceList } from '../const';+import {+ type AppUpdateInstall,+ deriveAppUpdateView,+ isAppUpdatePolling,+} from './deriveAppUpdateView';++const PROGRESS_POLL_MS = 1000;+/** A restart takes tens of seconds; asking faster only piles up timeouts. */+const RESTART_POLL_MS = 3000;+/** How long to wait for the device to come back after the restart. */+const RESTART_TIMEOUT_MS = 5 * 60_000;++interface UseDeviceAppUpdateParams {+ deviceId: string;+ /** Whether the device can take a remote update request right now. */+ enabled: boolean;+ /** Whether `lh connect` shares this device with the desktop app. */+ hasCliChannel: boolean;+}++/**+ * Drive a remote desktop-app update on one device: read where its update+ * stands, start a check, and restart it into the downloaded version — then+ * follow it until it reconnects on that version.+ */+export const useDeviceAppUpdate = ({+ deviceId,+ enabled,+ hasCliChannel,+}: UseDeviceAppUpdateParams) => {+ const workspaceId = useActiveWorkspaceId();+ const [install, setInstall] = useState<AppUpdateInstall | null>(null);+ const [requesting, setRequesting] = useState(false);++ const { data, isValidating, mutate } = useClientDataSWR<DeviceAppUpdateStateResult>(+ // A restart in flight keeps polling even while the device drops offline.+ enabled || install ? deviceKeys.appUpdateState(workspaceId, deviceId) : null,+ () => deviceService.getAppUpdateState({ deviceId }),+ {+ refreshInterval: (latest) => {+ if (!isAppUpdatePolling(deriveAppUpdateView(latest, install, hasCliChannel))) return 0;+ return install ? RESTART_POLL_MS : PROGRESS_POLL_MS;+ },+ revalidateOnFocus: false,+ },+ );++ const view = deriveAppUpdateView(data, install, hasCliChannel);++ useEffect(() => {+ if (!install || install.timedOut) return;+ const timer = setTimeout(+ () => setInstall((current) => current && { ...current, timedOut: true }),+ RESTART_TIMEOUT_MS,+ );+ return () => clearTimeout(timer);+ }, [install]);++ // The device reconnected — on the new version or not — so the list now+ // carries its fresh connection and registered version.+ const reconnected = view.kind === 'updated' || view.kind === 'installFailed';+ useEffect(() => {+ if (reconnected) refreshDeviceList();+ }, [reconnected]);++ const request = async (run: () => Promise<void>) => {+ setRequesting(true);+ try {+ await run();+ } catch (error) {+ toast.error((error as Error).message);+ } finally {+ setRequesting(false);+ }+ };++ const check = () =>+ request(async () => {+ setInstall(null);+ const result = await deviceService.checkAppUpdate({ deviceId });+ await mutate(result, { revalidate: false });+ });++ const installUpdate = () =>+ request(async () => {+ const result = await deviceService.installAppUpdate({ deviceId });+ if (result.status === 'ok') {+ setInstall({ targetVersion: result.targetVersion, timedOut: false });+ return;+ }+ // Show why the device refused (outdated client, offline) in place.+ await mutate(result, { revalidate: false });+ });++ return {+ check,+ /** What the device itself says it runs, when it answered. */+ currentVersion: data?.status === 'ok' ? data.state.currentVersion : undefined,+ install: installUpdate,+ /** A read of the device's state is in flight. */+ refreshing: isValidating,+ requesting,+ /** Ask the device again — an `unavailable` answer is not polled on its own. */+ retry: () => mutate(),+ view,+ };+};++export type DeviceAppUpdate = ReturnType<typeof useDeviceAppUpdate>;diff --git a/src/features/DeviceManager/Connections.tsx b/src/features/DeviceManager/Connections.tsxnew file mode 100644index 00000000000..e083595f27d--- /dev/null+++ b/src/features/DeviceManager/Connections.tsx@@ -0,0 +1,129 @@+'use client';++import type { DeviceListItem } from '@lobechat/types';+import { Block, Flexbox } from '@lobehub/ui';+import { Tag, Text } from '@lobehub/ui/base-ui';+import dayjs from 'dayjs';+import type { ReactNode } from 'react';+import { useTranslation } from 'react-i18next';++import { AppUpdateAction, AppUpdateHint, useDeviceAppUpdate } from './AppUpdate';+import { getChannelKind, getChannelVersion } from './channelKind';+import FieldLabel from './FieldLabel';+import PresenceDot from './PresenceDot';++interface ConnectionCardProps {+ channel: string;+ /** Second line for anything beyond the connection itself, e.g. update progress. */+ detail?: ReactNode;+ /** Right-aligned action, e.g. the desktop app's update button. */+ extra?: ReactNode;+ /** False while the client is away, e.g. restarting into an update. */+ live: boolean;+ /** How long it's been connected (or that it's away). */+ status: ReactNode;+ version?: string;+}++/**+ * One client connection: state dot, client, version, connection status and+ * action on one baseline-aligned line; anything more goes on a second line.+ */+const ConnectionCard = ({ channel, detail, extra, live, status, version }: ConnectionCardProps) => (+ <Block gap={4} paddingBlock={8} paddingInline={12} variant={'outlined'}>+ <Flexbox horizontal align={'baseline'} gap={8}>+ <Text style={{ flex: 'none' }}>+ <PresenceDot live={live} />+ </Text>+ <Text weight={500}>{channel}</Text>+ {version && <Tag size={'small'}>v{version}</Tag>}+ <Flexbox flex={1} style={{ minWidth: 0 }}>+ {status}+ </Flexbox>+ {extra}+ </Flexbox>+ {detail}+ </Block>+);++interface ConnectionsProps {+ canEdit: boolean;+ device: DeviceListItem;+}++/**+ * The device's live connections, one card per client with the version it runs.+ * The desktop app's card also carries its remote update — confirmed only once+ * the device reconnects on the new version.+ */+const Connections = ({ canEdit, device }: ConnectionsProps) => {+ const { t } = useTranslation('setting');++ const channels = device.channels ?? [];+ const kinds = channels.map((c) => getChannelKind(c.channel));+ const desktopIndex = kinds.indexOf('desktop');+ const hasDesktopChannel = desktopIndex !== -1;++ const update = useDeviceAppUpdate({+ deviceId: device.deviceId,+ enabled: canEdit && hasDesktopChannel,+ hasCliChannel: kinds.includes('cli'),+ });++ // A restart drops the desktop app offline; keep following it in place of+ // its card until it reconnects.+ const restartInFlight =+ !hasDesktopChannel && update.view.kind !== 'loading' && update.view.kind !== 'unavailable';++ const plainStatus = (text: string) => (+ <Text ellipsis fontSize={12} type={'secondary'}>+ {text}+ </Text>+ );++ const desktopCard = (channel: string, connectedText: string, live: boolean, key?: string) => (+ <ConnectionCard+ channel={channel}+ detail={<AppUpdateHint style={{ paddingInlineStart: 16 }} update={update} />}+ extra={canEdit ? <AppUpdateAction update={update} /> : undefined}+ key={key}+ live={live}+ status={plainStatus(connectedText)}+ version={getChannelVersion('desktop', device.metadata, update.currentVersion)}+ />+ );++ return (+ <Flexbox gap={8}>+ <FieldLabel>{t('devices.detail.connections')}</FieldLabel>+ {channels.map((channel, index) => {+ const key = `${channel.connectedAt}-${index}`;+ const label = channel.channel ?? t('devices.channel.unknown');+ const connectedText = t('devices.channel.connected', {+ time: dayjs(channel.connectedAt).fromNow(),+ });+ if (index === desktopIndex) return desktopCard(label, connectedText, true, key);++ return (+ <ConnectionCard+ live+ channel={label}+ key={key}+ status={plainStatus(connectedText)}+ version={getChannelVersion(kinds[index], device.metadata)}+ />+ );+ })}+ {restartInFlight && desktopCard('desktop', t('devices.status.offline'), false)}+ {channels.length === 0 &&+ !restartInFlight &&+ plainStatus(+ `${t('devices.status.offline')} · ${t('devices.lastSeen', {+ time: dayjs(device.lastSeen).fromNow(),+ })}`,+ )}+ </Flexbox>+ );+};++export default Connections;diff --git a/src/features/DeviceManager/DeviceDetailPanel.tsx b/src/features/DeviceManager/DeviceDetailPanel.tsxindex 9be1092f968..3fec5ed3b9a 100644--- a/src/features/DeviceManager/DeviceDetailPanel.tsx+++ b/src/features/DeviceManager/DeviceDetailPanel.tsx@@ -5,9 +5,8 @@ import type { DeviceListItem, DeviceWorkspaceShare } from '@lobechat/types';import { Flexbox, Icon, Input, SortableList } from '@lobehub/ui';import { ActionIcon, Avatar, Button, confirmModal, Tag, Text, toast } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar } from 'antd-style';-import dayjs from 'dayjs';import { FolderOpenIcon, FolderPlusIcon, LockIcon, XIcon } from 'lucide-react';-import { memo, type ReactNode, useState } from 'react';+import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';import DirIcon from '@/features/ChatInput/ControlBar/DirIcon';@@ -17,8 +16,11 @@ import { deviceService } from '@/services/device';import { electronSystemService } from '@/services/electron/system';import { nextWorkingDirs } from '@/store/device';+import Connections from './Connections';import { refreshDeviceList } from './const';+import FieldLabel from './FieldLabel';import { getDeviceIcon } from './getDeviceIcon';+import PresenceDot from './PresenceDot';import { useCanEditDevice } from './useCanEditDevice';const styles = createStaticStyles(({ css }) => ({@@ -38,12 +40,6 @@ const styles = createStaticStyles(({ css }) => ({height: 100%;min-height: 0;`,- dot: css`- flex: none;- width: 8px;- height: 8px;- border-radius: 50%;- `,header: css`flex: none;padding-block: 16px;@@ -82,16 +78,6 @@ const styles = createStaticStyles(({ css }) => ({`,}));-// Section label — one consistent treatment for every field heading in the panel.-const FieldLabel = memo<{ children: ReactNode; extra?: ReactNode }>(({ children, extra }) => (- <Flexbox horizontal align={'center'} distribution={'space-between'}>- <Text fontSize={12} type={'secondary'} weight={500}>- {children}- </Text>- {extra}- </Flexbox>-));-interface DeviceDetailPanelProps {device: DeviceListItem;isCurrent?: boolean;@@ -120,8 +106,7 @@ const DeviceDetailPanel = memo<DeviceDetailPanelProps>(({ device, isCurrent, onC// Only the machine you're on can browse its own filesystem natively.const canBrowse = !!isCurrent && isDesktop;- // Render the device's live connections straight from `device.channels` — one- // row per connection; an empty array means offline.+ // An empty `device.channels` means offline.const channels = device.channels ?? [];const online = channels.length > 0;@@ -243,17 +228,27 @@ const DeviceDetailPanel = memo<DeviceDetailPanelProps>(({ device, isCurrent, onC<Flexbox horizontal align={'center'} className={styles.header} gap={12}><span className={styles.iconTile}>{getDeviceIcon(device.platform, 18)}</span><Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>- <Text ellipsis weight={600}>- {device.friendlyName || device.hostname || device.deviceId}- </Text>- <Flexbox horizontal align={'center'} gap={8}>- <Tag color={online ? 'success' : 'default'} size={'small'}>- {online- ? t('devices.status.onlineConnections', { count: channels.length })- : t('devices.status.offline')}- </Tag>- {isCurrent && <Tag size={'small'}>{t('devices.currentBadge')}</Tag>}+ {/* Presence is a dot after the name; the connections below say which. */}+ <Flexbox horizontal align={'baseline'} gap={8} style={{ minWidth: 0 }}>+ <Text ellipsis weight={600}>+ {device.friendlyName || device.hostname || device.deviceId}+ </Text>+ <Text style={{ flex: 'none' }}>+ <PresenceDot+ live={online}+ title={+ online+ ? t('devices.status.onlineConnections', { count: channels.length })+ : t('devices.status.offline')+ }+ />+ </Text></Flexbox>+ {isCurrent && (+ <Flexbox horizontal>+ <Tag size={'small'}>{t('devices.currentBadge')}</Tag>+ </Flexbox>+ )}</Flexbox><ActionIcon icon={XIcon} size={'small'} onClick={onClose} /></Flexbox>@@ -312,29 +307,8 @@ const DeviceDetailPanel = memo<DeviceDetailPanelProps>(({ device, isCurrent, onC</Flexbox>)}- {/* ─── Connections ─── */}- <Flexbox gap={8}>- <FieldLabel>{t('devices.detail.connections')}</FieldLabel>- {channels.length > 0 ? (- channels.map((channel, index) => (- <Flexbox horizontal align={'center'} gap={8} key={`${channel.connectedAt}-${index}`}>- <span className={styles.dot} style={{ background: cssVar.colorSuccess }} />- {channel.channel && <Tag size={'small'}>{channel.channel}</Tag>}- <Text fontSize={12} type={'secondary'}>- {t('devices.channel.connected', { time: dayjs(channel.connectedAt).fromNow() })}- </Text>- </Flexbox>- ))- ) : (- <Flexbox horizontal align={'center'} gap={8}>- <span className={styles.dot} style={{ background: cssVar.colorTextQuaternary }} />- <Text fontSize={12} type={'secondary'}>- {t('devices.status.offline')} ·{' '}- {t('devices.lastSeen', { time: dayjs(device.lastSeen).fromNow() })}- </Text>- </Flexbox>- )}- </Flexbox>+ {/* ─── Connections, each with its client version; desktop carries the update ─── */}+ <Connections canEdit={canEdit} device={device} />{/* ─── Name ─── */}<Flexbox gap={8}>diff --git a/src/features/DeviceManager/DeviceManager.tsx b/src/features/DeviceManager/DeviceManager.tsxindex a324b6717e8..809f9e5b32a 100644--- a/src/features/DeviceManager/DeviceManager.tsx+++ b/src/features/DeviceManager/DeviceManager.tsx@@ -395,7 +395,8 @@ const DeviceManager = memo<DeviceManagerProps>((props) => {<FlexboxclassName={styles.listScroll}gap={2}- paddingBlock={4}+ // The personal page's card already insets the rows evenly.+ paddingBlock={isWorkspace ? 4 : 0}paddingInline={isWorkspace ? 4 : 0}>{devices.map((device) => (diff --git a/src/features/DeviceManager/FieldLabel.tsx b/src/features/DeviceManager/FieldLabel.tsxnew file mode 100644index 00000000000..21647f6e114--- /dev/null+++ b/src/features/DeviceManager/FieldLabel.tsx@@ -0,0 +1,15 @@+import { Flexbox } from '@lobehub/ui';+import { Text } from '@lobehub/ui/base-ui';+import type { ReactNode } from 'react';++/** Section label — one consistent treatment for every field heading in the detail panel. */+const FieldLabel = ({ children, extra }: { children: ReactNode; extra?: ReactNode }) => (+ <Flexbox horizontal align={'center'} distribution={'space-between'}>+ <Text fontSize={12} type={'secondary'} weight={500}>+ {children}+ </Text>+ {extra}+ </Flexbox>+);++export default FieldLabel;diff --git a/src/features/DeviceManager/PresenceDot.tsx b/src/features/DeviceManager/PresenceDot.tsxnew file mode 100644index 00000000000..70be7fb1681--- /dev/null+++ b/src/features/DeviceManager/PresenceDot.tsx@@ -0,0 +1,34 @@+import { createStaticStyles, cssVar } from 'antd-style';++const styles = createStaticStyles(({ css }) => ({+ dot: css`+ display: inline-block;++ width: 8px;+ height: 8px;+ border-radius: 50%;++ vertical-align: middle;+ `,+}));++interface PresenceDotProps {+ live: boolean;+ title?: string;+}++/**+ * A connection-state dot meant to sit on a text line: render it inside a+ * `Text` so `vertical-align: middle` centers it on that text's x-height.+ * Flex centering lines up boxes, not glyphs, and leaves the dot visibly off+ * next to lowercase text.+ */+const PresenceDot = ({ live, title }: PresenceDotProps) => (+ <span+ className={styles.dot}+ style={{ background: live ? cssVar.colorSuccess : cssVar.colorTextQuaternary }}+ title={title}+ />+);++export default PresenceDot;diff --git a/src/features/DeviceManager/channelKind.test.ts b/src/features/DeviceManager/channelKind.test.tsnew file mode 100644index 00000000000..17857a5e042--- /dev/null+++ b/src/features/DeviceManager/channelKind.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from 'vitest';++import { getChannelKind, getChannelVersion } from './channelKind';++describe('getChannelKind', () => {+ it('matches a client and its suffixed variants', () => {+ expect(getChannelKind('desktop')).toBe('desktop');+ expect(getChannelKind('desktop-dev')).toBe('desktop');+ expect(getChannelKind('cli')).toBe('cli');+ });++ it('ignores unknown or missing channels', () => {+ expect(getChannelKind('desktopish')).toBeUndefined();+ expect(getChannelKind('mobile')).toBeUndefined();+ expect(getChannelKind(null)).toBeUndefined();+ });+});++describe('getChannelVersion', () => {+ const metadata = { appVersion: '2.0.0', cliVersion: '0.0.60' };++ it('reads each client its own version from one merged registry row', () => {+ expect(getChannelVersion('desktop', metadata)).toBe('2.0.0');+ expect(getChannelVersion('cli', metadata)).toBe('0.0.60');+ });++ it('prefers the desktop app live answer over the registry', () => {+ expect(getChannelVersion('desktop', metadata, '2.1.0')).toBe('2.1.0');+ expect(getChannelVersion('cli', metadata, '2.1.0')).toBe('0.0.60');+ });++ it('returns nothing when the client never reported a version', () => {+ expect(getChannelVersion('cli', { appVersion: '2.0.0' })).toBeUndefined();+ expect(getChannelVersion(undefined, metadata)).toBeUndefined();+ expect(getChannelVersion('desktop', null)).toBeUndefined();+ });+});diff --git a/src/features/DeviceManager/channelKind.ts b/src/features/DeviceManager/channelKind.tsnew file mode 100644index 00000000000..b144ca93a46--- /dev/null+++ b/src/features/DeviceManager/channelKind.ts@@ -0,0 +1,33 @@+export type ChannelKind = 'cli' | 'desktop';++/**+ * Which client holds a gateway connection. Channels carry a suffix for variants+ * of the same client (`desktop-dev`), so match on the prefix.+ */+export const getChannelKind = (channel: string | null | undefined): ChannelKind | undefined => {+ if (!channel) return undefined;+ for (const kind of ['desktop', 'cli'] as const) {+ if (channel === kind || channel.startsWith(`${kind}-`)) return kind;+ }+ return undefined;+};++/** The metadata key each client reports its own version under on register. */+const VERSION_KEY: Record<ChannelKind, string> = {+ cli: 'cliVersion',+ desktop: 'appVersion',+};++/**+ * The version a connection's client runs. The desktop app's live answer beats+ * the registry, which only holds what it reported on its last connect.+ */+export const getChannelVersion = (+ kind: ChannelKind | undefined,+ metadata: Record<string, string> | null | undefined,+ liveDesktopVersion?: string,+): string | undefined => {+ if (!kind) return undefined;+ if (kind === 'desktop' && liveDesktopVersion) return liveDesktopVersion;+ return metadata?.[VERSION_KEY[kind]] || undefined;+};diff --git a/src/features/Settings/devices/index.tsx b/src/features/Settings/devices/index.tsxindex 28941e28098..fd403487ee3 100644--- a/src/features/Settings/devices/index.tsx+++ b/src/features/Settings/devices/index.tsx@@ -3,6 +3,7 @@import { isDesktop } from '@lobechat/const';import { Flexbox, Form, Icon } from '@lobehub/ui';import { ActionIcon, Button, Text } from '@lobehub/ui/base-ui';+import { createStaticStyles } from 'antd-style';import { MonitorUpIcon, RefreshCwIcon } from 'lucide-react';import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -21,6 +22,17 @@ import { useElectronStore } from '@/store/electron';import KeepAwake from './KeepAwake';+const styles = createStaticStyles(({ css }) => ({+ // The device rows carry their own padding and hover fill; a thin, even inset+ // keeps that fill the same distance from every edge of the card. The Form+ // zeroes the group body's block padding with !important, hence the override.+ listGroup: css`+ .ant-collapse-body {+ padding: 4px !important;+ }+ `,+}));+interface PageProps {mobile?: boolean;}@@ -54,6 +66,7 @@ const Page = memo<PageProps>(({ mobile }) => {const list = (<Flexbox gap={24}><Form+ classNames={{ group: styles.listGroup }}collapsible={false}itemsType={'group'}variant={'filled'}diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 1120aa061bb..42524197ce7 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -837,6 +837,11 @@ export const knowledgeBaseKeys = {// ---- device -------------------------------------------------------------export const deviceKeys = {+ appUpdateState: def('device:appUpdateState', (workspaceId: string | null, deviceId: string) => [+ 'device:appUpdateState',+ workspaceId,+ deviceId,+ ]),browseDirectory: def('device:browseDirectory',(workspaceId: string | null, deviceId: string, path?: string, cursor?: string) =>diff --git a/src/services/device.ts b/src/services/device.tsindex 588cea02ab5..726c73af916 100644--- a/src/services/device.ts+++ b/src/services/device.ts@@ -69,6 +69,21 @@ class DeviceService {return lambdaClient.device.listListeningPorts.query(input);}+ /** Where the device's desktop app update stands; never starts a check. */+ getAppUpdateState(input: Parameters<DeviceClient['getAppUpdateState']['query']>[0]) {+ return lambdaClient.device.getAppUpdateState.query(input);+ }++ /** Start an update check on the device; a found update downloads on its own. */+ checkAppUpdate(input: Parameters<DeviceClient['checkAppUpdate']['mutate']>[0]) {+ return lambdaClient.device.checkAppUpdate.mutate(input);+ }++ /** Restart the device's desktop app into its downloaded update. */+ installAppUpdate(input: Parameters<DeviceClient['installAppUpdate']['mutate']>[0]) {+ return lambdaClient.device.installAppUpdate.mutate(input);+ }+/** Revoke a link. */revokeTunnel(input: Parameters<DeviceClient['revokeTunnel']['mutate']>[0]) {return lambdaClient.device.revokeTunnel.mutate(input);