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.

πŸ”¨ chore(desktop): share dev instance isolation and label dev windows (#22823)

YuTengjingaef402e2b4bc
diff --git a/.agents/acceptance/PROJECT.md b/.agents/acceptance/PROJECT.md
index 26cfcca7008..52f31410cf8 100644
--- a/.agents/acceptance/PROJECT.md
+++ b/.agents/acceptance/PROJECT.md
@@ -282,9 +282,16 @@ stale standalone install: a recently added workspace package fails to resolve
one manual sign-in instead.
- Concurrent instances (N worktrees / parallel runs): `electron-dev.sh` drives a
pool β€” `start <id>` gives each its own CDP port, userData dir (with copied
- login), Vite port, and IPC id. Drive each with a distinct
+ login), Vite port, and IPC id, and labels every window with the checkout and
+ `#<id>` (dev builds only, from `LOBE_DESKTOP_INSTANCE_LABEL`) so a screenshot
+ shows which instance it came from. Drive each with a distinct
`agent-browser --session s<port> --cdp <port>`. Pool design, the collision
matrix, and the login-copy recipe: `.agents/acceptance/references/multi-instance.md`.
+- Instance rules live in `apps/desktop/scripts/devInstance.mts` (ports, profile,
+ IPC and label environment; the CDP check that the UI rendered; login snapshot
+ seeding and saving). `electron-dev.sh` calls it through `devInstanceCli.mts`,
+ and other launchers that run several checkouts import it, so change the
+ rules there rather than in the shell script.
### Heterogeneous-agent compatibility (project skill)
diff --git a/.agents/acceptance/references/multi-instance.md b/.agents/acceptance/references/multi-instance.md
index fabb2d2a4c2..de529a08335 100644
--- a/.agents/acceptance/references/multi-instance.md
+++ b/.agents/acceptance/references/multi-instance.md
@@ -49,16 +49,16 @@ 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 | `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. |
-| Static file server / iMessage bridge | `getPort()` dynamic | βœ… auto-allocated, safe. |
+| 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 | `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** | πŸ”‘ macOS: an instance with `LOBE_DESKTOP_MOCK_KEYCHAIN=1` uses the mock keychain (fixed key, no prompt per checkout binary). |
+| 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)
@@ -77,6 +77,12 @@ Naively "give each instance a different app name" (a tempting first instinct)
> **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.
+> On macOS, an instance with its own userData and `LOBE_DESKTOP_MOCK_KEYCHAIN=1`
+> (the pool sets it) also passes `--use-mock-keychain`: the keychain grants access
+> per binary, and every checkout installs its own ad-hoc-signed Electron, so the
+> real keychain asked for the login password once per checkout. Such instances
+> share the mock key with each other, not with the default profile. The mock key
+> is public, so set the flag only for profiles holding test accounts.
> 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.
@@ -117,25 +123,25 @@ 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)
-```
+On macOS a pool instance (its own `LOBE_DESKTOP_USER_DATA_DIR` plus
+`LOBE_DESKTOP_MOCK_KEYCHAIN=1`) encrypts tokens and cookies with Chromium's mock keychain (`src/main/pre-app-init.ts`), so the
+system keychain never asks for the login password once per checkout. A login
+copies only between profiles with the same key: from one such instance to
+another (the pool snapshot), not from the default `lobehub-desktop-dev` profile,
+which uses the real keychain. A snapshot saved before this switch no longer
+decrypts (the instance log shows `Failed to decrypt access token` and the window
+stays signed out): sign in once in a pool instance, then `stop` it to re-take the
+snapshot. Copy a login with `apps/desktop/scripts/devInstanceCli.mts`: `save-login`
+snapshots a signed-in profile and `seed-login` copies it into a new one (both run by
+`electron-dev.sh`). They copy only the login-bearing items below, NOT the multi-GB
+caches, and drop the install-scoped `gatewayDeviceId`:
- `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.
+- Decryption works because both profiles use the same key: the mock keychain
+ for pool instances on macOS, otherwise the keychain entry
+ `lobehub-desktop-dev Safe Storage` (app name unchanged). **Same machine only**
+ for the keychain key β€” 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).
@@ -223,8 +229,8 @@ 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 start 1 # CDP 9223, Vite 5174, userData ud-1 (login copied), IPC id -9223
+electron-dev.sh start 2 # CDP 9224, Vite 5175, userData ud-2, IPC id -9224
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
@@ -232,10 +238,15 @@ electron-dev.sh stop --all # stop every instance
```
- 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`.
+ `IPC id=lobehub-desktop-dev-<cdp port>` (named by port so launchers with
+ other id schemes cannot pick the same socket), a window label of the checkout
+ plus `#<id>`, per-id log + pidfile. All of it comes from
+ `apps/desktop/scripts/devInstance.mts`.
+- A copied login drops `gatewayDeviceId`, the device-gateway connection id; two
+ instances sharing it replace each other's socket on every reconnect.
+- `start <id>` seeds a fresh userData with the login-item set from the snapshot
+ the last `stop` saved; the first run signs in once inside the app. `stop <id>`
+ wipes the userData 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>`.
@@ -244,7 +255,7 @@ electron-dev.sh stop --all # stop every instance
### Round 1 β€” concurrency, login reuse, isolation (Model A)
-Golden profile `lobehub-desktop-dev` (logged in, user\_2gmT…); 3 userData copies
+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.
diff --git a/.agents/acceptance/scripts/electron-dev.sh b/.agents/acceptance/scripts/electron-dev.sh
index a4e09450d78..9b322fcc306 100755
--- a/.agents/acceptance/scripts/electron-dev.sh
+++ b/.agents/acceptance/scripts/electron-dev.sh
@@ -19,7 +19,11 @@
# 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 seeded from the saved snapshot)
-# IPC id = lobehub-desktop-dev-<id> β†’ needs LOBE_IPC_ID support
+# IPC id = lobehub-desktop-dev-<cdp port> β†’ needs LOBE_IPC_ID support
+# label = checkout name + #<id>, shown on every window (dev builds only)
+# Ports, profile env, renderer readiness and login state come from the shared
+# module apps/desktop/scripts/devInstance.mts (via devInstanceCli.mts), which
+# other multi-checkout launchers import too β€” fix them there, not here.
# Drive each with a DISTINCT agent-browser session, else the daemon reuses one
# connection across ports: agent-browser --session s<port> --cdp <port> ...
#
@@ -28,8 +32,9 @@
# wipes the userData, and `start` seeds new instances from that snapshot. The
# app's OAuth refresh token ROTATES on every boot, so only the instance that
# booted last holds a usable one β€” the snapshot must be re-taken each run, which
-# is exactly what `stop` does. The golden profile is only a fallback for the very
-# first run, and is never written to (it belongs to the user's own dev app).
+# is exactly what `stop` does. On macOS pool instances encrypt the login with
+# Chromium's mock keychain (no keychain prompt per checkout), so they cannot
+# read the user's own dev profile: the first run signs in once inside the app.
# ./electron-dev.sh login-status # where the login comes from + expiry
# ./electron-dev.sh save-login <id> # snapshot a live instance without stopping
# If an instance is killed instead of stopped (crash, command timeout), its
@@ -43,8 +48,6 @@
# POOL_DIR β€” pool state dir (default: /tmp/lobe-electron-pool)
# LOBE_LOGIN_STATE_DIR β€” persistent login snapshot, survives /tmp cleanup
# (default: ~/.lobehub/agent-testing/electron-login)
-# LOBE_GOLDEN_PROFILE β€” userData to seed from when no snapshot exists yet
-# (default: ~/Library/Application Support/lobehub-desktop-dev)
# KEEP_DATA=1 β€” on `stop <id>`, keep the instance's userData dir
# SKIP_LOGIN_SAVE=1 β€” on `stop <id>`, do not snapshot the login state
# ELECTRON_WAIT_S β€” max seconds to wait for CDP (default: 90)
@@ -66,9 +69,13 @@ RENDERER_WAIT_S="${RENDERER_WAIT_S:-60}"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
POOL_DIR="${POOL_DIR:-/tmp/lobe-electron-pool}"
-GOLDEN_PROFILE="${LOBE_GOLDEN_PROFILE:-$HOME/Library/Application Support/lobehub-desktop-dev}"
# Persistent across runs AND across /tmp cleanup β€” the pool dir is not.
LOGIN_STATE_DIR="${LOBE_LOGIN_STATE_DIR:-$HOME/.lobehub/agent-testing/electron-login}"
+DEV_INSTANCE_CLI="$PROJECT_ROOT/apps/desktop/scripts/devInstanceCli.mts"
+
+dev_instance() {
+ node "$DEV_INSTANCE_CLI" "$@"
+}
# 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
@@ -81,6 +88,8 @@ CDP_PORT=""
VITE_PORT=""
USER_DATA_DIR=""
IPC_ID=""
+INSTANCE_LABEL=""
+INSTANCE_ENV=()
ELECTRON_LOG=""
PIDFILE=""
@@ -93,6 +102,7 @@ derive_instance() {
VITE_PORT="" # legacy: no override, config default applies
USER_DATA_DIR="" # legacy: default userData
IPC_ID="" # legacy: default IPC id
+ INSTANCE_LABEL="$(dev_instance checkout-label "$PROJECT_ROOT" 2>/dev/null || true)"
ELECTRON_LOG="${ENV_ELECTRON_LOG:-/tmp/electron-dev.log}"
PIDFILE="/tmp/electron-dev-cdp-${CDP_PORT}.pid"
else
@@ -104,7 +114,14 @@ derive_instance() {
CDP_PORT=$((CDP_BASE + id))
VITE_PORT=$((VITE_BASE + id))
USER_DATA_DIR="$POOL_DIR/ud-$id"
- IPC_ID="lobehub-desktop-dev-$id"
+ INSTANCE_LABEL="$(dev_instance checkout-label "$PROJECT_ROOT" 2>/dev/null || true) #$id"
+ INSTANCE_ENV=()
+ local line
+ while IFS= read -r line; do
+ [ -n "$line" ] && INSTANCE_ENV+=("$line")
+ case "$line" in LOBE_IPC_ID=*) IPC_ID="${line#LOBE_IPC_ID=}" ;; esac
+ done < <(dev_instance env --cdp-port "$CDP_PORT" --renderer-port "$VITE_PORT" \
+ --user-data "$USER_DATA_DIR" --label "$INSTANCE_LABEL")
ELECTRON_LOG="$POOL_DIR/instance-$id.log"
PIDFILE="$POOL_DIR/instance-$id.pid"
fi
@@ -190,120 +207,20 @@ wait_for_cdp() {
}
wait_for_renderer() {
- 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 --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
+ # Never fatal: a slow first Vite load should not tear down a reachable app.
+ dev_instance wait-renderer --cdp-port "$CDP_PORT" --timeout-s "$RENDERER_WAIT_S" || true
}
# ── Login state ──────────────────────────────────────────────────────
#
-# The login-bearing subset of a userData dir (skips the multi-GB caches). The
-# OAuth tokens themselves live in lobehub-settings.json β†’ encryptedTokens.
-LOGIN_ITEMS=(
- "lobehub-settings.json" "Local State" "Preferences"
- "Cookies" "Cookies-journal" "Local Storage" "IndexedDB"
- "Session Storage" "Network Persistent State" "lobehub-storage"
-)
-
-copy_login_items() {
- local src="$1" dst="$2" f
- mkdir -p "$dst"
- for f in "${LOGIN_ITEMS[@]}"; do
- [ -e "$src/$f" ] && cp -R "$src/$f" "$dst/" 2>/dev/null || true
- done
-}
-
-# Reads lobehub-settings.json β†’ encryptedTokens and prints
-# "<hasRefreshToken:0|1> <msUntilAccessTokenExpiry|?>"
-#
-# `expiresAt` is `Date.now() + data.expires_in * 1000` (RemoteServerConfigCtr.saveTokens),
-# i.e. the ACCESS token's lifetime β€” NOT the refresh token's. It is routinely in the
-# past on a perfectly refreshable login, so it must never gate whether we keep a
-# profile. What does gate it: the app deletes the whole `encryptedTokens` key
-# (clearTokens) the moment a refresh fails non-retryably (`invalid_grant` &co), and
-# keeps it on transient failures. So a present refreshToken means "can still re-auth".
-read_token_state() {
- python3 - "$1/lobehub-settings.json" 2>/dev/null <<'PY' || echo "0 ?"
-import json, pathlib, sys, time
-
-path = pathlib.Path(sys.argv[1])
-if not path.is_file():
- print("0 ?")
- sys.exit(0)
-try:
- tokens = (json.loads(path.read_text()) or {}).get('encryptedTokens') or {}
-except Exception:
- print("0 ?")
- sys.exit(0)
-
-has_refresh = 1 if tokens.get('refreshToken') else 0
-expires_at = tokens.get('expiresAt')
-if not expires_at:
- print(f"{has_refresh} ?")
- sys.exit(0)
-# The field has been seen in both seconds and milliseconds.
-if expires_at < 1e11:
- expires_at *= 1000
-print(f"{has_refresh} {int(expires_at - time.time() * 1000)}")
-PY
-}
-
-# True when the profile still carries a refresh token, i.e. the app can mint a new
-# session from it on the next boot. An expired ACCESS token says nothing here.
-profile_can_reauth() {
- local state
- state=$(read_token_state "$1")
- [ "${state%% *}" = "1" ]
-}
-
-describe_login() {
- local label="$1" profile="$2" state ms access
- if [ ! -d "$profile" ]; then
- echo " $label: (absent) β€” $profile"
- return
- fi
- state=$(read_token_state "$profile")
- ms="${state##* }"
- if [[ "$ms" =~ ^-?[0-9]+$ ]]; then
- [ "$ms" -gt 0 ] &&
- access="access token fresh for $((ms / 3600000))h" ||
- access="access token stale $(( -ms / 3600000 ))h (harmless β€” it gets refreshed)"
- else
- access="no access-token expiry recorded"
- fi
- if [ "${state%% *}" = "1" ]; then
- echo " $label: refresh token PRESENT β€” $access β€” $profile"
- else
- echo " $label: refresh token GONE (app cleared it after a failed refresh) β€” $profile"
- fi
-}
+# The login-bearing subset of a userData dir, the refresh-token check and the
+# install-scoped settings a copy must drop live in devInstance.mts.
# 1 when the running renderer reports a signed-in user. The OAuth refresh token
# is not the only way the app holds a session (a better-auth cookie outlives it),
# so an expired token does NOT mean the instance is signed out β€” ask the app.
probe_renderer_authed() {
- if ! curl -sf --max-time 2 "http://localhost:${CDP_PORT}/json/version" >/dev/null 2>&1; then
- echo 0
- return
- fi
- local out
- out=$(agent-browser --session "edev$CDP_PORT" --cdp "$CDP_PORT" eval \
- '(function(){try{var u=window.__LOBE_STORES.user();return (u.user&&u.user.id)?"AUTHED":"ANON";}catch(e){return "ERR";}})()' \
- 2>/dev/null | tail -1 || true)
- case "$out" in
- *AUTHED*) echo 1 ;;
- *) echo 0 ;;
- esac
+ dev_instance signed-in --cdp-port "$CDP_PORT" 2>/dev/null || echo 0
}
# Persist an instance's login into the snapshot so the NEXT run starts signed in.
@@ -313,50 +230,13 @@ probe_renderer_authed() {
# overrides the token check, which cannot see a cookie-only session.
save_login_state() {
local src="$1" authed_hint="${2:-0}"
- [ -d "$src" ] || return 0
- if [ "$authed_hint" != "1" ] && ! profile_can_reauth "$src"; then
- echo "[electron-dev] Not saving login state: $src is signed out (the app cleared its refresh token) β€” kept the previous snapshot."
- return 0
- fi
- local staging="${LOGIN_STATE_DIR}.staging.$$"
- rm -rf "$staging"
- mkdir -p "$(dirname "$LOGIN_STATE_DIR")"
- copy_login_items "$src" "$staging"
- rm -rf "$LOGIN_STATE_DIR"
- mv "$staging" "$LOGIN_STATE_DIR"
- if profile_can_reauth "$LOGIN_STATE_DIR"; then
- echo "[electron-dev] Saved login state β†’ $LOGIN_STATE_DIR (refresh token captured)"
- else
- echo "[electron-dev] Saved login state β†’ $LOGIN_STATE_DIR (cookie session only β€” no refresh token on disk)"
- fi
+ dev_instance save-login --user-data "$src" --snapshot "$LOGIN_STATE_DIR" --signed-in "$authed_hint"
}
-# Seed a fresh userData dir: prefer the snapshot we saved on the last stop, and
-# fall back to the user's own dev profile for the very first run. No-op if the
-# dir already exists.
+# Seed a fresh userData dir from the snapshot saved on the last stop. No-op if
+# the dir already exists.
seed_userdata() {
- local dst="$1"
- [ -d "$dst" ] && return 0
-
- # The snapshot only exists because a `stop`/`save-login` found that instance
- # signed in, so prefer it unconditionally over the golden profile.
- local src="" label=""
- if [ -d "$LOGIN_STATE_DIR" ]; then
- src="$LOGIN_STATE_DIR"
- label="saved login state"
- elif [ -d "$GOLDEN_PROFILE" ]; then
- src="$GOLDEN_PROFILE"
- label="golden profile (first run)"
- else
- echo "[electron-dev] WARNING: no login state at $LOGIN_STATE_DIR or $GOLDEN_PROFILE β€” instance will start signed out."
- mkdir -p "$dst"
- return 0
- fi
-
- echo "[electron-dev] Seeding userData from $label β†’ $dst"
- profile_can_reauth "$src" ||
- echo "[electron-dev] note: no refresh token on disk β€” a cookie session may still carry it; otherwise sign in once and 'stop' will capture it."
- copy_login_items "$src" "$dst"
+ dev_instance seed-login --user-data "$1" --snapshot "$LOGIN_STATE_DIR"
}
# ── Commands ─────────────────────────────────────────────────────────
@@ -483,11 +363,14 @@ do_start() {
done
# Env prefix + userData seeding for pool instances.
- local env_assignments=""
+ 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'"
+ env_assignments=("${INSTANCE_ENV[@]}")
+ else
+ env_assignments=("LOBE_DESKTOP_CDP_PORT=$CDP_PORT")
+ [ -n "$INSTANCE_LABEL" ] && env_assignments+=("LOBE_DESKTOP_INSTANCE_LABEL=$INSTANCE_LABEL")
fi
echo "[electron-dev] Starting Electron dev..."
@@ -496,19 +379,22 @@ do_start() {
[ -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"
+ [ -n "$INSTANCE_LABEL" ] && echo "[electron-dev] Label: $INSTANCE_LABEL"
echo "[electron-dev] Log: $ELECTRON_LOG"
mkdir -p "$(dirname "$ELECTRON_LOG")"
: >"$ELECTRON_LOG"
- local launch_cmd="
- cd '$PROJECT_ROOT/apps/desktop'
- exec env $env_assignments LOBE_DESKTOP_CDP_PORT=$CDP_PORT pnpm dev
- "
+ # Values reach `env` as separate argv entries, so labels and paths with spaces
+ # or quotes survive without shell re-parsing.
+ # shellcheck disable=SC2016 # expanded by the inner bash, not here
+ local launch_cmd='cd "$1" && shift && exec env "$@" pnpm dev'
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-dev "$PROJECT_ROOT/apps/desktop" "${env_assignments[@]}" \
+ >>"$ELECTRON_LOG" 2>&1 </dev/null &
else
- bash -c "$launch_cmd" >>"$ELECTRON_LOG" 2>&1 </dev/null &
+ bash -c "$launch_cmd" electron-dev "$PROJECT_ROOT/apps/desktop" "${env_assignments[@]}" \
+ >>"$ELECTRON_LOG" 2>&1 </dev/null &
fi
local launcher_pid=$!
echo "$launcher_pid" >"$PIDFILE"
@@ -565,17 +451,7 @@ do_list() {
}
do_login_status() {
- echo "[electron-dev] Login sources (the snapshot wins when present):"
- describe_login "saved snapshot" "$LOGIN_STATE_DIR"
- describe_login "golden profile" "$GOLDEN_PROFILE"
- if [ ! -d "$LOGIN_STATE_DIR" ] && [ ! -d "$GOLDEN_PROFILE" ]; then
- echo "[electron-dev] Nothing to seed from: sign in once inside the app, then 'save-login <id>' (or just 'stop <id>')."
- return 2
- fi
- echo "[electron-dev] Note: 'expiresAt' in the profile is the ACCESS token's lifetime, not the"
- echo "[electron-dev] refresh token's β€” a stale one is normal and gets refreshed on boot. Only a"
- echo "[electron-dev] missing refresh token means signed out. 'stop'/'save-login' also probe the"
- echo "[electron-dev] running renderer, so a cookie-only session is captured too."
+ dev_instance login-status --snapshot "$LOGIN_STATE_DIR"
}
do_stop_all() {
diff --git a/apps/desktop/scripts/__tests__/devInstance.test.mts b/apps/desktop/scripts/__tests__/devInstance.test.mts
new file mode 100644
index 00000000000..a95445be29d
--- /dev/null
+++ b/apps/desktop/scripts/__tests__/devInstance.test.mts
@@ -0,0 +1,322 @@
+import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ copyLoginItems,
+ createDesktopDevInstance,
+ describeLoginState,
+ getAppDataDirectory,
+ getCheckoutLabel,
+ getDesktopDevEnvironment,
+ probeCdpPages,
+ readTokenState,
+ saveLoginState,
+ seedLoginState,
+ waitForDesktopWindow,
+} from '../devInstance.mts';
+
+let root: string;
+
+beforeEach(async () => {
+ root = await mkdtemp(path.join(os.tmpdir(), 'dev-instance-'));
+});
+
+afterEach(async () => {
+ await rm(root, { force: true, recursive: true });
+});
+
+const writeProfile = async (
+ directory: string,
+ settings: Record<string, unknown>,
+ extraItems: string[] = [],
+) => {
+ await mkdir(directory, { recursive: true });
+ await writeFile(path.join(directory, 'lobehub-settings.json'), JSON.stringify(settings));
+ for (const item of extraItems) await writeFile(path.join(directory, item), item);
+};
+
+const signedIn = { encryptedTokens: { expiresAt: 2_000_000_000_000, refreshToken: 'r' } };
+
+describe('instance environment', () => {
+ it('derives the IPC socket name from the CDP port so id schemes cannot collide', () => {
+ const instance = createDesktopDevInstance({
+ cdpPort: 9317,
+ label: 'feature-x',
+ rendererPort: 5217,
+ userDataDirectory: '/tmp/profile',
+ });
+
+ expect(getDesktopDevEnvironment(instance)).toEqual({
+ LOBE_DESKTOP_CDP_PORT: '9317',
+ LOBE_DESKTOP_INSTANCE_LABEL: 'feature-x',
+ LOBE_DESKTOP_USER_DATA_DIR: '/tmp/profile',
+ LOBE_DESKTOP_VITE_PORT: '5217',
+ LOBE_IPC_ID: 'lobehub-desktop-dev-9317',
+ });
+ });
+
+ it('asks for the mock keychain only for a profile of its own', () => {
+ expect(
+ getDesktopDevEnvironment(
+ createDesktopDevInstance({
+ cdpPort: 9317,
+ mockKeychain: true,
+ rendererPort: 5217,
+ userDataDirectory: '/tmp/profile',
+ }),
+ ),
+ ).toMatchObject({ LOBE_DESKTOP_MOCK_KEYCHAIN: '1' });
+ expect(
+ getDesktopDevEnvironment(
+ createDesktopDevInstance({ cdpPort: 9223, mockKeychain: true, rendererPort: 5174 }),
+ ),
+ ).not.toHaveProperty('LOBE_DESKTOP_MOCK_KEYCHAIN');
+ });
+
+ it('omits the profile and label when the shared default applies', () => {
+ expect(
+ getDesktopDevEnvironment(createDesktopDevInstance({ cdpPort: 9223, rendererPort: 5174 })),
+ ).toEqual({
+ LOBE_DESKTOP_CDP_PORT: '9223',
+ LOBE_DESKTOP_VITE_PORT: '5174',
+ LOBE_IPC_ID: 'lobehub-desktop-dev-9223',
+ });
+ });
+
+ it('labels a checkout by directory and adds the branch only when the name hides it', () => {
+ expect(getCheckoutLabel({ branch: 'feat/desktop-label', root: '/w/feat-desktop-label' })).toBe(
+ 'feat-desktop-label',
+ );
+ expect(getCheckoutLabel({ branch: 'main', root: '/w/lobehub' })).toBe('lobehub Β· main');
+ expect(getCheckoutLabel({ branch: '', root: '/w/lobehub' })).toBe('lobehub');
+ });
+
+ it('resolves Electron appData per platform', () => {
+ expect(getAppDataDirectory('darwin', {}, '/Users/u')).toBe(
+ '/Users/u/Library/Application Support',
+ );
+ expect(getAppDataDirectory('linux', { XDG_CONFIG_HOME: '/cfg' }, '/home/u')).toBe('/cfg');
+ expect(getAppDataDirectory('linux', {}, '/home/u')).toBe('/home/u/.config');
+ expect(getAppDataDirectory('win32', { APPDATA: 'C:\\A' }, 'C:\\U')).toBe('C:\\A');
+ });
+});
+
+describe('renderer probes', () => {
+ const fetchTargets = (targets: unknown) =>
+ vi.fn(async () => new Response(JSON.stringify(targets))) as unknown as typeof fetch;
+
+ it('is true when any page target evaluates to true', async () => {
+ const evaluate = vi.fn(async (url: string) => url === 'ws://page-2');
+
+ await expect(
+ probeCdpPages(
+ 9300,
+ 'expr',
+ fetchTargets([
+ { type: 'page', webSocketDebuggerUrl: 'ws://page-1' },
+ { type: 'service_worker', webSocketDebuggerUrl: 'ws://worker' },
+ { type: 'page', webSocketDebuggerUrl: 'ws://page-2' },
+ ]),
+ evaluate,
+ ),
+ ).resolves.toBe(true);
+ expect(evaluate).not.toHaveBeenCalledWith('ws://worker', 'expr');
+ });
+
+ it('is false when CDP is unreachable or every evaluation fails', async () => {
+ const unreachable = vi.fn(async () => {
+ throw new Error('ECONNREFUSED');
+ }) as unknown as typeof fetch;
+ await expect(probeCdpPages(9300, 'expr', unreachable)).resolves.toBe(false);
+
+ await expect(
+ probeCdpPages(
+ 9300,
+ 'expr',
+ fetchTargets([{ type: 'page', webSocketDebuggerUrl: 'ws://page' }]),
+ vi.fn(async () => {
+ throw new Error('closed');
+ }),
+ ),
+ ).resolves.toBe(false);
+ });
+
+ it('reports a timeout instead of throwing so callers decide whether it is fatal', async () => {
+ let clock = 0;
+ const probe = vi.fn(async () => false);
+ const wait = vi.fn(async (durationMs: number) => {
+ clock += durationMs;
+ });
+
+ await expect(
+ waitForDesktopWindow({ cdpPort: 9300, now: () => clock, probe, timeoutMs: 3000, wait }),
+ ).resolves.toBe(false);
+ expect(probe).toHaveBeenCalledTimes(4);
+ expect(clock).toBe(3000);
+ });
+
+ /** Regression: a fixed attempt count let 2s probes stretch a 60s wait to about 180s. */
+ it('stops at the deadline even when each probe is slow', async () => {
+ let clock = 0;
+ const probe = vi.fn(async () => {
+ clock += 2000;
+ return false;
+ });
+ const wait = vi.fn(async (durationMs: number) => {
+ clock += durationMs;
+ });
+
+ await expect(
+ waitForDesktopWindow({ cdpPort: 9300, now: () => clock, probe, timeoutMs: 3000, wait }),
+ ).resolves.toBe(false);
+ expect(probe).toHaveBeenCalledTimes(2);
+ expect(clock).toBeLessThanOrEqual(5000);
+ });
+
+ it('stops waiting when the process tree exits', async () => {
+ await expect(
+ waitForDesktopWindow({
+ assertRunning: () => {
+ throw new Error('exited');
+ },
+ cdpPort: 9300,
+ probe: async () => true,
+ timeoutMs: 3000,
+ }),
+ ).rejects.toThrow('exited');
+ });
+});
+
+describe('login state', () => {
+ it('reads expiry in seconds or milliseconds and treats the refresh token as the signal', async () => {
+ const profile = path.join(root, 'profile');
+ await writeProfile(profile, { encryptedTokens: { expiresAt: 1000, refreshToken: 'r' } });
+ await expect(readTokenState(profile, 0)).resolves.toEqual({
+ accessTokenExpiresInMs: 1_000_000,
+ hasRefreshToken: true,
+ });
+
+ await writeProfile(profile, { encryptedTokens: { expiresAt: 1_700_000_000_000 } });
+ await expect(readTokenState(profile, 1_700_000_000_000)).resolves.toEqual({
+ accessTokenExpiresInMs: 0,
+ hasRefreshToken: false,
+ });
+
+ await expect(readTokenState(path.join(root, 'absent'))).resolves.toEqual({
+ hasRefreshToken: false,
+ });
+ });
+
+ it('copies only login items into a private directory and drops the gateway connection id', async () => {
+ const source = path.join(root, 'source');
+ const target = path.join(root, 'target');
+ await writeProfile(source, { ...signedIn, gatewayDeviceId: 'shared', locale: 'en' }, [
+ 'Cookies',
+ 'Cache',
+ ]);
+
+ await copyLoginItems(source, target);
+
+ expect((await stat(target)).mode & 0o777).toBe(0o700);
+ await expect(stat(path.join(target, 'Cookies'))).resolves.toBeTruthy();
+ await expect(stat(path.join(target, 'Cache'))).rejects.toThrow();
+ const settings = JSON.parse(await readFile(path.join(target, 'lobehub-settings.json'), 'utf8'));
+ expect(settings).toEqual({ ...signedIn, locale: 'en' });
+ });
+
+ it('seeds from the first available source', async () => {
+ const snapshot = path.join(root, 'snapshot');
+ const golden = path.join(root, 'golden');
+ await writeProfile(snapshot, signedIn);
+ await writeProfile(golden, {});
+
+ const result = await seedLoginState(path.join(root, 'target'), [
+ { directory: path.join(root, 'missing'), label: 'missing' },
+ { directory: snapshot, label: 'snapshot' },
+ { directory: golden, label: 'golden' },
+ ]);
+
+ expect(result).toMatchObject({
+ canReauth: true,
+ source: { label: 'snapshot' },
+ status: 'seeded',
+ });
+ await expect(stat(snapshot)).resolves.toBeTruthy();
+ });
+
+ it('leaves an existing profile alone and creates an empty one when nothing can seed it', async () => {
+ const existing = path.join(root, 'existing');
+ await writeProfile(existing, { locale: 'en' });
+ const snapshot = path.join(root, 'snapshot');
+ await writeProfile(snapshot, signedIn);
+
+ await expect(
+ seedLoginState(existing, [{ directory: snapshot, label: 'snapshot' }]),
+ ).resolves.toEqual({ status: 'existing' });
+ await expect(stat(snapshot)).resolves.toBeTruthy();
+
+ const fresh = path.join(root, 'fresh');
+ await expect(seedLoginState(fresh, [])).resolves.toEqual({ status: 'none' });
+ expect((await stat(fresh)).mode & 0o777).toBe(0o700);
+ });
+
+ it('keeps the previous snapshot when the source is signed out', async () => {
+ const snapshot = path.join(root, 'snapshot');
+ await writeProfile(snapshot, signedIn);
+ const source = path.join(root, 'source');
+ await writeProfile(source, { locale: 'fr' });
+
+ await expect(saveLoginState(source, { snapshotDirectory: snapshot })).resolves.toBe(
+ 'signed-out',
+ );
+ expect(
+ JSON.parse(await readFile(path.join(snapshot, 'lobehub-settings.json'), 'utf8')),
+ ).toEqual(signedIn);
+ await expect(
+ saveLoginState(path.join(root, 'absent'), { snapshotDirectory: snapshot }),
+ ).resolves.toBe('missing');
+ });
+
+ it('replaces the snapshot from a signed-in source, including a cookie-only session', async () => {
+ const snapshot = path.join(root, 'state', 'snapshot');
+ const source = path.join(root, 'source');
+ await writeProfile(source, signedIn, ['Cookies']);
+
+ await expect(saveLoginState(source, { snapshotDirectory: snapshot })).resolves.toBe('saved');
+ await expect(stat(path.join(snapshot, 'Cookies'))).resolves.toBeTruthy();
+
+ await writeProfile(source, { locale: 'de' });
+ await expect(
+ saveLoginState(source, { signedIn: true, snapshotDirectory: snapshot }),
+ ).resolves.toBe('saved-cookie-only');
+ });
+
+ /** Regression: saving chmod-ed the parent to 0700, failing (EPERM) under a shared /tmp. */
+ it('keeps the permissions of an existing snapshot parent', async () => {
+ const parent = path.join(root, 'shared');
+ await mkdir(parent, { mode: 0o755 });
+ const snapshot = path.join(parent, 'snapshot');
+ const source = path.join(root, 'source');
+ await writeProfile(source, signedIn);
+
+ await expect(saveLoginState(source, { snapshotDirectory: snapshot })).resolves.toBe('saved');
+ expect((await stat(parent)).mode & 0o777).toBe(0o755);
+ expect((await stat(snapshot)).mode & 0o777).toBe(0o700);
+ });
+
+ it('describes whether a profile can still sign the next instance in', async () => {
+ const profile = path.join(root, 'profile');
+ await expect(describeLoginState('snapshot', profile)).resolves.toContain('(absent)');
+
+ await writeProfile(profile, { encryptedTokens: { expiresAt: 7200, refreshToken: 'r' } });
+ await expect(describeLoginState('snapshot', profile, 0)).resolves.toContain(
+ 'refresh token PRESENT β€” access token fresh for 2h',
+ );
+
+ await writeProfile(profile, {});
+ await expect(describeLoginState('snapshot', profile)).resolves.toContain('refresh token GONE');
+ });
+});
diff --git a/apps/desktop/scripts/devInstance.mts b/apps/desktop/scripts/devInstance.mts
new file mode 100644
index 00000000000..ddafa66dee8
--- /dev/null
+++ b/apps/desktop/scripts/devInstance.mts
@@ -0,0 +1,484 @@
+/**
+ * One isolated Electron dev instance of `apps/desktop`: its ports, profile, IPC
+ * socket and window label, the check that its renderer has rendered, and the
+ * login state it can inherit or hand back.
+ *
+ * Every launcher that runs `pnpm run dev` in this package for more than one
+ * checkout at a time (`.agents/acceptance/scripts/electron-dev.sh`, and
+ * downstream runtimes that import this file) shares these rules, so a fix here
+ * reaches all of them. Only `node:` built-ins are imported and the TypeScript is
+ * erasable, so `node scripts/devInstanceCli.mts` runs it without a build step.
+ */
+import { execFile } from 'node:child_process';
+import { chmod, cp, mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { promisify } from 'node:util';
+
+// ─── Instance identity ───────────────────────────────────────────────
+
+export interface DesktopDevInstance {
+ /** Chrome DevTools Protocol port (`--remote-debugging-port`). */
+ cdpPort: number;
+ /**
+ * Names the Electron IPC socket (`${ipcId}-electron-ipc.sock` in the temp dir).
+ * Without it every dev instance binds the package name and the latest launch
+ * takes over the socket.
+ */
+ ipcId: string;
+ /** Shown on every window so a screenshot or a glance tells the checkout apart. */
+ label?: string;
+ /**
+ * Encrypt the profile's tokens and cookies with Chromium's fixed mock key
+ * instead of the macOS keychain (`src/main/pre-app-init.ts`). Only for
+ * profiles holding test accounts: the key is public, so a production login
+ * must stay behind the keychain.
+ */
+ mockKeychain?: boolean;
+ /** Renderer Vite dev server port (`strictPort`, so it must be free). */
+ rendererPort: number;
+ /**
+ * Profile directory. Electron's single-instance lock is keyed by it, so two
+ * instances can only run together with distinct directories. Absent means the
+ * shared default dev profile.
+ */
+ userDataDirectory?: string;
+}
+
+/**
+ * The CDP port already has to be unique per running instance, so deriving the
+ * socket name from it keeps launchers with different id schemes (a manual pool
+ * id, a checkout slot) from colliding on `lobehub-desktop-dev-<n>`. The name
+ * stays short enough for the 104-byte Unix socket path limit.
+ */
+export const getDesktopDevIpcId = (cdpPort: number) => `lobehub-desktop-dev-${cdpPort}`;
+
+export const createDesktopDevInstance = ({
+ cdpPort,
+ label,
+ mockKeychain,
+ rendererPort,
+ userDataDirectory,
+}: Omit<DesktopDevInstance, 'ipcId'>): DesktopDevInstance => ({
+ cdpPort,
+ ipcId: getDesktopDevIpcId(cdpPort),
+ rendererPort,
+ ...(label ? { label } : undefined),
+ ...(mockKeychain && userDataDirectory ? { mockKeychain } : undefined),
+ ...(userDataDirectory ? { userDataDirectory } : undefined),
+});
+
+/** Variables `scripts/dev.mjs` and the main process read to isolate one instance. */
+export const getDesktopDevEnvironment = (instance: DesktopDevInstance): Record<string, string> => ({
+ LOBE_DESKTOP_CDP_PORT: String(instance.cdpPort),
+ LOBE_DESKTOP_VITE_PORT: String(instance.rendererPort),
+ LOBE_IPC_ID: instance.ipcId,
+ ...(instance.label ? { LOBE_DESKTOP_INSTANCE_LABEL: instance.label } : undefined),
+ ...(instance.mockKeychain ? { LOBE_DESKTOP_MOCK_KEYCHAIN: '1' } : undefined),
+ ...(instance.userDataDirectory
+ ? { LOBE_DESKTOP_USER_DATA_DIR: instance.userDataDirectory }
+ : undefined),
+});
+
+const execFileAsync = promisify(execFile);
+
+const git = async (checkout: string, args: string[]) => {
+ try {
+ const { stdout } = await execFileAsync('git', ['-C', checkout, ...args], { encoding: 'utf8' });
+ return stdout.trim();
+ } catch {
+ return '';
+ }
+};
+
+/**
+ * The checkout a developer recognizes: when this repository is a submodule, its
+ * own directory name is the same in every superproject worktree, so the
+ * superproject's working tree names it instead.
+ */
+export const readCheckout = async (directory: string) => {
+ const superproject = await git(directory, ['rev-parse', '--show-superproject-working-tree']);
+ const root =
+ superproject || (await git(directory, ['rev-parse', '--show-toplevel'])) || directory;
+ return { branch: await git(root, ['branch', '--show-current']), root };
+};
+
+/**
+ * Names a checkout for the window label: the directory, plus the branch when the
+ * directory name does not already spell it (worktree directories usually do).
+ */
+export const getCheckoutLabel = ({ branch, root }: { branch: string; root: string }) => {
+ const name = path.basename(path.resolve(root));
+ if (!branch || branch.replaceAll('/', '-') === name) return name;
+ return `${name} Β· ${branch}`;
+};
+
+export const readCheckoutLabel = async (directory: string) =>
+ getCheckoutLabel(await readCheckout(directory));
+
+/** The profile holds session cookies and tokens, so only the owner may read it. */
+export const ensurePrivateDirectory = async (directory: string) => {
+ await mkdir(directory, { mode: 0o700, recursive: true });
+ await chmod(directory, 0o700);
+};
+
+/** Electron's `app.getPath('appData')` for the current platform. */
+export const getAppDataDirectory = (
+ platform: NodeJS.Platform = process.platform,
+ environment: NodeJS.ProcessEnv = process.env,
+ home = os.homedir(),
+) => {
+ if (platform === 'darwin') return path.join(home, 'Library', 'Application Support');
+ if (platform === 'win32') return environment.APPDATA || path.join(home, 'AppData', 'Roaming');
+ return environment.XDG_CONFIG_HOME || path.join(home, '.config');
+};
+
+/** The profile a dev instance uses without `LOBE_DESKTOP_USER_DATA_DIR` (`src/main/pre-app-init.ts`). */
+export const getDefaultDevProfileDirectory = () =>
+ path.join(getAppDataDirectory(), 'lobehub-desktop-dev');
+
+/** Survives `/tmp` cleanup and worktree removal; one per machine user. */
+export const getDefaultLoginSnapshotDirectory = () =>
+ path.join(os.homedir(), '.lobehub', 'agent-testing', 'electron-login');
+
+// ─── Renderer readiness ──────────────────────────────────────────────
+
+const CDP_PROBE_TIMEOUT_MS = 2000;
+const RENDERER_RETRY_MS = 1000;
+
+export const getCdpUrl = (cdpPort: number) => `http://127.0.0.1:${cdpPort}`;
+
+interface CdpTarget {
+ type?: string;
+ webSocketDebuggerUrl?: string;
+}
+
+/**
+ * The renderer counts as usable once `#root` (`index.html`) shows text and no
+ * loader covers the window. Route boundaries first paint `BrandTextLoading`, a
+ * full-window `role="status"` loader whose dev build has its own text, so text
+ * alone is not enough; a loader inside already painted chrome (`ContentLoading`
+ * in a panel) does not block.
+ */
+export const RENDERED_EXPRESSION = `(() => {
+ if (document.readyState !== 'complete') return false;
+ const root = document.getElementById('root');
+ if (!root || root.innerText.trim().length === 0) return false;
+ const loaders = document.querySelectorAll('[role="status"][aria-label="Loading"]');
+ return [...loaders].every((loader) => {
+ const box = (loader.parentElement ?? loader).getBoundingClientRect();
+ return box.height < window.innerHeight * 0.9;
+ });
+})()`;
+
+/** `window.__LOBE_STORES` is the dev-only store handle the renderer exposes. */
+export const SIGNED_IN_EXPRESSION = `(() => {
+ try {
+ const user = window.__LOBE_STORES?.user?.();
+ return Boolean(user?.user?.id);
+ } catch {
+ return false;
+ }
+})()`;
+
+/** Evaluates one expression in a CDP page target and returns its value. */
+export const evaluateCdpTarget = (
+ webSocketUrl: string,
+ expression: string,
+ timeoutMs = CDP_PROBE_TIMEOUT_MS,
+): Promise<unknown> =>
+ new Promise((resolve, reject) => {
+ const socket = new WebSocket(webSocketUrl);
+ const timer = setTimeout(() => {
+ socket.close();
+ reject(new Error(`CDP evaluation timed out after ${timeoutMs}ms`));
+ }, timeoutMs);
+ const settle = (callback: () => void) => {
+ clearTimeout(timer);
+ socket.close();
+ callback();
+ };
+
+ socket.addEventListener('open', () => {
+ socket.send(
+ JSON.stringify({
+ id: 1,
+ method: 'Runtime.evaluate',
+ params: { expression, returnByValue: true },
+ }),
+ );
+ });
+ socket.addEventListener('message', (event) => {
+ const message = JSON.parse(String(event.data)) as {
+ id?: number;
+ result?: { result?: { value?: unknown } };
+ };
+ if (message.id === 1) settle(() => resolve(message.result?.result?.value));
+ });
+ socket.addEventListener('error', () =>
+ settle(() => reject(new Error('CDP WebSocket connection failed'))),
+ );
+ });
+
+/** True when any page target of the instance evaluates `expression` to `true`. */
+export const probeCdpPages = async (
+ cdpPort: number,
+ expression: string,
+ fetchImplementation: typeof fetch = fetch,
+ evaluate: typeof evaluateCdpTarget = evaluateCdpTarget,
+): Promise<boolean> => {
+ try {
+ const response = await fetchImplementation(`${getCdpUrl(cdpPort)}/json/list`, {
+ signal: AbortSignal.timeout(CDP_PROBE_TIMEOUT_MS),
+ });
+ if (!response.ok) return false;
+
+ const targets = (await response.json()) as CdpTarget[];
+ if (!Array.isArray(targets)) return false;
+
+ const pages = targets.filter((target) => target.type === 'page' && target.webSocketDebuggerUrl);
+ const results = await Promise.all(
+ pages.map((page) =>
+ evaluate(page.webSocketDebuggerUrl!, expression).then(
+ (value) => value === true,
+ () => false,
+ ),
+ ),
+ );
+ return results.includes(true);
+ } catch {
+ return false;
+ }
+};
+
+/**
+ * True once a page has rendered its UI, the first point an agent can screenshot
+ * or drive it. A reachable CDP port does not prove that: the window may still be
+ * on its loading screen, or Electron may be about to quit on the single-instance
+ * lock.
+ */
+export const probeDesktopWindow = (
+ cdpPort: number,
+ fetchImplementation?: typeof fetch,
+ evaluate?: typeof evaluateCdpTarget,
+) => probeCdpPages(cdpPort, RENDERED_EXPRESSION, fetchImplementation, evaluate);
+
+/**
+ * Asks the running renderer whether a user is signed in. The on-disk refresh
+ * token is not the only session the app can hold, so this sees what
+ * `readTokenState` cannot.
+ */
+export const probeDesktopSignedIn = (
+ cdpPort: number,
+ fetchImplementation?: typeof fetch,
+ evaluate?: typeof evaluateCdpTarget,
+) => probeCdpPages(cdpPort, SIGNED_IN_EXPRESSION, fetchImplementation, evaluate);
+
+export interface WaitForDesktopWindowOptions {
+ /** Throws when the Electron process tree has already exited. */
+ assertRunning?: () => void;
+ cdpPort: number;
+ /** Clock for the deadline; defaults to `Date.now`. */
+ now?: () => number;
+ probe?: (cdpPort: number) => Promise<boolean>;
+ signal?: AbortSignal;
+ timeoutMs: number;
+ wait?: (durationMs: number) => Promise<void>;
+}
+
+/** Resolves `true` once the window renders, `false` when `timeoutMs` runs out. */
+export const waitForDesktopWindow = async ({
+ assertRunning,
+ cdpPort,
+ probe = probeDesktopWindow,
+ signal,
+ timeoutMs,
+ now = Date.now,
+ wait = (durationMs) =>
+ new Promise((resolve) => {
+ setTimeout(resolve, durationMs);
+ }),
+}: WaitForDesktopWindowOptions) => {
+ // A deadline, not an attempt count: an unresponsive renderer makes each probe
+ // take seconds, so counting attempts would stretch the wait several times over.
+ const deadline = now() + timeoutMs;
+
+ for (;;) {
+ signal?.throwIfAborted();
+ assertRunning?.();
+ if (await probe(cdpPort)) return true;
+ const remaining = deadline - now();
+ if (remaining <= 0) return false;
+ await wait(Math.min(RENDERER_RETRY_MS, remaining));
+ }
+};
+
+// ─── Login state ─────────────────────────────────────────────────────
+
+/**
+ * The login-bearing subset of a profile, skipping the multi-GB caches. The OAuth
+ * tokens live in `lobehub-settings.json` β†’ `encryptedTokens`, encrypted with an
+ * OS keychain key derived from the app name, which `pre-app-init.ts` keeps
+ * constant so a copy still decrypts.
+ */
+export const LOGIN_ITEMS = [
+ 'lobehub-settings.json',
+ 'Local State',
+ 'Preferences',
+ 'Cookies',
+ 'Cookies-journal',
+ 'Local Storage',
+ 'IndexedDB',
+ 'Session Storage',
+ 'Network Persistent State',
+ 'lobehub-storage',
+];
+
+const SETTINGS_FILE = 'lobehub-settings.json';
+
+/**
+ * Per-install values that must not follow a login into another profile.
+ * `gatewayDeviceId` is the device gateway connection id: two instances sharing
+ * it replace each other's socket on every reconnect.
+ */
+const INSTALL_SCOPED_SETTINGS = ['gatewayDeviceId'];
+
+const exists = async (target: string) => {
+ try {
+ await stat(target);
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+const readSettings = async (profile: string): Promise<Record<string, unknown> | undefined> => {
+ try {
+ const parsed = JSON.parse(await readFile(path.join(profile, SETTINGS_FILE), 'utf8'));
+ return parsed && typeof parsed === 'object' ? parsed : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+export interface TokenState {
+ /** Milliseconds until the ACCESS token expires; negative when already expired. */
+ accessTokenExpiresInMs?: number;
+ /**
+ * The app deletes `encryptedTokens` once a refresh fails non-retryably
+ * (`invalid_grant`), so a present refresh token means it can still re-auth.
+ */
+ hasRefreshToken: boolean;
+}
+
+/**
+ * `expiresAt` is the ACCESS token's lifetime (`RemoteServerConfigCtr.saveTokens`),
+ * routinely in the past on a perfectly refreshable login, so it never decides
+ * whether a profile is signed in.
+ */
+export const readTokenState = async (profile: string, now = Date.now()): Promise<TokenState> => {
+ const tokens = (await readSettings(profile))?.encryptedTokens as
+ { expiresAt?: number; refreshToken?: string } | undefined;
+ const hasRefreshToken = Boolean(tokens?.refreshToken);
+ if (!tokens?.expiresAt) return { hasRefreshToken };
+ // The field has been seen in both seconds and milliseconds.
+ const expiresAt = tokens.expiresAt < 1e11 ? tokens.expiresAt * 1000 : tokens.expiresAt;
+ return { accessTokenExpiresInMs: Math.round(expiresAt - now), hasRefreshToken };
+};
+
+export const profileCanReauth = async (profile: string) =>
+ (await readTokenState(profile)).hasRefreshToken;
+
+/** Copies the login items into `target` (created private), dropping install-scoped settings. */
+export const copyLoginItems = async (source: string, target: string) => {
+ await ensurePrivateDirectory(target);
+ for (const item of LOGIN_ITEMS) {
+ const from = path.join(source, item);
+ if (await exists(from))
+ await cp(from, path.join(target, item), { force: true, recursive: true });
+ }
+
+ const settings = await readSettings(target);
+ if (!settings || !INSTALL_SCOPED_SETTINGS.some((key) => key in settings)) return;
+ for (const key of INSTALL_SCOPED_SETTINGS) delete settings[key];
+ await writeFile(path.join(target, SETTINGS_FILE), JSON.stringify(settings, null, 2));
+};
+
+export type SaveLoginResult = 'missing' | 'saved' | 'saved-cookie-only' | 'signed-out';
+
+/**
+ * Snapshots a stopped instance's login so the next instance starts signed in.
+ * The refresh token rotates on use, so the snapshot is only valid when its
+ * source never boots on that token again: take it from a profile that is about
+ * to be removed. `signedIn` (asked from the live renderer before it stopped)
+ * covers a cookie-only session the token check cannot see.
+ */
+export const saveLoginState = async (
+ source: string,
+ { signedIn = false, snapshotDirectory }: { signedIn?: boolean; snapshotDirectory: string },
+): Promise<SaveLoginResult> => {
+ if (!(await exists(source))) return 'missing';
+ if (!signedIn && !(await profileCanReauth(source))) return 'signed-out';
+
+ const staging = `${snapshotDirectory}.staging.${process.pid}`;
+ await rm(staging, { force: true, recursive: true });
+ // The parent may be a shared directory such as /tmp: create it, never chmod it.
+ // `copyLoginItems` makes the snapshot itself private.
+ await mkdir(path.dirname(snapshotDirectory), { recursive: true });
+ await copyLoginItems(source, staging);
+ await rm(snapshotDirectory, { force: true, recursive: true });
+ await rename(staging, snapshotDirectory);
+ return (await profileCanReauth(snapshotDirectory)) ? 'saved' : 'saved-cookie-only';
+};
+
+export interface LoginSource {
+ directory: string;
+ label: string;
+}
+
+export type SeedLoginResult =
+ | { status: 'existing' }
+ | { status: 'none' }
+ | { canReauth: boolean; source: LoginSource; status: 'seeded' };
+
+/**
+ * Seeds a new profile from the first usable source. An existing profile is left
+ * alone: it carries its own login, which a copy would overwrite. A copied login
+ * is readable only between profiles that share an encryption key: on macOS a
+ * profile given through `LOBE_DESKTOP_USER_DATA_DIR` uses Chromium's mock
+ * keychain (`src/main/pre-app-init.ts`), so it cannot read one from the shared
+ * default profile, which uses the real keychain.
+ */
+export const seedLoginState = async (
+ target: string,
+ sources: LoginSource[],
+): Promise<SeedLoginResult> => {
+ if (await exists(target)) return { status: 'existing' };
+
+ for (const source of sources) {
+ if (!(await exists(source.directory))) continue;
+
+ await copyLoginItems(source.directory, target);
+ return { canReauth: await profileCanReauth(target), source, status: 'seeded' };
+ }
+
+ await ensurePrivateDirectory(target);
+ return { status: 'none' };
+};
+
+/** One line on whether `profile` can sign the next instance in. */
+export const describeLoginState = async (label: string, profile: string, now = Date.now()) => {
+ if (!(await exists(profile))) return `${label}: (absent) β€” ${profile}`;
+
+ const { accessTokenExpiresInMs: remaining, hasRefreshToken } = await readTokenState(profile, now);
+ const access =
+ remaining === undefined
+ ? 'no access-token expiry recorded'
+ : remaining > 0
+ ? `access token fresh for ${Math.floor(remaining / 3_600_000)}h`
+ : `access token stale ${Math.floor(-remaining / 3_600_000)}h (harmless β€” it gets refreshed)`;
+
+ return hasRefreshToken
+ ? `${label}: refresh token PRESENT β€” ${access} β€” ${profile}`
+ : `${label}: refresh token GONE (app cleared it after a failed refresh) β€” ${profile}`;
+};
diff --git a/apps/desktop/scripts/devInstanceCli.mts b/apps/desktop/scripts/devInstanceCli.mts
new file mode 100644
index 00000000000..6a593ef549c
--- /dev/null
+++ b/apps/desktop/scripts/devInstanceCli.mts
@@ -0,0 +1,171 @@
+/**
+ * Shell entry to `devInstance.mts` for `.agents/acceptance/scripts/electron-dev.sh`.
+ *
+ * node scripts/devInstanceCli.mts env --cdp-port 9223 --renderer-port 5174 [--user-data DIR] [--label TEXT]
+ * node scripts/devInstanceCli.mts checkout-label DIR
+ * node scripts/devInstanceCli.mts wait-renderer --cdp-port 9223 --timeout-s 60
+ * node scripts/devInstanceCli.mts signed-in --cdp-port 9223
+ * node scripts/devInstanceCli.mts seed-login --user-data DIR --snapshot DIR
+ * node scripts/devInstanceCli.mts save-login --user-data DIR --snapshot DIR [--signed-in 1]
+ * node scripts/devInstanceCli.mts login-status --snapshot DIR
+ *
+ * `env` prints one `KEY=value` per line; messages carry the `[electron-dev]` prefix.
+ */
+import { stat } from 'node:fs/promises';
+import { parseArgs } from 'node:util';
+
+import {
+ createDesktopDevInstance,
+ describeLoginState,
+ getDesktopDevEnvironment,
+ probeDesktopSignedIn,
+ readCheckoutLabel,
+ saveLoginState,
+ seedLoginState,
+ waitForDesktopWindow,
+} from './devInstance.mts';
+
+const log = (message: string) => console.log(`[electron-dev] ${message}`);
+
+const { positionals, values } = parseArgs({
+ allowPositionals: true,
+ options: {
+ 'cdp-port': { type: 'string' },
+ 'label': { type: 'string' },
+ 'renderer-port': { type: 'string' },
+ 'signed-in': { type: 'string' },
+ 'snapshot': { type: 'string' },
+ 'timeout-s': { type: 'string' },
+ 'user-data': { type: 'string' },
+ },
+});
+
+const required = (name: keyof typeof values) => {
+ const value = values[name];
+ if (typeof value !== 'string' || value.length === 0) {
+ console.error(`[electron-dev] --${name} is required`);
+ process.exit(64);
+ }
+ return value;
+};
+
+const port = (name: 'cdp-port' | 'renderer-port') => {
+ const value = Number(required(name));
+ if (!Number.isInteger(value) || value <= 0) {
+ console.error(`[electron-dev] --${name} must be a positive integer`);
+ process.exit(64);
+ }
+ return value;
+};
+
+const [command, argument] = positionals;
+
+switch (command) {
+ case 'env': {
+ const environment = getDesktopDevEnvironment(
+ createDesktopDevInstance({
+ cdpPort: port('cdp-port'),
+ label: values.label,
+ // Pool instances sign in to test accounts and copy logins between profiles.
+ mockKeychain: true,
+ rendererPort: port('renderer-port'),
+ userDataDirectory: values['user-data'],
+ }),
+ );
+ for (const [key, value] of Object.entries(environment)) console.log(`${key}=${value}`);
+ break;
+ }
+
+ case 'checkout-label': {
+ console.log(await readCheckoutLabel(argument ?? process.cwd()));
+ break;
+ }
+
+ case 'wait-renderer': {
+ const timeoutS = Number(values['timeout-s'] ?? 60);
+ log(`Waiting for the renderer to render (up to ${timeoutS}s)...`);
+ const rendered = await waitForDesktopWindow({
+ cdpPort: port('cdp-port'),
+ timeoutMs: timeoutS * 1000,
+ });
+ if (rendered) {
+ log('Renderer ready.');
+ } else {
+ log(`WARNING: Renderer did not render within ${timeoutS}s β€” proceeding anyway.`);
+ process.exitCode = 1;
+ }
+ break;
+ }
+
+ case 'signed-in': {
+ console.log((await probeDesktopSignedIn(port('cdp-port'))) ? '1' : '0');
+ break;
+ }
+
+ case 'seed-login': {
+ const target = required('user-data');
+ const result = await seedLoginState(target, [
+ { directory: required('snapshot'), label: 'saved login state' },
+ ]);
+ if (result.status === 'none') {
+ log(
+ `WARNING: no login state at ${values.snapshot} β€” instance will start signed out; sign in once and 'stop' will capture it.`,
+ );
+ } else if (result.status === 'seeded') {
+ log(`Seeding userData from ${result.source.label} β†’ ${target}`);
+ if (!result.canReauth)
+ log(
+ " note: no refresh token on disk β€” a cookie session may still carry it; otherwise sign in once and 'stop' will capture it.",
+ );
+ }
+ break;
+ }
+
+ case 'save-login': {
+ const source = required('user-data');
+ const snapshotDirectory = required('snapshot');
+ const result = await saveLoginState(source, {
+ signedIn: values['signed-in'] === '1',
+ snapshotDirectory,
+ });
+ if (result === 'signed-out')
+ log(
+ `Not saving login state: ${source} is signed out (the app cleared its refresh token) β€” kept the previous snapshot.`,
+ );
+ else if (result === 'saved')
+ log(`Saved login state β†’ ${snapshotDirectory} (refresh token captured)`);
+ else if (result === 'saved-cookie-only')
+ log(
+ `Saved login state β†’ ${snapshotDirectory} (cookie session only β€” no refresh token on disk)`,
+ );
+ break;
+ }
+
+ case 'login-status': {
+ const snapshot = required('snapshot');
+ console.log(` ${await describeLoginState('saved snapshot', snapshot)}`);
+ const present = await stat(snapshot).then(
+ () => true,
+ () => false,
+ );
+ if (!present) {
+ log(
+ "Nothing to seed from: sign in once inside the app, then 'save-login <id>' (or just 'stop <id>').",
+ );
+ process.exitCode = 2;
+ break;
+ }
+ log("Note: 'expiresAt' in the profile is the ACCESS token's lifetime, not the");
+ log("refresh token's β€” a stale one is normal and gets refreshed on boot. Only a");
+ log("missing refresh token means signed out. 'stop'/'save-login' also probe the");
+ log('running renderer, so a cookie-only session is captured too.');
+ break;
+ }
+
+ default: {
+ console.error(
+ 'Usage: devInstanceCli.mts {env|checkout-label|wait-renderer|signed-in|seed-login|save-login|login-status}',
+ );
+ process.exit(64);
+ }
+}
diff --git a/apps/desktop/src/main/controllers/AuthCtr.ts b/apps/desktop/src/main/controllers/AuthCtr.ts
index f2a3da958e9..ee01da2c64f 100644
--- a/apps/desktop/src/main/controllers/AuthCtr.ts
+++ b/apps/desktop/src/main/controllers/AuthCtr.ts
@@ -9,7 +9,9 @@ import type {
} from '@lobechat/electron-client-ipc';
import { BrowserWindow, shell } from 'electron';
+import { isDev } from '@/const/env';
import GatewayConnectionService from '@/services/gatewayConnectionSrv';
+import { openAuthorizationUrl } from '@/utils/authorizationUrl';
import { appendVercelCookie } from '@/utils/http-headers';
import { createLogger } from '@/utils/logger';
import { netFetch } from '@/utils/net-fetch';
@@ -120,9 +122,12 @@ export default class AuthCtr extends ControllerModule {
logger.info(`Constructed authorization URL: ${authUrl.toString()}`);
- // Open authorization URL in the default browser
- await shell.openExternal(authUrl.toString());
- logger.debug('Opening authorization URL in default browser');
+ // Open the authorization URL in the default browser, or hand it to a dev launcher
+ const destination = await openAuthorizationUrl(authUrl.toString(), {
+ isDev,
+ openExternal: (url) => shell.openExternal(url),
+ });
+ logger.debug(`Authorization URL sent to the ${destination}`);
this.broadcastAuthorizationProgress({
elapsed: 0,
diff --git a/apps/desktop/src/main/core/browser/Browser.ts b/apps/desktop/src/main/core/browser/Browser.ts
index ee37a4c0a81..08011f4f769 100644
--- a/apps/desktop/src/main/core/browser/Browser.ts
+++ b/apps/desktop/src/main/core/browser/Browser.ts
@@ -17,6 +17,7 @@ import { LOADING_SCREEN_PAINTED_CHANNEL } from '~common/loadingScreen';
import { SYSTEM_LANGUAGE_ARG_PREFIX } from '~common/systemLanguage';
import type { App } from '../App';
+import { attachDevInstanceLabel, getDevInstanceLabel } from './devInstanceLabel';
import { WindowStateManager } from './WindowStateManager';
import { WindowThemeManager } from './WindowThemeManager';
@@ -332,6 +333,9 @@ export default class Browser {
this.setupTopLevelNavigationListener(browserWindow);
this.setupWillPreventUnloadListener(browserWindow);
this.setupContextMenu(browserWindow);
+
+ const devInstanceLabel = getDevInstanceLabel();
+ if (devInstanceLabel) attachDevInstanceLabel(browserWindow, devInstanceLabel);
}
private setupTopLevelNavigationListener(browserWindow: BrowserWindow): void {
diff --git a/apps/desktop/src/main/core/browser/__tests__/devInstanceLabel.test.ts b/apps/desktop/src/main/core/browser/__tests__/devInstanceLabel.test.ts
new file mode 100644
index 00000000000..6a115faf141
--- /dev/null
+++ b/apps/desktop/src/main/core/browser/__tests__/devInstanceLabel.test.ts
@@ -0,0 +1,64 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ attachDevInstanceLabel,
+ formatDevInstanceTitle,
+ getDevInstanceLabel,
+} from '../devInstanceLabel';
+
+const { isDev } = vi.hoisted(() => ({ isDev: vi.fn(() => true) }));
+
+vi.mock('@/utils/platform', () => ({ dev: isDev }));
+
+afterEach(() => {
+ isDev.mockReturnValue(true);
+});
+
+describe('getDevInstanceLabel', () => {
+ it('returns the launcher label in dev builds', () => {
+ expect(getDevInstanceLabel({ LOBE_DESKTOP_INSTANCE_LABEL: ' feature-x ' })).toBe('feature-x');
+ expect(getDevInstanceLabel({ LOBE_DESKTOP_INSTANCE_LABEL: ' ' })).toBeUndefined();
+ expect(getDevInstanceLabel({})).toBeUndefined();
+ });
+
+ it('never labels a packaged build', () => {
+ isDev.mockReturnValue(false);
+
+ expect(getDevInstanceLabel({ LOBE_DESKTOP_INSTANCE_LABEL: 'feature-x' })).toBeUndefined();
+ });
+});
+
+describe('attachDevInstanceLabel', () => {
+ const createWindow = () => {
+ const listeners = new Map<string, (...args: any[]) => void>();
+ const browserWindow = {
+ setTitle: vi.fn(),
+ webContents: {
+ on: vi.fn((event: string, listener: (...args: any[]) => void) => {
+ listeners.set(event, listener);
+ }),
+ },
+ };
+ return { browserWindow, listeners };
+ };
+
+ it('suffixes the native title instead of letting the page replace it', () => {
+ const { browserWindow, listeners } = createWindow();
+ attachDevInstanceLabel(browserWindow as any, 'feature-x');
+
+ const event = { preventDefault: vi.fn() };
+ listeners.get('page-title-updated')!(event, 'LobeHub');
+
+ expect(event.preventDefault).toHaveBeenCalled();
+ expect(browserWindow.setTitle).toHaveBeenCalledWith('LobeHub β€” feature-x');
+ expect(formatDevInstanceTitle('', 'feature-x')).toBe('feature-x');
+ });
+
+ /** Regression: an in-page badge covered the title bar of every window. */
+ it('draws nothing over the page', () => {
+ const { browserWindow, listeners } = createWindow();
+ attachDevInstanceLabel(browserWindow as any, 'feature-x');
+
+ expect([...listeners.keys()]).toEqual(['page-title-updated']);
+ });
+});
diff --git a/apps/desktop/src/main/core/browser/devInstanceLabel.ts b/apps/desktop/src/main/core/browser/devInstanceLabel.ts
new file mode 100644
index 00000000000..11eb5475f84
--- /dev/null
+++ b/apps/desktop/src/main/core/browser/devInstanceLabel.ts
@@ -0,0 +1,29 @@
+import type { BrowserWindow } from 'electron';
+
+import * as electronIs from '@/utils/platform';
+
+/**
+ * Several dev instances (one per checkout) run side by side and all look the
+ * same, so a launcher names each one through `LOBE_DESKTOP_INSTANCE_LABEL`
+ * (`scripts/devInstance.mts`). Packaged builds never show it.
+ */
+export const getDevInstanceLabel = (environment: NodeJS.ProcessEnv = process.env) => {
+ if (!electronIs.dev()) return undefined;
+ const label = environment.LOBE_DESKTOP_INSTANCE_LABEL?.trim();
+ return label || undefined;
+};
+
+export const formatDevInstanceTitle = (title: string, label: string) =>
+ title ? `${title} β€” ${label}` : label;
+
+/**
+ * Suffixes the native window title with the instance label. The frameless title
+ * bar hides it, but the window menu, Mission Control and CDP target lists show
+ * it, without drawing anything over the page.
+ */
+export const attachDevInstanceLabel = (browserWindow: BrowserWindow, label: string) => {
+ browserWindow.webContents.on('page-title-updated', (event, title) => {
+ event.preventDefault();
+ browserWindow.setTitle(formatDevInstanceTitle(title, label));
+ });
+};
diff --git a/apps/desktop/src/main/pre-app-init.test.ts b/apps/desktop/src/main/pre-app-init.test.ts
new file mode 100644
index 00000000000..8ddd1b77016
--- /dev/null
+++ b/apps/desktop/src/main/pre-app-init.test.ts
@@ -0,0 +1,71 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const { app, isDev } = vi.hoisted(() => ({
+ app: {
+ commandLine: { appendSwitch: vi.fn() },
+ getPath: vi.fn(() => '/app-data'),
+ setName: vi.fn(),
+ setPath: vi.fn(),
+ },
+ isDev: vi.fn(() => true),
+}));
+
+vi.mock('electron', () => ({ app }));
+vi.mock('@/utils/platform', () => ({ dev: isDev }));
+
+const platform = Object.getOwnPropertyDescriptor(process, 'platform')!;
+
+const load = async ({
+ mockKeychain = true,
+ platform: name,
+ userData,
+}: {
+ mockKeychain?: boolean;
+ platform: string;
+ userData?: string;
+}) => {
+ Object.defineProperty(process, 'platform', { value: name });
+ vi.stubEnv('LOBE_DESKTOP_USER_DATA_DIR', userData ?? '');
+ vi.stubEnv('LOBE_DESKTOP_MOCK_KEYCHAIN', mockKeychain ? '1' : '');
+ await import('./pre-app-init');
+};
+
+describe('pre-app-init', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.resetModules();
+ });
+
+ afterEach(() => {
+ Object.defineProperty(process, 'platform', platform);
+ vi.unstubAllEnvs();
+ });
+
+ it('keeps a marked launcher-managed macOS instance off the system keychain', async () => {
+ await load({ platform: 'darwin', userData: '/checkout/.cache/desktop-user-data' });
+
+ expect(app.setPath).toHaveBeenCalledWith('userData', '/checkout/.cache/desktop-user-data');
+ expect(app.commandLine.appendSwitch).toHaveBeenCalledWith('use-mock-keychain');
+ });
+
+ /** Regression: every launcher profile used the public mock key, including production logins. */
+ it('keeps the keychain for a profile the launcher did not mark', async () => {
+ await load({
+ mockKeychain: false,
+ platform: 'darwin',
+ userData: '/checkout/.cache/desktop-user-data-online',
+ });
+
+ expect(app.commandLine.appendSwitch).not.toHaveBeenCalled();
+ });
+
+ it('keeps the keychain for the shared dev profile and other platforms', async () => {
+ await load({ platform: 'darwin' });
+ expect(app.setPath).toHaveBeenCalledWith('userData', '/app-data/lobehub-desktop-dev');
+
+ vi.resetModules();
+ await load({ platform: 'linux', userData: '/checkout/.cache/desktop-user-data' });
+
+ expect(app.commandLine.appendSwitch).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/pre-app-init.ts b/apps/desktop/src/main/pre-app-init.ts
index c4530a2665d..352562de6bf 100644
--- a/apps/desktop/src/main/pre-app-init.ts
+++ b/apps/desktop/src/main/pre-app-init.ts
@@ -23,6 +23,18 @@ if (electronIs.dev()) {
'userData',
userDataOverride || path.join(app.getPath('appData'), 'lobehub-desktop-dev'),
);
+ // A launcher-managed instance with a test-account profile (`scripts/devInstance.mts`,
+ // `mockKeychain`) encrypts tokens and cookies with Chromium's fixed mock key
+ // instead of the macOS keychain. The keychain grants access per binary, and the
+ // dev Electron is ad-hoc signed and installed once per checkout, so every
+ // checkout would ask for the login password again. The fixed key is public, so
+ // a profile holding a production login keeps the keychain.
+ if (
+ userDataOverride &&
+ process.env.LOBE_DESKTOP_MOCK_KEYCHAIN === '1' &&
+ process.platform === 'darwin'
+ )
+ app.commandLine.appendSwitch('use-mock-keychain');
}
if (globalThis.__SHELL__) Object.freeze(globalThis.__SHELL__);
diff --git a/apps/desktop/src/main/utils/__tests__/authorizationUrl.test.ts b/apps/desktop/src/main/utils/__tests__/authorizationUrl.test.ts
new file mode 100644
index 00000000000..7f427104fe9
--- /dev/null
+++ b/apps/desktop/src/main/utils/__tests__/authorizationUrl.test.ts
@@ -0,0 +1,63 @@
+import { mkdtemp, readdir, readFile, rm, stat } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AUTH_URL_FILE_ENV, openAuthorizationUrl } from '../authorizationUrl';
+
+let root: string;
+
+beforeEach(async () => {
+ root = await mkdtemp(path.join(os.tmpdir(), 'auth-url-'));
+});
+
+afterEach(async () => {
+ await rm(root, { force: true, recursive: true });
+});
+
+describe('openAuthorizationUrl', () => {
+ it('writes the URL to the launcher file in dev instead of opening a browser', async () => {
+ const file = path.join(root, 'auth-url');
+ const openExternal = vi.fn(async () => {});
+
+ await expect(
+ openAuthorizationUrl('https://x/oidc/auth?state=s', {
+ env: { [AUTH_URL_FILE_ENV]: file },
+ isDev: true,
+ openExternal,
+ }),
+ ).resolves.toBe('file');
+
+ expect(openExternal).not.toHaveBeenCalled();
+ expect(await readFile(file, 'utf8')).toBe('https://x/oidc/auth?state=s');
+ expect((await stat(file)).mode & 0o777).toBe(0o600);
+ /** Renamed into place, so a polling launcher never sees a partial URL. */
+ expect(await readdir(root)).toEqual(['auth-url']);
+ });
+
+ it('opens the browser when no launcher asked for the URL', async () => {
+ const openExternal = vi.fn(async () => {});
+
+ await expect(
+ openAuthorizationUrl('https://x', { env: {}, isDev: true, openExternal }),
+ ).resolves.toBe('browser');
+ expect(openExternal).toHaveBeenCalledWith('https://x');
+ });
+
+ it('ignores the variable in a packaged build', async () => {
+ const openExternal = vi.fn(async () => {});
+ const write = vi.fn();
+
+ await expect(
+ openAuthorizationUrl('https://x', {
+ env: { [AUTH_URL_FILE_ENV]: path.join(root, 'auth-url') },
+ isDev: false,
+ openExternal,
+ write,
+ }),
+ ).resolves.toBe('browser');
+ expect(write).not.toHaveBeenCalled();
+ expect(openExternal).toHaveBeenCalledWith('https://x');
+ });
+});
diff --git a/apps/desktop/src/main/utils/authorizationUrl.ts b/apps/desktop/src/main/utils/authorizationUrl.ts
new file mode 100644
index 00000000000..c545dd90968
--- /dev/null
+++ b/apps/desktop/src/main/utils/authorizationUrl.ts
@@ -0,0 +1,46 @@
+import { rename, writeFile } from 'node:fs/promises';
+
+/**
+ * Dev launchers set this to a file path to receive the OIDC authorization URL instead of
+ * having it opened in the system browser, so a script can approve the request with a test
+ * account and several windows never fight over one browser session.
+ */
+export const AUTH_URL_FILE_ENV = 'LOBE_DESKTOP_AUTH_URL_FILE';
+
+export interface OpenAuthorizationUrlOptions {
+ env?: NodeJS.ProcessEnv;
+ isDev: boolean;
+ move?: typeof rename;
+ openExternal: (url: string) => Promise<void>;
+ write?: typeof writeFile;
+}
+
+/**
+ * Hands the authorization URL to the dev launcher when it asked for it, otherwise opens it
+ * in the default browser. Packaged builds always open the browser.
+ *
+ * @returns where the URL went, for logging
+ */
+export const openAuthorizationUrl = async (
+ url: string,
+ {
+ env = process.env,
+ isDev,
+ move = rename,
+ openExternal,
+ write = writeFile,
+ }: OpenAuthorizationUrlOptions,
+): Promise<'browser' | 'file'> => {
+ const file = env[AUTH_URL_FILE_ENV];
+ if (isDev && file) {
+ // The URL carries the PKCE state; keep it readable by the owner only. Rename into
+ // place so a launcher polling the file never reads a partial URL.
+ const staging = `${file}.${process.pid}.tmp`;
+ await write(staging, url, { mode: 0o600 });
+ await move(staging, file);
+ return 'file';
+ }
+
+ await openExternal(url);
+ return 'browser';
+};