Skip to content

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

✨ feat(chat): add worktree selector (#15898)

Arvin Xu2fff315a0368
diff --git a/apps/desktop/src/main/controllers/GitCtr.ts b/apps/desktop/src/main/controllers/GitCtr.ts
index 341ef589fa9..5129103e169 100644
--- a/apps/desktop/src/main/controllers/GitCtr.ts
+++ b/apps/desktop/src/main/controllers/GitCtr.ts
@@ -11,6 +11,7 @@ import type {
GitPullResult,
GitPushResult,
GitRemoteBranchListItem,
+ GitRemoveWorktreeResult,
GitRenameBranchResult,
GitWorkingTreeFiles,
GitWorkingTreePatches,
@@ -34,6 +35,7 @@ import {
listGitWorktrees as computeListGitWorktrees,
pullGitBranch as runPullGitBranch,
pushGitBranch as runPushGitBranch,
+ removeGitWorktree as runRemoveGitWorktree,
renameGitBranch as runRenameGitBranch,
revertGitFile as runRevertGitFile,
} from '@lobechat/local-file-shell';
@@ -138,6 +140,14 @@ export default class GitController extends ControllerModule {
return runDeleteGitBranch(payload);
}
+ @IpcMethod()
+ async removeGitWorktree(payload: {
+ path: string;
+ worktreePath: string;
+ }): Promise<GitRemoveWorktreeResult> {
+ return runRemoveGitWorktree(payload);
+ }
+
@IpcMethod()
async pullGitBranch(payload: { path: string }): Promise<GitPullResult> {
return runPullGitBranch(payload);
diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.ts
index 0c088c1c1d7..a1526b7816d 100644
--- a/apps/server/src/routers/lambda/device.ts
+++ b/apps/server/src/routers/lambda/device.ts
@@ -291,6 +291,27 @@ export const deviceRouter = router({
}),
),
+ /**
+ * Remove a detached worktree in a directory's repository on a remote device,
+ * via the device's `removeGitWorktree` RPC.
+ */
+ removeGitWorktree: deviceProcedure
+ .input(
+ z.object({
+ deviceId: z.string(),
+ path: z.string(),
+ worktreePath: z.string(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) =>
+ deviceGateway.removeGitWorktree({
+ deviceId: input.deviceId,
+ path: input.path,
+ userId: ctx.userId,
+ worktreePath: input.worktreePath,
+ }),
+ ),
+
/**
* Pull (`--ff-only`) the current branch of a directory on a remote device, via
* the device's `pullGitBranch` RPC.
@@ -890,7 +911,13 @@ export const deviceRouter = router({
deviceId: z.string(),
friendlyName: z.string().max(100).nullish(),
workingDirs: z
- .array(z.object({ path: z.string(), repoType: z.enum(['git', 'github']).optional() }))
+ .array(
+ z.object({
+ git: z.object({ activeWorktree: z.string().optional() }).optional(),
+ path: z.string(),
+ repoType: z.enum(['git', 'github']).optional(),
+ }),
+ )
.max(20)
.optional(),
}),
diff --git a/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.test.ts b/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.test.ts
index 84f0dbad46b..0f258697904 100644
--- a/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.test.ts
+++ b/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.test.ts
@@ -36,6 +36,18 @@ describe('resolveDeviceWorkingDirectory', () => {
).toBe('/per-device');
});
+ it('uses the active worktree from the per-device source entry as the effective cwd', () => {
+ expect(
+ resolveDeviceWorkingDirectory({
+ deviceDefaultCwd: '/default',
+ deviceId: 'device-1',
+ workingDirByDevice: {
+ 'device-1': { git: { activeWorktree: '/repo-fix' }, path: '/repo', repoType: 'git' },
+ },
+ }),
+ ).toBe('/repo-fix');
+ });
+
it('only matches the per-device pick for the dispatched device', () => {
expect(
resolveDeviceWorkingDirectory({
diff --git a/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.ts b/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.ts
index df3366b95f6..87bb6282e72 100644
--- a/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.ts
+++ b/apps/server/src/services/aiAgent/resolveDeviceWorkingDirectory.ts
@@ -1,3 +1,6 @@
+import type { WorkingDirConfigValue } from '@lobechat/types';
+import { getWorkingDirEffectivePath } from '@lobechat/types';
+
/**
* Resolve the working directory for a device-bound run.
*
@@ -22,10 +25,12 @@ export const resolveDeviceWorkingDirectory = (params: {
deviceId?: string;
initialWorkingDirectory?: string;
topicWorkingDirectory?: string;
- workingDirByDevice?: Record<string, string> | null;
+ workingDirByDevice?: Record<string, WorkingDirConfigValue> | null;
}): string | undefined =>
params.topicWorkingDirectory ||
params.initialWorkingDirectory ||
- (params.deviceId ? params.workingDirByDevice?.[params.deviceId] : undefined) ||
+ getWorkingDirEffectivePath(
+ params.deviceId ? params.workingDirByDevice?.[params.deviceId] : undefined,
+ ) ||
params.deviceDefaultCwd ||
undefined;
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index 974a41c5b5f..50da90aa9c0 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -20,6 +20,7 @@ import type {
DeviceGitFileRevertResult,
DeviceGitLinkedPullRequestResult,
DeviceGitRemoteBranchListItem,
+ DeviceGitRemoveWorktreeResult,
DeviceGitRenameBranchResult,
DeviceGitSyncResult,
DeviceGitWorkingTreeFiles,
@@ -419,6 +420,39 @@ export class DeviceGateway {
}
}
+ /**
+ * Remove a detached worktree in a directory's repository on a remote device via
+ * the `removeGitWorktree` device RPC.
+ */
+ async removeGitWorktree(params: {
+ deviceId: string;
+ path: string;
+ timeout?: number;
+ userId: string;
+ worktreePath: string;
+ }): Promise<DeviceGitRemoveWorktreeResult> {
+ const { userId, deviceId, path, worktreePath, timeout = 30_000 } = params;
+ const client = this.getClient();
+ if (!client) return { error: 'Device gateway not configured', success: false };
+
+ try {
+ const result = await client.invokeRpc<DeviceGitRemoveWorktreeResult>(
+ { deviceId, timeout, userId },
+ { method: 'removeGitWorktree', params: { path, worktreePath } },
+ );
+
+ if (!result.success || !result.data) {
+ log('removeGitWorktree: failed for deviceId=%s — %s', deviceId, result.error);
+ return { error: result.error || 'Remove worktree failed', success: false };
+ }
+
+ return result.data;
+ } catch (error) {
+ log('removeGitWorktree: error for deviceId=%s — %O', deviceId, error);
+ return { error: (error as Error)?.message || 'Remove worktree failed', success: false };
+ }
+ }
+
/**
* Pull (`--ff-only`) the current branch of a directory on a remote device via
* the `pullGitBranch` device RPC.
diff --git a/locales/en-US/device.json b/locales/en-US/device.json
index c03e54facd0..928576dcf7a 100644
--- a/locales/en-US/device.json
+++ b/locales/en-US/device.json
@@ -4,6 +4,7 @@
"workingDirectory.addFolderTitle": "Add working directory",
"workingDirectory.agentDescription": "Default working directory for all conversations with this Agent",
"workingDirectory.agentLevel": "Agent Working Directory",
+ "workingDirectory.bareWorktree": "bare",
"workingDirectory.branchSearchPlaceholder": "Search branches",
"workingDirectory.branchesEmpty": "No local branches",
"workingDirectory.branchesHeading": "Branches",
@@ -13,15 +14,19 @@
"workingDirectory.checkoutAction": "Checkout",
"workingDirectory.checkoutFailed": "Checkout failed",
"workingDirectory.chooseDifferentFolder": "Choose a folder...",
+ "workingDirectory.clean": "clean",
"workingDirectory.clear": "Clear",
"workingDirectory.createBranchAction": "Checkout new branch…",
"workingDirectory.createBranchTitle": "Create new branch",
"workingDirectory.current": "Current working directory",
+ "workingDirectory.currentWorktree": "current",
"workingDirectory.deleteBranchAction": "Delete branch",
"workingDirectory.deleteBranchConfirm": "Delete branch “{{name}}”? This permanently removes it, including any unmerged commits.",
"workingDirectory.deleteBranchTitle": "Delete branch",
"workingDirectory.deleteFailed": "Delete failed",
"workingDirectory.detachedHead": "Detached HEAD at {{sha}}",
+ "workingDirectory.detachedHeadShort": "detached@{{sha}}",
+ "workingDirectory.detachedWorktree": "detached",
"workingDirectory.diffStatTooltip": "Added {{added}} · Modified {{modified}} · Deleted {{deleted}}",
"workingDirectory.filesAdded": "Added",
"workingDirectory.filesDeleted": "Deleted",
@@ -30,6 +35,7 @@
"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.notSet": "Click to set working directory",
@@ -37,6 +43,7 @@
"workingDirectory.pathNotExist": "This path doesn't exist on the device",
"workingDirectory.placeholder": "Enter directory path, e.g. /Users/name/projects",
"workingDirectory.prTooltipWithExtra": "{{title}} (+{{count}} more open PR on this branch)",
+ "workingDirectory.prunableWorktree": "prunable",
"workingDirectory.pullAction": "Click to pull {{count}} commit(s) from {{upstream}}",
"workingDirectory.pullFailed": "Pull failed",
"workingDirectory.pullInProgress": "Pulling…",
@@ -51,6 +58,11 @@
"workingDirectory.recent": "Recent",
"workingDirectory.refreshGitStatus": "Refresh branch & PR status",
"workingDirectory.removeRecent": "Remove from recent",
+ "workingDirectory.removeWorktreeAction": "Delete detached worktree",
+ "workingDirectory.removeWorktreeConfirm": "Delete detached worktree “{{name}}”? This removes the worktree directory. Git will refuse if it has uncommitted changes.",
+ "workingDirectory.removeWorktreeFailed": "Delete worktree failed",
+ "workingDirectory.removeWorktreeSuccess": "Worktree deleted",
+ "workingDirectory.removeWorktreeTitle": "Delete detached worktree",
"workingDirectory.renameBranchAction": "Rename branch",
"workingDirectory.renameBranchTitle": "Rename branch",
"workingDirectory.renameFailed": "Rename failed",
@@ -60,5 +72,10 @@
"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.uncommittedChanges_other": "Uncommitted changes: {{count}} files",
+ "workingDirectory.worktreeCount": "{{count}} worktrees",
+ "workingDirectory.worktreeSwitchDescription": "Switch the current conversation working directory",
+ "workingDirectory.worktreeUnavailable": "unavailable",
+ "workingDirectory.worktreesEmpty": "No worktrees found",
+ "workingDirectory.worktreesHeading": "Worktrees"
}
diff --git a/locales/zh-CN/device.json b/locales/zh-CN/device.json
index 7954db885fa..4ed6b2d2766 100644
--- a/locales/zh-CN/device.json
+++ b/locales/zh-CN/device.json
@@ -4,6 +4,7 @@
"workingDirectory.addFolderTitle": "添加工作目录",
"workingDirectory.agentDescription": "该助手下所有对话的默认工作目录",
"workingDirectory.agentLevel": "代理工作目录",
+ "workingDirectory.bareWorktree": "bare",
"workingDirectory.branchSearchPlaceholder": "搜索分支",
"workingDirectory.branchesEmpty": "暂无本地分支",
"workingDirectory.branchesHeading": "分支",
@@ -13,15 +14,19 @@
"workingDirectory.checkoutAction": "切换分支",
"workingDirectory.checkoutFailed": "切换分支失败",
"workingDirectory.chooseDifferentFolder": "选择其他文件夹",
+ "workingDirectory.clean": "clean",
"workingDirectory.clear": "清除目录",
"workingDirectory.createBranchAction": "检出新分支…",
"workingDirectory.createBranchTitle": "创建新分支",
"workingDirectory.current": "当前工作目录",
+ "workingDirectory.currentWorktree": "current",
"workingDirectory.deleteBranchAction": "删除分支",
"workingDirectory.deleteBranchConfirm": "确定删除分支「{{name}}」吗?此操作会永久删除该分支,包括尚未合并的提交。",
"workingDirectory.deleteBranchTitle": "删除分支",
"workingDirectory.deleteFailed": "删除失败",
"workingDirectory.detachedHead": "游离 HEAD,当前提交 {{sha}}",
+ "workingDirectory.detachedHeadShort": "detached@{{sha}}",
+ "workingDirectory.detachedWorktree": "detached",
"workingDirectory.diffStatTooltip": "新增 {{added}} · 修改 {{modified}} · 删除 {{deleted}}",
"workingDirectory.filesAdded": "新增",
"workingDirectory.filesDeleted": "删除",
@@ -30,6 +35,7 @@
"workingDirectory.filesModified": "修改",
"workingDirectory.ghMissing": "安装并登录 GitHub CLI(gh)即可显示关联的 Pull Request",
"workingDirectory.heteroHint": "该 Agent 始终在某个工作目录中运行。在你手动选择之前,会使用默认目录——可在下方选择其他目录。",
+ "workingDirectory.lockedWorktree": "locked",
"workingDirectory.newBranchPlaceholder": "feature/新分支名称",
"workingDirectory.noRecent": "暂无最近目录",
"workingDirectory.notSet": "点击设置工作目录",
@@ -37,6 +43,7 @@
"workingDirectory.pathNotExist": "该设备上不存在此路径",
"workingDirectory.placeholder": "输入目录路径,如 /Users/name/projects",
"workingDirectory.prTooltipWithExtra": "{{title}}(此分支还有 {{count}} 个开放 PR)",
+ "workingDirectory.prunableWorktree": "prunable",
"workingDirectory.pullAction": "点击从 {{upstream}} 拉取 {{count}} 个提交",
"workingDirectory.pullFailed": "拉取失败",
"workingDirectory.pullInProgress": "拉取中…",
@@ -51,6 +58,11 @@
"workingDirectory.recent": "最近使用",
"workingDirectory.refreshGitStatus": "刷新分支与 PR 状态",
"workingDirectory.removeRecent": "从最近目录中移除",
+ "workingDirectory.removeWorktreeAction": "删除游离 Worktree",
+ "workingDirectory.removeWorktreeConfirm": "删除游离 Worktree“{{name}}”?这会移除该 worktree 目录;如果仍有未提交更改,Git 会拒绝删除。",
+ "workingDirectory.removeWorktreeFailed": "删除 Worktree 失败",
+ "workingDirectory.removeWorktreeSuccess": "Worktree 已删除",
+ "workingDirectory.removeWorktreeTitle": "删除游离 Worktree",
"workingDirectory.renameBranchAction": "重命名分支",
"workingDirectory.renameBranchTitle": "重命名分支",
"workingDirectory.renameFailed": "重命名失败",
@@ -60,5 +72,10 @@
"workingDirectory.topicLevel": "对话覆盖",
"workingDirectory.topicOverride": "为当前对话覆盖设置",
"workingDirectory.uncommittedChanges_one": "未提交的更改:{{count}} 个文件",
- "workingDirectory.uncommittedChanges_other": "未提交的更改:{{count}} 个文件"
+ "workingDirectory.uncommittedChanges_other": "未提交的更改:{{count}} 个文件",
+ "workingDirectory.worktreeCount": "{{count}} 个 worktree",
+ "workingDirectory.worktreeSwitchDescription": "切换当前对话的 working directory",
+ "workingDirectory.worktreeUnavailable": "不可用",
+ "workingDirectory.worktreesEmpty": "未发现 worktree",
+ "workingDirectory.worktreesHeading": "选择 Worktree"
}
diff --git a/packages/device-control/src/__tests__/dispatch.test.ts b/packages/device-control/src/__tests__/dispatch.test.ts
index 777016f0996..f8d139f5c57 100644
--- a/packages/device-control/src/__tests__/dispatch.test.ts
+++ b/packages/device-control/src/__tests__/dispatch.test.ts
@@ -160,4 +160,19 @@ describe('executeDeviceRpc', () => {
expect(result.success).toBe(true);
expect(await readFile(filePath, 'utf8')).toBe('remote edit');
});
+
+ it('routes listGitWorktrees through the shared git dispatcher', async () => {
+ // Not a git repo → the shared local-file-shell impl returns an empty list.
+ const result = await executeDeviceRpc('listGitWorktrees', { path: root }, makeDeps());
+ expect(Array.isArray(result)).toBe(true);
+ });
+
+ it('routes removeGitWorktree through the shared git dispatcher', async () => {
+ const result = (await executeDeviceRpc(
+ 'removeGitWorktree',
+ { path: root, worktreePath: root },
+ makeDeps(),
+ )) as { success: boolean };
+ expect(result.success).toBe(false);
+ });
});
diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.ts
index 75f334d8e4f..a26a73b3860 100644
--- a/packages/device-control/src/dispatch.ts
+++ b/packages/device-control/src/dispatch.ts
@@ -10,9 +10,11 @@ import {
getLinkedPullRequest,
listGitBranches,
listGitRemoteBranches,
+ listGitWorktrees,
moveLocalFiles,
pullGitBranch,
pushGitBranch,
+ removeGitWorktree,
renameGitBranch,
renameLocalFile,
revertGitFile,
@@ -54,9 +56,11 @@ export const DEVICE_RPC_METHODS = [
'getGitAheadBehind',
'listGitBranches',
'listGitRemoteBranches',
+ 'listGitWorktrees',
'checkoutGitBranch',
'renameGitBranch',
'deleteGitBranch',
+ 'removeGitWorktree',
'pullGitBranch',
'pushGitBranch',
'revertGitFile',
@@ -153,6 +157,10 @@ export const executeDeviceRpc = async (
return listGitRemoteBranches((params as { path: string }).path);
}
+ case 'listGitWorktrees': {
+ return listGitWorktrees((params as { path: string }).path);
+ }
+
case 'checkoutGitBranch': {
return checkoutGitBranch(params as { branch: string; create?: boolean; path: string });
}
@@ -165,6 +173,10 @@ export const executeDeviceRpc = async (
return deleteGitBranch(params as { branch: string; path: string });
}
+ case 'removeGitWorktree': {
+ return removeGitWorktree(params as { path: string; worktreePath: string });
+ }
+
case 'pullGitBranch': {
return pullGitBranch(params as { path: string });
}
diff --git a/packages/electron-client-ipc/src/types/git.ts b/packages/electron-client-ipc/src/types/git.ts
index 04546473e98..f566b56996e 100644
--- a/packages/electron-client-ipc/src/types/git.ts
+++ b/packages/electron-client-ipc/src/types/git.ts
@@ -206,6 +206,11 @@ export interface GitDeleteBranchResult {
success: boolean;
}
+export interface GitRemoveWorktreeResult {
+ error?: string;
+ success: boolean;
+}
+
export interface GitPullResult {
error?: string;
/** True when `git pull` reported the branch was already up-to-date */
diff --git a/packages/local-file-shell/src/git/__tests__/branches.test.ts b/packages/local-file-shell/src/git/__tests__/branches.test.ts
index bd43595fd0b..2c0f0881cef 100644
--- a/packages/local-file-shell/src/git/__tests__/branches.test.ts
+++ b/packages/local-file-shell/src/git/__tests__/branches.test.ts
@@ -18,7 +18,7 @@ import {
} from '../branches';
import { getGitAheadBehind, getGitBranch } from '../info';
import { getGitBranchDiff, getGitWorkingTreeFiles, getGitWorkingTreePatches } from '../workingTree';
-import { listGitWorktrees, parseGitWorktreeList } from '../worktrees';
+import { listGitWorktrees, parseGitWorktreeList, removeGitWorktree } from '../worktrees';
const git = (cwd: string, ...args: string[]): string =>
execFileSync('git', args, { cwd, encoding: 'utf8' }).trim();
@@ -126,6 +126,45 @@ describe('branch read operations', () => {
});
});
+describe('removeGitWorktree', () => {
+ it('removes a detached non-current worktree', async () => {
+ const worktreeParent = await mkdtemp(path.join(tmpdir(), 'lfs-worktree-remove-'));
+ cleanup.push(worktreeParent);
+ const linked = path.join(worktreeParent, 'detached');
+ git(repo, 'worktree', 'add', '--detach', linked, 'HEAD');
+ const linkedRealPath = await realpath(linked);
+
+ expect(await removeGitWorktree({ path: repo, worktreePath: linked })).toEqual({
+ success: true,
+ });
+
+ expect(existsSync(linkedRealPath)).toBe(false);
+ expect((await listGitWorktrees(repo)).map((worktree) => worktree.path)).not.toContain(
+ linkedRealPath,
+ );
+ });
+
+ it('refuses to remove a branch worktree', async () => {
+ git(repo, 'branch', 'feature');
+ const worktreeParent = await mkdtemp(path.join(tmpdir(), 'lfs-worktree-branch-'));
+ cleanup.push(worktreeParent);
+ const linked = path.join(worktreeParent, 'linked');
+ git(repo, 'worktree', 'add', linked, 'feature');
+
+ expect(await removeGitWorktree({ path: repo, worktreePath: linked })).toEqual({
+ error: 'Only detached worktrees can be removed',
+ success: false,
+ });
+ });
+
+ it('refuses to remove the current worktree', async () => {
+ expect(await removeGitWorktree({ path: repo, worktreePath: repo })).toEqual({
+ error: 'Cannot remove the current worktree',
+ success: false,
+ });
+ });
+});
+
describe('checkoutGitBranch', () => {
it('creates and switches to a new branch', async () => {
const result = await checkoutGitBranch({ branch: 'feature', create: true, path: repo });
diff --git a/packages/local-file-shell/src/git/types.ts b/packages/local-file-shell/src/git/types.ts
index 99b9741a602..2636dc0c5b6 100644
--- a/packages/local-file-shell/src/git/types.ts
+++ b/packages/local-file-shell/src/git/types.ts
@@ -193,6 +193,11 @@ export interface GitDeleteBranchResult {
success: boolean;
}
+export interface GitRemoveWorktreeResult {
+ error?: string;
+ success: boolean;
+}
+
export interface GitPullResult {
error?: string;
/** True when `git pull` reported the branch was already up-to-date */
diff --git a/packages/local-file-shell/src/git/worktrees.ts b/packages/local-file-shell/src/git/worktrees.ts
index 884114c3aac..0f5837b8574 100644
--- a/packages/local-file-shell/src/git/worktrees.ts
+++ b/packages/local-file-shell/src/git/worktrees.ts
@@ -4,7 +4,7 @@ import path from 'node:path';
import { promisify } from 'node:util';
import { getGitWorkingTreeStatus } from './info';
-import type { GitWorkingTreeStatus, GitWorktreeListItem } from './types';
+import type { GitRemoveWorktreeResult, GitWorkingTreeStatus, GitWorktreeListItem } from './types';
const execFileAsync = promisify(execFile);
@@ -123,3 +123,41 @@ export const listGitWorktrees = async (dirPath: string): Promise<GitWorktreeList
return [];
}
};
+
+const findListedWorktree = async (
+ dirPath: string,
+ worktreePath: string,
+): Promise<GitWorktreeListItem | undefined> => {
+ const targetPath = await safeRealpath(worktreePath);
+ const worktrees = await listGitWorktrees(dirPath);
+
+ for (const worktree of worktrees) {
+ if ((await safeRealpath(worktree.path)) === targetPath) return worktree;
+ }
+};
+
+export const removeGitWorktree = async (payload: {
+ path: string;
+ worktreePath: string;
+}): Promise<GitRemoveWorktreeResult> => {
+ const { path: dirPath, worktreePath } = payload;
+ if (!dirPath?.trim()) return { error: 'Working directory is required', success: false };
+ if (!worktreePath?.trim()) return { error: 'Worktree path is required', success: false };
+
+ const worktree = await findListedWorktree(dirPath, worktreePath);
+ if (!worktree) return { error: 'Worktree not found', success: false };
+ if (worktree.current) return { error: 'Cannot remove the current worktree', success: false };
+ if (!worktree.detached)
+ return { error: 'Only detached worktrees can be removed', success: false };
+
+ try {
+ await execFileAsync('git', ['worktree', 'remove', worktree.path], {
+ cwd: dirPath,
+ timeout: 30_000,
+ });
+ return { success: true };
+ } catch (error: any) {
+ const stderr: string = (error?.stderr ?? error?.message ?? '').toString().trim();
+ return { error: stderr || 'git worktree remove failed', success: false };
+ }
+};
diff --git a/packages/locales/src/default/device.ts b/packages/locales/src/default/device.ts
index b94e6955500..50ab2b74650 100644
--- a/packages/locales/src/default/device.ts
+++ b/packages/locales/src/default/device.ts
@@ -16,6 +16,7 @@ export default {
'workingDirectory.checkoutFailed': 'Checkout failed',
'workingDirectory.chooseDifferentFolder': 'Choose a folder...',
'workingDirectory.clear': 'Clear',
+ 'workingDirectory.clean': 'clean',
'workingDirectory.createBranchAction': 'Checkout new branch…',
'workingDirectory.createBranchTitle': 'Create new branch',
'workingDirectory.current': 'Current working directory',
@@ -67,4 +68,21 @@ export default {
'workingDirectory.topicOverride': 'Override for this conversation',
'workingDirectory.uncommittedChanges_one': 'Uncommitted changes: {{count}} file',
'workingDirectory.uncommittedChanges_other': 'Uncommitted changes: {{count}} files',
+ 'workingDirectory.bareWorktree': 'bare',
+ 'workingDirectory.currentWorktree': 'current',
+ 'workingDirectory.detachedHeadShort': 'detached@{{sha}}',
+ 'workingDirectory.detachedWorktree': 'detached',
+ 'workingDirectory.lockedWorktree': 'locked',
+ 'workingDirectory.prunableWorktree': 'prunable',
+ 'workingDirectory.removeWorktreeAction': 'Delete detached worktree',
+ 'workingDirectory.removeWorktreeConfirm':
+ 'Delete detached worktree “{{name}}”? This removes the worktree directory. Git will refuse if it has uncommitted changes.',
+ 'workingDirectory.removeWorktreeFailed': 'Delete worktree failed',
+ 'workingDirectory.removeWorktreeSuccess': 'Worktree deleted',
+ 'workingDirectory.removeWorktreeTitle': 'Delete detached worktree',
+ 'workingDirectory.worktreeCount': '{{count}} worktrees',
+ 'workingDirectory.worktreeSwitchDescription': 'Switch the current conversation working directory',
+ 'workingDirectory.worktreeUnavailable': 'unavailable',
+ 'workingDirectory.worktreesEmpty': 'No worktrees found',
+ 'workingDirectory.worktreesHeading': 'Worktrees',
};
diff --git a/packages/types/src/agent/agencyConfig.ts b/packages/types/src/agent/agencyConfig.ts
index cdf6c103e28..4feca146834 100644
--- a/packages/types/src/agent/agencyConfig.ts
+++ b/packages/types/src/agent/agencyConfig.ts
@@ -1,3 +1,5 @@
+import type { WorkingDirConfigValue } from '../device';
+
/**
* Selector value that means "do not override the underlying CLI".
*
@@ -496,19 +498,23 @@ export interface LobeAgentAgencyConfig {
*/
verifyRubricId?: string;
/**
- * Per-device working directory chosen for this agent. Key = `deviceId` (the
- * local machine uses its own gateway deviceId, so local and remote share one
- * model). This is the **agent-level** cwd in the resolution precedence:
+ * Per-device working directory source chosen for this agent. Key = `deviceId`
+ * (the local machine uses its own gateway deviceId, so local and remote share
+ * one model). This is the **agent-level** source in the resolution precedence:
*
* `topic.metadata.workingDirectory`
- * > `workingDirByDevice[targetDeviceId]`
+ * > effective path of `workingDirByDevice[targetDeviceId]`
* > `device.defaultCwd`
*
+ * Legacy values are plain path strings. New git-aware values may carry
+ * `git.activeWorktree`; when present, that active worktree is the effective
+ * cwd while `path` remains the source/recent entry.
+ *
* Keyed per device so switching the bound device never resolves a path that
* only exists on another machine. Persisted (server-synced) so the choice
* follows the user across sessions / ends.
*/
- workingDirByDevice?: Record<string, string>;
+ workingDirByDevice?: Record<string, WorkingDirConfigValue>;
}
/**
@@ -524,8 +530,8 @@ export interface LobeAgentAgencyConfig {
* patch touches no device entries.
*/
export const pruneWorkingDirByDeviceDeletes = (
- merged: { workingDirByDevice?: Record<string, string | undefined> } | null | undefined,
- patch: { workingDirByDevice?: Record<string, string | undefined> } | null | undefined,
+ merged: { workingDirByDevice?: Record<string, unknown> } | null | undefined,
+ patch: { workingDirByDevice?: Record<string, unknown> } | null | undefined,
): void => {
const incoming = patch?.workingDirByDevice;
const target = merged?.workingDirByDevice;
diff --git a/packages/types/src/device.ts b/packages/types/src/device.ts
index fb5e869db36..a697b289145 100644
--- a/packages/types/src/device.ts
+++ b/packages/types/src/device.ts
@@ -52,14 +52,46 @@ export interface WorkspaceInitResult {
}
/**
- * A working directory a device has used. Structured (rather than a bare path
- * string) so metadata such as the detected repo type survives — a remote client
- * viewing this device can't re-probe its filesystem, so whatever isn't captured
- * here at the source is lost. Mirrors the client-local `RecentDirEntry` shape.
+ * A working directory source a device has used. Structured (rather than a bare
+ * path string) so metadata such as the detected repo type and active git
+ * worktree survives — a remote client viewing this device can't re-probe its
+ * filesystem, so whatever isn't captured here at the source is lost. Mirrors
+ * the client-local `RecentDirEntry` shape.
*/
-export interface WorkingDirEntry {
+export type WorkingDirRepoType = 'git' | 'github';
+
+export interface WorkingDirGitState {
+ /**
+ * Active checkout selected under this git source. When absent, the source
+ * path itself is the effective working directory.
+ */
+ activeWorktree?: string;
+}
+
+export interface WorkingDirConfig {
+ git?: WorkingDirGitState;
path: string;
- repoType?: 'git' | 'github';
+ repoType?: WorkingDirRepoType;
+}
+
+export type WorkingDirConfigValue = string | WorkingDirConfig;
+
+export const getWorkingDirSourcePath = (
+ entry?: WorkingDirConfigValue | null,
+): string | undefined => {
+ if (!entry) return undefined;
+ return typeof entry === 'string' ? entry : entry.path;
+};
+
+export const getWorkingDirEffectivePath = (
+ entry?: WorkingDirConfigValue | null,
+): string | undefined => {
+ if (!entry) return undefined;
+ if (typeof entry === 'string') return entry;
+ return entry.git?.activeWorktree || entry.path;
+};
+
+export interface WorkingDirEntry extends WorkingDirConfig {
/**
* Cached "workspace init" scan of this directory (AGENTS.md + project skills).
* Populated server-side at run start via `deviceGateway.initWorkspace` and
@@ -335,6 +367,12 @@ export interface DeviceGitDeleteBranchResult {
success: boolean;
}
+/** Result of the `removeGitWorktree` device RPC. Mirrors the desktop shape. */
+export interface DeviceGitRemoveWorktreeResult {
+ error?: string;
+ success: boolean;
+}
+
/**
* Repo-relative paths of dirty working-tree files for a directory on a remote
* device, returned by the `getGitWorkingTreeFiles` device RPC. Powers the Files
diff --git a/src/features/ChatInput/ControlBar/BranchSwitcher.tsx b/src/features/ChatInput/ControlBar/BranchSwitcher.tsx
index eac6e1e6fc2..78c1fc4c111 100644
--- a/src/features/ChatInput/ControlBar/BranchSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/BranchSwitcher.tsx
@@ -45,6 +45,10 @@ const styles = createStaticStyles(({ css }) => ({
text-overflow: ellipsis;
white-space: nowrap;
`,
+ triggerAnchor: css`
+ display: inline-flex;
+ flex: none;
+ `,
container: css`
display: flex;
flex-direction: column;
@@ -392,7 +396,9 @@ const BranchSwitcher = memo<BranchSwitcherProps>(
return (
<DropdownMenuRoot open={open} onOpenChange={onOpenChange}>
- <DropdownMenuTrigger>{children}</DropdownMenuTrigger>
+ <DropdownMenuTrigger className={styles.triggerAnchor}>
+ <div>{children}</div>
+ </DropdownMenuTrigger>
<DropdownMenuPortal>
<DropdownMenuPositioner placement="topLeft" sideOffset={8}>
<DropdownMenuPopup>
diff --git a/src/features/ChatInput/ControlBar/GitStatus.tsx b/src/features/ChatInput/ControlBar/GitStatus.tsx
index 868623c920f..8e1761a77df 100644
--- a/src/features/ChatInput/ControlBar/GitStatus.tsx
+++ b/src/features/ChatInput/ControlBar/GitStatus.tsx
@@ -13,11 +13,13 @@ import {
useFetchGitBranch,
useFetchGitLinkedPR,
useFetchGitWorkingTreeStatus,
+ useFetchGitWorktrees,
} from '@/store/device';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import BranchSwitcher from './BranchSwitcher';
+import WorktreeSwitcher from './WorktreeSwitcher';
const styles = createStaticStyles(({ css }) => {
return {
@@ -147,12 +149,14 @@ const styles = createStaticStyles(({ css }) => {
interface GitStatusProps {
/** When set, git status / branch switch / pull / push all run against this
* remote device via RPC. Omit for the local machine (talks over IPC). */
+ agentId: string;
deviceId?: string;
isGithub: boolean;
path: string;
+ sourcePath?: string;
}
-const GitStatus = memo<GitStatusProps>(({ path, isGithub, deviceId }) => {
+const GitStatus = memo<GitStatusProps>(({ agentId, path, sourcePath, isGithub, deviceId }) => {
const { t } = useTranslation('device');
// Transport (Electron IPC vs device RPC) is decided inside the service; the
// component just reads, identically for local and remote.
@@ -167,6 +171,7 @@ const GitStatus = memo<GitStatusProps>(({ path, isGithub, deviceId }) => {
path,
);
const { data: aheadBehind, mutate: mutateAheadBehind } = useFetchGitAheadBehind(deviceId, path);
+ const { data: worktrees = [], mutate: mutateWorktrees } = useFetchGitWorktrees(deviceId, path);
const [switcherOpen, setSwitcherOpen] = useState(false);
const [pulling, setPulling] = useState(false);
const [pushing, setPushing] = useState(false);
@@ -191,8 +196,14 @@ const GitStatus = memo<GitStatusProps>(({ path, isGithub, deviceId }) => {
}, [showRightPanel, workingSidebarTab, setWorkingSidebarTab, toggleRightPanel]);
const refreshAfterSync = useCallback(async () => {
- await Promise.all([mutateBranch(), mutatePR(), mutateWorkingStatus(), mutateAheadBehind()]);
- }, [mutateBranch, mutatePR, mutateWorkingStatus, mutateAheadBehind]);
+ await Promise.all([
+ mutateBranch(),
+ mutatePR(),
+ mutateWorkingStatus(),
+ mutateAheadBehind(),
+ mutateWorktrees(),
+ ]);
+ }, [mutateBranch, mutatePR, mutateWorkingStatus, mutateAheadBehind, mutateWorktrees]);
// Flip the displayed branch instantly on checkout. No revalidate here — the
// switcher's onAfterCheckout reconciles once the checkout lands. The linked-PR
@@ -285,7 +296,21 @@ const GitStatus = memo<GitStatusProps>(({ path, isGithub, deviceId }) => {
</div>
);
- const branchNode = detached ? (
+ const hasMultipleWorktrees = worktrees.length > 1;
+
+ const branchNode = hasMultipleWorktrees ? (
+ <WorktreeSwitcher
+ agentId={agentId}
+ currentBranch={branch}
+ detached={detached}
+ deviceId={deviceId}
+ isGithub={isGithub}
+ path={path}
+ sourcePath={sourcePath ?? path}
+ worktrees={worktrees}
+ onWorktreesChange={mutateWorktrees}
+ />
+ ) : detached ? (
// Detached HEAD → plain branch label (nothing to switch to).
<Tooltip title={branchTooltip}>{branchTrigger}</Tooltip>
) : (
diff --git a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx
index e53ee8cff90..6a37d6df62b 100644
--- a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx
+++ b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx
@@ -1,6 +1,8 @@
'use client';
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 { createStaticStyles, cssVar, cx } from 'antd-style';
import {
@@ -311,7 +313,7 @@ const WorkingDirectoryPicker = memo<WorkingDirectoryPickerProps>(({ agentId }) =
const { clear, commit } = useCommitWorkingDirectory(agentId);
const removeDeviceWorkingDir = useDeviceStore((s) => s.removeDeviceWorkingDir);
- const pick = async (entry: { path: string; repoType?: 'git' | 'github' }) => {
+ const pick = async (entry: WorkingDirEntry) => {
await commit(entry);
setOpen(false);
};
@@ -348,7 +350,7 @@ const WorkingDirectoryPicker = memo<WorkingDirectoryPickerProps>(({ agentId }) =
</Flexbox>
) : (
recents.map((entry) => {
- const isActive = entry.path === selectedDir;
+ const isActive = getWorkingDirEffectivePath(entry) === selectedDir;
return (
<Flexbox
horizontal
diff --git a/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx b/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx
index 72142a326aa..5e4b7682622 100644
--- a/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx
+++ b/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx
@@ -1,6 +1,7 @@
'use client';
import { isDesktop } from '@lobechat/const';
+import { getWorkingDirEffectivePath } from '@lobechat/types';
import { memo } from 'react';
import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';
@@ -35,8 +36,14 @@ const WorkingDirectorySection = memo<WorkingDirectorySectionProps>(({ agentId })
// Local machine probes the filesystem for repoType; a remote device's repoType
// comes from the cached `workingDirs` entry (we can't probe a remote fs here).
const localRepoType = useRepoType(isLocalDevice ? effectiveWorkingDirectory : undefined);
- const remoteDirs = useDeviceStore(deviceSelectors.getDeviceWorkingDirs(targetDeviceId));
- const remoteRepoType = remoteDirs.find((d) => d.path === effectiveWorkingDirectory)?.repoType;
+ const deviceDirs = useDeviceStore(deviceSelectors.getDeviceWorkingDirs(targetDeviceId));
+ const currentEntry = deviceDirs.find(
+ (d) =>
+ d.path === effectiveWorkingDirectory ||
+ getWorkingDirEffectivePath(d) === effectiveWorkingDirectory,
+ );
+ const sourceWorkingDirectory = currentEntry?.path ?? effectiveWorkingDirectory;
+ const remoteRepoType = currentEntry?.repoType;
const repoType = isLocalDevice ? localRepoType : remoteRepoType;
return (
@@ -44,9 +51,11 @@ const WorkingDirectorySection = memo<WorkingDirectorySectionProps>(({ agentId })
<WorkingDirectoryPicker agentId={agentId} />
{effectiveWorkingDirectory && repoType && (
<GitStatus
+ agentId={agentId}
deviceId={isLocalDevice ? undefined : targetDeviceId}
isGithub={repoType === 'github'}
path={effectiveWorkingDirectory}
+ sourcePath={sourceWorkingDirectory}
/>
)}
</>
diff --git a/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx b/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx
new file mode 100644
index 00000000000..74338eb9596
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx
@@ -0,0 +1,579 @@
+import type { DeviceGitWorktreeListItem, WorkingDirEntry } from '@lobechat/types';
+import { Icon, Tooltip } from '@lobehub/ui';
+import {
+ confirmModal,
+ DropdownMenuItem,
+ DropdownMenuPopup,
+ DropdownMenuPortal,
+ DropdownMenuPositioner,
+ DropdownMenuRoot,
+ DropdownMenuTrigger,
+} 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 { useTranslation } from 'react-i18next';
+
+import { message } from '@/components/AntdStaticMethods';
+import { gitService } from '@/services/git';
+
+import { useCommitWorkingDirectory } from './useCommitWorkingDirectory';
+
+const styles = createStaticStyles(({ css }) => ({
+ badge: css`
+ flex: none;
+
+ padding-block: 1px;
+ padding-inline: 5px;
+ border-radius: 999px;
+
+ font-size: 11px;
+ line-height: 15px;
+ color: ${cssVar.colorTextSecondary};
+
+ background: ${cssVar.colorFillSecondary};
+ `,
+ branch: css`
+ overflow: hidden;
+ flex: 0 1 auto;
+
+ min-width: 40px;
+ max-width: 300px;
+
+ font-size: 13px;
+ line-height: 18px;
+ color: ${cssVar.colorTextSecondary};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ branchInline: css`
+ overflow: hidden;
+
+ min-width: 28px;
+ max-width: 220px;
+
+ color: ${cssVar.colorText};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ check: css`
+ display: flex;
+ flex: none;
+ align-items: center;
+ justify-content: center;
+
+ width: 18px;
+
+ color: ${cssVar.colorPrimary};
+ `,
+ actionCell: css`
+ display: flex;
+ flex: none;
+ align-items: center;
+ justify-content: center;
+
+ width: 20px;
+ `,
+ container: css`
+ display: flex;
+ flex-direction: column;
+
+ width: 520px;
+ max-width: calc(100vw - 48px);
+ margin: -4px;
+ `,
+ count: css`
+ flex: none;
+
+ padding-inline: 5px;
+ border-radius: 999px;
+
+ font-size: 11px;
+ line-height: 16px;
+ color: ${cssVar.colorTextTertiary};
+
+ background: ${cssVar.colorFillSecondary};
+ `,
+ diffStat: css`
+ display: inline-flex;
+ flex: none;
+ gap: 3px;
+ justify-content: flex-end;
+
+ font-variant-numeric: tabular-nums;
+ line-height: 1;
+ `,
+ diffStatAdded: css`
+ color: ${cssVar.colorSuccess};
+ `,
+ diffStatDeleted: css`
+ color: ${cssVar.colorError};
+ `,
+ diffStatModified: css`
+ color: ${cssVar.colorWarning};
+ `,
+ emptyState: css`
+ padding-block: 16px;
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ text-align: center;
+ `,
+ header: css`
+ display: flex;
+ gap: 12px;
+ align-items: center;
+ justify-content: space-between;
+
+ padding-block: 8px;
+ padding-inline: 12px;
+ border-block-end: 1px solid ${cssVar.colorSplit};
+ `,
+ headerMeta: css`
+ flex: none;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ headerSubtitle: css`
+ margin-block-start: 1px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ headerTitle: css`
+ font-weight: 600;
+ color: ${cssVar.colorText};
+ `,
+ item: css`
+ cursor: pointer;
+
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) minmax(44px, auto) 20px;
+ gap: 10px;
+ align-items: center;
+
+ min-height: 48px;
+ padding-block: 6px;
+ padding-inline: 8px;
+ border-radius: 8px;
+
+ font-size: 13px;
+ color: ${cssVar.colorText};
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+
+ &:hover .worktree-row-action {
+ display: flex;
+ }
+
+ &[data-current='true'] {
+ background: ${cssVar.colorFillSecondary};
+ }
+
+ &[aria-disabled='true'] {
+ cursor: not-allowed;
+ opacity: 0.55;
+ }
+ `,
+ itemMain: css`
+ overflow: hidden;
+ min-width: 0;
+ `,
+ dirtyCell: css`
+ display: flex;
+ flex: none;
+ align-items: center;
+ justify-content: flex-end;
+
+ min-width: 44px;
+ `,
+ list: css`
+ overflow-y: auto;
+ max-height: 360px;
+ padding: 6px;
+ `,
+ name: css`
+ overflow: hidden;
+ flex: 0 1 auto;
+
+ max-width: 240px;
+
+ font-size: 13px;
+ font-weight: 400;
+ line-height: 18px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ path: css`
+ overflow: hidden;
+
+ margin-block-start: 1px;
+
+ font-size: 11px;
+ line-height: 16px;
+ color: ${cssVar.colorTextTertiary};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ rowTitle: css`
+ overflow: hidden;
+ display: flex;
+ gap: 6px;
+ align-items: center;
+
+ min-width: 0;
+
+ white-space: nowrap;
+ `,
+ rowAction: css`
+ cursor: pointer;
+
+ display: none;
+ align-items: center;
+ justify-content: center;
+
+ width: 20px;
+ height: 20px;
+ border-radius: 4px;
+
+ color: ${cssVar.colorTextTertiary};
+
+ transition: all 0.2s;
+
+ &:hover {
+ color: ${cssVar.colorError};
+ background: ${cssVar.colorErrorBg};
+ }
+ `,
+ trigger: css`
+ cursor: pointer;
+
+ display: inline-flex;
+ flex: none;
+ gap: 5px;
+ align-items: center;
+
+ max-width: 420px;
+ padding-block: 2px;
+ padding-inline: 4px;
+ border-radius: 4px;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ white-space: nowrap;
+
+ transition: background 0.2s;
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ triggerAnchor: css`
+ display: inline-flex;
+ flex: none;
+ `,
+ worktreeName: css`
+ overflow: hidden;
+ max-width: 140px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+}));
+
+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 => {
+ const normalized = normalizeDisplayPath(path);
+ return TEMP_PATH_PREFIXES.some(
+ (prefix) => normalized === prefix || normalized.startsWith(`${prefix}/`),
+ );
+};
+
+const getRelativeDisplayPath = (targetPath: string, sourcePath: string): string => {
+ if (!targetPath || !sourcePath || isTempPath(targetPath)) return targetPath;
+
+ const target = normalizeDisplayPath(targetPath);
+ const source = normalizeDisplayPath(sourcePath);
+ if (!target.startsWith('/') || !source.startsWith('/')) return targetPath;
+ if (target === source) return targetPath;
+
+ const targetParts = target.split('/').filter(Boolean);
+ const sourceParts = source.split('/').filter(Boolean);
+ let commonLength = 0;
+ while (
+ commonLength < targetParts.length &&
+ commonLength < sourceParts.length &&
+ targetParts[commonLength] === sourceParts[commonLength]
+ ) {
+ commonLength += 1;
+ }
+
+ if (commonLength < 2) return targetPath;
+
+ const parentSteps = Array.from({ length: sourceParts.length - commonLength }, () => '..');
+ const relativeParts = [...parentSteps, ...targetParts.slice(commonLength)];
+
+ return relativeParts.length > 0 ? relativeParts.join('/') : '.';
+};
+
+const getShortHead = (head?: string): string | undefined => head?.slice(0, 7);
+
+const getWorktreeBranch = (
+ worktree: DeviceGitWorktreeListItem,
+ fallbackBranch: string,
+ detachedLabel: (sha: string) => string,
+): string => {
+ if (worktree.branch) return worktree.branch;
+ const head = getShortHead(worktree.head);
+ if (worktree.detached && head) return detachedLabel(head);
+ return fallbackBranch;
+};
+
+const isDisabled = (worktree: DeviceGitWorktreeListItem): boolean =>
+ !!worktree.bare || !!worktree.prunable;
+
+const canRemoveWorktree = (worktree: DeviceGitWorktreeListItem): boolean =>
+ !!worktree.detached && !worktree.current && !worktree.locked && !isDisabled(worktree);
+
+interface DirtyStatProps {
+ status?: DeviceGitWorktreeListItem['status'];
+}
+
+const DirtyStat = memo<DirtyStatProps>(({ status }) => {
+ if (!status || status.clean) return null;
+
+ return (
+ <span className={styles.diffStat}>
+ {status.added > 0 && <span className={styles.diffStatAdded}>+{status.added}</span>}
+ {status.modified > 0 && <span className={styles.diffStatModified}>±{status.modified}</span>}
+ {status.deleted > 0 && <span className={styles.diffStatDeleted}>-{status.deleted}</span>}
+ </span>
+ );
+});
+
+DirtyStat.displayName = 'DirtyStat';
+
+interface WorktreeSwitcherProps {
+ agentId: string;
+ currentBranch: string;
+ detached?: boolean;
+ deviceId?: string;
+ isGithub: boolean;
+ onWorktreesChange?: () => Promise<unknown> | unknown;
+ path: string;
+ sourcePath: string;
+ worktrees: DeviceGitWorktreeListItem[];
+}
+
+const WorktreeSwitcher = memo<WorktreeSwitcherProps>(
+ ({
+ agentId,
+ currentBranch,
+ detached,
+ deviceId,
+ isGithub,
+ onWorktreesChange,
+ path,
+ sourcePath,
+ worktrees,
+ }) => {
+ const { t } = useTranslation('device');
+ const { t: tCommon } = useTranslation('common');
+ const [open, setOpen] = useState(false);
+ const { commit } = useCommitWorkingDirectory(agentId);
+
+ const currentWorktree = useMemo(
+ () =>
+ worktrees.find((worktree) => worktree.current) ?? worktrees.find((w) => w.path === path),
+ [path, worktrees],
+ );
+
+ const currentPath = currentWorktree?.path ?? path;
+ const currentName = getPathName(currentPath);
+ const branchLabel = currentWorktree
+ ? getWorktreeBranch(currentWorktree, currentBranch, (sha) =>
+ t('workingDirectory.detachedHeadShort', { sha }),
+ )
+ : currentBranch;
+
+ const commitWorktree = useCallback(
+ async (worktree: DeviceGitWorktreeListItem) => {
+ if (worktree.current || isDisabled(worktree)) {
+ setOpen(false);
+ return;
+ }
+
+ const entry: WorkingDirEntry = {
+ ...(worktree.path === sourcePath ? {} : { git: { activeWorktree: worktree.path } }),
+ path: sourcePath,
+ repoType: isGithub ? 'github' : 'git',
+ };
+ await commit(entry);
+ setOpen(false);
+ },
+ [commit, isGithub, sourcePath],
+ );
+
+ const handleRemoveWorktree = useCallback(
+ (event: MouseEvent, worktree: DeviceGitWorktreeListItem) => {
+ event.stopPropagation();
+ setOpen(false);
+ confirmModal({
+ cancelText: tCommon('cancel'),
+ content: t('workingDirectory.removeWorktreeConfirm', {
+ name: getPathName(worktree.path),
+ }),
+ okButtonProps: { danger: true },
+ okText: tCommon('delete'),
+ onOk: async () => {
+ const result = await gitService.removeGitWorktree({
+ deviceId,
+ path,
+ worktreePath: worktree.path,
+ });
+ if (result.success) {
+ message.success(t('workingDirectory.removeWorktreeSuccess'));
+ await onWorktreesChange?.();
+ return;
+ }
+ message.error(result.error || t('workingDirectory.removeWorktreeFailed'));
+ },
+ title: t('workingDirectory.removeWorktreeTitle'),
+ });
+ },
+ [deviceId, onWorktreesChange, path, t, tCommon],
+ );
+
+ const triggerTitle = detached
+ ? t('workingDirectory.detachedHead', { sha: currentBranch })
+ : `${currentName} · ${branchLabel}`;
+
+ const trigger = (
+ <div className={styles.trigger}>
+ <Icon icon={GitForkIcon} size={12} />
+ <span className={styles.worktreeName}>{currentName}</span>
+ <span className={styles.branchInline}>{branchLabel}</span>
+ <span className={styles.count}>{worktrees.length}</span>
+ </div>
+ );
+
+ return (
+ <DropdownMenuRoot open={open} onOpenChange={setOpen}>
+ <DropdownMenuTrigger className={styles.triggerAnchor}>
+ <div>{open ? trigger : <Tooltip title={triggerTitle}>{trigger}</Tooltip>}</div>
+ </DropdownMenuTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuPositioner placement="topLeft" sideOffset={8}>
+ <DropdownMenuPopup>
+ <div className={styles.container}>
+ <div className={styles.header}>
+ <div>
+ <div className={styles.headerTitle}>
+ {t('workingDirectory.worktreesHeading')}
+ </div>
+ <div className={styles.headerSubtitle}>
+ {t('workingDirectory.worktreeSwitchDescription')}
+ </div>
+ </div>
+ <div className={styles.headerMeta}>
+ {t('workingDirectory.worktreeCount', { count: worktrees.length })}
+ </div>
+ </div>
+
+ <div className={styles.list}>
+ {worktrees.length === 0 ? (
+ <div className={styles.emptyState}>{t('workingDirectory.worktreesEmpty')}</div>
+ ) : (
+ worktrees.map((worktree) => {
+ const branch = getWorktreeBranch(worktree, currentBranch, (sha) =>
+ t('workingDirectory.detachedHeadShort', { sha }),
+ );
+ const displayPath = getRelativeDisplayPath(worktree.path, sourcePath);
+ const disabled = isDisabled(worktree);
+ const removable = canRemoveWorktree(worktree);
+
+ return (
+ <DropdownMenuItem
+ aria-disabled={disabled}
+ className={styles.item}
+ closeOnClick={false}
+ data-current={worktree.current}
+ key={worktree.path}
+ onClick={() => void commitWorktree(worktree)}
+ >
+ <div className={styles.itemMain}>
+ <div className={styles.rowTitle}>
+ <span className={styles.name}>{getPathName(worktree.path)}</span>
+ <span className={styles.branch}>{branch}</span>
+ {worktree.current && (
+ <span className={styles.badge}>
+ {t('workingDirectory.currentWorktree')}
+ </span>
+ )}
+ {worktree.detached && (
+ <span className={styles.badge}>
+ {t('workingDirectory.detachedWorktree')}
+ </span>
+ )}
+ {worktree.locked && (
+ <span className={styles.badge}>
+ {t('workingDirectory.lockedWorktree')}
+ </span>
+ )}
+ {worktree.prunable && (
+ <span className={styles.badge}>
+ {t('workingDirectory.prunableWorktree')}
+ </span>
+ )}
+ {worktree.bare && (
+ <span className={styles.badge}>
+ {t('workingDirectory.bareWorktree')}
+ </span>
+ )}
+ </div>
+ <div className={styles.path} title={worktree.path}>
+ {displayPath}
+ </div>
+ </div>
+ <div className={styles.dirtyCell}>
+ <DirtyStat status={worktree.status} />
+ </div>
+ <div className={styles.actionCell}>
+ {worktree.current ? (
+ <Icon className={styles.check} icon={CheckIcon} size={14} />
+ ) : (
+ removable && (
+ <Tooltip title={t('workingDirectory.removeWorktreeAction')}>
+ <div
+ aria-label={t('workingDirectory.removeWorktreeAction')}
+ className={`${styles.rowAction} worktree-row-action`}
+ role="button"
+ onClick={(event) => handleRemoveWorktree(event, worktree)}
+ >
+ <Icon icon={Trash2Icon} size={13} />
+ </div>
+ </Tooltip>
+ )
+ )}
+ </div>
+ </DropdownMenuItem>
+ );
+ })
+ )}
+ </div>
+ </div>
+ </DropdownMenuPopup>
+ </DropdownMenuPositioner>
+ </DropdownMenuPortal>
+ </DropdownMenuRoot>
+ );
+ },
+);
+
+WorktreeSwitcher.displayName = 'WorktreeSwitcher';
+
+export default WorktreeSwitcher;
diff --git a/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx b/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx
index 7c0e4ac9430..602b859a7d2 100644
--- a/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx
+++ b/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx
@@ -18,21 +18,28 @@ const gitHookMocks = vi.hoisted(() => ({
mutateBranch: vi.fn(),
mutatePR: vi.fn(),
mutateWorkingTreeStatus: vi.fn(),
+ mutateWorktrees: vi.fn(),
useFetchGitAheadBehind: vi.fn(),
useFetchGitBranch: vi.fn(),
useFetchGitLinkedPR: vi.fn(),
useFetchGitWorkingTreeStatus: vi.fn(),
+ useFetchGitWorktrees: vi.fn(),
}));
vi.mock('../BranchSwitcher', () => ({
default: ({ children }: { children: ReactNode }) => <>{children}</>,
}));
+vi.mock('../WorktreeSwitcher', () => ({
+ default: () => <span data-testid="worktree-switcher" />,
+}));
+
vi.mock('@/store/device', () => ({
useFetchGitAheadBehind: gitHookMocks.useFetchGitAheadBehind,
useFetchGitBranch: gitHookMocks.useFetchGitBranch,
useFetchGitLinkedPR: gitHookMocks.useFetchGitLinkedPR,
useFetchGitWorkingTreeStatus: gitHookMocks.useFetchGitWorkingTreeStatus,
+ useFetchGitWorktrees: gitHookMocks.useFetchGitWorktrees,
}));
vi.mock('@/store/global', () => ({
@@ -105,11 +112,15 @@ beforeEach(() => {
data: undefined,
mutate: gitHookMocks.mutateAheadBehind,
});
+ gitHookMocks.useFetchGitWorktrees.mockReturnValue({
+ data: [],
+ mutate: gitHookMocks.mutateWorktrees,
+ });
});
describe('GitStatus', () => {
it('opens the review panel when clicking remote device diff stats', () => {
- render(<GitStatus deviceId="device-1" isGithub={false} path="/repo" />);
+ render(<GitStatus agentId="agent-1" deviceId="device-1" isGithub={false} path="/repo" />);
fireEvent.click(screen.getByRole('button'));
diff --git a/src/features/ChatInput/ControlBar/__tests__/WorktreeSwitcher.test.tsx b/src/features/ChatInput/ControlBar/__tests__/WorktreeSwitcher.test.tsx
new file mode 100644
index 00000000000..3f03e7724e1
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/__tests__/WorktreeSwitcher.test.tsx
@@ -0,0 +1,293 @@
+import { fireEvent, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import WorktreeSwitcher from '../WorktreeSwitcher';
+
+const commitMock = vi.hoisted(() => vi.fn());
+const confirmModalMock = vi.hoisted(() => vi.fn());
+const messageErrorMock = vi.hoisted(() => vi.fn());
+const messageSuccessMock = vi.hoisted(() => vi.fn());
+const removeGitWorktreeMock = vi.hoisted(() => vi.fn());
+
+vi.mock('../useCommitWorkingDirectory', () => ({
+ useCommitWorkingDirectory: () => ({ commit: commitMock }),
+}));
+
+vi.mock('@/components/AntdStaticMethods', () => ({
+ message: {
+ error: messageErrorMock,
+ success: messageSuccessMock,
+ },
+}));
+
+vi.mock('@/services/git', () => ({
+ gitService: {
+ removeGitWorktree: removeGitWorktreeMock,
+ },
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ Icon: () => <span data-testid="icon" />,
+ Tooltip: ({ children }: { children: ReactNode }) => (
+ <span data-testid="worktree-tooltip">{children}</span>
+ ),
+}));
+
+vi.mock('@lobehub/ui/base-ui', () => ({
+ confirmModal: confirmModalMock,
+ DropdownMenuItem: ({ children, onClick }: { children: ReactNode; onClick?: () => void }) => (
+ <button onClick={onClick}>{children}</button>
+ ),
+ DropdownMenuPopup: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ DropdownMenuPortal: ({ children }: { children: ReactNode }) => <>{children}</>,
+ DropdownMenuPositioner: ({ children }: { children: ReactNode }) => <>{children}</>,
+ DropdownMenuRoot: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ DropdownMenuTrigger: ({ children, className }: { children: ReactNode; className?: string }) => (
+ <div className={className} data-testid="worktree-dropdown-trigger">
+ {children}
+ </div>
+ ),
+}));
+
+vi.mock('antd-style', () => ({
+ createStaticStyles: () => ({}),
+ cssVar: new Proxy({}, { get: () => 'var(--mock)' }),
+ cx: (...classes: string[]) => classes.filter(Boolean).join(' '),
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, values?: Record<string, unknown>) =>
+ values ? `${key}:${JSON.stringify(values)}` : key,
+ }),
+}));
+
+beforeEach(() => {
+ commitMock.mockReset();
+ confirmModalMock.mockReset();
+ messageErrorMock.mockReset();
+ messageSuccessMock.mockReset();
+ removeGitWorktreeMock.mockReset();
+ removeGitWorktreeMock.mockResolvedValue({ success: true });
+});
+
+describe('WorktreeSwitcher', () => {
+ it('keeps the dropdown trigger anchored to a stable DOM wrapper', () => {
+ render(
+ <WorktreeSwitcher
+ isGithub
+ agentId="agent-1"
+ currentBranch="feat/current"
+ path="/repo"
+ sourcePath="/repo"
+ worktrees={[
+ {
+ branch: 'feat/current',
+ current: true,
+ path: '/repo',
+ status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },
+ },
+ {
+ branch: 'canary',
+ current: false,
+ path: '/repo-canary',
+ status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },
+ },
+ ]}
+ />,
+ );
+
+ expect(screen.getByTestId('worktree-dropdown-trigger').firstElementChild?.tagName).toBe('DIV');
+ expect(screen.getByTestId('worktree-tooltip')).toBeTruthy();
+ });
+
+ it('renders dirty stats and omits clean labels in the worktree list', () => {
+ render(
+ <WorktreeSwitcher
+ isGithub
+ agentId="agent-1"
+ currentBranch="feat/current"
+ path="/repo"
+ sourcePath="/repo"
+ worktrees={[
+ {
+ branch: 'feat/current',
+ current: true,
+ path: '/repo',
+ status: { added: 2, clean: false, deleted: 1, modified: 3, total: 6 },
+ },
+ {
+ branch: 'canary',
+ current: false,
+ path: '/repo-canary',
+ status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },
+ },
+ ]}
+ />,
+ );
+
+ expect(screen.getByText('+2')).toBeTruthy();
+ expect(screen.getByText('±3')).toBeTruthy();
+ expect(screen.getByText('-1')).toBeTruthy();
+ expect(screen.getByText('+2').parentElement?.parentElement?.textContent).toBe('+2±3-1');
+ expect(
+ screen.getByText('workingDirectory.currentWorktree').parentElement?.textContent,
+ ).toContain('feat/current');
+ expect(screen.queryByText('workingDirectory.clean')).toBeNull();
+ });
+
+ it('shows worktree paths relative to the source path except temp paths', () => {
+ render(
+ <WorktreeSwitcher
+ isGithub
+ agentId="agent-1"
+ currentBranch="feat/current"
+ path="/Users/me/projects/project"
+ sourcePath="/Users/me/projects/project"
+ worktrees={[
+ {
+ branch: 'feat/current',
+ current: true,
+ path: '/Users/me/projects/project',
+ status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },
+ },
+ {
+ branch: 'canary',
+ current: false,
+ path: '/Users/me/projects/project-fix',
+ status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },
+ },
+ {
+ branch: 'scratch',
+ current: false,
+ path: '/tmp/project-scratch',
+ status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },
+ },
+ ]}
+ />,
+ );
+
+ expect(screen.getByText('/Users/me/projects/project')).toBeTruthy();
+ expect(screen.getByText('../project-fix')).toBeTruthy();
+ expect(screen.getByText('/tmp/project-scratch')).toBeTruthy();
+ });
+
+ it('confirms and removes a detached non-current worktree', async () => {
+ const onWorktreesChange = vi.fn();
+ render(
+ <WorktreeSwitcher
+ isGithub
+ agentId="agent-1"
+ currentBranch="feat/current"
+ deviceId="device-1"
+ path="/repo"
+ sourcePath="/repo"
+ worktrees={[
+ {
+ branch: 'feat/current',
+ current: true,
+ path: '/repo',
+ status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },
+ },
+ {
+ current: false,
+ detached: true,
+ head: '4f46abcdef',
+ path: '/repo-detached',
+ status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },
+ },
+ {
+ branch: 'canary',
+ current: false,
+ path: '/repo-canary',
+ status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },
+ },
+ ]}
+ onWorktreesChange={onWorktreesChange}
+ />,
+ );
+
+ expect(screen.getAllByLabelText('workingDirectory.removeWorktreeAction')).toHaveLength(1);
+
+ fireEvent.click(screen.getByLabelText('workingDirectory.removeWorktreeAction'));
+
+ expect(commitMock).not.toHaveBeenCalled();
+ expect(confirmModalMock).toHaveBeenCalledTimes(1);
+
+ await confirmModalMock.mock.calls[0][0].onOk();
+
+ expect(removeGitWorktreeMock).toHaveBeenCalledWith({
+ deviceId: 'device-1',
+ path: '/repo',
+ worktreePath: '/repo-detached',
+ });
+ expect(onWorktreesChange).toHaveBeenCalled();
+ expect(messageSuccessMock).toHaveBeenCalledWith('workingDirectory.removeWorktreeSuccess');
+ expect(messageErrorMock).not.toHaveBeenCalled();
+ });
+
+ it('commits the selected worktree path as the working directory', () => {
+ render(
+ <WorktreeSwitcher
+ isGithub
+ agentId="agent-1"
+ currentBranch="feat/current"
+ path="/repo"
+ sourcePath="/repo"
+ worktrees={[
+ {
+ branch: 'feat/current',
+ current: true,
+ path: '/repo',
+ status: { added: 1, clean: false, deleted: 0, modified: 0, total: 1 },
+ },
+ {
+ branch: 'canary',
+ current: false,
+ path: '/repo-canary',
+ status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },
+ },
+ ]}
+ />,
+ );
+
+ fireEvent.click(screen.getByText('/repo-canary'));
+
+ expect(commitMock).toHaveBeenCalledWith({
+ git: { activeWorktree: '/repo-canary' },
+ path: '/repo',
+ repoType: 'github',
+ });
+ });
+
+ it('clears the active worktree when selecting the source worktree', () => {
+ render(
+ <WorktreeSwitcher
+ agentId="agent-1"
+ currentBranch="feat/current"
+ isGithub={false}
+ path="/repo-canary"
+ sourcePath="/repo"
+ worktrees={[
+ {
+ branch: 'feat/current',
+ current: false,
+ path: '/repo',
+ status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },
+ },
+ {
+ branch: 'canary',
+ current: true,
+ path: '/repo-canary',
+ status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },
+ },
+ ]}
+ />,
+ );
+
+ fireEvent.click(screen.getByTitle('/repo'));
+
+ expect(commitMock).toHaveBeenCalledWith({ path: '/repo', repoType: 'git' });
+ });
+});
diff --git a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts
index 876bade5f2a..2424e98e244 100644
--- a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts
+++ b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts
@@ -1,7 +1,14 @@
-import type { WorkingDirEntry } from '@lobechat/types';
+import type {
+ LobeAgentConfig,
+ WorkingDirConfig,
+ WorkingDirConfigValue,
+ WorkingDirEntry,
+} from '@lobechat/types';
+import { getWorkingDirEffectivePath } from '@lobechat/types';
import { confirmModal } from '@lobehub/ui/base-ui';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
+import type { PartialDeep } from 'type-fest';
import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';
import { useAgentStore } from '@/store/agent';
@@ -11,6 +18,31 @@ import { topicSelectors } from '@/store/chat/selectors';
import { useDeviceStore } from '@/store/device';
import { useElectronStore } from '@/store/electron';
+const normalizeWorkingDirEntry = (entry: WorkingDirEntry): WorkingDirEntry | undefined => {
+ const path = entry.path.trim();
+ if (!path) return undefined;
+
+ const activeWorktree = entry.git?.activeWorktree?.trim();
+ const next: WorkingDirEntry = { ...entry, path };
+
+ if (activeWorktree) {
+ next.git = { ...entry.git, activeWorktree };
+ } else if (next.git) {
+ const git = { ...next.git };
+ delete git.activeWorktree;
+ if (Object.keys(git).length > 0) next.git = git;
+ else delete next.git;
+ }
+
+ return next;
+};
+
+const toAgentWorkingDirConfig = (entry: WorkingDirEntry): WorkingDirConfig => ({
+ ...(entry.git ? { git: entry.git } : {}),
+ path: entry.path,
+ ...(entry.repoType ? { repoType: entry.repoType } : {}),
+});
+
/**
* Unified working-directory writes, shared by the directory picker for both
* local and remote runs.
@@ -51,24 +83,39 @@ export const useCommitWorkingDirectory = (agentId: string) => {
const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId);
const writeCwd = useCallback(
- async (newPath: string, entry?: WorkingDirEntry) => {
+ async (entry?: WorkingDirEntry) => {
+ const effectivePath = getWorkingDirEffectivePath(entry);
// Topic override wins once a conversation exists; otherwise persist the
// agent's per-device choice so a new topic inherits it.
if (activeTopicId) {
- await updateTopicMetadata(activeTopicId, { workingDirectory: newPath });
- } else if (targetDeviceId) {
- const prev = agencyConfig?.workingDirByDevice ?? {};
- await updateAgentConfigById(agentId, {
- agencyConfig: {
- ...agencyConfig,
- workingDirByDevice: { ...prev, [targetDeviceId]: newPath },
- },
- });
+ await updateTopicMetadata(activeTopicId, { workingDirectory: effectivePath });
+ } else {
+ if (targetDeviceId) {
+ const prev = agencyConfig?.workingDirByDevice ?? {};
+ // Clearing sends `undefined` rather than dropping the key: deep-merge
+ // (client store + server persist) can't remove a key, so the delete is
+ // carried as an explicit `undefined` and pruned after each merge.
+ const nextMap: Record<string, WorkingDirConfigValue | undefined> = {
+ ...prev,
+ [targetDeviceId]: entry ? toAgentWorkingDirConfig(entry) : undefined,
+ };
+ const configPatch = {
+ agencyConfig: { ...agencyConfig, workingDirByDevice: nextMap },
+ } as PartialDeep<LobeAgentConfig>;
+ await updateAgentConfigById(agentId, configPatch);
+ }
+ // Clearing the agent default must also drop the legacy per-agent value —
+ // otherwise it keeps re-supplying a stale cwd from a lower precedence
+ // level and Clear looks dead. (Only clears the localStorage map; no
+ // network round-trip since `workingDirectory` is stripped before send.)
+ if (!effectivePath && legacyAgentWorkingDirectory) {
+ await updateAgentRuntimeEnvConfigById(agentId, { workingDirectory: undefined });
+ }
}
// Record on the target device's recent list (not the device-wide default —
// a per-agent pick shouldn't repoint other agents on the same device).
- if (entry && targetDeviceId) {
- await updateDeviceCwd(targetDeviceId, { ...entry, path: newPath }, { setDefault: false });
+ if (entry && effectivePath && targetDeviceId) {
+ await updateDeviceCwd(targetDeviceId, entry, { setDefault: false });
}
},
[
@@ -76,7 +123,9 @@ export const useCommitWorkingDirectory = (agentId: string) => {
agencyConfig,
activeTopicId,
targetDeviceId,
+ legacyAgentWorkingDirectory,
updateAgentConfigById,
+ updateAgentRuntimeEnvConfigById,
updateTopicMetadata,
updateDeviceCwd,
],
@@ -98,13 +147,14 @@ export const useCommitWorkingDirectory = (agentId: string) => {
// per-device map from the legacy slot, so clear both together to avoid a
// dead second click.
if (targetDeviceId && agencyConfig?.workingDirByDevice?.[targetDeviceId]) {
- const nextMap: Record<string, string | undefined> = {
+ const nextMap: Record<string, WorkingDirConfigValue | undefined> = {
...agencyConfig.workingDirByDevice,
[targetDeviceId]: undefined,
};
- await updateAgentConfigById(agentId, {
+ const configPatch = {
agencyConfig: { ...agencyConfig, workingDirByDevice: nextMap },
- });
+ } as PartialDeep<LobeAgentConfig>;
+ await updateAgentConfigById(agentId, configPatch);
}
// (Only clears the localStorage map; no network round-trip since
// `workingDirectory` is stripped before send.)
@@ -126,14 +176,15 @@ export const useCommitWorkingDirectory = (agentId: string) => {
/** Pick a directory (with the CC-session-reset guard). */
const commit = useCallback(
async (entry: WorkingDirEntry) => {
- const newPath = entry.path.trim();
- if (!newPath) return;
+ const normalizedEntry = normalizeWorkingDirEntry(entry);
+ const effectivePath = getWorkingDirEffectivePath(normalizedEntry);
+ if (!normalizedEntry || !effectivePath) return;
- const run = () => writeCwd(newPath, entry);
+ const run = () => writeCwd(normalizedEntry);
const priorSessionId = activeTopic?.metadata?.heteroSessionId;
const priorCwd = activeTopic?.metadata?.workingDirectory;
- if (priorSessionId && priorCwd && priorCwd !== newPath) {
+ if (priorSessionId && priorCwd && priorCwd !== effectivePath) {
confirmModal({
cancelText: t('heteroAgent.switchCwd.cancel', { ns: 'chat' }),
content: t('heteroAgent.switchCwd.content', { ns: 'chat' }),
diff --git a/src/features/ChatInput/ControlBar/useRepoType.ts b/src/features/ChatInput/ControlBar/useRepoType.ts
index 449438412bc..f20c3cdc8ca 100644
--- a/src/features/ChatInput/ControlBar/useRepoType.ts
+++ b/src/features/ChatInput/ControlBar/useRepoType.ts
@@ -1,4 +1,5 @@
import { isDesktop } from '@lobechat/const';
+import { getWorkingDirEffectivePath } from '@lobechat/types';
import { useEffect, useMemo } from 'react';
import useSWR from 'swr';
@@ -31,7 +32,7 @@ export const useRepoType = (path?: string, deviceId?: string): RepoType => {
path
? deviceSelectors
.getDeviceWorkingDirs(deviceId)(s)
- .find((d) => d.path === path)?.repoType
+ .find((d) => d.path === path || getWorkingDirEffectivePath(d) === path)?.repoType
: undefined,
);
diff --git a/src/helpers/agentWorkingDirectory.test.ts b/src/helpers/agentWorkingDirectory.test.ts
index d66b0ca9bc0..5aac460b42e 100644
--- a/src/helpers/agentWorkingDirectory.test.ts
+++ b/src/helpers/agentWorkingDirectory.test.ts
@@ -26,10 +26,7 @@ describe('resolveTargetDeviceId', () => {
it('does not use stale bindings for sandbox targets', () => {
expect(
- resolveTargetDeviceId(
- cfg({ boundDeviceId: 'dev-1', executionTarget: 'sandbox' }),
- undefined,
- ),
+ resolveTargetDeviceId(cfg({ boundDeviceId: 'dev-1', executionTarget: 'sandbox' }), undefined),
).toBeUndefined();
});
@@ -87,6 +84,19 @@ describe('resolveAgentWorkingDirectory', () => {
);
});
+ it('uses the active worktree from the per-device source entry as the effective cwd', () => {
+ const agencyConfig = cfg({
+ executionTarget: 'local',
+ workingDirByDevice: {
+ cur: { git: { activeWorktree: '/repo-fix' }, path: '/repo', repoType: 'git' },
+ },
+ });
+
+ expect(resolveAgentWorkingDirectory({ agencyConfig, currentDeviceId: 'cur' })).toBe(
+ '/repo-fix',
+ );
+ });
+
it('ignores the per-device choice when the target device has no entry', () => {
const agencyConfig = cfg({
executionTarget: 'local',
diff --git a/src/helpers/agentWorkingDirectory.ts b/src/helpers/agentWorkingDirectory.ts
index 5b0567c8b12..e7760c7fc3f 100644
--- a/src/helpers/agentWorkingDirectory.ts
+++ b/src/helpers/agentWorkingDirectory.ts
@@ -1,4 +1,5 @@
import type { LobeAgentAgencyConfig } from '@lobechat/types';
+import { getWorkingDirEffectivePath } from '@lobechat/types';
/**
* The device a run targets: an explicitly bound remote device, this machine,
@@ -46,7 +47,7 @@ export const resolveAgentWorkingDirectory = (params: {
} = params;
const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId);
const agentChoice = targetDeviceId
- ? agencyConfig?.workingDirByDevice?.[targetDeviceId]
+ ? getWorkingDirEffectivePath(agencyConfig?.workingDirByDevice?.[targetDeviceId])
: undefined;
return (
topicWorkingDirectory ||
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index a9c2530ed8f..8d7dc384b74 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -483,6 +483,11 @@ export const deviceKeys = {
deviceId,
path,
]),
+ gitWorktrees: def('device:gitWorktrees', (deviceId: string, path: string) => [
+ 'device:gitWorktrees',
+ deviceId,
+ path,
+ ]),
listDevices: def('device:listDevices', () => ['device:listDevices']),
repoType: def('device:repoType', (path: string) => ['device:repoType', path]),
};
diff --git a/src/services/electron/git.ts b/src/services/electron/git.ts
index 5c8ef273d88..9d108b87f6a 100644
--- a/src/services/electron/git.ts
+++ b/src/services/electron/git.ts
@@ -11,6 +11,7 @@ import {
type GitPullResult,
type GitPushResult,
type GitRemoteBranchListItem,
+ type GitRemoveWorktreeResult,
type GitRenameBranchResult,
type GitWorkingTreeFiles,
type GitWorkingTreePatches,
@@ -108,6 +109,13 @@ class ElectronGitService {
async deleteGitBranch(params: { branch: string; path: string }): Promise<GitDeleteBranchResult> {
return this.ipc.git.deleteGitBranch(params);
}
+
+ async removeGitWorktree(params: {
+ path: string;
+ worktreePath: string;
+ }): Promise<GitRemoveWorktreeResult> {
+ return this.ipc.git.removeGitWorktree(params);
+ }
}
export const electronGitService = new ElectronGitService();
diff --git a/src/services/git.ts b/src/services/git.ts
index a3184e21cfe..d36021951d1 100644
--- a/src/services/git.ts
+++ b/src/services/git.ts
@@ -11,6 +11,7 @@ import type {
DeviceGitCheckoutResult,
DeviceGitDeleteBranchResult,
DeviceGitLinkedPullRequest,
+ DeviceGitRemoveWorktreeResult,
DeviceGitRenameBranchResult,
DeviceGitSyncResult,
DeviceGitWorkingTreeStatus,
@@ -103,6 +104,21 @@ class GitService {
: electronGitService.deleteGitBranch({ branch, path });
}
+ /** Remove a detached worktree from a working directory's repository. */
+ removeGitWorktree({
+ deviceId,
+ path,
+ worktreePath,
+ }: {
+ deviceId?: string;
+ path: string;
+ worktreePath: string;
+ }): Promise<DeviceGitRemoveWorktreeResult> {
+ return deviceId
+ ? lambdaClient.device.removeGitWorktree.mutate({ deviceId, path, worktreePath })
+ : electronGitService.removeGitWorktree({ path, worktreePath });
+ }
+
/** Pull (`--ff-only`) the current branch of a working directory. */
pullGitBranch({
deviceId,
diff --git a/src/store/agent/selectors/agentByIdSelectors.ts b/src/store/agent/selectors/agentByIdSelectors.ts
index 200e98911f7..23728b30221 100644
--- a/src/store/agent/selectors/agentByIdSelectors.ts
+++ b/src/store/agent/selectors/agentByIdSelectors.ts
@@ -3,6 +3,7 @@ import { DEFAULT_MODEL, DEFAUTT_AGENT_TTS_CONFIG, isDesktop } from '@lobechat/co
import { type AgentBuilderContext } from '@lobechat/context-engine';
import {
type AgentMode,
+ getWorkingDirEffectivePath,
type LobeAgentAgencyConfig,
type LobeAgentTTSConfig,
type RuntimeEnvConfig,
@@ -121,7 +122,7 @@ const getAgentWorkingDirectoryById =
const agencyConfig = agentSelectors.getAgentConfigById(agentId)(s)?.agencyConfig;
const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId);
const agentChoice = targetDeviceId
- ? agencyConfig?.workingDirByDevice?.[targetDeviceId]
+ ? getWorkingDirEffectivePath(agencyConfig?.workingDirByDevice?.[targetDeviceId])
: undefined;
return (
diff --git a/src/store/agent/selectors/selectors.ts b/src/store/agent/selectors/selectors.ts
index 4fb60a883be..ea3bdf34da3 100644
--- a/src/store/agent/selectors/selectors.ts
+++ b/src/store/agent/selectors/selectors.ts
@@ -16,7 +16,7 @@ import {
type MetaData,
type RuntimeEnvConfig,
} from '@lobechat/types';
-import { KnowledgeType } from '@lobechat/types';
+import { getWorkingDirEffectivePath, KnowledgeType } from '@lobechat/types';
import { DEFAULT_OPENING_QUESTIONS } from '@/features/AgentSetting/store/selectors';
import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';
@@ -274,7 +274,7 @@ const currentAgentWorkingDirectory =
const agencyConfig = currentAgentConfig(s)?.agencyConfig;
const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId);
const agentChoice = targetDeviceId
- ? agencyConfig?.workingDirByDevice?.[targetDeviceId]
+ ? getWorkingDirEffectivePath(agencyConfig?.workingDirByDevice?.[targetDeviceId])
: undefined;
return agentChoice ?? s.localAgentWorkingDirectoryMap[activeAgentId] ?? homePath;
diff --git a/src/store/device/deviceCwd.test.ts b/src/store/device/deviceCwd.test.ts
index c6df5199c5a..02b7adcdcb5 100644
--- a/src/store/device/deviceCwd.test.ts
+++ b/src/store/device/deviceCwd.test.ts
@@ -31,6 +31,36 @@ describe('nextWorkingDirs', () => {
]);
});
+ it('stores active worktree metadata on the source entry without duplicating the source', () => {
+ const result = nextWorkingDirs(
+ { git: { activeWorktree: '/repo-fix' }, path: '/repo', repoType: 'git' },
+ [entry('/repo', 'git'), entry('/other')],
+ );
+
+ expect(result).toEqual([
+ { git: { activeWorktree: '/repo-fix' }, path: '/repo', repoType: 'git' },
+ entry('/other'),
+ ]);
+ });
+
+ it('preserves existing workspace cache when updating a source entry', () => {
+ const workspace = { instructions: [], skills: [] };
+ const result = nextWorkingDirs(
+ { git: { activeWorktree: '/repo-fix' }, path: '/repo', repoType: 'git' },
+ [{ path: '/repo', repoType: 'git', workspace, workspaceScannedAt: 123 }],
+ );
+
+ expect(result).toEqual([
+ {
+ git: { activeWorktree: '/repo-fix' },
+ path: '/repo',
+ repoType: 'git',
+ workspace,
+ workspaceScannedAt: 123,
+ },
+ ]);
+ });
+
it('caps the list length', () => {
const current = Array.from({ length: WORKING_DIRS_MAX }, (_, i) => entry(`/p${i}`));
const result = nextWorkingDirs(entry('/new'), current);
diff --git a/src/store/device/deviceCwd.ts b/src/store/device/deviceCwd.ts
index aa16be61600..8c469b6eb4f 100644
--- a/src/store/device/deviceCwd.ts
+++ b/src/store/device/deviceCwd.ts
@@ -19,7 +19,15 @@ export const nextWorkingDirs = (
): WorkingDirEntry[] => {
const path = entry.path.trim();
if (!path) return [...current];
- return [{ ...entry, path }, ...current.filter((d) => d.path !== path)].slice(0, max);
+ const existing = current.find((d) => d.path === path);
+ const nextEntry: WorkingDirEntry = { ...entry, path };
+
+ if (!nextEntry.workspace && existing?.workspace) nextEntry.workspace = existing.workspace;
+ if (!nextEntry.workspaceScannedAt && existing?.workspaceScannedAt) {
+ nextEntry.workspaceScannedAt = existing.workspaceScannedAt;
+ }
+
+ return [nextEntry, ...current.filter((d) => d.path !== path)].slice(0, max);
};
/** Drop a path from a device's `workingDirs` recent list (used by the picker's
diff --git a/src/store/device/gitHooks.ts b/src/store/device/gitHooks.ts
index 608156bd935..301f341d0ca 100644
--- a/src/store/device/gitHooks.ts
+++ b/src/store/device/gitHooks.ts
@@ -84,7 +84,7 @@ export const useFetchGitAheadBehind = (deviceId: string | undefined, path?: stri
*/
export const useFetchGitWorktrees = (deviceId: string | undefined, path?: string) =>
useClientDataSWR<DeviceGitWorktreeListItem[]>(
- isEnabled(deviceId, path) ? ['git-worktrees', deviceId ?? 'local', path] : null,
+ isEnabled(deviceId, path) ? deviceKeys.gitWorktrees(deviceId ?? 'local', path) : null,
() => gitService.listGitWorktrees({ deviceId, path: path! }),
{ focusThrottleInterval: 5 * 1000, revalidateOnFocus: true, shouldRetryOnError: false },
);