🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
💄 fix(chat-input): refine hetero ActionBar working-directory & git switcher UX (#16712)
Arvin Xu8dbef81e29bd
diff --git a/.agents/skills/agent-testing/references/multi-instance.md b/.agents/skills/agent-testing/references/multi-instance.mdindex f2bfe4f4b57..22c33e77116 100644--- a/.agents/skills/agent-testing/references/multi-instance.md+++ b/.agents/skills/agent-testing/references/multi-instance.md@@ -11,22 +11,54 @@ Use case driving this: **N git worktrees under one project, each doing differentwork, each running its own Electron dev instance** — so each needs its own Vitedev server + its own userData, while reusing the developer's existing login.+## Worktree instance prerequisites (deps + first mount) — validated 2026-07-04++A git worktree starts with **no `node_modules`** (gitignored, not shared). Two traps+sink an `electron-dev.sh start <id>` on a fresh worktree before it will even mount:++- **`pnpm install` per worktree — do NOT symlink the main checkout's `node_modules`.**+ Symlinking the primary repo's `node_modules` into the worktree _looks_ like it works+ but silently pins the **main branch's dependency versions**, which can lag the+ worktree branch. Real failure: a worktree on `canary` imports `FloatingPanel` from+ `@lobehub/ui ^5.19.0`, but the symlinked main checkout had `5.18.0` → the renderer+ crashed at load (`Uncaught SyntaxError: … does not provide an export named+'FloatingPanel'`) and the app hung on the loading screen (`#root` empty,+ `__LOBE_STORES` undefined) **even though raw-CDP screenshots still showed a painted+ frame** from before the crash. Fix: real `pnpm install` in the worktree **root** _and_+ `apps/desktop` (standalone install, per Step 0.1) before `start`. (`type-check` warns+ of the same skew: cross-root `packages/*` dual-identity errors when `node_modules` is+ symlinked across worktree roots.)+- **First cold Vite load can `ECONNRESET` under resource contention.** Two full+ Electron+Vite dev stacks at once (main app + a fresh worktree instance) can overwhelm+ Vite on the cold module storm: the log fills with `Vite dev server fetch failed:+http://127.0.0.1:<port>/src/… [read ECONNRESET]`, the SPA hangs on the loading screen,+ `#root` stays at 0 children. **Not a code error** — a clean `electron-dev.sh stop <id>+&& start <id>` once the install/CPU storm is over mounts cleanly (0 ECONNRESET,+ `__LOBE_STORES` becomes an object, `#root` fills).++> "Screenshot shows the app but `eval` sees an empty `#root`" → the app never mounted+> (loading-screen shell), not a target mismatch. Confirm with `eval+"document.getElementById('root')?.childElementCount"` (0 + a `#loading-screen` = not+> mounted). And remember `cdp-screenshot.sh` reads **`--port`, not** a `CDP_PORT` env —+> pass `--port 92xx` for a pool instance or you'll silently shoot the default 9222 (the+> main app), not your worktree instance.+## The real bottleneck is NOT "one port"CDP is single-port, multi-target: one `--remote-debugging-port` exposes every`BrowserWindow` as a target. What actually blocks N independent, write-isolatedapp sessions are dev-build singletons. Validated verdicts:-| Singleton | Location | Verdict for N instances |-| --------- | -------- | ----------------------- |-| Electron single-instance lock | `App.ts:227` | ✅ **keyed by userData** — distinct userData dirs each get their own lock; all instances run. No code change needed. |-| Chromium `SingletonLock` | per userData dir | ✅ one per userData dir automatically (observed distinct PIDs per dir). |-| userData dir `lobehub-desktop-dev` | `pre-app-init.ts:12` | ✅ fixed — now env-overridable via `LOBE_DESKTOP_USER_DATA_DIR`. |-| Vite dev server `strictPort:true` 5173 | `electron.vite.config.ts` | ✅ fixed — now env-overridable via `LOBE_DESKTOP_VITE_PORT` (Model B: one Vite per worktree). |-| `electron-server-ipc` unix socket | `App.ts` → `packages/electron-server-ipc/src/ipcServer.ts:23-31` | ✅ fixed — id now env-overridable via `LOBE_IPC_ID`; distinct sockets, no more hijack (was last-writer-wins). |-| safeStorage / Chromium cookie encryption | OS keychain, keyed by **app name** | 🔑 requires **app name constant** to decrypt a copied login state. |-| Global shortcuts / `lobehub://` protocol | OS-global | first/last wins; harmless for headless automation. |-| Static file server / iMessage bridge | `getPort()` dynamic | ✅ auto-allocated, safe. |+| Singleton | Location | Verdict for N instances |+| ---------------------------------------- | ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |+| Electron single-instance lock | `App.ts:227` | ✅ **keyed by userData** — distinct userData dirs each get their own lock; all instances run. No code change needed. |+| Chromium `SingletonLock` | per userData dir | ✅ one per userData dir automatically (observed distinct PIDs per dir). |+| userData dir `lobehub-desktop-dev` | `pre-app-init.ts:12` | ✅ fixed — now env-overridable via `LOBE_DESKTOP_USER_DATA_DIR`. |+| Vite dev server `strictPort:true` 5173 | `electron.vite.config.ts` | ✅ fixed — now env-overridable via `LOBE_DESKTOP_VITE_PORT` (Model B: one Vite per worktree). |+| `electron-server-ipc` unix socket | `App.ts` → `packages/electron-server-ipc/src/ipcServer.ts:23-31` | ✅ fixed — id now env-overridable via `LOBE_IPC_ID`; distinct sockets, no more hijack (was last-writer-wins). |+| safeStorage / Chromium cookie encryption | OS keychain, keyed by **app name** | 🔑 requires **app name constant** to decrypt a copied login state. |+| Global shortcuts / `lobehub://` protocol | OS-global | first/last wins; harmless for headless automation. |+| Static file server / iMessage bridge | `getPort()` dynamic | ✅ auto-allocated, safe. |## The key tension (and its resolution)@@ -59,7 +91,10 @@ branch ships all three:```tsapp.setName('lobehub-desktop-dev');const userDataOverride = process.env.LOBE_DESKTOP_USER_DATA_DIR;- app.setPath('userData', userDataOverride || path.join(app.getPath('appData'), 'lobehub-desktop-dev'));+ app.setPath(+ 'userData',+ userDataOverride || path.join(app.getPath('appData'), 'lobehub-desktop-dev'),+ );```2. **`apps/desktop/src/main/core/App.ts`** — per-instance IPC id so the@@ -90,10 +125,10 @@ login-bearing items, NOT the multi-GB caches: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+ 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)+done # ~27 MB vs the 1.7 GB full profile (Cache/Code Cache/GPUCache skipped)```- `lobehub-settings.json` → `encryptedTokens` (OIDC access/refresh, safeStorage).@@ -186,11 +221,11 @@ project path (the old single-instance script matched every project Electron bybinary path, so a 2nd `start` tore down the 1st):```bash-electron-dev.sh start 1 # CDP 9223, Vite 5174, userData ud-1 (login copied), IPC id -1-electron-dev.sh start 2 # CDP 9224, Vite 5175, userData ud-2, IPC id -2-electron-dev.sh list # show running pool instances-electron-dev.sh stop 1 # sibling-safe: kills ONLY instance 1 (KEEP_DATA=1 to keep ud)-electron-dev.sh stop --all # stop every instance+electron-dev.sh start 1 # CDP 9223, Vite 5174, userData ud-1 (login copied), IPC id -1+electron-dev.sh start 2 # CDP 9224, Vite 5175, userData ud-2, IPC id -2+electron-dev.sh list # show running pool instances+electron-dev.sh stop 1 # sibling-safe: kills ONLY instance 1 (KEEP_DATA=1 to keep ud)+electron-dev.sh stop --all # stop every instance# no id → legacy single-instance behavior (CDP 9222), unchanged```@@ -207,9 +242,9 @@ 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.+5173\), inst2/inst3 = raw electron (CDP 9224/9225) sharing Vite.- ✅ **All 3 booted** — no single-instance exit (distinct `SingletonLock` PIDs).- ✅ **All 3 signed in** — `isSignedIn:true, user_2gmT…` on all ports (copieddiff --git a/locales/en-US/device.json b/locales/en-US/device.jsonindex b8640c2f87c..fb891820b12 100644--- a/locales/en-US/device.json+++ b/locales/en-US/device.json@@ -8,6 +8,7 @@"workingDirectory.branchSearchPlaceholder": "Search branches","workingDirectory.branchesEmpty": "No local branches","workingDirectory.branchesHeading": "Branches",+ "workingDirectory.branchesLoadFailed": "Failed to load branches","workingDirectory.branchesLoading": "Loading branches…","workingDirectory.branchesNoMatch": "No matching branches","workingDirectory.cancel": "Cancel",@@ -15,11 +16,12 @@"workingDirectory.checkoutFailed": "Checkout failed","workingDirectory.chooseDifferentFolder": "Choose a folder...","workingDirectory.clean": "clean",- "workingDirectory.clear": "Clear",+ "workingDirectory.clear": "Reset to default","workingDirectory.createBranchAction": "Checkout new branch…","workingDirectory.createBranchTitle": "Create new branch","workingDirectory.current": "Current working directory","workingDirectory.currentWorktree": "current",+ "workingDirectory.defaultBadge": "Default","workingDirectory.deleteBranchAction": "Delete branch","workingDirectory.deleteBranchConfirm": "Delete branch “{{name}}”? This permanently removes it, including any unmerged commits.","workingDirectory.deleteBranchTitle": "Delete branch",@@ -34,10 +36,10 @@"workingDirectory.filesLoading": "Loading changes…","workingDirectory.filesModified": "Modified","workingDirectory.ghMissing": "Install and log in to the GitHub CLI (`gh`) to see linked pull requests",- "workingDirectory.heteroHint": "This agent always runs inside a working directory. Until you pick one, it uses a default folder — choose another below to change it.","workingDirectory.lockedWorktree": "locked","workingDirectory.newBranchPlaceholder": "feature/new-branch-name",- "workingDirectory.noRecent": "No recent directories",+ "workingDirectory.noMatch": "No matching directories",+ "workingDirectory.noRecent": "No directories yet","workingDirectory.notSet": "Click to set working directory","workingDirectory.pathNotDirectory": "This path is not a directory","workingDirectory.pathNotExist": "This path doesn't exist on the device",@@ -55,7 +57,7 @@"workingDirectory.pushInProgress": "Pushing…","workingDirectory.pushNoop": "Everything up-to-date","workingDirectory.pushSuccess": "Pushed successfully",- "workingDirectory.recent": "Recent",+ "workingDirectory.recent": "Working directories","workingDirectory.refreshGitStatus": "Refresh branch & PR status","workingDirectory.removeRecent": "Remove from recent","workingDirectory.removeWorktreeAction": "Delete worktree",@@ -63,16 +65,20 @@"workingDirectory.removeWorktreeFailed": "Delete worktree failed","workingDirectory.removeWorktreeSuccess": "Worktree deleted","workingDirectory.removeWorktreeTitle": "Delete worktree",+ "workingDirectory.removed": "Removed “{{name}}”","workingDirectory.renameBranchAction": "Rename branch","workingDirectory.renameBranchTitle": "Rename branch","workingDirectory.renameFailed": "Rename failed",+ "workingDirectory.searchPlaceholder": "Search directories","workingDirectory.selectFolder": "Select folder",+ "workingDirectory.setDefault": "Set as default","workingDirectory.title": "Working Directory","workingDirectory.topicDescription": "Override Agent default for this conversation only","workingDirectory.topicLevel": "Conversation override","workingDirectory.topicOverride": "Override for this conversation","workingDirectory.uncommittedChanges_one": "Uncommitted changes: {{count}} file","workingDirectory.uncommittedChanges_other": "Uncommitted changes: {{count}} files",+ "workingDirectory.undo": "Undo","workingDirectory.worktreeCount": "{{count}} worktrees","workingDirectory.worktreeSwitchDescription": "Switch the current conversation working directory","workingDirectory.worktreeUnavailable": "unavailable",diff --git a/locales/zh-CN/device.json b/locales/zh-CN/device.jsonindex 507a959f27a..e22de011021 100644--- a/locales/zh-CN/device.json+++ b/locales/zh-CN/device.json@@ -8,6 +8,7 @@"workingDirectory.branchSearchPlaceholder": "搜索分支","workingDirectory.branchesEmpty": "暂无本地分支","workingDirectory.branchesHeading": "分支",+ "workingDirectory.branchesLoadFailed": "分支加载失败","workingDirectory.branchesLoading": "加载分支中…","workingDirectory.branchesNoMatch": "没有匹配的分支","workingDirectory.cancel": "取消",@@ -15,11 +16,12 @@"workingDirectory.checkoutFailed": "切换分支失败","workingDirectory.chooseDifferentFolder": "选择其他文件夹","workingDirectory.clean": "clean",- "workingDirectory.clear": "清除目录",+ "workingDirectory.clear": "恢复默认","workingDirectory.createBranchAction": "检出新分支…","workingDirectory.createBranchTitle": "创建新分支","workingDirectory.current": "当前工作目录","workingDirectory.currentWorktree": "current",+ "workingDirectory.defaultBadge": "默认","workingDirectory.deleteBranchAction": "删除分支","workingDirectory.deleteBranchConfirm": "确定删除分支「{{name}}」吗?此操作会永久删除该分支,包括尚未合并的提交。","workingDirectory.deleteBranchTitle": "删除分支",@@ -34,10 +36,10 @@"workingDirectory.filesLoading": "加载中…","workingDirectory.filesModified": "修改","workingDirectory.ghMissing": "安装并登录 GitHub CLI(gh)即可显示关联的 Pull Request",- "workingDirectory.heteroHint": "该 Agent 始终在某个工作目录中运行。在你手动选择之前,会使用默认目录——可在下方选择其他目录。","workingDirectory.lockedWorktree": "locked","workingDirectory.newBranchPlaceholder": "feature/新分支名称",- "workingDirectory.noRecent": "暂无最近目录",+ "workingDirectory.noMatch": "没有匹配的目录",+ "workingDirectory.noRecent": "暂无工作目录","workingDirectory.notSet": "点击设置工作目录","workingDirectory.pathNotDirectory": "该路径不是一个目录","workingDirectory.pathNotExist": "该设备上不存在此路径",@@ -55,7 +57,7 @@"workingDirectory.pushInProgress": "推送中…","workingDirectory.pushNoop": "已是最新","workingDirectory.pushSuccess": "推送成功",- "workingDirectory.recent": "最近使用",+ "workingDirectory.recent": "工作目录","workingDirectory.refreshGitStatus": "刷新分支与 PR 状态","workingDirectory.removeRecent": "从最近目录中移除","workingDirectory.removeWorktreeAction": "删除 Worktree",@@ -63,16 +65,20 @@"workingDirectory.removeWorktreeFailed": "删除 Worktree 失败","workingDirectory.removeWorktreeSuccess": "Worktree 已删除","workingDirectory.removeWorktreeTitle": "删除 Worktree",+ "workingDirectory.removed": "已移除「{{name}}」","workingDirectory.renameBranchAction": "重命名分支","workingDirectory.renameBranchTitle": "重命名分支","workingDirectory.renameFailed": "重命名失败",+ "workingDirectory.searchPlaceholder": "搜索工作目录","workingDirectory.selectFolder": "选择文件夹",+ "workingDirectory.setDefault": "设为默认","workingDirectory.title": "工作目录","workingDirectory.topicDescription": "仅覆盖当前对话的工作目录","workingDirectory.topicLevel": "对话覆盖","workingDirectory.topicOverride": "为当前对话覆盖设置","workingDirectory.uncommittedChanges_one": "未提交的更改:{{count}} 个文件","workingDirectory.uncommittedChanges_other": "未提交的更改:{{count}} 个文件",+ "workingDirectory.undo": "撤销","workingDirectory.worktreeCount": "{{count}} 个 worktree","workingDirectory.worktreeSwitchDescription": "切换当前对话的 working directory","workingDirectory.worktreeUnavailable": "不可用",diff --git a/packages/locales/src/default/device.ts b/packages/locales/src/default/device.tsindex ac107aa88e4..2dd0c752123 100644--- a/packages/locales/src/default/device.ts+++ b/packages/locales/src/default/device.ts@@ -9,17 +9,19 @@ export default {'workingDirectory.branchSearchPlaceholder': 'Search branches','workingDirectory.branchesEmpty': 'No local branches','workingDirectory.branchesHeading': 'Branches',+ 'workingDirectory.branchesLoadFailed': 'Failed to load branches','workingDirectory.branchesLoading': 'Loading branches…','workingDirectory.branchesNoMatch': 'No matching branches','workingDirectory.cancel': 'Cancel','workingDirectory.checkoutAction': 'Checkout','workingDirectory.checkoutFailed': 'Checkout failed','workingDirectory.chooseDifferentFolder': 'Choose a folder...',- 'workingDirectory.clear': 'Clear',+ 'workingDirectory.clear': 'Reset to default','workingDirectory.clean': 'clean','workingDirectory.createBranchAction': 'Checkout new branch…','workingDirectory.createBranchTitle': 'Create new branch','workingDirectory.current': 'Current working directory',+ 'workingDirectory.defaultBadge': 'Default','workingDirectory.deleteBranchAction': 'Delete branch','workingDirectory.deleteBranchConfirm':'Delete branch “{{name}}”? This permanently removes it, including any unmerged commits.',@@ -35,10 +37,9 @@ export default {'workingDirectory.filesModified': 'Modified','workingDirectory.ghMissing':'Install and log in to the GitHub CLI (`gh`) to see linked pull requests',- 'workingDirectory.heteroHint':- 'This agent always runs inside a working directory. Until you pick one, it uses a default folder — choose another below to change it.','workingDirectory.newBranchPlaceholder': 'feature/new-branch-name',- 'workingDirectory.noRecent': 'No recent directories',+ 'workingDirectory.noMatch': 'No matching directories',+ 'workingDirectory.noRecent': 'No directories yet','workingDirectory.notSet': 'Click to set working directory','workingDirectory.pathNotDirectory': 'This path is not a directory','workingDirectory.pathNotExist': "This path doesn't exist on the device",@@ -55,14 +56,18 @@ export default {'workingDirectory.pushInProgress': 'Pushing…','workingDirectory.pushNoop': 'Everything up-to-date','workingDirectory.pushSuccess': 'Pushed successfully',- 'workingDirectory.recent': 'Recent',+ 'workingDirectory.recent': 'Working directories','workingDirectory.refreshGitStatus': 'Refresh branch & PR status','workingDirectory.removeRecent': 'Remove from recent',+ 'workingDirectory.removed': 'Removed “{{name}}”','workingDirectory.renameBranchAction': 'Rename branch','workingDirectory.renameBranchTitle': 'Rename branch','workingDirectory.renameFailed': 'Rename failed',+ 'workingDirectory.searchPlaceholder': 'Search directories','workingDirectory.selectFolder': 'Select folder',+ 'workingDirectory.setDefault': 'Set as default','workingDirectory.title': 'Working Directory',+ 'workingDirectory.undo': 'Undo','workingDirectory.topicDescription': 'Override Agent default for this conversation only','workingDirectory.topicLevel': 'Conversation override','workingDirectory.topicOverride': 'Override for this conversation',diff --git a/src/features/ChatInput/ControlBar/BranchSwitcher.tsx b/src/features/ChatInput/ControlBar/BranchSwitcher.tsxindex 78c1fc4c111..f8087c884d2 100644--- a/src/features/ChatInput/ControlBar/BranchSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/BranchSwitcher.tsx@@ -7,6 +7,7 @@ import {DropdownMenuPositioner,DropdownMenuRoot,DropdownMenuTrigger,+ toast,} from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar, cx } from 'antd-style';import {@@ -26,12 +27,12 @@ import {useCallback,useEffect,useMemo,+ useRef,useState,} from 'react';import { useTranslation } from 'react-i18next';import useSWR from 'swr';-import { message } from '@/components/AntdStaticMethods';import { deviceKeys } from '@/libs/swr/keys';import { gitService } from '@/services/git';import { useFetchGitWorkingTreeStatus } from '@/store/device';@@ -241,6 +242,7 @@ const BranchSwitcher = memo<BranchSwitcherProps>(const { t: tCommon } = useTranslation('common');const [search, setSearch] = useState('');const [busyBranch, setBusyBranch] = useState<string | null>(null);+ const currentRowRef = useRef<HTMLDivElement>(null);const {data: branches = [],@@ -276,6 +278,32 @@ const BranchSwitcher = memo<BranchSwitcherProps>(if (!open) setSearch('');}, [open]);+ // Surface a branch-list load failure as a Toast with Retry (base-ui Toast+ // carries an action; antd `message` can't). Reopening the dropdown also+ // refetches, but Retry recovers without closing.+ useEffect(() => {+ if (open && branchesError) {+ toast.error({+ actions: [+ { label: tCommon('retry'), onClick: () => void mutateBranches(), variant: 'text' },+ ],+ title: t('workingDirectory.branchesLoadFailed'),+ });+ }+ }, [open, branchesError, mutateBranches, t, tCommon]);++ // Scroll the current branch into view each time the dropdown opens — the+ // popup mounts at scrollTop=0, so a checked branch below the fold would read+ // as "nothing selected". Keyed on branches.length so it fires once the async+ // list has painted.+ useEffect(() => {+ if (!open) return;+ const raf = requestAnimationFrame(() => {+ currentRowRef.current?.scrollIntoView({ block: 'nearest' });+ });+ return () => cancelAnimationFrame(raf);+ }, [open, branches.length, currentBranch]);+const filtered = useMemo(() => {const query = search.trim().toLowerCase();if (!query) return branches;@@ -297,7 +325,7 @@ const BranchSwitcher = memo<BranchSwitcherProps>(try {const result = await gitService.checkoutGitBranch({ branch, create, deviceId, path });if (!result.success) {- message.error(result.error || t('workingDirectory.checkoutFailed'));+ toast.error(result.error || t('workingDirectory.checkoutFailed'));}} finally {onAfterCheckout?.();@@ -385,7 +413,7 @@ const BranchSwitcher = memo<BranchSwitcherProps>(const result = await gitService.deleteGitBranch({ branch, deviceId, path });onAfterCheckout?.();if (!result.success) {- message.error(result.error || t('workingDirectory.deleteFailed'));+ toast.error(result.error || t('workingDirectory.deleteFailed'));}},title: t('workingDirectory.deleteBranchTitle'),@@ -434,7 +462,7 @@ const BranchSwitcher = memo<BranchSwitcherProps>({!isLoading && branchesError && (<div className={styles.emptyState}>- {(branchesError as Error)?.message || t('workingDirectory.branchesEmpty')}+ {t('workingDirectory.branchesLoadFailed')}</div>)}@@ -454,6 +482,7 @@ const BranchSwitcher = memo<BranchSwitcherProps>(className={styles.item}closeOnClick={false}key={branch.name}+ ref={isCurrent ? currentRowRef : undefined}onClick={() => handleCheckout(branch.name)}><Icondiff --git a/src/features/ChatInput/ControlBar/GitStatus.tsx b/src/features/ChatInput/ControlBar/GitStatus.tsxindex 8e1761a77df..2d2657c0f77 100644--- a/src/features/ChatInput/ControlBar/GitStatus.tsx+++ b/src/features/ChatInput/ControlBar/GitStatus.tsx@@ -1,10 +1,10 @@import { Icon, Tooltip } from '@lobehub/ui';+import { toast } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar } from 'antd-style';import { ArrowDownIcon, ArrowUpIcon, GitBranchIcon, GitPullRequest } from 'lucide-react';import { memo, useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';-import { message } from '@/components/AntdStaticMethods';import RingLoadingIcon from '@/components/RingLoading';import { electronSystemService } from '@/services/electron/system';import { gitService } from '@/services/git';@@ -225,13 +225,13 @@ const GitStatus = memo<GitStatusProps>(({ agentId, path, sourcePath, isGithub, dconst result = await gitService.pullGitBranch({ deviceId, path });if (result.success) {if (result.noop) {- message.info(t('workingDirectory.pullNoop'));+ toast.info(t('workingDirectory.pullNoop'));} else {- message.success(t('workingDirectory.pullSuccess'));+ toast.success(t('workingDirectory.pullSuccess'));}await refreshAfterSync();} else {- message.error(result.error || t('workingDirectory.pullFailed'));+ toast.error(result.error || t('workingDirectory.pullFailed'));}} finally {setPulling(false);@@ -245,13 +245,13 @@ const GitStatus = memo<GitStatusProps>(({ agentId, path, sourcePath, isGithub, dconst result = await gitService.pushGitBranch({ deviceId, path });if (result.success) {if (result.noop) {- message.info(t('workingDirectory.pushNoop'));+ toast.info(t('workingDirectory.pushNoop'));} else {- message.success(t('workingDirectory.pushSuccess'));+ toast.success(t('workingDirectory.pushSuccess'));}await refreshAfterSync();} else {- message.error(result.error || t('workingDirectory.pushFailed'));+ toast.error(result.error || t('workingDirectory.pushFailed'));}} finally {setPushing(false);diff --git a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsxindex 6a37d6df62b..aa6cfbd1c4c 100644--- a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx+++ b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx@@ -3,7 +3,8 @@import { isDesktop } from '@lobechat/const';import type { WorkingDirEntry } from '@lobechat/types';import { getWorkingDirEffectivePath } from '@lobechat/types';-import { Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';+import { Flexbox, Icon, Input, Popover, Tooltip } from '@lobehub/ui';+import { toast } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar, cx } from 'antd-style';import {CheckIcon,@@ -11,10 +12,11 @@ import {FolderIcon,FolderOpenIcon,FolderPlusIcon,- InfoIcon,+ SearchIcon,+ StarIcon,XIcon,} from 'lucide-react';-import { memo, useState } from 'react';+import { memo, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { openAddWorkingDirModal } from '@/features/WorkingDirectory';@@ -37,7 +39,23 @@ import DirIcon from './DirIcon';import { useCommitWorkingDirectory } from './useCommitWorkingDirectory';import { useMigrateDeviceRecents } from './useMigrateDeviceRecents';+// Show the in-place search box only once the list is long enough that scanning+// gets tedious — a short list doesn't need the extra chrome.+const SEARCH_THRESHOLD = 8;+const styles = createStaticStyles(({ css }) => ({+ badge: css`+ flex: none;++ padding-inline: 5px;+ border-radius: 999px;++ font-size: 10px;+ line-height: 15px;+ color: ${cssVar.colorTextTertiary};++ background: ${cssVar.colorFillSecondary};+ `,button: css`cursor: pointer;@@ -111,14 +129,23 @@ const styles = createStaticStyles(({ css }) => ({&:hover {background: ${cssVar.colorFillTertiary};}++ /* Reveal the row actions (set-default / remove) only on hover. */+ &:hover .wd-row-actions {+ display: flex;+ }`,dirItemActive: css`background: ${cssVar.colorFillTertiary};`,dirName: css`+ overflow: hidden;+font-size: 13px;font-weight: 500;color: ${cssVar.colorText};+ text-overflow: ellipsis;+ white-space: nowrap;`,dirPath: css`overflow: hidden;@@ -128,20 +155,7 @@ const styles = createStaticStyles(({ css }) => ({text-overflow: ellipsis;white-space: nowrap;`,- hint: css`- margin-block: 2px 4px;- margin-inline: 4px;- padding-block: 6px;- padding-inline: 8px;- border-radius: ${cssVar.borderRadius};-- font-size: 12px;- line-height: 1.5;- color: ${cssVar.colorTextSecondary};-- background: ${cssVar.colorFillQuaternary};- `,- removeBtn: css`+ rowAction: css`cursor: pointer;display: flex;@@ -162,9 +176,28 @@ const styles = createStaticStyles(({ css }) => ({background: ${cssVar.colorFillSecondary};}`,+ rowActions: css`+ display: none;+ flex: none;+ gap: 2px;+ align-items: center;+ `,scrollContainer: css`overflow-y: auto;- max-height: 360px;+ max-height: 320px;+ `,+ searchBar: css`+ padding-block: 2px;+ padding-inline: 8px;+ border-block-end: 1px solid ${cssVar.colorSplit};++ .ant-input-affix-wrapper {+ padding-inline: 0;+ }++ .ant-input-prefix {+ margin-inline-end: 8px;+ }`,sectionTitle: css`padding-block: 6px 2px;@@ -259,10 +292,17 @@ interface WorkingDirectoryPickerProps {* `useCommitWorkingDirectory` (topic override / agent per-device choice). When* the target is this machine, the native folder dialog is offered; a true remote* device falls back to manual path entry (its filesystem isn't browsable here).+ *+ * The device-wide **default** directory (`device.defaultCwd`) is surfaced+ * explicitly — the row carrying it wears a "default" badge, and any row can be+ * promoted to the default from its hover actions — so the fallback the agent+ * runs in when nothing is picked is never invisible.*/const WorkingDirectoryPicker = memo<WorkingDirectoryPickerProps>(({ agentId }) => {const { t } = useTranslation('device');const [open, setOpen] = useState(false);+ const [search, setSearch] = useState('');+ const activeRowRef = useRef<HTMLDivElement>(null);// Populate the device store (SWR dedupes across callers). Devices sit behind an// authed lambda procedure, so only fetch once signed in (desktop always fetches).@@ -272,10 +312,6 @@ const WorkingDirectoryPicker = memo<WorkingDirectoryPickerProps>(({ agentId }) =useMigrateDeviceRecents();const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));- // Derive hetero-ness from the agencyConfig already in hand — `heterogeneousProvider`- // is exactly what `isAgentHeterogeneousById` checks, so a second store subscription- // would only be redundant binding.- const isHeterogeneous = !!agencyConfig?.heterogeneousProvider;const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId);// The local machine's filesystem is browsable; a remote device's is not.@@ -289,7 +325,7 @@ const WorkingDirectoryPicker = memo<WorkingDirectoryPickerProps>(({ agentId }) =);// The explicitly-selected cwd (no home fallback) — drives the active check and- // the Clear affordance.+ // the Reset affordance.const selectedDir = resolveAgentWorkingDirectory({agencyConfig,currentDeviceId,@@ -298,8 +334,8 @@ const WorkingDirectoryPicker = memo<WorkingDirectoryPickerProps>(({ agentId }) =topicWorkingDirectory,});- // Clear only makes sense when an agent-level override exists. The device-wide- // `deviceDefaultCwd` isn't clearable from here (it's a device setting), so+ // Reset only makes sense when an agent-level override exists. The device-wide+ // `deviceDefaultCwd` isn't clearable from here (it's the fallback itself), so// gating on it would render a dead button when the cwd comes from the default.const agentChoice = targetDeviceId? agencyConfig?.workingDirByDevice?.[targetDeviceId]@@ -312,24 +348,135 @@ const WorkingDirectoryPicker = memo<WorkingDirectoryPickerProps>(({ agentId }) =const { clear, commit } = useCommitWorkingDirectory(agentId);const removeDeviceWorkingDir = useDeviceStore((s) => s.removeDeviceWorkingDir);+ const updateDeviceCwd = useDeviceStore((s) => s.updateDeviceCwd);++ const filtered = useMemo(() => {+ const query = search.trim().toLowerCase();+ if (!query) return recents;+ return recents.filter(+ (entry) =>+ getDirName(entry.path).toLowerCase().includes(query) ||+ entry.path.toLowerCase().includes(query),+ );+ }, [recents, search]);++ const showSearch = recents.length > SEARCH_THRESHOLD;++ // Reset the query each time the picker closes.+ useEffect(() => {+ if (!open) setSearch('');+ }, [open]);++ // Scroll the current selection into view every time the picker opens — the+ // popover re-mounts its list at scrollTop=0, so a selected dir below the fold+ // would otherwise read as "nothing selected". Re-run when the filtered rows+ // change (search) so the active row, if still present, stays visible.+ useEffect(() => {+ if (!open) return;+ const raf = requestAnimationFrame(() => {+ activeRowRef.current?.scrollIntoView({ block: 'nearest' });+ });+ return () => cancelAnimationFrame(raf);+ }, [open, filtered.length]);const pick = async (entry: WorkingDirEntry) => {await commit(entry);setOpen(false);};- const handleRemoveRecent = (e: React.MouseEvent, path: string) => {+ const handleRemoveRecent = (e: React.MouseEvent, entry: WorkingDirEntry) => {e.stopPropagation();- if (targetDeviceId) void removeDeviceWorkingDir(targetDeviceId, path);+ if (!targetDeviceId) return;+ // Both remove and the undo re-add persist the *whole* `workingDirs` array, so+ // an undo fired before the remove settles would race it — a late-finishing+ // remove would clobber the re-added entry and the undo would silently fail.+ // Chain the undo behind the remove promise so the re-add always writes last.+ const removed = removeDeviceWorkingDir(targetDeviceId, entry.path);+ toast.success({+ actions: [+ {+ label: t('workingDirectory.undo'),+ onClick: () =>+ void removed.then(() => updateDeviceCwd(targetDeviceId, entry, { setDefault: false })),+ variant: 'text',+ },+ ],+ title: t('workingDirectory.removed', { name: getDirName(entry.path) }),+ });};- const content = (- <Flexbox gap={4} style={{ minWidth: 280 }}>- {isHeterogeneous && (- <Flexbox horizontal align={'flex-start'} className={styles.hint} gap={6}>- <Icon icon={InfoIcon} size={14} style={{ flex: 'none', marginTop: 2 }} />- <span>{t('workingDirectory.heteroHint')}</span>+ const handleSetDefault = (e: React.MouseEvent, entry: WorkingDirEntry) => {+ e.stopPropagation();+ if (targetDeviceId) void updateDeviceCwd(targetDeviceId, entry, { setDefault: true });+ };++ const renderRow = (entry: WorkingDirEntry) => {+ const effectivePath = getWorkingDirEffectivePath(entry);+ const isActive = effectivePath === selectedDir;+ const isDefault = !!deviceDefaultCwd && effectivePath === deviceDefaultCwd;+ return (+ <Flexbox+ horizontal+ align={'center'}+ className={cx(styles.dirItem, isActive && styles.dirItemActive)}+ gap={8}+ key={entry.path}+ ref={isActive ? activeRowRef : undefined}+ onClick={() => void pick(entry)}+ >+ <DirIcon repoType={entry.repoType} />+ <Flexbox flex={1} style={{ minWidth: 0 }}>+ <Flexbox horizontal align={'center'} gap={6}>+ <div className={styles.dirName}>{getDirName(entry.path)}</div>+ {isDefault && (+ <span className={styles.badge}>{t('workingDirectory.defaultBadge')}</span>+ )}+ </Flexbox>+ <div className={styles.dirPath}>{entry.path}</div>+ </Flexbox>+ <Flexbox horizontal align={'center'} gap={2} style={{ flex: 'none' }}>+ {/* Set-as-default is offered on every non-default row — including the+ active one (promoting the dir you're currently using to the device+ default is the common case). Remove (X) is hidden on the active row:+ you can't remove the selection out from under yourself. */}+ <div className={cx('wd-row-actions', styles.rowActions)}>+ {!isDefault && (+ <Tooltip title={t('workingDirectory.setDefault')}>+ <div className={styles.rowAction} onClick={(e) => handleSetDefault(e, entry)}>+ <Icon icon={StarIcon} size={13} />+ </div>+ </Tooltip>+ )}+ {!isActive && (+ <Tooltip title={t('workingDirectory.removeRecent')}>+ <div className={styles.rowAction} onClick={(e) => handleRemoveRecent(e, entry)}>+ <Icon icon={XIcon} size={12} />+ </div>+ </Tooltip>+ )}+ </div>+ {isActive && (+ <Icon icon={CheckIcon} size={16} style={{ color: cssVar.colorSuccess, flex: 'none' }} />+ )}</Flexbox>+ </Flexbox>+ );+ };++ const content = (+ <Flexbox gap={4} style={{ maxWidth: 'calc(100vw - 48px)', width: 320 }}>+ {showSearch && (+ <div className={styles.searchBar}>+ <Input+ autoFocus+ placeholder={t('workingDirectory.searchPlaceholder')}+ prefix={<Icon icon={SearchIcon} size={14} />}+ size="small"+ value={search}+ variant="borderless"+ onChange={(e) => setSearch(e.target.value)}+ />+ </div>)}<Flexbox horizontal align={'center'} distribution={'space-between'}><div className={styles.sectionTitle}>{t('workingDirectory.recent')}</div>@@ -340,49 +487,16 @@ const WorkingDirectoryPicker = memo<WorkingDirectoryPickerProps>(({ agentId }) =)}</Flexbox><div className={styles.scrollContainer}>- {recents.length === 0 ? (+ {filtered.length === 0 ? (<Flexboxalign={'center'}justify={'center'}style={{ color: cssVar.colorTextQuaternary, fontSize: 12, padding: '12px 8px' }}>- {t('workingDirectory.noRecent')}+ {search.trim() ? t('workingDirectory.noMatch') : t('workingDirectory.noRecent')}</Flexbox>) : (- recents.map((entry) => {- const isActive = getWorkingDirEffectivePath(entry) === selectedDir;- return (- <Flexbox- horizontal- align={'center'}- className={cx(styles.dirItem, isActive && styles.dirItemActive)}- gap={8}- key={entry.path}- onClick={() => void pick(entry)}- >- <DirIcon repoType={entry.repoType} />- <Flexbox flex={1} style={{ minWidth: 0 }}>- <div className={styles.dirName}>{getDirName(entry.path)}</div>- <div className={styles.dirPath}>{entry.path}</div>- </Flexbox>- {isActive ? (- <Icon- icon={CheckIcon}- size={16}- style={{ color: cssVar.colorSuccess, flex: 'none' }}- />- ) : (- <div- className={styles.removeBtn}- title={t('workingDirectory.removeRecent')}- onClick={(e) => handleRemoveRecent(e, entry.path)}- >- <Icon icon={XIcon} size={12} />- </div>- )}- </Flexbox>- );- })+ filtered.map(renderRow))}</div>diff --git a/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx b/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsxindex 818b5a7fcad..3adc64035a0 100644--- a/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx@@ -8,13 +8,13 @@ import {DropdownMenuPositioner,DropdownMenuRoot,DropdownMenuTrigger,+ toast,} from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar } from 'antd-style';import { CheckIcon, GitForkIcon, Trash2Icon } from 'lucide-react';-import { memo, type MouseEvent, useCallback, useMemo, useState } from 'react';+import { memo, type MouseEvent, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import { message } from '@/components/AntdStaticMethods';import { gitService } from '@/services/git';import { useCommitWorkingDirectory } from './useCommitWorkingDirectory';@@ -391,6 +391,7 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(const { t } = useTranslation('device');const { t: tCommon } = useTranslation('common');const [open, setOpen] = useState(false);+ const currentRowRef = useRef<HTMLDivElement>(null);const { commit } = useCommitWorkingDirectory(agentId);const currentWorktree = useMemo(@@ -443,11 +444,11 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(worktreePath: worktree.path,});if (result.success) {- message.success(t('workingDirectory.removeWorktreeSuccess'));+ toast.success(t('workingDirectory.removeWorktreeSuccess'));await onWorktreesChange?.();return;}- message.error(result.error || t('workingDirectory.removeWorktreeFailed'));+ toast.error(result.error || t('workingDirectory.removeWorktreeFailed'));},title: t('workingDirectory.removeWorktreeTitle'),});@@ -455,6 +456,17 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>([deviceId, onWorktreesChange, path, t, tCommon],);+ // Scroll the current worktree into view each time the dropdown opens — the+ // list mounts at scrollTop=0, so a current worktree below the fold would+ // otherwise read as "nothing selected".+ useEffect(() => {+ if (!open) return;+ const raf = requestAnimationFrame(() => {+ currentRowRef.current?.scrollIntoView({ block: 'nearest' });+ });+ return () => cancelAnimationFrame(raf);+ }, [open, worktrees.length, currentPath]);+const triggerTitle = detached? t('workingDirectory.detachedHead', { sha: currentBranch }): `${currentName} · ${branchLabel}`;@@ -510,6 +522,7 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(closeOnClick={false}data-current={worktree.current}key={worktree.path}+ ref={worktree.path === currentPath ? currentRowRef : undefined}onClick={() => void commitWorktree(worktree)}><div className={styles.itemMain}>diff --git a/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx b/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsxindex 602b859a7d2..87c4e13a015 100644--- a/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx+++ b/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx@@ -68,6 +68,10 @@ vi.mock('@/components/AntdStaticMethods', () => ({message: { error: vi.fn(), info: vi.fn(), success: vi.fn() },}));+vi.mock('@lobehub/ui/base-ui', () => ({+ toast: { error: vi.fn(), info: vi.fn(), success: vi.fn() },+}));+vi.mock('@/components/RingLoading', () => ({default: () => <span data-testid="ring-loading" />,}));diff --git a/src/features/ChatInput/ControlBar/__tests__/WorktreeSwitcher.test.tsx b/src/features/ChatInput/ControlBar/__tests__/WorktreeSwitcher.test.tsxindex 2b9c23d911b..7772ee303cf 100644--- a/src/features/ChatInput/ControlBar/__tests__/WorktreeSwitcher.test.tsx+++ b/src/features/ChatInput/ControlBar/__tests__/WorktreeSwitcher.test.tsx@@ -48,6 +48,7 @@ vi.mock('@lobehub/ui/base-ui', () => ({{children}</div>),+ toast: { error: messageErrorMock, info: vi.fn(), success: messageSuccessMock },}));vi.mock('antd-style', () => ({