π€― 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): create new worktrees under ~/.lobehub/worktrees (#22203)
Lobehub Coderfddcb7710414
diff --git a/apps/server/src/routers/lambda/__tests__/deviceGitWorktree.test.ts b/apps/server/src/routers/lambda/__tests__/deviceGitWorktree.test.tsnew file mode 100644index 00000000000..f6b859de08c--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/deviceGitWorktree.test.ts@@ -0,0 +1,95 @@+// @vitest-environment node+import { deriveWorktreePath } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { deviceRouter } from '../device';++const mocks = vi.hoisted(() => ({ addGitWorktree: vi.fn(), queryDeviceSystemInfo: vi.fn() }));++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn() }));+vi.mock('@/database/models/device', () => ({ DeviceModel: class {} }));+vi.mock('@/server/services/deviceGateway', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ deviceGateway: {+ addGitWorktree: mocks.addGitWorktree,+ queryDeviceSystemInfo: mocks.queryDeviceSystemInfo,+ },+}));++/**+ * The server re-derives the target from the trusted `path` + `branch` instead of+ * accepting one from the client, and must land on the same central folder the+ * renderer previews, rooted at the home directory the device reports.+ */+describe('device.addGitWorktree', () => {+ const caller = deviceRouter.createCaller({ userId: 'user' } as never);++ beforeEach(() => {+ vi.clearAllMocks();+ mocks.addGitWorktree.mockResolvedValue({ success: true });+ mocks.queryDeviceSystemInfo.mockResolvedValue({ homePath: '/Users/me' });+ });++ it('sends the central worktree path the renderer previews', async () => {+ await caller.addGitWorktree({ branch: 'feat/x', deviceId: 'device', path: '/code/lobehub' });++ const { worktreePath } = mocks.addGitWorktree.mock.calls[0][0];+ expect(worktreePath).toBe(+ deriveWorktreePath('/code/lobehub', 'feat/x', { homeDir: '/Users/me' }),+ );+ expect(worktreePath).toMatch(/^\/Users\/me\/\.lobehub\/worktrees\/lobehub-[\da-f]{8}\/feat-x$/);+ expect(mocks.queryDeviceSystemInfo).toHaveBeenCalledWith('user', 'device', undefined, {+ maxAgeMs: expect.any(Number),+ });+ });++ // From a linked worktree the client sends the main checkout as `sourcePath`,+ // and both sides key the folder on it.+ it('keys the folder on sourcePath when the call comes from a linked worktree', async () => {+ await caller.addGitWorktree({+ branch: 'feat/x',+ deviceId: 'device',+ path: '/Users/me/.lobehub/worktrees/lobehub-0000beef/feat-a',+ sourcePath: '/code/lobehub',+ });++ expect(mocks.addGitWorktree.mock.calls[0][0]).toMatchObject({+ path: '/Users/me/.lobehub/worktrees/lobehub-0000beef/feat-a',+ worktreePath: deriveWorktreePath('/code/lobehub', 'feat/x', { homeDir: '/Users/me' }),+ });+ });++ it('falls back to the sibling layout when the device reports no home', async () => {+ mocks.queryDeviceSystemInfo.mockResolvedValue(undefined);++ await caller.addGitWorktree({ branch: 'feat/x', deviceId: 'device', path: '/code/lobehub' });++ expect(mocks.addGitWorktree.mock.calls[0][0].worktreePath).toBe('/code/lobehub-feat-x');+ });++ it('ignores a client-supplied absolute target', async () => {+ await caller.addGitWorktree({+ branch: 'feat/x',+ deviceId: 'device',+ path: '/code/lobehub',+ worktreePath: '/etc/evil',+ } as never);++ expect(mocks.addGitWorktree.mock.calls[0][0].worktreePath).toBe(+ deriveWorktreePath('/code/lobehub', 'feat/x', { homeDir: '/Users/me' }),+ );+ });++ it('keeps the sibling fallback next to the repo git runs in, not a client sourcePath', async () => {+ mocks.queryDeviceSystemInfo.mockResolvedValue(undefined);++ await caller.addGitWorktree({+ branch: 'feat/x',+ deviceId: 'device',+ path: '/code/lobehub',+ sourcePath: '/Users/me/.ssh/x',+ });++ expect(mocks.addGitWorktree.mock.calls[0][0].worktreePath).toBe('/code/lobehub-feat-x');+ });+});diff --git a/apps/server/src/routers/lambda/device/git.ts b/apps/server/src/routers/lambda/device/git.tsindex 4f6ee8c1c74..8f25f09226b 100644--- a/apps/server/src/routers/lambda/device/git.ts+++ b/apps/server/src/routers/lambda/device/git.ts@@ -1,5 +1,6 @@import { deriveWorktreePath } from '@lobechat/types';import { TRPCError } from '@trpc/server';+import debug from 'debug';import { z } from 'zod';import { requireWorkspaceRoleWhenScoped } from '@/business/server/trpc-middlewares/workspaceAuth';@@ -9,6 +10,11 @@ import { deviceGateway } from '@/server/services/deviceGateway';import { assertWorkspaceRootApproved } from '../deviceWorkspaceGuard';import { deviceProcedure } from './procedures';+const log = debug('lobe-server:device-git');++/** A device's home directory rarely changes; reuse a recent system-info read. */+const WORKTREE_HOME_MAX_AGE_MS = 10 * 60 * 1000;+/*** A gateway read that resolved to `undefined` (gateway unconfigured, device* offline, RPC failed). Thrown rather than mapped to `[]` or `null`: `[]` is@@ -265,10 +271,15 @@ export const gitRouter = router({* 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.+ * The target directory is derived here from the trusted `sourcePath` (the+ * repo's main checkout, falling back to `path` for released clients) and+ * `branch` β `<home>/.lobehub/worktrees/<repoKey>/<branch>`, with `<home>`+ * from the device's reported `homePath` β 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. A device that does not report its home falls back to the+ * `<repo>-<branch>` sibling layout. The path is always absolute, so released+ * clients that run `git worktree add` verbatim keep working.*/addGitWorktree: deviceProcedure.input(@@ -276,18 +287,34 @@ export const gitRouter = router({branch: z.string(),deviceId: z.string(),path: z.string(),+ /** The repo's main checkout, which keys the folder; `path` may be a linked worktree. */+ sourcePath: z.string().optional(),}),)- .mutation(async ({ ctx, input }) =>- deviceGateway.addGitWorktree({+ .mutation(async ({ ctx, input }) => {+ const systemInfo = await deviceGateway.queryDeviceSystemInfo(+ ctx.userId,+ input.deviceId,+ ctx.workspaceId,+ { maxAgeMs: WORKTREE_HOME_MAX_AGE_MS },+ );+ const homeDir = systemInfo?.homePath;+ if (!homeDir)+ log('addGitWorktree: no homePath for deviceId=%s, using sibling layout', input.deviceId);+ // `sourcePath` only names and hashes the central folder; the sibling+ // fallback places the checkout next to its key, so it keeps keying on+ // `path`, the repo git actually runs in, rather than on a client string.+ const keyPath = homeDir ? input.sourcePath || input.path : input.path;++ return deviceGateway.addGitWorktree({branch: input.branch,deviceId: input.deviceId,path: input.path,userId: ctx.userId,workspaceId: ctx.workspaceId,- worktreePath: deriveWorktreePath(input.path, input.branch),- }),- ),+ worktreePath: deriveWorktreePath(keyPath, input.branch, { homeDir }),+ });+ }),/*** Pull (`--ff-only`) the current branch of a directory on a remote device, via* the device's `pullGitBranch` RPC.diff --git a/packages/const/src/worktreeName.ts b/packages/const/src/worktreeName.tsindex 07f675cc856..5198bef8470 100644--- a/packages/const/src/worktreeName.ts+++ b/packages/const/src/worktreeName.ts@@ -6,7 +6,7 @@* 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`).+ * folder name (`deriveWorktreePath` turns it into `wt-202610020308-quiet-hill`).*//** Namespace prefix, so worktrees created by the app group together in the branch list. */diff --git a/packages/device-control/src/__tests__/workspaceGuard.test.ts b/packages/device-control/src/__tests__/workspaceGuard.test.tsnew file mode 100644index 00000000000..7cbd3bd022e--- /dev/null+++ b/packages/device-control/src/__tests__/workspaceGuard.test.ts@@ -0,0 +1,52 @@+import { mkdir, mkdtemp, realpath, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { assertEntriesWithinWorkspace, WORKSPACE_ESCAPE_MESSAGE } from '../workspaceGuard';++let home: string;++beforeEach(async () => {+ home = await realpath(await mkdtemp(path.join(tmpdir(), 'dc-guard-home-')));+ vi.stubEnv('HOME', home);+ vi.stubEnv('USERPROFILE', home);+});++afterEach(async () => {+ vi.unstubAllEnvs();+ await rm(home, { force: true, recursive: true });+});++// New worktrees land in `~/.lobehub/worktrees/<repoKey>/<branch>` and become the+// conversation's working directory, so the guard must treat them like any root.+describe('assertEntriesWithinWorkspace under the central worktree root', () => {+ const relRoot = '.lobehub/worktrees/lobehub-1a2b3c4d/feat-x';++ it('allows entries inside a worktree under ~/.lobehub', async () => {+ await mkdir(path.join(home, relRoot), { recursive: true });++ for (const root of [`~/${relRoot}`, path.join(home, relRoot)]) {+ await expect(+ assertEntriesWithinWorkspace(root, [+ path.join(home, relRoot, 'src/index.ts'),+ path.join(home, relRoot, 'new/nested/file.ts'),+ ]),+ ).resolves.toBeUndefined();+ }+ });++ it('still refuses entries in a sibling worktree or elsewhere under ~/.lobehub', async () => {+ await mkdir(path.join(home, relRoot), { recursive: true });++ await expect(+ assertEntriesWithinWorkspace(`~/${relRoot}`, [+ path.join(home, '.lobehub/worktrees/lobehub-1a2b3c4d/feat-y/a.ts'),+ ]),+ ).rejects.toThrow(WORKSPACE_ESCAPE_MESSAGE);+ await expect(+ assertEntriesWithinWorkspace(`~/${relRoot}`, [path.join(home, '.lobehub/credentials.json')]),+ ).rejects.toThrow(WORKSPACE_ESCAPE_MESSAGE);+ });+});diff --git a/packages/local-file-shell/src/git/__tests__/addWorktree.test.ts b/packages/local-file-shell/src/git/__tests__/addWorktree.test.tsnew file mode 100644index 00000000000..19d70d0e9a1--- /dev/null+++ b/packages/local-file-shell/src/git/__tests__/addWorktree.test.ts@@ -0,0 +1,132 @@+import { execFileSync } from 'node:child_process';+import { existsSync } from 'node:fs';+import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getGitBranch } from '../info';+import { addGitWorktree, listGitWorktrees } from '../worktrees';++const git = (cwd: string, ...args: string[]): string =>+ execFileSync('git', args, { cwd, encoding: 'utf8' }).trim();++const initRepo = async (parent: string, name = 'lobehub'): Promise<string> => {+ const dir = path.join(parent, name);+ await mkdir(dir, { recursive: true });+ execFileSync('git', ['-c', 'init.defaultBranch=main', 'init'], { cwd: dir });+ git(dir, 'config', 'user.email', '[email protected]');+ git(dir, 'config', 'user.name', 'Test');+ git(dir, 'config', 'commit.gpgsign', 'false');+ await writeFile(path.join(dir, 'a.txt'), 'hello\n');+ git(dir, 'add', 'a.txt');+ git(dir, 'commit', '-m', 'init');+ return dir;+};++/**+ * The `~/.lobehub/worktrees/<repoKey>/<branchFolder>` shape `deriveWorktreePath`+ * (`@lobechat/types`, which owns the repo-key hash) hands the device.+ */+const deriveWorktreePath = (sourcePath: string, branch: string, hash = '0000beef'): string =>+ `${home}/.lobehub/worktrees/${path.basename(sourcePath)}-${hash}/${branch.replaceAll('/', '-') || 'worktree'}`;++let home: string;+let code: string;+let repo: string;++beforeEach(async () => {+ // A disposable stand-in for the home directory the server passes in.+ home = await realpath(await mkdtemp(path.join(tmpdir(), 'lfs-home-')));+ code = await realpath(await mkdtemp(path.join(tmpdir(), 'lfs-code-')));+ repo = await initRepo(code);+});++afterEach(async () => {+ await Promise.all([home, code].map((dir) => rm(dir, { force: true, recursive: true })));+});++describe('addGitWorktree', () => {+ it('creates the worktree and its missing parent folders under ~/.lobehub/worktrees', async () => {+ const worktreePath = deriveWorktreePath(repo, 'feat/x');+ const result = await addGitWorktree({ branch: 'feat/x', path: repo, worktreePath });++ expect(result.success).toBe(true);+ expect(+ result.worktreePath?.startsWith(path.join(home, '.lobehub', 'worktrees') + path.sep),+ ).toBe(true);+ expect(path.basename(result.worktreePath!)).toBe('feat-x');+ expect(await getGitBranch(result.worktreePath!)).toEqual({ branch: 'feat/x' });+ expect((await listGitWorktrees(repo)).map((w) => w.path)).toContain(result.worktreePath);+ });++ it('keeps same-named repos in separate folders', async () => {+ const other = await initRepo(path.join(code, 'other'));+ const a = await addGitWorktree({+ branch: 'feat/x',+ path: repo,+ worktreePath: deriveWorktreePath(repo, 'feat/x'),+ });+ const b = await addGitWorktree({+ branch: 'feat/x',+ path: other,+ worktreePath: deriveWorktreePath(other, 'feat/x', '1111cafe'),+ });++ expect(a.success && b.success).toBe(true);+ expect(a.worktreePath).not.toBe(b.worktreePath);+ });++ it('still lists an existing sibling worktree next to new central ones', async () => {+ const sibling = path.join(code, 'lobehub-legacy');+ git(repo, 'worktree', 'add', '-b', 'legacy', sibling);++ const result = await addGitWorktree({+ branch: 'feat/y',+ path: repo,+ worktreePath: deriveWorktreePath(repo, 'feat/y'),+ });++ expect(result.success).toBe(true);+ expect(existsSync(sibling)).toBe(true);+ const paths = (await listGitWorktrees(repo)).map((w) => w.path);+ expect(paths).toEqual(expect.arrayContaining([repo, sibling, result.worktreePath]));+ });++ it('reports an existing target folder instead of reusing it', async () => {+ const worktreePath = deriveWorktreePath(repo, 'feat/x');+ await mkdir(worktreePath, { recursive: true });++ const result = await addGitWorktree({ branch: 'feat/x', path: repo, worktreePath });++ expect(result).toEqual({+ error: `Worktree folder already exists: ${worktreePath}`,+ success: false,+ });+ expect(git(repo, 'branch', '--list', 'feat/x')).toBe('');+ });++ it('reports an unwritable worktree root', async () => {+ // A file where the `.lobehub` folder should be makes the mkdir fail even+ // when the tests run as root (where permission bits are ignored).+ await writeFile(path.join(home, '.lobehub'), '');+ const worktreePath = deriveWorktreePath(repo, 'feat/x');++ const result = await addGitWorktree({ branch: 'feat/x', path: repo, worktreePath });++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/^Cannot create worktree folder .*\.lobehub.*: E[A-Z]+$/);+ expect(git(repo, 'branch', '--list', 'feat/x')).toBe('');+ });++ it('rejects an empty branch and a relative target', async () => {+ expect(+ await addGitWorktree({ branch: ' ', path: repo, worktreePath: deriveWorktreePath(repo, '') }),+ ).toEqual({ error: 'Branch name is required', success: false });+ expect(await addGitWorktree({ branch: 'feat/x', path: repo, worktreePath: 'rel/x' })).toEqual({+ error: 'Worktree path must be absolute: rel/x',+ success: false,+ });+ });+});diff --git a/packages/local-file-shell/src/git/worktrees.ts b/packages/local-file-shell/src/git/worktrees.tsindex bcd18a7c724..b3d3ba434df 100644--- a/packages/local-file-shell/src/git/worktrees.ts+++ b/packages/local-file-shell/src/git/worktrees.ts@@ -1,5 +1,6 @@import { execFile } from 'node:child_process';-import { realpath } from 'node:fs/promises';+import { existsSync } from 'node:fs';+import { mkdir, realpath } from 'node:fs/promises';import path from 'node:path';import { promisify } from 'node:util';@@ -171,8 +172,10 @@ export const removeGitWorktree = async (payload: {* 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.+ * directory (`deriveWorktreePath`, under `~/.lobehub/worktrees/`). The missing+ * parent folders are created first, and an existing target or an unwritable+ * root is reported as such instead of git's generic failure. Returns the+ * created path on success so the UI can switch into it.*/export const addGitWorktree = async (payload: {branch: string;@@ -186,6 +189,19 @@ export const addGitWorktree = async (payload: {if (isInvalidBranchRef(branch))return { error: `Invalid branch name: ${branch}`, success: false };+ if (!path.isAbsolute(worktreePath))+ return { error: `Worktree path must be absolute: ${worktreePath}`, success: false };+ if (existsSync(worktreePath))+ return { error: `Worktree folder already exists: ${worktreePath}`, success: false };++ const parent = path.dirname(worktreePath);+ try {+ await mkdir(parent, { recursive: true });+ } catch (error: any) {+ const reason = error?.code ?? error?.message ?? 'unknown error';+ return { error: `Cannot create worktree folder ${parent}: ${reason}`, success: false };+ }+try {await execFileAsync('git', ['worktree', 'add', '-b', branch, worktreePath], {cwd: dirPath,diff --git a/packages/types/src/device.test.ts b/packages/types/src/device.test.tsindex 667a2917c97..d0f94ff3dc1 100644--- a/packages/types/src/device.test.ts+++ b/packages/types/src/device.test.ts@@ -166,18 +166,62 @@ describe('workingDirConfigSchema', () => {});describe('deriveWorktreePath', () => {+ const home = '/Users/me';+ const key = (sourcePath: string) =>+ deriveWorktreePath(sourcePath, 'b', { homeDir: home }).split(/[/\\]/).at(-2) as string;+// 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',+ // (`wt/<timestamp>-<adjective>-<noun>`): the `/` folds to `-`, and the+ // checkout lands under the central root, keyed by repo name + path hash.+ it('folds a generated branch into the central worktree root', () => {+ expect(+ deriveWorktreePath('/code/lobehub', 'wt/202610020308-quiet-hill', { homeDir: home }),+ ).toBe(`/Users/me/.lobehub/worktrees/${key('/code/lobehub')}/wt-202610020308-quiet-hill`);+ expect(key('/code/lobehub')).toMatch(/^lobehub-[\da-f]{8}$/);+ // Trailing separators on either input don't change the result.+ expect(deriveWorktreePath('/code/lobehub/', 'feat/x', { homeDir: '/Users/me/' })).toBe(+ deriveWorktreePath('/code/lobehub', 'feat/x', { homeDir: home }),);});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',+ const source = 'C:\\code\\lobehub';+ expect(+ deriveWorktreePath(source, 'wt/202610020308-quiet-hill', { homeDir: 'C:\\Users\\me' }),+ ).toBe(`C:\\Users\\me\\.lobehub\\worktrees\\${key(source)}\\wt-202610020308-quiet-hill`);+ });++ it('keeps same-named repos at different paths apart', () => {+ const a = deriveWorktreePath('/work/a/lobehub', 'feat/x', { homeDir: home });+ const b = deriveWorktreePath('/work/b/lobehub', 'feat/x', { homeDir: home });+ expect(a).not.toBe(b);+ expect(key('/work/a/lobehub')).toMatch(/^lobehub-/);+ expect(key('/work/b/lobehub')).toMatch(/^lobehub-/);+ });++ it('falls back to a fixed folder for an empty or fully folded branch', () => {+ const root = `/Users/me/.lobehub/worktrees/${key('/code/lobehub')}`;+ expect(deriveWorktreePath('/code/lobehub', '', { homeDir: home })).toBe(`${root}/worktree`);+ expect(deriveWorktreePath('/code/lobehub', ' / ~ ', { homeDir: home })).toBe(+ `${root}/worktree`,+ );+ });++ it('cannot climb out of the repo key folder', () => {+ const root = `/Users/me/.lobehub/worktrees/${key('/code/lobehub')}`;+ expect(deriveWorktreePath('/code/lobehub', '..', { homeDir: home })).toBe(`${root}/worktree`);+ expect(deriveWorktreePath('/code/lobehub', '../../etc', { homeDir: home })).toBe(`${root}/etc`);+ });++ // Without a known home (a device that does not report one) the previous+ // sibling layout is kept, so released devices still get an absolute path.+ it('falls back to a sibling folder without a home directory', () => {+ expect(deriveWorktreePath('/code/lobehub', 'wt/202610020308-quiet-hill')).toBe(+ '/code/lobehub-wt-202610020308-quiet-hill',+ );+ expect(deriveWorktreePath('C:\\code\\lobehub', 'wt/x', { homeDir: ' ' })).toBe(+ 'C:\\code\\lobehub-wt-x',);+ expect(deriveWorktreePath('/code/lobehub', '')).toBe('/code/lobehub');});});diff --git a/packages/types/src/device.ts b/packages/types/src/device.tsindex 66397bd4168..25a1308e425 100644--- a/packages/types/src/device.ts+++ b/packages/types/src/device.ts@@ -184,7 +184,7 @@ export const getWorkingDirEffectivePath = (return entry.git?.activeWorktree || entry.path;};-export { deriveWorktreePath } from './worktreePath';+export { deriveWorktreePath, type DeriveWorktreePathOptions } from './worktreePath';export interface WorkingDirEntry extends WorkingDirConfig {/**diff --git a/packages/types/src/worktreePath.ts b/packages/types/src/worktreePath.tsindex 8b8fcb22f41..319de4c370e 100644--- a/packages/types/src/worktreePath.ts+++ b/packages/types/src/worktreePath.ts@@ -1,19 +1,56 @@/**- * 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.+ * Derive the target directory for a new worktree under the central root+ * `<homeDir>/.lobehub/worktrees/<repoKey>/<branchFolder>`, e.g. `/code/lobehub`+ * + `feat/x` β `/Users/me/.lobehub/worktrees/lobehub-1a2b3c4d/feat-x`. `repoKey`+ * is the repo folder name plus a short hash of the source path, so two repos+ * that share a name never land in the same folder. 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.+ *+ * This package also runs in the browser, so the caller passes the home+ * directory of the machine that owns the repo (the server reads it from the+ * device's reported `homePath`). Without one it falls back to the previous+ * layout, a `<repoName>-<branch>` sibling of the source repo, so a device that+ * cannot report its home still gets a usable absolute path. Existing sibling+ * worktrees are untouched β `git worktree list` still reports them.*/const isSep = (ch: string): boolean => ch === '/' || ch === '\\';-export const deriveWorktreePath = (sourcePath: string, branch: string): string => {+const WORKTREE_ROOT_SEGMENTS = ['.lobehub', 'worktrees'] as const;++/** Folder used when the branch folds to nothing (empty or all illegal characters). */+const EMPTY_BRANCH_FOLDER = 'worktree';++/**+ * 32-bit FNV-1a as 8 hex chars. Not for security β only to tell same-named repos+ * apart β but it must be synchronous and identical in the browser and on Node,+ * which rules out `crypto.subtle` and `node:crypto`.+ */+const shortHash = (input: string): string => {+ let hash = 0x81_1c_9d_c5;+ for (let i = 0; i < input.length; i += 1) {+ hash ^= input.charCodeAt(i);+ hash = Math.imul(hash, 0x01_00_01_93);+ }+ return (hash >>> 0).toString(16).padStart(8, '0');+};++export interface DeriveWorktreePathOptions {+ /** Home directory of the machine that owns the repo; omitted β sibling layout. */+ homeDir?: string;+}++export const deriveWorktreePath = (+ sourcePath: string,+ branch: string,+ { homeDir }: DeriveWorktreePathOptions = {},+): 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 β@@ -28,9 +65,23 @@ export const deriveWorktreePath = (sourcePath: string, branch: string): string =const folded = branch.trim().replaceAll(/[\s~^:?*[\]\\/]+/g, '-');let start = 0;let end = folded.length;- while (start < end && folded[start] === '-') start += 1;++ if (!homeDir?.trim()) {+ 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;+ }++ // Leading '.' is stripped too: the folder sits inside the central root, so a+ // `.` / `..` branch must not resolve to the repo key folder or its parent.+ while (start < end && (folded[start] === '-' || 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;+ const branchFolder = folded.slice(start, end) || EMPTY_BRANCH_FOLDER;+ const repoKey = `${repoName}-${shortHash(trimmed)}`;++ let he = homeDir.length;+ while (he > 0 && isSep(homeDir[he - 1])) he -= 1;+ return [homeDir.slice(0, he), ...WORKTREE_ROOT_SEGMENTS, repoKey, branchFolder].join(sep);};diff --git a/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx b/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsxindex e9c0206b590..ddfb9f8341c 100644--- a/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx@@ -41,6 +41,7 @@ import { gitService } from '@/services/git';import { openCreateWorktreeModal } from './CreateWorktreeModal';import gitMenuTriggerStyles from './gitMenuTrigger.module.css';import { useSwitchWorktree } from './useSwitchWorktree';+import { useWorktreeHomeDir } from './useWorktreeHomeDir';import { getPathName, isDisabled, normalizeDisplayPath } from './worktreeHelpers';const spin = stylex.keyframes({ to: { transform: 'rotate(360deg)' } });@@ -396,6 +397,7 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(const [removingPaths, setRemovingPaths] = useState<Set<string>>(() => new Set());const currentRowRef = useRef<HTMLDivElement>(null);const switchWorktree = useSwitchWorktree({ agentId, isGithub, sourcePath, topicId });+ const resolveHomeDir = useWorktreeHomeDir(deviceId, open);// Clear the query each time the dropdown closes so it reopens unfiltered.useEffect(() => {@@ -511,9 +513,15 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(// 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 });+ async (branch: string, homeDir: string | undefined): Promise<string | undefined> => {+ const worktreePath = deriveWorktreePath(sourcePath, branch, { homeDir });+ const result = await gitService.addGitWorktree({+ branch,+ deviceId,+ path,+ sourcePath,+ worktreePath,+ });if (!result.success) return result.error || t('workingDirectory.createWorktreeFailed');// Point the conversation at the freshly created worktree, then reconcile@@ -525,8 +533,11 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>([deviceId, onWorktreesChange, path, sourcePath, switchWorktree, t],);- const openCreateWorktree = useCallback(() => {+ const openCreateWorktree = useCallback(async () => {setOpen(false);+ // Resolved once, so the previewed folder is the one submitted (and the one+ // the server derives from the same reported home).+ const homeDir = await resolveHomeDir();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@@ -535,11 +546,11 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(// list can be awaited: snapshotting an in-flight (empty) list would hand// out a name git is guaranteed to refuse.deviceId,- onSubmit: handleCreateWorktree,+ onSubmit: (branch) => handleCreateWorktree(branch, homeDir),path,- resolvePath: (branch) => deriveWorktreePath(sourcePath, branch),+ resolvePath: (branch) => deriveWorktreePath(sourcePath, branch, { homeDir }),});- }, [deviceId, handleCreateWorktree, path, sourcePath]);+ }, [deviceId, handleCreateWorktree, path, resolveHomeDir, 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__/WorktreeSwitcher.test.tsx b/src/features/ChatInput/ControlBar/__tests__/WorktreeSwitcher.test.tsxindex 2272924c33d..6c35b438222 100644--- a/src/features/ChatInput/ControlBar/__tests__/WorktreeSwitcher.test.tsx+++ b/src/features/ChatInput/ControlBar/__tests__/WorktreeSwitcher.test.tsx@@ -1,3 +1,4 @@+import { deriveWorktreePath } from '@lobechat/types';import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';import type { ReactNode } from 'react';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -8,6 +9,8 @@ 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 addGitWorktreeMock = vi.hoisted(() => vi.fn());+const openCreateWorktreeModalMock = vi.hoisted(() => vi.fn());const removeGitWorktreeMock = vi.hoisted(() => vi.fn());const toastLoadingCloseMock = vi.hoisted(() => vi.fn());const toastLoadingMock = vi.hoisted(() =>@@ -20,10 +23,19 @@ vi.mock('../useCommitWorkingDirectory', () => ({vi.mock('@/services/git', () => ({gitService: {+ addGitWorktree: addGitWorktreeMock,removeGitWorktree: removeGitWorktreeMock,},}));+vi.mock('../CreateWorktreeModal', () => ({+ openCreateWorktreeModal: openCreateWorktreeModalMock,+}));++vi.mock('../useWorktreeHomeDir', () => ({+ useWorktreeHomeDir: () => async () => '/Users/me',+}));+vi.mock('@lobehub/ui', async (importOriginal) => {const actual = await importOriginal<Record<string, unknown>>();const factories: ((original: typeof importOriginal) => unknown)[] = [@@ -526,4 +538,52 @@ describe('WorktreeSwitcher', () => {expect(commitMock).toHaveBeenCalledWith({ path: '/repo', repoType: 'git' });});++ // From inside a linked worktree `path` is that worktree, but the folder is+ // keyed on the repo's main checkout, which the server receives as `sourcePath`.+ it('creates new worktrees under the central root of the repo owner home', async () => {+ addGitWorktreeMock.mockResolvedValue({ success: false, error: 'boom' });+ render(+ <WorktreeSwitcher+ isGithub+ agentId="agent-1"+ currentBranch="feat/current"+ deviceId="device-1"+ path="/Users/me/.lobehub/worktrees/lobehub-0000beef/feat-current"+ sourcePath="/code/lobehub"+ worktrees={[+ {+ branch: 'main',+ current: false,+ path: '/code/lobehub',+ status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },+ },+ {+ branch: 'feat/current',+ current: true,+ path: '/Users/me/.lobehub/worktrees/lobehub-0000beef/feat-current',+ status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },+ },+ ]}+ />,+ );++ fireEvent.click(screen.getByText('workingDirectory.createWorktreeAction'));++ await waitFor(() => expect(openCreateWorktreeModalMock).toHaveBeenCalledTimes(1));+ const options = openCreateWorktreeModalMock.mock.calls[0][0];+ const preview = options.resolvePath('feat/x');+ expect(preview).toBe(deriveWorktreePath('/code/lobehub', 'feat/x', { homeDir: '/Users/me' }));++ // A failed create is reported back to the modal instead of switching.+ await expect(options.onSubmit('feat/x')).resolves.toBe('boom');+ expect(addGitWorktreeMock).toHaveBeenCalledWith({+ branch: 'feat/x',+ deviceId: 'device-1',+ path: '/Users/me/.lobehub/worktrees/lobehub-0000beef/feat-current',+ sourcePath: '/code/lobehub',+ worktreePath: preview,+ });+ expect(commitMock).not.toHaveBeenCalled();+ });});diff --git a/src/features/ChatInput/ControlBar/__tests__/useWorktreeHomeDir.test.ts b/src/features/ChatInput/ControlBar/__tests__/useWorktreeHomeDir.test.tsnew file mode 100644index 00000000000..7c7edad8b97--- /dev/null+++ b/src/features/ChatInput/ControlBar/__tests__/useWorktreeHomeDir.test.ts@@ -0,0 +1,67 @@+import { act, renderHook, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useElectronStore } from '@/store/electron';++import { useWorktreeHomeDir } from '../useWorktreeHomeDir';++const getDeviceSystemInfoMock = vi.hoisted(() => vi.fn());++vi.mock('@/services/device', () => ({+ deviceService: { getDeviceSystemInfo: getDeviceSystemInfoMock },+}));++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ useActiveWorkspaceId: () => null,+}));++const setLocalHome = (home?: string) =>+ useElectronStore.setState((s) => ({+ appState: { ...s.appState, userPath: home ? ({ home } as never) : undefined },+ }));++describe('useWorktreeHomeDir', () => {+ beforeEach(() => {+ getDeviceSystemInfoMock.mockReset();+ setLocalHome('/Users/local');+ });++ it('uses the desktop home for the local machine without asking a device', async () => {+ const { result } = renderHook(() => useWorktreeHomeDir(undefined, true));++ await expect(result.current()).resolves.toBe('/Users/local');+ expect(getDeviceSystemInfoMock).not.toHaveBeenCalled();+ });++ it('does not ask a remote device until prefetch or resolve', async () => {+ getDeviceSystemInfoMock.mockResolvedValue({ homePath: '/home/remote' });++ const { result } = renderHook(() => useWorktreeHomeDir('device-lazy'));+ expect(getDeviceSystemInfoMock).not.toHaveBeenCalled();++ await expect(result.current()).resolves.toBe('/home/remote');+ expect(getDeviceSystemInfoMock).toHaveBeenCalledWith({ deviceId: 'device-lazy' });+ });++ it('reuses the prefetched home a remote device reports', async () => {+ getDeviceSystemInfoMock.mockResolvedValue({ homePath: '/home/remote' });++ const { result } = renderHook(() => useWorktreeHomeDir('device-prefetch', true));+ await waitFor(() => expect(getDeviceSystemInfoMock).toHaveBeenCalledTimes(1));++ // Let SWR commit the prefetched answer before resolving.+ await act(async () => {});++ await expect(result.current()).resolves.toBe('/home/remote');+ expect(getDeviceSystemInfoMock).toHaveBeenCalledTimes(1);+ });++ it('resolves undefined for a device that reports no home or fails', async () => {+ getDeviceSystemInfoMock.mockResolvedValueOnce(undefined);+ const { result } = renderHook(() => useWorktreeHomeDir('device-no-home'));+ await expect(result.current()).resolves.toBeUndefined();++ getDeviceSystemInfoMock.mockRejectedValueOnce(new Error('offline'));+ await expect(result.current()).resolves.toBeUndefined();+ });+});diff --git a/src/features/ChatInput/ControlBar/useWorktreeHomeDir.ts b/src/features/ChatInput/ControlBar/useWorktreeHomeDir.tsnew file mode 100644index 00000000000..d9cf6348bab--- /dev/null+++ b/src/features/ChatInput/ControlBar/useWorktreeHomeDir.ts@@ -0,0 +1,36 @@+import { useCallback } from 'react';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { useClientDataSWR } from '@/libs/swr';+import { deviceKeys } from '@/libs/swr/keys';+import { deviceService } from '@/services/device';+import { useElectronStore } from '@/store/electron';+import { desktopStateSelectors } from '@/store/electron/selectors';++/**+ * Resolve the home directory of the machine that owns the repo, for+ * `deriveWorktreePath`. A remote device's home comes from the `homePath` it+ * reports β the same value the server derives from β and the local machine's+ * from the desktop app state. `prefetch` starts the remote read early (while+ * the worktree menu is open) so the create modal opens without waiting.+ * Resolves `undefined` when unknown, which derives the sibling-folder fallback,+ * matching the server for a device that does not report its home.+ */+export const useWorktreeHomeDir = (deviceId?: string, prefetch = false) => {+ const workspaceId = useActiveWorkspaceId();+ const { data } = useClientDataSWR(+ deviceId && prefetch ? deviceKeys.systemInfo(workspaceId, deviceId) : null,+ () => deviceService.getDeviceSystemInfo({ deviceId: deviceId! }),+ { revalidateOnFocus: false },+ );++ return useCallback(async (): Promise<string | undefined> => {+ if (!deviceId)+ return desktopStateSelectors.userHomePath(useElectronStore.getState()) || undefined;+ if (data) return data.homePath || undefined;+ // An unreachable device can't create a worktree either; the sibling+ // fallback only shapes the preview until the create call reports why.+ const info = await deviceService.getDeviceSystemInfo({ deviceId }).catch(() => undefined);+ return info?.homePath || undefined;+ }, [data, deviceId]);+};diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex a33bef5dc0f..7847403f2a6 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -425,6 +425,11 @@ export const deviceKeys = {workspaceId,deviceId,]),+ systemInfo: def('device:systemInfo', (workspaceId: string | null, deviceId: string) => [+ 'device:systemInfo',+ workspaceId,+ deviceId,+ ]),browseDirectory: def('device:browseDirectory',(workspaceId: string | null, deviceId: string, path?: string, cursor?: string) =>diff --git a/src/services/device.ts b/src/services/device.tsindex 4c88e3a41ba..01ba65a337b 100644--- a/src/services/device.ts+++ b/src/services/device.ts@@ -129,6 +129,11 @@ class DeviceService {return lambdaClient.device.listListeningPorts.query(input);}+ /** The device's reported paths and runtime info (home, desktop, shell, ...). */+ getDeviceSystemInfo(input: Parameters<DeviceClient['getDeviceSystemInfo']['query']>[0]) {+ return lambdaClient.device.getDeviceSystemInfo.query(input);+ }+/** Where the device's desktop app update stands; never starts a check. */getAppUpdateState(input: Parameters<DeviceClient['getAppUpdateState']['query']>[0]) {return lambdaClient.device.getAppUpdateState.query(input);diff --git a/src/services/git.ts b/src/services/git.tsindex 2fbc91f690c..2e46bae7960 100644--- a/src/services/git.ts+++ b/src/services/git.ts@@ -143,15 +143,18 @@ class GitService {branch,deviceId,path,+ sourcePath,worktreePath,}: {branch: string;deviceId?: string;path: string;+ /** The repo's main checkout; the server keys the target folder on it. */+ sourcePath?: string;worktreePath: string;}): Promise<DeviceGitAddWorktreeResult> {return deviceId- ? lambdaClient.device.addGitWorktree.mutate({ branch, deviceId, path })+ ? lambdaClient.device.addGitWorktree.mutate({ branch, deviceId, path, sourcePath }): electronGitService.addGitWorktree({ branch, path, worktreePath });}