🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(device): add one-click reconnect for offline devices (#18949)
Arvin Xu31d62b7d2d8e
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.tsindex 0403cacc544..2afa561b8e6 100644--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts@@ -20,13 +20,14 @@ import { setDesktopUserAgentHeader } from '@/utils/user-agent';import BrowserControlCtr from './BrowserControlCtr';import HeterogeneousAgentCtr from './HeterogeneousAgentCtr';-import { ControllerModule, IpcMethod } from './index';+import { ControllerModule, createProtocolHandler, IpcMethod } from './index';import LocalFileCtr from './LocalFileCtr';import McpCtr from './McpCtr';import RemoteServerConfigCtr from './RemoteServerConfigCtr';import ShellCommandCtr from './ShellCommandCtr';const logger = createLogger('controllers:GatewayConnectionCtr');+const deviceProtocolHandler = createProtocolHandler('device');type AvailableRemotePlatformRuntime = Extract<RemotePlatformCommandRuntime, { available: true }>;@@ -132,6 +133,10 @@ export default class GatewayConnectionCtr extends ControllerModule {private readonly hermesSessionMap = new Map<string, string>();private localSystemRuntime: LocalSystemExecutionRuntime | null = null;+ private resolveGatewayReady: (() => void) | undefined;+ private readonly gatewayReady = new Promise<void>((resolve) => {+ this.resolveGatewayReady = resolve;+ });// ─── Service Accessor ───@@ -205,6 +210,8 @@ export default class GatewayConnectionCtr extends ControllerModule {this.checkWorkspaceDeviceRegistered(workspaceId, deviceId),);+ this.resolveGatewayReady?.();+// Auto-connect if already logged inthis.tryAutoConnect();}@@ -237,6 +244,24 @@ export default class GatewayConnectionCtr extends ControllerModule {return this.service.getDeviceInfo();}+ /**+ * Let the web app wake this desktop and restore its gateway connection from+ * an offline device row. The device id guard matters when the user has more+ * than one registered computer: opening the deep link on a different machine+ * must not silently connect that machine instead.+ */+ @deviceProtocolHandler('reconnect')+ async reconnectFromProtocol({ deviceId }: { deviceId?: string }): Promise<boolean> {+ if (!deviceId) return false;++ await this.gatewayReady;+ if (!(await this.service.matchesDeviceId(deviceId))) return false;++ this.app.storeManager.set('gatewayEnabled', true);+ const result = await this.service.connect();+ return result.success;+ }+// ─── Auto Connect ───private async tryAutoConnect() {diff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.tsindex 76a177ff611..c95ad7a37ee 100644--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts@@ -1,5 +1,7 @@import type * as ChildProcessModule from 'node:child_process';+import type * as CryptoModule from 'node:crypto';+import { deriveDeviceId, deriveScopedFallbackId } from '@lobechat/device-identity';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { App } from '@/core/App';@@ -179,7 +181,8 @@ vi.mock('@/const/env', () => ({isDev: false,}));-vi.mock('node:crypto', () => ({+vi.mock('node:crypto', async (importOriginal) => ({+ ...(await importOriginal<typeof CryptoModule>()),randomUUID: vi.fn(() => 'mock-device-uuid'),}));@@ -394,6 +397,66 @@ describe('GatewayConnectionCtr', () => {expect(mockStoreSet).toHaveBeenCalledWith('gatewayEnabled', true);});+ it('should reconnect the matching device from a protocol link', async () => {+ vi.mocked(mockRemoteServerConfigCtr.isRemoteServerConfigured).mockResolvedValueOnce(false);+ ctr.afterFirstFrame();+ await vi.advanceTimersByTimeAsync(0);+ mockStoreSet.mockClear();++ const { deviceId } = await ctr.getDeviceInfo();+ const result = await ctr.reconnectFromProtocol({ deviceId });++ expect(result).toBe(true);+ expect(mockStoreSet).toHaveBeenCalledWith('gatewayEnabled', true);+ });++ it('should wait for gateway initialization on a cold-start protocol reconnect', async () => {+ vi.mocked(mockRemoteServerConfigCtr.isRemoteServerConfigured).mockResolvedValueOnce(false);++ const reconnect = ctr.reconnectFromProtocol({ deviceId: 'mock-device-uuid' });+ await vi.advanceTimersByTimeAsync(0);+ expect(mockStoreSet).not.toHaveBeenCalledWith('gatewayEnabled', true);++ ctr.afterFirstFrame();+ await expect(reconnect).resolves.toBe(true);+ expect(mockStoreSet).toHaveBeenCalledWith('gatewayEnabled', true);+ });++ it('should reject a protocol reconnect intended for another device', async () => {+ vi.mocked(mockRemoteServerConfigCtr.isRemoteServerConfigured).mockResolvedValueOnce(false);+ ctr.afterFirstFrame();+ await vi.advanceTimersByTimeAsync(0);+ mockStoreSet.mockClear();++ const result = await ctr.reconnectFromProtocol({ deviceId: 'another-device' });++ expect(result).toBe(false);+ expect(mockStoreSet).not.toHaveBeenCalled();+ });++ it('should reconnect a persisted workspace identity for this machine', async () => {+ const workspaceId = 'workspace-1';+ const fallbackId = 'mock-device-uuid';+ mockStoreGet.mockImplementation((key: string) => {+ if (key === 'gatewayEnabled') return true;+ if (key === 'gatewayDeviceId') return fallbackId;+ if (key === 'gatewayWorkspaceEnrollments') return [workspaceId];+ return undefined;+ });+ vi.mocked(mockRemoteServerConfigCtr.isRemoteServerConfigured).mockResolvedValueOnce(false);+ ctr.afterFirstFrame();+ await vi.advanceTimersByTimeAsync(0);+ mockStoreSet.mockClear();++ const workspaceDevice = deriveDeviceId(`workspace:${workspaceId}`, {+ fallbackId: deriveScopedFallbackId(fallbackId, `workspace:${workspaceId}`),+ });+ const result = await ctr.reconnectFromProtocol({ deviceId: workspaceDevice.deviceId });++ expect(result).toBe(true);+ expect(mockStoreSet).toHaveBeenCalledWith('gatewayEnabled', true);+ });+it('should no-op when already connected', async () => {ctr.afterFirstFrame();await vi.advanceTimersByTimeAsync(0);diff --git a/apps/desktop/src/main/services/gatewayConnectionSrv.ts b/apps/desktop/src/main/services/gatewayConnectionSrv.tsindex 0b24f938e4f..49789931b9d 100644--- a/apps/desktop/src/main/services/gatewayConnectionSrv.ts+++ b/apps/desktop/src/main/services/gatewayConnectionSrv.ts@@ -304,6 +304,31 @@ export default class GatewayConnectionService extends ServiceModule {};}+ /**+ * Whether a registry device id belongs to this physical desktop.+ *+ * A machine can be reachable through both its personal identity and one+ * derived identity per persisted workspace enrollment. Reconnect deep links+ * must accept all of those identities without waking a different machine.+ */+ async matchesDeviceId(deviceId: string): Promise<boolean> {+ if (this.getDeviceId() === deviceId) return true;++ const token = await this.tokenProvider?.();+ const userId = token ? this.extractUserIdFromToken(token) : undefined;+ if (userId) {+ const identity = await this.resolveDeviceIdentity(userId);+ if (identity.deviceId === deviceId) return true;+ }++ for (const workspaceId of this.getPersistedWorkspaceEnrollments()) {+ const identity = await this.resolveWorkspaceDeviceIdentity(workspaceId);+ if (identity.deviceId === deviceId) return true;+ }++ return false;+ }+// ─── Connection Logic ───async connect(): Promise<{ error?: string; success: boolean }> {diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 5719333314c..fe996b568f3 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -839,6 +839,8 @@"heteroAgent.executionTarget.offline": "Offline","heteroAgent.executionTarget.online": "Online","heteroAgent.executionTarget.personalGroup": "Private Devices",+ "heteroAgent.executionTarget.reconnect": "Reconnect",+ "heteroAgent.executionTarget.reconnectFailed": "Could not reconnect this device. Make sure the desktop app is running, then try again.","heteroAgent.executionTarget.sandbox": "Cloud Sandbox","heteroAgent.executionTarget.sandboxDesc": "Run in an ephemeral cloud sandbox","heteroAgent.executionTarget.sandboxUnsupported": "{{name}} currently runs only on a local or connected device",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex ff0971f70de..21c52ca41a2 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -839,6 +839,8 @@"heteroAgent.executionTarget.offline": "离线","heteroAgent.executionTarget.online": "在线","heteroAgent.executionTarget.personalGroup": "私人设备",+ "heteroAgent.executionTarget.reconnect": "重新连接",+ "heteroAgent.executionTarget.reconnectFailed": "无法重新连接此设备。请确认桌面端正在运行,然后重试。","heteroAgent.executionTarget.sandbox": "云端沙箱","heteroAgent.executionTarget.sandboxDesc": "在临时云端沙箱中运行","heteroAgent.executionTarget.sandboxUnsupported": "{{name}} 目前仅支持在本地设备或已连接设备上运行",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 1ef50f7ef7b..3f13bde7698 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -589,6 +589,9 @@ export default {'heteroAgent.executionTarget.noneDesc': 'No device enabled','heteroAgent.executionTarget.offline': 'Offline','heteroAgent.executionTarget.online': 'Online',+ 'heteroAgent.executionTarget.reconnect': 'Reconnect',+ 'heteroAgent.executionTarget.reconnectFailed':+ 'Could not reconnect this device. Make sure the desktop app is running, then try again.','heteroAgent.executionTarget.personalGroup': 'Private Devices','heteroAgent.executionTarget.sandbox': 'Cloud Sandbox','heteroAgent.executionTarget.sandboxDesc': 'Run in an ephemeral cloud sandbox',diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsxindex cf73323a2e0..5115a60ee10 100644--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx@@ -4,7 +4,7 @@ import { isDesktop } from '@lobechat/const';import { HETEROGENEOUS_TYPE_LABELS } from '@lobechat/heterogeneous-agents';import type { DeviceExecutionTarget } from '@lobechat/types';import { Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';-import { Button } from '@lobehub/ui/base-ui';+import { Button, toast } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar, cx } from 'antd-style';import {CheckIcon,@@ -12,6 +12,7 @@ import {ExternalLinkIcon,InfoIcon,MonitorDownIcon,+ RefreshCwIcon,SettingsIcon,ShieldCheckIcon,} from 'lucide-react';@@ -214,6 +215,12 @@ const styles = createStaticStyles(({ css }) => ({min-width: 0;`,+ reconnectButton: css`+ min-height: 18px;+ padding-block: 0;+ padding-inline: 2px;+ font-size: 11px;+ `,optionTitle: css`overflow: hidden;@@ -400,7 +407,7 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {// Workspace-keyed SWR fetch — the raw lambdaQuery key has no workspace// dimension, so the picker kept showing the previous workspace's pool after// a switch.- const { data: devices, isLoading } = useDeviceList();+ const { data: devices, isLoading, mutate: refreshDevices } = useDeviceList();// The current machine's own gateway deviceId (desktop only), used to badge the// matching device row with a "This device" tag and show the local-process@@ -408,6 +415,40 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {useElectronStore((s) => s.useFetchGatewayDeviceInfo)();const gatewayDeviceInfo = useElectronStore((s) => s.gatewayDeviceInfo);const currentDeviceId = isDesktop ? gatewayDeviceInfo?.deviceId : undefined;+ const [reconnectingDeviceId, setReconnectingDeviceId] = useState<string>();++ const handleReconnectDevice = useCallback(+ async (deviceId: string) => {+ setReconnectingDeviceId(deviceId);+ try {+ if (isDesktop && deviceId === currentDeviceId) {+ await useElectronStore.getState().connectGateway();+ } else {+ window.location.href = `lobehub://device/reconnect?deviceId=${encodeURIComponent(deviceId)}`;+ }++ // The deep link crosses browser → desktop → gateway → server, so give+ // the live device registry a short window to converge instead of+ // making the user close and reopen the picker to see the result.+ let connected = false;+ for (let attempt = 0; attempt < 8; attempt += 1) {+ const nextDevices = await refreshDevices();+ if (nextDevices?.some((device) => device.deviceId === deviceId && device.online)) {+ connected = true;+ break;+ }+ await new Promise((resolve) => setTimeout(resolve, 1000));+ }+ if (!connected) toast.error(t('heteroAgent.executionTarget.reconnectFailed'));+ } catch (error) {+ console.error('Device reconnect failed:', error);+ toast.error(t('heteroAgent.executionTarget.reconnectFailed'));+ } finally {+ setReconnectingDeviceId(undefined);+ }+ },+ [currentDeviceId, refreshDevices, t],+ );// A member's explicit target override may resolve `local`; without one the// raw shared fallback stays workspace-scoped so a legacy `local` value keeps@@ -670,7 +711,26 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {label={d.friendlyName || d.hostname || d.deviceId}tag={isCurrentMachine ? t('heteroAgent.executionTarget.gateway') : undefined}desc={- isCurrentMachine ? t('heteroAgent.executionTarget.gatewayDesc') : renderDeviceStatus(d)+ <>+ {isCurrentMachine+ ? t('heteroAgent.executionTarget.gatewayDesc')+ : renderDeviceStatus(d)}+ {d.online ? null : (+ <Button+ className={styles.reconnectButton}+ icon={RefreshCwIcon}+ loading={reconnectingDeviceId === d.deviceId}+ size={'small'}+ type={'text'}+ onClick={(event) => {+ event.stopPropagation();+ void handleReconnectDevice(d.deviceId);+ }}+ >+ {t('heteroAgent.executionTarget.reconnect')}+ </Button>+ )}+ </>}onClick={() => void handleSelect('device', d.deviceId)}/>