🤯 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 type * as LobeChatConst from '@lobechat/const';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import type * as LucideReact from 'lucide-react';
import type { CSSProperties, PropsWithChildren, ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import Header from './index';
const mocks = vi.hoisted(() => ({
copyToClipboard: vi.fn(),
marketSubmission: { isSubmitting: false, isUnderReview: false, open: vi.fn(), revision: 0 },
agentState: {
activeAgentId: 'agent-1',
authorId: undefined as string | undefined,
config: {
model: 'gpt-4o',
plugins: ['lobe-web-browsing'],
provider: 'openai',
},
isInbox: false,
isBuiltinAgent: false,
isCurrentAgentHeterogeneous: false,
meta: {
description: 'Test description',
tags: ['test'],
title: 'Test Agent',
},
createdAt: undefined as Date | undefined,
systemRole: 'You are helpful.',
visibility: 'public' as 'private' | 'public',
},
globalState: {
isStatusInit: true,
showAgentBuilderPanel: false,
toggleAgentBuilderPanel: vi.fn(),
},
homeState: {
removeAgent: vi.fn(),
},
hasActiveWorkspace: true,
/**
* What the Agent Share business slot reports. The rules behind it live with
* the deployment that offers sharing; this file only renders the outcome.
*/
shareSupport: { publishable: false, supported: false, visible: false as boolean | undefined },
serverConfigState: {
featureFlags: { enableAgentShare: undefined as boolean | undefined },
// Business features on by default in these tests — the Cloud-only
// structural half of the share gate is exercised by its own describe
// block below; everywhere else it stays open so the pre-existing
// rollout-flag behavior remains isolated to that one variable.
serverConfig: { enableBusinessFeatures: true },
},
navigate: vi.fn(),
// The two independent halves of "may configure this agent": the workspace
// role permission and this agent's General Access level.
permission: { allowed: true },
resourceAccess: { canEditResource: true, canManageResource: true },
profileState: {
editor: undefined as { getDocument: (format: string) => string | undefined } | undefined,
lockState: { holderId: null as string | null, lockedByOther: false, pending: false },
},
}));
vi.mock('@/business/client/useAgentShareSupported', () => ({
useAgentShareSupported: () => mocks.shareSupport,
}));
vi.mock('@lobechat/const', async (importOriginal) => ({
...(await importOriginal<typeof LobeChatConst>()),
isDesktop: false,
}));
interface MockDropdownItem {
children?: MockDropdownItem[];
disabled?: boolean;
key?: string;
label?: ReactNode;
onClick?: () => void;
type?: string;
}
// `disabled` is forwarded rather than dropped: the permission entries below are
// deliberately rendered-but-disabled, so a harness that ignores the flag would
// report them as available and pass no matter what the component decides.
const renderMenuItems = (items: MockDropdownItem[]) =>
items
.filter((item) => item.type !== 'divider')
.map((item) => (
<div key={item.key}>
<button disabled={item.disabled} type="button" onClick={item.onClick}>
{item.label}
</button>
{item.children && <div>{renderMenuItems(item.children)}</div>}
</div>
));
const getLatestExportedBlob = () => vi.mocked(URL.createObjectURL).mock.calls.at(-1)?.[0] as Blob;
vi.mock('@lobehub/ui', async (importOriginal) => ({
...(await importOriginal<object>()),
copyToClipboard: mocks.copyToClipboard,
DropdownMenu: ({
children,
items = [],
}: PropsWithChildren<{
items?: MockDropdownItem[];
}>) => (
<div>
{children}
<div data-testid="agent-profile-menu">{renderMenuItems(items)}</div>
</div>
),
}));
vi.mock('antd', async (importOriginal) => {
const actual = (await importOriginal()) as {
App: Record<string, unknown>;
Modal: Record<string, unknown>;
} & Record<string, unknown>;
return {
...actual,
App: {
...actual.App,
useApp: () => ({
modal: {
confirm: vi.fn(),
},
}),
},
Modal: {
...actual.Modal,
confirm: vi.fn(),
},
};
});
vi.mock('lucide-react', async (importOriginal) => ({
...(await importOriginal<typeof LucideReact>()),
BotMessageSquareIcon: () => null,
Circle: () => null,
Download: () => null,
MoreHorizontal: () => null,
Settings2Icon: () => null,
Share2Icon: () => <span data-testid="share-entry-icon" />,
Trash: () => null,
}));
vi.mock('react-router', () => ({
useNavigate: () => mocks.navigate,
}));
vi.mock('@/const/layoutTokens', () => ({
DESKTOP_HEADER_ICON_SMALL_SIZE: 24,
}));
vi.mock('@/features/AgentBreadcrumb', () => ({
default: () => null,
}));
vi.mock('@/features/AgentMarketSubmission/useAgentMarketSubmission', () => ({
useAgentMarketSubmission: () => mocks.marketSubmission,
}));
vi.mock('@/business/client/hooks/useHasActiveWorkspace', () => ({
useHasActiveWorkspace: () => mocks.hasActiveWorkspace,
}));
vi.mock('@/features/ResourcePermission/AccessLevelTag', () => ({
default: ({ resourceId }: { resourceId?: string }) => (
<span data-testid="access-level-resource-id">{resourceId}</span>
),
}));
vi.mock('@/hooks/usePermission', () => ({
usePermission: () => mocks.permission,
}));
vi.mock('@/features/ResourcePermission/useResourceAccess', () => ({
useResourceAccess: () => mocks.resourceAccess,
}));
vi.mock('@/features/NavHeader', () => ({
default: ({
left,
right,
styles,
}: {
left?: ReactNode;
right?: ReactNode;
styles?: { left?: CSSProperties };
}) => (
<header>
<div data-testid="nav-header-left" style={styles?.left}>
{left}
</div>
{right}
</header>
),
}));
vi.mock('@/features/RightPanel/ToggleRightPanelButton', () => ({
default: () => <button type="button">agentBuilder</button>,
}));
vi.mock('@/store/agent', () => ({
useAgentStore: (selector: (state: typeof mocks.agentState) => unknown) =>
selector(mocks.agentState),
}));
vi.mock('@/store/agent/selectors', () => ({
agentSelectors: {
currentAgentAuthorId: (state: typeof mocks.agentState) => state.authorId,
currentAgentConfig: (state: typeof mocks.agentState) => state.config,
currentAgentCreatedAt: (state: typeof mocks.agentState) => state.createdAt,
currentAgentMeta: (state: typeof mocks.agentState) => state.meta,
currentAgentSystemRole: (state: typeof mocks.agentState) => state.systemRole,
currentAgentVisibility: (state: typeof mocks.agentState) => state.visibility,
isCurrentAgentHeterogeneous: (state: typeof mocks.agentState) =>
state.isCurrentAgentHeterogeneous,
},
builtinAgentSelectors: {
isBuiltinAgent: (agentId?: string) => (state: typeof mocks.agentState) =>
!!agentId && !!state.isBuiltinAgent,
isInboxAgent: (state: typeof mocks.agentState) => state.isInbox,
},
}));
vi.mock('@/store/global', () => ({
useGlobalStore: (selector: (state: typeof mocks.globalState) => unknown) =>
selector(mocks.globalState),
}));
vi.mock('@/store/global/selectors', () => ({
systemStatusSelectors: {
isStatusInit: (state: typeof mocks.globalState) => state.isStatusInit,
showAgentBuilderPanel: (state: typeof mocks.globalState) => state.showAgentBuilderPanel,
},
}));
vi.mock('@/store/home', () => ({
useHomeStore: (selector: (state: typeof mocks.homeState) => unknown) => selector(mocks.homeState),
}));
vi.mock('@/store/serverConfig', () => ({
useServerConfigStore: (selector: (state: typeof mocks.serverConfigState) => unknown) =>
selector(mocks.serverConfigState),
}));
vi.mock('@/store/serverConfig/selectors', () => ({
featureFlagsSelectors: (state: typeof mocks.serverConfigState) => state.featureFlags,
serverConfigSelectors: {
enableBusinessFeatures: (state: typeof mocks.serverConfigState) =>
state.serverConfig.enableBusinessFeatures,
},
}));
vi.mock('../store', () => ({
selectors: {
lockHolderId: (s: typeof mocks.profileState) => s.lockState.holderId,
lockPending: (s: typeof mocks.profileState) => s.lockState.pending,
lockedByOther: (s: typeof mocks.profileState) => s.lockState.lockedByOther,
},
useProfileStore: (selector: (state: typeof mocks.profileState) => unknown) =>
selector(mocks.profileState),
}));
vi.mock('./AgentForkTag', () => ({
default: () => null,
}));
vi.mock('./AgentStatusTag', () => ({
default: () => <span>Unpublished</span>,
}));
vi.mock('@/services/marketApi', () => ({
marketApiService: { getAgentDetail: vi.fn().mockResolvedValue({ status: 'unpublished' }) },
}));
describe('Agent profile Header', () => {
beforeEach(() => {
mocks.marketSubmission.isUnderReview = false;
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});
vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:agent-profile');
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
mocks.agentState.isCurrentAgentHeterogeneous = false;
mocks.agentState.isBuiltinAgent = false;
mocks.agentState.isInbox = false;
mocks.agentState.systemRole = 'You are helpful.';
mocks.agentState.visibility = 'public';
mocks.globalState.showAgentBuilderPanel = false;
mocks.profileState.editor = undefined;
mocks.profileState.lockState.pending = false;
mocks.profileState.lockState.lockedByOther = false;
mocks.permission.allowed = true;
mocks.resourceAccess.canEditResource = true;
mocks.resourceAccess.canManageResource = true;
mocks.hasActiveWorkspace = true;
mocks.shareSupport = { publishable: false, supported: false, visible: false };
mocks.serverConfigState.featureFlags.enableAgentShare = undefined;
mocks.serverConfigState.serverConfig.enableBusinessFeatures = true;
vi.stubGlobal('__MOBILE__', false);
});
describe('Market review entry', () => {
it('replaces the unpublished status with under review after submission', () => {
const { rerender } = render(<Header />);
expect(screen.getByText('Unpublished')).toBeVisible();
expect(screen.queryByText('Under Review')).toBeNull();
mocks.marketSubmission.isUnderReview = true;
rerender(<Header key="submitted" />);
expect(screen.getByText('Under Review')).toBeVisible();
expect(screen.queryByText('Unpublished')).toBeNull();
});
it('keeps publishing inside the collapsed actions menu, not directly in the header', () => {
render(<Header />);
const entry = screen.getByRole('button', { name: 'marketSubmission.entry' });
expect(screen.getByTestId('agent-profile-menu')).toContainElement(entry);
expect(entry).toBeVisible();
});
it('offers submission independently of the share rollout flag', () => {
mocks.serverConfigState.featureFlags.enableAgentShare = false;
render(<Header />);
expect(screen.getByText('marketSubmission.entry')).toBeEnabled();
});
it.each(['builtin', 'heterogeneous'] as const)('hides submission for %s agents', (kind) => {
mocks.agentState.isBuiltinAgent = kind === 'builtin';
mocks.agentState.isCurrentAgentHeterogeneous = kind === 'heterogeneous';
render(<Header />);
expect(screen.queryByText('marketSubmission.entry')).toBeNull();
});
it.each(['role', 'resource', 'lock'] as const)(
'disables submission when blocked by %s',
(kind) => {
mocks.permission.allowed = kind !== 'role';
mocks.resourceAccess.canManageResource = kind !== 'resource';
mocks.profileState.lockState.lockedByOther = kind === 'lock';
render(<Header />);
expect(screen.getByText('marketSubmission.entry')).toBeDisabled();
},
);
});
describe('share entry', () => {
// Agent sharing runs a visitor's conversation on the creator's account, so
// the capability is contributed by the deployment that does that
// accounting. This file owns only what the header does with the answer;
// the rules themselves are tested with the slot's real implementation.
it('offers no share entry by default', () => {
render(<Header />);
expect(screen.queryByTestId('share-entry-icon')).toBeNull();
});
it('hides the share entry while the capability is still unresolved', () => {
mocks.shareSupport = { publishable: false, supported: true, visible: undefined };
render(<Header />);
expect(screen.queryByTestId('share-entry-icon')).toBeNull();
});
it('offers the share entry when the deployment reports it visible', () => {
mocks.shareSupport = { publishable: true, supported: true, visible: true };
render(<Header />);
expect(screen.getByTestId('share-entry-icon')).toBeInTheDocument();
});
// Share settings are a sibling tab of the profile group, so the entry
// navigates instead of opening a modal.
it('navigates to the share tab', () => {
mocks.shareSupport = { publishable: true, supported: true, visible: true };
render(<Header />);
fireEvent.click(screen.getByTestId('share-entry-icon'));
expect(mocks.navigate).toHaveBeenCalledWith('/agent/agent-1/share');
});
});
// `ResourceConfigAccessGate` requires the role permission AND resource-level
// edit access. A member whose role cannot edit content but who holds `edit`
// General Access on this agent satisfies only the second half — offering them
// an enabled entry sends them to a page that immediately bounces them back.
it.each([
['the role cannot edit content', { canEditResource: true, permission: false }],
['General Access is view-only', { canEditResource: false, permission: true }],
])('disables the mobile config entries when %s', (_label, { canEditResource, permission }) => {
vi.stubGlobal('__MOBILE__', true);
mocks.permission.allowed = permission;
mocks.resourceAccess.canEditResource = canEditResource;
// No global mock reset in this file, so the shared spy carries calls in
// from earlier cases; a "never navigated" assertion has to start clean.
mocks.navigate.mockClear();
render(<Header />);
const settings = screen.getByRole('button', { name: 'advancedSettings' });
const permissionEntry = screen.getByRole('button', { name: 'permission.page.agentEntry' });
expect(settings).toBeDisabled();
expect(permissionEntry).toBeDisabled();
// The handler guards independently of the `disabled` prop, since the real
// menu renders through a component that may still deliver the click.
fireEvent.click(permissionEntry);
expect(mocks.navigate).not.toHaveBeenCalledWith('/agent/agent-1/permission');
});
it.each([false, true])(
'keeps the breadcrumb aligned with the left content inset when builder expanded is %s',
(showAgentBuilderPanel) => {
mocks.globalState.showAgentBuilderPanel = showAgentBuilderPanel;
render(<Header />);
expect(screen.getByTestId('nav-header-left').style.paddingInlineStart).toBe('8px');
},
);
it('should show the markdown export action', () => {
render(<Header />);
expect(screen.getByRole('button', { name: 'pageEditor.menu.export' })).toBeInTheDocument();
expect(
screen.getByRole('button', { name: 'pageEditor.menu.export.markdown' }),
).toBeInTheDocument();
});
it('copies the Agent ID from the actions menu', async () => {
render(<Header />);
fireEvent.click(screen.getByRole('button', { name: 'agent.copyId' }));
await waitFor(() => expect(mocks.copyToClipboard).toHaveBeenCalledWith('agent-1'));
});
it('leaves the config entries to the sidebar on desktop', () => {
render(<Header />);
expect(screen.queryByRole('button', { name: 'advancedSettings' })).toBeNull();
expect(screen.queryByRole('button', { name: 'permission.page.agentEntry' })).toBeNull();
});
it('shows workspace resource permission controls for the LobeAI inbox agent', () => {
vi.stubGlobal('__MOBILE__', true);
mocks.agentState.isInbox = true;
render(<Header />);
expect(screen.getByRole('button', { name: 'permission.page.agentEntry' })).toBeInTheDocument();
expect(screen.getByTestId('access-level-resource-id')).toHaveTextContent('agent-1');
});
it('opens the Permission page from the mobile menu entry', () => {
vi.stubGlobal('__MOBILE__', true);
render(<Header />);
fireEvent.click(screen.getByRole('button', { name: 'permission.page.agentEntry' }));
expect(mocks.navigate).toHaveBeenCalledWith('/agent/agent-1/permission');
});
it('keeps the Permission entry on a private workspace agent — its model / environment policies still apply once shared', () => {
vi.stubGlobal('__MOBILE__', true);
mocks.agentState.visibility = 'private';
render(<Header />);
expect(screen.getByRole('button', { name: 'permission.page.agentEntry' })).toBeInTheDocument();
// Member access is meaningless while private, so the tag stays unbound.
expect(screen.getByTestId('access-level-resource-id')).toHaveTextContent('');
});
it('should export the current agent profile as markdown', async () => {
render(<Header />);
fireEvent.click(screen.getByRole('button', { name: 'pageEditor.menu.export.markdown' }));
await waitFor(() => expect(URL.createObjectURL).toHaveBeenCalled());
const exportedBlob = getLatestExportedBlob();
await expect(exportedBlob.text()).resolves.toContain('# Test Agent');
await expect(exportedBlob.text()).resolves.toContain('You are helpful.');
expect(HTMLAnchorElement.prototype.click).toHaveBeenCalled();
expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:agent-profile');
});
it('should preserve an empty prompt from the mounted editor when exporting markdown', async () => {
mocks.profileState.editor = {
getDocument: vi.fn().mockReturnValue(''),
};
render(<Header />);
fireEvent.click(screen.getByRole('button', { name: 'pageEditor.menu.export.markdown' }));
await waitFor(() => expect(URL.createObjectURL).toHaveBeenCalled());
const exportedBlob = getLatestExportedBlob();
const exportedMarkdown = await exportedBlob.text();
expect(exportedMarkdown).toContain('# Test Agent');
expect(exportedMarkdown).not.toContain('You are helpful.');
expect(exportedMarkdown).not.toContain('settingAgent.prompt.title');
});
it('should ignore the hidden editor when exporting heterogeneous agent markdown', async () => {
const getDocument = vi.fn().mockReturnValue('');
mocks.agentState.isCurrentAgentHeterogeneous = true;
mocks.profileState.editor = { getDocument };
render(<Header />);
fireEvent.click(screen.getByRole('button', { name: 'pageEditor.menu.export.markdown' }));
await waitFor(() => expect(URL.createObjectURL).toHaveBeenCalled());
const exportedBlob = getLatestExportedBlob();
const exportedMarkdown = await exportedBlob.text();
expect(getDocument).not.toHaveBeenCalled();
expect(exportedMarkdown).toContain('You are helpful.');
});
});