🤯 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(desktop): keep the device awake and steady through reconnects (#19962)
Arvin Xu97c9f9fe2026
diff --git a/apps/desktop/src/main/const/store.ts b/apps/desktop/src/main/const/store.tsindex 7f0405f2b5a..034233bce3f 100644--- a/apps/desktop/src/main/const/store.ts+++ b/apps/desktop/src/main/const/store.ts@@ -31,6 +31,7 @@ export const STORE_DEFAULTS: ElectronMainStore = {encryptedTokens: {},gatewayDeviceId: '',gatewayEnabled: true,+ gatewayKeepAwake: true,gatewayUrl: 'https://device-gateway.lobehub.com',gatewayWorkspaceEnrollments: [],heteroSessionDirPrefs: {},diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.tsindex bfd6e5209cf..19e175381c4 100644--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts@@ -248,7 +248,18 @@ export default class GatewayConnectionCtr extends ControllerModule {@IpcMethod()async getConnectionStatus(): Promise<{ status: GatewayConnectionStatus }> {- return { status: this.service.getStatus() };+ return { status: this.service.getDisplayedStatus() };+ }++ @IpcMethod()+ async getKeepAwake(): Promise<{ enabled: boolean }> {+ return { enabled: this.service.getKeepAwake() };+ }++ @IpcMethod()+ async setKeepAwake({ enabled }: { enabled: boolean }): Promise<{ enabled: boolean }> {+ this.service.setKeepAwake(enabled);+ return { enabled: this.service.getKeepAwake() };}@IpcMethod()diff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.tsindex 88032f761d8..ddada220170 100644--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts@@ -625,7 +625,7 @@ describe('GatewayConnectionCtr', () => {// ─── Reconnection ───describe('reconnection', () => {- it('should broadcast reconnecting status when client emits reconnecting', async () => {+ it('should broadcast reconnecting status once the reconnect outlasts the grace period', async () => {ctr.afterFirstFrame();await vi.advanceTimersByTimeAsync(0);const client = MockGatewayClient.lastInstance!;@@ -633,7 +633,11 @@ describe('GatewayConnectionCtr', () => {mockBroadcast.mockClear();client.simulateReconnecting(1000);+ expect(mockBroadcast).not.toHaveBeenCalledWith('gatewayConnectionStatusChanged', {+ status: 'reconnecting',+ });+ vi.advanceTimersByTime(5000);expect(mockBroadcast).toHaveBeenCalledWith('gatewayConnectionStatusChanged', {status: 'reconnecting',});diff --git a/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.ts b/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.tsindex 53167fc1dfb..1fc9b845fd8 100644--- a/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.ts+++ b/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.ts@@ -1,5 +1,5 @@import type { GatewayClient } from '@lobechat/device-gateway-client';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { App } from '@/core/App';@@ -91,3 +91,146 @@ describe('GatewayConnectionService system_info_request', () => {});});});++describe('GatewayConnectionService power save blocker', () => {+ let service: GatewayConnectionService;+ let store: Record<string, unknown>;++ beforeEach(async () => {+ const { powerSaveBlocker } = await import('electron');+ vi.mocked(powerSaveBlocker.start).mockReset().mockReturnValue(7);+ vi.mocked(powerSaveBlocker.stop).mockReset();++ store = {};+ const app = {+ browserManager: { broadcastToAllWindows: vi.fn() },+ storeManager: {+ get: vi.fn((key: string, fallback?: unknown) => (key in store ? store[key] : fallback)),+ set: vi.fn((key: string, value: unknown) => {+ store[key] = value;+ }),+ },+ } as unknown as App;+ service = new GatewayConnectionService(app);+ });++ const setStatus = (status: string) => (service as any).setStatus(status);++ it('keeps the blocker through a transient reconnect', async () => {+ const { powerSaveBlocker } = await import('electron');++ setStatus('connected');+ setStatus('reconnecting');+ setStatus('connecting');+ setStatus('authenticating');+ setStatus('connected');++ expect(powerSaveBlocker.start).toHaveBeenCalledTimes(1);+ expect(powerSaveBlocker.start).toHaveBeenCalledWith('prevent-app-suspension');+ expect(powerSaveBlocker.stop).not.toHaveBeenCalled();+ });++ it('releases the blocker once the connection settles on disconnected', async () => {+ const { powerSaveBlocker } = await import('electron');++ setStatus('connected');+ setStatus('disconnected');++ expect(powerSaveBlocker.stop).toHaveBeenCalledWith(7);+ });++ it('never holds the blocker when keep-awake is turned off', async () => {+ const { powerSaveBlocker } = await import('electron');+ store.gatewayKeepAwake = false;++ setStatus('connecting');+ setStatus('connected');++ expect(powerSaveBlocker.start).not.toHaveBeenCalled();+ });++ it('applies a keep-awake toggle to the live connection immediately', async () => {+ const { powerSaveBlocker } = await import('electron');+ setStatus('connected');++ service.setKeepAwake(false);+ expect(powerSaveBlocker.stop).toHaveBeenCalledWith(7);+ expect(service.getKeepAwake()).toBe(false);++ service.setKeepAwake(true);+ expect(powerSaveBlocker.start).toHaveBeenCalledTimes(2);+ });++ it('does not start the blocker from a toggle while disconnected', async () => {+ const { powerSaveBlocker } = await import('electron');++ service.setKeepAwake(true);++ expect(powerSaveBlocker.start).not.toHaveBeenCalled();+ });+});++describe('GatewayConnectionService status broadcast', () => {+ let service: GatewayConnectionService;+ let broadcast: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ vi.useFakeTimers();+ broadcast = vi.fn();+ const app = {+ browserManager: { broadcastToAllWindows: broadcast },+ storeManager: { get: vi.fn((_key: string, fallback?: unknown) => fallback), set: vi.fn() },+ } as unknown as App;+ service = new GatewayConnectionService(app);+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ const setStatus = (status: string) => (service as any).setStatus(status);+ const broadcastStatuses = () => broadcast.mock.calls.map(([, payload]) => payload.status);++ it('hides a reconnect that recovers within the grace period', () => {+ setStatus('connecting');+ setStatus('authenticating');+ setStatus('connected');+ broadcast.mockClear();++ setStatus('reconnecting');+ setStatus('connecting');+ setStatus('authenticating');+ vi.advanceTimersByTime(3000);+ setStatus('connected');+ vi.advanceTimersByTime(10_000);++ expect(broadcast).not.toHaveBeenCalled();+ expect(service.getDisplayedStatus()).toBe('connected');+ expect(service.getStatus()).toBe('connected');+ });++ it('surfaces a reconnect that outlasts the grace period', () => {+ setStatus('connected');+ broadcast.mockClear();++ setStatus('reconnecting');+ setStatus('connecting');+ expect(service.getDisplayedStatus()).toBe('connected');++ vi.advanceTimersByTime(5000);+ expect(broadcastStatuses()).toEqual(['connecting']);++ setStatus('authenticating');+ setStatus('connected');+ expect(broadcastStatuses()).toEqual(['connecting', 'authenticating', 'connected']);+ });++ it('shows an explicit disconnect immediately', () => {+ setStatus('connected');+ broadcast.mockClear();++ setStatus('disconnected');++ expect(broadcastStatuses()).toEqual(['disconnected']);+ });+});diff --git a/apps/desktop/src/main/services/gatewayConnectionSrv.ts b/apps/desktop/src/main/services/gatewayConnectionSrv.tsindex 3b4e5d282d1..8d786d228f3 100644--- a/apps/desktop/src/main/services/gatewayConnectionSrv.ts+++ b/apps/desktop/src/main/services/gatewayConnectionSrv.ts@@ -34,6 +34,13 @@ const logger = createLogger('services:GatewayConnectionSrv');const DEFAULT_GATEWAY_URL = OFFICIAL_DEVICE_GATEWAY_URL;+/**+ * The socket drops about once an hour (Cloudflare moving the Durable Object,+ * edge link resets) and is back within ~2s. A drop that recovers inside this+ * window is not surfaced to the UI, so the device indicator doesn't flicker.+ */+const RECONNECT_UI_GRACE_MS = 5000;+/*** Result envelope a tool-call handler must return. Mirrors* `BuiltinServerRuntimeOutput` so the renderer-side and remote-device paths@@ -145,6 +152,9 @@ export default class GatewayConnectionService extends ServiceModule {private status: GatewayConnectionStatus = 'disconnected';private deviceId: string | null = null;private powerSaveBlockerId: number | null = null;+ /** Status last pushed to renderers; lags `status` during a transient drop. */+ private displayedStatus: GatewayConnectionStatus = 'disconnected';+ private statusBroadcastTimer: ReturnType<typeof setTimeout> | null = null;private identitySource: IdentitySource | null = null;@@ -300,6 +310,11 @@ export default class GatewayConnectionService extends ServiceModule {return this.status;}+ /** Status as shown in the UI — hides reconnects that recover quickly. */+ getDisplayedStatus(): GatewayConnectionStatus {+ return this.displayedStatus;+ }+getDeviceInfo() {return {deviceId: this.getDeviceId(),@@ -921,10 +936,37 @@ export default class GatewayConnectionService extends ServiceModule {// ─── Power Save Blocker ───+ getKeepAwake(): boolean {+ return this.app.storeManager.get('gatewayKeepAwake', true);+ }++ setKeepAwake(enabled: boolean) {+ this.app.storeManager.set('gatewayKeepAwake', enabled);+ logger.info(`Keep awake while connected: ${enabled}`);+ this.syncPowerSaveBlocker();+ }+/**- * Start power save blocker to prevent macOS App Nap from suspending the process- * while the gateway connection is active. Uses 'prevent-app-suspension' so the- * display can still sleep — only the app process is kept alive.+ * Hold the blocker for as long as the device is meant to be online — not+ * just while the socket is `connected`. Releasing it on every transient drop+ * (the socket blips every few tens of minutes) hands macOS a window to idle+ * sleep: with the default "sleep 1 minute after the display turns off" the+ * idle timer has long expired, so the machine sleeps before the ~2s reconnect+ * lands and stays offline until the user comes back. Only an explicit+ * disconnect (status settles on `disconnected`) or the user opting out lets+ * the system sleep again.+ */+ private syncPowerSaveBlocker() {+ if (this.status !== 'disconnected' && this.getKeepAwake()) {+ this.startPowerSaveBlocker();+ } else {+ this.stopPowerSaveBlocker();+ }+ }++ /**+ * 'prevent-app-suspension' keeps the system from idle-sleeping (and App Nap+ * from suspending the process) while still letting the display sleep.*/private startPowerSaveBlocker() {if (this.powerSaveBlockerId !== null) return;@@ -947,14 +989,34 @@ export default class GatewayConnectionService extends ServiceModule {logger.info(`Connection status: ${this.status} → ${status}`);this.status = status;- // Keep the app process alive while gateway is connected so macOS App Nap- // does not suspend it during display sleep, which would drop the WebSocket.- if (status === 'connected') {- this.startPowerSaveBlocker();- } else {- this.stopPowerSaveBlocker();+ this.syncPowerSaveBlocker();+ this.scheduleStatusBroadcast(status);+ }++ private scheduleStatusBroadcast(status: GatewayConnectionStatus) {+ if (this.statusBroadcastTimer) {+ clearTimeout(this.statusBroadcastTimer);+ this.statusBroadcastTimer = null;+ }++ // Leaving `connected` for a reconnect: hold the UI on `connected` for a+ // grace period. An explicit `disconnected` is always shown immediately.+ const isTransientDrop =+ this.displayedStatus === 'connected' && status !== 'connected' && status !== 'disconnected';+ if (isTransientDrop) {+ this.statusBroadcastTimer = setTimeout(() => {+ this.statusBroadcastTimer = null;+ this.broadcastStatus(this.status);+ }, RECONNECT_UI_GRACE_MS);+ return;}+ this.broadcastStatus(status);+ }++ private broadcastStatus(status: GatewayConnectionStatus) {+ if (this.displayedStatus === status) return;+ this.displayedStatus = status;this.app.browserManager.broadcastToAllWindows('gatewayConnectionStatusChanged', { status });}diff --git a/apps/desktop/src/main/types/store.ts b/apps/desktop/src/main/types/store.tsindex 8536c7a7869..3f5289ac009 100644--- a/apps/desktop/src/main/types/store.ts+++ b/apps/desktop/src/main/types/store.ts@@ -29,6 +29,12 @@ export interface ElectronMainStore {};gatewayDeviceId: string;gatewayEnabled: boolean;+ /**+ * Keep the computer from idle-sleeping while the device gateway connection+ * is enabled, so the device stays reachable from other clients. The display+ * can still sleep.+ */+ gatewayKeepAwake: boolean;gatewayUrl: string;/*** Workspaces this machine's personal gateway connection has been shared intodiff --git a/locales/en-US/desktop-onboarding.json b/locales/en-US/desktop-onboarding.jsonindex 5e23cf1c0b8..bfd857bd7a3 100644--- a/locales/en-US/desktop-onboarding.json+++ b/locales/en-US/desktop-onboarding.json@@ -2,6 +2,16 @@"authResult.failed.desc": "Please try again or switch to a different sign-in method","authResult.failed.title": "Authorization Failed","back": "Back",+ "keepAwake.description": "LobeHub connects this computer as a device, so agents running in the cloud, on the web or on your phone can use its files and tools. When the computer goes to sleep, the device drops offline and those tasks can't reach it.",+ "keepAwake.footerNote": "You can change this anytime in Settings → Devices. Closing a laptop lid without an external display still puts it to sleep.",+ "keepAwake.off.description": "Follow the system energy settings. The device goes offline whenever the computer sleeps.",+ "keepAwake.off.title": "Allow Sleep",+ "keepAwake.on.badge": "Recommended",+ "keepAwake.on.description": "Prevent automatic sleep while the device is connected. The display can still turn off.",+ "keepAwake.on.title": "Stay Available",+ "keepAwake.title": "Keep This Computer Available",+ "keepAwake.title2": "So your agents can reach it anytime",+ "keepAwake.title3": "Even when you step away","navigation.next": "Continue","next": "Next","screen1.description": "AI-powered productivity platform with intelligent agents",diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex d5ac3b81237..33e4005e374 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -430,6 +430,8 @@"devices.empty.title": "Connect your first device","devices.fallbackBadge": "Unstable identity","devices.fallbackTooltip": "This device couldn't be identified by its machine ID, so reinstalling the app may create a duplicate entry.",+ "devices.keepAwake.desc": "Prevent automatic sleep while this computer is connected as a device, so it stays reachable. The display can still turn off; closing a laptop lid without an external display still puts it to sleep.",+ "devices.keepAwake.title": "Keep Awake While Connected","devices.lastSeen": "Last connected {{time}}","devices.remove.confirm": "Remove this device?","devices.remove.confirmDesc": "This disconnects the device from your account. It does not sign the device out, and it can re-register on next connect.",@@ -463,6 +465,7 @@"devices.status.online": "Online","devices.status.onlineConnections_one": "Online · {{count}} connection","devices.status.onlineConnections_other": "Online · {{count}} connections",+ "devices.thisComputer": "This Computer","devices.title": "My Devices","devices.visibility.publish": "Publish to Workspace","devices.visibility.publishConfirmTitle": "Publish this device to the workspace?",diff --git a/locales/zh-CN/desktop-onboarding.json b/locales/zh-CN/desktop-onboarding.jsonindex 42d4134540b..a8832b15ac0 100644--- a/locales/zh-CN/desktop-onboarding.json+++ b/locales/zh-CN/desktop-onboarding.json@@ -2,6 +2,16 @@"authResult.failed.desc": "请重试,或切换其他登录方式","authResult.failed.title": "授权失败","back": "返回",+ "keepAwake.description": "LobeHub 会把这台电脑连接为设备,让云端、网页或手机上运行的助手使用它的文件和工具。电脑一旦睡眠,设备就会离线,这些任务也就无法再访问它。",+ "keepAwake.footerNote": "可随时在「设置 → 设备」中修改。未连接外接显示器时,合上笔记本屏幕仍会进入睡眠。",+ "keepAwake.off.description": "遵循系统的节能设置。电脑睡眠时设备将离线。",+ "keepAwake.off.title": "允许睡眠",+ "keepAwake.on.badge": "推荐",+ "keepAwake.on.description": "设备连接期间阻止电脑自动睡眠,屏幕仍可正常关闭。",+ "keepAwake.on.title": "保持在线",+ "keepAwake.title": "让这台电脑保持在线",+ "keepAwake.title2": "助手随时都能访问它",+ "keepAwake.title3": "即使你暂时离开","navigation.next": "继续","next": "下一步","screen1.description": "AI 驱动的生产力平台,内置智能助理",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 0d3c8ed224d..8f1eb220c28 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -430,6 +430,8 @@"devices.empty.title": "连接你的第一台设备","devices.fallbackBadge": "身份不稳定","devices.fallbackTooltip": "未能通过机器 ID 识别此设备,重装应用可能会产生重复条目。",+ "devices.keepAwake.desc": "作为设备连接期间阻止电脑自动睡眠,保证它始终可被访问。屏幕仍可正常关闭;未连接外接显示器时合上笔记本屏幕仍会睡眠。",+ "devices.keepAwake.title": "连接期间保持唤醒","devices.lastSeen": "最后连接于 {{time}}","devices.remove.confirm": "移除此设备?","devices.remove.confirmDesc": "这会断开设备与你账户的关联,但不会让设备登出,下次连接时它可重新注册。",@@ -463,6 +465,7 @@"devices.status.online": "在线","devices.status.onlineConnections_one": "在线 · {{count}} 个连接","devices.status.onlineConnections_other": "在线 · {{count}} 个连接",+ "devices.thisComputer": "这台电脑","devices.title": "我的设备","devices.visibility.publish": "发布到工作区","devices.visibility.publishConfirmTitle": "将此设备发布到工作区?",diff --git a/packages/locales/src/default/desktop-onboarding.ts b/packages/locales/src/default/desktop-onboarding.tsindex 38f96c5022e..e1820c923cf 100644--- a/packages/locales/src/default/desktop-onboarding.ts+++ b/packages/locales/src/default/desktop-onboarding.ts@@ -3,6 +3,20 @@ export default {'authResult.failed.title': 'Authorization Failed','back': 'Back',+ 'keepAwake.description':+ "LobeHub connects this computer as a device, so agents running in the cloud, on the web or on your phone can use its files and tools. When the computer goes to sleep, the device drops offline and those tasks can't reach it.",+ 'keepAwake.footerNote':+ 'You can change this anytime in Settings → Devices. Closing a laptop lid without an external display still puts it to sleep.',+ 'keepAwake.off.description':+ 'Follow the system energy settings. The device goes offline whenever the computer sleeps.',+ 'keepAwake.off.title': 'Allow Sleep',+ 'keepAwake.on.badge': 'Recommended',+ 'keepAwake.on.description':+ 'Prevent automatic sleep while the device is connected. The display can still turn off.',+ 'keepAwake.on.title': 'Stay Available',+ 'keepAwake.title': 'Keep This Computer Available',+ 'keepAwake.title2': 'So your agents can reach it anytime',+ 'keepAwake.title3': 'Even when you step away','navigation.next': 'Continue','next': 'Next',diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 2070cc10271..9136646188e 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -1,4 +1,8 @@export default {+ 'devices.keepAwake.desc':+ 'Prevent automatic sleep while this computer is connected as a device, so it stays reachable. The display can still turn off; closing a laptop lid without an external display still puts it to sleep.',+ 'devices.keepAwake.title': 'Keep Awake While Connected',+ 'devices.thisComputer': 'This Computer','marketSubmission.entry': 'Publish','marketSubmission.title': 'Publish to Market','marketSubmission.submit': 'Publish',diff --git a/src/features/DesktopOnboarding/flow.test.ts b/src/features/DesktopOnboarding/flow.test.tsindex 86c2bd5f294..a872394faac 100644--- a/src/features/DesktopOnboarding/flow.test.ts+++ b/src/features/DesktopOnboarding/flow.test.ts@@ -38,7 +38,7 @@ describe('desktop onboarding flow', () => {).toBe(DesktopOnboardingScreen.Permissions);});- it('continues from Login to DataMode on non-macOS', () => {+ it('continues from Login to KeepAwake on non-macOS', () => {expect(resolveNextScreen({current: DesktopOnboardingScreen.Login,@@ -46,6 +46,28 @@ describe('desktop onboarding flow', () => {isAuthenticated: true,isMac: false,}),+ ).toBe(DesktopOnboardingScreen.KeepAwake);+ });++ it('continues from Permissions to KeepAwake on macOS', () => {+ expect(+ resolveNextScreen({+ current: DesktopOnboardingScreen.Permissions,+ everCompleted: false,+ isAuthenticated: true,+ isMac: true,+ }),+ ).toBe(DesktopOnboardingScreen.KeepAwake);+ });++ it('continues from KeepAwake to DataMode', () => {+ expect(+ resolveNextScreen({+ current: DesktopOnboardingScreen.KeepAwake,+ everCompleted: false,+ isAuthenticated: true,+ isMac: false,+ }),).toBe(DesktopOnboardingScreen.DataMode);});@@ -112,5 +134,14 @@ describe('desktop onboarding flow', () => {}),).toBe(DesktopOnboardingScreen.Login);});++ it('returns from DataMode to KeepAwake', () => {+ expect(+ resolvePreviousScreen({+ current: DesktopOnboardingScreen.DataMode,+ isMac: false,+ }),+ ).toBe(DesktopOnboardingScreen.KeepAwake);+ });});});diff --git a/src/features/DesktopOnboarding/flow.ts b/src/features/DesktopOnboarding/flow.tsindex 255d5e92b3e..b781fa86225 100644--- a/src/features/DesktopOnboarding/flow.ts+++ b/src/features/DesktopOnboarding/flow.ts@@ -16,11 +16,13 @@ const getDesktopOnboardingFlow = (isMac: boolean) =>DesktopOnboardingScreen.Welcome,DesktopOnboardingScreen.Login,DesktopOnboardingScreen.Permissions,+ DesktopOnboardingScreen.KeepAwake,DesktopOnboardingScreen.DataMode,]: [DesktopOnboardingScreen.Welcome,DesktopOnboardingScreen.Login,+ DesktopOnboardingScreen.KeepAwake,DesktopOnboardingScreen.DataMode,];diff --git a/src/features/DesktopOnboarding/index.tsx b/src/features/DesktopOnboarding/index.tsxindex 72ebcd42a39..1e73769afe5 100644--- a/src/features/DesktopOnboarding/index.tsx+++ b/src/features/DesktopOnboarding/index.tsx@@ -14,6 +14,7 @@ import { resolveNextScreen, resolvePreviousScreen } from './flow';import OnboardingContainer from './Layout';import { resolveInitialScreen } from './resolveInitialScreen';import DataModeStep from './steps/DataModeStep';+import KeepAwakeStep from './steps/KeepAwakeStep';import LoginStep from './steps/LoginStep';import PermissionsStep from './steps/PermissionsStep';import WelcomeStep from './steps/WelcomeStep';@@ -197,13 +198,16 @@ const DesktopOnboardingPage = memo(() => {return <WelcomeStep onNext={goToNextStep} />;}case DesktopOnboardingScreen.Permissions: {- // macOS-only screen; fallback to DataMode if platform doesn't support.+ // macOS-only screen; fallback to the next step if platform doesn't support.if (!isMac) {- setCurrentScreen(DesktopOnboardingScreen.DataMode);+ setCurrentScreen(DesktopOnboardingScreen.KeepAwake);return null;}return <PermissionsStep onBack={goToPreviousStep} onNext={goToNextStep} />;}+ case DesktopOnboardingScreen.KeepAwake: {+ return <KeepAwakeStep onBack={goToPreviousStep} onNext={goToNextStep} />;+ }case DesktopOnboardingScreen.DataMode: {return <DataModeStep onBack={goToPreviousStep} onNext={goToNextStep} />;}diff --git a/src/features/DesktopOnboarding/resolveInitialScreen.test.ts b/src/features/DesktopOnboarding/resolveInitialScreen.test.tsindex 83afbcc2337..337a01fcb8f 100644--- a/src/features/DesktopOnboarding/resolveInitialScreen.test.ts+++ b/src/features/DesktopOnboarding/resolveInitialScreen.test.ts@@ -48,7 +48,7 @@ describe('resolveInitialScreen', () => {).toBe(DesktopOnboardingScreen.Welcome);});- it('rewrites Permissions to DataMode on non-macOS', () => {+ it('rewrites Permissions to KeepAwake on non-macOS', () => {expect(resolveInitialScreen({everCompleted: false,@@ -56,6 +56,6 @@ describe('resolveInitialScreen', () => {requested: DesktopOnboardingScreen.Permissions,saved: null,}),- ).toBe(DesktopOnboardingScreen.DataMode);+ ).toBe(DesktopOnboardingScreen.KeepAwake);});});diff --git a/src/features/DesktopOnboarding/resolveInitialScreen.ts b/src/features/DesktopOnboarding/resolveInitialScreen.tsindex f5e3240e5c3..b0154d1826f 100644--- a/src/features/DesktopOnboarding/resolveInitialScreen.ts+++ b/src/features/DesktopOnboarding/resolveInitialScreen.ts@@ -20,7 +20,7 @@ interface ResolveInitialScreenInput {* 3. `Login` if the user has previously completed onboarding.* 4. `Welcome` for first-time users.*- * On non-macOS, `Permissions` is rewritten to `DataMode` since the macOS-only+ * On non-macOS, `Permissions` is rewritten to `KeepAwake` since the macOS-only* screen has no useful content.*/export const resolveInitialScreen = ({@@ -33,7 +33,7 @@ export const resolveInitialScreen = ({const chosen = requested ?? saved ?? fallback;if (!isMac && chosen === DesktopOnboardingScreen.Permissions) {- return DesktopOnboardingScreen.DataMode;+ return DesktopOnboardingScreen.KeepAwake;}return chosen;};diff --git a/src/features/DesktopOnboarding/steps/KeepAwakeStep.tsx b/src/features/DesktopOnboarding/steps/KeepAwakeStep.tsxnew file mode 100644index 00000000000..875d033d143--- /dev/null+++ b/src/features/DesktopOnboarding/steps/KeepAwakeStep.tsx@@ -0,0 +1,121 @@+'use client';++import { Block, Empty, Flexbox } from '@lobehub/ui';+import { Button, Checkbox, Tag, Text } from '@lobehub/ui/base-ui';+import { cssVar } from 'antd-style';+import { MonitorCheck, Undo2Icon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { useGatewayKeepAwake } from '@/features/Electron/connection/useGatewayKeepAwake';++import LobeMessage from '../components/LobeMessage';+import OnboardingFooterActions from '../components/OnboardingFooterActions';++interface KeepAwakeStepProps {+ onBack: () => void;+ onNext: () => void;+}++/**+ * Let the user decide up front whether this computer may idle-sleep while it+ * is connected as a device. Sleeping drops the device offline, so remote runs+ * that target it fail until the user comes back.+ */+const KeepAwakeStep = memo<KeepAwakeStepProps>(({ onBack, onNext }) => {+ const { t } = useTranslation('desktop-onboarding');+ const { enabled, setKeepAwake } = useGatewayKeepAwake();+ // The store defaults to on; treat the pre-load state the same way.+ const keepAwake = enabled ?? true;++ const checkIcon = (+ <Checkbox+ checked+ backgroundColor={cssVar.colorSuccess}+ shape={'circle'}+ size={20}+ style={{ position: 'absolute', right: 12, top: 12 }}+ />+ );++ return (+ <Flexbox gap={16} style={{ height: '100%', minHeight: '100%' }}>+ <Flexbox>+ <LobeMessage+ sentences={[t('keepAwake.title'), t('keepAwake.title2'), t('keepAwake.title3')]}+ />+ <Text as={'p'}>{t('keepAwake.description')}</Text>+ </Flexbox>+ <Flexbox gap={16} style={{ width: '100%' }}>+ <Block+ clickable+ gap={16}+ padding={16}+ style={{ borderColor: keepAwake ? cssVar.colorSuccess : undefined }}+ variant={'outlined'}+ onClick={() => void setKeepAwake(true)}+ >+ {keepAwake && checkIcon}+ <Empty+ description={t('keepAwake.on.description')}+ icon={MonitorCheck}+ padding={0}+ type={'page'}+ descriptionProps={{+ fontSize: 14,+ }}+ title={+ <Flexbox horizontal align={'center'} gap={8}>+ {t('keepAwake.on.title')}+ <Tag color={'success'}>{t('keepAwake.on.badge')}</Tag>+ </Flexbox>+ }+ titleProps={{+ fontSize: 18,+ }}+ />+ </Block>+ <Block+ clickable+ gap={6}+ padding={16}+ style={{ borderColor: keepAwake ? undefined : cssVar.colorSuccess }}+ variant={'outlined'}+ onClick={() => void setKeepAwake(false)}+ >+ {!keepAwake && checkIcon}+ <Text strong fontSize={18}>+ {t('keepAwake.off.title')}+ </Text>+ <Text fontSize={14} type={'secondary'}>+ {t('keepAwake.off.description')}+ </Text>+ </Block>+ </Flexbox>+ <Text color={cssVar.colorTextSecondary} fontSize={12} style={{ marginTop: 16 }}>+ {t('keepAwake.footerNote')}+ </Text>+ <OnboardingFooterActions+ left={+ <Button+ icon={Undo2Icon}+ style={{ color: cssVar.colorTextDescription }}+ type={'text'}+ onClick={onBack}+ >+ {t('back')}+ </Button>+ }+ right={+ <Button type={'primary'} onClick={onNext}>+ {t('next')}+ </Button>+ }+ />+ </Flexbox>+ );+});++KeepAwakeStep.displayName = 'KeepAwakeStep';++export default KeepAwakeStep;diff --git a/src/features/DesktopOnboarding/storage.ts b/src/features/DesktopOnboarding/storage.tsindex f15ba813a3b..7b6d3c5cf58 100644--- a/src/features/DesktopOnboarding/storage.ts+++ b/src/features/DesktopOnboarding/storage.ts@@ -37,7 +37,7 @@ export const setDesktopOnboardingCompleted = () => {/*** Whether the user has *ever* completed desktop onboarding on this install.* Backed by localStorage so it survives quit/relaunch — used to skip first-run- * screens (Welcome / Permissions / DataMode) when a returning user is sent+ * screens (Welcome / Permissions / KeepAwake / DataMode) when a returning user is sent* back to /desktop-onboarding (e.g. token refresh failed, sign-out).*/export const getDesktopOnboardingEverCompleted = () => {diff --git a/src/features/DesktopOnboarding/types.ts b/src/features/DesktopOnboarding/types.tsindex a24601331fa..1a257348fe2 100644--- a/src/features/DesktopOnboarding/types.ts+++ b/src/features/DesktopOnboarding/types.ts@@ -1,5 +1,6 @@export enum DesktopOnboardingScreen {DataMode = 'data-mode',+ KeepAwake = 'keep-awake',Login = 'login',Permissions = 'permissions',Welcome = 'welcome',diff --git a/src/features/Electron/connection/useGatewayKeepAwake.ts b/src/features/Electron/connection/useGatewayKeepAwake.tsnew file mode 100644index 00000000000..7000fd75914--- /dev/null+++ b/src/features/Electron/connection/useGatewayKeepAwake.ts@@ -0,0 +1,31 @@+import { useCallback } from 'react';+import useSWR from 'swr';++import { gatewayConnectionService } from '@/services/electron/gatewayConnection';++const SWR_KEY = 'desktop-gateway-keep-awake';++/**+ * Whether this computer is kept from idle-sleeping while its device gateway+ * connection is enabled. Persisted in the desktop main-process store.+ */+export const useGatewayKeepAwake = () => {+ const { data, isLoading, mutate } = useSWR(+ SWR_KEY,+ async () => (await gatewayConnectionService.getKeepAwake()).enabled,+ { revalidateOnFocus: false },+ );++ const setKeepAwake = useCallback(+ async (enabled: boolean) => {+ await mutate(async () => (await gatewayConnectionService.setKeepAwake(enabled)).enabled, {+ optimisticData: enabled,+ revalidate: false,+ rollbackOnError: true,+ });+ },+ [mutate],+ );++ return { enabled: data, isLoading, setKeepAwake };+};diff --git a/src/features/Settings/devices/KeepAwake.tsx b/src/features/Settings/devices/KeepAwake.tsxnew file mode 100644index 00000000000..4a0c22c8341--- /dev/null+++ b/src/features/Settings/devices/KeepAwake.tsx@@ -0,0 +1,52 @@+'use client';++import { type FormGroupItemType } from '@lobehub/ui';+import { Form } from '@lobehub/ui';+import { Switch } from '@lobehub/ui/base-ui';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { FORM_STYLE } from '@/const/layoutTokens';+import { useGatewayKeepAwake } from '@/features/Electron/connection/useGatewayKeepAwake';++/**+ * Desktop-only: keep this computer from idle-sleeping while it is connected as+ * a device, so remote runs can still reach it after the user walks away.+ */+const KeepAwake = memo(() => {+ const { t } = useTranslation('setting');+ const { enabled, isLoading, setKeepAwake } = useGatewayKeepAwake();++ const items: FormGroupItemType = {+ children: [+ {+ children: (+ <Switch+ checked={!!enabled}+ disabled={isLoading}+ onChange={(checked) => void setKeepAwake(checked)}+ />+ ),+ desc: t('devices.keepAwake.desc'),+ label: t('devices.keepAwake.title'),+ minWidth: undefined,+ valuePropName: 'checked',+ },+ ],+ title: t('devices.thisComputer'),+ };++ return (+ <Form+ collapsible={false}+ items={[items]}+ itemsType={'group'}+ variant={'filled'}+ {...FORM_STYLE}+ />+ );+});++KeepAwake.displayName = 'KeepAwake';++export default KeepAwake;diff --git a/src/features/Settings/devices/index.tsx b/src/features/Settings/devices/index.tsxindex 3fd23cffa85..28941e28098 100644--- a/src/features/Settings/devices/index.tsx+++ b/src/features/Settings/devices/index.tsx@@ -19,6 +19,8 @@ import RightPanel from '@/features/RightPanel';import SettingContainer from '@/features/Setting/SettingContainer';import { useElectronStore } from '@/store/electron';+import KeepAwake from './KeepAwake';+interface PageProps {mobile?: boolean;}@@ -50,49 +52,52 @@ const Page = memo<PageProps>(({ mobile }) => {const externalDetail = !mobile;const list = (- <Form- collapsible={false}- itemsType={'group'}- variant={'filled'}- items={[- {- children: (- <DeviceManager- inlineDetail={!externalDetail}- scope={'personal'}- selectedDeviceId={selectedDeviceId}- onConnect={handleConnect}- onSelectedDeviceChange={setSelectedDeviceId}- />- ),- extra: (- <Flexbox horizontal align={'center'} gap={8}>- {devices.length > 0 && (- <Text fontSize={12} type={'secondary'} weight={500}>- {t('devices.selection.total', { count: devices.length })}- </Text>- )}- <Button- icon={<Icon icon={MonitorUpIcon} />}- size={'small'}- onClick={() => handleConnect()}- >- {t('devices.connectWizard.button')}- </Button>- <ActionIcon- icon={RefreshCwIcon}- loading={isValidating}- size={'small'}- title={t('devices.actions.refresh')}- onClick={() => mutate()}+ <Flexbox gap={24}>+ <Form+ collapsible={false}+ itemsType={'group'}+ variant={'filled'}+ items={[+ {+ children: (+ <DeviceManager+ inlineDetail={!externalDetail}+ scope={'personal'}+ selectedDeviceId={selectedDeviceId}+ onConnect={handleConnect}+ onSelectedDeviceChange={setSelectedDeviceId}/>- </Flexbox>- ),- title: t('devices.title'),- },- ]}- {...FORM_STYLE}- />+ ),+ extra: (+ <Flexbox horizontal align={'center'} gap={8}>+ {devices.length > 0 && (+ <Text fontSize={12} type={'secondary'} weight={500}>+ {t('devices.selection.total', { count: devices.length })}+ </Text>+ )}+ <Button+ icon={<Icon icon={MonitorUpIcon} />}+ size={'small'}+ onClick={() => handleConnect()}+ >+ {t('devices.connectWizard.button')}+ </Button>+ <ActionIcon+ icon={RefreshCwIcon}+ loading={isValidating}+ size={'small'}+ title={t('devices.actions.refresh')}+ onClick={() => mutate()}+ />+ </Flexbox>+ ),+ title: t('devices.title'),+ },+ ]}+ {...FORM_STYLE}+ />+ {isDesktop && <KeepAwake />}+ </Flexbox>);const connectModal = (diff --git a/src/services/electron/gatewayConnection.ts b/src/services/electron/gatewayConnection.tsindex 982f435e334..6e787a46a26 100644--- a/src/services/electron/gatewayConnection.ts+++ b/src/services/electron/gatewayConnection.ts@@ -13,6 +13,14 @@ class GatewayConnectionService {return ensureElectronIpc().gatewayConnection.getConnectionStatus();};+ getKeepAwake = async () => {+ return ensureElectronIpc().gatewayConnection.getKeepAwake();+ };++ setKeepAwake = async (enabled: boolean) => {+ return ensureElectronIpc().gatewayConnection.setKeepAwake({ enabled });+ };+getDeviceInfo = async () => {return ensureElectronIpc().gatewayConnection.getDeviceInfo();};