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.

♻️ refactor(nav): turn sidebar header select into an identity switcher (#18338)

Innei446027e18f01
diff --git a/locales/en-US/common.json b/locales/en-US/common.json
index 835ea373d85..8e6e1e81228 100644
--- a/locales/en-US/common.json
+++ b/locales/en-US/common.json
@@ -415,9 +415,12 @@
"navPanel.publicAgents": "Workspace",
"navPanel.resetDefault": "Reset to Default",
"navPanel.searchAgent": "Search Agent...",
+ "navPanel.searchProject": "Search projects...",
"navPanel.searchRecent": "Search Recent...",
"navPanel.searchResultEmpty": "No search results found",
"navPanel.show": "Show",
+ "navPanel.switcherAll": "All",
+ "navPanel.switcherRecent": "Recent",
"navPanel.viewAllAgents": "View all",
"navPanel.visible": "Visible",
"new": "New",
diff --git a/locales/zh-CN/common.json b/locales/zh-CN/common.json
index 3a92831295b..cee463f20b4 100644
--- a/locales/zh-CN/common.json
+++ b/locales/zh-CN/common.json
@@ -415,9 +415,12 @@
"navPanel.publicAgents": "工作区",
"navPanel.resetDefault": "恢复默认",
"navPanel.searchAgent": "搜索助理…",
+ "navPanel.searchProject": "搜索项目…",
"navPanel.searchRecent": "搜索最近…",
"navPanel.searchResultEmpty": "暂无搜索结果",
"navPanel.show": "显示",
+ "navPanel.switcherAll": "全部",
+ "navPanel.switcherRecent": "最近",
"navPanel.viewAllAgents": "查看全部",
"navPanel.visible": "显示中",
"new": "新",
diff --git a/packages/locales/src/default/common.ts b/packages/locales/src/default/common.ts
index 0b0b09c4077..369d9e33604 100644
--- a/packages/locales/src/default/common.ts
+++ b/packages/locales/src/default/common.ts
@@ -504,9 +504,12 @@ export default {
'navPanel.show': 'Show',
'navPanel.visible': 'Visible',
'navPanel.searchAgent': 'Search Agent...',
+ 'navPanel.searchProject': 'Search projects...',
'navPanel.viewAllAgents': 'View all',
'navPanel.searchRecent': 'Search Recent...',
'navPanel.searchResultEmpty': 'No search results found',
+ 'navPanel.switcherAll': 'All',
+ 'navPanel.switcherRecent': 'Recent',
'new': 'New',
'pro': 'Pro',
'noContent': 'No content',
diff --git a/src/features/AgentSidebar/Header/Agent/SwitchPanel.tsx b/src/features/AgentSidebar/Header/Agent/SwitchPanel.tsx
index 2c63957e173..49dda7ce071 100644
--- a/src/features/AgentSidebar/Header/Agent/SwitchPanel.tsx
+++ b/src/features/AgentSidebar/Header/Agent/SwitchPanel.tsx
@@ -1,84 +1,74 @@
-import { Flexbox, Text } from '@lobehub/ui';
-import { createStaticStyles } from 'antd-style';
import type { PropsWithChildren } from 'react';
-import { memo, Suspense, useCallback, useMemo } from 'react';
+import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
-import AgentListContent from '@/features/HomeSidebar/Body/Agent/List/AgentListContent';
-import { AgentModalProvider } from '@/features/HomeSidebar/Body/Agent/ModalProvider';
-import PrivateList from '@/features/HomeSidebar/Body/Private/List';
-import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useHomeAgentRows } from '@/features/Home/AgentSelect/useHomeAgentRows';
+import { resolvePreservedAgentUrl } from '@/features/HomeSidebar/Body/Agent/List/usePreservedAgentUrl';
import { SidebarHeaderSelectPopover } from '@/features/NavPanel/SidebarHeaderSelect';
+import type { SwitcherItem } from '@/features/NavPanel/switcher/switcherItems';
+import SwitcherMenu from '@/features/NavPanel/switcher/SwitcherMenu';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useActiveLocation } from '@/hooks/useActiveLocation';
import { useFetchAgentList } from '@/hooks/useFetchAgentList';
+import { useAgentStore } from '@/store/agent';
import { useHomeStore } from '@/store/home';
import { homeAgentListSelectors } from '@/store/home/selectors';
-const styles = createStaticStyles(({ css }) => ({
- sectionHeader: css`
- padding-block: 4px;
- padding-inline: 8px;
- line-height: 20px;
- `,
-}));
-
-interface SectionHeaderProps {
- children: React.ReactNode;
-}
-
-const SectionHeader = memo<SectionHeaderProps>(({ children }) => (
- <Flexbox className={styles.sectionHeader}>
- <Text fontSize={12} type="secondary" weight={500}>
- {children}
- </Text>
- </Flexbox>
-));
-
const SwitchPanel = memo<PropsWithChildren>(({ children }) => {
- const navigate = useWorkspaceAwareNavigate();
- const activeWorkspaceId = useActiveWorkspaceId();
const { t } = useTranslation('common');
- // AgentListContent no longer owns the SWR subscription; subscribe here so
- // the standalone switcher still triggers a fetch when opened.
- useFetchAgentList();
-
- // Only show the "私人 / 工作区" split when the user actually has private
- // items in this workspace — a lone Private header above an empty section
- // would be noise.
- const hasPrivateItems = useHomeStore(homeAgentListSelectors.hasPrivateAgents);
- const showPrivateSection = Boolean(activeWorkspaceId) && hasPrivateItems;
+ const navigate = useWorkspaceAwareNavigate();
+ const { pathname } = useActiveLocation();
+ const { error, mutate } = useFetchAgentList();
+ const isInit = useHomeStore(homeAgentListSelectors.isAgentListInit);
+ const activeId = useAgentStore((s) => s.activeAgentId);
+ const { privateRows, workspaceRows } = useHomeAgentRows();
- const handleMoreClick = useCallback(() => navigate('/'), [navigate]);
+ const items = useMemo<SwitcherItem[]>(
+ () => [
+ ...privateRows.map((row) => ({
+ avatar: row.avatar,
+ background: row.backgroundColor,
+ id: row.id,
+ private: true,
+ title: row.title,
+ })),
+ ...workspaceRows.map((row) => ({
+ avatar: row.avatar,
+ background: row.backgroundColor,
+ id: row.id,
+ title: row.title,
+ })),
+ ],
+ [privateRows, workspaceRows],
+ );
- const content = useMemo(
- () => (
- <Suspense fallback={<SkeletonList rows={6} />}>
- <AgentModalProvider>
- <Flexbox
- gap={4}
- padding={8}
- style={{
- maxHeight: '50vh',
- overflowY: 'auto',
- }}
- >
- {showPrivateSection && (
- <>
- <SectionHeader>{t('navPanel.privateAgents')}</SectionHeader>
- <PrivateList hideCreateButton onMoreClick={handleMoreClick} />
- <SectionHeader>{t('navPanel.publicAgents')}</SectionHeader>
- </>
- )}
- <AgentListContent onMoreClick={handleMoreClick} />
- </Flexbox>
- </AgentModalProvider>
- </Suspense>
- ),
- [handleMoreClick, showPrivateSection, t],
+ const handleSelect = useCallback(
+ (id: string) => {
+ navigate(resolvePreservedAgentUrl(pathname, id));
+ },
+ [navigate, pathname],
);
- return <SidebarHeaderSelectPopover content={content}>{children}</SidebarHeaderSelectPopover>;
+ return (
+ <SidebarHeaderSelectPopover
+ content={
+ <SwitcherMenu
+ activeId={activeId}
+ error={error}
+ isLoading={!isInit && !error}
+ items={items}
+ kind={'agent'}
+ searchPlaceholder={t('navPanel.searchAgent')}
+ onRetry={() => mutate()}
+ onSelect={handleSelect}
+ />
+ }
+ >
+ {children}
+ </SidebarHeaderSelectPopover>
+ );
});
+SwitchPanel.displayName = 'SwitchPanel';
+
export default SwitchPanel;
diff --git a/src/features/HomeSidebar/Body/Agent/List/usePreservedAgentUrl.test.ts b/src/features/HomeSidebar/Body/Agent/List/usePreservedAgentUrl.test.ts
new file mode 100644
index 00000000000..552946afeab
--- /dev/null
+++ b/src/features/HomeSidebar/Body/Agent/List/usePreservedAgentUrl.test.ts
@@ -0,0 +1,17 @@
+import { AGENT_CHAT_URL } from '@lobechat/const';
+import { describe, expect, it } from 'vitest';
+
+import { resolvePreservedAgentUrl } from './usePreservedAgentUrl';
+
+describe('resolvePreservedAgentUrl', () => {
+ it('keeps an agent-scoped subview when switching agents', () => {
+ expect(resolvePreservedAgentUrl('/agent/agt_a/topics', 'agt_b')).toBe('/agent/agt_b/topics');
+ expect(resolvePreservedAgentUrl('/agent/agt_a/profile', 'agt_b')).toBe('/agent/agt_b/profile');
+ });
+
+ it('drops topic and task ids that belong to the previous agent', () => {
+ expect(resolvePreservedAgentUrl('/agent/agt_a/topic/tpc_1', 'agt_b')).toBe(
+ AGENT_CHAT_URL('agt_b', false),
+ );
+ });
+});
diff --git a/src/features/HomeSidebar/Body/Agent/List/usePreservedAgentUrl.ts b/src/features/HomeSidebar/Body/Agent/List/usePreservedAgentUrl.ts
index d661707176c..dd8f4b14ef5 100644
--- a/src/features/HomeSidebar/Body/Agent/List/usePreservedAgentUrl.ts
+++ b/src/features/HomeSidebar/Body/Agent/List/usePreservedAgentUrl.ts
@@ -13,14 +13,16 @@ const PRESERVED_AGENT_SUB_PATHS = new Set(['topics', 'profile', 'channel']);
* same view. Topic / task ids belong to the previous agent and are
* intentionally dropped.
*/
+export const resolvePreservedAgentUrl = (pathname: string, agentId: string): string => {
+ const match = pathname.match(/^\/agent\/[^/]+\/([^/]+)\/?$/);
+ const subPath = match?.[1];
+ if (subPath && PRESERVED_AGENT_SUB_PATHS.has(subPath)) {
+ return `/agent/${agentId}/${subPath}`;
+ }
+ return AGENT_CHAT_URL(agentId, false);
+};
+
export const usePreservedAgentUrl = (agentId: string): string => {
const { pathname } = useActiveLocation();
- return useMemo(() => {
- const match = pathname.match(/^\/agent\/[^/]+\/([^/]+)\/?$/);
- const subPath = match?.[1];
- if (subPath && PRESERVED_AGENT_SUB_PATHS.has(subPath)) {
- return `/agent/${agentId}/${subPath}`;
- }
- return AGENT_CHAT_URL(agentId, false);
- }, [agentId, pathname]);
+ return useMemo(() => resolvePreservedAgentUrl(pathname, agentId), [agentId, pathname]);
};
diff --git a/src/features/NavPanel/SidebarHeaderSelect.tsx b/src/features/NavPanel/SidebarHeaderSelect.tsx
index 806f35c94ab..dfa52756c56 100644
--- a/src/features/NavPanel/SidebarHeaderSelect.tsx
+++ b/src/features/NavPanel/SidebarHeaderSelect.tsx
@@ -1,5 +1,6 @@
'use client';
+import type { BlockProps } from '@lobehub/ui';
import { ActionIcon, Avatar, Block, Popover, Text } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { ChevronsUpDownIcon } from 'lucide-react';
@@ -23,36 +24,48 @@ interface SidebarHeaderSelectPopoverProps {
}
export const SidebarHeaderSelectPopover = memo<SidebarHeaderSelectPopoverProps>(
- ({ children, content, width = 240 }) => (
+ ({ children, content, width = 280 }) => (
<Popover
classNames={{ trigger: styles.trigger }}
content={content}
nativeButton={false}
placement={'bottomLeft'}
- styles={{ content: { padding: 0, width } }}
trigger={'click'}
+ styles={{
+ content: {
+ maxHeight: 'min(420px, 70vh)',
+ overflow: 'hidden',
+ padding: 0,
+ paddingBlock: 0,
+ paddingInline: 0,
+ width,
+ },
+ }}
>
{children}
</Popover>
),
);
-interface SidebarHeaderSelectTriggerProps {
+// Popover clones this trigger to inject onClick/ref; rest must reach Block.
+interface SidebarHeaderSelectTriggerProps extends Omit<BlockProps, 'children' | 'title'> {
avatar?: ReactNode | string;
background?: string;
title: ReactNode;
}
export const SidebarHeaderSelectTrigger = memo<SidebarHeaderSelectTriggerProps>(
- ({ avatar, background, title }) => (
+ ({ avatar, background, className, style, title, ...rest }) => (
<Block
clickable
horizontal
align={'center'}
+ className={className}
gap={8}
padding={2}
- style={{ minWidth: 32, overflow: 'hidden' }}
+ style={{ minWidth: 32, overflow: 'hidden', ...style }}
variant={'borderless'}
+ {...rest}
>
<Avatar avatar={avatar} background={background} shape={'square'} size={28} />
<Text ellipsis weight={500}>
diff --git a/src/features/NavPanel/switcher/SwitcherMenu.tsx b/src/features/NavPanel/switcher/SwitcherMenu.tsx
new file mode 100644
index 00000000000..e8cb3a3a4db
--- /dev/null
+++ b/src/features/NavPanel/switcher/SwitcherMenu.tsx
@@ -0,0 +1,173 @@
+import { Flexbox, Icon, Input, Text, usePopoverContext } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { SearchIcon } from 'lucide-react';
+import { memo, useEffect, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncBoundary from '@/components/AsyncBoundary';
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+
+import { filterSwitcherItems, pickRecentItems, type SwitcherItem } from './switcherItems';
+import SwitcherRow from './SwitcherRow';
+import { useSwitcherRecents } from './useSwitcherRecents';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ list: css`
+ overflow-y: auto;
+ overscroll-behavior: contain;
+ flex: 1 1 auto;
+
+ min-height: 0;
+ max-height: min(360px, 50vh);
+ margin-block-end: calc(var(--switcher-inset) * -1);
+ margin-inline: calc(var(--switcher-inset) * -1);
+ padding-block: 4px var(--switcher-inset);
+ padding-inline: var(--switcher-inset);
+ `,
+ root: css`
+ --switcher-inset: 6px;
+
+ overflow: hidden;
+ max-height: min(420px, 70vh);
+ padding: var(--switcher-inset);
+ `,
+ search: css`
+ flex: none;
+
+ margin-inline: calc(var(--switcher-inset) * -1);
+ padding-block: 2px 8px;
+ padding-inline: 14px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+
+ .ant-input-affix-wrapper,
+ .ant-input {
+ padding-inline: 0;
+ border: none !important;
+ background: transparent !important;
+ box-shadow: none !important;
+ }
+ `,
+ section: css`
+ padding-block: 6px 2px;
+ padding-inline: 8px;
+
+ font-size: 12px;
+ font-weight: 500;
+ line-height: 16px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+}));
+
+interface SwitcherMenuProps {
+ activeId?: string;
+ error?: unknown;
+ isLoading?: boolean;
+ items: SwitcherItem[];
+ kind: 'agent' | 'project';
+ onRetry?: () => void;
+ onSelect: (id: string) => void;
+ searchPlaceholder: string;
+}
+
+const SwitcherMenu = memo<SwitcherMenuProps>(
+ ({ activeId, error, isLoading, items, kind, onRetry, onSelect, searchPlaceholder }) => {
+ const { t } = useTranslation('common');
+ const { close } = usePopoverContext();
+ const { ids, touch } = useSwitcherRecents(kind);
+ const [query, setQuery] = useState('');
+
+ useEffect(() => {
+ if (activeId) touch(activeId);
+ }, [activeId, touch]);
+
+ const searching = query.trim().length > 0;
+ const visibleItems = useMemo(() => filterSwitcherItems(items, query), [items, query]);
+ const recentItems = useMemo(
+ () => (searching ? [] : pickRecentItems(ids, items, { excludeId: activeId })),
+ [activeId, ids, items, searching],
+ );
+
+ const handleSelect = (id: string) => {
+ touch(id);
+ close();
+ if (id !== activeId) onSelect(id);
+ };
+
+ const showRecent = recentItems.length > 0;
+
+ return (
+ <Flexbox className={styles.root}>
+ <div className={styles.search}>
+ <Input
+ allowClear
+ autoFocus
+ placeholder={searchPlaceholder}
+ prefix={<Icon color={cssVar.colorTextTertiary} icon={SearchIcon} size={14} />}
+ size={'small'}
+ value={query}
+ variant={'borderless'}
+ onChange={(event) => setQuery(event.target.value)}
+ onPressEnter={() => {
+ const first = visibleItems[0];
+ if (first) handleSelect(first.id);
+ }}
+ />
+ </div>
+ <AsyncBoundary
+ data={isLoading ? undefined : items}
+ error={error}
+ errorVariant={'inline'}
+ isEmpty={searching && visibleItems.length === 0}
+ isLoading={isLoading}
+ loading={<SkeletonList rows={4} />}
+ empty={
+ <Flexbox align={'center'} padding={16}>
+ <Text fontSize={13} type={'secondary'}>
+ {t('navPanel.searchResultEmpty')}
+ </Text>
+ </Flexbox>
+ }
+ onRetry={onRetry}
+ >
+ <div className={styles.list}>
+ <Flexbox>
+ {showRecent && (
+ <>
+ <Text as={'div'} className={styles.section}>
+ {t('navPanel.switcherRecent', { defaultValue: 'Recent' })}
+ </Text>
+ {recentItems.map((item) => (
+ <SwitcherRow
+ item={item}
+ key={`recent-${item.id}`}
+ privateLabel={t('navPanel.privateAgents')}
+ onSelect={handleSelect}
+ />
+ ))}
+ </>
+ )}
+ {showRecent && (
+ <Text as={'div'} className={styles.section}>
+ {t('navPanel.switcherAll', { defaultValue: 'All' })}
+ </Text>
+ )}
+ {visibleItems.map((item) => (
+ <SwitcherRow
+ active={item.id === activeId}
+ item={item}
+ key={item.id}
+ privateLabel={t('navPanel.privateAgents')}
+ onSelect={handleSelect}
+ />
+ ))}
+ </Flexbox>
+ </div>
+ </AsyncBoundary>
+ </Flexbox>
+ );
+ },
+);
+
+SwitcherMenu.displayName = 'SwitcherMenu';
+
+export default SwitcherMenu;
diff --git a/src/features/NavPanel/switcher/SwitcherRow.tsx b/src/features/NavPanel/switcher/SwitcherRow.tsx
new file mode 100644
index 00000000000..bc4fed4b497
--- /dev/null
+++ b/src/features/NavPanel/switcher/SwitcherRow.tsx
@@ -0,0 +1,66 @@
+import { Avatar, Block, Icon, Text } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { CheckIcon } from 'lucide-react';
+import { memo } from 'react';
+
+import type { SwitcherItem } from './switcherItems';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ current: css`
+ background: ${cssVar.colorFillTertiary};
+ `,
+ row: css`
+ cursor: pointer;
+
+ overflow: hidden;
+ flex: none;
+
+ padding-inline: 8px;
+ border-radius: ${cssVar.borderRadius};
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+}));
+
+interface SwitcherRowProps {
+ active?: boolean;
+ item: SwitcherItem;
+ onSelect: (id: string) => void;
+ privateLabel?: string;
+}
+
+const SwitcherRow = memo<SwitcherRowProps>(({ active, item, onSelect, privateLabel }) => (
+ <Block
+ clickable
+ horizontal
+ align={'center'}
+ className={active ? `${styles.row} ${styles.current}` : styles.row}
+ flex={'none'}
+ gap={8}
+ height={36}
+ variant={'borderless'}
+ onClick={() => onSelect(item.id)}
+ >
+ <Avatar avatar={item.avatar} background={item.background} shape={'square'} size={28} />
+ <Text
+ ellipsis
+ color={active ? cssVar.colorText : cssVar.colorTextSecondary}
+ style={{ flex: 1 }}
+ weight={active ? 500 : undefined}
+ >
+ {item.title}
+ </Text>
+ {item.private && privateLabel && (
+ <Text color={cssVar.colorTextTertiary} fontSize={12}>
+ {privateLabel}
+ </Text>
+ )}
+ {active && <Icon color={cssVar.colorText} icon={CheckIcon} size={14} />}
+ </Block>
+));
+
+SwitcherRow.displayName = 'SwitcherRow';
+
+export default SwitcherRow;
diff --git a/src/features/NavPanel/switcher/switcherItems.test.ts b/src/features/NavPanel/switcher/switcherItems.test.ts
new file mode 100644
index 00000000000..8f28323327f
--- /dev/null
+++ b/src/features/NavPanel/switcher/switcherItems.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ filterSwitcherItems,
+ pickRecentItems,
+ type SwitcherItem,
+ touchRecentId,
+} from './switcherItems';
+
+const item = (id: string, title = id): SwitcherItem => ({ id, title });
+
+describe('touchRecentId', () => {
+ it('prepends a new id and drops older overflow', () => {
+ expect(touchRecentId(['a', 'b', 'c'], 'd', 3)).toEqual(['d', 'a', 'b']);
+ });
+
+ it('moves an existing id to the front', () => {
+ expect(touchRecentId(['a', 'b', 'c'], 'b')).toEqual(['b', 'a', 'c']);
+ });
+
+ it('ignores an empty id', () => {
+ expect(touchRecentId(['a'], '')).toEqual(['a']);
+ });
+});
+
+describe('pickRecentItems', () => {
+ const items = [item('a', 'Alpha'), item('b', 'Beta'), item('c', 'Gamma')];
+
+ it('resolves ids that still exist, in recency order', () => {
+ expect(pickRecentItems(['c', 'missing', 'a'], items)).toEqual([
+ item('c', 'Gamma'),
+ item('a', 'Alpha'),
+ ]);
+ });
+
+ it('skips the active id and respects the limit', () => {
+ expect(pickRecentItems(['a', 'b', 'c'], items, { excludeId: 'a', limit: 1 })).toEqual([
+ item('b', 'Beta'),
+ ]);
+ });
+});
+
+describe('filterSwitcherItems', () => {
+ const items = [item('1', 'Lobe AI'), item('2', 'Writing'), item('3', 'Research')];
+
+ it('returns all items when the query is blank', () => {
+ expect(filterSwitcherItems(items, ' ')).toEqual(items);
+ });
+
+ it('matches titles case-insensitively', () => {
+ expect(filterSwitcherItems(items, 'wr')).toEqual([item('2', 'Writing')]);
+ });
+});
diff --git a/src/features/NavPanel/switcher/switcherItems.ts b/src/features/NavPanel/switcher/switcherItems.ts
new file mode 100644
index 00000000000..36d36bae06b
--- /dev/null
+++ b/src/features/NavPanel/switcher/switcherItems.ts
@@ -0,0 +1,45 @@
+export interface SwitcherItem {
+ avatar?: string;
+ background?: string;
+ id: string;
+ private?: boolean;
+ title: string;
+}
+
+export const SWITCHER_RECENT_CAP = 8;
+export const SWITCHER_RECENT_LIMIT = 5;
+
+export const touchRecentId = (ids: string[], id: string, cap = SWITCHER_RECENT_CAP): string[] => {
+ if (!id) return ids;
+ return [id, ...ids.filter((item) => item !== id)].slice(0, cap);
+};
+
+export const pickRecentItems = <T extends { id: string }>(
+ ids: string[],
+ items: readonly T[],
+ options?: { excludeId?: string; limit?: number },
+): T[] => {
+ const excludeId = options?.excludeId;
+ const limit = options?.limit ?? SWITCHER_RECENT_LIMIT;
+ const map = new Map(items.map((item) => [item.id, item]));
+ const out: T[] = [];
+
+ for (const id of ids) {
+ if (id === excludeId) continue;
+ const item = map.get(id);
+ if (!item) continue;
+ out.push(item);
+ if (out.length >= limit) break;
+ }
+
+ return out;
+};
+
+export const filterSwitcherItems = <T extends { title: string }>(
+ items: readonly T[],
+ query: string,
+): T[] => {
+ const normalized = query.trim().toLowerCase();
+ if (!normalized) return [...items];
+ return items.filter((item) => item.title.toLowerCase().includes(normalized));
+};
diff --git a/src/features/NavPanel/switcher/useSwitcherRecents.ts b/src/features/NavPanel/switcher/useSwitcherRecents.ts
new file mode 100644
index 00000000000..90659fe5250
--- /dev/null
+++ b/src/features/NavPanel/switcher/useSwitcherRecents.ts
@@ -0,0 +1,49 @@
+import { useCallback, useEffect, useState } from 'react';
+
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+
+import { touchRecentId } from './switcherItems';
+
+const STORAGE_PREFIX = 'lobe-switcher-recent';
+
+const readIds = (key: string): string[] => {
+ if (typeof window === 'undefined') return [];
+ try {
+ const raw = window.localStorage.getItem(key);
+ if (!raw) return [];
+ const parsed: unknown = JSON.parse(raw);
+ if (!Array.isArray(parsed)) return [];
+ return parsed.filter((item): item is string => typeof item === 'string' && item.length > 0);
+ } catch {
+ return [];
+ }
+};
+
+const writeIds = (key: string, ids: string[]) => {
+ if (typeof window === 'undefined') return;
+ window.localStorage.setItem(key, JSON.stringify(ids));
+};
+
+export const useSwitcherRecents = (kind: 'agent' | 'project') => {
+ const workspaceId = useActiveWorkspaceId();
+ const key = `${STORAGE_PREFIX}:${workspaceId ?? 'personal'}:${kind}`;
+ const [ids, setIds] = useState<string[]>(() => readIds(key));
+
+ useEffect(() => {
+ setIds(readIds(key));
+ }, [key]);
+
+ const touch = useCallback(
+ (id: string) => {
+ if (!id) return;
+ setIds((prev) => {
+ const next = touchRecentId(prev, id);
+ writeIds(key, next);
+ return next;
+ });
+ },
+ [key],
+ );
+
+ return { ids, touch };
+};
diff --git a/src/features/Projects/Layout/ProjectHeader.tsx b/src/features/Projects/Layout/ProjectHeader.tsx
index a19f402f403..535d84ac36c 100644
--- a/src/features/Projects/Layout/ProjectHeader.tsx
+++ b/src/features/Projects/Layout/ProjectHeader.tsx
@@ -1,16 +1,15 @@
'use client';
-import { Flexbox } from '@lobehub/ui';
-import { SquareKanbanIcon } from 'lucide-react';
-import { memo } from 'react';
+import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import NavItem from '@/features/NavPanel/components/NavItem';
import SideBarHeaderLayout from '@/features/NavPanel/SideBarHeaderLayout';
import {
SidebarHeaderSelectPopover,
SidebarHeaderSelectTrigger,
} from '@/features/NavPanel/SidebarHeaderSelect';
+import type { SwitcherItem } from '@/features/NavPanel/switcher/switcherItems';
+import SwitcherMenu from '@/features/NavPanel/switcher/SwitcherMenu';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import type { ProjectDetail } from '@/store/project';
import { useCurrentProjectList, useProjectStore } from '@/store/project';
@@ -20,32 +19,45 @@ interface ProjectHeaderProps {
}
const ProjectHeader = memo<ProjectHeaderProps>(({ project }) => {
- const { t } = useTranslation('project');
+ const { t } = useTranslation(['project', 'common']);
const navigate = useWorkspaceAwareNavigate();
const projects = useCurrentProjectList();
- useProjectStore((s) => s.useFetchProjectList)(true);
-
- const handleSelect = (projectId: string) => navigate(`/project/${projectId}`);
-
- const content = (
- <Flexbox gap={4} padding={8} style={{ maxHeight: '50vh', overflowY: 'auto' }}>
- {projects.map((item) => (
- <NavItem
- active={item.id === project?.id}
- icon={item.avatar || SquareKanbanIcon}
- key={item.id}
- title={item.name}
- onClick={() => handleSelect(item.id)}
- />
- ))}
- </Flexbox>
+ const { error, isLoading, mutate } = useProjectStore((s) => s.useFetchProjectList)(true);
+
+ const items = useMemo<SwitcherItem[]>(
+ () =>
+ projects.map((item) => ({
+ avatar: item.avatar || item.name,
+ id: item.id,
+ private: item.visibility === 'private',
+ title: item.name,
+ })),
+ [projects],
+ );
+
+ const handleSelect = useCallback(
+ (projectId: string) => navigate(`/project/${projectId}`),
+ [navigate],
);
return (
<SideBarHeaderLayout
backTo="/"
left={
- <SidebarHeaderSelectPopover content={content}>
+ <SidebarHeaderSelectPopover
+ content={
+ <SwitcherMenu
+ activeId={project?.id}
+ error={error}
+ isLoading={isLoading && items.length === 0}
+ items={items}
+ kind={'project'}
+ searchPlaceholder={t('navPanel.searchProject', { ns: 'common' })}
+ onRetry={() => mutate()}
+ onSelect={handleSelect}
+ />
+ }
+ >
<SidebarHeaderSelectTrigger
avatar={project?.avatar || project?.name || t('sidebar.title')}
title={project?.name || t('sidebar.title')}