Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(electron): simplify Device Gateway popover (#18161)

AmAzing-59d479aa7dcb
diff --git a/apps/desktop/src/main/const/store.ts b/apps/desktop/src/main/const/store.ts
index c1ae5cdeca3..7f0405f2b5a 100644
--- a/apps/desktop/src/main/const/store.ts
+++ b/apps/desktop/src/main/const/store.ts
@@ -29,9 +29,7 @@ export const STORE_DEFAULTS: ElectronMainStore = {
appTrayVisible: true,
dataSyncConfig: { storageMode: 'cloud' },
encryptedTokens: {},
- gatewayDeviceDescription: '',
gatewayDeviceId: '',
- gatewayDeviceName: '',
gatewayEnabled: true,
gatewayUrl: 'https://device-gateway.lobehub.com',
gatewayWorkspaceEnrollments: [],
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
index 962b2bceb32..b9e4e48660c 100644
--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
@@ -224,27 +224,13 @@ export default class GatewayConnectionCtr extends ControllerModule {
@IpcMethod()
async getDeviceInfo(): Promise<{
- description: string;
deviceId: string;
hostname: string;
- name: string;
platform: string;
}> {
return this.service.getDeviceInfo();
}
- @IpcMethod()
- async setDeviceName(params: { name: string }): Promise<{ success: boolean }> {
- this.service.setDeviceName(params.name);
- return { success: true };
- }
-
- @IpcMethod()
- async setDeviceDescription(params: { description: string }): Promise<{ success: boolean }> {
- this.service.setDeviceDescription(params.description);
- return { success: true };
- }
-
// ─── 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.ts
index 2fd710adfb3..7c0843c4211 100644
--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
@@ -1614,10 +1614,8 @@ describe('GatewayConnectionCtr', () => {
const info = await ctr.getDeviceInfo();
expect(info).toEqual({
- description: '',
deviceId: 'my-device',
hostname: 'mock-hostname',
- name: 'mock-hostname',
platform: process.platform,
});
});
diff --git a/apps/desktop/src/main/services/gatewayConnectionSrv.ts b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
index 114a110e0d3..8a3b0e9692f 100644
--- a/apps/desktop/src/main/services/gatewayConnectionSrv.ts
+++ b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
@@ -298,32 +298,12 @@ export default class GatewayConnectionService extends ServiceModule {
getDeviceInfo() {
return {
- description: this.getDeviceDescription(),
deviceId: this.getDeviceId(),
hostname: os.hostname(),
- name: this.getDeviceName(),
platform: process.platform,
};
}
- // ─── Device Name & Description ───
-
- getDeviceName(): string {
- return (this.app.storeManager.get('gatewayDeviceName') as string) || os.hostname();
- }
-
- setDeviceName(name: string) {
- this.app.storeManager.set('gatewayDeviceName', name);
- }
-
- getDeviceDescription(): string {
- return (this.app.storeManager.get('gatewayDeviceDescription') as string) || '';
- }
-
- setDeviceDescription(description: string) {
- this.app.storeManager.set('gatewayDeviceDescription', description);
- }
-
// ─── Connection Logic ───
async connect(): Promise<{ error?: string; success: boolean }> {
diff --git a/apps/desktop/src/main/types/store.ts b/apps/desktop/src/main/types/store.ts
index 51edfc4cc5d..c0e41fb1513 100644
--- a/apps/desktop/src/main/types/store.ts
+++ b/apps/desktop/src/main/types/store.ts
@@ -22,9 +22,7 @@ export interface ElectronMainStore {
lastRefreshAt?: number;
refreshToken?: string;
};
- gatewayDeviceDescription: string;
gatewayDeviceId: string;
- gatewayDeviceName: string;
gatewayEnabled: boolean;
gatewayUrl: string;
/**
diff --git a/locales/en-US/electron.json b/locales/en-US/electron.json
index fdfa4922534..eb2c4289779 100644
--- a/locales/en-US/electron.json
+++ b/locales/en-US/electron.json
@@ -1,12 +1,9 @@
{
- "gateway.description": "Description",
- "gateway.descriptionPlaceholder": "Optional",
- "gateway.deviceName": "Device Name",
- "gateway.deviceNamePlaceholder": "Enter device name",
"gateway.enableConnection": "Connect to Gateway",
- "gateway.statusConnected": "Connected to Gateway",
- "gateway.statusConnecting": "Connecting to Gateway...",
- "gateway.statusDisconnected": "Not connected to Gateway",
+ "gateway.manageDevices": "Manage devices",
+ "gateway.statusConnected": "This device is connected to Gateway",
+ "gateway.statusConnecting": "This device is connecting to Gateway...",
+ "gateway.statusDisconnected": "This device is not connected to Gateway",
"gateway.title": "Device Gateway",
"navigation.agents": "Agents",
"navigation.channels": "Channels",
diff --git a/locales/zh-CN/electron.json b/locales/zh-CN/electron.json
index f95cc8e1b48..0eaf7bf3290 100644
--- a/locales/zh-CN/electron.json
+++ b/locales/zh-CN/electron.json
@@ -1,12 +1,9 @@
{
- "gateway.description": "描述",
- "gateway.descriptionPlaceholder": "可选",
- "gateway.deviceName": "设备名称",
- "gateway.deviceNamePlaceholder": "输入设备名称",
"gateway.enableConnection": "连接到网关",
- "gateway.statusConnected": "已连接到网关",
- "gateway.statusConnecting": "正在连接到网关...",
- "gateway.statusDisconnected": "未连接到网关",
+ "gateway.manageDevices": "管理设备",
+ "gateway.statusConnected": "本机已连接设备网关",
+ "gateway.statusConnecting": "本机正在连接设备网关...",
+ "gateway.statusDisconnected": "本机未连接设备网关",
"gateway.title": "设备网关",
"navigation.agents": "助手",
"navigation.channels": "消息频道",
diff --git a/packages/locales/src/default/electron.ts b/packages/locales/src/default/electron.ts
index ed3cca0e9ae..15503ea5a04 100644
--- a/packages/locales/src/default/electron.ts
+++ b/packages/locales/src/default/electron.ts
@@ -91,14 +91,11 @@ export default {
'proxy.validation.serverRequired': 'Server address is required when proxy is enabled',
'proxy.validation.typeRequired': 'Proxy type is required when proxy is enabled',
'proxy.validation.usernameRequired': 'Username is required when authentication is enabled',
- 'gateway.description': 'Description',
- 'gateway.descriptionPlaceholder': 'Optional',
- 'gateway.deviceName': 'Device Name',
- 'gateway.deviceNamePlaceholder': 'Enter device name',
'gateway.enableConnection': 'Connect to Gateway',
- 'gateway.statusConnected': 'Connected to Gateway',
- 'gateway.statusConnecting': 'Connecting to Gateway...',
- 'gateway.statusDisconnected': 'Not connected to Gateway',
+ 'gateway.manageDevices': 'Manage devices',
+ 'gateway.statusConnected': 'This device is connected to Gateway',
+ 'gateway.statusConnecting': 'This device is connecting to Gateway...',
+ 'gateway.statusDisconnected': 'This device is not connected to Gateway',
'gateway.title': 'Device Gateway',
'remoteServer.authError': 'Authorization failed: {{error}}',
'remoteServer.authPending': 'Please complete the authorization in your browser',
diff --git a/src/features/Electron/connection/DeviceGateway.tsx b/src/features/Electron/connection/DeviceGateway.tsx
index 6545d2cfc35..484f28f7c0c 100644
--- a/src/features/Electron/connection/DeviceGateway.tsx
+++ b/src/features/Electron/connection/DeviceGateway.tsx
@@ -1,20 +1,17 @@
import { useWatchBroadcast } from '@lobechat/electron-client-ipc';
import { ActionIcon, Flexbox } from '@lobehub/ui';
-import { Switch } from '@lobehub/ui/base-ui';
-import { Input, Popover } from 'antd';
+import { Popover, Switch } from '@lobehub/ui/base-ui';
import { createStaticStyles } from 'antd-style';
-import { HardDrive } from 'lucide-react';
+import { HardDrive, SettingsIcon } from 'lucide-react';
import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useElectronStore } from '@/store/electron';
import { electronSyncSelectors } from '@/store/electron/selectors';
const styles = createStaticStyles(({ css, cssVar }) => ({
- fieldLabel: css`
- font-size: 12px;
- color: ${cssVar.colorTextDescription};
- `,
greenDot: css`
position: absolute;
inset-block-end: 0;
@@ -27,19 +24,14 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
background: #52c41a;
`,
- input: css`
- border: none;
- background: ${cssVar.colorFillTertiary};
-
- &:hover,
- &:focus {
- background: ${cssVar.colorFillSecondary};
- }
- `,
popoverContent: css`
- width: 280px;
- padding-block: 4px;
- padding-inline: 0;
+ width: 250px;
+ `,
+ scopeHint: css`
+ font-size: 11px;
+ line-height: 1.4;
+ color: ${cssVar.colorTextDescription};
+ white-space: nowrap;
`,
statusTitle: css`
font-size: 13px;
@@ -50,40 +42,34 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
const DeviceGateway = memo(() => {
const { t } = useTranslation('electron');
+ const navigate = useWorkspaceAwareNavigate();
const [
gatewayStatus,
connectGateway,
disconnectGateway,
setGatewayConnectionStatus,
useFetchGatewayStatus,
- useFetchGatewayDeviceInfo,
- updateDeviceName,
- updateDeviceDescription,
- gatewayDeviceInfo,
] = useElectronStore((s) => [
s.gatewayConnectionStatus,
s.connectGateway,
s.disconnectGateway,
s.setGatewayConnectionStatus,
s.useFetchGatewayStatus,
- s.useFetchGatewayDeviceInfo,
- s.updateDeviceName,
- s.updateDeviceDescription,
- s.gatewayDeviceInfo,
]);
useFetchGatewayStatus();
- useFetchGatewayDeviceInfo();
useWatchBroadcast('gatewayConnectionStatusChanged', ({ status }) => {
setGatewayConnectionStatus(status);
});
const isConnected = gatewayStatus === 'connected';
- const isConnecting = gatewayStatus === 'connecting' || gatewayStatus === 'reconnecting';
+ const isConnecting =
+ gatewayStatus === 'authenticating' ||
+ gatewayStatus === 'connecting' ||
+ gatewayStatus === 'reconnecting';
- const [localName, setLocalName] = useState<string | undefined>();
- const [localDescription, setLocalDescription] = useState<string | undefined>();
+ const [open, setOpen] = useState(false);
const handleSwitchChange = useCallback(
async (checked: boolean) => {
@@ -96,64 +82,52 @@ const DeviceGateway = memo(() => {
[connectGateway, disconnectGateway],
);
- const handleNameBlur = useCallback(() => {
- if (localName !== undefined && localName !== gatewayDeviceInfo?.name) {
- updateDeviceName(localName);
- }
- setLocalName(undefined);
- }, [localName, gatewayDeviceInfo?.name, updateDeviceName]);
-
- const handleDescriptionBlur = useCallback(() => {
- if (localDescription !== undefined && localDescription !== gatewayDeviceInfo?.description) {
- updateDeviceDescription(localDescription);
- }
- setLocalDescription(undefined);
- }, [localDescription, gatewayDeviceInfo?.description, updateDeviceDescription]);
+ const connectionHint = t(
+ isConnecting
+ ? 'gateway.statusConnecting'
+ : isConnected
+ ? 'gateway.statusConnected'
+ : 'gateway.statusDisconnected',
+ );
const popoverContent = (
- <Flexbox className={styles.popoverContent} gap={16}>
+ <Flexbox className={styles.popoverContent} gap={4}>
<Flexbox horizontal align="center" justify="space-between">
- <span className={styles.statusTitle}>{t('gateway.enableConnection')}</span>
- <Switch
- checked={isConnected || isConnecting}
- loading={isConnecting}
- size="small"
- onChange={handleSwitchChange}
- />
- </Flexbox>
-
- <Flexbox gap={4}>
- <span className={styles.fieldLabel}>{t('gateway.deviceName')}</span>
- <Input
- className={styles.input}
- placeholder={t('gateway.deviceNamePlaceholder')}
- size="small"
- value={localName ?? gatewayDeviceInfo?.name ?? ''}
- variant="filled"
- onBlur={handleNameBlur}
- onChange={(e) => setLocalName(e.target.value)}
- onPressEnter={handleNameBlur}
- />
- </Flexbox>
-
- <Flexbox gap={4}>
- <span className={styles.fieldLabel}>{t('gateway.description')}</span>
- <Input.TextArea
- autoSize={{ maxRows: 3, minRows: 2 }}
- className={styles.input}
- placeholder={t('gateway.descriptionPlaceholder')}
- size="small"
- value={localDescription ?? gatewayDeviceInfo?.description ?? ''}
- variant="filled"
- onBlur={handleDescriptionBlur}
- onChange={(e) => setLocalDescription(e.target.value)}
- />
+ <span className={styles.statusTitle}>{t('gateway.title')}</span>
+ <Flexbox horizontal align="center" gap={6}>
+ <ActionIcon
+ aria-label={t('gateway.manageDevices')}
+ icon={SettingsIcon}
+ size="small"
+ title={t('gateway.manageDevices')}
+ onClick={() => {
+ setOpen(false);
+ navigate('/settings/devices', { escape: true });
+ }}
+ />
+ <Switch
+ aria-label={t('gateway.enableConnection')}
+ checked={isConnected || isConnecting}
+ loading={isConnecting}
+ size="small"
+ onChange={handleSwitchChange}
+ />
+ </Flexbox>
</Flexbox>
+ <span className={styles.scopeHint}>{connectionHint}</span>
</Flexbox>
);
return (
- <Popover arrow={false} content={popoverContent} placement="bottomRight" trigger="click">
+ <Popover
+ arrow={false}
+ content={popoverContent}
+ open={open}
+ placement="bottomRight"
+ styles={{ content: { padding: 8 } }}
+ trigger="click"
+ onOpenChange={setOpen}
+ >
<div style={{ position: 'relative' }}>
<ActionIcon
icon={HardDrive}
@@ -170,8 +144,9 @@ const DeviceGateway = memo(() => {
const DeviceGatewayWithAuth = memo(() => {
const isSyncActive = useElectronStore(electronSyncSelectors.isSyncActive);
+ const activeWorkspaceSlug = useActiveWorkspaceSlug();
- if (!isSyncActive) return null;
+ if (!isSyncActive || activeWorkspaceSlug) return null;
return <DeviceGateway />;
});
diff --git a/src/services/electron/gatewayConnection.ts b/src/services/electron/gatewayConnection.ts
index 7cb29c08862..982f435e334 100644
--- a/src/services/electron/gatewayConnection.ts
+++ b/src/services/electron/gatewayConnection.ts
@@ -16,14 +16,6 @@ class GatewayConnectionService {
getDeviceInfo = async () => {
return ensureElectronIpc().gatewayConnection.getDeviceInfo();
};
-
- setDeviceDescription = async (description: string) => {
- return ensureElectronIpc().gatewayConnection.setDeviceDescription({ description });
- };
-
- setDeviceName = async (name: string) => {
- return ensureElectronIpc().gatewayConnection.setDeviceName({ name });
- };
}
export const gatewayConnectionService = new GatewayConnectionService();
diff --git a/src/store/electron/actions/gateway.ts b/src/store/electron/actions/gateway.ts
index 123b585a151..1d2be406ba4 100644
--- a/src/store/electron/actions/gateway.ts
+++ b/src/store/electron/actions/gateway.ts
@@ -2,7 +2,6 @@ import type { GatewayConnectionStatus } from '@lobechat/electron-client-ipc';
import { type SWRResponse } from 'swr';
import useSWR from 'swr';
-import { mutate } from '@/libs/swr';
import { electronKeys } from '@/libs/swr/keys';
import { gatewayConnectionService } from '@/services/electron/gatewayConnection';
import { type StoreSetter } from '@/store/types';
@@ -14,21 +13,18 @@ export const gatewaySlice = (set: Setter, get: () => ElectronStore, _api?: unkno
new ElectronGatewayActionImpl(set, get, _api);
export interface GatewayDeviceInfo {
- description: string;
deviceId: string;
hostname: string;
- name: string;
platform: string;
}
export class ElectronGatewayActionImpl {
- readonly #get: () => ElectronStore;
readonly #set: Setter;
- constructor(set: Setter, get: () => ElectronStore, _api?: unknown) {
+ constructor(set: Setter, _get: () => ElectronStore, _api?: unknown) {
+ void _get;
void _api;
this.#set = set;
- this.#get = get;
}
connectGateway = async (): Promise<void> => {
@@ -53,32 +49,10 @@ export class ElectronGatewayActionImpl {
}
};
- refreshGatewayDeviceInfo = async (): Promise<void> => {
- await mutate(electronKeys.gatewayDeviceInfo());
- };
-
setGatewayConnectionStatus = (status: GatewayConnectionStatus): void => {
this.#set({ gatewayConnectionStatus: status }, false, 'setGatewayConnectionStatus');
};
- updateDeviceDescription = async (description: string): Promise<void> => {
- try {
- await gatewayConnectionService.setDeviceDescription(description);
- await this.#get().refreshGatewayDeviceInfo();
- } catch (error) {
- console.error('Update device description failed:', error);
- }
- };
-
- updateDeviceName = async (name: string): Promise<void> => {
- try {
- await gatewayConnectionService.setDeviceName(name);
- await this.#get().refreshGatewayDeviceInfo();
- } catch (error) {
- console.error('Update device name failed:', error);
- }
- };
-
useFetchGatewayDeviceInfo = (): SWRResponse<GatewayDeviceInfo> => {
return useSWR<GatewayDeviceInfo>(
electronKeys.gatewayDeviceInfo(),