🤯 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
💄 style(contacts): open a contact card before the chat or the profile (#22815)
Arvin Xu600005e618d2
diff --git a/locales/en-US/common.json b/locales/en-US/common.jsonindex fac576167d9..393ee52ab6f 100644--- a/locales/en-US/common.json+++ b/locales/en-US/common.json@@ -184,8 +184,12 @@"confirm": "Confirm","contact": "Contact Us","contacts.create": "New agent",+ "contacts.editProfile": "Edit profile","contacts.empty": "None yet","contacts.groups": "Groups",+ "contacts.noDescription": "No description yet",+ "contacts.notFound": "This contact no longer exists or is not visible to you",+ "contacts.sendMessage": "Send message","continue": "Continue","copy": "Copy","copyFail": "Copy failed",diff --git a/locales/zh-CN/common.json b/locales/zh-CN/common.jsonindex 1c8c327d1ee..fbc3a7cef64 100644--- a/locales/zh-CN/common.json+++ b/locales/zh-CN/common.json@@ -184,8 +184,12 @@"confirm": "确认","contact": "联系我们","contacts.create": "新建助理",+ "contacts.editProfile": "编辑档案","contacts.empty": "暂无","contacts.groups": "群组",+ "contacts.noDescription": "还没有简介",+ "contacts.notFound": "该联系人不存在或你无权查看",+ "contacts.sendMessage": "发消息","continue": "继续","copy": "复制","copyFail": "复制失败",diff --git a/packages/locales/src/default/common.ts b/packages/locales/src/default/common.tsindex 99e9947741a..c2881a0cfcb 100644--- a/packages/locales/src/default/common.ts+++ b/packages/locales/src/default/common.ts@@ -433,8 +433,12 @@ export default {'gotIt': 'Got it','more': 'More','contacts.create': 'New agent',+ 'contacts.editProfile': 'Edit profile','contacts.empty': 'None yet','contacts.groups': 'Groups',+ 'contacts.noDescription': 'No description yet',+ 'contacts.notFound': 'This contact no longer exists or is not visible to you',+ 'contacts.sendMessage': 'Send message','messageList.empty': 'No conversations yet','messageList.newChat': 'New conversation','messageList.running': 'Running…',diff --git a/src/features/ContactList/ContactAvatar.tsx b/src/features/ContactList/ContactAvatar.tsxnew file mode 100644index 00000000000..e1718c5faed--- /dev/null+++ b/src/features/ContactList/ContactAvatar.tsx@@ -0,0 +1,33 @@+import type { SidebarAgentItem } from '@lobechat/types';+import { memo } from 'react';++import AgentAvatar from '@/components/AgentAvatar';+import AgentGroupAvatar from '@/features/AgentGroupAvatar';++/** An agent's or group's avatar, shared by the contact row and the contact card. */+const ContactAvatar = memo<{ item: SidebarAgentItem; name: string; size: number }>(+ ({ item, name, size }) => {+ const customAvatar = typeof item.avatar === 'string' ? item.avatar : undefined;++ return item.type === 'group' ? (+ <AgentGroupAvatar+ avatar={customAvatar}+ backgroundColor={item.backgroundColor || undefined}+ memberAvatars={Array.isArray(item.avatar) ? item.avatar : []}+ size={size}+ />+ ) : (+ <AgentAvatar+ agentId={item.id}+ avatar={customAvatar}+ background={item.backgroundColor || undefined}+ name={name}+ size={size}+ />+ );+ },+);++ContactAvatar.displayName = 'ContactAvatar';++export default ContactAvatar;diff --git a/src/features/ContactList/ContactDetail.tsx b/src/features/ContactList/ContactDetail.tsxnew file mode 100644index 00000000000..0cdc11febe3--- /dev/null+++ b/src/features/ContactList/ContactDetail.tsx@@ -0,0 +1,216 @@+'use client';++import { Button, cx, Empty, Flexbox, Skeleton, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { MessageCircleIcon, PencilLineIcon, UserRoundXIcon } from 'lucide-react';+import { type CSSProperties, memo } from 'react';+import { useTranslation } from 'react-i18next';+import { useParams } from 'react-router';++import AsyncError from '@/components/AsyncError';+import { cardStyles } from '@/features/AgentViewAll/AgentCard';+import { coverPattern } from '@/features/AgentViewAll/coverColor';+import { resolveAgentBadge } from '@/features/AgentViewAll/resolveAgentBadge';+import SidebarItemAvatar from '@/features/AgentViewAll/SidebarItemAvatar';+import { useAgentCoverColor } from '@/features/AgentViewAll/useAgentCoverColor';+import NavHeader from '@/features/NavHeader';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';++import { type ContactCardState, useContactCard } from './useContactCard';++const AVATAR_SIZE = 88;+const COVER_HEIGHT = 144;++const styles = stylex.create({+ body: {+ paddingBlockEnd: '48px',+ paddingInline: '24px',+ maxWidth: '520px',+ width: '100%',+ textAlign: 'center',+ },+ // The badge cover from the agents wall, widened into a profile header.+ cover: {+ position: 'relative',+ overflow: 'hidden',+ flexShrink: 0,+ borderRadius: '12px',+ height: `${COVER_HEIGHT}px`,+ width: '100%',+ },+ // The avatar straddles the cover's bottom edge, as on the badge.+ avatar: {+ marginBlockStart: `-${AVATAR_SIZE / 2}px`,+ },+ description: {+ fontSize: '14px',+ lineHeight: '22px',+ color: cssVar.colorTextSecondary,+ whiteSpace: 'pre-wrap',+ },+ placeholder: {+ fontSize: '14px',+ color: cssVar.colorTextQuaternary,+ },+ slug: {+ fontSize: '13px',+ color: cssVar.colorTextTertiary,+ },+ state: {+ paddingBlock: '48px',+ paddingInline: '24px',+ maxWidth: '520px',+ width: '100%',+ },+});++const ContactCard = memo<Extract<ContactCardState, { status: 'ready' }>>(+ ({ canEdit, chatUrl, item, profileUrl, role, slug, title }) => {+ const { t } = useTranslation('common');+ const navigate = useWorkspaceAwareNavigate();+ const badge = resolveAgentBadge(item);+ const coverColor = useAgentCoverColor(item, badge.cover, !!badge.coverImage);++ return (+ <>+ <div {...stylex.props(styles.cover)}>+ <div+ className={cardStyles.cover}+ data-cover-image={badge.coverImage ? '' : undefined}+ data-pattern={badge.coverImage ? undefined : coverPattern(item)}+ style={+ {+ '--agent-cover': coverColor,+ 'backgroundImage': badge.coverImage+ ? `url(${JSON.stringify(badge.coverImage)})`+ : undefined,+ 'height': '100%',+ } as CSSProperties+ }+ />+ </div>+ <Flexbox align={'center'} gap={8} {...stylex.props(styles.body)}>+ <span+ className={cx(+ stylex.props(styles.avatar).className,+ cardStyles.avatarRing,+ !badge.cover && cardStyles.avatarPlain,+ item.type === 'group' && cardStyles.avatarRingGroup,+ )}+ >+ <SidebarItemAvatar item={item} shape={'circle'} size={AVATAR_SIZE - 6} />+ </span>+ <Text+ ellipsis+ as={'h1'}+ fontSize={22}+ style={{ margin: 0, maxWidth: '100%' }}+ weight={600}+ >+ {title}+ </Text>+ {(role || slug) && (+ <Flexbox horizontal align={'center'} gap={8} justify={'center'}>+ {role && (+ <span className={cardStyles.role} title={role}>+ {role}+ </span>+ )}+ {slug && <span {...stylex.props(styles.slug)}>@{slug}</span>}+ </Flexbox>+ )}+ {item.description ? (+ <span {...stylex.props(styles.description)}>{item.description}</span>+ ) : (+ <span {...stylex.props(styles.placeholder)}>{t('contacts.noDescription')}</span>+ )}+ <Flexbox horizontal gap={8} justify={'center'} style={{ marginBlockStart: 16 }}>+ <Button icon={MessageCircleIcon} type={'primary'} onClick={() => navigate(chatUrl)}>+ {t('contacts.sendMessage')}+ </Button>+ {canEdit && (+ <Button icon={PencilLineIcon} onClick={() => navigate(profileUrl)}>+ {t('contacts.editProfile')}+ </Button>+ )}+ </Flexbox>+ </Flexbox>+ </>+ );+ },+);++ContactCard.displayName = 'ContactCard';++/**+ * A contact's card beside the Contacts list: the agents-wall badge widened into+ * a profile header, with "Send message" into its chat and, for editors, "Edit+ * profile". Opening a contact only previews it — the chat and the edit surface+ * are one click on.+ */+const ContactDetail = memo<{ id: string }>(({ id }) => {+ const { t } = useTranslation('common');+ const card = useContactCard(id);++ switch (card.status) {+ case 'ready': {+ return <ContactCard {...card} />;+ }+ case 'error': {+ return (+ <Flexbox align={'center'} flex={1} justify={'center'} {...stylex.props(styles.state)}>+ <AsyncError error={card.error} variant="inline" onRetry={card.retry} />+ </Flexbox>+ );+ }+ case 'missing': {+ return (+ <Flexbox align={'center'} flex={1} justify={'center'} {...stylex.props(styles.state)}>+ <Empty description={t('contacts.notFound')} icon={UserRoundXIcon} />+ </Flexbox>+ );+ }+ default: {+ return (+ <>+ <Skeleton height={COVER_HEIGHT} radius={12} width={'100%'} />+ <Flexbox align={'center'} gap={12} {...stylex.props(styles.body)}>+ <Skeleton.Avatar+ shape={'circle'}+ size={AVATAR_SIZE}+ style={{ marginBlockStart: -AVATAR_SIZE / 2 }}+ />+ <Skeleton height={28} width={160} />+ <Skeleton.Text rows={2} width={['100%', '60%']} />+ </Flexbox>+ </>+ );+ }+ }+});++ContactDetail.displayName = 'ContactDetail';++export { ContactDetail };++/** `/agents/:id`: the contact card in the content column of the Contacts tab. */+const ContactDetailPage = () => {+ const { id } = useParams<{ id: string }>();++ return (+ <Flexbox flex={1} height={'100%'}>+ <NavHeader />+ <Flexbox+ align={'center'}+ flex={1}+ paddingInline={16}+ style={{ overflowY: 'auto', paddingBlockStart: 8 }}+ >+ {id && <ContactDetail id={id} key={id} />}+ </Flexbox>+ </Flexbox>+ );+};++export default ContactDetailPage;diff --git a/src/features/ContactList/const.ts b/src/features/ContactList/const.tsnew file mode 100644index 00000000000..06b00354946--- /dev/null+++ b/src/features/ContactList/const.ts@@ -0,0 +1,2 @@+/** The contact card of an agent or group, shown beside the Contacts list. */+export const CONTACT_URL = (id: string) => `/agents/${id}`;diff --git a/src/features/ContactList/index.test.tsx b/src/features/ContactList/index.test.tsxindex 61241b228b5..0a04d2719a6 100644--- a/src/features/ContactList/index.test.tsx+++ b/src/features/ContactList/index.test.tsx@@ -75,4 +75,23 @@ describe('ContactListBody', () => {);expect(screen.queryByText('Turns ideas into product specs')).not.toBeInTheDocument();});++ it('opens the contact card instead of the profile editor', () => {+ agentList.init = true;+ agentList.items = [+ { id: 'agt_1', title: 'Product Helper' },+ { id: 'grp_1', title: 'Launch Crew', type: 'group' },+ ];++ render(createElement(ContactListBody));++ expect(screen.getByRole('link', { name: 'Product Helper' })).toHaveAttribute(+ 'href',+ '/agents/agt_1',+ );+ expect(screen.getByRole('link', { name: 'Launch Crew' })).toHaveAttribute(+ 'href',+ '/agents/grp_1',+ );+ });});diff --git a/src/features/ContactList/index.tsx b/src/features/ContactList/index.tsxindex 176e1d2358d..18ca85be3f7 100644--- a/src/features/ContactList/index.tsx+++ b/src/features/ContactList/index.tsx@@ -19,10 +19,8 @@ import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';-import AgentAvatar from '@/components/AgentAvatar';import AsyncError from '@/components/AsyncError';import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';-import AgentGroupAvatar from '@/features/AgentGroupAvatar';import { AgentModalProvider } from '@/features/HomeSidebar/Body/Agent/ModalProvider';import { useCreateMenuItems } from '@/features/HomeSidebar/hooks';import { AVATAR_SIZE, ConversationRow, ListHeader } from '@/features/MessageList';@@ -35,6 +33,8 @@ import { useFetchAgentList } from '@/hooks/useFetchAgentList';import { useHomeStore } from '@/store/home';import { homeAgentListSelectors } from '@/store/home/selectors';+import { CONTACT_URL } from './const';+import ContactAvatar from './ContactAvatar';import { styles } from './style';const byTitle = (fallback: string) => (a: SidebarAgentItem, b: SidebarAgentItem) =>@@ -46,41 +46,23 @@ const useActiveRouteId = () => {const segments = pathname.split('/').filter(Boolean);const [root, id] = slug && segments[0] === slug ? segments.slice(1) : segments;- return root === 'agent' || root === 'group' ? id : undefined;+ return root === 'agents' || root === 'agent' || root === 'group' ? id : undefined;};const Contact = memo<{ active: boolean; item: SidebarAgentItem }>(({ active, item }) => {const { t } = useTranslation('chat');- const isGroup = item.type === 'group';- const title = isGroup- ? item.title || t('untitledAgent')- : agentDisplayName(item, t('untitledAgent'));- const customAvatar = typeof item.avatar === 'string' ? item.avatar : undefined;+ const title =+ item.type === 'group'+ ? item.title || t('untitledAgent')+ : agentDisplayName(item, t('untitledAgent'));return (<ConversationRowsingleLineactive={active}+ avatar={<ContactAvatar item={item} name={title} size={AVATAR_SIZE} />}title={title}- url={isGroup ? `/group/${item.id}/profile` : `/agent/${item.id}/profile`}- avatar={- isGroup ? (- <AgentGroupAvatar- avatar={customAvatar}- backgroundColor={item.backgroundColor || undefined}- memberAvatars={Array.isArray(item.avatar) ? item.avatar : []}- size={AVATAR_SIZE}- />- ) : (- <AgentAvatar- agentId={item.id}- avatar={customAvatar}- background={item.backgroundColor || undefined}- name={title}- size={AVATAR_SIZE}- />- )- }+ url={CONTACT_URL(item.id)}/>);});@@ -188,7 +170,8 @@ Header.displayName = 'ContactListHeader';/*** Contacts tab list column: every agent and group, alphabetically. A row opens- * the profile (`/agent/:id/profile`), which is the agent's edit surface.+ * the contact card (`/agents/:id`) and keeps the list in place; the card is+ * where the user starts a chat or goes on to edit the profile.*/const ContactListPortal = () => (<NavPanelPortal navKey={NAV_PANEL_CONTACTS_KEY}>diff --git a/src/features/ContactList/useContactCard.test.ts b/src/features/ContactList/useContactCard.test.tsnew file mode 100644index 00000000000..168da39a4ed--- /dev/null+++ b/src/features/ContactList/useContactCard.test.ts@@ -0,0 +1,91 @@+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useContactCard } from './useContactCard';++const fetch = vi.hoisted(() => ({ error: undefined as unknown, mutate: vi.fn() }));+const agentList = vi.hoisted(() => ({ init: true, items: [] as { id: string }[] }));+const access = vi.hoisted(() => ({ canEdit: true }));++vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('@/hooks/useFetchAgentList', () => ({ useFetchAgentList: () => fetch }));+vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: true }) }));+vi.mock('@/features/ResourcePermission/useResourceAccess', () => ({+ useResourceAccess: () => ({ canEditResource: access.canEdit }),+}));+vi.mock('@/store/home', () => ({+ useHomeStore: (selector: (state: object) => unknown) => selector({}),+}));+vi.mock('@/store/home/selectors', () => ({+ homeAgentListSelectors: {+ getAgentById: (id: string) => () => agentList.items.find((item) => item.id === id),+ isAgentListInit: () => agentList.init,+ },+}));++beforeEach(() => {+ fetch.error = undefined;+ fetch.mutate.mockReset();+ access.canEdit = true;+ agentList.init = true;+ agentList.items = [+ { id: 'agt_1', name: 'Ada', slug: 'ada', title: 'Product Helper' },+ { id: 'grp_1', title: 'Launch Crew', type: 'group' },+ ] as { id: string }[];+});++describe('useContactCard', () => {+ it('opens an agent chat and its profile editor', () => {+ const { result } = renderHook(() => useContactCard('agt_1'));++ expect(result.current).toMatchObject({+ canEdit: true,+ chatUrl: '/agent/agt_1',+ profileUrl: '/agent/agt_1/profile',+ role: 'Product Helper',+ slug: 'ada',+ status: 'ready',+ title: 'Ada',+ });+ });++ it('opens a group chat and the group profile', () => {+ const { result } = renderHook(() => useContactCard('grp_1'));++ expect(result.current).toMatchObject({+ chatUrl: '/group/grp_1',+ profileUrl: '/group/grp_1/profile',+ role: undefined,+ status: 'ready',+ title: 'Launch Crew',+ });+ });++ it('does not offer the profile editor to viewers who cannot edit', () => {+ access.canEdit = false;++ const { result } = renderHook(() => useContactCard('agt_1'));++ expect(result.current).toMatchObject({ canEdit: false, status: 'ready' });+ });++ it('waits for the first load, then reports a contact that is not in the list', () => {+ agentList.init = false;+ expect(renderHook(() => useContactCard('agt_missing')).result.current.status).toBe('loading');++ agentList.init = true;+ expect(renderHook(() => useContactCard('agt_missing')).result.current.status).toBe('missing');+ });++ it('turns a failed first load into a retry instead of an endless skeleton', () => {+ agentList.init = false;+ agentList.items = [];+ fetch.error = new Error('429');++ const { result } = renderHook(() => useContactCard('agt_1'));++ expect(result.current.status).toBe('error');+ if (result.current.status === 'error') result.current.retry();+ expect(fetch.mutate).toHaveBeenCalled();+ });+});diff --git a/src/features/ContactList/useContactCard.ts b/src/features/ContactList/useContactCard.tsnew file mode 100644index 00000000000..f47837a1e64--- /dev/null+++ b/src/features/ContactList/useContactCard.ts@@ -0,0 +1,68 @@+import { AGENT_CHAT_URL, AGENT_PROFILE_URL, GROUP_CHAT_URL } from '@lobechat/const';+import {+ agentDisplayName,+ agentSecondaryDisplayName,+ type SidebarAgentItem,+} from '@lobechat/types';+import isEqual from 'fast-deep-equal';+import { useTranslation } from 'react-i18next';++import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';+import { useFetchAgentList } from '@/hooks/useFetchAgentList';+import { usePermission } from '@/hooks/usePermission';+import { useHomeStore } from '@/store/home';+import { homeAgentListSelectors } from '@/store/home/selectors';++interface ContactCardData {+ /** Who may open the profile editor; the server still checks every write. */+ canEdit: boolean;+ chatUrl: string;+ item: SidebarAgentItem;+ profileUrl: string;+ /** The agent's role beside its personal name; absent for groups and unnamed agents. */+ role?: string;+ slug?: string;+ title: string;+}++export type ContactCardState =+ | { error: unknown; retry: () => void; status: 'error' }+ | { status: 'loading' }+ | { status: 'missing' }+ | ({ status: 'ready' } & ContactCardData);++/**+ * Everything the contact card shows for an agent or group, read from the+ * already-loaded contact list. A failed first load is `error` rather than an+ * endless `loading`: on mobile no Contacts list sits beside the card to offer+ * the retry.+ */+export const useContactCard = (id: string): ContactCardState => {+ const { t } = useTranslation('chat');+ const { error, mutate } = useFetchAgentList();+ const isInit = useHomeStore(homeAgentListSelectors.isAgentListInit);+ const item = useHomeStore(homeAgentListSelectors.getAgentById(id), isEqual);+ const isGroup = item?.type === 'group';++ const { allowed: canEditContent } = usePermission('edit_own_content');+ const { canEditResource } = useResourceAccess(+ isGroup ? 'agentGroup' : 'agent',+ item ? id : undefined,+ );++ if (!item) {+ if (isInit) return { status: 'missing' };+ return error ? { error, retry: () => void mutate(), status: 'error' } : { status: 'loading' };+ }++ return {+ canEdit: !!canEditContent && canEditResource,+ chatUrl: isGroup ? GROUP_CHAT_URL(id) : AGENT_CHAT_URL(id),+ item,+ profileUrl: isGroup ? `/group/${id}/profile` : AGENT_PROFILE_URL(id),+ role: isGroup ? undefined : agentSecondaryDisplayName(item),+ slug: isGroup ? undefined : item.slug || undefined,+ status: 'ready',+ title: isGroup ? item.title || t('untitledAgent') : agentDisplayName(item, t('untitledAgent')),+ };+};diff --git a/src/routes/(main)/agents/[id]/index.tsx b/src/routes/(main)/agents/[id]/index.tsxnew file mode 100644index 00000000000..56093edf55a--- /dev/null+++ b/src/routes/(main)/agents/[id]/index.tsx@@ -0,0 +1,5 @@+import ContactDetailPage from '@/features/ContactList/ContactDetail';++const ContactDetailRoute = () => <ContactDetailPage />;++export default ContactDetailRoute;diff --git a/src/spa/router/collaborationRoutes.tsx b/src/spa/router/collaborationRoutes.tsxindex 7fe26905e13..65693c6312a 100644--- a/src/spa/router/collaborationRoutes.tsx+++ b/src/spa/router/collaborationRoutes.tsx@@ -17,6 +17,15 @@ export const collaborationRoutes: RouteObject[] = [handle: { meta: agentsRouteMeta },index: true,},+ {+ element: dynamicElement(+ () => import('@/routes/(main)/agents/[id]'),+ 'Desktop > Agents > Contact',+ { preloadId: 'agents' },+ ),+ handle: { meta: agentsRouteMeta },+ path: ':id',+ },],errorElement: <ErrorBoundary resetPath=".." />,path: 'agents',diff --git a/src/spa/router/mobileRouter.config.tsx b/src/spa/router/mobileRouter.config.tsxindex 8dbefd91357..e565ebbe10d 100644--- a/src/spa/router/mobileRouter.config.tsx+++ b/src/spa/router/mobileRouter.config.tsx@@ -303,6 +303,15 @@ export const sharedMainAreaChildren: RouteObject[] = [handle: { meta: routeMeta({ icon: BotIcon, titleKey: 'navigation.agents' }) },index: true,},+ {+ element: dynamicElement(+ () => import('@/routes/(main)/agents/[id]'),+ 'Mobile > Agents > Contact',+ { preloadId: 'mobile-agents' },+ ),+ handle: { meta: routeMeta({ icon: BotIcon, titleKey: 'navigation.agents' }) },+ path: ':id',+ },],errorElement: <ErrorBoundary resetPath=".." />,path: 'agents',