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(home): virtualize and add search to the home Agent switcher (#21441)

Arvin Xuac1e8d7de650
diff --git a/src/features/Home/AgentSelect/AgentList.tsx b/src/features/Home/AgentSelect/AgentList.tsx
index 0970392c943..7b3a0b4178e 100644
--- a/src/features/Home/AgentSelect/AgentList.tsx
+++ b/src/features/Home/AgentSelect/AgentList.tsx
@@ -1,8 +1,19 @@
'use client';
-import { ActionIcon, Block, createStaticStyles, cssVar, Flexbox, Text } from '@lobehub/ui';
-import { PinIcon } from 'lucide-react';
-import { memo, type ReactNode } from 'react';
+import {
+ ActionIcon,
+ createStaticStyles,
+ cssVar,
+ cx,
+ DropdownMenuHeader,
+ DropdownMenuItem,
+ DropdownMenuScrollViewport,
+ Icon,
+ Input,
+ Text,
+} from '@lobehub/ui';
+import { PinIcon, SearchIcon } from 'lucide-react';
+import { memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import AsyncBoundary from '@/components/AsyncBoundary';
@@ -14,13 +25,35 @@ import { homeAgentListSelectors } from '@/store/home/selectors';
import { type AgentRow, useHomeAgentRows } from './useHomeAgentRows';
+/** Row height hint for the virtual list — keep in sync with `styles.item`. */
+const ROW_HEIGHT = 36;
+const SECTION_HEIGHT = 28;
+const MAX_LIST_HEIGHT = 360;
+
const styles = createStaticStyles(({ css, cssVar }) => ({
active: css`
background: ${cssVar.colorFillTertiary};
`,
+ empty: css`
+ padding-block: 24px;
+ padding-inline: 12px;
+
+ font-size: 13px;
+ color: ${cssVar.colorTextTertiary};
+ text-align: center;
+ `,
+ header: css`
+ padding: 0;
+ `,
item: css`
cursor: pointer;
- padding-block: 6px;
+
+ display: flex;
+ gap: 8px;
+ align-items: center;
+
+ height: ${ROW_HEIGHT}px;
+ padding-block: 0;
padding-inline: 8px;
border-radius: ${cssVar.borderRadius};
@@ -28,13 +61,21 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
background: ${cssVar.colorFillSecondary};
}
`,
- list: css`
- padding: 8px;
- `,
- sectionHeader: css`
+ searchBar: css`
padding-block: 4px;
+ padding-inline: 12px;
+ border-block-end: 1px solid ${cssVar.colorSplit};
+ `,
+ // Same spec as the agent-detail SwitchPanel's section header.
+ section: css`
+ height: ${SECTION_HEIGHT}px;
+ padding-block: 4px 2px;
padding-inline: 8px;
+
+ font-size: 12px;
+ font-weight: 500;
line-height: 20px;
+ color: ${cssVar.colorTextSecondary};
`,
}));
@@ -46,56 +87,53 @@ interface AgentListProps {
onSelect: (agentId: string) => void;
}
-// Same spec as the agent-detail SwitchPanel's section header.
-const SectionHeader = memo<{ children: ReactNode }>(({ children }) => (
- <Flexbox className={styles.sectionHeader}>
- <Text fontSize={12} type={'secondary'} weight={500}>
- {children}
- </Text>
- </Flexbox>
-));
+type ListRow =
+ | { key: string; kind: 'section'; label: string }
+ | { key: string; kind: 'agent'; row: AgentRow };
+
+const toAgentRow = (row: AgentRow): ListRow => ({ key: row.id, kind: 'agent', row });
+const toSectionRow = (key: string, label: string): ListRow => ({ key, kind: 'section', label });
const AgentList = memo<AgentListProps>(({ activeAgentId, error, onRetry, onSelect }) => {
const { t } = useTranslation('common');
+ const [search, setSearch] = useState('');
const isInit = useHomeStore(homeAgentListSelectors.isAgentListInit);
const { privateRows, showPrivateSection, workspaceRows } = useHomeAgentRows();
- const renderRow = (row: AgentRow) => {
- const isActive = row.id === activeAgentId;
-
- return (
- <Block
- clickable
- horizontal
- align={'center'}
- className={`${styles.item} ${isActive ? styles.active : ''}`}
- gap={8}
- key={row.id}
- variant={'borderless'}
- onClick={() => onSelect(row.id)}
- >
- <Avatar
- avatar={row.avatar || DEFAULT_AVATAR}
- background={row.backgroundColor}
- name={row.title}
- shape={'square'}
- size={24}
- />
- <Text
- ellipsis
- color={isActive ? cssVar.colorText : cssVar.colorTextSecondary}
- style={{ flex: 1 }}
- weight={isActive ? 600 : 500}
- >
- {row.title}
- </Text>
- {row.pinned && (
- <ActionIcon icon={PinIcon} size={12} style={{ opacity: 0.5, pointerEvents: 'none' }} />
- )}
- </Block>
- );
- };
+ const rows = useMemo<ListRow[]>(() => {
+ const query = search.trim().toLowerCase();
+ const match = (row: AgentRow) =>
+ !query ||
+ row.title.toLowerCase().includes(query) ||
+ (row.subtitle ?? '').toLowerCase().includes(query);
+
+ const privateMatches = privateRows.filter(match);
+ const workspaceMatches = workspaceRows.filter(match);
+
+ if (!showPrivateSection) return [...workspaceMatches, ...privateMatches].map(toAgentRow);
+
+ // A section whose rows were all filtered out drops its header too — an
+ // empty label above nothing reads as a bug.
+ const out: ListRow[] = [];
+ if (privateMatches.length > 0) {
+ out.push(toSectionRow('section-private', t('navPanel.privateAgents')));
+ out.push(...privateMatches.map(toAgentRow));
+ }
+ if (workspaceMatches.length > 0) {
+ out.push(toSectionRow('section-workspace', t('navPanel.publicAgents')));
+ out.push(...workspaceMatches.map(toAgentRow));
+ }
+ return out;
+ }, [privateRows, search, showPrivateSection, t, workspaceRows]);
+
+ // The virtual viewport needs an explicit height; clamp to the old 360px cap
+ // so a long list scrolls instead of growing the popup.
+ const contentHeight = rows.reduce(
+ (sum, item) => sum + (item.kind === 'section' ? SECTION_HEIGHT : ROW_HEIGHT),
+ 0,
+ );
+ const listHeight = Math.min(Math.max(contentHeight, ROW_HEIGHT), MAX_LIST_HEIGHT);
// Error gated ahead of the skeleton so a failed list fetch shows Retry instead
// of a permanent skeleton (`isAgentListInit` only flips on success).
@@ -108,22 +146,83 @@ const AgentList = memo<AgentListProps>(({ activeAgentId, error, onRetry, onSelec
loading={<SkeletonList rows={6} style={{ padding: 8 }} />}
onRetry={onRetry}
>
- <Flexbox
- className={styles.list}
- gap={2}
- style={{ maxHeight: 360, overflowY: 'auto', width: '100%' }}
- >
- {showPrivateSection ? (
- <>
- <SectionHeader>{t('navPanel.privateAgents')}</SectionHeader>
- {privateRows.map(renderRow)}
- <SectionHeader>{t('navPanel.publicAgents')}</SectionHeader>
- {workspaceRows.map(renderRow)}
- </>
- ) : (
- [...workspaceRows, ...privateRows].map(renderRow)
- )}
- </Flexbox>
+ <DropdownMenuHeader className={styles.header}>
+ <div className={styles.searchBar}>
+ <Input
+ autoFocus
+ placeholder={t('navPanel.searchAgent')}
+ prefix={<Icon icon={SearchIcon} size={14} />}
+ size={'small'}
+ style={{ paddingInline: 0 }}
+ value={search}
+ variant={'borderless'}
+ onChange={(e) => setSearch(e.target.value)}
+ // Let arrows / Esc reach the menu (they move focus into the list and
+ // close it); keep plain typing from triggering menu typeahead.
+ onKeyDown={(e) => {
+ const isMenuKey = e.key === 'Escape' || e.key === 'ArrowDown' || e.key === 'ArrowUp';
+ if (!isMenuKey) e.stopPropagation();
+ }}
+ />
+ </div>
+ </DropdownMenuHeader>
+ {rows.length === 0 ? (
+ <div className={styles.empty}>{t('navPanel.searchResultEmpty')}</div>
+ ) : (
+ <DropdownMenuScrollViewport
+ getItemLabel={(_, index) => {
+ const item = rows[index];
+ return item?.kind === 'agent' ? item.row.title : undefined;
+ }}
+ // virtua sizes itself on mount; remount when the filtered count changes
+ // so a narrowed list never leaves stale rows undrawn.
+ key={rows.length}
+ listItemHeight={ROW_HEIGHT}
+ style={{ height: listHeight }}
+ virtual
+ >
+ {rows.map((item) =>
+ item.kind === 'section' ? (
+ // `aria-disabled` keeps typeahead / Home-End from landing on a
+ // header row: the virtual list skips disabled entries.
+ <div aria-disabled className={styles.section} key={item.key}>
+ {item.label}
+ </div>
+ ) : (
+ <DropdownMenuItem
+ className={cx(styles.item, item.row.id === activeAgentId && styles.active)}
+ key={item.key}
+ onClick={() => onSelect(item.row.id)}
+ >
+ <Avatar
+ avatar={item.row.avatar || DEFAULT_AVATAR}
+ background={item.row.backgroundColor}
+ name={item.row.title}
+ shape={'square'}
+ size={24}
+ />
+ <Text
+ ellipsis
+ color={
+ item.row.id === activeAgentId ? cssVar.colorText : cssVar.colorTextSecondary
+ }
+ style={{ flex: 1 }}
+ weight={item.row.id === activeAgentId ? 600 : 500}
+ >
+ {item.row.title}
+ </Text>
+ {item.row.pinned && (
+ <ActionIcon
+ icon={PinIcon}
+ size={12}
+ style={{ opacity: 0.5, pointerEvents: 'none' }}
+ />
+ )}
+ </DropdownMenuItem>
+ ),
+ )}
+ </DropdownMenuScrollViewport>
+ )}
</AsyncBoundary>
);
});
diff --git a/src/features/Home/AgentSelect/index.tsx b/src/features/Home/AgentSelect/index.tsx
index 9657abcbc49..383a2ba2942 100644
--- a/src/features/Home/AgentSelect/index.tsx
+++ b/src/features/Home/AgentSelect/index.tsx
@@ -1,9 +1,18 @@
'use client';
import { agentDisplayName } from '@lobechat/types';
-import { Button, createStaticStyles, Popover, Text } from '@lobehub/ui';
+import {
+ Button,
+ createStaticStyles,
+ DropdownMenuPopup,
+ DropdownMenuPortal,
+ DropdownMenuPositioner,
+ DropdownMenuRoot,
+ DropdownMenuTrigger,
+ Text,
+} from '@lobehub/ui';
import { ChevronsUpDownIcon } from 'lucide-react';
-import { memo, useState } from 'react';
+import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import Avatar from '@/components/Avatar';
@@ -29,6 +38,14 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
font-size: 14px;
line-height: 20px;
`,
+ popup: css`
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+
+ width: 360px;
+ max-width: calc(100vw - 16px);
+ `,
trigger: css`
gap: 8px;
justify-content: flex-start;
@@ -75,52 +92,63 @@ const AgentSelect = memo(() => {
(typeof displayMeta?.avatar === 'string' ? displayMeta.avatar : undefined) ||
(showInboxFallback ? DEFAULT_INBOX_AVATAR : DEFAULT_AVATAR);
- const handleSelect = (agentId: string) => {
- updateSystemStatus({ homeSelectedAgentId: agentId });
- setOpen(false);
+ const handleOpenChange = useCallback((nextOpen: boolean) => {
+ setOpen(nextOpen);
+ }, []);
- const agentState = useAgentStore.getState();
- if (agentState.agentMap[agentId]) return;
+ const handleSelect = useCallback(
+ (agentId: string) => {
+ updateSystemStatus({ homeSelectedAgentId: agentId });
+ setOpen(false);
- agentService
- .getAgentConfigById(agentId)
- .then((config) => {
- if (config) agentState.internal_dispatchAgentMap(agentId, config);
- })
- .catch((error) => console.error('[AgentSelect] failed to prefetch agent config', error));
- };
+ const agentState = useAgentStore.getState();
+ if (agentState.agentMap[agentId]) return;
+
+ agentService
+ .getAgentConfigById(agentId)
+ .then((config) => {
+ if (config) agentState.internal_dispatchAgentMap(agentId, config);
+ })
+ .catch((error) => console.error('[AgentSelect] failed to prefetch agent config', error));
+ },
+ [updateSystemStatus],
+ );
return (
- <Popover
- classNames={{ trigger: styles.trigger }}
- open={open}
- placement={'bottomLeft'}
- styles={{ content: { padding: 0, width: 360 } }}
- trigger={'click'}
- content={
- <AgentList
- activeAgentId={displayAgentId}
- error={error}
- onRetry={() => mutate()}
- onSelect={handleSelect}
- />
- }
- onOpenChange={setOpen}
- >
- <Button aria-expanded={open} aria-haspopup={'dialog'} type={'text'}>
- <Avatar
- avatar={displayAvatar}
- background={displayMeta?.backgroundColor || undefined}
- name={displayTitle}
- shape={'square'}
- size={24}
- />
- <Text ellipsis className={styles.name} style={{ minWidth: 0 }} weight={600}>
- {displayTitle}
- </Text>
- <ChevronsUpDownIcon className={`${styles.chevron} agent-select-chevron`} size={12} />
- </Button>
- </Popover>
+ <DropdownMenuRoot open={open} onOpenChange={handleOpenChange}>
+ <DropdownMenuTrigger>
+ <Button
+ aria-expanded={open}
+ aria-haspopup={'menu'}
+ className={styles.trigger}
+ type={'text'}
+ >
+ <Avatar
+ avatar={displayAvatar}
+ background={displayMeta?.backgroundColor || undefined}
+ name={displayTitle}
+ shape={'square'}
+ size={24}
+ />
+ <Text ellipsis className={styles.name} style={{ minWidth: 0 }} weight={600}>
+ {displayTitle}
+ </Text>
+ <ChevronsUpDownIcon className={`${styles.chevron} agent-select-chevron`} size={12} />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuPositioner placement={'bottomLeft'} sideOffset={8}>
+ <DropdownMenuPopup className={styles.popup}>
+ <AgentList
+ activeAgentId={displayAgentId}
+ error={error}
+ onRetry={() => mutate()}
+ onSelect={handleSelect}
+ />
+ </DropdownMenuPopup>
+ </DropdownMenuPositioner>
+ </DropdownMenuPortal>
+ </DropdownMenuRoot>
);
});