Skip to content

๐Ÿคฏ LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

๐Ÿ› fix(chat-input): resolve the worktree switcher against the main worktree (#16967)

Arvin Xu19cf14444ae3
diff --git a/.agents/skills/agent-testing/references/auth.md b/.agents/skills/agent-testing/references/auth.md
index 26b0868f812..0f68308a263 100644
--- a/.agents/skills/agent-testing/references/auth.md
+++ b/.agents/skills/agent-testing/references/auth.md
@@ -35,7 +35,7 @@ not `127.0.0.1`.
| -------- | ---------------------------------------- | ----------------------------------------------------------------- | ---------------------------------------------- |
| CLI | Seeded API key or OIDC Device Code Flow | `.records/env/agent-testing-cli.env` + `$HOME/.lobehub-dev` | No for seed path; yes for device-code fallback |
| Web | Seeded better-auth login or cookie copy | `~/.lobehub-agent-testing/web-state.json` + agent-browser session | No for seed path; copy cookie only as fallback |
-| Electron | App's own login state | Electron user-data dir | Log in once manually in the app |
+| Electron | App's own login state | `~/.lobehub/agent-testing/electron-login` (snapshot on `stop`) | No โ€” the agent drives the sign-in itself |
| Bot | Native apps (Discord/WeChat/โ€ฆ) logged in | Each app's own session | Once per app |
## CLI โ€” Seeded API key
@@ -147,10 +147,19 @@ agent-browser --session lobehub-dev snapshot -i | head -20
## Electron
-The desktop app keeps its own persistent login state in its user-data
-directory โ€” log in once manually inside the app and it survives restarts of
-`electron-dev.sh`. No injection needed. The standard check (do NOT hand-roll a
-store eval) once Electron is up with CDP:
+The desktop app keeps its login in its user-data directory. Pool instances get a
+throwaway userData, so `electron-dev.sh` persists the login **for you**: `stop`
+snapshots it into `~/.lobehub/agent-testing/electron-login` before wiping the dir,
+and `start` seeds every new instance from that snapshot. Sign in once, not once
+per run.
+
+```bash
+EDEV=./.agents/skills/agent-testing/scripts/electron-dev.sh
+$EDEV login-status # which source seeds the next instance, and its expiry
+$EDEV save-login <id> # snapshot a live instance without stopping it
+```
+
+The standard check (do NOT hand-roll a store eval) once Electron is up with CDP:
```bash
./.agents/skills/agent-testing/scripts/app-probe.sh auth
@@ -160,6 +169,42 @@ store eval) once Electron is up with CDP:
`setup-auth.sh status` runs this probe automatically when CDP 9222 is
reachable.
+### When the instance comes up signed out
+
+Sign it in **yourself** โ€” never hand this step to the user. The desktop flow is
+OAuth+PKCE against `/oidc/auth`, and the redirect target is a **server page the app
+then polls** (`/oidc/callback/desktop`), not a `lobehub://` deep link โ€” so no other
+app can steal the callback, and no click is needed when the default browser already
+has a LobeHub session:
+
+```bash
+agent-browser --session s<port> --cdp <port> eval --stdin << 'EOF'
+(async () => {
+ const m = await import('/src/services/electron/remoteServer.ts');
+ return JSON.stringify(await (m.remoteServerService || m.default).requestAuthorization({ storageMode: 'cloud' }));
+})()
+EOF
+# poll until user().user.id appears, then capture it:
+$EDEV save-login <id>
+```
+
+Three traps behind a signed-out instance:
+
+- **The refresh token rotates on every boot.** Only the instance that booted last
+ holds a usable one, so a `stop` is what keeps the snapshot alive. If an instance is
+ _killed_ instead (crash, command timeout) its rotated token dies with it โ€”
+ `save-login <id>` before anything risky.
+- **`encryptedTokens.expiresAt` is the ACCESS token's expiry, not the refresh
+ token's.** It is `Date.now() + data.expires_in * 1000` in
+ `RemoteServerConfigCtr.saveTokens`, so it goes stale on a perfectly refreshable
+ login and must never gate whether a profile is kept. The signal that _does_ mean
+ signed out is a **missing `refreshToken`**: the app calls `clearTokens()` (deleting
+ the whole `encryptedTokens` key) when a refresh fails non-retryably
+ (`invalid_grant` \&co), and preserves it on transient failures.
+- **Even a missing token does not always mean signed out.** A better-auth cookie can
+ outlive it. `stop` / `save-login` probe the _running renderer_ for a user id, so a
+ live cookie-only session is captured too; the on-disk token alone would miss it.
+
## Scope
These recipes only cover **local dev** authentication. They do not:
diff --git a/.agents/skills/agent-testing/references/common-mistakes.md b/.agents/skills/agent-testing/references/common-mistakes.md
index 1724044b40b..981baa30c81 100644
--- a/.agents/skills/agent-testing/references/common-mistakes.md
+++ b/.agents/skills/agent-testing/references/common-mistakes.md
@@ -211,6 +211,39 @@ skill's job to solve and then iterate back into these logs.
---
+## Case 8b โ€” Handing the user the sign-in click when the app under test is signed out
+
+**Wrong approach**: an isolated Electron instance came up signed out (its userData had been wiped by an
+earlier `electron-dev.sh stop`, and the golden profile's refresh token was rejected โ†’ `invalid_grant`), so
+the run stopped and offered the user a choice: "I click Sign in and you authorize in the browser" vs
+"skip the screenshot".
+
+**Why it's wrong**: this is Case 8 wearing a different hat. `auth.md` says "Electron: log in once manually
+in the app" โ€” that line is addressed to the **agent**, not the user. Auth is environment mechanics, and the
+standing rule is that the skill owns those end to end. The user's words: " ไฝ ไปฅๅŽ้ƒฝ่‡ชๅทฑ็‚น sign in ๆŽˆๆƒ๏ผŒไธๅบ”
+่ฏฅ่ฎฉๆˆ‘ๆ“ไฝœ ".
+
+**What it breaks**: burns a round on a question the user doesn't want, and stalls a UI-touching change
+(Case 9 / Case 10) one click short of its screenshot.
+
+**Correct approach**: drive the sign-in yourself โ€” click the app's own "Sign in" entry, follow the OAuth
+flow in the browser it opens, and get back into the app. Only escalate when a step genuinely needs
+something you cannot supply (a 2FA push on their phone), and then name the exact blocking step instead of
+offering to drop the evidence.
+
+**What this run changed**: `electron-dev.sh stop <id>` used to delete the instance's userData and its login
+with it, so every run re-entered the sign-in flow. It now snapshots the login into
+`~/.lobehub/agent-testing/electron-login` first, and `start` seeds new instances from that snapshot
+(`login-status` shows the source + expiry; `save-login <id>` captures a live instance before anything
+risky, since a _killed_ instance loses its rotated refresh token).
+
+**Corollary**: never assume a profile is signed in because it exists โ€” probe for a real signed-in state
+(`user().user?.id`, or a cheap authed mutation) before building a fixture on top of it. A rendered sidebar
+is not proof: the signed-out onboarding screen has text too, so `innerText.length > 50` passes while
+`createAgent` returns `UNAUTHORIZED`.
+
+---
+
## Case 9 โ€” Self-judging a screenshot as "too costly" and asking the user to picture the result
**Wrong approach**: after a small user-facing UI change (a padding tweak), skipping
diff --git a/.agents/skills/agent-testing/references/probe-mock-patterns.md b/.agents/skills/agent-testing/references/probe-mock-patterns.md
index 489442ab381..f2aa2506268 100644
--- a/.agents/skills/agent-testing/references/probe-mock-patterns.md
+++ b/.agents/skills/agent-testing/references/probe-mock-patterns.md
@@ -485,6 +485,78 @@
server's `S3_ACCESS_KEY_ID/S3_SECRET_ACCESS_KEY=S3RVER`, `S3_ENABLE_PATH_STYLE=1`,
`S3_PUBLIC_DOMAIN=http://127.0.0.1:29000/<bucket>`.
+### E8. โœ… WORKS โ€” a git-worktree checkout needs its OWN `pnpm install`, not a symlinked `node_modules`
+
+- **Situation**: verifying a UI change from a `git worktree` (e.g. `.claude/worktrees/<name>`), which
+ starts with no `node_modules`.
+- **Doesn't work**: symlinking the main checkout's `node_modules` (root and/or `apps/desktop`) into the
+ worktree. The workspace links inside it point `@lobechat/*` at the MAIN checkout's `packages/`, which
+ sits on a different branch โ€” the Electron main build then dies with
+ `[MISSING_EXPORT] "X" is not exported by "../../packages/<pkg>/src/..."`. Renderer source resolves from
+ the worktree while packages resolve from the main repo, so the two disagree.
+- **Works**: run `pnpm install` at the worktree root AND `cd apps/desktop && pnpm install` (standalone,
+ not in the workspace). \~5 min total, mostly hardlinked from the store.
+- **Also**: a Vite dev server left over from an earlier failed `electron-dev.sh start <id>` is REUSED by
+ the retry (`CDP already reachable โ€ฆ Skipping start`) and can keep serving pre-edit module text. If the
+ DOM shows markup that contradicts the source, curl the dev server for the file and grep for a token you
+ just added (`curl -s 127.0.0.1:<vitePort>/src/path/File.tsx | grep -c myNewSymbol`) before blaming the
+ code. `electron-dev.sh stop <id>` then start again to get a clean server.
+
+### E9. Electron dev's FIRST cold boot sits on the splash with an empty `#root` for 1โ€“3 minutes
+
+- **Situation**: after `electron-dev.sh start <id>`, `app-probe.sh auth` returns `isSignedIn:false`,
+ `#root` has providers but `innerText.length === 0`, and the screenshot is just the LobeHub splash. The
+ main log shows `Proactive token refresh failed` / `invalid_grant`.
+- **Doesn't work**: concluding the copied login state expired. That refresh error is a red herring โ€” the
+ app recovers, and `RENDERER_WAIT_S` (60s) can expire while Vite is still on
+ `[optimizer] bundling dependencies`, which ends in `optimized dependencies changed. reloading`.
+- **Works**: poll until the DOM actually has content instead of sleeping a fixed amount:
+ ```bash
+ until [ "$(agent-browser --session s \
+ '(function(){return String(document.getElementById("root").innerText.trim().length>50)})()' < port > --cdp < port > eval \
+ | tr -d '"')" = "true" ]; do sleep 5; done
+ ```
+ Also note `zsh does NOT word-split unquoted vars` โ€” `S="--session x --cdp 9226"; agent-browser $S eval`
+ fails with `Unknown command`. Inline the flags or use an array.
+
+### E10. โœ… WORKS โ€” stop the main process from yanking the renderer back to its last tab
+
+- **Situation**: driving the SPA to a specific route for a screenshot. `history.pushState` + `popstate`
+ lands correctly, then \~15โ€“20s later `location.pathname` snaps back to whatever tab the main process
+ has stored (e.g. `/devtools/claude-code`). A hard `location.href` nav is reverted the same way.
+- **Cause**: the main process broadcasts `navigate`, and `src/features/DesktopNavigationBridge` obeys it.
+- **Works**: HMR-neutralize the bridge for the run, then revert:
+ ```tsx
+ // src/features/DesktopNavigationBridge/index.tsx โ€” [AGENT-TEST] REMOVE
+ useWatchBroadcast('navigate', () => {
+ void handleNavigate;
+ });
+ ```
+ `git checkout -- src/features/DesktopNavigationBridge/index.tsx` afterwards; `grep -rn AGENT-TEST src/`
+ must come back empty.
+
+### E11. โœ… WORKS โ€” drive the working-directory / git-status ControlBar without the native dir picker
+
+- The picker opens a native dialog, but the same write path is reachable from the store. With no active
+ topic, `commit()` persists to `agencyConfig.workingDirByDevice[deviceId]`:
+ ```js
+ const a = window.__LOBE_STORES.agent(),
+ d = window.__LOBE_STORES.device();
+ const did = window.__LOBE_STORES.electron().gatewayDeviceInfo.deviceId;
+ const entry = { path: '/abs/repo', repoType: 'git' };
+ await a.updateAgentConfigById(agentId, {
+ agencyConfig: { workingDirByDevice: { [did]: entry } },
+ });
+ await d.updateDeviceCwd(did, entry, { setDefault: false }); // so the entry exists โ†’ sourcePath resolves
+ ```
+ Create a throwaway agent with `agent().createAgent({ title })` and delete it afterwards with
+ `session().removeSession(agentId)` (there is no `deleteAgent` on the agent store) plus
+ `device().removeDeviceWorkingDir(did, path)` โ€” otherwise the fixture cwd lingers in the real account.
+- **Identify icons precisely**: lucide renders `svg.lucide.lucide-git-fork`. Several git icons live in the
+ same bar (the dir picker's `DirIcon` is `git-branch`, the review toggle is `git-compare`), so scope the
+ assertion to the trigger: `document.querySelector('[role=button][aria-label="Worktrees"]') svg`, and
+ still open the PNG to confirm (Case 1).
+
### E6. code-inspector-plugin breaks Turbopack compile of Next-served authed pages
- **Situation**: the first AUTHENTICATED render of a Next-served (non-SPA) page whose client
diff --git a/.agents/skills/agent-testing/scripts/electron-dev.sh b/.agents/skills/agent-testing/scripts/electron-dev.sh
index 11e61aa00d0..17da0d29923 100755
--- a/.agents/skills/agent-testing/scripts/electron-dev.sh
+++ b/.agents/skills/agent-testing/scripts/electron-dev.sh
@@ -18,20 +18,35 @@
# 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)
+# userData = $POOL_DIR/ud-<id> (login state seeded from the saved snapshot)
# 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> ...
#
+# Login persistence (so you sign in ONCE, not once per run):
+# `stop` snapshots the instance's login state into $LOGIN_STATE_DIR before it
+# 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).
+# ./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
+# rotated token dies with it โ€” run `save-login` before anything risky.
+#
# Environment variables:
# 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
+# 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)
# RENDERER_WAIT_S โ€” max seconds to wait for the SPA (default: 60)
#
@@ -52,6 +67,8 @@ 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}"
# 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
@@ -188,27 +205,158 @@ wait_for_renderer() {
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.
+# โ”€โ”€ 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
+}
+
+# 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
+}
+
+# Persist an instance's login into the snapshot so the NEXT run starts signed in.
+# The refresh token rotates on every boot, so the instance's copy is the only
+# valid one by the time it stops โ€” capture it before the userData is wiped.
+# `authed_hint=1` (from probe_renderer_authed, taken while the app was alive)
+# 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
+}
+
+# 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_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."
+
+ # 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 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
+
+ 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"
}
# โ”€โ”€ Commands โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
@@ -218,6 +366,13 @@ do_stop() {
[ "$POOL_MODE" = "1" ] && label="instance $INSTANCE (cdp $CDP_PORT)"
echo "[electron-dev] Stopping Electron dev ($label)..."
+ # Ask the still-running app whether it is signed in โ€” after the kill there is
+ # nothing left to ask, and the on-disk token alone can't see a cookie session.
+ local authed=0
+ if [ "$POOL_MODE" = "1" ] && [ "${SKIP_LOGIN_SAVE:-0}" != "1" ]; then
+ authed=$(probe_renderer_authed)
+ fi
+
local seed_pids
seed_pids=$(find_instance_pids)
@@ -280,8 +435,10 @@ do_stop() {
agent-browser --session "edev$CDP_PORT" --cdp "$CDP_PORT" close --all 2>/dev/null || true
rm -f "$PIDFILE"
- # Pool mode: wipe the instance's userData unless asked to keep it.
+ # Pool mode: capture the (freshly rotated) login before touching the userData,
+ # then wipe it unless asked to keep it.
if [ "$POOL_MODE" = "1" ] && [ -n "$USER_DATA_DIR" ]; then
+ [ "${SKIP_LOGIN_SAVE:-0}" = "1" ] || save_login_state "$USER_DATA_DIR" "$authed"
if [ "${KEEP_DATA:-0}" = "1" ]; then
echo "[electron-dev] Keeping userData: $USER_DATA_DIR"
else
@@ -359,7 +516,9 @@ do_start() {
if ! wait_for_cdp; then
echo "[electron-dev] Failed to bring up CDP. Cleaning up..."
- do_stop
+ # The app never came up, so its userData is just the seed copy โ€” snapshotting it
+ # would overwrite a good snapshot with an unverified (possibly rejected) token.
+ SKIP_LOGIN_SAVE=1 do_stop
return 1
fi
wait_for_renderer || true
@@ -371,9 +530,11 @@ do_start() {
fi
}
-# Quiet stop used at the head of start โ€” never wipes userData.
+# Quiet stop used at the head of start โ€” never wipes userData, and never
+# snapshots: a leftover userData can carry a token that a LATER run has already
+# rotated away, which still looks unexpired but would overwrite a good snapshot.
do_stop_quiet_for_start() {
- KEEP_DATA=1 do_stop >/dev/null 2>&1 || true
+ KEEP_DATA=1 SKIP_LOGIN_SAVE=1 do_stop >/dev/null 2>&1 || true
}
do_restart() {
@@ -403,6 +564,20 @@ do_list() {
[ "$found" = "0" ] && echo " (none)"
}
+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."
+}
+
do_stop_all() {
local found=0
if [ -d "$POOL_DIR" ]; then
@@ -445,18 +620,33 @@ case "$CMD" in
list)
do_list
;;
+ save-login)
+ derive_instance "$INSTANCE"
+ if [ "$POOL_MODE" != "1" ]; then
+ echo "[electron-dev] save-login needs a pool instance id (its userData dir)."
+ exit 1
+ fi
+ save_login_state "$USER_DATA_DIR" "$(probe_renderer_authed)"
+ ;;
+ login-status)
+ do_login_status
+ ;;
*)
echo "Usage: $0 {start|stop|status|restart} [<id>] | $0 stop --all | $0 list"
+ echo " $0 save-login <id> | $0 login-status"
echo ""
- 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."
+ 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 seeded from the saved snapshot) + IPC id."
+ echo " stop [<id>] โ€” Stop an instance. Pool stop is sibling-safe, and snapshots the"
+ echo " instance's login first. KEEP_DATA=1 preserves the userData;"
+ echo " SKIP_LOGIN_SAVE=1 skips the snapshot."
+ 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."
+ echo " save-login <id> โ€” Snapshot a live instance's login without stopping it."
+ echo " login-status โ€” Show which source will seed the next instance, and its expiry."
exit 1
;;
esac
diff --git a/.agents/skills/agent-testing/ui/electron.md b/.agents/skills/agent-testing/ui/electron.md
index 9c6a48b6ff4..450abc31e5a 100644
--- a/.agents/skills/agent-testing/ui/electron.md
+++ b/.agents/skills/agent-testing/ui/electron.md
@@ -2,7 +2,7 @@
Default surface for verifying **pure frontend changes** (components, store logic, styles, interactions) in the primary product shape. Drives the Electron renderer over CDP with `agent-browser` โ€” see [../references/agent-browser.md](../references/agent-browser.md) for the full command reference.
-**Auth**: the Electron app keeps its own persistent login state โ€” log in once manually in the app; sessions survive restarts. Run `../scripts/setup-auth.sh status` before testing (see [../references/auth.md](../references/auth.md)).
+**Auth**: `electron-dev.sh` persists the login across runs โ€” `stop` snapshots it to `~/.lobehub/agent-testing/electron-login`, `start` seeds each new instance from there (`login-status` inspects it, `save-login <id>` captures a live instance). Sign in once, not once per run โ€” and if an instance still comes up signed out, **drive the sign-in yourself**; never ask the user to click it. Run `../scripts/setup-auth.sh status` before testing (see [../references/auth.md](../references/auth.md)).
**Linux / headless (cloud)**: Electron itself runs on Linux, but it has no true headless mode โ€” it needs a display server. In a headless environment wrap the launch with `xvfb-run` (virtual framebuffer). Everything CDP-based keeps working under Xvfb: the `agent-browser --cdp 9222` connection, snapshots, eval, and `agent-browser screenshot` (captured from the renderer via CDP, not the OS screen). What does NOT work on Linux: `capture-app-window.sh` (macOS `screencapture`), osascript, and the ffmpeg recording scripts in their current form.
@@ -40,12 +40,15 @@ After `start` succeeds, connect with: `agent-browser --cdp 9222 snapshot -i`
#### Environment Variables
-| Variable | Default | Description |
-| ----------------- | ----------------------- | ---------------------------------------- |
-| `CDP_PORT` | `9222` | Chrome DevTools Protocol port |
-| `ELECTRON_LOG` | `/tmp/electron-dev.log` | Electron process log |
-| `ELECTRON_WAIT_S` | `60` | Max seconds to wait for Electron process |
-| `RENDERER_WAIT_S` | `60` | Max seconds to wait for SPA to load |
+| Variable | Default | Description |
+| ---------------------- | ----------------------------------------- | ------------------------------------------------- |
+| `CDP_PORT` | `9222` | Chrome DevTools Protocol port |
+| `ELECTRON_LOG` | `/tmp/electron-dev.log` | Electron process log |
+| `ELECTRON_WAIT_S` | `60` | Max seconds to wait for Electron process |
+| `RENDERER_WAIT_S` | `60` | Max seconds to wait for SPA to load |
+| `LOBE_LOGIN_STATE_DIR` | `~/.lobehub/agent-testing/electron-login` | Persistent login snapshot (survives `/tmp` wipes) |
+| `KEEP_DATA` | `0` | `1` = `stop <id>` keeps the instance's userData |
+| `SKIP_LOGIN_SAVE` | `0` | `1` = `stop <id>` does not snapshot the login |
### LobeHub Probes & Quick Navigation
diff --git a/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx b/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx
index e38ecd68200..a3b6e2ff501 100644
--- a/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx
@@ -384,15 +384,24 @@ const getWorktreeBranch = (
const isDisabled = (worktree: DeviceGitWorktreeListItem): boolean =>
!!worktree.bare || !!worktree.prunable;
-// The main/source worktree can never be removed (`git worktree remove <main>`
-// fails with "is a main working tree"), and when the agent runs on a linked
-// worktree it is listed with `current: false` โ€” so exclude it by path too, not
-// just via the `current` flag, to avoid offering a delete that always errors.
-const canRemoveWorktree = (worktree: DeviceGitWorktreeListItem, sourcePath: string): boolean =>
+// The main worktree can never be removed (`git worktree remove <main>` fails with
+// "is a main working tree"), and when the agent runs on a linked worktree it is
+// listed with `current: false` โ€” so exclude it by path too, not just via the
+// `current` flag, to avoid offering a delete that always errors. `sourcePath` is
+// NOT the main worktree whenever the user picks a linked worktree directly as the
+// working directory, so it is excluded separately (removing the conversation's own
+// source repo would strand it), not used as a stand-in for the main worktree.
+const canRemoveWorktree = (
+ worktree: DeviceGitWorktreeListItem,
+ sourcePath: string,
+ mainWorktreePath?: string,
+): boolean =>
!worktree.current &&
!worktree.locked &&
!isDisabled(worktree) &&
- normalizeDisplayPath(worktree.path) !== normalizeDisplayPath(sourcePath);
+ normalizeDisplayPath(worktree.path) !== normalizeDisplayPath(sourcePath) &&
+ (!mainWorktreePath ||
+ normalizeDisplayPath(worktree.path) !== normalizeDisplayPath(mainWorktreePath));
interface DirtyStatProps {
status?: DeviceGitWorktreeListItem['status'];
@@ -609,8 +618,17 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(
const triggerTitle = detached
? t('workingDirectory.detachedHead', { sha: currentBranch })
: `${currentName} ยท ${branchLabel}`;
- const isSourceWorktree = normalizeDisplayPath(currentPath) === normalizeDisplayPath(sourcePath);
- const triggerIcon = isSourceWorktree ? GitBranchIcon : GitForkIcon;
+ // `git worktree list` always emits the main worktree first (a bare repo has
+ // none, so every checkout is linked). Compare against it rather than
+ // `sourcePath`, which is itself a linked worktree whenever the user picks one
+ // directly as the working directory โ€” that would show a branch icon while
+ // standing inside a worktree.
+ const [mainWorktree] = worktrees;
+ const isLinkedWorktree =
+ !!mainWorktree &&
+ (!!mainWorktree.bare ||
+ normalizeDisplayPath(currentPath) !== normalizeDisplayPath(mainWorktree.path));
+ const triggerIcon = isLinkedWorktree ? GitForkIcon : GitBranchIcon;
const trigger = (
<div
@@ -670,7 +688,8 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(
const displayPath = getRelativeDisplayPath(worktree.path, sourcePath);
const disabled = isDisabled(worktree);
const removing = removingPaths.has(worktree.path);
- const removable = canRemoveWorktree(worktree, sourcePath) && !removing;
+ const removable =
+ canRemoveWorktree(worktree, sourcePath, mainWorktree?.path) && !removing;
return (
<DropdownMenuItem
diff --git a/src/features/ChatInput/ControlBar/__tests__/WorktreeSwitcher.test.tsx b/src/features/ChatInput/ControlBar/__tests__/WorktreeSwitcher.test.tsx
index 2af2903d9d9..51143904c4b 100644
--- a/src/features/ChatInput/ControlBar/__tests__/WorktreeSwitcher.test.tsx
+++ b/src/features/ChatInput/ControlBar/__tests__/WorktreeSwitcher.test.tsx
@@ -32,7 +32,7 @@ vi.mock('@/services/git', () => ({
}));
vi.mock('@lobehub/ui', () => ({
- Icon: () => <span data-testid="icon" />,
+ Icon: ({ icon }: any) => <span data-icon={icon?.displayName ?? icon?.name} data-testid="icon" />,
Input: ({ value, onChange, placeholder }: any) => (
<input placeholder={placeholder} value={value} onChange={onChange} />
),
@@ -87,6 +87,14 @@ beforeEach(() => {
removeGitWorktreeMock.mockResolvedValue({ success: true });
});
+const triggerIconName = () =>
+ within(screen.getByTestId('worktree-dropdown-trigger'))
+ .getAllByTestId('icon')[0]
+ .getAttribute('data-icon');
+
+/** Text of the worktree row owning `el` โ€” rows render as `<button>` (mocked DropdownMenuItem). */
+const rowTextOf = (el: HTMLElement) => el.closest('button')?.textContent ?? '';
+
describe('WorktreeSwitcher', () => {
it('keeps the dropdown trigger anchored to a stable DOM wrapper', () => {
render(
@@ -118,6 +126,62 @@ describe('WorktreeSwitcher', () => {
expect(within(trigger).getByTestId('worktree-tooltip')).toBeTruthy();
});
+ it('shows a branch icon on the main worktree and a fork icon on a linked one', () => {
+ const cleanStatus = { added: 0, clean: true, deleted: 0, modified: 0, total: 0 };
+ const worktrees = [
+ { branch: 'canary', current: true, path: '/repo', status: cleanStatus },
+ { branch: 'feat/x', current: false, path: '/repo-feat', status: cleanStatus },
+ ];
+
+ const { rerender } = render(
+ <WorktreeSwitcher
+ isGithub
+ agentId="agent-1"
+ currentBranch="canary"
+ path="/repo"
+ sourcePath="/repo"
+ worktrees={worktrees}
+ />,
+ );
+ expect(triggerIconName()).toBe('GitBranch');
+
+ // The user picked the linked worktree directly as the working directory, so
+ // `sourcePath` is the worktree itself โ€” the icon must still read "worktree".
+ rerender(
+ <WorktreeSwitcher
+ isGithub
+ agentId="agent-1"
+ currentBranch="feat/x"
+ path="/repo-feat"
+ sourcePath="/repo-feat"
+ worktrees={[
+ { ...worktrees[0], current: false },
+ { ...worktrees[1], current: true },
+ ]}
+ />,
+ );
+ expect(triggerIconName()).toBe('GitFork');
+ });
+
+ it('treats every checkout of a bare repository as a linked worktree', () => {
+ const cleanStatus = { added: 0, clean: true, deleted: 0, modified: 0, total: 0 };
+ render(
+ <WorktreeSwitcher
+ isGithub
+ agentId="agent-1"
+ currentBranch="canary"
+ path="/repo/canary"
+ sourcePath="/repo/canary"
+ worktrees={[
+ { bare: true, current: false, path: '/repo' },
+ { branch: 'canary', current: true, path: '/repo/canary', status: cleanStatus },
+ ]}
+ />,
+ );
+
+ expect(triggerIconName()).toBe('GitFork');
+ });
+
it('renders dirty stats and omits clean labels in the worktree list', () => {
render(
<WorktreeSwitcher
@@ -189,6 +253,32 @@ describe('WorktreeSwitcher', () => {
expect(screen.getByText('/tmp/project-scratch')).toBeTruthy();
});
+ it('never offers to remove the main worktree, even when it is not the source path', () => {
+ const cleanStatus = { added: 0, clean: true, deleted: 0, modified: 0, total: 0 };
+ render(
+ <WorktreeSwitcher
+ isGithub
+ agentId="agent-1"
+ currentBranch="feat/x"
+ path="/repo-feat"
+ sourcePath="/repo-feat"
+ worktrees={[
+ // main worktree โ€” listed first, and `current: false` because the
+ // conversation runs on a linked one. `git worktree remove` would error.
+ { branch: 'canary', current: false, path: '/repo', status: cleanStatus },
+ { branch: 'feat/x', current: true, path: '/repo-feat', status: cleanStatus },
+ { branch: 'feat/y', current: false, path: '/repo-other', status: cleanStatus },
+ ]}
+ />,
+ );
+
+ // Only `/repo-other` is removable: `/repo` is the main worktree and
+ // `/repo-feat` is both the current worktree and the conversation's source.
+ const removeButtons = screen.getAllByLabelText('workingDirectory.removeWorktreeAction');
+ expect(removeButtons).toHaveLength(1);
+ expect(rowTextOf(removeButtons[0])).toContain('feat/y');
+ });
+
it('confirms and removes a non-current worktree', async () => {
const onWorktreesChange = vi.fn();
render(