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.

✨ feat(desktop): support concurrent dev instances for multi-instance testing (#16553)

Arvin Xu90612a96843b
diff --git a/.agents/skills/agent-testing/references/multi-instance.md b/.agents/skills/agent-testing/references/multi-instance.md
new file mode 100644
index 00000000000..f2bfe4f4b57
--- /dev/null
+++ b/.agents/skills/agent-testing/references/multi-instance.md
@@ -0,0 +1,236 @@
+# Concurrent Electron Instances (Multi-Instance Automation)
+
+Status: **implemented + empirically validated 2026-07-01.** Multiple isolated dev
+Electron instances run concurrently, each with its own userData dir, Vite dev
+port, and IPC socket, each signed in from a copied login state, with independent
+renderer state. Three env-gated product knobs (`LOBE_DESKTOP_USER_DATA_DIR`,
+`LOBE_IPC_ID`, `LOBE_DESKTOP_VITE_PORT`) plus an `electron-dev.sh` instance pool.
+Details, collision matrix, and two validation transcripts below.
+
+Use case driving this: **N git worktrees under one project, each doing different
+work, each running its own Electron dev instance** β€” so each needs its own Vite
+dev server + its own userData, while reusing the developer's existing login.
+
+## The real bottleneck is NOT "one port"
+
+CDP is single-port, multi-target: one `--remote-debugging-port` exposes every
+`BrowserWindow` as a target. What actually blocks N independent, write-isolated
+app sessions are dev-build singletons. Validated verdicts:
+
+| Singleton | Location | Verdict for N instances |
+| --------- | -------- | ----------------------- |
+| 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). |
+| `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. |
+| Static file server / iMessage bridge | `getPort()` dynamic | βœ… auto-allocated, safe. |
+
+## The key tension (and its resolution)
+
+Two requirements pull opposite ways:
+
+- **Login-state reuse** needs the **app name constant** β€” `safeStorage` (OIDC
+ tokens in `lobehub-settings.json`) and Chromium cookie encryption (better-auth
+ session in `Cookies`) derive their key from an OS-keychain entry named after
+ the app. Change the app name β†’ copied secrets no longer decrypt.
+- **IPC-socket uniqueness** wants a **per-instance appId** (the socket path is
+ `os.tmpdir()/${appId}-electron-ipc.sock`, appId = app name).
+
+Naively "give each instance a different app name" (a tempting first instinct)
+**breaks login reuse** β€” the exact thing this use case needs. Resolution:
+
+> **Keep `app.setName('lobehub-desktop-dev')` constant for every instance. Vary
+> only the userData dir.** That satisfies the single-instance lock (keyed by
+> userData) AND keeps the keychain key valid so copied tokens/cookies decrypt.
+> The IPC socket is decoupled from the app name via its own `LOBE_IPC_ID` knob
+> (not the app name), so each instance still gets a distinct socket.
+
+## Product changes (all env-gated, all validated)
+
+Three tiny env-gated knobs β€” no behavior change unless the env is set. This
+branch ships all three:
+
+1. **`apps/desktop/src/main/pre-app-init.ts`** β€” per-instance userData, app name
+ fixed (so copied login state still decrypts):
+
+ ```ts
+ app.setName('lobehub-desktop-dev');
+ const userDataOverride = process.env.LOBE_DESKTOP_USER_DATA_DIR;
+ app.setPath('userData', userDataOverride || path.join(app.getPath('appData'), 'lobehub-desktop-dev'));
+ ```
+
+2. **`apps/desktop/src/main/core/App.ts`** β€” per-instance IPC id so the
+ `electron-server-ipc` socket path stops colliding (no more "last one wins"):
+
+ ```ts
+ const ipcId = process.env.LOBE_IPC_ID || name;
+ this.ipcServer = new ElectronIPCServer(ipcId, ipcServerEvents);
+ ```
+
+3. **`apps/desktop/electron.vite.config.ts`** β€” per-instance Vite dev port
+ (Model B: one Vite per worktree), kept `strictPort` so HMR clientPort matches:
+
+ ```ts
+ const DEV_VITE_PORT = Number(process.env.LOBE_DESKTOP_VITE_PORT) || 5173;
+ // ...used for both server.port and server.hmr.clientPort
+ ```
+
+All three verified live via the `electron-dev.sh` pool (transcript below).
+
+## Login-state reuse across userData dirs (validated)
+
+To make a fresh userData dir come up **already logged in**, copy from the golden
+profile (`~/Library/Application Support/lobehub-desktop-dev/`) β€” only the
+login-bearing items, NOT the multi-GB caches:
+
+```bash
+SRC="$HOME/Library/Application Support/lobehub-desktop-dev"
+DST="/tmp/lobe-ud-<id>"
+for f in lobehub-settings.json "Local State" Preferences \
+ Cookies Cookies-journal "Local Storage" IndexedDB \
+ "Session Storage" "Network Persistent State" lobehub-storage; do
+ [ -e "$SRC/$f" ] && cp -R "$SRC/$f" "$DST/"
+done # ~27 MB vs the 1.7 GB full profile (Cache/Code Cache/GPUCache skipped)
+```
+
+- `lobehub-settings.json` β†’ `encryptedTokens` (OIDC access/refresh, safeStorage).
+- `Cookies` + `Local Storage` + `IndexedDB` β†’ better-auth renderer session.
+- Decryption works because app name is unchanged on the same machine (keychain
+ entry `lobehub-desktop-dev Safe Storage` is reused). **Same machine only** β€”
+ a copy to another machine won't decrypt.
+- **Stale-token caveat:** if the copied access token's `exp` has passed you'll
+ see `Authentication failed: "exp" claim timestamp check failed` β€” this actually
+ **confirms decryption succeeded** (the token was decrypted, then found expired).
+ `isSignedIn` still returns true (session/refresh recovers), but profile API
+ calls may lag until refresh completes (the settings page briefly shows
+ "Anonymous User" + skeletons). Copy from a freshly-active profile for a clean
+ first paint.
+
+## IPC socket caveat (the one real conflict)
+
+`ipcServer.ts` constructor does `if (fs.existsSync(socketPath)) fs.unlinkSync(...)`
+then binds. So starting instance N **unlinks instance N-1's socket and takes over
+the path** + rewrites `${appId}-electron-ipc-info.json`. Observed: non-fatal, no
+crash, all instances keep running and their **renderer↔main IPC (standard
+Electron `ipcMain`/`ipcRenderer`) is unaffected** (that's per-webContents). Only
+the external `electron-server-ipc` channel β€” used by the embedded CLI `lh` and
+the Next server to reach the main process β€” resolves to the **last-started
+instance**. For CDP-driven UI automation this is harmless. To make it clean for a
+real feature, give the IPC server a per-instance appId (env, decoupled from
+`app.setName`) at `App.ts` where `new ElectronIPCServer(appId, …)` is constructed.
+
+## agent-browser driving gotcha (important)
+
+The `agent-browser` daemon **reuses one session across `--cdp` ports** β€” calling
+`agent-browser --cdp 9223 …` then `--cdp 9224 …` both hit whichever target the
+daemon connected to first, so reads/writes bleed and look like cross-instance
+state sync (they aren't). Two correct patterns:
+
+```bash
+# βœ… pin a distinct session name per instance β€” supports concurrent driving
+agent-browser --session s9223 --cdp 9223 snapshot -i
+agent-browser --session s9224 --cdp 9224 snapshot -i
+
+# βœ… or reset between targets (slower, serial)
+agent-browser close --all && agent-browser --cdp 9223 get url
+```
+
+Raw `curl http://localhost:<port>/json/list` always shows a port's true target
+(title/url/id) and is the tie-breaker when in doubt.
+
+## Two operating models
+
+### 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`:
+
+```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
+
+# 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 \
+ npx electron . --remote-debugging-port=9224
+LOBE_DESKTOP_USER_DATA_DIR=/tmp/lobe-ud-3 ELECTRON_RENDERER_URL=http://127.0.0.1:5173 \
+ npx electron . --remote-debugging-port=9225
+```
+
+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).
+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
+```
+
+`electron-vite 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).
+
+## electron-dev.sh instance pool (implemented)
+
+`scripts/electron-dev.sh` now keys lifecycle on an **instance id**, not the
+project path (the old single-instance script matched every project Electron by
+binary path, so a 2nd `start` tore down the 1st):
+
+```bash
+electron-dev.sh start 1 # CDP 9223, Vite 5174, userData ud-1 (login copied), IPC id -1
+electron-dev.sh start 2 # CDP 9224, Vite 5175, userData ud-2, IPC id -2
+electron-dev.sh list # show running pool instances
+electron-dev.sh stop 1 # sibling-safe: kills ONLY instance 1 (KEEP_DATA=1 to keep ud)
+electron-dev.sh stop --all # stop every instance
+# no id β†’ legacy single-instance behavior (CDP 9222), unchanged
+```
+
+- Derives `CDP=9222+id`, `Vite=5173+id`, `userData=$POOL_DIR/ud-<id>`,
+ `IPC id=lobehub-desktop-dev-<id>`, per-id log + pidfile.
+- `start <id>` seeds a fresh userData with the login-item set from the golden
+ profile (override via `LOBE_GOLDEN_PROFILE`); `stop <id>` wipes it unless
+ `KEEP_DATA=1`.
+- `stop <id>` matches by **pidfile session-leader tree + CDP/Vite port holders**,
+ never the broad project path β†’ never kills a sibling.
+- Drive each instance with `agent-browser --session s<port> --cdp <port>`.
+
+## Validation transcripts (2026-07-01)
+
+### Round 1 β€” concurrency, login reuse, isolation (Model A)
+
+Golden profile `lobehub-desktop-dev` (logged in, user_2gmT…); 3 userData copies
+(27 MB each), app name constant. inst1 = `electron-vite dev` (CDP 9223, Vite
+5173), inst2/inst3 = raw electron (CDP 9224/9225) sharing Vite.
+
+- βœ… **All 3 booted** β€” no single-instance exit (distinct `SingletonLock` PIDs).
+- βœ… **All 3 signed in** β€” `isSignedIn:true, user_2gmT…` on all ports (copied
+ `safeStorage` tokens decrypted; app name unchanged).
+- βœ… **State isolated** β€” raw `/json/list` showed distinct target ids + URLs. The
+ "all same route" seen mid-test was the agent-browser daemon session-reuse
+ artifact, fixed by per-instance `--session`.
+- ⚠️ **IPC socket hijack** (pre-fix) β€” last-started instance owned the socket;
+ non-fatal, renderers unaffected. β†’ motivated the `LOBE_IPC_ID` fix below.
+
+### Round 2 β€” the three product knobs + the pool (Model B)
+
+`electron-dev.sh start 1` + `start 2` on the fixed build:
+
+- βœ… **Vite port override** β€” 5174 **and** 5175 bound concurrently (two
+ `electron-vite dev`, `strictPort` no longer collides).
+- βœ… **IPC decouple** β€” two **distinct** sockets `lobehub-desktop-dev-1-…sock` +
+ `…-2-…sock`; no hijack.
+- βœ… **userData isolation** β€” ud-1 / ud-2 with distinct `SingletonLock` PIDs; both
+ CDP ports reachable; `list` shows both UP.
+- βœ… **Sibling-safe stop** β€” `stop 1` killed instance 1's 7-proc tree + wiped
+ ud-1, while instance 2 (9224 / 5175 / its socket) stayed fully alive.
+
+Teardown: `stop --all`; `rm -rf` pool dir. Ports released.
diff --git a/.agents/skills/agent-testing/scripts/electron-dev.sh b/.agents/skills/agent-testing/scripts/electron-dev.sh
index e69cb8ed34e..11e61aa00d0 100755
--- a/.agents/skills/agent-testing/scripts/electron-dev.sh
+++ b/.agents/skills/agent-testing/scripts/electron-dev.sh
@@ -1,36 +1,98 @@
#!/usr/bin/env bash
#
-# electron-dev.sh β€” Manage Electron dev environment for testing
+# electron-dev.sh β€” Manage Electron dev environment(s) for testing
#
-# Usage:
-# ./electron-dev.sh start # Kill existing, start fresh, wait until ready
-# ./electron-dev.sh stop # Kill all Electron-related processes
-# ./electron-dev.sh status # Check if Electron is running and CDP is reachable
-# ./electron-dev.sh restart # Stop then start
+# Single instance (legacy, backward compatible):
+# ./electron-dev.sh start # CDP 9222, default userData, default Vite port
+# ./electron-dev.sh stop
+# ./electron-dev.sh status
+# ./electron-dev.sh restart
+#
+# Instance pool (concurrent isolated instances β€” e.g. one git worktree each):
+# ./electron-dev.sh start <id> # CDP 9222+id, Vite 5173+id, own userData + IPC id
+# ./electron-dev.sh stop <id> # stop ONLY instance <id> (never touches siblings)
+# ./electron-dev.sh stop --all # stop every pool instance
+# ./electron-dev.sh status <id>
+# ./electron-dev.sh list # list running pool instances
+#
+# Each pool instance <id> gets, all env-driven so instances never collide:
+# CDP port = CDP_BASE + id (9222 + id)
+# Vite port = VITE_BASE + id (5173 + id) β†’ needs LOBE_DESKTOP_VITE_PORT support
+# userData = $POOL_DIR/ud-<id> (login state copied from the golden profile)
+# IPC id = lobehub-desktop-dev-<id> β†’ needs LOBE_IPC_ID support
+# Drive each with a DISTINCT agent-browser session, else the daemon reuses one
+# connection across ports: agent-browser --session s<port> --cdp <port> ...
#
# Environment variables:
-# CDP_PORT β€” Chrome DevTools Protocol port (default: 9222)
-# ELECTRON_LOG β€” Log file path (default: /tmp/electron-dev.log)
-# ELECTRON_WAIT_S β€” Max seconds to wait for CDP to become reachable (default: 90)
-# RENDERER_WAIT_S β€” Max seconds to wait for SPA after CDP is up (default: 60)
-# FORCE_KILL_USER β€” When set to 1, silently kill the user's `bun run dev`
-# Electron without confirmation (default: always confirm-by-action)
+# CDP_PORT β€” (legacy only) CDP port (default: 9222)
+# ELECTRON_LOG β€” (legacy only) log file path (default: /tmp/electron-dev.log)
+# CDP_BASE β€” pool CDP base (default: 9222 β†’ instance id adds on top)
+# VITE_BASE β€” pool Vite base (default: 5173)
+# POOL_DIR β€” pool state dir (default: /tmp/lobe-electron-pool)
+# LOBE_GOLDEN_PROFILE β€” userData to copy login state from
+# (default: ~/Library/Application Support/lobehub-desktop-dev)
+# KEEP_DATA=1 β€” on `stop <id>`, keep the instance's userData dir
+# ELECTRON_WAIT_S β€” max seconds to wait for CDP (default: 90)
+# RENDERER_WAIT_S β€” max seconds to wait for the SPA (default: 60)
#
set -euo pipefail
-CDP_PORT="${CDP_PORT:-9222}"
-ELECTRON_LOG="${ELECTRON_LOG:-/tmp/electron-dev.log}"
+# Capture legacy env overrides BEFORE we clobber the same-named internals.
+ENV_CDP_PORT="${CDP_PORT:-}"
+ENV_ELECTRON_LOG="${ELECTRON_LOG:-}"
+
+CMD="${1:-help}"
+INSTANCE="${2:-}" # empty = legacy single instance; integer = pool member
+
+CDP_BASE="${CDP_BASE:-9222}"
+VITE_BASE="${VITE_BASE:-5173}"
ELECTRON_WAIT_S="${ELECTRON_WAIT_S:-90}"
RENDERER_WAIT_S="${RENDERER_WAIT_S:-60}"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../../../.." && pwd)"
-PIDFILE="/tmp/electron-dev-cdp-${CDP_PORT}.pid"
+POOL_DIR="${POOL_DIR:-/tmp/lobe-electron-pool}"
+GOLDEN_PROFILE="${LOBE_GOLDEN_PROFILE:-$HOME/Library/Application Support/lobehub-desktop-dev}"
-# Project-scoped electron path prefix used for pgrep matching. Any Electron
-# binary from this project (main + helpers, with or without --remote-debugging-port)
-# starts with this string in its argv[0], so a single substring match catches all.
+# Project-scoped electron path prefix used for pgrep matching in LEGACY mode only
+# (pool mode never uses it β€” it would cross instances). Any Electron binary from
+# this project starts with this string in its argv[0].
PROJECT_ELECTRON_PATH="${PROJECT_ROOT}/apps/desktop/node_modules/.pnpm/electron@"
+# Per-instance vars, filled by derive_instance.
+POOL_MODE=0
+CDP_PORT=""
+VITE_PORT=""
+USER_DATA_DIR=""
+IPC_ID=""
+ELECTRON_LOG=""
+PIDFILE=""
+
+# Resolve the target instance's ports/paths from its id (empty id = legacy).
+derive_instance() {
+ local id="$1"
+ if [ -z "$id" ]; then
+ POOL_MODE=0
+ CDP_PORT="${ENV_CDP_PORT:-$CDP_BASE}"
+ VITE_PORT="" # legacy: no override, config default applies
+ USER_DATA_DIR="" # legacy: default userData
+ IPC_ID="" # legacy: default IPC id
+ ELECTRON_LOG="${ENV_ELECTRON_LOG:-/tmp/electron-dev.log}"
+ PIDFILE="/tmp/electron-dev-cdp-${CDP_PORT}.pid"
+ else
+ [[ "$id" =~ ^[0-9]+$ ]] || {
+ echo "[electron-dev] instance id must be a non-negative integer, got: $id" >&2
+ exit 1
+ }
+ POOL_MODE=1
+ CDP_PORT=$((CDP_BASE + id))
+ VITE_PORT=$((VITE_BASE + id))
+ USER_DATA_DIR="$POOL_DIR/ud-$id"
+ IPC_ID="lobehub-desktop-dev-$id"
+ ELECTRON_LOG="$POOL_DIR/instance-$id.log"
+ PIDFILE="$POOL_DIR/instance-$id.pid"
+ fi
+}
+
# ── Helpers ──────────────────────────────────────────────────────────
# Print pid + every descendant pid (DFS via pgrep -P).
@@ -44,24 +106,15 @@ expand_descendants() {
done
}
-# Find seed PIDs related to this project's Electron dev session.
-# Matches REGARDLESS of whether --remote-debugging-port was passed, so it also
-# catches a plain `bun run dev` session the user started outside this script.
-find_project_pids() {
+# 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).
+find_instance_pids() {
local pids=""
- # 1. Any process whose command line mentions this project's electron path
- # (covers the main Electron binary AND every Helper subprocess)
- local electron_pids
- electron_pids=$(pgrep -f "$PROJECT_ELECTRON_PATH" 2>/dev/null || true)
- pids="$pids $electron_pids"
-
- # 2. electron-vite dev server (narrow match to avoid catching unrelated Vite invocations)
- local vite_pids
- vite_pids=$(pgrep -f "electron-vite[/.].*\\bdev\\b" 2>/dev/null || true)
- pids="$pids $vite_pids"
-
- # 3. The launcher subshell from a previous `start` (saved to pidfile)
+ # 1. Launcher subshell saved by a previous `start`
if [ -f "$PIDFILE" ]; then
local saved_pid
saved_pid=$(cat "$PIDFILE" 2>/dev/null || true)
@@ -70,30 +123,37 @@ find_project_pids() {
fi
fi
- # 4. Whatever is currently bound to the CDP port β€” catches strays whose
- # binary path doesn't match (e.g. orphaned from a crashed restart)
+ # 2. Whatever is bound to this instance's CDP port
local port_pid
port_pid=$(lsof -ti tcp:"$CDP_PORT" -sTCP:LISTEN 2>/dev/null || true)
pids="$pids $port_pid"
- # `|| true` because `grep -v '^$'` exits 1 when input has no non-empty
- # lines, which (with pipefail + set -e) silently kills the caller.
+ # 3. Whatever is bound to this instance's Vite port (pool mode)
+ if [ -n "$VITE_PORT" ]; then
+ local vite_pid
+ vite_pid=$(lsof -ti tcp:"$VITE_PORT" -sTCP:LISTEN 2>/dev/null || true)
+ pids="$pids $vite_pid"
+ fi
+
+ # 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)"
+ fi
+
+ # `|| true` because `grep -v '^$'` exits 1 on all-empty input, which with
+ # pipefail + set -e would silently kill the caller.
echo "$pids" | tr ' ' '\n' | sort -u | grep -v '^$' | tr '\n' ' ' || true
}
-# Wait for the CDP HTTP endpoint to respond, with a deadline + early bail-out
-# if the launcher process died (no point waiting if Electron crashed).
wait_for_cdp() {
- local deadline=$(( $(date +%s) + ELECTRON_WAIT_S ))
+ local deadline=$(($(date +%s) + ELECTRON_WAIT_S))
echo "[electron-dev] Waiting for CDP on port ${CDP_PORT} (up to ${ELECTRON_WAIT_S}s)..."
-
while [ "$(date +%s)" -lt "$deadline" ]; do
if curl -sf --max-time 2 "http://localhost:${CDP_PORT}/json/version" >/dev/null 2>&1; then
echo "[electron-dev] CDP is reachable."
return 0
fi
-
- # If our launcher subshell died, abort early so we don't hang the full timeout
if [ -f "$PIDFILE" ]; then
local saved_pid
saved_pid=$(cat "$PIDFILE" 2>/dev/null || true)
@@ -104,75 +164,92 @@ wait_for_cdp() {
return 1
fi
fi
-
sleep 2
done
-
echo "[electron-dev] ERROR: CDP did not respond within ${ELECTRON_WAIT_S}s"
echo "[electron-dev] Last 30 lines of $ELECTRON_LOG:"
tail -30 "$ELECTRON_LOG" 2>/dev/null || true
return 1
}
-# After CDP is up, wait until the SPA renders interactive elements.
wait_for_renderer() {
- local deadline=$(( $(date +%s) + RENDERER_WAIT_S ))
+ local deadline=$(($(date +%s) + RENDERER_WAIT_S))
echo "[electron-dev] Waiting for SPA to load (up to ${RENDERER_WAIT_S}s)..."
-
while [ "$(date +%s)" -lt "$deadline" ]; do
local snap
- snap=$(agent-browser --cdp "$CDP_PORT" snapshot -i 2>&1 || true)
+ snap=$(agent-browser --session "edev$CDP_PORT" --cdp "$CDP_PORT" snapshot -i 2>&1 || true)
if echo "$snap" | grep -qE '\b(link|button)\b'; then
echo "[electron-dev] Renderer ready."
return 0
fi
sleep 2
done
-
echo "[electron-dev] WARNING: Renderer not interactive within ${RENDERER_WAIT_S}s β€” proceeding anyway."
return 0
}
+# Copy the login-bearing items from the golden profile into a fresh userData dir
+# (skips the multi-GB caches). No-op if the dir already exists.
+seed_userdata() {
+ local dst="$1"
+ [ -d "$dst" ] && return 0
+ if [ ! -d "$GOLDEN_PROFILE" ]; then
+ echo "[electron-dev] WARNING: golden profile not found at $GOLDEN_PROFILE β€” instance will start signed out."
+ mkdir -p "$dst"
+ return 0
+ fi
+ echo "[electron-dev] Seeding login state from golden profile β†’ $dst"
+ mkdir -p "$dst"
+ local items=(
+ "lobehub-settings.json" "Local State" "Preferences"
+ "Cookies" "Cookies-journal" "Local Storage" "IndexedDB"
+ "Session Storage" "Network Persistent State" "lobehub-storage"
+ )
+ local f
+ for f in "${items[@]}"; do
+ [ -e "$GOLDEN_PROFILE/$f" ] && cp -R "$GOLDEN_PROFILE/$f" "$dst/" 2>/dev/null || true
+ done
+}
+
# ── Commands ─────────────────────────────────────────────────────────
do_stop() {
- echo "[electron-dev] Stopping Electron dev environment..."
+ local label="legacy"
+ [ "$POOL_MODE" = "1" ] && label="instance $INSTANCE (cdp $CDP_PORT)"
+ echo "[electron-dev] Stopping Electron dev ($label)..."
local seed_pids
- seed_pids=$(find_project_pids)
+ seed_pids=$(find_instance_pids)
- # Expand to include all descendants β€” catches helpers spawned by the main
- # process AFTER our pgrep snapshot, and the launcher's child node/electron-vite
- # process tree.
local all_pids=""
+ local pid
for pid in $seed_pids; do
all_pids="$all_pids $(expand_descendants "$pid")"
done
all_pids=$(echo "$all_pids" | tr ' ' '\n' | sort -u | grep -v '^$' | tr '\n' ' ' || true)
if [ -z "$all_pids" ]; then
- echo "[electron-dev] No project Electron/vite processes found."
+ echo "[electron-dev] No matching Electron/vite processes found."
else
local count
count=$(echo "$all_pids" | tr ' ' '\n' | grep -c .)
echo "[electron-dev] Sending SIGTERM to $count process(es): $all_pids"
- for pid in $all_pids; do
- kill "$pid" 2>/dev/null || true
- done
+ for pid in $all_pids; do kill "$pid" 2>/dev/null || true; done
- # Wait up to 5s for graceful exit
local waited=0
while [ $waited -lt 5 ]; do
local any_alive=0
for pid in $all_pids; do
- if kill -0 "$pid" 2>/dev/null; then any_alive=1; break; fi
+ if kill -0 "$pid" 2>/dev/null; then
+ any_alive=1
+ break
+ fi
done
[ "$any_alive" = "0" ] && break
sleep 1
waited=$((waited + 1))
done
- # SIGKILL anyone still alive
for pid in $all_pids; do
if kill -0 "$pid" 2>/dev/null; then
echo "[electron-dev] Force-killing PID $pid"
@@ -181,110 +258,103 @@ do_stop() {
done
fi
- # Belt-and-suspenders: anything still bound to the CDP port goes away
+ # Belt-and-suspenders: free this instance's CDP port.
local port_pid
port_pid=$(lsof -ti tcp:"$CDP_PORT" -sTCP:LISTEN 2>/dev/null || true)
if [ -n "$port_pid" ]; then
- echo "[electron-dev] Port $CDP_PORT still bound by PID $port_pid; force-killing"
+ echo "[electron-dev] CDP port $CDP_PORT still bound by $port_pid; force-killing"
# shellcheck disable=SC2086
kill -9 $port_pid 2>/dev/null || true
fi
- # Also re-sweep the project's electron processes β€” sometimes the OS spawns
- # new helpers during shutdown that didn't exist when we first enumerated.
- local stragglers
- stragglers=$(pgrep -f "$PROJECT_ELECTRON_PATH" 2>/dev/null || true)
- if [ -n "$stragglers" ]; then
- echo "[electron-dev] Cleaning up stragglers: $stragglers"
- for pid in $stragglers; do
- kill -9 "$pid" 2>/dev/null || true
- done
+ # Legacy only: re-sweep stray project electron (pool mode must NOT β€” sibling-safe).
+ if [ "$POOL_MODE" = "0" ]; then
+ local stragglers
+ stragglers=$(pgrep -f "$PROJECT_ELECTRON_PATH" 2>/dev/null || true)
+ if [ -n "$stragglers" ]; then
+ echo "[electron-dev] Cleaning up stragglers: $stragglers"
+ for pid in $stragglers; do kill -9 "$pid" 2>/dev/null || true; done
+ fi
fi
- # Close any agent-browser sessions connected to this port
- agent-browser --cdp "$CDP_PORT" close --all 2>/dev/null || true
-
+ agent-browser --session "edev$CDP_PORT" --cdp "$CDP_PORT" close --all 2>/dev/null || true
rm -f "$PIDFILE"
- echo "[electron-dev] Stopped."
-}
-do_status() {
- local pids
- pids=$(find_project_pids)
-
- if [ -z "$pids" ]; then
- echo "[electron-dev] No project Electron processes found."
- return 1
+ # Pool mode: wipe the instance's userData unless asked to keep it.
+ if [ "$POOL_MODE" = "1" ] && [ -n "$USER_DATA_DIR" ]; then
+ if [ "${KEEP_DATA:-0}" = "1" ]; then
+ echo "[electron-dev] Keeping userData: $USER_DATA_DIR"
+ else
+ rm -rf "$USER_DATA_DIR"
+ echo "[electron-dev] Removed userData: $USER_DATA_DIR"
+ fi
fi
- echo "[electron-dev] Project processes: $pids"
+ echo "[electron-dev] Stopped ($label)."
+}
+do_status() {
if curl -sf --max-time 2 "http://localhost:${CDP_PORT}/json/version" >/dev/null 2>&1; then
local url
- url=$(agent-browser --cdp "$CDP_PORT" get url 2>&1 | tail -1 || echo "?")
- echo "[electron-dev] CDP port ${CDP_PORT} is reachable. URL: $url"
+ url=$(agent-browser --session "edev$CDP_PORT" --cdp "$CDP_PORT" get url 2>&1 | tail -1 || echo "?")
+ echo "[electron-dev] CDP $CDP_PORT reachable. URL: $url"
return 0
- else
- echo "[electron-dev] CDP port ${CDP_PORT} is NOT reachable (no --remote-debugging-port, or still loading)."
- return 2
fi
+ echo "[electron-dev] CDP $CDP_PORT NOT reachable (not started, or still loading)."
+ return 2
}
do_start() {
- # Already up and CDP is reachable β†’ nothing to do
if curl -sf --max-time 2 "http://localhost:${CDP_PORT}/json/version" >/dev/null 2>&1; then
- echo "[electron-dev] CDP already reachable on port $CDP_PORT. Skipping start."
- echo "[electron-dev] Use 'restart' to force a fresh session."
+ echo "[electron-dev] CDP already reachable on $CDP_PORT. Skipping start (use 'restart')."
return 0
fi
- # Detect the user's existing dev session (or stale processes) BEFORE killing
- local existing
- existing=$(find_project_pids)
- if [ -n "$existing" ]; then
- echo "[electron-dev] Existing project Electron/vite processes detected:"
- echo "$existing" | tr ' ' '\n' | sed 's/^/[electron-dev] PID /'
- echo "[electron-dev] Tearing them down so we can start a CDP-enabled session..."
- fi
+ # Clear stale state for THIS instance/session first.
+ do_stop_quiet_for_start
- do_stop
-
- # Wait for port + user-data-dir locks to release. Without this, the new
- # Electron may fail with "user data directory in use" or fail to bind CDP.
+ # Wait for this instance's ports to release.
local waited=0
while [ $waited -lt 10 ]; do
- if ! lsof -i tcp:"$CDP_PORT" >/dev/null 2>&1 \
- && ! pgrep -f "$PROJECT_ELECTRON_PATH" >/dev/null 2>&1; then
- break
- fi
- [ $waited -eq 0 ] && echo "[electron-dev] Waiting for port + Electron locks to release..."
+ local busy=0
+ lsof -i tcp:"$CDP_PORT" >/dev/null 2>&1 && busy=1
+ [ -n "$VITE_PORT" ] && lsof -i tcp:"$VITE_PORT" >/dev/null 2>&1 && busy=1
+ [ "$busy" = "0" ] && break
+ [ $waited -eq 0 ] && echo "[electron-dev] Waiting for ports to release..."
sleep 1
waited=$((waited + 1))
done
- echo "[electron-dev] Starting Electron dev server..."
- echo "[electron-dev] Project: $PROJECT_ROOT"
- echo "[electron-dev] CDP port: $CDP_PORT"
- echo "[electron-dev] Log: $ELECTRON_LOG"
+ # Env prefix + userData seeding for pool instances.
+ local env_assignments=""
+ if [ "$POOL_MODE" = "1" ]; then
+ mkdir -p "$POOL_DIR"
+ seed_userdata "$USER_DATA_DIR"
+ env_assignments="LOBE_DESKTOP_USER_DATA_DIR='$USER_DATA_DIR' LOBE_DESKTOP_VITE_PORT=$VITE_PORT LOBE_IPC_ID='$IPC_ID'"
+ fi
- : > "$ELECTRON_LOG" # Truncate log
+ echo "[electron-dev] Starting Electron dev..."
+ echo "[electron-dev] Project: $PROJECT_ROOT"
+ echo "[electron-dev] CDP port: $CDP_PORT"
+ [ -n "$VITE_PORT" ] && echo "[electron-dev] Vite port: $VITE_PORT"
+ [ -n "$USER_DATA_DIR" ] && echo "[electron-dev] userData: $USER_DATA_DIR"
+ [ -n "$IPC_ID" ] && echo "[electron-dev] IPC id: $IPC_ID"
+ echo "[electron-dev] Log: $ELECTRON_LOG"
+
+ mkdir -p "$(dirname "$ELECTRON_LOG")"
+ : >"$ELECTRON_LOG"
- # Launch in a new session (setsid) so the whole process tree shares a PGID
- # we can later signal in one shot. `setsid bash -c '... exec ...' &` keeps
- # the bash shell as the session leader; its PID is what we save.
- # macOS doesn't ship setsid by default β€” fall back to plain bash; cleanup
- # still works via `expand_descendants` walking the process tree.
local launch_cmd="
cd '$PROJECT_ROOT/apps/desktop'
- exec npx electron-vite dev -- --remote-debugging-port=$CDP_PORT
+ exec env $env_assignments npx electron-vite dev -- --remote-debugging-port=$CDP_PORT
"
if command -v setsid >/dev/null 2>&1; then
- setsid bash -c "$launch_cmd" >> "$ELECTRON_LOG" 2>&1 < /dev/null &
+ setsid bash -c "$launch_cmd" >>"$ELECTRON_LOG" 2>&1 </dev/null &
else
- bash -c "$launch_cmd" >> "$ELECTRON_LOG" 2>&1 < /dev/null &
+ bash -c "$launch_cmd" >>"$ELECTRON_LOG" 2>&1 </dev/null &
fi
local launcher_pid=$!
- echo "$launcher_pid" > "$PIDFILE"
+ echo "$launcher_pid" >"$PIDFILE"
echo "[electron-dev] Launcher PID (session leader): $launcher_pid"
if ! wait_for_cdp; then
@@ -292,12 +362,18 @@ do_start() {
do_stop
return 1
fi
+ wait_for_renderer || true
- if ! wait_for_renderer; then
- echo "[electron-dev] Renderer not interactive β€” you may need to wait more."
+ if [ "$POOL_MODE" = "1" ]; then
+ echo "[electron-dev] Ready! Drive it with: agent-browser --session s$CDP_PORT --cdp $CDP_PORT snapshot -i"
+ else
+ echo "[electron-dev] Ready! Use: agent-browser --cdp $CDP_PORT snapshot -i"
fi
+}
- echo "[electron-dev] Ready! Use: agent-browser --cdp $CDP_PORT snapshot -i"
+# Quiet stop used at the head of start β€” never wipes userData.
+do_stop_quiet_for_start() {
+ KEEP_DATA=1 do_stop >/dev/null 2>&1 || true
}
do_restart() {
@@ -306,22 +382,81 @@ do_restart() {
do_start
}
+do_list() {
+ echo "[electron-dev] Pool instances (dir: $POOL_DIR):"
+ local found=0
+ if [ -d "$POOL_DIR" ]; then
+ local pf id port reach
+ for pf in "$POOL_DIR"/instance-*.pid; do
+ [ -e "$pf" ] || continue
+ found=1
+ id=$(basename "$pf" | sed -E 's/instance-([0-9]+)\.pid/\1/')
+ port=$((CDP_BASE + id))
+ if curl -sf --max-time 2 "http://localhost:${port}/json/version" >/dev/null 2>&1; then
+ reach="UP"
+ else
+ reach="down"
+ fi
+ echo " instance $id β†’ cdp $port [$reach], vite $((VITE_BASE + id)), ud $POOL_DIR/ud-$id"
+ done
+ fi
+ [ "$found" = "0" ] && echo " (none)"
+}
+
+do_stop_all() {
+ local found=0
+ if [ -d "$POOL_DIR" ]; then
+ local pf id
+ for pf in "$POOL_DIR"/instance-*.pid; do
+ [ -e "$pf" ] || continue
+ found=1
+ id=$(basename "$pf" | sed -E 's/instance-([0-9]+)\.pid/\1/')
+ INSTANCE="$id"
+ derive_instance "$id"
+ do_stop
+ done
+ fi
+ [ "$found" = "0" ] && echo "[electron-dev] No pool instances to stop."
+}
+
# ── Main ─────────────────────────────────────────────────────────────
-case "${1:-help}" in
- start) do_start ;;
- stop) do_stop ;;
- status) do_status ;;
- restart) do_restart ;;
+case "$CMD" in
+ start)
+ derive_instance "$INSTANCE"
+ do_start
+ ;;
+ stop)
+ if [ "$INSTANCE" = "--all" ]; then
+ do_stop_all
+ else
+ derive_instance "$INSTANCE"
+ do_stop
+ fi
+ ;;
+ status)
+ derive_instance "$INSTANCE"
+ do_status
+ ;;
+ restart)
+ derive_instance "$INSTANCE"
+ do_restart
+ ;;
+ list)
+ do_list
+ ;;
*)
- echo "Usage: $0 {start|stop|status|restart}"
+ echo "Usage: $0 {start|stop|status|restart} [<id>] | $0 stop --all | $0 list"
echo ""
- echo " start β€” Start Electron dev with CDP. Detects + tears down any"
- echo " existing project Electron (e.g. \`bun run dev\`) first."
- echo " stop β€” Kill all project Electron/vite processes (main + helpers"
- echo " + descendants), with SIGTERM β†’ 5s wait β†’ SIGKILL fallback."
- echo " status β€” Check if Electron is running and CDP is reachable."
- echo " restart β€” Stop then start."
+ echo " start [<id>] β€” Start an instance. No id = legacy single instance (CDP 9222)."
+ echo " <id> = pool member: CDP 9222+id, Vite 5173+id, own userData"
+ echo " (login copied from the golden profile) + IPC id."
+ echo " stop [<id>] β€” Stop an instance. Pool stop is sibling-safe. KEEP_DATA=1 to"
+ echo " preserve the instance's userData."
+ echo " stop --all β€” Stop every pool instance."
+ echo " status [<id>] β€” Check whether the instance's CDP is reachable."
+ echo " restart [<id>] β€” Stop then start."
+ echo " list β€” List pool instances and their CDP reachability."
exit 1
;;
esac
diff --git a/.agents/skills/agent-testing/ui/electron.md b/.agents/skills/agent-testing/ui/electron.md
index 667dc1e9528..7f3f888fa36 100644
--- a/.agents/skills/agent-testing/ui/electron.md
+++ b/.agents/skills/agent-testing/ui/electron.md
@@ -30,6 +30,14 @@ After `start` succeeds, connect with: `agent-browser --cdp 9222 snapshot -i`
**Always run `$SCRIPT stop` when done testing** β€” `pkill -f "Electron"` alone won't catch all helper processes.
+> **Concurrent instances (N worktrees / parallel verification)?** `electron-dev.sh`
+> drives a pool: `start <id>` gives each instance its own CDP port, userData dir
+> (with copied login state), and β€” via env β€” its own Vite port + IPC id, so
+> multiple isolated dev instances run at once. Drive each with a distinct
+> `agent-browser --session s<port> --cdp <port>` (the daemon otherwise reuses one
+> session across ports). Full design, the collision matrix, and the login-copy
+> recipe: [../references/multi-instance.md](../references/multi-instance.md).
+
#### Environment Variables
| Variable | Default | Description |
diff --git a/apps/desktop/electron.vite.config.ts b/apps/desktop/electron.vite.config.ts
index 354f71b7b0f..fe7d77e6de0 100644
--- a/apps/desktop/electron.vite.config.ts
+++ b/apps/desktop/electron.vite.config.ts
@@ -17,6 +17,12 @@ import {
import { externalRuntimeModules } from './external-runtime-deps.config.mjs';
import { getNativeExternalDependencies } from './native-deps.config.mjs';
+// Renderer dev-server port. Overridable per instance (e.g. one git worktree per
+// concurrent dev instance) via LOBE_DESKTOP_VITE_PORT; `electron-vite dev` injects
+// the matching ELECTRON_RENDERER_URL into the main process automatically. Kept
+// deterministic (still `strictPort`) so the HMR `clientPort` stays in sync.
+const DEV_VITE_PORT = Number(process.env.LOBE_DESKTOP_VITE_PORT) || 5173;
+
/**
* Force `base: '/'` in renderer config. The `electron-vite` preset
* unconditionally rewrites base to `'./'` in production (with `enforce: 'pre'`),
@@ -345,14 +351,14 @@ export default defineConfig({
// silently sliding, and `clientPort` baked into the HMR injection has to match.
server: {
hmr: {
- clientPort: 5173,
+ clientPort: DEV_VITE_PORT,
host: '127.0.0.1',
protocol: 'ws',
},
// Force IPv4 so main-process `fetch` skips happy-eyeballs dual-stack
// attempts that surface as ETIMEDOUT under cold-start request bursts.
host: '127.0.0.1',
- port: 5173,
+ port: DEV_VITE_PORT,
strictPort: true,
},
},
diff --git a/apps/desktop/src/main/core/App.ts b/apps/desktop/src/main/core/App.ts
index 53247d07a08..4a832bf29ea 100644
--- a/apps/desktop/src/main/core/App.ts
+++ b/apps/desktop/src/main/core/App.ts
@@ -469,7 +469,11 @@ export class App {
};
});
- this.ipcServer = new ElectronIPCServer(name, ipcServerEvents);
+ // Socket path is derived from this id (`${id}-electron-ipc.sock`). Keep the
+ // package name by default; override with LOBE_IPC_ID so concurrent dev
+ // instances get distinct sockets instead of the last one hijacking the path.
+ const ipcId = process.env.LOBE_IPC_ID || name;
+ this.ipcServer = new ElectronIPCServer(ipcId, ipcServerEvents);
}
// Add before-quit handler function
diff --git a/apps/desktop/src/main/pre-app-init.ts b/apps/desktop/src/main/pre-app-init.ts
index 7880afa2e8e..9e30ab31d79 100644
--- a/apps/desktop/src/main/pre-app-init.ts
+++ b/apps/desktop/src/main/pre-app-init.ts
@@ -10,6 +10,16 @@ import * as electronIs from 'electron-is';
// IndexedDB would collide if both shared the packaged-app's userData dir. Pin dev to
// a sibling directory so prod sessions stay clean.
if (electronIs.dev()) {
+ // App name stays constant so safeStorage / Chromium cookie encryption keys
+ // (OS-keychain entries derived from the app name) keep decrypting a copied
+ // login state across instances. Only userData varies per instance, which is
+ // enough: Electron's single-instance lock is keyed by the userData dir, so
+ // distinct dirs let multiple dev instances run concurrently. Override with an
+ // absolute path via LOBE_DESKTOP_USER_DATA_DIR for multi-instance testing.
app.setName('lobehub-desktop-dev');
- app.setPath('userData', path.join(app.getPath('appData'), 'lobehub-desktop-dev'));
+ const userDataOverride = process.env.LOBE_DESKTOP_USER_DATA_DIR;
+ app.setPath(
+ 'userData',
+ userDataOverride || path.join(app.getPath('appData'), 'lobehub-desktop-dev'),
+ );
}