🤯 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): add a persistent remote debugging setting for packaged builds (#22869)
YuTengjingfdbbce7889e6
diff --git a/apps/desktop/src/common/remoteDebugging.ts b/apps/desktop/src/common/remoteDebugging.tsnew file mode 100644index 00000000000..cd460ef6437--- /dev/null+++ b/apps/desktop/src/common/remoteDebugging.ts@@ -0,0 +1,9 @@+/**+ * Renderer argument the main process adds while Chromium remote debugging (CDP) is on.+ * The preload reads it to tell the renderer to register its Zustand stores on+ * `window.__LOBE_STORES`, so a CDP client can read state snapshots from a packaged build.+ */+export const EXPOSE_STORES_ARG = '--lobe-expose-stores';++export const readExposeStoresArg = (argv: readonly string[]): boolean =>+ argv.includes(EXPOSE_STORES_ARG);diff --git a/apps/desktop/src/main/const/store.ts b/apps/desktop/src/main/const/store.tsindex 83e5fdcfcea..29d55a1b849 100644--- a/apps/desktop/src/main/const/store.ts+++ b/apps/desktop/src/main/const/store.ts@@ -42,6 +42,7 @@ export const STORE_DEFAULTS: ElectronMainStore = {localFileWorkspaceRoots: [],networkProxy: defaultProxySettings,pendingRestoreRoute: '',+ remoteDebuggingEnabled: false,shortcuts: DEFAULT_ELECTRON_DESKTOP_SHORTCUTS,storagePath: appStorageDir,themeMode: 'system',diff --git a/apps/desktop/src/main/controllers/SystemCtr.ts b/apps/desktop/src/main/controllers/SystemCtr.tsindex e936ae0e55b..588c9f542c0 100644--- a/apps/desktop/src/main/controllers/SystemCtr.ts+++ b/apps/desktop/src/main/controllers/SystemCtr.ts@@ -4,11 +4,13 @@ import process from 'node:process';import type {DebugLoggingSettings,ElectronAppState,+ RemoteDebuggingSettings,ThemeMode,} from '@lobechat/electron-client-ipc';import { app, dialog, nativeTheme, shell } from 'electron';import { legacyLocalDbDir } from '@/const/dir';+import { getRemoteDebuggingLaunchState, REMOTE_DEBUGGING_PORT } from '@/modules/remoteDebugging';import { createLogger } from '@/utils/logger';import {getAccessibilityStatus,@@ -223,6 +225,23 @@ export default class SystemController extends ControllerModule {return this.getDebugLoggingSettings();}+ @IpcMethod()+ getRemoteDebuggingSettings(): RemoteDebuggingSettings {+ return {+ ...getRemoteDebuggingLaunchState(),+ enabled: this.app.storeManager.get('remoteDebuggingEnabled', false),+ port: REMOTE_DEBUGGING_PORT,+ };+ }++ /** Persists the toggle; Chromium reads the CDP switch only at startup, so it applies on restart. */+ @IpcMethod()+ setRemoteDebuggingEnabled(enabled: boolean): RemoteDebuggingSettings {+ this.app.storeManager.set('remoteDebuggingEnabled', enabled);+ logger.info(`Remote debugging ${enabled ? 'enabled' : 'disabled'} for the next launch`);+ return this.getRemoteDebuggingSettings();+ }+/** Reveals `<userData>/logs/` so a user can attach the files to a bug report. */@IpcMethod()async openLogDirectory(): Promise<void> {diff --git a/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.tsindex 58bc4f0a1c3..7e38a9b8e2e 100644--- a/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts@@ -90,6 +90,12 @@ const structuredLogMock = vi.hoisted(() => ({}));vi.mock('@/utils/structuredLog', () => structuredLogMock);+const remoteDebuggingMock = vi.hoisted(() => ({+ REMOTE_DEBUGGING_PORT: 9222,+ getRemoteDebuggingLaunchState: vi.fn(() => ({ active: false, openedByLaunchOption: false })),+}));+vi.mock('@/modules/remoteDebugging', () => remoteDebuggingMock);+// Mock platform detectionvi.mock('@/utils/platform', () => ({macOS: vi.fn(() => true),@@ -256,6 +262,28 @@ describe('SystemController', () => {});});+ describe('remote debugging', () => {+ it('reports the persisted toggle with the current launch state', async () => {+ mockStoreManager.get.mockReturnValueOnce(true);++ expect(await invokeIpc('system.getRemoteDebuggingSettings')).toEqual({+ active: false,+ enabled: true,+ openedByLaunchOption: false,+ port: 9222,+ });+ });++ it('persists the toggle for the next launch without opening CDP now', async () => {+ mockStoreManager.get.mockReturnValueOnce(true);++ const result = await invokeIpc('system.setRemoteDebuggingEnabled', true);++ expect(mockStoreManager.set).toHaveBeenCalledWith('remoteDebuggingEnabled', true);+ expect(result).toMatchObject({ active: false, enabled: true });+ });+ });+describe('setLastWorkspaceSlug', () => {it("records the slug under the current account's entry", async () => {mockStoreManager.get.mockReturnValueOnce({ user_2: 'other' });diff --git a/apps/desktop/src/main/core/App.ts b/apps/desktop/src/main/core/App.tsindex e5968ae67f7..7f21db2ba7b 100644--- a/apps/desktop/src/main/core/App.ts+++ b/apps/desktop/src/main/core/App.ts@@ -26,6 +26,7 @@ import {} from '@/modules/binaries';import { generateCliWrapper, getCliWrapperDir } from '@/modules/cliEmbedding';import { PermissionGuide } from '@/modules/permissionGuide/PermissionGuide';+import { applyRemoteDebuggingSwitch } from '@/modules/remoteDebugging';import { ScreenCaptureManager } from '@/modules/screenCapture/ScreenCaptureManager';import { BUILD_CHANNEL, UPDATE_SERVER_URL } from '@/modules/updater/configs';import type { IServiceModule, ServiceLifecycle, ServiceModule } from '@/services';@@ -507,6 +508,7 @@ export class App {app.commandLine.appendSwitch('enable-precise-memory-info');app.commandLine.appendSwitch('enable-features', this.chromeFlags.join(','));+ applyRemoteDebuggingSwitch(this.storeManager.get('remoteDebuggingEnabled', false));logger.debug('Waiting for app to be ready');await app.whenReady();diff --git a/apps/desktop/src/main/core/__tests__/App.test.ts b/apps/desktop/src/main/core/__tests__/App.test.tsindex 3986ba998be..2565bdf3119 100644--- a/apps/desktop/src/main/core/__tests__/App.test.ts+++ b/apps/desktop/src/main/core/__tests__/App.test.ts@@ -26,6 +26,7 @@ vi.mock('electron', () => ({on: vi.fn(),commandLine: {appendSwitch: vi.fn(),+ hasSwitch: vi.fn(() => false),},dock: {setIcon: vi.fn(),diff --git a/apps/desktop/src/main/core/browser/Browser.ts b/apps/desktop/src/main/core/browser/Browser.tsindex bac69549ff9..472a3070647 100644--- a/apps/desktop/src/main/core/browser/Browser.ts+++ b/apps/desktop/src/main/core/browser/Browser.ts@@ -10,6 +10,7 @@ import { preloadDir, resourcesDir } from '@/const/dir';import { DESKTOP_EXTERNAL_NAVIGATION_HOSTS, isMac } from '@/const/env';import RemoteServerConfigCtr from '@/controllers/RemoteServerConfigCtr';import { backendProxyProtocolManager } from '@/core/infrastructure/BackendProxyProtocolManager';+import { getRemoteDebuggingRendererArgs } from '@/modules/remoteDebugging';import { appendVercelCookie, setResponseHeader } from '@/utils/http-headers';import { createLogger } from '@/utils/logger';import { getSystemLanguage, resolveUILocale } from '@/utils/system-language';@@ -242,7 +243,10 @@ export default class Browser {show: false,title,webPreferences: {- additionalArguments: [`${SYSTEM_LANGUAGE_ARG_PREFIX}${getSystemLanguage()}`],+ additionalArguments: [+ `${SYSTEM_LANGUAGE_ARG_PREFIX}${getSystemLanguage()}`,+ ...getRemoteDebuggingRendererArgs(),+ ],backgroundThrottling: false,contextIsolation: true,preload: path.join(preloadDir, 'index.js'),diff --git a/apps/desktop/src/main/core/browser/__tests__/Browser.test.ts b/apps/desktop/src/main/core/browser/__tests__/Browser.test.tsindex f95f3b5827f..71a086d6631 100644--- a/apps/desktop/src/main/core/browser/__tests__/Browser.test.ts+++ b/apps/desktop/src/main/core/browser/__tests__/Browser.test.ts@@ -1,3 +1,4 @@+import type { BrowserWindowConstructorOptions } from 'electron';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { type App as AppCore } from '../../App';@@ -58,6 +59,7 @@ const {return {mockAppModule: {+ commandLine: { hasSwitch: vi.fn(() => false) },dock: {setBadge: vi.fn(),show: vi.fn(),@@ -294,6 +296,18 @@ describe('Browser', () => {expect(MockBrowserWindow).toHaveBeenCalled();});+ it('tells the renderer to expose stores while remote debugging is on', () => {+ const rendererArgs = (call: unknown[] | undefined) =>+ (call?.[0] as BrowserWindowConstructorOptions).webPreferences?.additionalArguments;++ expect(rendererArgs(MockBrowserWindow.mock.calls[0])).not.toContain('--lobe-expose-stores');++ mockAppModule.commandLine.hasSwitch.mockReturnValueOnce(true);+ new Browser({ ...defaultOptions, identifier: 'debug-window' }, mockApp);++ expect(rendererArgs(MockBrowserWindow.mock.lastCall)).toContain('--lobe-expose-stores');+ });+it('loads the renderer directly without a splash-page navigation', async () => {await vi.waitFor(() => {expect(mockBrowserWindow.loadURL).toHaveBeenCalledWith(diff --git a/apps/desktop/src/main/modules/remoteDebugging/index.test.ts b/apps/desktop/src/main/modules/remoteDebugging/index.test.tsnew file mode 100644index 00000000000..b728d0384af--- /dev/null+++ b/apps/desktop/src/main/modules/remoteDebugging/index.test.ts@@ -0,0 +1,81 @@+import { app } from 'electron';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { EXPOSE_STORES_ARG, readExposeStoresArg } from '~common/remoteDebugging';++import type * as RemoteDebugging from './index';++vi.mock('electron', () => ({+ app: { commandLine: { appendSwitch: vi.fn(), hasSwitch: vi.fn() } },+}));++describe('remoteDebugging', () => {+ let applyRemoteDebuggingSwitch: typeof RemoteDebugging.applyRemoteDebuggingSwitch;+ let getRemoteDebuggingLaunchState: typeof RemoteDebugging.getRemoteDebuggingLaunchState;+ let getRemoteDebuggingRendererArgs: typeof RemoteDebugging.getRemoteDebuggingRendererArgs;+ let REMOTE_DEBUGGING_PORT: number;++ // The module remembers whether the toggle opened CDP, so each case loads a fresh copy.+ beforeEach(async () => {+ vi.clearAllMocks();+ vi.resetModules();+ vi.mocked(app.commandLine.hasSwitch).mockReturnValue(false);+ ({+ applyRemoteDebuggingSwitch,+ getRemoteDebuggingLaunchState,+ getRemoteDebuggingRendererArgs,+ REMOTE_DEBUGGING_PORT,+ } = await import('./index'));+ });++ it('opens the CDP port when the toggle is on', () => {+ applyRemoteDebuggingSwitch(true);++ expect(app.commandLine.appendSwitch).toHaveBeenCalledWith(+ 'remote-debugging-port',+ String(REMOTE_DEBUGGING_PORT),+ );+ });++ it('leaves the port closed when the toggle is off', () => {+ applyRemoteDebuggingSwitch(false);++ expect(app.commandLine.appendSwitch).not.toHaveBeenCalled();+ });++ it('keeps a port given on the command line', () => {+ vi.mocked(app.commandLine.hasSwitch).mockReturnValue(true);++ applyRemoteDebuggingSwitch(true);++ expect(app.commandLine.appendSwitch).not.toHaveBeenCalled();+ });++ it('tells the renderer to expose stores only while CDP is open', () => {+ expect(getRemoteDebuggingRendererArgs()).toEqual([]);++ vi.mocked(app.commandLine.hasSwitch).mockReturnValue(true);++ expect(getRemoteDebuggingRendererArgs()).toEqual([EXPOSE_STORES_ARG]);+ expect(readExposeStoresArg(['--other', EXPOSE_STORES_ARG])).toBe(true);+ expect(readExposeStoresArg(['--other'])).toBe(false);+ });++ it('reports CDP opened by the toggle as active and switchable', () => {+ applyRemoteDebuggingSwitch(true);+ vi.mocked(app.commandLine.hasSwitch).mockReturnValue(true);++ expect(getRemoteDebuggingLaunchState()).toEqual({ active: true, openedByLaunchOption: false });+ });++ it('reports CDP opened by a launch option as locked on', () => {+ vi.mocked(app.commandLine.hasSwitch).mockReturnValue(true);+ applyRemoteDebuggingSwitch(false);++ expect(getRemoteDebuggingLaunchState()).toEqual({ active: true, openedByLaunchOption: true });+ });++ it('reports CDP closed when neither opened it', () => {+ expect(getRemoteDebuggingLaunchState()).toEqual({ active: false, openedByLaunchOption: false });+ });+});diff --git a/apps/desktop/src/main/modules/remoteDebugging/index.ts b/apps/desktop/src/main/modules/remoteDebugging/index.tsnew file mode 100644index 00000000000..d874a562ef4--- /dev/null+++ b/apps/desktop/src/main/modules/remoteDebugging/index.ts@@ -0,0 +1,50 @@+import { app } from 'electron';++import { createLogger } from '@/utils/logger';+import { EXPOSE_STORES_ARG } from '~common/remoteDebugging';++const logger = createLogger('modules:remoteDebugging');++/** Port the persisted Settings → About → Remote Debugging toggle opens CDP on. */+export const REMOTE_DEBUGGING_PORT = 9222;++const REMOTE_DEBUGGING_SWITCH = 'remote-debugging-port';++/** Whether this launch opened CDP because of the persisted toggle, not a launch option. */+let openedByToggle = false;++/**+ * Open the Chromium DevTools protocol port when the user turned the toggle on.+ * Must run before `app.whenReady()`: Chromium reads the switch only at startup,+ * so a change applies on the next launch.+ *+ * A port already given on the command line (`--remote-debugging-port`, or the dev+ * launcher's `LOBE_DESKTOP_CDP_PORT`) wins. Chromium binds the port to 127.0.0.1.+ */+export const applyRemoteDebuggingSwitch = (enabled: boolean): void => {+ if (!enabled || app.commandLine.hasSwitch(REMOTE_DEBUGGING_SWITCH)) return;++ app.commandLine.appendSwitch(REMOTE_DEBUGGING_SWITCH, String(REMOTE_DEBUGGING_PORT));+ openedByToggle = true;+ logger.warn(`Remote debugging is enabled on 127.0.0.1:${REMOTE_DEBUGGING_PORT}`);+};++/**+ * Renderer arguments for app windows. While CDP is open, by the toggle or a+ * command-line switch, the renderer also exposes its store snapshots: anything that+ * can attach to CDP can already evaluate code in the page, so this adds no access.+ */+export const getRemoteDebuggingRendererArgs = (): string[] =>+ app.commandLine.hasSwitch(REMOTE_DEBUGGING_SWITCH) ? [EXPOSE_STORES_ARG] : [];++export interface RemoteDebuggingLaunchState {+ /** CDP is open in this launch, by the toggle or a launch option. */+ active: boolean;+ /** A launch option opened CDP, so the toggle cannot close it. */+ openedByLaunchOption: boolean;+}++export const getRemoteDebuggingLaunchState = (): RemoteDebuggingLaunchState => {+ const active = app.commandLine.hasSwitch(REMOTE_DEBUGGING_SWITCH);+ return { active, openedByLaunchOption: active && !openedByToggle };+};diff --git a/apps/desktop/src/main/types/store.ts b/apps/desktop/src/main/types/store.tsindex 1438dad7c4c..a9d77fd2439 100644--- a/apps/desktop/src/main/types/store.ts+++ b/apps/desktop/src/main/types/store.ts@@ -88,6 +88,12 @@ export interface ElectronMainStore {localFileWorkspaceRoots: string[];networkProxy: NetworkProxySettings;pendingRestoreRoute: string;+ /**+ * Settings → About → Remote Debugging: open the Chromium DevTools protocol port on every+ * launch, even in packaged builds, so agents can evaluate code, read store+ * snapshots and take screenshots. Off by default; a change applies on restart.+ */+ remoteDebuggingEnabled: boolean;shortcuts: Record<string, string>;storagePath: string;themeMode: 'dark' | 'light' | 'system';diff --git a/apps/desktop/src/preload/electronApi.ts b/apps/desktop/src/preload/electronApi.tsindex ee4575361f3..ac1dc73e777 100644--- a/apps/desktop/src/preload/electronApi.ts+++ b/apps/desktop/src/preload/electronApi.ts@@ -2,6 +2,7 @@ import { electronAPI } from '@electron-toolkit/preload';import type { RendererMemoryInfo, ScreenCaptureSession } from '@lobechat/electron-client-ipc';import { contextBridge, ipcRenderer } from 'electron';+import { readExposeStoresArg } from '~common/remoteDebugging';import { readSystemLanguageArg } from '~common/systemLanguage';import { invoke } from './invoke';@@ -73,6 +74,7 @@ export const setupElectronApi = () => {chromeVersion: process.versions.chrome,darwinMajorVersion,electronVersion: process.versions.electron,+ exposeStores: readExposeStoresArg(process.argv),isMacTahoe: process.platform === 'darwin' && darwinMajorVersion >= 25,nodeVersion: process.versions.node,platform: process.platform,diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex cebe3d44ebc..7dda75a5458 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -1384,6 +1384,13 @@"settingAbout.debugLogs.openDirectoryDesc": "Attach these files when you report an issue.","settingAbout.debugLogs.title": "Debug Logs","settingAbout.diagnostics.title": "Diagnostics",+ "settingAbout.remoteDebugging.confirm.content": "After you restart LobeHub, programs on this computer can connect to port {{port}}, control LobeHub windows, and read your signed-in session and data. The port opens on every launch until you turn this off. Turn it on only while debugging.",+ "settingAbout.remoteDebugging.confirm.ok": "Allow",+ "settingAbout.remoteDebugging.confirm.title": "Allow remote debugging?",+ "settingAbout.remoteDebugging.desc": "Let developer tools on this computer connect to LobeHub on port {{port}} and read app state.",+ "settingAbout.remoteDebugging.launchOptionDesc": "Remote debugging was turned on by a launch option for this session.",+ "settingAbout.remoteDebugging.restartToApply": "Restart LobeHub to apply this change.",+ "settingAbout.remoteDebugging.title": "Remote Debugging","settingAgent.agentTools.add": "Add Tool","settingAgent.agentTools.agentEmpty": "No agent-exclusive tools yet","settingAgent.agentTools.authorizedBy": "Authorized by {{name}}",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex d0e02335663..e583058fc4e 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -1384,6 +1384,13 @@"settingAbout.debugLogs.openDirectoryDesc": "反馈问题时可附上这些文件。","settingAbout.debugLogs.title": "调试日志","settingAbout.diagnostics.title": "诊断",+ "settingAbout.remoteDebugging.confirm.content": "重启 LobeHub 后,本机上的程序可以通过端口 {{port}} 控制 LobeHub 窗口,并读取你的登录状态和数据。关闭前每次启动都会开放该端口,请仅在调试时开启。",+ "settingAbout.remoteDebugging.confirm.ok": "允许",+ "settingAbout.remoteDebugging.confirm.title": "允许远程调试?",+ "settingAbout.remoteDebugging.desc": "允许本机的开发者工具通过端口 {{port}} 连接 LobeHub 并读取应用状态。",+ "settingAbout.remoteDebugging.launchOptionDesc": "本次运行已通过启动参数开启远程调试。",+ "settingAbout.remoteDebugging.restartToApply": "重启 LobeHub 后生效。",+ "settingAbout.remoteDebugging.title": "远程调试","settingAgent.agentTools.add": "添加工具","settingAgent.agentTools.agentEmpty": "还没有 Agent 专属工具","settingAgent.agentTools.authorizedBy": "由 {{name}} 授权",diff --git a/packages/electron-client-ipc/src/types/system.ts b/packages/electron-client-ipc/src/types/system.tsindex 961b3849385..c698120a29a 100644--- a/packages/electron-client-ipc/src/types/system.ts+++ b/packages/electron-client-ipc/src/types/system.ts@@ -33,6 +33,18 @@ export type ThemeAppearance = 'dark' | 'light' | string;export type GuidedPermission = 'accessibility' | 'fullDisk' | 'inputMonitoring' | 'screen';export type PermissionGuideStatus = 'active' | 'dismissed' | 'granted';+/** Settings → About → Remote debugging. */+export interface RemoteDebuggingSettings {+ /** CDP is open in this launch; differs from `enabled` until the app restarts. */+ active: boolean;+ /** Persisted toggle, read at the next launch. */+ enabled: boolean;+ /** A launch option (`--remote-debugging-port`) opened CDP, so the switch is shown on and locked. */+ openedByLaunchOption: boolean;+ /** Local port CDP listens on while the toggle is on. */+ port: number;+}+/** Settings → About → Debug logs. */export interface DebugLoggingSettings {/** Dev builds record `debug` regardless of `enabled`, so the switch is shown on and locked. */diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex d940c14b83c..e87ffa68581 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -1366,6 +1366,16 @@ export default {'settingAbout.debugLogs.openDirectoryDesc': 'Attach these files when you report an issue.','settingAbout.debugLogs.title': 'Debug Logs','settingAbout.diagnostics.title': 'Diagnostics',+ 'settingAbout.remoteDebugging.confirm.content':+ 'After you restart LobeHub, programs on this computer can connect to port {{port}}, control LobeHub windows, and read your signed-in session and data. The port opens on every launch until you turn this off. Turn it on only while debugging.',+ 'settingAbout.remoteDebugging.confirm.ok': 'Allow',+ 'settingAbout.remoteDebugging.confirm.title': 'Allow remote debugging?',+ 'settingAbout.remoteDebugging.desc':+ 'Let developer tools on this computer connect to LobeHub on port {{port}} and read app state.',+ 'settingAbout.remoteDebugging.launchOptionDesc':+ 'Remote debugging was turned on by a launch option for this session.',+ 'settingAbout.remoteDebugging.restartToApply': 'Restart LobeHub to apply this change.',+ 'settingAbout.remoteDebugging.title': 'Remote Debugging','settingAppearance.appTray.desc':'Show the LobeHub icon in the system tray or macOS menu bar. Disabling it also removes tray menu access.','settingAppearance.appTray.title': 'Show App Tray',diff --git a/src/features/Settings/about/features/DebugLogs.tsx b/src/features/Settings/about/features/DebugLogs.tsxindex f1a7dee0dae..0665dde7daa 100644--- a/src/features/Settings/about/features/DebugLogs.tsx+++ b/src/features/Settings/about/features/DebugLogs.tsx@@ -12,6 +12,8 @@ import { FORM_STYLE } from '@/const/layoutTokens';import { SettingsSearchAnchor } from '@/features/SettingsSearch/anchor';import { desktopSettingsService } from '@/services/electron/settings';+import { useRemoteDebuggingItem } from './useRemoteDebuggingItem';+/*** Desktop-only: packaged builds record `info` and above by default; this switch* adds `debug` records while a user reproduces a bug. Dev builds always record@@ -21,6 +23,7 @@ const DebugLogs = memo(() => {const { t } = useTranslation('setting');const [updating, setUpdating] = useState(false);const form = useForm();+ const remoteDebuggingItem = useRemoteDebuggingItem();const { data, mutate } = useSWR(isDesktop ? 'desktop-debug-logging-settings' : null,@@ -69,6 +72,7 @@ const DebugLogs = memo(() => {label: t('settingAbout.debugLogs.directory'),minWidth: undefined,},+ ...(remoteDebuggingItem ? [remoteDebuggingItem] : []),],title: t('settingAbout.diagnostics.title'),};diff --git a/src/features/Settings/about/features/useRemoteDebuggingItem.tsx b/src/features/Settings/about/features/useRemoteDebuggingItem.tsxnew file mode 100644index 00000000000..bc435e0c29d--- /dev/null+++ b/src/features/Settings/about/features/useRemoteDebuggingItem.tsx@@ -0,0 +1,79 @@+'use client';++import { isDesktop } from '@lobechat/const';+import { confirmModal, Switch } from '@lobehub/ui';+import { type FormFieldProps } from '@lobehub/ui/form';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';+import useSWR from 'swr';++import { SettingsSearchAnchor } from '@/features/SettingsSearch/anchor';+import { desktopSettingsService } from '@/services/electron/settings';++/**+ * Desktop-only Diagnostics row: persist the Chromium DevTools protocol (CDP) port for+ * every launch, so agents can drive a packaged build. Chromium reads the switch only at+ * startup, so the row says when a change still needs a restart. A launch option that+ * already opened CDP shows the switch on and locked.+ */+export const useRemoteDebuggingItem = (): FormFieldProps | undefined => {+ const { t } = useTranslation('setting');+ const [updating, setUpdating] = useState(false);++ const { data, mutate } = useSWR(+ isDesktop ? 'desktop-remote-debugging-settings' : null,+ desktopSettingsService.getRemoteDebuggingSettings,+ { revalidateOnFocus: false },+ );++ if (!isDesktop) return;++ const save = async (enabled: boolean) => {+ setUpdating(true);+ try {+ const next = await desktopSettingsService.setRemoteDebuggingEnabled(enabled);+ await mutate(next, { revalidate: false });+ } finally {+ setUpdating(false);+ }+ };++ const port = data?.port;+ const desc = data?.openedByLaunchOption+ ? t('settingAbout.remoteDebugging.launchOptionDesc')+ : data && data.enabled !== data.active+ ? t('settingAbout.remoteDebugging.restartToApply')+ : t('settingAbout.remoteDebugging.desc', { port });++ return {+ children: (+ <Switch+ checked={data ? data.openedByLaunchOption || data.enabled : false}+ disabled={!data || data.openedByLaunchOption}+ loading={updating}+ onChange={(checked: boolean) => {+ if (!checked) {+ void save(false);+ return;+ }+ // Opening CDP hands local programs full control of the app; confirm first.+ confirmModal({+ cancelText: t('cancel', { ns: 'common' }),+ content: t('settingAbout.remoteDebugging.confirm.content', { port }),+ okButtonProps: { danger: true },+ okText: t('settingAbout.remoteDebugging.confirm.ok'),+ onOk: () => save(true),+ title: t('settingAbout.remoteDebugging.confirm.title'),+ });+ }}+ />+ ),+ desc,+ label: (+ <SettingsSearchAnchor id={'about-remote-debugging'}>+ {t('settingAbout.remoteDebugging.title')}+ </SettingsSearchAnchor>+ ),+ minWidth: undefined,+ };+};diff --git a/src/features/SettingsSearch/items.ts b/src/features/SettingsSearch/items.tsindex 809e6d922a0..e9146039188 100644--- a/src/features/SettingsSearch/items.ts+++ b/src/features/SettingsSearch/items.ts@@ -368,6 +368,13 @@ export const SETTINGS_SEARCH_ITEMS: SettingsSearchItem[] = [tab: SettingsTabs.About,visible: (ctx) => ctx.isDesktop,},+ {+ anchor: 'about-remote-debugging',+ keywords: ['remote debugging', 'cdp', 'devtools', 'diagnostics', 'debug port'],+ labelKey: 'settingAbout.remoteDebugging.title',+ tab: SettingsTabs.About,+ visible: (ctx) => ctx.isDesktop,+ },{anchor: 'appearance-font-family',descKey: 'settingAppearance.font.fontFamily.desc',diff --git a/src/services/electron/settings.ts b/src/services/electron/settings.tsindex 9b7ea5e7a9d..36ee1d66faf 100644--- a/src/services/electron/settings.ts+++ b/src/services/electron/settings.ts@@ -28,6 +28,20 @@ class DesktopSettingsService {return ensureElectronIpc().system.setDebugLoggingEnabled(enabled);};+ /**+ * Get the Remote debugging setting (Settings → About)+ */+ getRemoteDebuggingSettings = async () => {+ return ensureElectronIpc().system.getRemoteDebuggingSettings();+ };++ /**+ * Persist the CDP toggle; it applies at the next launch+ */+ setRemoteDebuggingEnabled = async (enabled: boolean) => {+ return ensureElectronIpc().system.setRemoteDebuggingEnabled(enabled);+ };+/*** Reveal the desktop log directory in the system file manager*/diff --git a/src/store/middleware/expose.test.ts b/src/store/middleware/expose.test.tsnew file mode 100644index 00000000000..937e355ba0f--- /dev/null+++ b/src/store/middleware/expose.test.ts@@ -0,0 +1,42 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { expose } from './expose';++const envState = vi.hoisted(() => ({ isDev: false }));+vi.mock('@/utils/env', () => ({+ get isDev() {+ return envState.isDev;+ },+}));++const store = { getState: () => ({ count: 1 }) };++describe('expose', () => {+ afterEach(() => {+ envState.isDev = false;+ delete window.__LOBE_STORES;+ delete window.lobeEnv;+ });++ it('keeps production stores private', () => {+ expose('counter', store);++ expect(window.__LOBE_STORES).toBeUndefined();+ });++ it('exposes stores in development', () => {+ envState.isDev = true;++ expose('counter', store);++ expect(window.__LOBE_STORES?.counter()).toEqual({ count: 1 });+ });++ it('exposes production stores while Desktop remote debugging is on', () => {+ window.lobeEnv = { exposeStores: true };++ expose('counter', store);++ expect(window.__LOBE_STORES?.counter()).toEqual({ count: 1 });+ });+});diff --git a/src/store/middleware/expose.ts b/src/store/middleware/expose.tsindex db17615df4b..94c9c5b4fd3 100644--- a/src/store/middleware/expose.ts+++ b/src/store/middleware/expose.ts@@ -1,11 +1,14 @@import { isDev } from '@/utils/env';/**- * In development, registers the store on `window.__LOBE_STORES[name]` as a getter that returns- * the current snapshot from `store.getState()`.+ * Registers the store on `window.__LOBE_STORES[name]` as a getter that returns the current+ * snapshot from `store.getState()`. Runs in development, and in Desktop builds while remote+ * debugging is on: the preload sets `lobeEnv.exposeStores` before any store module loads, and+ * a CDP client can already evaluate code in the page, so the snapshots add no access.*/export function expose<T>(name: string, store: { getState: () => T }): void {- if (!isDev || typeof window === 'undefined') return;+ if (typeof window === 'undefined') return;+ if (!isDev && !window.lobeEnv?.exposeStores) return;window.__LOBE_STORES ??= {};window.__LOBE_STORES[name] = () => store.getState();diff --git a/src/types/global.d.ts b/src/types/global.d.tsindex 35e5edb0a97..ebcca521712 100644--- a/src/types/global.d.ts+++ b/src/types/global.d.ts@@ -11,7 +11,10 @@ declare global {__DEBUG_PROXY__: boolean | undefined;__editor?: IEditor;__LOBE_BOOT_T_HTML__?: number;- /** Dev-only: Zustand store snapshots via `getState()` keyed by store name */+ /**+ * Zustand store snapshots via `getState()` keyed by store name. Registered in dev, and in+ * Desktop builds while remote debugging is on (`lobeEnv.exposeStores`).+ */__LOBE_STORES?: Record<string, () => unknown>;/** Chat input editor of the main composer, mounted by MainChatInput while it is on screen */__mainEditor?: ChatInputEditor;@@ -20,6 +23,8 @@ declare global {chromeVersion?: string;darwinMajorVersion?: number;electronVersion?: string;+ /** Desktop remote debugging (CDP) is on, so stores register on `window.__LOBE_STORES` */+ exposeStores?: boolean;isMacTahoe?: boolean;nodeVersion?: string;platform?: NodeJS.Platform;