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.

πŸ› fix(desktop): restore dev & automation pipeline after electron-vite removal (#17238)

Inneie55eb448236b
diff --git a/.agents/skills/agent-testing/references/common-mistakes.md b/.agents/skills/agent-testing/references/common-mistakes.md
index 4a107b6c563..b80091b97cc 100644
--- a/.agents/skills/agent-testing/references/common-mistakes.md
+++ b/.agents/skills/agent-testing/references/common-mistakes.md
@@ -230,7 +230,7 @@ false fail), on the wrong bundle entirely.
**Correct approach**: to verify working-tree UI in the desktop shape, start an
isolated dev instance that loads live code β€” `electron-dev.sh start <id>` runs
-`electron-vite dev` (its own CDP/Vite, copied login), which DOES bundle your src
+the dev orchestrator `scripts/dev.mjs` (its own CDP/Vite, copied login), which DOES bundle your src
changes. Prove it's live by MEASURING a known-changed value (e.g. computed
`::before` inset 10px vs old 28px) before trusting any screenshot. Don't kill the
user's resident 9222 app β€” use a pool id. Also: `agent-browser open` mangles
diff --git a/.agents/skills/agent-testing/references/multi-instance.md b/.agents/skills/agent-testing/references/multi-instance.md
index 64620b85b48..fabb2d2a4c2 100644
--- a/.agents/skills/agent-testing/references/multi-instance.md
+++ b/.agents/skills/agent-testing/references/multi-instance.md
@@ -54,7 +54,7 @@ app sessions are dev-build singletons. Validated verdicts:
| Electron single-instance lock | `App.ts:227` | βœ… **keyed by userData** β€” distinct userData dirs each get their own lock; all instances run. No code change needed. |
| Chromium `SingletonLock` | per userData dir | βœ… one per userData dir automatically (observed distinct PIDs per dir). |
| userData dir `lobehub-desktop-dev` | `pre-app-init.ts:12` | βœ… fixed β€” now env-overridable via `LOBE_DESKTOP_USER_DATA_DIR`. |
-| Vite dev server `strictPort:true` 5173 | `electron.vite.config.ts` | βœ… fixed β€” now env-overridable via `LOBE_DESKTOP_VITE_PORT` (Model B: one Vite per worktree). |
+| Vite dev server `strictPort:true` 5173 | `apps/desktop/vite.shared.ts` | βœ… fixed β€” now env-overridable via `LOBE_DESKTOP_VITE_PORT` (Model B: one Vite per worktree). |
| `electron-server-ipc` unix socket | `App.ts` β†’ `packages/electron-server-ipc/src/ipcServer.ts:23-31` | βœ… fixed β€” id now env-overridable via `LOBE_IPC_ID`; distinct sockets, no more hijack (was last-writer-wins). |
| safeStorage / Chromium cookie encryption | OS keychain, keyed by **app name** | πŸ”‘ requires **app name constant** to decrypt a copied login state. |
| Global shortcuts / `lobehub://` protocol | OS-global | first/last wins; harmless for headless automation. |
@@ -105,7 +105,7 @@ branch ships all three:
this.ipcServer = new ElectronIPCServer(ipcId, ipcServerEvents);
```
-3. **`apps/desktop/electron.vite.config.ts`** β€” per-instance Vite dev port
+3. **`apps/desktop/vite.shared.ts`** β€” per-instance Vite dev port
(Model B: one Vite per worktree), kept `strictPort` so HMR clientPort matches:
```ts
@@ -180,14 +180,15 @@ Raw `curl http://localhost:<port>/json/list` always shows a port's true target
### Model A β€” one Vite, many electron processes (what the validation used)
-One `electron-vite dev` owns Vite 5173 + the built `dist/main`; extra instances
-are raw electrons sharing the renderer via `ELECTRON_RENDERER_URL`:
+One dev orchestrator (`pnpm dev` in `apps/desktop`) owns Vite 5173 + the built
+`dist/main`; extra instances are raw electrons sharing the renderer via
+`ELECTRON_RENDERER_URL`:
```bash
# instance 1: owns Vite 5173 + is itself CDP 9223
cd apps/desktop
LOBE_DESKTOP_USER_DATA_DIR=/tmp/lobe-ud-1 \
- npx electron-vite dev -- --remote-debugging-port=9223
+ pnpm dev -- --remote-debugging-port=9223
# instances 2,3: reuse Vite 5173 + built main, isolate userData + CDP
LOBE_DESKTOP_USER_DATA_DIR=/tmp/lobe-ud-2 ELECTRON_RENDERER_URL=http://127.0.0.1:5173 \
@@ -200,19 +201,20 @@ Lightest; all share one build/renderer. Extra instances get no HMR re-launch.
### Model B β€” one Vite per worktree (the N-worktree use case)
-Each worktree runs its own `electron-vite dev` (own code, own build, own HMR).
+Each worktree runs its own dev orchestrator (own code, own build, own HMR).
The `LOBE_DESKTOP_VITE_PORT` knob makes this work β€” otherwise the 2nd worktree
fails on `strictPort` 5173. Just use the pool (below), or by hand per worktree:
```bash
LOBE_DESKTOP_VITE_PORT=51xx LOBE_DESKTOP_USER_DATA_DIR=… LOBE_IPC_ID=… \
- npx electron-vite dev -- --remote-debugging-port=92xx
+ pnpm dev -- --remote-debugging-port=92xx
```
-`electron-vite dev` injects the matching `ELECTRON_RENDERER_URL` automatically.
+`pnpm dev` injects the matching `ELECTRON_RENDERER_URL` automatically.
Cost: N Vite servers + N builds (heavy); acceptable since each worktree is a
-distinct dev target. **Validated** β€” two `electron-vite dev` on 5174 + 5175 ran
-concurrently (transcript below).
+distinct dev target. **Validated** β€” two dev orchestrators on 5174 + 5175 ran
+concurrently (transcript below, recorded pre-migration with `electron-vite dev`;
+the port/isolation knobs are unchanged).
## electron-dev.sh instance pool (implemented)
diff --git a/.agents/skills/agent-testing/scripts/electron-dev.sh b/.agents/skills/agent-testing/scripts/electron-dev.sh
index 5b4abb581ef..99113abd0e4 100755
--- a/.agents/skills/agent-testing/scripts/electron-dev.sh
+++ b/.agents/skills/agent-testing/scripts/electron-dev.sh
@@ -126,8 +126,8 @@ expand_descendants() {
# Seed PIDs for the CURRENT instance only. Pool mode scopes strictly to this
# instance (pidfile session leader + whoever holds this instance's CDP/Vite
# ports) so stopping one instance never kills a sibling. Legacy mode additionally
-# sweeps the project's Electron + electron-vite (to tear down a stray `bun run
-# dev` the user started outside this script).
+# sweeps the project's Electron + dev orchestrator (to tear down a stray `bun
+# run dev` the user started outside this script).
find_instance_pids() {
local pids=""
@@ -155,7 +155,7 @@ find_instance_pids() {
# 4. Legacy only: broad project matching (would cross pool instances)
if [ "$POOL_MODE" = "0" ]; then
pids="$pids $(pgrep -f "$PROJECT_ELECTRON_PATH" 2>/dev/null || true)"
- pids="$pids $(pgrep -f "electron-vite[/.].*\\bdev\\b" 2>/dev/null || true)"
+ pids="$pids $(pgrep -f "scripts/dev\\.mjs" 2>/dev/null || true)"
fi
# `|| true` because `grep -v '^$'` exits 1 on all-empty input, which with
diff --git a/.agents/skills/agent-testing/scripts/record-electron-demo.sh b/.agents/skills/agent-testing/scripts/record-electron-demo.sh
index d5f1a6fd336..ac0aec38268 100755
--- a/.agents/skills/agent-testing/scripts/record-electron-demo.sh
+++ b/.agents/skills/agent-testing/scripts/record-electron-demo.sh
@@ -36,7 +36,7 @@ RECORD_PID=""
cleanup() {
echo "[cleanup] Stopping all processes..."
[ -n "$RECORD_PID" ] && kill -INT "$RECORD_PID" 2>/dev/null && sleep 2
- pkill -f "electron-vite" 2>/dev/null || true
+ pkill -f "scripts/dev.mjs" 2>/dev/null || true
pkill -f "Electron" 2>/dev/null || true
pkill -f "agent-browser" 2>/dev/null || true
echo "[cleanup] Done."
@@ -317,14 +317,14 @@ echo "=== Electron Demo Recorder ==="
# 1. Kill existing instances
echo "[setup] Cleaning up existing processes..."
pkill -f "Electron" 2>/dev/null || true
-pkill -f "electron-vite" 2>/dev/null || true
+pkill -f "scripts/dev.mjs" 2>/dev/null || true
pkill -f "agent-browser" 2>/dev/null || true
sleep 3
# 2. Start Electron
echo "[setup] Starting Electron..."
cd "$PROJECT_ROOT/apps/desktop"
-ELECTRON_ENABLE_LOGGING=1 npx electron-vite dev -- --remote-debugging-port="$CDP_PORT" > "$ELECTRON_LOG" 2>&1 &
+ELECTRON_ENABLE_LOGGING=1 pnpm dev -- --remote-debugging-port="$CDP_PORT" > "$ELECTRON_LOG" 2>&1 &
wait_for_electron
wait_for_renderer
diff --git a/.agents/skills/agent-testing/ui/electron.md b/.agents/skills/agent-testing/ui/electron.md
index 531407cac1c..1ef96bc2c4f 100644
--- a/.agents/skills/agent-testing/ui/electron.md
+++ b/.agents/skills/agent-testing/ui/electron.md
@@ -171,7 +171,7 @@ agent-browser --cdp 9222 eval "JSON.stringify(window.__CAPTURED_ERRORS)"
- **Always use `electron-dev.sh stop` to clean up** β€” `pkill -f "Electron"` only kills the main process; helper processes (GPU, renderer, network) survive. The script finds and kills all of them via PID matching against the project's electron binary path.
-- **`npx electron-vite dev` must run from `apps/desktop/`** β€” running from project root fails silently. The `electron-dev.sh` script handles this automatically.
+- **`pnpm dev` must run from `apps/desktop/`** β€” running from project root starts the web app instead. The `electron-dev.sh` script handles this automatically.
- **Dev build auto-opens DevTools, which hijacks the CDP target** β€” `agent-browser --cdp 9222` may attach to the DevTools page (`devtools://…`) instead of the app (`app://renderer/`). Symptom: `get url` returns a `devtools://` URL. Fix: close the DevTools target and reconnect:
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index ef7b8746601..74241a243a1 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -35,7 +35,8 @@
"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",
- "start": "electron .",
+ "start": "npm run build:main && electron .",
+ "start:reuse": "electron .",
"stylelint": "stylelint \"src/**/*.{js,jsx,ts,tsx}\" --fix",
"test": "vitest --run",
"type-check": "tsgo --noEmit -p tsconfig.json",
diff --git a/apps/desktop/scripts/__tests__/devOrchestrator.test.mjs b/apps/desktop/scripts/__tests__/devOrchestrator.test.mjs
new file mode 100644
index 00000000000..754834836b5
--- /dev/null
+++ b/apps/desktop/scripts/__tests__/devOrchestrator.test.mjs
@@ -0,0 +1,210 @@
+import { EventEmitter } from 'node:events';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createDevOrchestrator } from '../devOrchestrator.mjs';
+
+class FakeChild extends EventEmitter {
+ kill = vi.fn();
+}
+
+const createHarness = (overrides = {}) => {
+ const spawned = [];
+ const watchers = [];
+ const state = { bundlesExist: false, mtime: 1, portReady: false };
+
+ const options = {
+ checkPort: vi.fn(async () => state.portReady),
+ desktopRoot: '/repo/apps/desktop',
+ electronBin: '/bin/electron',
+ exit: vi.fn(),
+ existsSync: vi.fn(() => state.bundlesExist),
+ log: vi.fn(),
+ logError: vi.fn(),
+ nodeBin: '/bin/node',
+ spawn: vi.fn((bin, args, opts) => {
+ const child = new FakeChild();
+ spawned.push({ args, bin, child, opts });
+ return child;
+ }),
+ statSync: vi.fn(() => ({ mtimeMs: state.mtime })),
+ viteBin: '/repo/node_modules/vite/bin/vite.js',
+ vitePort: 5199,
+ watch: vi.fn((dir, cb) => {
+ watchers.push(cb);
+ }),
+ ...overrides,
+ };
+
+ const orchestrator = createDevOrchestrator(options);
+ const viteChildren = () => spawned.filter((s) => s.bin === '/bin/node');
+ const electronSpawns = () => spawned.filter((s) => s.bin === '/bin/electron');
+
+ const becomeReady = async () => {
+ state.bundlesExist = true;
+ state.portReady = true;
+ await vi.advanceTimersByTimeAsync(2000);
+ };
+
+ return {
+ becomeReady,
+ electronSpawns,
+ options,
+ orchestrator,
+ spawned,
+ state,
+ viteChildren,
+ watchers,
+ };
+};
+
+describe('createDevOrchestrator', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('spawns the three vite processes through the node binary (no pnpm shim)', () => {
+ const h = createHarness();
+ h.orchestrator.start();
+
+ expect(h.viteChildren()).toHaveLength(3);
+ for (const { args, opts } of h.viteChildren()) {
+ expect(args[0]).toBe('/repo/node_modules/vite/bin/vite.js');
+ expect(opts.cwd).toBe('/repo/apps/desktop');
+ }
+ const configs = h.viteChildren().map(({ args }) => args.at(-1));
+ expect(configs).toEqual([
+ 'vite.renderer.config.ts',
+ 'vite.main.config.ts',
+ 'vite.preload.config.ts',
+ ]);
+ });
+
+ it('shuts everything down when a vite child exits early', () => {
+ const h = createHarness();
+ h.orchestrator.start();
+
+ h.viteChildren()[1].child.emit('exit', 7);
+
+ expect(h.options.exit).toHaveBeenCalledWith(7);
+ for (const { child } of h.viteChildren()) {
+ expect(child.kill).toHaveBeenCalled();
+ }
+ expect(h.electronSpawns()).toHaveLength(0);
+ });
+
+ it('launches electron only after bundles are stable and the renderer port accepts', async () => {
+ const h = createHarness();
+ h.orchestrator.start();
+
+ h.state.bundlesExist = true;
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(h.electronSpawns()).toHaveLength(0);
+
+ h.state.portReady = true;
+ await vi.advanceTimersByTimeAsync(400);
+
+ expect(h.electronSpawns()).toHaveLength(1);
+ const { args, opts } = h.electronSpawns()[0];
+ expect(args).toEqual(['.']);
+ expect(opts.env.ELECTRON_RENDERER_URL).toBe('http://127.0.0.1:5199');
+ expect(opts.env.NODE_ENV).toBe('development');
+ expect(h.options.watch).toHaveBeenCalledTimes(2);
+ });
+
+ it('waits for the bundle signature to stay quiet before launching', async () => {
+ const h = createHarness();
+ h.orchestrator.start();
+ h.state.bundlesExist = true;
+ h.state.portReady = true;
+
+ await vi.advanceTimersByTimeAsync(600);
+ h.state.mtime = 2;
+ await vi.advanceTimersByTimeAsync(600);
+ expect(h.electronSpawns()).toHaveLength(0);
+
+ await vi.advanceTimersByTimeAsync(1400);
+ expect(h.electronSpawns()).toHaveLength(1);
+ });
+
+ it('passes extra CLI args through to electron', async () => {
+ const h = createHarness({ electronArgs: ['--remote-debugging-port=9223', '--foo'] });
+ h.orchestrator.start();
+ await h.becomeReady();
+
+ expect(h.electronSpawns()[0].args).toEqual(['.', '--remote-debugging-port=9223', '--foo']);
+ });
+
+ it('restarts electron when a bundle change fires the watcher', async () => {
+ const h = createHarness();
+ h.orchestrator.start();
+ await h.becomeReady();
+
+ const electron = h.electronSpawns()[0].child;
+ h.watchers[0]('change');
+ await vi.advanceTimersByTimeAsync(500);
+ expect(electron.kill).toHaveBeenCalled();
+
+ electron.emit('exit', null);
+ expect(h.electronSpawns()).toHaveLength(2);
+ expect(h.options.exit).not.toHaveBeenCalled();
+ });
+
+ it('debounces rapid bundle changes into one restart', async () => {
+ const h = createHarness();
+ h.orchestrator.start();
+ await h.becomeReady();
+
+ const electron = h.electronSpawns()[0].child;
+ h.watchers[0]('change');
+ await vi.advanceTimersByTimeAsync(200);
+ h.watchers[1]('change');
+ await vi.advanceTimersByTimeAsync(500);
+
+ expect(electron.kill).toHaveBeenCalledTimes(1);
+ });
+
+ it('stops the watchers when electron is quit by hand', async () => {
+ const h = createHarness();
+ h.orchestrator.start();
+ await h.becomeReady();
+
+ h.electronSpawns()[0].child.emit('exit', 0);
+
+ expect(h.options.exit).toHaveBeenCalledWith(0);
+ for (const { child } of h.viteChildren()) {
+ expect(child.kill).toHaveBeenCalled();
+ }
+ });
+
+ it('shutdown kills electron and all vite children exactly once', async () => {
+ const h = createHarness();
+ h.orchestrator.start();
+ await h.becomeReady();
+
+ h.orchestrator.shutdown(0);
+ h.orchestrator.shutdown(1);
+
+ expect(h.options.exit).toHaveBeenCalledTimes(1);
+ expect(h.options.exit).toHaveBeenCalledWith(0);
+ expect(h.electronSpawns()[0].child.kill).toHaveBeenCalled();
+ for (const { child } of h.viteChildren()) {
+ expect(child.kill).toHaveBeenCalled();
+ }
+ });
+
+ it('fails with exit(1) when the initial build never produces bundles', async () => {
+ const h = createHarness();
+ h.orchestrator.start();
+
+ await vi.advanceTimersByTimeAsync(121_000);
+
+ expect(h.options.logError).toHaveBeenCalled();
+ expect(h.options.exit).toHaveBeenCalledWith(1);
+ expect(h.electronSpawns()).toHaveLength(0);
+ });
+});
diff --git a/apps/desktop/scripts/dev.mjs b/apps/desktop/scripts/dev.mjs
index 1c16d5163c5..c4dbc4d520d 100644
--- a/apps/desktop/scripts/dev.mjs
+++ b/apps/desktop/scripts/dev.mjs
@@ -1,132 +1,36 @@
-import { spawn } from 'node:child_process';
-import { existsSync, statSync, watch } from 'node:fs';
import { createRequire } from 'node:module';
-import net from 'node:net';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
+import { createDevOrchestrator } from './devOrchestrator.mjs';
+
const desktopRoot = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const require = createRequire(path.join(desktopRoot, 'package.json'));
-const electronBin = require('electron');
-
-const VITE_PORT = Number(process.env.LOBE_DESKTOP_VITE_PORT) || 5173;
-const CDP_PORT = Number(process.env.LOBE_DESKTOP_CDP_PORT);
-const MAIN_BUNDLE = path.join(desktopRoot, 'dist/main/index.js');
-const PRELOAD_BUNDLE = path.join(desktopRoot, 'dist/preload/index.js');
-
-let electron = null;
-let restarting = false;
-let shuttingDown = false;
-
-const spawnVite = (args) =>
- spawn('pnpm', ['exec', 'vite', ...args], { cwd: desktopRoot, stdio: 'inherit' });
-
-const children = [
- spawnVite(['--config', 'vite.renderer.config.ts']),
- spawnVite(['build', '--watch', '--mode', 'development', '--config', 'vite.main.config.ts']),
- spawnVite(['build', '--watch', '--mode', 'development', '--config', 'vite.preload.config.ts']),
-];
-
-for (const child of children) {
- child.on('exit', (code) => {
- if (!shuttingDown) shutdown(code ?? 1);
- });
-}
-function shutdown(code) {
- if (shuttingDown) return;
- shuttingDown = true;
- electron?.kill();
- for (const child of children) child.kill();
- process.exit(code);
+// vite's `exports` map blocks `require.resolve('vite/bin/vite.js')` directly.
+const viteBin = path.join(path.dirname(require.resolve('vite/package.json')), 'bin/vite.js');
+
+// Forward everything after `pnpm dev --` (e.g. --remote-debugging-port=9223) to electron.
+const rawArgs = process.argv.slice(2);
+const electronArgs = rawArgs[0] === '--' ? rawArgs.slice(1) : rawArgs;
+const cdpPort = Number(process.env.LOBE_DESKTOP_CDP_PORT);
+if (
+ Number.isInteger(cdpPort) &&
+ cdpPort > 0 &&
+ !electronArgs.some((arg) => arg.startsWith('--remote-debugging-port'))
+) {
+ electronArgs.push(`--remote-debugging-port=${cdpPort}`);
}
-process.on('SIGINT', () => shutdown(0));
-process.on('SIGTERM', () => shutdown(0));
-
-function startElectron() {
- const args = ['.'];
- if (Number.isInteger(CDP_PORT) && CDP_PORT > 0) {
- args.push(`--remote-debugging-port=${CDP_PORT}`);
- }
-
- electron = spawn(electronBin, args, {
- cwd: desktopRoot,
- env: {
- ...process.env,
- ELECTRON_RENDERER_URL: `http://127.0.0.1:${VITE_PORT}`,
- NODE_ENV: 'development',
- },
- stdio: 'inherit',
- });
- electron.on('exit', (code) => {
- if (shuttingDown) return;
- if (restarting) {
- restarting = false;
- startElectron();
- return;
- }
- // The app was quit by hand β€” stop the watchers instead of idling forever.
- console.log('[desktop-dev] electron exited, stopping dev watchers');
- shutdown(code ?? 0);
- });
-}
-
-let debounce = null;
-function scheduleRestart() {
- clearTimeout(debounce);
- debounce = setTimeout(() => {
- if (shuttingDown || !electron) return;
- console.log('[desktop-dev] main/preload bundle changed, restarting electron');
- restarting = true;
- electron.kill();
- }, 400);
-}
-
-function watchBundles() {
- for (const dir of [path.dirname(MAIN_BUNDLE), path.dirname(PRELOAD_BUNDLE)]) {
- watch(dir, scheduleRestart);
- }
-}
+const orchestrator = createDevOrchestrator({
+ desktopRoot,
+ electronArgs,
+ electronBin: require('electron'),
+ viteBin,
+ vitePort: Number(process.env.LOBE_DESKTOP_VITE_PORT) || 5173,
+});
-const rendererServerReady = () =>
- new Promise((resolve) => {
- const socket = net.connect({ host: '127.0.0.1', port: VITE_PORT }, () => {
- socket.destroy();
- resolve(true);
- });
- socket.on('error', () => resolve(false));
- });
+process.on('SIGINT', () => orchestrator.shutdown(0));
+process.on('SIGTERM', () => orchestrator.shutdown(0));
-// The two build configs `emptyOutDir` on startup and finish at different times,
-// so wait until the renderer server accepts connections and both bundles exist
-// and have been quiet for a second before launching electron or attaching watchers.
-const started = Date.now();
-let lastChange = Date.now();
-let lastSignature = '';
-let checking = false;
-const poll = setInterval(async () => {
- if (checking) return;
- checking = true;
- try {
- if (Date.now() - started > 120_000) {
- console.error('[desktop-dev] initial build did not produce bundles within 120s');
- shutdown(1);
- return;
- }
- if (!existsSync(MAIN_BUNDLE) || !existsSync(PRELOAD_BUNDLE)) return;
- const signature = [MAIN_BUNDLE, PRELOAD_BUNDLE].map((f) => statSync(f).mtimeMs).join(':');
- if (signature !== lastSignature) {
- lastSignature = signature;
- lastChange = Date.now();
- return;
- }
- if (Date.now() - lastChange < 1000) return;
- if (!(await rendererServerReady())) return;
- clearInterval(poll);
- watchBundles();
- startElectron();
- } finally {
- checking = false;
- }
-}, 200);
+orchestrator.start();
diff --git a/apps/desktop/scripts/devOrchestrator.mjs b/apps/desktop/scripts/devOrchestrator.mjs
new file mode 100644
index 00000000000..4cf8e615649
--- /dev/null
+++ b/apps/desktop/scripts/devOrchestrator.mjs
@@ -0,0 +1,163 @@
+import { spawn as nodeSpawn } from 'node:child_process';
+import {
+ existsSync as nodeExistsSync,
+ statSync as nodeStatSync,
+ watch as nodeWatch,
+} from 'node:fs';
+import net from 'node:net';
+import path from 'node:path';
+
+const defaultCheckPort = (port) =>
+ new Promise((resolve) => {
+ const socket = net.connect({ host: '127.0.0.1', port }, () => {
+ socket.destroy();
+ resolve(true);
+ });
+ socket.on('error', () => resolve(false));
+ });
+
+export function createDevOrchestrator({
+ desktopRoot,
+ electronBin,
+ viteBin,
+ vitePort,
+ electronArgs = [],
+ nodeBin = process.execPath,
+ pollIntervalMs = 200,
+ bundleQuietMs = 1000,
+ initialBuildTimeoutMs = 120_000,
+ restartDebounceMs = 400,
+ spawn = nodeSpawn,
+ existsSync = nodeExistsSync,
+ statSync = nodeStatSync,
+ watch = nodeWatch,
+ checkPort = defaultCheckPort,
+ exit = (code) => process.exit(code),
+ log = console.log,
+ logError = console.error,
+}) {
+ const MAIN_BUNDLE = path.join(desktopRoot, 'dist/main/index.js');
+ const PRELOAD_BUNDLE = path.join(desktopRoot, 'dist/preload/index.js');
+
+ const children = [];
+ let electron = null;
+ let restarting = false;
+ let shuttingDown = false;
+ let poll = null;
+ let debounce = null;
+
+ // Spawn vite through the current node binary instead of a `pnpm` shim:
+ // on Windows the shim is `pnpm.cmd`, which a shell-less spawn cannot start.
+ const spawnVite = (args) =>
+ spawn(nodeBin, [viteBin, ...args], { cwd: desktopRoot, stdio: 'inherit' });
+
+ function shutdown(code) {
+ if (shuttingDown) return;
+ shuttingDown = true;
+ clearInterval(poll);
+ clearTimeout(debounce);
+ electron?.kill();
+ for (const child of children) child.kill();
+ exit(code);
+ }
+
+ function startElectron() {
+ // Automation scripts (e.g. record-electron-demo.sh) grep the log for
+ // "starting electron" as the readiness signal β€” keep this line stable.
+ log('[desktop-dev] starting electron');
+ electron = spawn(electronBin, ['.', ...electronArgs], {
+ cwd: desktopRoot,
+ env: {
+ ...process.env,
+ ELECTRON_RENDERER_URL: `http://127.0.0.1:${vitePort}`,
+ NODE_ENV: 'development',
+ },
+ stdio: 'inherit',
+ });
+ electron.on('exit', (code) => {
+ if (shuttingDown) return;
+ if (restarting) {
+ restarting = false;
+ startElectron();
+ return;
+ }
+ // The app was quit by hand β€” stop the watchers instead of idling forever.
+ log('[desktop-dev] electron exited, stopping dev watchers');
+ shutdown(code ?? 0);
+ });
+ }
+
+ function scheduleRestart() {
+ clearTimeout(debounce);
+ debounce = setTimeout(() => {
+ if (shuttingDown || !electron) return;
+ log('[desktop-dev] main/preload bundle changed, restarting electron');
+ restarting = true;
+ electron.kill();
+ }, restartDebounceMs);
+ }
+
+ function watchBundles() {
+ for (const dir of [path.dirname(MAIN_BUNDLE), path.dirname(PRELOAD_BUNDLE)]) {
+ watch(dir, scheduleRestart);
+ }
+ }
+
+ function start() {
+ children.push(
+ spawnVite(['--config', 'vite.renderer.config.ts']),
+ spawnVite(['build', '--watch', '--mode', 'development', '--config', 'vite.main.config.ts']),
+ spawnVite([
+ 'build',
+ '--watch',
+ '--mode',
+ 'development',
+ '--config',
+ 'vite.preload.config.ts',
+ ]),
+ );
+
+ for (const child of children) {
+ child.on('exit', (code) => {
+ if (!shuttingDown) shutdown(code ?? 1);
+ });
+ }
+
+ // The two build configs `emptyOutDir` on startup and finish at different times,
+ // so wait until the renderer server accepts connections and both bundles exist
+ // and have been quiet for a second before launching electron or attaching watchers.
+ const started = Date.now();
+ let lastChange = Date.now();
+ let lastSignature = '';
+ let checking = false;
+ poll = setInterval(async () => {
+ if (checking) return;
+ checking = true;
+ try {
+ if (Date.now() - started > initialBuildTimeoutMs) {
+ logError(
+ `[desktop-dev] initial build did not produce bundles within ${Math.round(initialBuildTimeoutMs / 1000)}s`,
+ );
+ shutdown(1);
+ return;
+ }
+ if (!existsSync(MAIN_BUNDLE) || !existsSync(PRELOAD_BUNDLE)) return;
+ const signature = [MAIN_BUNDLE, PRELOAD_BUNDLE].map((f) => statSync(f).mtimeMs).join(':');
+ if (signature !== lastSignature) {
+ lastSignature = signature;
+ lastChange = Date.now();
+ return;
+ }
+ if (Date.now() - lastChange < bundleQuietMs) return;
+ if (!(await checkPort(vitePort))) return;
+ clearInterval(poll);
+ watchBundles();
+ startElectron();
+ } finally {
+ checking = false;
+ }
+ }, pollIntervalMs);
+ }
+
+ return { shutdown, start };
+}
diff --git a/apps/desktop/vite.main.config.ts b/apps/desktop/vite.main.config.ts
index 878a3659a30..aa605e4a86d 100644
--- a/apps/desktop/vite.main.config.ts
+++ b/apps/desktop/vite.main.config.ts
@@ -6,6 +6,7 @@ import { externalRuntimeModules } from './external-runtime-deps.config.mjs';
import { getNativeExternalDependencies } from './native-deps.config.mjs';
import {
applyDesktopViteConfigExtension,
+ isCloudDesktopBuild,
loadDesktopEnv,
MAIN_NODE_TARGET,
mainProcessAlias,
@@ -19,12 +20,12 @@ export default defineConfig(async (env) => {
const isDev = mode === 'development';
const updateChannel = process.env.UPDATE_CHANNEL;
- const isCloudDesktopBuild = process.env.CLOUD_DESKTOP === '1';
+ const isCloudDesktop = isCloudDesktopBuild();
const externalNavigationHosts =
- process.env.DESKTOP_EXTERNAL_NAVIGATION_HOSTS ?? (isCloudDesktopBuild ? 'stripe.com' : '');
+ process.env.DESKTOP_EXTERNAL_NAVIGATION_HOSTS ?? (isCloudDesktop ? 'stripe.com' : '');
console.info(`[vite.main.config.ts] Detected UPDATE_CHANNEL: ${updateChannel}`);
- console.info(`[vite.main.config.ts] Cloud desktop build: ${isCloudDesktopBuild}`);
+ console.info(`[vite.main.config.ts] Cloud desktop build: ${isCloudDesktop}`);
const config = {
build: {
diff --git a/apps/desktop/vite.renderer.config.ts b/apps/desktop/vite.renderer.config.ts
index 9ed34181d5d..231ed7bdc4b 100644
--- a/apps/desktop/vite.renderer.config.ts
+++ b/apps/desktop/vite.renderer.config.ts
@@ -187,6 +187,8 @@ export default defineConfig(async (env) => {
const { mode } = env;
loadDesktopEnv(mode);
+ const isCloudDesktop = isCloudDesktopBuild();
+
const config = {
// Absolute base: relative asset URLs break in the popup window because its
// SPA URL (`/popup/agent/:aid/:tid`) is deep enough that relative resolution
@@ -217,15 +219,15 @@ export default defineConfig(async (env) => {
envPrefix: ['RENDERER_VITE_', 'VITE_'],
optimizeDeps: sharedOptimizeDeps,
plugins: [
- isCloudDesktopBuild && cloudTsconfigPathsPlugin(),
- isCloudDesktopBuild && cloudDesktopBusinessConstPlugin(),
+ isCloudDesktop && cloudTsconfigPathsPlugin(),
+ isCloudDesktop && cloudDesktopBusinessConstPlugin(),
electronDesktopHtmlPlugin(),
vanillaExtractPlugin(),
...(sharedRendererPlugins({ platform: 'desktop' }) as PluginOption[]),
],
resolve: {
dedupe: ['react', 'react-dom'],
- tsconfigPaths: !isCloudDesktopBuild,
+ tsconfigPaths: !isCloudDesktop,
},
root: ROOT_DIR,
// In dev the BrowserWindow loads `app://renderer/` and the Electron main process
diff --git a/apps/desktop/vite.shared.ts b/apps/desktop/vite.shared.ts
index 47c25598c0c..def0da3cd6b 100644
--- a/apps/desktop/vite.shared.ts
+++ b/apps/desktop/vite.shared.ts
@@ -10,7 +10,9 @@ export const DESKTOP_DIR = __dirname;
export const ROOT_DIR = path.resolve(__dirname, '../..');
export const CLOUD_ROOT_DIR = path.resolve(__dirname, '../../..');
-export const isCloudDesktopBuild = process.env.CLOUD_DESKTOP === '1';
+// Must stay a function: configs call it after `loadDesktopEnv(mode)`, so a
+// `CLOUD_DESKTOP=1` coming from `apps/desktop/.env` (not just the CLI env) is seen.
+export const isCloudDesktopBuild = () => process.env.CLOUD_DESKTOP === '1';
// Renderer dev-server port. Overridable per instance (e.g. one git worktree per
// concurrent dev instance) via LOBE_DESKTOP_VITE_PORT; `scripts/dev.mjs` injects
@@ -27,7 +29,7 @@ export const desktopPackageJson = JSON.parse(
) as { version: string };
export const loadDesktopEnv = (mode: string) => {
- dotenv.config();
+ dotenv.config({ path: path.join(DESKTOP_DIR, '.env') });
Object.assign(process.env, loadEnv(mode, ROOT_DIR, ''));
};