🤯 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
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';
import WorktreeSwitcher from '../WorktreeSwitcher';
const commitMock = vi.hoisted(() => vi.fn());
const confirmModalMock = vi.hoisted(() => vi.fn());
const messageErrorMock = vi.hoisted(() => vi.fn());
const messageSuccessMock = vi.hoisted(() => vi.fn());
const 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(() =>
vi.fn(() => ({ close: toastLoadingCloseMock, id: 'pending', update: vi.fn() })),
);
vi.mock('../useCommitWorkingDirectory', () => ({
useCommitWorkingDirectory: () => ({ commit: commitMock }),
}));
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)[] = [
async (importOriginal) => ({
...(await importOriginal<object>()),
Icon: ({ icon }: any) => (
<span data-icon={icon?.displayName ?? icon?.name} data-testid="icon" />
),
Tooltip: ({ children }: { children: ReactNode }) => (
<span data-testid="worktree-tooltip">{children}</span>
),
}),
async (importOriginal) => ({
...(await importOriginal<object>()),
confirmModal: confirmModalMock,
DropdownMenuItem: ({ children, onClick }: { children: ReactNode; onClick?: () => void }) => (
<button onClick={onClick}>{children}</button>
),
DropdownMenuPopup: ({ children }: { children: ReactNode }) => <div>{children}</div>,
DropdownMenuPortal: ({ children }: { children: ReactNode }) => <>{children}</>,
DropdownMenuPositioner: ({ children }: { children: ReactNode }) => <>{children}</>,
DropdownMenuRoot: ({ children }: { children: ReactNode }) => <div>{children}</div>,
DropdownMenuTrigger: ({
children,
className,
}: {
children: ReactNode;
className?: string;
}) => (
<div className={className} data-testid="worktree-dropdown-trigger">
{children}
</div>
),
toast: {
error: messageErrorMock,
info: vi.fn(),
loading: toastLoadingMock,
success: messageSuccessMock,
},
}),
];
const merged: Record<string, unknown> = { ...actual };
for (const factory of factories) {
const part = (await factory(importOriginal)) as Record<string, unknown>;
for (const [key, value] of Object.entries(part)) if (value !== actual[key]) merged[key] = value;
}
return merged;
});
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, values?: Record<string, unknown>) =>
values ? `${key}:${JSON.stringify(values)}` : key,
}),
}));
beforeEach(() => {
commitMock.mockReset();
confirmModalMock.mockReset();
messageErrorMock.mockReset();
messageSuccessMock.mockReset();
toastLoadingMock.mockClear();
toastLoadingCloseMock.mockReset();
removeGitWorktreeMock.mockReset();
removeGitWorktreeMock.mockResolvedValue({ success: true });
});
const triggerIconName = () =>
within(screen.getByTestId('worktree-dropdown-trigger'))
.getAllByTestId('icon')[0]
.getAttribute('data-icon');
/** Text of the worktree row owning `el` — rows render as `<button>` (mocked DropdownMenuItem). */
const rowTextOf = (el: HTMLElement) => el.closest('button')?.textContent ?? '';
const canaryWorktreeEntry = () => ({
branch: 'canary',
current: false,
path: '/repo-canary',
status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },
});
const currentWorktreeEntry = () => ({
branch: 'feat/current',
current: true,
path: '/repo',
status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },
});
describe('WorktreeSwitcher', () => {
it('keeps the dropdown trigger anchored to a stable DOM wrapper', () => {
render(
<WorktreeSwitcher
isGithub
agentId="agent-1"
currentBranch="feat/current"
path="/repo"
sourcePath="/repo"
worktrees={[currentWorktreeEntry(), canaryWorktreeEntry()]}
/>,
);
const trigger = screen.getByTestId('worktree-dropdown-trigger');
expect(trigger.firstElementChild?.tagName).toBe('DIV');
expect(within(trigger).getByTestId('worktree-tooltip')).toBeTruthy();
});
it('keeps the trigger mounted but inert while the branch is unconfirmed', () => {
render(
<WorktreeSwitcher
disabled
isGithub
agentId="agent-1"
currentBranch="feat/current"
path="/repo"
sourcePath="/repo"
worktrees={[currentWorktreeEntry()]}
/>,
);
const trigger = screen.getByTestId('worktree-dropdown-trigger');
// Same DOM and icon as the enabled trigger — only the action is gated.
expect(within(trigger).getByTestId('icon')).toBeTruthy();
expect(trigger.firstElementChild).toHaveAttribute('aria-disabled', 'true');
});
it('shows a branch icon on the main worktree and a fork icon on a linked one', () => {
const cleanStatus = { added: 0, clean: true, deleted: 0, modified: 0, total: 0 };
const worktrees = [
{ branch: 'canary', current: true, path: '/repo', status: cleanStatus },
{ branch: 'feat/x', current: false, path: '/repo-feat', status: cleanStatus },
];
const { rerender } = render(
<WorktreeSwitcher
isGithub
agentId="agent-1"
currentBranch="canary"
path="/repo"
sourcePath="/repo"
worktrees={worktrees}
/>,
);
expect(triggerIconName()).toBe('GitBranch');
// The user picked the linked worktree directly as the working directory, so
// `sourcePath` is the worktree itself — the icon must still read "worktree".
rerender(
<WorktreeSwitcher
isGithub
agentId="agent-1"
currentBranch="feat/x"
path="/repo-feat"
sourcePath="/repo-feat"
worktrees={[
{ ...worktrees[0], current: false },
{ ...worktrees[1], current: true },
]}
/>,
);
expect(triggerIconName()).toBe('GitFork');
});
it('treats every checkout of a bare repository as a linked worktree', () => {
const cleanStatus = { added: 0, clean: true, deleted: 0, modified: 0, total: 0 };
render(
<WorktreeSwitcher
isGithub
agentId="agent-1"
currentBranch="canary"
path="/repo/canary"
sourcePath="/repo/canary"
worktrees={[
{ bare: true, current: false, path: '/repo' },
{ branch: 'canary', current: true, path: '/repo/canary', status: cleanStatus },
]}
/>,
);
expect(triggerIconName()).toBe('GitFork');
});
it('renders dirty stats and omits clean labels in the worktree list', () => {
render(
<WorktreeSwitcher
isGithub
agentId="agent-1"
currentBranch="feat/current"
path="/repo"
sourcePath="/repo"
worktrees={[
{
branch: 'feat/current',
current: true,
path: '/repo',
status: { added: 2, clean: false, deleted: 1, modified: 3, total: 6 },
},
canaryWorktreeEntry(),
]}
/>,
);
expect(screen.getByText('+2')).toBeTruthy();
expect(screen.getByText('±3')).toBeTruthy();
expect(screen.getByText('-1')).toBeTruthy();
expect(screen.getByText('+2').parentElement?.parentElement?.textContent).toBe('+2±3-1');
expect(
screen.getByText('workingDirectory.currentWorktree').parentElement?.textContent,
).toContain('feat/current');
expect(screen.queryByText('workingDirectory.clean')).toBeNull();
});
it('shows worktree paths relative to the source path except temp paths', () => {
render(
<WorktreeSwitcher
isGithub
agentId="agent-1"
currentBranch="feat/current"
path="/Users/me/projects/project"
sourcePath="/Users/me/projects/project"
worktrees={[
{
branch: 'feat/current',
current: true,
path: '/Users/me/projects/project',
status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },
},
{
branch: 'canary',
current: false,
path: '/Users/me/projects/project-fix',
status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },
},
{
branch: 'scratch',
current: false,
path: '/tmp/project-scratch',
status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },
},
]}
/>,
);
expect(screen.getByText('/Users/me/projects/project')).toBeTruthy();
expect(screen.getByText('../project-fix')).toBeTruthy();
expect(screen.getByText('/tmp/project-scratch')).toBeTruthy();
});
it('never offers to remove the main worktree, even when it is not the source path', () => {
const cleanStatus = { added: 0, clean: true, deleted: 0, modified: 0, total: 0 };
render(
<WorktreeSwitcher
isGithub
agentId="agent-1"
currentBranch="feat/x"
path="/repo-feat"
sourcePath="/repo-feat"
worktrees={[
// main worktree — listed first, and `current: false` because the
// conversation runs on a linked one. `git worktree remove` would error.
{ branch: 'canary', current: false, path: '/repo', status: cleanStatus },
{ branch: 'feat/x', current: true, path: '/repo-feat', status: cleanStatus },
{ branch: 'feat/y', current: false, path: '/repo-other', status: cleanStatus },
]}
/>,
);
// Only `/repo-other` is removable: `/repo` is the main worktree and
// `/repo-feat` is both the current worktree and the conversation's source.
const removeButtons = screen.getAllByLabelText('workingDirectory.removeWorktreeAction');
expect(removeButtons).toHaveLength(1);
expect(rowTextOf(removeButtons[0])).toContain('feat/y');
});
it('confirms and removes a non-current worktree', async () => {
const onWorktreesChange = vi.fn();
render(
<WorktreeSwitcher
isGithub
agentId="agent-1"
currentBranch="feat/current"
deviceId="device-1"
path="/repo"
sourcePath="/repo"
worktrees={[
currentWorktreeEntry(),
{
current: false,
detached: true,
head: '4f46abcdef',
path: '/repo-detached',
status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },
},
canaryWorktreeEntry(),
]}
onWorktreesChange={onWorktreesChange}
/>,
);
// both the detached and the branch worktree are removable; only the current one is not
const removeButtons = screen.getAllByLabelText('workingDirectory.removeWorktreeAction');
expect(removeButtons).toHaveLength(2);
fireEvent.click(removeButtons[0]);
expect(commitMock).not.toHaveBeenCalled();
expect(confirmModalMock).toHaveBeenCalledTimes(1);
// onOk returns synchronously (non-blocking) — the removal runs in the
// background, so assert against the eventual side effects rather than the
// resolved value.
confirmModalMock.mock.calls[0][0].onOk();
// a pending toast surfaces immediately since the closed dropdown hides the row
expect(toastLoadingMock).toHaveBeenCalledWith(
'workingDirectory.removeWorktreePending:{"name":"repo-detached"}',
);
expect(removeGitWorktreeMock).toHaveBeenCalledWith({
deviceId: 'device-1',
path: '/repo',
worktreePath: '/repo-detached',
});
await waitFor(() => {
expect(onWorktreesChange).toHaveBeenCalled();
});
// the pending toast is dismissed before the terminal toast is shown
expect(toastLoadingCloseMock).toHaveBeenCalledTimes(1);
expect(messageSuccessMock).toHaveBeenCalledWith('workingDirectory.removeWorktreeSuccess');
expect(messageErrorMock).not.toHaveBeenCalled();
});
it('surfaces an error toast without rolling into success when removal fails', async () => {
removeGitWorktreeMock.mockResolvedValue({
error: 'fatal: worktree contains modified or untracked files',
success: false,
});
const onWorktreesChange = vi.fn();
render(
<WorktreeSwitcher
isGithub
agentId="agent-1"
currentBranch="feat/current"
deviceId="device-1"
path="/repo"
sourcePath="/repo"
worktrees={[currentWorktreeEntry(), canaryWorktreeEntry()]}
onWorktreesChange={onWorktreesChange}
/>,
);
fireEvent.click(screen.getByLabelText('workingDirectory.removeWorktreeAction'));
confirmModalMock.mock.calls[0][0].onOk();
await waitFor(() => {
expect(messageErrorMock).toHaveBeenCalledWith(
'fatal: worktree contains modified or untracked files',
);
});
// the pending toast is dismissed even when the removal fails
expect(toastLoadingCloseMock).toHaveBeenCalledTimes(1);
expect(messageSuccessMock).not.toHaveBeenCalled();
expect(onWorktreesChange).not.toHaveBeenCalled();
});
it('never offers to remove the source worktree even when it is not current', () => {
render(
<WorktreeSwitcher
isGithub
agentId="agent-1"
currentBranch="feat/current"
deviceId="device-1"
path="/repo-canary"
sourcePath="/repo"
worktrees={[
{
// The main/source worktree — listed as non-current because the agent
// runs on a linked worktree. `git worktree remove` would always fail.
branch: 'main',
current: false,
path: '/repo',
status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },
},
{
branch: 'canary',
current: true,
path: '/repo-canary',
status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },
},
{
branch: 'feature',
current: false,
path: '/repo-feature',
status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },
},
]}
/>,
);
// Only the linked branch worktree is removable; the source and the current
// worktree are both excluded.
expect(screen.getAllByLabelText('workingDirectory.removeWorktreeAction')).toHaveLength(1);
});
// The branch is the only label left once the worktree directory is deleted.
it('commits the selected worktree path and its branch as the working directory', () => {
render(
<WorktreeSwitcher
isGithub
agentId="agent-1"
currentBranch="feat/current"
path="/repo"
sourcePath="/repo"
worktrees={[
{
branch: 'feat/current',
current: true,
path: '/repo',
status: { added: 1, clean: false, deleted: 0, modified: 0, total: 1 },
},
canaryWorktreeEntry(),
]}
/>,
);
fireEvent.click(screen.getByText('/repo-canary'));
expect(commitMock).toHaveBeenCalledWith({
git: { activeWorktree: '/repo-canary', branch: 'canary' },
path: '/repo',
repoType: 'github',
});
});
it('clears the active worktree when selecting the source worktree', () => {
render(
<WorktreeSwitcher
agentId="agent-1"
currentBranch="feat/current"
isGithub={false}
path="/repo-canary"
sourcePath="/repo"
worktrees={[
{
branch: 'feat/current',
current: false,
path: '/repo',
status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },
},
{
branch: 'canary',
current: true,
path: '/repo-canary',
status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },
},
]}
/>,
);
fireEvent.click(screen.getByTitle('/repo'));
expect(commitMock).toHaveBeenCalledWith({ path: '/repo', repoType: 'git' });
});
// 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();
});
});