🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(worktree): auto-generate branch names for new worktrees (#20307)
Arvin Xu1d3ecbee2fb7
diff --git a/locales/en-US/device.json b/locales/en-US/device.jsonindex be9ba3296e7..e2cba28b245 100644--- a/locales/en-US/device.json+++ b/locales/en-US/device.json@@ -91,6 +91,7 @@"workingDirectory.renameBranchAction": "Rename branch","workingDirectory.renameBranchTitle": "Rename branch","workingDirectory.renameFailed": "Rename failed",+ "workingDirectory.rollBranchName": "Roll another branch name","workingDirectory.searchPlaceholder": "Search directories","workingDirectory.selectFolder": "Select folder","workingDirectory.setDefault": "Set as default",diff --git a/locales/zh-CN/device.json b/locales/zh-CN/device.jsonindex fb3e24a33fe..517879cf247 100644--- a/locales/zh-CN/device.json+++ b/locales/zh-CN/device.json@@ -91,6 +91,7 @@"workingDirectory.renameBranchAction": "重命名分支","workingDirectory.renameBranchTitle": "重命名分支","workingDirectory.renameFailed": "重命名失败",+ "workingDirectory.rollBranchName": "换一个分支名","workingDirectory.searchPlaceholder": "搜索工作目录","workingDirectory.selectFolder": "选择文件夹","workingDirectory.setDefault": "设为默认",diff --git a/packages/const/src/index.ts b/packages/const/src/index.tsindex 8b6d2d4a294..21089f574bb 100644--- a/packages/const/src/index.ts+++ b/packages/const/src/index.ts@@ -37,3 +37,4 @@ export * from './user';export * from './userMemory';export * from './version';export * from './workspace';+export * from './worktreeName';diff --git a/packages/const/src/worktreeName.test.ts b/packages/const/src/worktreeName.test.tsnew file mode 100644index 00000000000..365af6eed70--- /dev/null+++ b/packages/const/src/worktreeName.test.ts@@ -0,0 +1,126 @@+import { describe, expect, it } from 'vitest';++import {+ formatWorktreeTimestamp,+ generateWorktreeBranchName,+ WORKTREE_ADJECTIVES,+ WORKTREE_BRANCH_PREFIX,+ WORKTREE_NOUNS,+} from './worktreeName';++const NOW = new Date(2026, 9, 2, 3, 8);++const sample = (times = 500) =>+ Array.from({ length: times }, () => generateWorktreeBranchName({ now: NOW }));++/** A deterministic stand-in for `Math.random` that walks `values` and loops. */+const sequence = (values: number[]) => {+ let index = 0;+ return () => values[index++ % values.length];+};++describe('formatWorktreeTimestamp', () => {+ it('zero-pads local Y/M/D/H/m', () => {+ expect(formatWorktreeTimestamp(new Date(2026, 0, 5, 4, 3))).toBe('202601050403');+ });++ it('reads the local clock rather than UTC', () => {+ // A local-constructed Date read back with local getters round-trips exactly,+ // whatever the machine's offset is. `toISOString()` would not.+ expect(formatWorktreeTimestamp(new Date(2026, 9, 2, 3, 8))).toBe('202610020308');+ });+});++describe('generateWorktreeBranchName', () => {+ it('yields <prefix>/<YYYYMMDDHHmm>-<adjective>-<noun>', () => {+ const shape = new RegExp(`^${WORKTREE_BRANCH_PREFIX}/\\d{12}-[a-z]+-[a-z]+$`);++ for (const name of sample()) {+ expect(name).toMatch(shape);+ }+ });++ it('draws the words from the exported pools', () => {+ const adjectives = new Set<string>(WORKTREE_ADJECTIVES);+ const nouns = new Set<string>(WORKTREE_NOUNS);++ for (const name of sample()) {+ // `wt/202610020308-quiet-hill` → ['wt/202610020308', 'quiet', 'hill']+ const [, adjective, noun] = name.split('-');+ expect(adjectives.has(adjective)).toBe(true);+ expect(nouns.has(noun)).toBe(true);+ }+ });++ it('is deterministic for an injected clock and random source', () => {+ expect(generateWorktreeBranchName({ now: NOW, random: () => 0 })).toBe(+ generateWorktreeBranchName({ now: NOW, random: () => 0 }),+ );+ });++ it('redraws when the drawn name is already taken', () => {+ const taken = generateWorktreeBranchName({ now: NOW, random: () => 0 });++ expect(+ generateWorktreeBranchName({+ exclude: [taken],+ now: NOW,+ random: sequence([0, 0, 0.5, 0.5]),+ }),+ ).not.toBe(taken);+ });++ it('keeps the first draw when nothing it drew is taken', () => {+ expect(+ generateWorktreeBranchName({ exclude: ['wt/202001010000-other-name'], now: NOW }),+ ).toMatch(/^wt\/202610020308-/);+ });++ it('spreads across the pool so repeats are rare', () => {+ expect(new Set(sample(200)).size).toBeGreaterThan(150);+ });++ // Git refuses `refs/heads/wt/x` while a ref `refs/heads/wt` exists, and every+ // namespaced draw shares that segment — so the namespace, not the word pair,+ // is what has to give.+ describe('when a ref occupies the namespace path', () => {+ it('falls back to the flat form instead of handing out a ref git will refuse', () => {+ expect(generateWorktreeBranchName({ exclude: ['wt'], now: NOW, random: () => 0 })).toMatch(+ /^wt-\d{12}-[a-z]+-[a-z]+$/,+ );+ });++ it('ignores the case of the occupying ref, like git refs do', () => {+ expect(generateWorktreeBranchName({ exclude: ['WT'], now: NOW, random: () => 0 })).toMatch(+ /^wt-\d{12}-/,+ );+ });++ it('keeps the namespace for taken names that are unrelated', () => {+ expect(+ generateWorktreeBranchName({ exclude: ['main', 'wt/202001010000-other-name'], now: NOW }),+ ).toMatch(/^wt\//);+ });++ it('redraws the flat form when the drawn flat name is taken too', () => {+ const taken = generateWorktreeBranchName({ exclude: ['wt'], now: NOW, random: () => 0 });++ expect(+ generateWorktreeBranchName({+ exclude: ['wt', taken],+ now: NOW,+ random: sequence([0, 0, 0.5, 0.5]),+ }),+ ).not.toBe(taken);+ });+ });+});++describe('worktree name pools', () => {+ const pools = { adjectives: WORKTREE_ADJECTIVES, nouns: WORKTREE_NOUNS };++ it.each(Object.entries(pools))('%s stay lowercase ASCII and unique', (_label, pool) => {+ expect(new Set(pool).size).toBe(pool.length);+ for (const word of pool) expect(word).toMatch(/^[a-z]+$/);+ });+});diff --git a/packages/const/src/worktreeName.ts b/packages/const/src/worktreeName.tsnew file mode 100644index 00000000000..07f675cc856--- /dev/null+++ b/packages/const/src/worktreeName.ts@@ -0,0 +1,206 @@+/**+ * Auto-generated branch names for a freshly created worktree.+ *+ * Shape: `wt/<YYYYMMDDHHmm>-<adjective>-<noun>` — e.g. `wt/202610020308-quiet-hill`.+ * The minutes-precision timestamp keeps the branch list chronological when sorted+ * by name; the word pair keeps the name human-readable and, together with the+ * timestamp, makes a collision unlikely. Only lowercase ASCII and `-` are used,+ * so the name is always a valid git ref, and it folds cleanly into the worktree+ * folder name (`deriveWorktreePath` turns it into `<repo>-wt-202610020308-quiet-hill`).+ */++/** Namespace prefix, so worktrees created by the app group together in the branch list. */+export const WORKTREE_BRANCH_PREFIX = 'wt';++export const WORKTREE_ADJECTIVES = [+ 'amber',+ 'bold',+ 'brave',+ 'breezy',+ 'bright',+ 'brisk',+ 'calm',+ 'cheerful',+ 'clever',+ 'coastal',+ 'crisp',+ 'curious',+ 'dapper',+ 'eager',+ 'early',+ 'easy',+ 'fancy',+ 'fluent',+ 'fresh',+ 'gentle',+ 'giddy',+ 'glad',+ 'golden',+ 'grand',+ 'handy',+ 'hardy',+ 'humble',+ 'jolly',+ 'keen',+ 'lively',+ 'lucid',+ 'lucky',+ 'mellow',+ 'merry',+ 'mighty',+ 'nimble',+ 'noble',+ 'plucky',+ 'proud',+ 'quiet',+ 'rapid',+ 'ready',+ 'silky',+ 'smooth',+ 'snowy',+ 'solar',+ 'steady',+ 'sunny',+ 'swift',+ 'tender',+ 'tidy',+] as const;++export const WORKTREE_NOUNS = [+ 'acorn',+ 'badger',+ 'bamboo',+ 'beacon',+ 'bison',+ 'brook',+ 'canyon',+ 'cedar',+ 'cloud',+ 'comet',+ 'coral',+ 'creek',+ 'dawn',+ 'delta',+ 'ember',+ 'falcon',+ 'fern',+ 'forest',+ 'fox',+ 'harbor',+ 'heron',+ 'hill',+ 'island',+ 'jade',+ 'lagoon',+ 'lantern',+ 'lark',+ 'maple',+ 'meadow',+ 'mesa',+ 'mist',+ 'moon',+ 'moss',+ 'oak',+ 'ocean',+ 'otter',+ 'peak',+ 'pine',+ 'pond',+ 'prairie',+ 'quartz',+ 'raven',+ 'reed',+ 'river',+ 'robin',+ 'sail',+ 'shore',+ 'sparrow',+ 'spring',+ 'stone',+ 'summit',+ 'tide',+ 'valley',+ 'willow',+] as const;++const pad = (value: number): string => String(value).padStart(2, '0');++/**+ * Local-time `YYYYMMDDHHmm`. Deliberately not `toISOString()`: the name is read+ * by the person who created it, against their own clock, not UTC.+ */+export const formatWorktreeTimestamp = (date: Date = new Date()): string =>+ `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}${pad(+ date.getHours(),+ )}${pad(date.getMinutes())}`;++const pick = <T>(pool: readonly T[], random: () => number): T =>+ pool[Math.min(pool.length - 1, Math.floor(random() * pool.length))];++/**+ * Whether a ref already occupies the candidate's path. Git stores refs as paths,+ * so `refs/heads/wt` and `refs/heads/wt/x` cannot coexist — creating the second+ * fails with `cannot lock ref … 'refs/heads/wt' exists`. Matching names exactly+ * cannot see that, and the reverse (the candidate becoming an ancestor of an+ * existing ref) is refused the same way, so every path segment is checked.+ */+const refPathConflict = (candidate: string, taken: ReadonlySet<string>): boolean => {+ if (taken.has(candidate)) return true;++ for (let end = candidate.indexOf('/'); end !== -1; end = candidate.indexOf('/', end + 1)) {+ if (taken.has(candidate.slice(0, end))) return true;+ }++ for (const ref of taken) {+ if (ref.startsWith(`${candidate}/`)) return true;+ }++ return false;+};++export interface GenerateWorktreeBranchNameOptions {+ /**+ * Refs the caller already has in view. Branch names count, including one that+ * names a path SEGMENT rather than a leaf (a branch literally called `wt`+ * blocks the whole `wt/` namespace). The draw retries a bounded number of+ * times against them, and a repeat beats no name (mirrors `randomAgentName`).+ */+ exclude?: Iterable<string>;+ now?: Date;+ random?: () => number;+}++const drawWith = (shape: () => string, taken: ReadonlySet<string>): string => {+ let candidate = shape();+ for (let i = 0; i < 20 && refPathConflict(candidate, taken); i++) candidate = shape();+ return candidate;+};++/**+ * Draw a branch name for a new worktree, with the timestamp taken from `now`+ * and the word pair from `random`. Both are injectable so callers stay testable.+ *+ * Names are namespaced (`wt/<timestamp>-…`) so app-created worktrees group+ * together in the branch list. Every namespaced draw shares the `wt` segment, so+ * a ref living there can never be drawn around — that namespace is unusable, and+ * the flat `wt-<timestamp>-…` form takes over rather than handing the user a+ * name git is guaranteed to refuse.+ */+export const generateWorktreeBranchName = ({+ exclude,+ now = new Date(),+ random = Math.random,+}: GenerateWorktreeBranchNameOptions = {}): string => {+ const taken = new Set(+ [...(exclude ?? [])].map((name) => name.trim().toLowerCase()).filter(Boolean),+ );+ const timestamp = formatWorktreeTimestamp(now);+ const tail = () =>+ `${timestamp}-${pick(WORKTREE_ADJECTIVES, random)}-${pick(WORKTREE_NOUNS, random)}`;++ if (taken.has(WORKTREE_BRANCH_PREFIX)) {+ return drawWith(() => `${WORKTREE_BRANCH_PREFIX}-${tail()}`, taken);+ }++ return drawWith(() => `${WORKTREE_BRANCH_PREFIX}/${tail()}`, taken);+};diff --git a/packages/locales/src/default/device.ts b/packages/locales/src/default/device.tsindex 31f40f7ef12..cac26f77a4c 100644--- a/packages/locales/src/default/device.ts+++ b/packages/locales/src/default/device.ts@@ -87,6 +87,7 @@ export default {'workingDirectory.renameBranchAction': 'Rename branch','workingDirectory.renameBranchTitle': 'Rename branch','workingDirectory.renameFailed': 'Rename failed',+ 'workingDirectory.rollBranchName': 'Roll another branch name','workingDirectory.searchPlaceholder': 'Search directories','workingDirectory.selectFolder': 'Select folder','workingDirectory.setDefault': 'Set as default',diff --git a/packages/types/src/device.test.ts b/packages/types/src/device.test.tsindex 178db401f96..667a2917c97 100644--- a/packages/types/src/device.test.ts+++ b/packages/types/src/device.test.ts@@ -2,7 +2,7 @@ import { describe, expect, expectTypeOf, it } from 'vitest';import type { z } from 'zod';import type { DeviceActivityOrder, WorkingDirConfig } from './device';-import { sortDevicesByActivity, workingDirConfigSchema } from './device';+import { deriveWorktreePath, sortDevicesByActivity, workingDirConfigSchema } from './device';describe('sortDevicesByActivity', () => {const device = (@@ -164,3 +164,20 @@ describe('workingDirConfigSchema', () => {expect(workingDirConfigSchema.parse(value)).toEqual(value);});});++describe('deriveWorktreePath', () => {+ // The folder the worktree modal previews for a generated branch+ // (`wt/<timestamp>-<adjective>-<noun>`): the `/` folds to `-`, so the checkout+ // lands next to the repo as `<repo>-wt-<timestamp>-<adjective>-<noun>`.+ it('folds a generated branch name into a sibling folder', () => {+ expect(deriveWorktreePath('/code/lobehub', 'wt/202610020308-quiet-hill')).toBe(+ '/code/lobehub-wt-202610020308-quiet-hill',+ );+ });++ it('keeps the source path separator on Windows', () => {+ expect(deriveWorktreePath('C:\\code\\lobehub', 'wt/202610020308-quiet-hill')).toBe(+ 'C:\\code\\lobehub-wt-202610020308-quiet-hill',+ );+ });+});diff --git a/src/features/ChatInput/ControlBar/CreateWorktreeModal.tsx b/src/features/ChatInput/ControlBar/CreateWorktreeModal.tsxindex cc0748f20d0..7ff4b0675e4 100644--- a/src/features/ChatInput/ControlBar/CreateWorktreeModal.tsx+++ b/src/features/ChatInput/ControlBar/CreateWorktreeModal.tsx@@ -2,108 +2,170 @@import { Flexbox } from '@lobehub/ui';import {+ ActionIcon,Button,createModal,Input,type ModalInstance,+ Skeleton,Text,useModalContext,} from '@lobehub/ui/base-ui';import { cssVar } from 'antd-style';import { t } from 'i18next';+import { DicesIcon } from 'lucide-react';import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import { useWorktreeBranchSeed } from './useWorktreeBranchSeed';+interface CreateWorktreeContentProps {+ deviceId?: string;/*** 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>;+ path: string;/** 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<HTMLInputElement>(null);+const CreateWorktreeContent = memo<CreateWorktreeContentProps>(+ ({ deviceId, onSubmit, path, resolvePath }) => {+ const { t: tDevice } = useTranslation('device');+ const { t: tCommon } = useTranslation('common');+ const { close } = useModalContext();+ // Seeded with a generated name so creating a worktree is a single Enter+ // press. The field stays editable, and the dice re-rolls it, for anyone who+ // would rather name the branch after the work. The name only appears once+ // the branch list behind it has settled — see `useWorktreeBranchSeed`.+ const { isReady, name, reroll } = useWorktreeBranchSeed(deviceId, path);+ // Typing (and an explicit re-roll) shadows the generated name, so a redraw+ // never overwrites what the user chose.+ const [edited, setEdited] = useState<string>();+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string>();+ const inputRef = useRef<HTMLInputElement>(null);++ const value = edited ?? name ?? '';+ const trimmed = value.trim();- useEffect(() => {- queueMicrotask(() => inputRef.current?.focus());- }, []);+ // Focus once the field exists; while the branch list is loading there is+ // nothing to focus yet.+ useEffect(() => {+ if (!isReady) return;+ queueMicrotask(() => inputRef.current?.focus());+ }, [isReady]);- 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]);+ // 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;+ const rollName = useCallback(() => {+ setEdited(undefined);+ reroll();+ setError(undefined);+ }, [reroll]);++ 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();- } finally {- setLoading(false);- }- }, [close, loading, onSubmit, value]);+ }, [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>+ return (+ <Flexbox gap={16}>+ <Flexbox gap={6}>+ {isReady ? (+ <Input+ placeholder={tDevice('workingDirectory.newBranchPlaceholder')}+ ref={inputRef}+ value={value}+ suffix={+ <ActionIcon+ icon={DicesIcon}+ size={'small'}+ title={tDevice('workingDirectory.rollBranchName')}+ onClick={rollName}+ />+ }+ onPressEnter={handleSubmit}+ onChange={(e) => {+ setEdited(e.target.value);+ setError(undefined);+ }}+ />+ ) : (+ <Skeleton height={32} radius={cssVar.borderRadius} />+ )}+ {!isReady ? <Skeleton height={16} radius={4} width={'70%'} /> : null}+ {isReady && previewPath ? (+ <Text style={{ color: cssVar.colorTextTertiary, fontSize: 12, wordBreak: 'break-all' }}>+ {tDevice('workingDirectory.newWorktreeLocation', { path: previewPath })}+ </Text>+ ) : null}+ {isReady && 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={!isReady || !trimmed}+ loading={loading}+ type={'primary'}+ onClick={handleSubmit}+ >+ {tDevice('workingDirectory.createWorktreeSubmit')}+ </Button>+ </Flexbox></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.+ * seeds the field with a generated branch name (time prefix + word pair, so it+ * sorts chronologically and needs no inventing) and 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.+ *+ * The name is drawn against the working directory's full local branch list, so+ * the directory it reads is part of the contract.*/export const openCreateWorktreeModal = (options: {+ deviceId?: string;onSubmit: (branch: string) => Promise<string | undefined>;+ path: string;resolvePath: (branch: string) => string;}): ModalInstance =>createModal({content: (- <CreateWorktreeContent resolvePath={options.resolvePath} onSubmit={options.onSubmit} />+ <CreateWorktreeContent+ deviceId={options.deviceId}+ path={options.path}+ resolvePath={options.resolvePath}+ onSubmit={options.onSubmit}+ />),footer: null,maskClosable: true,diff --git a/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx b/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsxindex bb788852a86..2f676ec9c37 100644--- a/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx@@ -595,10 +595,18 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(const openCreateWorktree = useCallback(() => {setOpen(false);openCreateWorktreeModal({+ // The modal reads the repo's full local branch list itself and draws the+ // generated default from it, so a name is not handed out twice and does+ // not collide with a ref on the `wt` namespace path (see+ // `generateWorktreeBranchName`). It lives there rather than here so the+ // list can be awaited: snapshotting an in-flight (empty) list would hand+ // out a name git is guaranteed to refuse.+ deviceId,onSubmit: handleCreateWorktree,+ path,resolvePath: (branch) => deriveWorktreePath(sourcePath, branch),});- }, [handleCreateWorktree, sourcePath]);+ }, [deviceId, handleCreateWorktree, path, 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 woulddiff --git a/src/features/ChatInput/ControlBar/__tests__/useWorktreeBranchSeed.test.ts b/src/features/ChatInput/ControlBar/__tests__/useWorktreeBranchSeed.test.tsnew file mode 100644index 00000000000..ddb97f07c84--- /dev/null+++ b/src/features/ChatInput/ControlBar/__tests__/useWorktreeBranchSeed.test.ts@@ -0,0 +1,57 @@+import type { DeviceGitBranchListItem } from '@lobechat/types';+import { renderHook, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { gitService } from '@/services/git';++import { useWorktreeBranchSeed } from '../useWorktreeBranchSeed';++const branch = (name: string): DeviceGitBranchListItem => ({ current: false, name });++let listGitBranches: ReturnType<typeof vi.spyOn>;++beforeEach(() => {+ listGitBranches = vi.spyOn(gitService, 'listGitBranches');+});++afterEach(() => {+ vi.restoreAllMocks();+});++const seed = (path: string) => renderHook(() => useWorktreeBranchSeed('device-1', path)).result;++describe('useWorktreeBranchSeed', () => {+ // Regression: the default name is drawn against the repo's branch list, and+ // that list arrives asynchronously. Drawing while the read is still in flight+ // makes it look like "no branches", so a repo whose refs include a branch+ // literally called `wt` was handed `wt/...` and git refused creation with+ // `cannot lock ref 'refs/heads/wt/...': 'refs/heads/wt' exists`.+ it('hands out no name while the branch list is still being read', () => {+ listGitBranches.mockImplementation(() => new Promise(() => {}));++ const result = seed('/repo/cold-cache');++ expect(result.current.isReady).toBe(false);+ expect(result.current.name).toBeUndefined();+ });++ it('avoids the wt/ namespace once a ref on it has been seen', async () => {+ listGitBranches.mockResolvedValue([branch('main'), branch('wt')]);++ const result = seed('/repo/taken-namespace');++ await waitFor(() => expect(result.current.isReady).toBe(true));+ // Only a list that actually contains `wt` produces the flat form, so this+ // value proves the occupying ref reached the draw.+ expect(result.current.name).toMatch(/^wt-\d{12}-[a-z]+-[a-z]+$/);+ });++ it('keeps the wt/ namespace when nothing occupies it', async () => {+ listGitBranches.mockResolvedValue([branch('main'), branch('canary')]);++ const result = seed('/repo/free-namespace');++ await waitFor(() => expect(result.current.isReady).toBe(true));+ expect(result.current.name).toMatch(/^wt\/\d{12}-[a-z]+-[a-z]+$/);+ });+});diff --git a/src/features/ChatInput/ControlBar/useWorktreeBranchSeed.ts b/src/features/ChatInput/ControlBar/useWorktreeBranchSeed.tsnew file mode 100644index 00000000000..e92387f963c--- /dev/null+++ b/src/features/ChatInput/ControlBar/useWorktreeBranchSeed.ts@@ -0,0 +1,57 @@+import { generateWorktreeBranchName } from '@lobechat/const';+import { useCallback, useEffect, useMemo, useState } from 'react';+import useSWR from 'swr';++import { deviceKeys } from '@/libs/swr/keys';+import { gitService } from '@/services/git';++export interface WorktreeBranchSeed {+ /** Whether the branch list has settled. No name may be drawn before this. */+ isReady: boolean;+ /** The generated default, `undefined` until the branch list has settled. */+ name?: string;+ /** Draw a different name from the settled list. */+ reroll: () => void;+}++/**+ * The default branch name for a new worktree, drawn against the working+ * directory's full local branch list.+ *+ * Waiting for that list to settle is the point of this hook. Git stores refs as+ * paths, so a branch literally called `wt` blocks the whole `wt/` namespace —+ * and a name drawn from a list that is still in flight reads as "no branches",+ * handing out a ref git is guaranteed to refuse (`cannot lock ref+ * 'refs/heads/wt/…': 'refs/heads/wt' exists`). The modal snapshots the name when+ * it opens, so a late result could never repair that. Shares the branch+ * switcher's SWR key, which means a branch dropdown opened earlier has the list+ * cached and the name is ready immediately.+ */+export const useWorktreeBranchSeed = (+ deviceId: string | undefined,+ path: string,+): WorktreeBranchSeed => {+ const { data: branches, isLoading } = useSWR(+ deviceKeys.gitBranches(deviceId ?? 'local', path),+ () => gitService.listGitBranches({ deviceId, path }),+ { revalidateOnFocus: false, shouldRetryOnError: false },+ );++ const excludeBranches = useMemo(() => branches?.map((branch) => branch.name) ?? [], [branches]);+ const isReady = !isLoading;++ const [name, setName] = useState<string>();++ // Draw once, and only from a settled list. `current ?? …` keeps a later+ // revalidation from renaming the branch the user is already looking at.+ useEffect(() => {+ if (!isReady) return;+ setName((current) => current ?? generateWorktreeBranchName({ exclude: excludeBranches }));+ }, [excludeBranches, isReady]);++ const reroll = useCallback(() => {+ setName(generateWorktreeBranchName({ exclude: excludeBranches }));+ }, [excludeBranches]);++ return { isReady, name, reroll };+};