🤯 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
/**
* @vitest-environment happy-dom
*/
import type { TaskDetailActivity } from '@lobechat/types';
import { fireEvent, render } from '@testing-library/react';
import type { CSSProperties, ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useGatewayReconnect } from '@/hooks/useGatewayReconnect';
import TopicChatDrawer, { TopicChatDrawerBody } from './index';
const mocks = vi.hoisted(() => ({
agentState: {
agentMap: {},
useHydrateAgentConfig: vi.fn(),
},
appOrigin: 'https://app.example.com',
chatState: {
closeArtifact: vi.fn(),
closeFilePreview: vi.fn(),
clearPortalStack: vi.fn(),
dbMessagesMap: {
'topic-chat-key': [{ id: 'message-1' }],
} as Record<string, { id: string }[]>,
messagesMap: {} as Record<string, { id: string }[]>,
portalStack: [] as {
artifact?: { id: string };
file?: { fileId: string };
sourceTopicId?: string;
taskId?: string;
type: string;
}[],
replaceMessages: vi.fn(),
showPortal: false,
topicDataMap: {},
topicDetailMap: {},
},
permission: {
allowed: true,
reason: 'requires member',
},
navigate: vi.fn(),
openTrustedExternalUrl: vi.fn(),
workspaceSlug: undefined as string | undefined,
serverConfigState: {
serverConfig: {
enableBusinessFeatures: false,
},
},
taskState: {
activeTaskId: 'T-1',
activeTopicDrawerFocusRequest: undefined as number | undefined,
activeTopicDrawerTopicId: 'topic-1',
closeTopicDrawer: vi.fn(),
useFetchTaskDetail: vi.fn(),
taskDetailMap: {
'T-1': {
activities: [
{
id: 'topic-1',
status: 'completed',
time: '2026-04-29T00:00:00.000Z',
title: 'Topic 1',
type: 'topic',
},
] as TaskDetailActivity[],
agentId: 'agt_assignee',
identifier: 'T-1',
instruction: 'Do the task',
status: 'completed',
},
},
},
userState: {
isSignedIn: true,
},
}));
const serializeSize = (size: unknown) =>
size === undefined ? '' : typeof size === 'string' ? size : JSON.stringify(size);
vi.mock('@lobehub/ui', async (importOriginal) => ({
...(await importOriginal<object>()),
copyToClipboard: vi.fn(),
DropdownMenu: ({
children,
items,
}: {
children?: ReactNode;
items?: { key: string; label?: ReactNode; onClick?: () => void; type?: string }[];
}) => (
<>
{children}
{items?.map((item) =>
item.type === 'divider' ? null : (
<button key={item.key} onClick={item.onClick}>
{item.label}
</button>
),
)}
</>
),
ActionIcon: ({
disabled,
icon,
onClick,
size,
title,
}: {
disabled?: boolean;
icon?: { name?: string };
onClick?: () => void;
size?: unknown;
title?: string;
}) => (
<button
data-icon={icon?.name}
data-size={serializeSize(size)}
data-testid="header-action-icon"
disabled={disabled}
title={title}
onClick={onClick}
>
{title}
</button>
),
FloatingPanel: ({
actions,
children,
height,
minHeight,
minWidth,
onClose,
open,
placement,
resizable = true,
styles,
title,
width,
}: {
actions?: ReactNode;
children?: ReactNode;
height?: unknown;
minHeight?: number;
minWidth?: number;
onClose?: () => void;
open?: boolean;
placement?: string;
resizable?: boolean;
styles?: { body?: CSSProperties; panel?: CSSProperties; title?: CSSProperties };
title?: ReactNode;
width?: unknown;
}) =>
open ? (
<div
data-height={serializeSize(height)}
data-min-height={serializeSize(minHeight)}
data-min-width={serializeSize(minWidth)}
data-panel-background={serializeSize(styles?.panel?.background)}
data-placement={placement}
data-resizable={String(resizable)}
data-testid="topic-panel"
data-width={serializeSize(width)}
style={styles?.panel}
>
<div data-testid="panel-title-slot" style={styles?.title}>
{title}
</div>
<div data-testid="panel-actions-slot">{actions}</div>
<button data-testid="panel-close-icon" onClick={onClose} />
<div data-testid="panel-body-slot" style={styles?.body}>
{children}
</div>
</div>
) : null,
}));
vi.mock('next/dynamic', () => ({
default: () =>
function DynamicComponent({ children }: { children?: ReactNode }) {
return <>{children}</>;
},
}));
vi.mock('@/features/Conversation/ChatList', () => ({
default: () => <div data-testid="chat-list" />,
}));
vi.mock('@/features/Conversation/ConversationProvider', () => ({
ConversationProvider: ({ children }: { children?: ReactNode }) => <>{children}</>,
}));
vi.mock('@/features/Conversation/Messages', () => ({
default: ({ id }: { id: string }) => <div data-testid="message-item">{id}</div>,
}));
vi.mock('@/features/Conversation/Markdown/plugins/Task', () => ({
TaskCardScopeProvider: ({ children }: { children?: ReactNode }) => <>{children}</>,
}));
vi.mock('@/features/Portal/router', () => ({
PortalContent: ({ onClose }: { onClose?: () => void }) => (
<button data-testid="artifact-portal" onClick={onClose}>
artifact portal
</button>
),
}));
vi.mock('@/features/ShareModal', () => ({
useShareModal: () => ({
openShareModal: vi.fn(),
}),
}));
vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
useWorkspaceAwareNavigate: () => mocks.navigate,
}));
vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
useActiveWorkspaceSlug: () => mocks.workspaceSlug,
}));
vi.mock('@/hooks/useAppOrigin', () => ({
useAppOrigin: () => mocks.appOrigin,
}));
vi.mock('@/utils/openTrustedExternalUrl', () => ({
openTrustedExternalUrl: mocks.openTrustedExternalUrl,
}));
vi.mock('@/hooks/useGatewayReconnect', () => ({
useGatewayReconnect: vi.fn(),
}));
vi.mock('@/hooks/useOperationState', () => ({
useOperationState: () => undefined,
}));
vi.mock('@/hooks/usePermission', () => ({
usePermission: () => ({ allowed: mocks.permission.allowed, reason: mocks.permission.reason }),
}));
vi.mock('@/store/agent', () => ({
useAgentStore: (selector: (state: typeof mocks.agentState) => unknown) =>
selector(mocks.agentState),
}));
vi.mock('@/store/chat', () => ({
useChatStore: (selector: (state: typeof mocks.chatState) => unknown) => selector(mocks.chatState),
}));
vi.mock('@/store/serverConfig', () => ({
useServerConfigStore: (selector: (state: typeof mocks.serverConfigState) => unknown) =>
selector(mocks.serverConfigState),
}));
vi.mock('@/store/task', () => ({
useTaskStore: (selector: (state: typeof mocks.taskState) => unknown) => selector(mocks.taskState),
}));
vi.mock('@/store/user', () => ({
useUserStore: (selector: (state: typeof mocks.userState) => unknown) => selector(mocks.userState),
}));
vi.mock('@/store/chat/utils/messageMapKey', () => ({
messageMapKey: () => 'topic-chat-key',
}));
vi.mock('../../features/AssigneeAvatar', () => ({
default: ({ agentId, size }: { agentId?: string; size?: number }) => (
<span data-agent-id={agentId} data-size={size} data-testid="assignee-avatar" />
),
}));
vi.mock('./FeedbackInput', () => ({
default: ({
defaultExpanded,
disableCollapse,
}: {
defaultExpanded?: boolean;
disableCollapse?: boolean;
}) => (
<div
data-default-expanded={String(Boolean(defaultExpanded))}
data-disable-collapse={String(Boolean(disableCollapse))}
data-testid="feedback-input"
/>
),
}));
describe('TopicChatDrawer', () => {
beforeEach(() => {
mocks.agentState.useHydrateAgentConfig.mockClear();
mocks.chatState.replaceMessages.mockClear();
mocks.chatState.portalStack = [];
mocks.chatState.showPortal = false;
mocks.chatState.closeArtifact.mockClear();
mocks.chatState.closeArtifact.mockImplementation(() => {
mocks.chatState.portalStack = mocks.chatState.portalStack.slice(0, -1);
});
mocks.chatState.closeFilePreview.mockClear();
mocks.chatState.closeFilePreview.mockImplementation(() => {
mocks.chatState.portalStack = mocks.chatState.portalStack.slice(0, -1);
});
mocks.chatState.clearPortalStack.mockClear();
mocks.chatState.clearPortalStack.mockImplementation(() => {
mocks.chatState.portalStack = [];
mocks.chatState.showPortal = false;
});
mocks.navigate.mockClear();
mocks.openTrustedExternalUrl.mockClear();
mocks.appOrigin = 'https://app.example.com';
mocks.workspaceSlug = undefined;
mocks.taskState.closeTopicDrawer.mockClear();
mocks.taskState.activeTopicDrawerFocusRequest = undefined;
mocks.taskState.activeTopicDrawerTopicId = 'topic-1';
mocks.taskState.taskDetailMap['T-1'].activities[0] = {
id: 'topic-1',
status: 'completed',
time: '2026-04-29T00:00:00.000Z',
title: 'Topic 1',
type: 'topic',
};
mocks.permission.allowed = true;
mocks.serverConfigState.serverConfig.enableBusinessFeatures = false;
vi.mocked(useGatewayReconnect).mockClear();
});
// The run drawer also mounts on the home inbox, where the chat store has no
// active agent — reconnecting against it would stream the run into a bucket
// this panel never reads, so the run's own agent has to be passed down.
it('reconnects a running topic against the drawer agent', () => {
mocks.taskState.taskDetailMap['T-1'].activities[0] = {
id: 'topic-1',
runningOperation: {
assistantMessageId: 'ast-1',
heteroType: 'claude-code',
operationId: 'op-1',
},
status: 'running',
time: '2026-04-29T00:00:00.000Z',
title: 'Topic 1',
type: 'topic',
};
render(<TopicChatDrawer />);
expect(useGatewayReconnect).toHaveBeenCalledWith(
'topic-1',
expect.objectContaining({ heteroType: 'claude-code', operationId: 'op-1' }),
'agt_assignee',
);
});
/** @example Embedded Topic B never reconnects against active drawer Topic A. */
it('keeps embedded operation context separate from an unrelated active drawer', () => {
mocks.taskState.taskDetailMap['T-1'].activities[0].runningOperation = {
assistantMessageId: 'ast-1',
heteroType: 'codex',
operationId: 'op-drawer',
};
const { rerender } = render(
<TopicChatDrawerBody agentId={'embedded-agent'} topicId={'topic-2'} />,
);
/** @example An unrelated active drawer supplies no fallback operation. */
expect(useGatewayReconnect).toHaveBeenLastCalledWith('topic-2', undefined, 'embedded-agent');
const runningOperation = {
assistantMessageId: 'ast-2',
heteroType: 'codex',
operationId: 'op-embedded',
};
rerender(
<TopicChatDrawerBody
agentId={'embedded-agent'}
runningOperation={runningOperation}
topicId={'topic-2'}
/>,
);
/** @example An explicit embedded run owns its streaming context. */
expect(useGatewayReconnect).toHaveBeenLastCalledWith(
'topic-2',
runningOperation,
'embedded-agent',
);
});
it('hydrates the task assignee agent config for drawer messages', () => {
render(<TopicChatDrawer />);
expect(mocks.agentState.useHydrateAgentConfig).toHaveBeenCalledWith(true, 'agt_assignee');
});
it('keeps the floating drawer reply input collapsed by default', () => {
const { getByTestId } = render(<TopicChatDrawer />);
expect(getByTestId('feedback-input')).toHaveAttribute('data-default-expanded', 'false');
expect(getByTestId('feedback-input')).toHaveAttribute('data-disable-collapse', 'false');
});
it('disables topic sharing for workspace viewers', () => {
mocks.permission.allowed = false;
mocks.serverConfigState.serverConfig.enableBusinessFeatures = true;
const { getByTitle } = render(<TopicChatDrawer />);
expect(getByTitle('requires member')).toBeDisabled();
});
it('constrains long panel titles before the header actions', () => {
const { getByTestId, getByText } = render(<TopicChatDrawer />);
const title = getByText('Topic 1');
expect(title).toHaveStyle({ flex: '0 1 auto', minWidth: '0' });
expect(title.parentElement).toHaveStyle({ maxWidth: '100%', overflow: 'hidden' });
expect(getByTestId('panel-title-slot')).toHaveStyle({
boxSizing: 'border-box',
maxWidth: '100%',
overflow: 'hidden',
});
});
it('shows the assignee avatar in the topic header', () => {
const { getByTestId } = render(<TopicChatDrawer />);
expect(getByTestId('assignee-avatar')).toHaveAttribute('data-agent-id', 'agt_assignee');
expect(getByTestId('assignee-avatar')).toHaveAttribute('data-size', '20');
});
it('uses the container background for the conversation panel', () => {
const { getByTestId } = render(<TopicChatDrawer />);
expect(getByTestId('topic-panel')).toHaveAttribute(
'data-panel-background',
'var(--lobe-color-bg-container)',
);
});
it('renders the share button in the floating panel actions slot', () => {
const { getAllByTestId, getByTestId } = render(<TopicChatDrawer />);
const icons = getAllByTestId('header-action-icon');
const moreIcon = icons.find((icon) => !icon.getAttribute('title'));
const expandIcon = icons.find(
(icon) => icon.getAttribute('title') === 'taskDetail.topicDrawer.expand',
);
const shareIcon = icons.find((icon) => icon.getAttribute('title') === 'share');
expect(moreIcon).toBeDefined();
expect(expandIcon).toBeDefined();
expect(shareIcon).toBeDefined();
expect(moreIcon!).toHaveAttribute('data-size', 'small');
expect(shareIcon!).toHaveAttribute('data-size', JSON.stringify({ blockSize: 32, size: 16 }));
expect(getByTestId('panel-actions-slot')).toContainElement(shareIcon!);
expect(getByTestId('panel-close-icon')).toBeInTheDocument();
});
it('expands the conversation into a full-height reading panel', () => {
const { getByTestId, getByTitle } = render(<TopicChatDrawer />);
fireEvent.click(getByTitle('taskDetail.topicDrawer.expand'));
expect(getByTestId('topic-panel')).toHaveAttribute(
'data-width',
'min(960px, calc(100vw - 16px))',
);
expect(getByTestId('topic-panel')).toHaveAttribute('data-height', 'calc(100dvh - 16px)');
expect(getByTitle('taskDetail.topicDrawer.collapse')).toBeInTheDocument();
});
it('opens expanded on hosts that default to the wide reading panel', () => {
const { getByTestId, getByTitle } = render(<TopicChatDrawer defaultExpanded />);
expect(getByTestId('topic-panel')).toHaveAttribute(
'data-width',
'min(960px, calc(100vw - 16px))',
);
expect(getByTestId('topic-panel')).toHaveAttribute('data-height', 'calc(100dvh - 16px)');
expect(getByTitle('taskDetail.topicDrawer.collapse')).toBeInTheDocument();
});
it('restores the host default size each time the drawer reopens', () => {
// The store mock is not reactive, so a throwaway prop forces each re-render.
const renderAt = (revision: number) => (
<TopicChatDrawer defaultExpanded {...({ 'data-revision': revision } as object)} />
);
const { getByTestId, getByTitle, queryByTestId, rerender } = render(renderAt(0));
fireEvent.click(getByTitle('taskDetail.topicDrawer.collapse'));
expect(getByTestId('topic-panel')).toHaveAttribute('data-width', '640');
mocks.taskState.activeTopicDrawerTopicId = undefined as unknown as string;
rerender(renderAt(1));
expect(queryByTestId('topic-panel')).not.toBeInTheDocument();
mocks.taskState.activeTopicDrawerTopicId = 'topic-1';
rerender(renderAt(2));
expect(getByTestId('topic-panel')).toHaveAttribute(
'data-width',
'min(960px, calc(100vw - 16px))',
);
});
it('opens the run in its Agent conversation', () => {
const { getByText } = render(<TopicChatDrawer />);
fireEvent.click(getByText('taskDetail.topicMenu.openAgentTopic'));
expect(mocks.taskState.closeTopicDrawer).toHaveBeenCalledOnce();
expect(mocks.navigate).toHaveBeenCalledWith('/agent/agt_assignee/topic-1');
});
it('closes an artifact inside the run drawer without clearing its parent task portal', () => {
mocks.chatState.portalStack = [
{ taskId: 'T-1', type: 'taskDetail' },
{ artifact: { id: 'message-1' }, type: 'artifact' },
];
mocks.chatState.showPortal = true;
const view = render(<TopicChatDrawer />);
expect(view.getByTestId('topic-panel')).toBeInTheDocument();
expect(view.getByTestId('artifact-portal')).toBeInTheDocument();
expect(view.queryByTestId('chat-list')).not.toBeInTheDocument();
expect(mocks.taskState.closeTopicDrawer).not.toHaveBeenCalled();
fireEvent.click(view.getByTestId('artifact-portal'));
expect(mocks.chatState.closeArtifact).toHaveBeenCalledOnce();
expect(mocks.chatState.clearPortalStack).not.toHaveBeenCalled();
view.unmount();
const conversationView = render(<TopicChatDrawer />);
expect(conversationView.getByTestId('chat-list')).toBeInTheDocument();
expect(conversationView.queryByTestId('artifact-portal')).not.toBeInTheDocument();
expect(mocks.taskState.closeTopicDrawer).not.toHaveBeenCalled();
});
it('closes its artifact together with the drawer so the topic reopens on the conversation', () => {
mocks.chatState.portalStack = [{ artifact: { id: 'message-1' }, type: 'artifact' }];
mocks.chatState.showPortal = true;
const view = render(<TopicChatDrawer />);
expect(view.getByTestId('artifact-portal')).toBeInTheDocument();
fireEvent.click(view.getByTestId('panel-close-icon'));
expect(mocks.chatState.closeArtifact).toHaveBeenCalledOnce();
expect(mocks.taskState.closeTopicDrawer).toHaveBeenCalledOnce();
});
it('leaves another conversation’s artifact open when the drawer closes', () => {
mocks.chatState.portalStack = [{ artifact: { id: 'another-message' }, type: 'artifact' }];
mocks.chatState.showPortal = true;
const view = render(<TopicChatDrawer />);
fireEvent.click(view.getByTestId('panel-close-icon'));
expect(mocks.chatState.closeArtifact).not.toHaveBeenCalled();
expect(mocks.taskState.closeTopicDrawer).toHaveBeenCalledOnce();
});
it('switches from its artifact to the conversation on each new focus request', () => {
// The store mock is not reactive and the drawer is a prop-less memo, so a
// throwaway prop forces each re-render after the mocked state changes.
const renderAt = (revision: number) => (
<TopicChatDrawer {...({ 'data-revision': revision } as object)} />
);
mocks.chatState.portalStack = [{ artifact: { id: 'message-1' }, type: 'artifact' }];
mocks.chatState.showPortal = true;
const view = render(renderAt(0));
expect(mocks.chatState.closeArtifact).not.toHaveBeenCalled();
mocks.taskState.activeTopicDrawerFocusRequest = 1;
view.rerender(renderAt(1));
expect(mocks.chatState.closeArtifact).toHaveBeenCalledOnce();
view.rerender(renderAt(2));
expect(view.getByTestId('chat-list')).toBeInTheDocument();
// An artifact opened later from inside the conversation stays open until
// another request arrives.
mocks.chatState.portalStack = [{ artifact: { id: 'message-1' }, type: 'artifact' }];
view.rerender(renderAt(3));
expect(view.getByTestId('artifact-portal')).toBeInTheDocument();
expect(mocks.chatState.closeArtifact).toHaveBeenCalledOnce();
mocks.taskState.activeTopicDrawerFocusRequest = 2;
view.rerender(renderAt(4));
expect(mocks.chatState.closeArtifact).toHaveBeenCalledTimes(2);
});
it('does not take over an artifact opened by another conversation', () => {
mocks.chatState.portalStack = [{ artifact: { id: 'another-message' }, type: 'artifact' }];
mocks.chatState.showPortal = true;
const view = render(<TopicChatDrawer />);
expect(view.getByTestId('chat-list')).toBeInTheDocument();
expect(view.queryByTestId('artifact-portal')).not.toBeInTheDocument();
expect(mocks.taskState.closeTopicDrawer).not.toHaveBeenCalled();
});
it('shows a file preview opened from its run inside the drawer instead of behind it', () => {
mocks.chatState.portalStack = [
{ file: { fileId: 'file_1' }, sourceTopicId: 'topic-1', type: 'filePreview' },
];
mocks.chatState.showPortal = true;
const view = render(<TopicChatDrawer />);
expect(view.getByTestId('artifact-portal')).toBeInTheDocument();
expect(view.queryByTestId('chat-list')).not.toBeInTheDocument();
fireEvent.click(view.getByTestId('artifact-portal'));
expect(mocks.chatState.closeFilePreview).toHaveBeenCalledOnce();
expect(mocks.chatState.closeArtifact).not.toHaveBeenCalled();
expect(mocks.taskState.closeTopicDrawer).not.toHaveBeenCalled();
});
it('closes its file preview together with the drawer', () => {
mocks.chatState.portalStack = [
{ file: { fileId: 'file_1' }, sourceTopicId: 'topic-1', type: 'filePreview' },
];
mocks.chatState.showPortal = true;
const view = render(<TopicChatDrawer />);
fireEvent.click(view.getByTestId('panel-close-icon'));
expect(mocks.chatState.closeFilePreview).toHaveBeenCalledOnce();
expect(mocks.taskState.closeTopicDrawer).toHaveBeenCalledOnce();
});
it.each([
['another topic', 'topic-2'],
['no conversation', undefined],
])('leaves a file preview opened from %s to the page portal', (_, sourceTopicId) => {
mocks.chatState.portalStack = [
{ file: { fileId: 'file_1' }, sourceTopicId, type: 'filePreview' },
];
mocks.chatState.showPortal = true;
const view = render(<TopicChatDrawer />);
expect(view.getByTestId('chat-list')).toBeInTheDocument();
expect(view.queryByTestId('artifact-portal')).not.toBeInTheDocument();
fireEvent.click(view.getByTestId('panel-close-icon'));
expect(mocks.chatState.closeFilePreview).not.toHaveBeenCalled();
});
it('opens the run conversation in the browser', () => {
mocks.workspaceSlug = 'acme';
const view = render(<TopicChatDrawer />);
fireEvent.click(view.getByTitle('report.actions.openInBrowser'));
expect(mocks.openTrustedExternalUrl).toHaveBeenCalledWith(
'https://app.example.com/acme/agent/agt_assignee/topic-1',
);
});
it('disables open in browser without an app origin', () => {
mocks.appOrigin = '';
const view = render(<TopicChatDrawer />);
expect(view.getByTitle('report.actions.openInBrowser')).toBeDisabled();
});
it('uses a resizable bottom-right floating panel', () => {
const { getByTestId } = render(<TopicChatDrawer />);
expect(getByTestId('topic-panel')).toHaveAttribute('data-placement', 'bottomRight');
expect(getByTestId('topic-panel')).toHaveAttribute('data-resizable', 'true');
expect(getByTestId('topic-panel')).toHaveAttribute('data-width', '640');
expect(getByTestId('topic-panel')).toHaveAttribute(
'data-height',
'min(640px, calc(100dvh - 16px))',
);
});
});