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(device): add "Create worktree" flow to the worktree switcher (#16810)

Arvin Xu8570578febc1
diff --git a/apps/desktop/src/main/controllers/GitCtr.ts b/apps/desktop/src/main/controllers/GitCtr.ts
index 5129103e169..7727f4aca42 100644
--- a/apps/desktop/src/main/controllers/GitCtr.ts
+++ b/apps/desktop/src/main/controllers/GitCtr.ts
@@ -1,5 +1,6 @@
import type {
GetGitBranchDiffPayload,
+ GitAddWorktreeResult,
GitAheadBehind,
GitBranchDiffPatches,
GitBranchInfo,
@@ -19,6 +20,7 @@ import type {
GitWorktreeListItem,
} from '@lobechat/electron-client-ipc';
import {
+ addGitWorktree as runAddGitWorktree,
checkoutGitBranch as runCheckoutGitBranch,
deleteGitBranch as runDeleteGitBranch,
type DeviceGitInfo,
@@ -148,6 +150,15 @@ export default class GitController extends ControllerModule {
return runRemoveGitWorktree(payload);
}
+ @IpcMethod()
+ async addGitWorktree(payload: {
+ branch: string;
+ path: string;
+ worktreePath: string;
+ }): Promise<GitAddWorktreeResult> {
+ return runAddGitWorktree(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 28c0c0119a5..81c93bf7348 100644
--- a/apps/server/src/routers/lambda/device.ts
+++ b/apps/server/src/routers/lambda/device.ts
@@ -1,5 +1,6 @@
import { REMOTE_HETEROGENEOUS_AGENT_CONFIGS } from '@lobechat/heterogeneous-agents';
import type { DeviceChannel, DeviceListItem, DeviceScope, WorkingDirEntry } from '@lobechat/types';
+import { deriveWorktreePath } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
@@ -309,10 +310,39 @@ export const deviceRouter = router({
deviceId: input.deviceId,
path: input.path,
userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
worktreePath: input.worktreePath,
}),
),
+ /**
+ * Add a linked worktree on a fresh branch in a directory's repository on a
+ * remote device, via the device's `addGitWorktree` RPC.
+ *
+ * The target directory is derived here from the trusted `path` + `branch`
+ * (a `<repo>-<branch>` sibling) rather than accepted from the request, so a
+ * crafted web call can't ask the device to check out at an arbitrary absolute
+ * path — the branch is folded to `-` in the folder name, so it can't traverse.
+ */
+ addGitWorktree: deviceProcedure
+ .input(
+ z.object({
+ branch: z.string(),
+ deviceId: z.string(),
+ path: z.string(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) =>
+ deviceGateway.addGitWorktree({
+ branch: input.branch,
+ deviceId: input.deviceId,
+ path: input.path,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ worktreePath: deriveWorktreePath(input.path, input.branch),
+ }),
+ ),
+
/**
* Pull (`--ff-only`) the current branch of a directory on a remote device, via
* the device's `pullGitBranch` RPC.
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index 11ea949f76b..9287e9008fb 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -11,6 +11,7 @@ import {
} from '@lobechat/device-gateway-client';
import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';
import type {
+ DeviceGitAddWorktreeResult,
DeviceGitAheadBehind,
DeviceGitBranchDiffPatches,
DeviceGitBranchInfo,
@@ -431,15 +432,16 @@ export class DeviceGateway {
path: string;
timeout?: number;
userId: string;
+ workspaceId?: string;
worktreePath: string;
}): Promise<DeviceGitRemoveWorktreeResult> {
- const { userId, deviceId, path, worktreePath, timeout = 30_000 } = params;
+ const { userId, deviceId, path, worktreePath, workspaceId, 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 },
+ { deviceId, timeout, userId, workspaceId },
{ method: 'removeGitWorktree', params: { path, worktreePath } },
);
@@ -455,6 +457,41 @@ export class DeviceGateway {
}
}
+ /**
+ * Add a linked worktree on a fresh branch in a directory's repository on a
+ * remote device via the `addGitWorktree` device RPC.
+ */
+ async addGitWorktree(params: {
+ branch: string;
+ deviceId: string;
+ path: string;
+ timeout?: number;
+ userId: string;
+ workspaceId?: string;
+ worktreePath: string;
+ }): Promise<DeviceGitAddWorktreeResult> {
+ const { userId, deviceId, branch, path, worktreePath, workspaceId, timeout = 30_000 } = params;
+ const client = this.getClient();
+ if (!client) return { error: 'Device gateway not configured', success: false };
+
+ try {
+ const result = await client.invokeRpc<DeviceGitAddWorktreeResult>(
+ { deviceId, timeout, userId, workspaceId },
+ { method: 'addGitWorktree', params: { branch, path, worktreePath } },
+ );
+
+ if (!result.success || !result.data) {
+ log('addGitWorktree: failed for deviceId=%s — %s', deviceId, result.error);
+ return { error: result.error || 'Add worktree failed', success: false };
+ }
+
+ return result.data;
+ } catch (error) {
+ log('addGitWorktree: error for deviceId=%s — %O', deviceId, error);
+ return { error: (error as Error)?.message || 'Add 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 95655d216b8..c67705b0491 100644
--- a/locales/en-US/device.json
+++ b/locales/en-US/device.json
@@ -19,6 +19,10 @@
"workingDirectory.clear": "Reset to default",
"workingDirectory.createBranchAction": "Checkout new branch…",
"workingDirectory.createBranchTitle": "Create new branch",
+ "workingDirectory.createWorktreeAction": "Create worktree…",
+ "workingDirectory.createWorktreeFailed": "Create worktree failed",
+ "workingDirectory.createWorktreeSubmit": "Create",
+ "workingDirectory.createWorktreeTitle": "Create new worktree",
"workingDirectory.current": "Current working directory",
"workingDirectory.currentWorktree": "current",
"workingDirectory.defaultBadge": "Default",
@@ -39,6 +43,7 @@
"workingDirectory.ghMissing": "Install and log in to the GitHub CLI (`gh`) to see linked pull requests",
"workingDirectory.lockedWorktree": "locked",
"workingDirectory.newBranchPlaceholder": "feature/new-branch-name",
+ "workingDirectory.newWorktreeLocation": "Will be created at {{path}}",
"workingDirectory.noMatch": "No matching directories",
"workingDirectory.noRecent": "No directories yet",
"workingDirectory.notSet": "Click to set working directory",
diff --git a/locales/zh-CN/device.json b/locales/zh-CN/device.json
index 50b1daa8309..2b8cd06d885 100644
--- a/locales/zh-CN/device.json
+++ b/locales/zh-CN/device.json
@@ -19,6 +19,10 @@
"workingDirectory.clear": "恢复默认",
"workingDirectory.createBranchAction": "检出新分支…",
"workingDirectory.createBranchTitle": "创建新分支",
+ "workingDirectory.createWorktreeAction": "创建工作树…",
+ "workingDirectory.createWorktreeFailed": "创建工作树失败",
+ "workingDirectory.createWorktreeSubmit": "创建",
+ "workingDirectory.createWorktreeTitle": "创建新工作树",
"workingDirectory.current": "当前工作目录",
"workingDirectory.currentWorktree": "current",
"workingDirectory.defaultBadge": "默认",
@@ -39,6 +43,7 @@
"workingDirectory.ghMissing": "安装并登录 GitHub CLI(gh)即可显示关联的 Pull Request",
"workingDirectory.lockedWorktree": "locked",
"workingDirectory.newBranchPlaceholder": "feature/新分支名称",
+ "workingDirectory.newWorktreeLocation": "将创建于 {{path}}",
"workingDirectory.noMatch": "没有匹配的目录",
"workingDirectory.noRecent": "暂无工作目录",
"workingDirectory.notSet": "点击设置工作目录",
diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.ts
index a26a73b3860..702ddecdf37 100644
--- a/packages/device-control/src/dispatch.ts
+++ b/packages/device-control/src/dispatch.ts
@@ -1,4 +1,5 @@
import {
+ addGitWorktree,
checkoutGitBranch,
deleteGitBranch,
getGitAheadBehind,
@@ -61,6 +62,7 @@ export const DEVICE_RPC_METHODS = [
'renameGitBranch',
'deleteGitBranch',
'removeGitWorktree',
+ 'addGitWorktree',
'pullGitBranch',
'pushGitBranch',
'revertGitFile',
@@ -177,6 +179,10 @@ export const executeDeviceRpc = async (
return removeGitWorktree(params as { path: string; worktreePath: string });
}
+ case 'addGitWorktree': {
+ return addGitWorktree(params as { branch: string; 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 7f46d068afc..7c8a93d1158 100644
--- a/packages/electron-client-ipc/src/types/git.ts
+++ b/packages/electron-client-ipc/src/types/git.ts
@@ -221,6 +221,13 @@ export interface GitRemoveWorktreeResult {
success: boolean;
}
+export interface GitAddWorktreeResult {
+ error?: string;
+ success: boolean;
+ /** Absolute path of the created worktree, echoed back so the UI can switch to it. */
+ worktreePath?: string;
+}
+
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/branches.ts b/packages/local-file-shell/src/git/branches.ts
index 4da8db08f51..8daad4df76a 100644
--- a/packages/local-file-shell/src/git/branches.ts
+++ b/packages/local-file-shell/src/git/branches.ts
@@ -19,7 +19,7 @@ const log = createLogger('local-file-shell:git');
const execFileAsync = promisify(execFile);
/** Reject obviously invalid branch refs early to avoid a confusing git error. */
-const isInvalidBranchRef = (name: string): boolean =>
+export const isInvalidBranchRef = (name: string): boolean =>
/[\s~^:?*[\\]/.test(name) || name.startsWith('-') || name.includes('..');
/**
diff --git a/packages/local-file-shell/src/git/types.ts b/packages/local-file-shell/src/git/types.ts
index a679c558908..435c185b923 100644
--- a/packages/local-file-shell/src/git/types.ts
+++ b/packages/local-file-shell/src/git/types.ts
@@ -208,6 +208,13 @@ export interface GitRemoveWorktreeResult {
success: boolean;
}
+export interface GitAddWorktreeResult {
+ error?: string;
+ success: boolean;
+ /** Absolute path of the created worktree, echoed back so the UI can switch to it. */
+ worktreePath?: string;
+}
+
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 3886739d9b2..bcd18a7c724 100644
--- a/packages/local-file-shell/src/git/worktrees.ts
+++ b/packages/local-file-shell/src/git/worktrees.ts
@@ -3,8 +3,14 @@ import { realpath } from 'node:fs/promises';
import path from 'node:path';
import { promisify } from 'node:util';
+import { isInvalidBranchRef } from './branches';
import { getGitWorkingTreeStatus } from './info';
-import type { GitRemoveWorktreeResult, GitWorkingTreeStatus, GitWorktreeListItem } from './types';
+import type {
+ GitAddWorktreeResult,
+ GitRemoveWorktreeResult,
+ GitWorkingTreeStatus,
+ GitWorktreeListItem,
+} from './types';
const execFileAsync = promisify(execFile);
@@ -160,3 +166,34 @@ export const removeGitWorktree = async (payload: {
return { error: stderr || 'git worktree remove failed', success: false };
}
};
+
+/**
+ * Add a linked worktree checked out on a fresh branch, mirroring the branch
+ * switcher's "create branch" flow (`git worktree add -b <branch> <path>`). The
+ * new branch forks from the repo's current HEAD; the caller supplies the target
+ * directory (an absolute sibling path the renderer derives from the source
+ * repo). Returns the created path on success so the UI can switch into it.
+ */
+export const addGitWorktree = async (payload: {
+ branch: string;
+ path: string;
+ worktreePath: string;
+}): Promise<GitAddWorktreeResult> => {
+ const { path: dirPath, branch, worktreePath } = payload;
+ if (!dirPath?.trim()) return { error: 'Working directory is required', success: false };
+ if (!branch?.trim()) return { error: 'Branch name is required', success: false };
+ if (!worktreePath?.trim()) return { error: 'Worktree path is required', success: false };
+ if (isInvalidBranchRef(branch))
+ return { error: `Invalid branch name: ${branch}`, success: false };
+
+ try {
+ await execFileAsync('git', ['worktree', 'add', '-b', branch, worktreePath], {
+ cwd: dirPath,
+ timeout: 30_000,
+ });
+ return { success: true, worktreePath };
+ } catch (error: any) {
+ const stderr: string = (error?.stderr ?? error?.message ?? '').toString().trim();
+ return { error: stderr || 'git worktree add failed', success: false };
+ }
+};
diff --git a/packages/locales/src/default/device.ts b/packages/locales/src/default/device.ts
index 2665db7c2e2..c01b7a5665a 100644
--- a/packages/locales/src/default/device.ts
+++ b/packages/locales/src/default/device.ts
@@ -20,6 +20,10 @@ export default {
'workingDirectory.clean': 'clean',
'workingDirectory.createBranchAction': 'Checkout new branch…',
'workingDirectory.createBranchTitle': 'Create new branch',
+ 'workingDirectory.createWorktreeAction': 'Create worktree…',
+ 'workingDirectory.createWorktreeFailed': 'Create worktree failed',
+ 'workingDirectory.createWorktreeSubmit': 'Create',
+ 'workingDirectory.createWorktreeTitle': 'Create new worktree',
'workingDirectory.current': 'Current working directory',
'workingDirectory.defaultBadge': 'Default',
'workingDirectory.deleteBranchAction': 'Delete branch',
@@ -40,6 +44,7 @@ export default {
'workingDirectory.ghMissing':
'Install and log in to the GitHub CLI (`gh`) to see linked pull requests',
'workingDirectory.newBranchPlaceholder': 'feature/new-branch-name',
+ 'workingDirectory.newWorktreeLocation': 'Will be created at {{path}}',
'workingDirectory.noMatch': 'No matching directories',
'workingDirectory.noRecent': 'No directories yet',
'workingDirectory.notSet': 'Click to set working directory',
diff --git a/packages/types/src/device.ts b/packages/types/src/device.ts
index 9015957695d..40889d3df33 100644
--- a/packages/types/src/device.ts
+++ b/packages/types/src/device.ts
@@ -138,6 +138,43 @@ export const getWorkingDirEffectivePath = (
return entry.git?.activeWorktree || entry.path;
};
+/**
+ * Derive the target directory for a new worktree: a sibling of the source repo
+ * named `<repoName>-<branch>` (e.g. `/code/lobehub` + `feat/x` →
+ * `/code/lobehub-feat-x`), matching the convention agents already use for their
+ * linked worktrees. Preserves the source path's separator so Windows paths stay
+ * intact, and folds ref-illegal characters in the branch to `-` for the folder.
+ *
+ * Shared by the renderer (path preview + local IPC call) and the server
+ * (`device.addGitWorktree`), which re-derives the target from the trusted
+ * `path` + `branch` rather than trusting a client-supplied absolute path — so a
+ * crafted web request can't ask a remote device to check out at an arbitrary
+ * location. Both callers must derive identically, hence the single source here.
+ */
+const isSep = (ch: string): boolean => ch === '/' || ch === '\\';
+
+export const deriveWorktreePath = (sourcePath: string, branch: string): string => {
+ const sep = sourcePath.includes('\\') && !sourcePath.includes('/') ? '\\' : '/';
+ // Strip trailing path separators, then the leading/trailing '-' of the folded
+ // branch, both with linear scans rather than anchored /[…]+$/ quantifiers —
+ // those are polynomial-ReDoS shapes (flagged by CodeQL) on a long crafted
+ // input, and this runs per request on the server with untrusted path/branch.
+ let te = sourcePath.length;
+ while (te > 0 && isSep(sourcePath[te - 1])) te -= 1;
+ const trimmed = sourcePath.slice(0, te);
+ const cut = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\'));
+ const parent = cut >= 0 ? trimmed.slice(0, cut) : '';
+ const repoName = (cut >= 0 ? trimmed.slice(cut + 1) : trimmed) || 'repo';
+ const folded = branch.trim().replaceAll(/[\s~^:?*[\]\\/]+/g, '-');
+ let start = 0;
+ let end = folded.length;
+ while (start < end && folded[start] === '-') start += 1;
+ while (end > start && folded[end - 1] === '-') end -= 1;
+ const suffix = folded.slice(start, end);
+ const folder = suffix ? `${repoName}-${suffix}` : repoName;
+ return parent ? `${parent}${sep}${folder}` : folder;
+};
+
export interface WorkingDirEntry extends WorkingDirConfig {
/**
* Cached "workspace init" scan of this directory (AGENTS.md + project skills).
@@ -412,6 +449,14 @@ export interface DeviceGitRemoveWorktreeResult {
success: boolean;
}
+/** Result of the `addGitWorktree` device RPC. Mirrors the desktop shape. */
+export interface DeviceGitAddWorktreeResult {
+ error?: string;
+ success: boolean;
+ /** Absolute path of the created worktree, echoed back so the UI can switch to it. */
+ worktreePath?: string;
+}
+
/**
* 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/CreateWorktreeModal.tsx b/src/features/ChatInput/ControlBar/CreateWorktreeModal.tsx
new file mode 100644
index 00000000000..29099d8803d
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/CreateWorktreeModal.tsx
@@ -0,0 +1,107 @@
+'use client';
+
+import { Flexbox, Input, Text } from '@lobehub/ui';
+import { Button, createModal, type ModalInstance, useModalContext } from '@lobehub/ui/base-ui';
+import { type InputRef } from 'antd';
+import { cssVar } from 'antd-style';
+import { t } from 'i18next';
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+interface CreateWorktreeContentProps {
+ /**
+ * Create the worktree on a fresh branch. Return an error message to show
+ * inline and keep the modal open; return undefined on success (modal closes).
+ */
+ onSubmit: (branch: string) => Promise<string | undefined>;
+ /** Preview the target directory the new worktree will occupy for a branch name. */
+ resolvePath: (branch: string) => string;
+}
+
+const CreateWorktreeContent = memo<CreateWorktreeContentProps>(({ onSubmit, resolvePath }) => {
+ const { t: tDevice } = useTranslation('device');
+ const { t: tCommon } = useTranslation('common');
+ const { close } = useModalContext();
+ const [value, setValue] = useState('');
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<string>();
+ const inputRef = useRef<InputRef>(null);
+
+ useEffect(() => {
+ queueMicrotask(() => inputRef.current?.focus());
+ }, []);
+
+ const trimmed = value.trim();
+ // Show where the worktree will land so the destination is never a surprise.
+ const previewPath = useMemo(() => (trimmed ? resolvePath(trimmed) : ''), [resolvePath, trimmed]);
+
+ const handleSubmit = useCallback(async () => {
+ if (loading) return;
+ const branch = value.trim();
+ if (!branch) return;
+ setLoading(true);
+ try {
+ const message = await onSubmit(branch);
+ if (message) {
+ setError(message);
+ return;
+ }
+ close();
+ } finally {
+ setLoading(false);
+ }
+ }, [close, loading, onSubmit, value]);
+
+ return (
+ <Flexbox gap={16}>
+ <Flexbox gap={6}>
+ <Input
+ placeholder={tDevice('workingDirectory.newBranchPlaceholder')}
+ ref={inputRef}
+ value={value}
+ onPressEnter={handleSubmit}
+ onChange={(e) => {
+ setValue(e.target.value);
+ setError(undefined);
+ }}
+ />
+ {previewPath ? (
+ <Text style={{ color: cssVar.colorTextTertiary, fontSize: 12, wordBreak: 'break-all' }}>
+ {tDevice('workingDirectory.newWorktreeLocation', { path: previewPath })}
+ </Text>
+ ) : null}
+ {error ? <Text style={{ color: cssVar.colorError, fontSize: 12 }}>{error}</Text> : null}
+ </Flexbox>
+ <Flexbox horizontal gap={8} justify={'flex-end'}>
+ <Button disabled={loading} onClick={close}>
+ {tCommon('cancel')}
+ </Button>
+ <Button disabled={!trimmed} loading={loading} type={'primary'} onClick={handleSubmit}>
+ {tDevice('workingDirectory.createWorktreeSubmit')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+CreateWorktreeContent.displayName = 'CreateWorktreeContent';
+
+/**
+ * Branch-name entry for "create worktree". Mirrors the create-branch modal but
+ * adds a live preview of the sibling directory the new worktree will occupy.
+ * Submitting runs `git worktree add -b <branch> <path>` and switches into it.
+ */
+export const openCreateWorktreeModal = (options: {
+ onSubmit: (branch: string) => Promise<string | undefined>;
+ resolvePath: (branch: string) => string;
+}): ModalInstance =>
+ createModal({
+ content: (
+ <CreateWorktreeContent resolvePath={options.resolvePath} onSubmit={options.onSubmit} />
+ ),
+ footer: null,
+ maskClosable: true,
+ styles: { header: { borderBottom: 'none' } },
+ title: t('workingDirectory.createWorktreeTitle', { ns: 'device' }),
+ width: 'min(90vw, 480px)',
+ });
diff --git a/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx b/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx
index 989dd3c9115..9c6d8b9793a 100644
--- a/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx
@@ -1,4 +1,8 @@
-import type { DeviceGitWorktreeListItem, WorkingDirEntry } from '@lobechat/types';
+import {
+ deriveWorktreePath,
+ type DeviceGitWorktreeListItem,
+ type WorkingDirEntry,
+} from '@lobechat/types';
import { Icon, Input, Tooltip } from '@lobehub/ui';
import {
confirmModal,
@@ -13,6 +17,7 @@ import {
import { createStaticStyles, cssVar, cx } from 'antd-style';
import {
CheckIcon,
+ FolderPlusIcon,
GitForkIcon,
LoaderCircleIcon,
RefreshCwIcon,
@@ -24,6 +29,7 @@ import { useTranslation } from 'react-i18next';
import { gitService } from '@/services/git';
+import { openCreateWorktreeModal } from './CreateWorktreeModal';
import { useCommitWorkingDirectory } from './useCommitWorkingDirectory';
const styles = createStaticStyles(({ css }) => ({
@@ -234,6 +240,32 @@ const styles = createStaticStyles(({ css }) => ({
flex: 1;
padding: 6px;
`,
+ createItemWrapper: css`
+ padding: 6px;
+ border-block-start: 1px solid ${cssVar.colorSplit};
+ `,
+ createItem: css`
+ cursor: pointer;
+
+ display: flex;
+ gap: 8px;
+ align-items: center;
+
+ padding-block: 6px;
+ padding-inline: 8px;
+ border-radius: 8px;
+
+ font-size: 13px;
+ color: ${cssVar.colorText};
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ createItemIcon: css`
+ flex: none;
+ color: ${cssVar.colorTextSecondary};
+ `,
name: css`
overflow: hidden;
flex: 0 1 auto;
@@ -551,6 +583,37 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(
[deviceId, onWorktreesChange, path, t, tCommon],
);
+ // Create a worktree on a fresh branch (mirrors the branch switcher's "create
+ // branch" flow), then switch the working directory into it. Returns an error
+ // message for inline display in the modal, or undefined on success.
+ const handleCreateWorktree = useCallback(
+ async (branch: string): Promise<string | undefined> => {
+ const worktreePath = deriveWorktreePath(sourcePath, branch);
+ const result = await gitService.addGitWorktree({ branch, deviceId, path, worktreePath });
+ if (!result.success) return result.error || t('workingDirectory.createWorktreeFailed');
+
+ // 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 onWorktreesChange?.();
+ return undefined;
+ },
+ [commit, deviceId, isGithub, onWorktreesChange, path, sourcePath, t],
+ );
+
+ const openCreateWorktree = useCallback(() => {
+ setOpen(false);
+ openCreateWorktreeModal({
+ onSubmit: handleCreateWorktree,
+ resolvePath: (branch) => deriveWorktreePath(sourcePath, branch),
+ });
+ }, [handleCreateWorktree, sourcePath]);
+
// Scroll the current worktree into view each time the dropdown opens — the
// list mounts at scrollTop=0, so a current worktree below the fold would
// otherwise read as "nothing selected".
@@ -697,6 +760,17 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(
})
)}
</div>
+
+ <div className={styles.createItemWrapper}>
+ <DropdownMenuItem
+ className={styles.createItem}
+ closeOnClick={false}
+ onClick={openCreateWorktree}
+ >
+ <Icon className={styles.createItemIcon} icon={FolderPlusIcon} size={14} />
+ <div>{t('workingDirectory.createWorktreeAction')}</div>
+ </DropdownMenuItem>
+ </div>
</div>
</DropdownMenuPopup>
</DropdownMenuPositioner>
diff --git a/src/services/electron/git.ts b/src/services/electron/git.ts
index 9d108b87f6a..8488f7b5523 100644
--- a/src/services/electron/git.ts
+++ b/src/services/electron/git.ts
@@ -1,5 +1,6 @@
import {
type GetGitBranchDiffPayload,
+ type GitAddWorktreeResult,
type GitAheadBehind,
type GitBranchDiffPatches,
type GitBranchInfo,
@@ -116,6 +117,14 @@ class ElectronGitService {
}): Promise<GitRemoveWorktreeResult> {
return this.ipc.git.removeGitWorktree(params);
}
+
+ async addGitWorktree(params: {
+ branch: string;
+ path: string;
+ worktreePath: string;
+ }): Promise<GitAddWorktreeResult> {
+ return this.ipc.git.addGitWorktree(params);
+ }
}
export const electronGitService = new ElectronGitService();
diff --git a/src/services/git.ts b/src/services/git.ts
index 2458d8f148f..bbc530992b3 100644
--- a/src/services/git.ts
+++ b/src/services/git.ts
@@ -6,6 +6,7 @@ import type {
GitWorkingTreePatches,
} from '@lobechat/electron-client-ipc';
import type {
+ DeviceGitAddWorktreeResult,
DeviceGitAheadBehind,
DeviceGitBranchListItem,
DeviceGitCheckoutResult,
@@ -121,6 +122,28 @@ class GitService {
: electronGitService.removeGitWorktree({ path, worktreePath });
}
+ /**
+ * Add a linked worktree on a fresh branch to a working directory's repository.
+ * A remote device derives the target path server-side from `path` + `branch`
+ * (never trusting a client-supplied absolute path), so `worktreePath` is only
+ * forwarded on the local IPC route where this machine owns the filesystem.
+ */
+ addGitWorktree({
+ branch,
+ deviceId,
+ path,
+ worktreePath,
+ }: {
+ branch: string;
+ deviceId?: string;
+ path: string;
+ worktreePath: string;
+ }): Promise<DeviceGitAddWorktreeResult> {
+ return deviceId
+ ? lambdaClient.device.addGitWorktree.mutate({ branch, deviceId, path })
+ : electronGitService.addGitWorktree({ branch, path, worktreePath });
+ }
+
/** Pull (`--ff-only`) the current branch of a working directory. */
pullGitBranch({
deviceId,