🤯 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
🐛 fix(desktop): make React DevTools work via standalone bridge (#17602)
Innei53d37c07dd7c
diff --git a/apps/desktop/README.md b/apps/desktop/README.mdindex ffae73fc589..558b93ed4de 100644--- a/apps/desktop/README.md+++ b/apps/desktop/README.md@@ -79,6 +79,21 @@ pnpm build:main # Production build (dist only)pnpm package:local # Local testing package```+### React DevTools++The renderer is served from the custom `app://renderer` origin, and Chromium+refuses to match extension content scripts against custom schemes — so the+React DevTools **browser extension can never attach** here, no matter how it is+installed. Use the standalone bridge instead, in two terminals:++```bash+pnpm react-devtools # standalone UI, listens on ws://localhost:8097+pnpm dev:react-devtools # dev run that injects the bridge script into the renderer+```++The bridge script is only injected while `DESKTOP_REACT_DEVTOOLS=1` is set, and+never in production builds.+## 🎯 Release Channels| Channel | Description | Stability | Auto-Updates |diff --git a/apps/desktop/README.zh-CN.md b/apps/desktop/README.zh-CN.mdindex f740104b996..fac2584379a 100644--- a/apps/desktop/README.zh-CN.md+++ b/apps/desktop/README.zh-CN.md@@ -79,6 +79,19 @@ pnpm build:main # 生产构建(仅 dist)pnpm package:local # 本地测试打包```+### React DevTools++渲染进程始终从自定义协议 `app://renderer` 加载,而 Chromium 不允许扩展的 content+script 匹配自定义协议 —— 因此 React DevTools **浏览器扩展在此永远无法挂载**,无论用+何种方式安装。请改用 standalone 桥接,开两个终端:++```bash+pnpm react-devtools # standalone 界面,监听 ws://localhost:8097+pnpm dev:react-devtools # 注入桥接脚本的开发启动命令+```++桥接脚本仅在 `DESKTOP_REACT_DEVTOOLS=1` 时注入,生产构建绝不包含。+## 🎯 发布渠道| 渠道 | 描述 | 稳定性 | 自动更新 |diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 4361d22e1d8..f3408783e71 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -16,6 +16,7 @@"build:main:raw": "vite build --config vite.main.config.ts && vite build --config vite.preload.config.ts && vite build --config vite.renderer.config.ts","build:run-unpack": "electron .","dev": "node scripts/dev.mjs",+ "dev:react-devtools": "cross-env DESKTOP_REACT_DEVTOOLS=1 npm run dev","dev:static": "cross-env DESKTOP_RENDERER_STATIC=1 npm run dev","fix:electron": "node scripts/fix-electron-runtime.mjs","format": "prettier --write ",@@ -35,6 +36,7 @@"package:mac": "npm run build:main && electron-builder --mac --config electron-builder.mjs --publish never","package:mac:local": "npm run build:main && cross-env UPDATE_CHANNEL=nightly electron-builder --mac --config electron-builder.mjs --publish never --c.mac.notarize=false -c.mac.identity=null","package:win": "npm run build:main && electron-builder --win --config electron-builder.mjs --publish never",+ "react-devtools": "bunx react-devtools@7","start": "npm run build:main && electron .","start:reuse": "electron .","stylelint": "stylelint \"src/**/*.{js,jsx,ts,tsx}\" --fix",@@ -85,7 +87,6 @@"diff": "^8.0.4","electron": "41.3.0","electron-builder": "26.14.0",- "electron-devtools-installer": "4.0.0","electron-is": "^3.0.0","electron-store": "^8.2.0","electron-updater": "^6.8.9",diff --git a/apps/desktop/src/main/core/App.ts b/apps/desktop/src/main/core/App.tsindex f9f602413d6..8cdcfab3b7b 100644--- a/apps/desktop/src/main/core/App.ts+++ b/apps/desktop/src/main/core/App.ts@@ -4,7 +4,6 @@ import path from 'node:path';import type { ElectronIPCEventHandler } from '@lobechat/electron-server-ipc';import { ElectronIPCServer } from '@lobechat/electron-server-ipc';import { app, nativeTheme, protocol } from 'electron';-import installExtension, { REACT_DEVELOPER_TOOLS } from 'electron-devtools-installer';import * as electronIs from 'electron-is';import { name } from '@/../../package.json';@@ -367,8 +366,6 @@ export class App {await app.whenReady();logger.debug('Application ready');- await this.installReactDevtools();-this.controllers.forEach((controller) => {if (typeof controller.afterAppReady === 'function') {try {@@ -384,21 +381,6 @@ export class App {logger.info('Application ready state completed');};- /**- * Development only: install React DevTools extension into Electron's devtools.- */- private installReactDevtools = async () => {- if (!isDev) return;-- try {- const name = await installExtension(REACT_DEVELOPER_TOOLS);-- logger.info(`Installed DevTools extension: ${name}`);- } catch (error) {- logger.warn('Failed to install React DevTools extension', error);- }- };-// ============= helper ============= ///**diff --git a/apps/desktop/src/main/core/__tests__/App.test.ts b/apps/desktop/src/main/core/__tests__/App.test.tsindex 306a482675c..600c4dfb8dd 100644--- a/apps/desktop/src/main/core/__tests__/App.test.ts+++ b/apps/desktop/src/main/core/__tests__/App.test.ts@@ -45,13 +45,6 @@ vi.mock('electron', () => ({},}));-// electron-devtools-installer accesses electron.app.getPath at import-time in node env;-// mock it to avoid side effects in unit tests-vi.mock('electron-devtools-installer', () => ({- REACT_DEVELOPER_TOOLS: 'REACT_DEVELOPER_TOOLS',- default: vi.fn(),-}));-vi.mock('fs-extra', () => ({pathExistsSync: (...args: any[]) => mockPathExistsSync(...args),}));diff --git a/apps/desktop/vite.renderer.config.ts b/apps/desktop/vite.renderer.config.tsindex 3c4dc8f58a3..5b5b4d337f1 100644--- a/apps/desktop/vite.renderer.config.ts+++ b/apps/desktop/vite.renderer.config.ts@@ -20,6 +20,7 @@ import {DEV_VITE_PORT,isCloudDesktopBuild,loadDesktopEnv,+ reactDevtoolsPlugin,RENDERER_CHROME_TARGET,ROOT_DIR,} from './vite.shared';@@ -245,6 +246,7 @@ export default defineConfig(async (env) => {isCloudDesktop && cloudTsconfigPathsPlugin(),isCloudDesktop && cloudDesktopBusinessConstPlugin(),electronDesktopHtmlPlugin(),+ reactDevtoolsPlugin(),excludeWebSpaBuildArtifactsPlugin(),vanillaExtractPlugin(),...(sharedRendererPlugins({ platform: 'desktop' }) as PluginOption[]),diff --git a/apps/desktop/vite.shared.test.ts b/apps/desktop/vite.shared.test.tsindex d62e7d8ba5f..051b32cf58e 100644--- a/apps/desktop/vite.shared.test.ts+++ b/apps/desktop/vite.shared.test.ts@@ -2,9 +2,14 @@ import { mkdtemp, rm, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import path from 'node:path';+import type { IndexHtmlTransformResult, Plugin } from 'vite';import { afterEach, describe, expect, it, vi } from 'vitest';-import { applyDesktopViteConfigExtension } from './vite.shared';+import {+ applyDesktopViteConfigExtension,+ REACT_DEVTOOLS_BRIDGE_URL,+ reactDevtoolsPlugin,+} from './vite.shared';describe('applyDesktopViteConfigExtension', () => {const temporaryDirectories: string[] = [];@@ -40,3 +45,37 @@ describe('applyDesktopViteConfigExtension', () => {expect(config.define).toEqual({ __TEST_TARGET__: '"main"' });});});++describe('reactDevtoolsPlugin', () => {+ afterEach(() => {+ vi.unstubAllEnvs();+ });++ const transformIndexHtml = () => {+ const plugin = reactDevtoolsPlugin() as Plugin & {+ transformIndexHtml: () => IndexHtmlTransformResult;+ };++ return plugin.transformIndexHtml();+ };++ it('injects nothing when DESKTOP_REACT_DEVTOOLS is unset', () => {+ vi.stubEnv('DESKTOP_REACT_DEVTOOLS', '');++ expect(transformIndexHtml()).toEqual([]);+ });++ it('injects the standalone bridge script when enabled', () => {+ vi.stubEnv('DESKTOP_REACT_DEVTOOLS', '1');++ expect(transformIndexHtml()).toEqual([+ { attrs: { src: REACT_DEVTOOLS_BRIDGE_URL }, injectTo: 'head-prepend', tag: 'script' },+ ]);+ });++ it('stays out of production builds', () => {+ vi.stubEnv('DESKTOP_REACT_DEVTOOLS', '1');++ expect((reactDevtoolsPlugin() as Plugin).apply).toBe('serve');+ });+});diff --git a/apps/desktop/vite.shared.ts b/apps/desktop/vite.shared.tsindex def0da3cd6b..6f2c7bf030f 100644--- a/apps/desktop/vite.shared.ts+++ b/apps/desktop/vite.shared.ts@@ -3,7 +3,7 @@ import { builtinModules } from 'node:module';import path from 'node:path';import dotenv from 'dotenv';-import type { ConfigEnv, UserConfig } from 'vite';+import type { ConfigEnv, PluginOption, UserConfig } from 'vite';import { loadEnv, runnerImport } from 'vite';export const DESKTOP_DIR = __dirname;@@ -33,6 +33,27 @@ export const loadDesktopEnv = (mode: string) => {Object.assign(process.env, loadEnv(mode, ROOT_DIR, ''));};+export const REACT_DEVTOOLS_BRIDGE_URL = 'http://localhost:8097';++/**+ * React DevTools cannot run as a Chrome extension here: its content scripts are+ * registered with `matches: ["<all_urls>"]`, and Chromium rejects widening that+ * to a custom scheme (both in the manifest and via `chrome.scripting`). The+ * renderer always loads from `app://renderer`, so the extension never installs+ * `window.__REACT_DEVTOOLS_GLOBAL_HOOK__` and its devtools panels never appear.+ * The standalone bridge (`npm run react-devtools`) is the only working path —+ * `http://localhost` stays exempt from mixed-content blocking on the secure+ * `app://` origin.+ */+export const reactDevtoolsPlugin = (): PluginOption => ({+ apply: 'serve',+ name: 'lobe-desktop-react-devtools',+ transformIndexHtml: () =>+ process.env.DESKTOP_REACT_DEVTOOLS === '1'+ ? [{ attrs: { src: REACT_DEVTOOLS_BRIDGE_URL }, injectTo: 'head-prepend', tag: 'script' }]+ : [],+});+export const nodeExternals = ['electron',/^electron\/.+/,