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): route a branch checkout into the worktree holding it (#16977)

Arvin Xu14748b07019e
diff --git a/locales/ar/device.json b/locales/ar/device.json
index e0278859147..1767c9e561e 100644
--- a/locales/ar/device.json
+++ b/locales/ar/device.json
@@ -5,6 +5,7 @@
"workingDirectory.agentDescription": "دليل العمل الافتراضي لجميع المحادثات مع هذا الوكيل",
"workingDirectory.agentLevel": "دليل العمل للوكيل",
"workingDirectory.bareWorktree": "مجرد",
+ "workingDirectory.branchInWorktree": "في شجرة العمل {{name}}",
"workingDirectory.branchSearchPlaceholder": "بحث عن الفروع",
"workingDirectory.branchesEmpty": "لا توجد فروع محلية",
"workingDirectory.branchesHeading": "الفروع",
diff --git a/locales/bg-BG/device.json b/locales/bg-BG/device.json
index 609de339f55..01d7edf7f7b 100644
--- a/locales/bg-BG/device.json
+++ b/locales/bg-BG/device.json
@@ -5,6 +5,7 @@
"workingDirectory.agentDescription": "По подразбиране работна директория за всички разговори с този агент",
"workingDirectory.agentLevel": "Работна директория на агента",
"workingDirectory.bareWorktree": "голо",
+ "workingDirectory.branchInWorktree": "В работното дърво {{name}}",
"workingDirectory.branchSearchPlaceholder": "Търсене на клонове",
"workingDirectory.branchesEmpty": "Няма локални клонове",
"workingDirectory.branchesHeading": "Клонове",
diff --git a/locales/de-DE/device.json b/locales/de-DE/device.json
index 98e6b45d842..fa5e2f5bb9d 100644
--- a/locales/de-DE/device.json
+++ b/locales/de-DE/device.json
@@ -5,6 +5,7 @@
"workingDirectory.agentDescription": "Standard-Arbeitsverzeichnis für alle Unterhaltungen mit diesem Agenten",
"workingDirectory.agentLevel": "Agent-Arbeitsverzeichnis",
"workingDirectory.bareWorktree": "nackt",
+ "workingDirectory.branchInWorktree": "Im Arbeitsbaum {{name}}",
"workingDirectory.branchSearchPlaceholder": "Zweige durchsuchen",
"workingDirectory.branchesEmpty": "Keine lokalen Zweige",
"workingDirectory.branchesHeading": "Zweige",
diff --git a/locales/en-US/device.json b/locales/en-US/device.json
index 243a2f052e2..f0486a7718b 100644
--- a/locales/en-US/device.json
+++ b/locales/en-US/device.json
@@ -5,6 +5,7 @@
"workingDirectory.agentDescription": "Default working directory for all conversations with this Agent",
"workingDirectory.agentLevel": "Agent Working Directory",
"workingDirectory.bareWorktree": "bare",
+ "workingDirectory.branchInWorktree": "In worktree {{name}}",
"workingDirectory.branchSearchPlaceholder": "Search branches",
"workingDirectory.branchesEmpty": "No local branches",
"workingDirectory.branchesHeading": "Branches",
diff --git a/locales/es-ES/device.json b/locales/es-ES/device.json
index 9940c4b370a..e274fed46a8 100644
--- a/locales/es-ES/device.json
+++ b/locales/es-ES/device.json
@@ -5,6 +5,7 @@
"workingDirectory.agentDescription": "Directorio de trabajo predeterminado para todas las conversaciones con este Agente",
"workingDirectory.agentLevel": "Directorio de Trabajo del Agente",
"workingDirectory.bareWorktree": "desnudo",
+ "workingDirectory.branchInWorktree": "En el área de trabajo {{name}}",
"workingDirectory.branchSearchPlaceholder": "Buscar ramas",
"workingDirectory.branchesEmpty": "No hay ramas locales",
"workingDirectory.branchesHeading": "Ramas",
diff --git a/locales/fa-IR/device.json b/locales/fa-IR/device.json
index 11b3b4927ad..1311c8f6663 100644
--- a/locales/fa-IR/device.json
+++ b/locales/fa-IR/device.json
@@ -5,6 +5,7 @@
"workingDirectory.agentDescription": "دایرکتوری کاری پیش‌فرض برای تمام مکالمات با این عامل",
"workingDirectory.agentLevel": "دایرکتوری کاری عامل",
"workingDirectory.bareWorktree": "برهنه",
+ "workingDirectory.branchInWorktree": "در شاخه کاری {{name}}",
"workingDirectory.branchSearchPlaceholder": "جستجوی شاخه‌ها",
"workingDirectory.branchesEmpty": "هیچ شاخه محلی وجود ندارد",
"workingDirectory.branchesHeading": "شاخه‌ها",
diff --git a/locales/fr-FR/device.json b/locales/fr-FR/device.json
index fd8986a5e04..94ac0b0e14c 100644
--- a/locales/fr-FR/device.json
+++ b/locales/fr-FR/device.json
@@ -5,6 +5,7 @@
"workingDirectory.agentDescription": "Répertoire de travail par défaut pour toutes les conversations avec cet Agent",
"workingDirectory.agentLevel": "Répertoire de travail de l'Agent",
"workingDirectory.bareWorktree": "nu",
+ "workingDirectory.branchInWorktree": "Dans l'arborescence de travail {{name}}",
"workingDirectory.branchSearchPlaceholder": "Rechercher des branches",
"workingDirectory.branchesEmpty": "Aucune branche locale",
"workingDirectory.branchesHeading": "Branches",
diff --git a/locales/it-IT/device.json b/locales/it-IT/device.json
index 5c31c456023..658ca2e04e6 100644
--- a/locales/it-IT/device.json
+++ b/locales/it-IT/device.json
@@ -5,6 +5,7 @@
"workingDirectory.agentDescription": "Directory di lavoro predefinita per tutte le conversazioni con questo Agente",
"workingDirectory.agentLevel": "Directory di lavoro dell'Agente",
"workingDirectory.bareWorktree": "nudo",
+ "workingDirectory.branchInWorktree": "Nel worktree {{name}}",
"workingDirectory.branchSearchPlaceholder": "Cerca rami",
"workingDirectory.branchesEmpty": "Nessun ramo locale",
"workingDirectory.branchesHeading": "Rami",
diff --git a/locales/ja-JP/device.json b/locales/ja-JP/device.json
index 03569afc060..3a5d105cad1 100644
--- a/locales/ja-JP/device.json
+++ b/locales/ja-JP/device.json
@@ -5,6 +5,7 @@
"workingDirectory.agentDescription": "このエージェントとのすべての会話におけるデフォルトの作業ディレクトリ",
"workingDirectory.agentLevel": "エージェント作業ディレクトリ",
"workingDirectory.bareWorktree": "ベア",
+ "workingDirectory.branchInWorktree": "作業ツリー {{name}} 内のブランチ",
"workingDirectory.branchSearchPlaceholder": "ブランチを検索",
"workingDirectory.branchesEmpty": "ローカルブランチがありません",
"workingDirectory.branchesHeading": "ブランチ",
diff --git a/locales/ko-KR/device.json b/locales/ko-KR/device.json
index f08ad10bd0a..6b3d71543b2 100644
--- a/locales/ko-KR/device.json
+++ b/locales/ko-KR/device.json
@@ -5,6 +5,7 @@
"workingDirectory.agentDescription": "이 에이전트와의 모든 대화에 대한 기본 작업 디렉토리",
"workingDirectory.agentLevel": "에이전트 작업 디렉토리",
"workingDirectory.bareWorktree": "베어",
+ "workingDirectory.branchInWorktree": "작업 트리 {{name}}에서",
"workingDirectory.branchSearchPlaceholder": "브랜치 검색",
"workingDirectory.branchesEmpty": "로컬 브랜치 없음",
"workingDirectory.branchesHeading": "브랜치",
diff --git a/locales/nl-NL/device.json b/locales/nl-NL/device.json
index d6f6c390e71..0e642f8ef99 100644
--- a/locales/nl-NL/device.json
+++ b/locales/nl-NL/device.json
@@ -5,6 +5,7 @@
"workingDirectory.agentDescription": "Standaard werkmap voor alle gesprekken met deze Agent",
"workingDirectory.agentLevel": "Agent Werkmap",
"workingDirectory.bareWorktree": "bare",
+ "workingDirectory.branchInWorktree": "In werkboom {{name}}",
"workingDirectory.branchSearchPlaceholder": "Branches zoeken",
"workingDirectory.branchesEmpty": "Geen lokale branches",
"workingDirectory.branchesHeading": "Branches",
diff --git a/locales/pl-PL/device.json b/locales/pl-PL/device.json
index 997bb581733..dd77dd4b69d 100644
--- a/locales/pl-PL/device.json
+++ b/locales/pl-PL/device.json
@@ -5,6 +5,7 @@
"workingDirectory.agentDescription": "Domyślny katalog roboczy dla wszystkich rozmów z tym Agentem",
"workingDirectory.agentLevel": "Katalog roboczy Agenta",
"workingDirectory.bareWorktree": "gołe",
+ "workingDirectory.branchInWorktree": "W obszarze roboczym {{name}}",
"workingDirectory.branchSearchPlaceholder": "Szukaj gałęzi",
"workingDirectory.branchesEmpty": "Brak lokalnych gałęzi",
"workingDirectory.branchesHeading": "Gałęzie",
diff --git a/locales/pt-BR/device.json b/locales/pt-BR/device.json
index 1dced585063..4792b1c67e5 100644
--- a/locales/pt-BR/device.json
+++ b/locales/pt-BR/device.json
@@ -5,6 +5,7 @@
"workingDirectory.agentDescription": "Diretório de trabalho padrão para todas as conversas com este Agente",
"workingDirectory.agentLevel": "Diretório de Trabalho do Agente",
"workingDirectory.bareWorktree": "nu",
+ "workingDirectory.branchInWorktree": "No worktree {{name}}",
"workingDirectory.branchSearchPlaceholder": "Pesquisar branches",
"workingDirectory.branchesEmpty": "Nenhum branch local",
"workingDirectory.branchesHeading": "Branches",
diff --git a/locales/ru-RU/device.json b/locales/ru-RU/device.json
index e51be79790a..de5a4a4e54d 100644
--- a/locales/ru-RU/device.json
+++ b/locales/ru-RU/device.json
@@ -5,6 +5,7 @@
"workingDirectory.agentDescription": "Рабочая директория по умолчанию для всех разговоров с этим агентом",
"workingDirectory.agentLevel": "Рабочая директория агента",
"workingDirectory.bareWorktree": "голый",
+ "workingDirectory.branchInWorktree": "В рабочем дереве {{name}}",
"workingDirectory.branchSearchPlaceholder": "Поиск веток",
"workingDirectory.branchesEmpty": "Нет локальных веток",
"workingDirectory.branchesHeading": "Ветки",
diff --git a/locales/tr-TR/device.json b/locales/tr-TR/device.json
index 8e80911689c..ab640efdc27 100644
--- a/locales/tr-TR/device.json
+++ b/locales/tr-TR/device.json
@@ -5,6 +5,7 @@
"workingDirectory.agentDescription": "Bu Agent ile yapılan tüm konuşmalar için varsayılan çalışma dizini",
"workingDirectory.agentLevel": "Agent Çalışma Dizini",
"workingDirectory.bareWorktree": "çıplak",
+ "workingDirectory.branchInWorktree": "Çalışma ağacında {{name}}",
"workingDirectory.branchSearchPlaceholder": "Dallar arasında ara",
"workingDirectory.branchesEmpty": "Yerel dal yok",
"workingDirectory.branchesHeading": "Dallar",
diff --git a/locales/vi-VN/device.json b/locales/vi-VN/device.json
index ee896f66ed7..ff9002e3654 100644
--- a/locales/vi-VN/device.json
+++ b/locales/vi-VN/device.json
@@ -5,6 +5,7 @@
"workingDirectory.agentDescription": "Thư mục làm việc mặc định cho tất cả các cuộc trò chuyện với Agent này",
"workingDirectory.agentLevel": "Thư mục làm việc của Agent",
"workingDirectory.bareWorktree": "trần",
+ "workingDirectory.branchInWorktree": "Trong worktree {{name}}",
"workingDirectory.branchSearchPlaceholder": "Tìm kiếm nhánh",
"workingDirectory.branchesEmpty": "Không có nhánh cục bộ",
"workingDirectory.branchesHeading": "Các nhánh",
diff --git a/locales/zh-CN/device.json b/locales/zh-CN/device.json
index 02ee24812f9..7283cc5f87e 100644
--- a/locales/zh-CN/device.json
+++ b/locales/zh-CN/device.json
@@ -5,6 +5,7 @@
"workingDirectory.agentDescription": "该助手下所有对话的默认工作目录",
"workingDirectory.agentLevel": "代理工作目录",
"workingDirectory.bareWorktree": "bare",
+ "workingDirectory.branchInWorktree": "位于工作树 {{name}}",
"workingDirectory.branchSearchPlaceholder": "搜索分支",
"workingDirectory.branchesEmpty": "暂无本地分支",
"workingDirectory.branchesHeading": "分支",
diff --git a/locales/zh-TW/device.json b/locales/zh-TW/device.json
index b68c2cd4a27..c451a36c0c4 100644
--- a/locales/zh-TW/device.json
+++ b/locales/zh-TW/device.json
@@ -5,6 +5,7 @@
"workingDirectory.agentDescription": "所有與此代理的對話的預設工作目錄",
"workingDirectory.agentLevel": "代理工作目錄",
"workingDirectory.bareWorktree": "裸倉庫",
+ "workingDirectory.branchInWorktree": "在工作樹 {{name}}",
"workingDirectory.branchSearchPlaceholder": "搜尋分支",
"workingDirectory.branchesEmpty": "沒有本地分支",
"workingDirectory.branchesHeading": "分支",
diff --git a/packages/locales/src/default/device.ts b/packages/locales/src/default/device.ts
index cea18614951..e242b0c4dc1 100644
--- a/packages/locales/src/default/device.ts
+++ b/packages/locales/src/default/device.ts
@@ -6,6 +6,7 @@ export default {
'workingDirectory.agentDescription':
'Default working directory for all conversations with this Agent',
'workingDirectory.agentLevel': 'Agent Working Directory',
+ 'workingDirectory.branchInWorktree': 'In worktree {{name}}',
'workingDirectory.branchSearchPlaceholder': 'Search branches',
'workingDirectory.branchesEmpty': 'No local branches',
'workingDirectory.branchesHeading': 'Branches',
diff --git a/src/features/ChatInput/ControlBar/BranchSwitcher.tsx b/src/features/ChatInput/ControlBar/BranchSwitcher.tsx
index f8087c884d2..3075a9d8cd6 100644
--- a/src/features/ChatInput/ControlBar/BranchSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/BranchSwitcher.tsx
@@ -1,3 +1,4 @@
+import type { DeviceGitWorktreeListItem } from '@lobechat/types';
import { Icon, Input, Tooltip } from '@lobehub/ui';
import {
confirmModal,
@@ -14,6 +15,7 @@ import {
CheckIcon,
GitBranchIcon,
GitBranchPlusIcon,
+ GitForkIcon,
LoaderIcon,
PencilIcon,
RefreshCwIcon,
@@ -39,6 +41,8 @@ import { useFetchGitWorkingTreeStatus } from '@/store/device';
import { openCreateBranchModal } from './CreateBranchModal';
import { openRenameBranchModal } from './RenameBranchModal';
+import { useSwitchWorktree } from './useSwitchWorktree';
+import { findWorktreeForBranch, getPathName } from './worktreeHelpers';
const styles = createStaticStyles(({ css }) => ({
branchLabel: css`
@@ -210,6 +214,7 @@ const styles = createStaticStyles(({ css }) => ({
}));
interface BranchSwitcherProps {
+ agentId: string;
children: ReactElement;
currentBranch?: string;
/**
@@ -217,6 +222,7 @@ interface BranchSwitcherProps {
* device). Omit for the local machine, which talks to Electron over IPC.
*/
deviceId?: string;
+ isGithub: boolean;
onAfterCheckout?: () => void;
onExternalRefresh?: () => void | Promise<void>;
onOpenChange: (open: boolean) => void;
@@ -224,18 +230,26 @@ interface BranchSwitcherProps {
onOptimisticCheckout?: (branch: string) => void;
open: boolean;
path: string;
+ /** The repo the conversation is anchored to (worktrees hang off it). */
+ sourcePath: string;
+ /** Used to route a checkout into the worktree that already holds the branch. */
+ worktrees: DeviceGitWorktreeListItem[];
}
const BranchSwitcher = memo<BranchSwitcherProps>(
({
+ agentId,
path,
currentBranch,
deviceId,
+ isGithub,
open,
onOpenChange,
onAfterCheckout,
onExternalRefresh,
onOptimisticCheckout,
+ sourcePath,
+ worktrees,
children,
}) => {
const { t } = useTranslation('device');
@@ -243,6 +257,7 @@ const BranchSwitcher = memo<BranchSwitcherProps>(
const [search, setSearch] = useState('');
const [busyBranch, setBusyBranch] = useState<string | null>(null);
const currentRowRef = useRef<HTMLDivElement>(null);
+ const switchWorktree = useSwitchWorktree({ agentId, isGithub, sourcePath });
const {
data: branches = [],
@@ -317,6 +332,23 @@ const BranchSwitcher = memo<BranchSwitcherProps>(
onOpenChange(false);
return;
}
+
+ // Git refuses to check out a branch another worktree already holds. That
+ // worktree's HEAD is on the branch, so switching into it is what the user
+ // asked for — route there instead of surfacing git's error.
+ const owner = create ? undefined : findWorktreeForBranch(worktrees, branch);
+ if (owner) {
+ setBusyBranch(branch);
+ onOpenChange(false);
+ try {
+ await switchWorktree(owner.path);
+ } finally {
+ onAfterCheckout?.();
+ setBusyBranch(null);
+ }
+ return;
+ }
+
setBusyBranch(branch);
// Reflect the switch instantly and close; the checkout + revalidate
// reconcile in the background (a failure rolls the label back).
@@ -340,7 +372,9 @@ const BranchSwitcher = memo<BranchSwitcherProps>(
onOptimisticCheckout,
onOpenChange,
path,
+ switchWorktree,
t,
+ worktrees,
],
);
@@ -477,6 +511,9 @@ const BranchSwitcher = memo<BranchSwitcherProps>(
{filtered.map((branch) => {
const isCurrent = branch.name === currentBranch;
const isBusy = busyBranch === branch.name;
+ // A branch another worktree holds can't be checked out here
+ // (clicking routes into that worktree) and can't be deleted.
+ const owner = findWorktreeForBranch(worktrees, branch.name);
return (
<DropdownMenuItem
className={styles.item}
@@ -487,7 +524,7 @@ const BranchSwitcher = memo<BranchSwitcherProps>(
>
<Icon
className={cx(styles.itemIcon, isBusy && styles.spinning)}
- icon={isBusy ? LoaderIcon : GitBranchIcon}
+ icon={isBusy ? LoaderIcon : owner ? GitForkIcon : GitBranchIcon}
size={14}
/>
<div className={styles.itemMain}>
@@ -499,6 +536,13 @@ const BranchSwitcher = memo<BranchSwitcherProps>(
})}
</div>
)}
+ {owner && (
+ <div className={styles.itemMeta}>
+ {t('workingDirectory.branchInWorktree', {
+ name: getPathName(owner.path),
+ })}
+ </div>
+ )}
</div>
{isCurrent && (
<Icon
@@ -517,7 +561,7 @@ const BranchSwitcher = memo<BranchSwitcherProps>(
<Icon icon={PencilIcon} size={13} />
</div>
</Tooltip>
- {!isCurrent && (
+ {!isCurrent && !owner && (
<Tooltip title={t('workingDirectory.deleteBranchAction')}>
<div
className={cx(styles.rowAction, styles.rowActionDanger)}
diff --git a/src/features/ChatInput/ControlBar/GitStatus.tsx b/src/features/ChatInput/ControlBar/GitStatus.tsx
index 8191ffb6307..f3a16573101 100644
--- a/src/features/ChatInput/ControlBar/GitStatus.tsx
+++ b/src/features/ChatInput/ControlBar/GitStatus.tsx
@@ -340,10 +340,14 @@ const GitStatus = memo<GitStatusProps>(({ agentId, path, sourcePath, isGithub, d
) : (
// Local switches over IPC; a remote device switches over RPC (deviceId set).
<BranchSwitcher
+ agentId={agentId}
currentBranch={branch}
deviceId={deviceId}
+ isGithub={isGithub}
open={switcherOpen}
path={path}
+ sourcePath={sourcePath ?? path}
+ worktrees={worktrees}
onExternalRefresh={refreshAfterSync}
onOpenChange={setSwitcherOpen}
onOptimisticCheckout={handleOptimisticCheckout}
diff --git a/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx b/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx
index 7b5b41433e4..23ee2e42f41 100644
--- a/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx
@@ -1,8 +1,4 @@
-import {
- deriveWorktreePath,
- type DeviceGitWorktreeListItem,
- type WorkingDirEntry,
-} from '@lobechat/types';
+import { deriveWorktreePath, type DeviceGitWorktreeListItem } from '@lobechat/types';
import { Icon, Input, Tooltip } from '@lobehub/ui';
import {
confirmModal,
@@ -31,7 +27,8 @@ import { useTranslation } from 'react-i18next';
import { gitService } from '@/services/git';
import { openCreateWorktreeModal } from './CreateWorktreeModal';
-import { useCommitWorkingDirectory } from './useCommitWorkingDirectory';
+import { useSwitchWorktree } from './useSwitchWorktree';
+import { getPathName, isDisabled, normalizeDisplayPath } from './worktreeHelpers';
const styles = createStaticStyles(({ css }) => ({
badge: css`
@@ -326,12 +323,6 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
-const getPathName = (path: string): string =>
- path.replaceAll('\\', '/').split('/').findLast(Boolean) || path;
-
-const normalizeDisplayPath = (path: string): string =>
- path.replaceAll('\\', '/').replace(/\/+$/, '');
-
const TEMP_PATH_PREFIXES = ['/tmp', '/var/tmp', '/private/tmp'];
const isTempPath = (path: string): boolean => {
@@ -381,9 +372,6 @@ const getWorktreeBranch = (
return fallbackBranch;
};
-const isDisabled = (worktree: DeviceGitWorktreeListItem): boolean =>
- !!worktree.bare || !!worktree.prunable;
-
// 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
@@ -456,7 +444,7 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(
// duplicate delete if the dropdown is reopened mid-removal.
const [removingPaths, setRemovingPaths] = useState<Set<string>>(() => new Set());
const currentRowRef = useRef<HTMLDivElement>(null);
- const { commit } = useCommitWorkingDirectory(agentId);
+ const switchWorktree = useSwitchWorktree({ agentId, isGithub, sourcePath });
// Clear the query each time the dropdown closes so it reopens unfiltered.
useEffect(() => {
@@ -508,15 +496,10 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(
return;
}
- const entry: WorkingDirEntry = {
- ...(worktree.path === sourcePath ? {} : { git: { activeWorktree: worktree.path } }),
- path: sourcePath,
- repoType: isGithub ? 'github' : 'git',
- };
- await commit(entry);
+ await switchWorktree(worktree.path);
setOpen(false);
},
- [commit, isGithub, sourcePath],
+ [switchWorktree],
);
const handleRemoveWorktree = useCallback(
@@ -584,16 +567,11 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(
// Point the conversation at the freshly created worktree, then reconcile
// the list so the new row (now `current`) appears.
- const createdPath = result.worktreePath ?? worktreePath;
- await commit({
- git: { activeWorktree: createdPath },
- path: sourcePath,
- repoType: isGithub ? 'github' : 'git',
- });
+ await switchWorktree(result.worktreePath ?? worktreePath);
await onWorktreesChange?.();
return undefined;
},
- [commit, deviceId, isGithub, onWorktreesChange, path, sourcePath, t],
+ [deviceId, onWorktreesChange, path, sourcePath, switchWorktree, t],
);
const openCreateWorktree = useCallback(() => {
diff --git a/src/features/ChatInput/ControlBar/__tests__/worktreeHelpers.test.ts b/src/features/ChatInput/ControlBar/__tests__/worktreeHelpers.test.ts
new file mode 100644
index 00000000000..9b3a41c0ca3
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/__tests__/worktreeHelpers.test.ts
@@ -0,0 +1,50 @@
+import type { DeviceGitWorktreeListItem } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { findWorktreeForBranch } from '../worktreeHelpers';
+
+const worktree = (
+ overrides: Partial<DeviceGitWorktreeListItem> & Pick<DeviceGitWorktreeListItem, 'path'>,
+): DeviceGitWorktreeListItem => ({ ...overrides }) as DeviceGitWorktreeListItem;
+
+describe('findWorktreeForBranch', () => {
+ it('resolves the linked worktree holding the branch', () => {
+ const worktrees = [
+ worktree({ branch: 'main', current: true, path: '/repo' }),
+ worktree({ branch: 'feat/x', path: '/repo-wt' }),
+ ];
+
+ expect(findWorktreeForBranch(worktrees, 'feat/x')?.path).toBe('/repo-wt');
+ });
+
+ it('ignores the current worktree, since checking out its branch is a no-op', () => {
+ const worktrees = [worktree({ branch: 'main', current: true, path: '/repo' })];
+
+ expect(findWorktreeForBranch(worktrees, 'main')).toBeUndefined();
+ });
+
+ it('ignores bare and prunable worktrees, which have no checkout to switch into', () => {
+ const worktrees = [
+ worktree({ bare: true, branch: 'feat/x', path: '/repo-bare' }),
+ worktree({ branch: 'feat/y', path: '/repo-gone', prunable: true }),
+ ];
+
+ expect(findWorktreeForBranch(worktrees, 'feat/x')).toBeUndefined();
+ expect(findWorktreeForBranch(worktrees, 'feat/y')).toBeUndefined();
+ });
+
+ it('returns undefined for a free branch, which checks out in place', () => {
+ const worktrees = [worktree({ branch: 'main', current: true, path: '/repo' })];
+
+ expect(findWorktreeForBranch(worktrees, 'feat/unheld')).toBeUndefined();
+ });
+
+ it('does not match a detached worktree that merely sits on the branch tip', () => {
+ const worktrees = [
+ worktree({ branch: 'main', current: true, path: '/repo' }),
+ worktree({ detached: true, head: 'abc1234', path: '/repo-detached' }),
+ ];
+
+ expect(findWorktreeForBranch(worktrees, 'feat/x')).toBeUndefined();
+ });
+});
diff --git a/src/features/ChatInput/ControlBar/useSwitchWorktree.ts b/src/features/ChatInput/ControlBar/useSwitchWorktree.ts
new file mode 100644
index 00000000000..e1de2c4df43
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/useSwitchWorktree.ts
@@ -0,0 +1,33 @@
+import type { WorkingDirEntry } from '@lobechat/types';
+import { useCallback } from 'react';
+
+import { useCommitWorkingDirectory } from './useCommitWorkingDirectory';
+
+interface UseSwitchWorktreeOptions {
+ agentId: string;
+ isGithub: boolean;
+ /** The repo the conversation is anchored to; worktrees are recorded relative to it. */
+ sourcePath: string;
+}
+
+/**
+ * Point the working directory at a worktree. Shared by the worktree dropdown,
+ * the create-worktree flow, and the branch dropdown — which routes into the
+ * worktree holding a branch rather than attempting a checkout git would reject.
+ */
+export const useSwitchWorktree = ({ agentId, isGithub, sourcePath }: UseSwitchWorktreeOptions) => {
+ const { commit } = useCommitWorkingDirectory(agentId);
+
+ return useCallback(
+ async (worktreePath: string) => {
+ const entry: WorkingDirEntry = {
+ // Selecting the source repo itself clears the worktree override.
+ ...(worktreePath === sourcePath ? {} : { git: { activeWorktree: worktreePath } }),
+ path: sourcePath,
+ repoType: isGithub ? 'github' : 'git',
+ };
+ await commit(entry);
+ },
+ [commit, isGithub, sourcePath],
+ );
+};
diff --git a/src/features/ChatInput/ControlBar/worktreeHelpers.ts b/src/features/ChatInput/ControlBar/worktreeHelpers.ts
new file mode 100644
index 00000000000..27bc868c8ac
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/worktreeHelpers.ts
@@ -0,0 +1,29 @@
+import type { DeviceGitWorktreeListItem } from '@lobechat/types';
+
+export const getPathName = (path: string): string =>
+ path.replaceAll('\\', '/').split('/').findLast(Boolean) || path;
+
+export const normalizeDisplayPath = (path: string): string =>
+ path.replaceAll('\\', '/').replace(/\/+$/, '');
+
+/** Bare and prunable worktrees have no usable checkout to switch into. */
+export const isDisabled = (worktree: DeviceGitWorktreeListItem): boolean =>
+ !!worktree.bare || !!worktree.prunable;
+
+/**
+ * Git allows a branch to be checked out in at most one worktree, so `git
+ * checkout <branch>` fails with "is already checked out at ..." whenever another
+ * worktree holds it. Resolve that owner up-front to route into it instead of
+ * letting the checkout fail — matching on the parsed `branch` field rather than
+ * on git's stderr, which is version- and locale-dependent.
+ *
+ * The current worktree is never the answer: a branch it holds is the current
+ * branch, and checking that out is a no-op the caller short-circuits earlier.
+ */
+export const findWorktreeForBranch = (
+ worktrees: DeviceGitWorktreeListItem[],
+ branch: string,
+): DeviceGitWorktreeListItem | undefined =>
+ worktrees.find(
+ (worktree) => !worktree.current && !isDisabled(worktree) && worktree.branch === branch,
+ );