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(git): add git worktree listing across local and gateway paths (#15889)

Arvin Xua15ef2e19d9a
diff --git a/apps/desktop/src/main/controllers/GitCtr.ts b/apps/desktop/src/main/controllers/GitCtr.ts
index 196dac3998b..341ef589fa9 100644
--- a/apps/desktop/src/main/controllers/GitCtr.ts
+++ b/apps/desktop/src/main/controllers/GitCtr.ts
@@ -15,6 +15,7 @@ import type {
GitWorkingTreeFiles,
GitWorkingTreePatches,
GitWorkingTreeStatus,
+ GitWorktreeListItem,
} from '@lobechat/electron-client-ipc';
import {
checkoutGitBranch as runCheckoutGitBranch,
@@ -30,6 +31,7 @@ import {
gitInfo as computeGitInfo,
listGitBranches as computeListGitBranches,
listGitRemoteBranches as computeListGitRemoteBranches,
+ listGitWorktrees as computeListGitWorktrees,
pullGitBranch as runPullGitBranch,
pushGitBranch as runPushGitBranch,
renameGitBranch as runRenameGitBranch,
@@ -83,6 +85,11 @@ export default class GitController extends ControllerModule {
return computeListGitRemoteBranches(dirPath);
}
+ @IpcMethod()
+ async listGitWorktrees(dirPath: string): Promise<GitWorktreeListItem[]> {
+ return computeListGitWorktrees(dirPath);
+ }
+
@IpcMethod()
async getGitWorkingTreeStatus(dirPath: string): Promise<GitWorkingTreeStatus> {
return computeGitWorkingTreeStatus(dirPath);
diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.ts
index 1849adb6ca8..12d44c8b1c4 100644
--- a/apps/server/src/routers/lambda/device.ts
+++ b/apps/server/src/routers/lambda/device.ts
@@ -119,6 +119,22 @@ export const deviceRouter = router({
return result ?? null;
}),
+ /**
+ * List the git worktrees attached to the same repository as a directory on a
+ * remote device, via the device's `listGitWorktrees` RPC. Lets the web/remote
+ * worktree picker mirror the local desktop's, populated over IPC.
+ */
+ listGitWorktrees: deviceProcedure
+ .input(z.object({ deviceId: z.string(), path: z.string() }))
+ .query(async ({ ctx, input }) => {
+ const result = await deviceGateway.listGitWorktrees({
+ deviceId: input.deviceId,
+ path: input.path,
+ userId: ctx.userId,
+ });
+ return result ?? [];
+ }),
+
/**
* List the local branches of a directory on a remote device, via the device's
* `listGitBranches` RPC. Lets the web/remote branch switcher populate the same
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index e503c5340d9..851e012bcb8 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -23,6 +23,7 @@ import type {
DeviceGitWorkingTreeFiles,
DeviceGitWorkingTreePatches,
DeviceGitWorkingTreeStatus,
+ DeviceGitWorktreeListItem,
DeviceListProjectSkillsResult,
DeviceLocalFilePreviewResult,
DeviceProjectFileIndexResult,
@@ -207,6 +208,13 @@ export class DeviceGateway {
});
}
+ /** Git worktrees attached to the same repository as a directory on a remote device. */
+ listGitWorktrees(params: { deviceId: string; path: string; userId: string }) {
+ return this.invokeGitRead<DeviceGitWorktreeListItem[]>('listGitWorktrees', params, {
+ path: params.path,
+ });
+ }
+
/**
* List the local branches of a directory on a remote device via the
* `listGitBranches` device RPC, so the web/remote branch switcher can populate
diff --git a/packages/electron-client-ipc/src/types/git.ts b/packages/electron-client-ipc/src/types/git.ts
index d6d0ac28bf7..04546473e98 100644
--- a/packages/electron-client-ipc/src/types/git.ts
+++ b/packages/electron-client-ipc/src/types/git.ts
@@ -39,6 +39,29 @@ export interface GitWorkingTreeStatus {
total: number;
}
+export interface GitWorktreeListItem {
+ /** True for bare repositories, which cannot be opened as a normal cwd. */
+ bare?: boolean;
+ /** Branch short name, absent for detached HEAD or bare entries. */
+ branch?: string;
+ /** True when this worktree is the one containing the queried cwd. */
+ current: boolean;
+ /** True when HEAD is detached. */
+ detached?: boolean;
+ /** Full HEAD SHA reported by `git worktree list --porcelain`. */
+ head?: string;
+ /** True when git marks this worktree as locked. */
+ locked?: boolean;
+ lockReason?: string;
+ /** Absolute worktree path. */
+ path: string;
+ /** True when git marks this worktree as prunable. */
+ prunable?: boolean;
+ pruneReason?: string;
+ /** Dirty-file counts for non-bare, non-prunable worktrees. */
+ status?: GitWorkingTreeStatus;
+}
+
export interface GitWorkingTreeFiles {
/** Repo-relative paths for untracked + staged-as-added files */
added: string[];
diff --git a/packages/local-file-shell/src/git/__tests__/branches.test.ts b/packages/local-file-shell/src/git/__tests__/branches.test.ts
index b3ba6c2acd8..bd43595fd0b 100644
--- a/packages/local-file-shell/src/git/__tests__/branches.test.ts
+++ b/packages/local-file-shell/src/git/__tests__/branches.test.ts
@@ -1,6 +1,6 @@
import { execFileSync } from 'node:child_process';
import { existsSync } from 'node:fs';
-import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
@@ -18,6 +18,7 @@ import {
} from '../branches';
import { getGitAheadBehind, getGitBranch } from '../info';
import { getGitBranchDiff, getGitWorkingTreeFiles, getGitWorkingTreePatches } from '../workingTree';
+import { listGitWorktrees, parseGitWorktreeList } from '../worktrees';
const git = (cwd: string, ...args: string[]): string =>
execFileSync('git', args, { cwd, encoding: 'utf8' }).trim();
@@ -62,6 +63,67 @@ describe('branch read operations', () => {
it('listGitRemoteBranches returns [] when there is no origin', async () => {
expect(await listGitRemoteBranches(repo)).toEqual([]);
});
+
+ it('parseGitWorktreeList handles branch, detached, and locked records', () => {
+ expect(
+ parseGitWorktreeList(
+ [
+ 'worktree /repo',
+ 'HEAD 1111111111111111111111111111111111111111',
+ 'branch refs/heads/main',
+ '',
+ 'worktree /repo-linked',
+ 'HEAD 2222222222222222222222222222222222222222',
+ 'detached',
+ 'locked moving patch',
+ '',
+ ].join('\0'),
+ ),
+ ).toEqual([
+ {
+ branch: 'main',
+ head: '1111111111111111111111111111111111111111',
+ path: '/repo',
+ },
+ {
+ detached: true,
+ head: '2222222222222222222222222222222222222222',
+ locked: true,
+ lockReason: 'moving patch',
+ path: '/repo-linked',
+ },
+ ]);
+ });
+
+ it('listGitWorktrees marks the current worktree and includes dirty status', async () => {
+ git(repo, 'branch', 'feature');
+ const worktreeParent = await mkdtemp(path.join(tmpdir(), 'lfs-worktree-parent-'));
+ cleanup.push(worktreeParent);
+ const linked = path.join(worktreeParent, 'linked');
+ git(repo, 'worktree', 'add', linked, 'feature');
+ await writeFile(path.join(linked, 'new.txt'), 'new\n');
+
+ const worktrees = await listGitWorktrees(repo);
+
+ // `git worktree list` reports paths with symlinks resolved (e.g. macOS
+ // /var -> /private/var), so compare against the realpath of each temp dir.
+ expect(worktrees).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ branch: 'main',
+ current: true,
+ path: await realpath(repo),
+ status: expect.objectContaining({ clean: true }),
+ }),
+ expect.objectContaining({
+ branch: 'feature',
+ current: false,
+ path: await realpath(linked),
+ status: expect.objectContaining({ added: 1, clean: false, total: 1 }),
+ }),
+ ]),
+ );
+ });
});
describe('checkoutGitBranch', () => {
diff --git a/packages/local-file-shell/src/git/index.ts b/packages/local-file-shell/src/git/index.ts
index 2d482cbc040..8d8f0adcac4 100644
--- a/packages/local-file-shell/src/git/index.ts
+++ b/packages/local-file-shell/src/git/index.ts
@@ -3,3 +3,4 @@ export * from './info';
export * from './repoType';
export * from './types';
export * from './workingTree';
+export * from './worktrees';
diff --git a/packages/local-file-shell/src/git/types.ts b/packages/local-file-shell/src/git/types.ts
index b3b34648850..99b9741a602 100644
--- a/packages/local-file-shell/src/git/types.ts
+++ b/packages/local-file-shell/src/git/types.ts
@@ -28,6 +28,20 @@ export interface GitWorkingTreeStatus {
total: number;
}
+export interface GitWorktreeListItem {
+ bare?: boolean;
+ branch?: string;
+ current: boolean;
+ detached?: boolean;
+ head?: string;
+ locked?: boolean;
+ lockReason?: string;
+ path: string;
+ prunable?: boolean;
+ pruneReason?: string;
+ status?: GitWorkingTreeStatus;
+}
+
export interface GitAheadBehind {
ahead: number;
behind: number;
diff --git a/packages/local-file-shell/src/git/worktrees.ts b/packages/local-file-shell/src/git/worktrees.ts
new file mode 100644
index 00000000000..884114c3aac
--- /dev/null
+++ b/packages/local-file-shell/src/git/worktrees.ts
@@ -0,0 +1,125 @@
+import { execFile } from 'node:child_process';
+import { realpath } from 'node:fs/promises';
+import path from 'node:path';
+import { promisify } from 'node:util';
+
+import { getGitWorkingTreeStatus } from './info';
+import type { GitWorkingTreeStatus, GitWorktreeListItem } from './types';
+
+const execFileAsync = promisify(execFile);
+
+const normalizeBranchRef = (ref: string): string =>
+ ref.startsWith('refs/heads/') ? ref.slice('refs/heads/'.length) : ref;
+
+const safeRealpath = async (target: string): Promise<string> => {
+ try {
+ return await realpath(target);
+ } catch {
+ return path.resolve(target);
+ }
+};
+
+interface ParsedWorktree {
+ bare?: boolean;
+ branch?: string;
+ detached?: boolean;
+ head?: string;
+ locked?: boolean;
+ lockReason?: string;
+ path: string;
+ prunable?: boolean;
+ pruneReason?: string;
+}
+
+export const parseGitWorktreeList = (stdout: string): ParsedWorktree[] => {
+ const records: ParsedWorktree[] = [];
+ let current: ParsedWorktree | undefined;
+
+ for (const token of stdout.split('\0')) {
+ if (!token) {
+ if (current) {
+ records.push(current);
+ current = undefined;
+ }
+ continue;
+ }
+
+ const [key, ...rest] = token.split(' ');
+ const value = rest.join(' ');
+
+ if (key === 'worktree') {
+ if (current) records.push(current);
+ current = { path: value };
+ continue;
+ }
+
+ if (!current) continue;
+
+ switch (key) {
+ case 'HEAD': {
+ current.head = value;
+ break;
+ }
+ case 'bare': {
+ current.bare = true;
+ break;
+ }
+ case 'branch': {
+ current.branch = normalizeBranchRef(value);
+ break;
+ }
+ case 'detached': {
+ current.detached = true;
+ break;
+ }
+ case 'locked': {
+ current.locked = true;
+ current.lockReason = value || undefined;
+ break;
+ }
+ case 'prunable': {
+ current.prunable = true;
+ current.pruneReason = value || undefined;
+ break;
+ }
+ }
+ }
+
+ if (current) records.push(current);
+ return records;
+};
+
+const readStatus = async (worktree: ParsedWorktree): Promise<GitWorkingTreeStatus | undefined> => {
+ if (worktree.bare || worktree.prunable) return undefined;
+ return getGitWorkingTreeStatus(worktree.path);
+};
+
+export const listGitWorktrees = async (dirPath: string): Promise<GitWorktreeListItem[]> => {
+ try {
+ const [{ stdout: rootStdout }, { stdout }] = await Promise.all([
+ execFileAsync('git', ['rev-parse', '--show-toplevel'], { cwd: dirPath, timeout: 5000 }),
+ execFileAsync('git', ['worktree', 'list', '--porcelain', '-z'], {
+ cwd: dirPath,
+ timeout: 5000,
+ }),
+ ]);
+
+ const currentRoot = await safeRealpath(rootStdout.trim());
+ const parsed = parseGitWorktreeList(stdout);
+ const statuses = await Promise.all(parsed.map(readStatus));
+
+ return Promise.all(
+ parsed.map(async (worktree, index): Promise<GitWorktreeListItem> => {
+ const worktreePath = await safeRealpath(worktree.path);
+ return {
+ ...worktree,
+ current: worktreePath === currentRoot,
+ path: worktree.path,
+ status: statuses[index],
+ };
+ }),
+ );
+ } catch {
+ return [];
+ }
+};
diff --git a/packages/types/src/device.ts b/packages/types/src/device.ts
index c5c9ef7868e..3a9d7adab8f 100644
--- a/packages/types/src/device.ts
+++ b/packages/types/src/device.ts
@@ -146,6 +146,24 @@ export interface DeviceGitWorkingTreeStatus {
total: number;
}
+/**
+ * One git worktree attached to a repository, returned by the `listGitWorktrees`
+ * device RPC. Mirrors the desktop `GitWorktreeListItem`.
+ */
+export interface DeviceGitWorktreeListItem {
+ bare?: boolean;
+ branch?: string;
+ current: boolean;
+ detached?: boolean;
+ head?: string;
+ locked?: boolean;
+ lockReason?: string;
+ path: string;
+ prunable?: boolean;
+ pruneReason?: string;
+ status?: DeviceGitWorkingTreeStatus;
+}
+
/**
* Commit divergence vs the upstream tracking ref, returned by the
* `getGitAheadBehind` device RPC. Mirrors the desktop shape.
diff --git a/src/services/electron/git.ts b/src/services/electron/git.ts
index 391703ac435..5c8ef273d88 100644
--- a/src/services/electron/git.ts
+++ b/src/services/electron/git.ts
@@ -15,6 +15,7 @@ import {
type GitWorkingTreeFiles,
type GitWorkingTreePatches,
type GitWorkingTreeStatus,
+ type GitWorktreeListItem,
} from '@lobechat/electron-client-ipc';
import { ensureElectronIpc } from '@/utils/electron/ipc';
@@ -52,6 +53,10 @@ class ElectronGitService {
return this.ipc.git.listGitRemoteBranches(dirPath);
}
+ async listGitWorktrees(dirPath: string): Promise<GitWorktreeListItem[]> {
+ return this.ipc.git.listGitWorktrees(dirPath);
+ }
+
async getGitWorkingTreeStatus(dirPath: string): Promise<GitWorkingTreeStatus> {
return this.ipc.git.getGitWorkingTreeStatus(dirPath);
}
diff --git a/src/services/git.ts b/src/services/git.ts
index 698bec9d1b5..4ac9ccb1b51 100644
--- a/src/services/git.ts
+++ b/src/services/git.ts
@@ -14,6 +14,7 @@ import type {
DeviceGitRenameBranchResult,
DeviceGitSyncResult,
DeviceGitWorkingTreeStatus,
+ DeviceGitWorktreeListItem,
} from '@lobechat/types';
import { lambdaClient } from '@/libs/trpc/client';
@@ -244,6 +245,19 @@ class GitService {
: electronGitService.listGitRemoteBranches(path);
}
+ /** Git worktrees attached to the same repository as a working directory. */
+ listGitWorktrees({
+ deviceId,
+ path,
+ }: {
+ deviceId?: string;
+ path: string;
+ }): Promise<DeviceGitWorktreeListItem[]> {
+ return deviceId
+ ? lambdaClient.device.listGitWorktrees.query({ deviceId, path })
+ : electronGitService.listGitWorktrees(path);
+ }
+
/** Revert (discard working-tree changes to) a single file in a working directory. */
revertGitFile({
deviceId,
diff --git a/src/store/device/gitHooks.ts b/src/store/device/gitHooks.ts
index f0fb0107211..40835abd153 100644
--- a/src/store/device/gitHooks.ts
+++ b/src/store/device/gitHooks.ts
@@ -1,5 +1,9 @@
import { isDesktop } from '@lobechat/const';
-import type { DeviceGitAheadBehind, DeviceGitWorkingTreeStatus } from '@lobechat/types';
+import type {
+ DeviceGitAheadBehind,
+ DeviceGitWorkingTreeStatus,
+ DeviceGitWorktreeListItem,
+} from '@lobechat/types';
import { useClientDataSWR } from '@/libs/swr';
import { deviceKeys } from '@/libs/swr/keys';
@@ -47,3 +51,15 @@ export const useFetchGitAheadBehind = (deviceId: string | undefined, path?: stri
() => gitService.getGitAheadBehind({ deviceId, path: path! }),
{ focusThrottleInterval: 5 * 1000, revalidateOnFocus: true, shouldRetryOnError: false },
);
+
+/**
+ * Worktrees attached to the same repository as the current working directory.
+ * Revalidates on focus so temp PR worktrees created outside the app appear
+ * without restarting the conversation.
+ */
+export const useFetchGitWorktrees = (deviceId: string | undefined, path?: string) =>
+ useClientDataSWR<DeviceGitWorktreeListItem[]>(
+ isEnabled(deviceId, path) ? ['git-worktrees', deviceId ?? 'local', path] : null,
+ () => gitService.listGitWorktrees({ deviceId, path: path! }),
+ { focusThrottleInterval: 5 * 1000, revalidateOnFocus: true, shouldRetryOnError: false },
+ );