🤯 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
🐛 fix: persist home sidebar collapse state (#14473)
YuTengjing58cda8a64583
diff --git a/src/routes/(main)/home/_layout/Body/index.test.tsx b/src/routes/(main)/home/_layout/Body/index.test.tsxnew file mode 100644index 00000000000..c1b6fb17bff--- /dev/null+++ b/src/routes/(main)/home/_layout/Body/index.test.tsx@@ -0,0 +1,124 @@+import { cleanup, fireEvent, render, screen } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import Body from './index';++interface MockGlobalState {+ status: {+ hiddenSidebarSections?: string[];+ sidebarExpandedKeys?: string[];+ sidebarItems?: string[];+ };+ updateSystemStatus: (patch: Partial<MockGlobalState['status']>) => void;+}++const mocks = vi.hoisted(() => ({+ globalState: undefined as unknown as MockGlobalState,+ updateSystemStatus: vi.fn(),+}));++vi.mock('@lobehub/ui', () => ({+ Accordion: ({+ children,+ expandedKeys,+ onExpandedChange,+ }: {+ children: React.ReactNode;+ expandedKeys?: string[];+ onExpandedChange?: (keys: string[]) => void;+ }) => (+ <div data-expanded-keys={JSON.stringify(expandedKeys)} data-testid="sidebar-accordion">+ <button aria-label="collapse recents" onClick={() => onExpandedChange?.(['agent'])} />+ {children}+ </div>+ ),+ ActionIcon: () => <span />,+ DropdownMenu: ({ children }: { children: React.ReactNode }) => <>{children}</>,+ Flexbox: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,+ Icon: () => <span />,+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock('react-router-dom', () => ({+ Link: ({ children, to }: { children: React.ReactNode; to: string }) => (+ <a href={to}>{children}</a>+ ),+ useNavigate: () => vi.fn(),+}));++vi.mock('@/features/NavPanel/components/NavItem', () => ({+ default: ({ title }: { title: string }) => <div>{title}</div>,+}));++vi.mock('@/hooks/useActiveTabKey', () => ({+ useActiveTabKey: () => 'home',+}));++vi.mock('@/hooks/useNavLayout', () => ({+ useNavLayout: () => ({ bottomMenuItems: [], topNavItems: [] }),+}));++vi.mock('@/utils/navigation', () => ({+ isModifierClick: () => false,+}));++vi.mock('@/utils/router', () => ({+ prefetchRoute: vi.fn(),+}));++vi.mock('@/routes/(main)/home/features/Recents', () => ({+ default: ({ itemKey }: { itemKey: string }) => <div data-testid={`sidebar-item-${itemKey}`} />,+}));++vi.mock('./Agent', () => ({+ default: ({ itemKey }: { itemKey: string }) => <div data-testid={`sidebar-item-${itemKey}`} />,+}));++vi.mock('./CustomizeSidebarModal', () => ({+ CustomizeSidebarModal: () => null,+ openCustomizeSidebarModal: vi.fn(),+}));++vi.mock('@/store/global', () => ({+ useGlobalStore: (selector: (state: MockGlobalState) => unknown) => selector(mocks.globalState),+}));++beforeEach(() => {+ mocks.updateSystemStatus.mockReset();+ mocks.globalState = {+ status: {+ hiddenSidebarSections: [],+ sidebarExpandedKeys: ['recents', 'agent'],+ sidebarItems: ['recents', 'agent'],+ },+ updateSystemStatus: mocks.updateSystemStatus,+ };+});++afterEach(() => {+ cleanup();+});++describe('Home sidebar body', () => {+ it('uses persisted sidebar accordion expanded keys', () => {+ mocks.globalState.status.sidebarExpandedKeys = ['agent'];++ render(<Body />);++ expect(screen.getByTestId('sidebar-accordion')).toHaveAttribute(+ 'data-expanded-keys',+ '["agent"]',+ );+ });++ it('persists sidebar accordion expanded changes', () => {+ render(<Body />);++ fireEvent.click(screen.getByRole('button', { name: 'collapse recents' }));++ expect(mocks.updateSystemStatus).toHaveBeenCalledWith({ sidebarExpandedKeys: ['agent'] });+ });+});diff --git a/src/routes/(main)/home/_layout/Body/index.tsx b/src/routes/(main)/home/_layout/Body/index.tsxindex 93a17ae027f..6762a40bdec 100644--- a/src/routes/(main)/home/_layout/Body/index.tsx+++ b/src/routes/(main)/home/_layout/Body/index.tsx@@ -1,14 +1,17 @@'use client';-import { Accordion, ActionIcon, DropdownMenu, Flexbox, Icon, type MenuProps } from '@lobehub/ui';+import type { MenuProps } from '@lobehub/ui';+import { Accordion, ActionIcon, DropdownMenu, Flexbox, Icon } from '@lobehub/ui';import { EyeOffIcon, MoreHorizontalIcon, SlidersHorizontalIcon } from 'lucide-react';-import { memo, type ReactElement, useCallback, useMemo } from 'react';+import type { Key, ReactElement } from 'react';+import { memo, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { Link, useNavigate } from 'react-router-dom';import NavItem from '@/features/NavPanel/components/NavItem';import { useActiveTabKey } from '@/hooks/useActiveTabKey';-import { type NavItem as NavItemType, useNavLayout } from '@/hooks/useNavLayout';+import type { NavItem as NavItemType } from '@/hooks/useNavLayout';+import { useNavLayout } from '@/hooks/useNavLayout';import Recents from '@/routes/(main)/home/features/Recents';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';@@ -38,12 +41,29 @@ const accordionComponents: Record<string, (key: string) => ReactElement> = {[GroupKey.Recents]: (key) => <Recents itemKey={key} key={key} />,};+const mergeSidebarExpandedKeys = (+ currentKeys: string[],+ accordionKeys: string[],+ expandedKeys: Key[],+): string[] => {+ const nextExpandedKeys = new Set(expandedKeys.map(String));+ const accordionKeySet = new Set(accordionKeys);+ const nextKeys = currentKeys.filter((key) => !accordionKeySet.has(key));++ for (const key of accordionKeys) {+ if (nextExpandedKeys.has(key)) nextKeys.push(key);+ }++ return nextKeys;+};+const Body = memo(() => {const { t } = useTranslation('common');const tab = useActiveTabKey();const navigate = useNavigate();const { topNavItems, bottomMenuItems } = useNavLayout();const sidebarItems = useGlobalStore(systemStatusSelectors.sidebarItems);+ const sidebarExpandedKeys = useGlobalStore(systemStatusSelectors.sidebarExpandedKeys);const hiddenSections = useGlobalStore(systemStatusSelectors.hiddenSidebarSections);const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);@@ -124,21 +144,37 @@ const Body = memo(() => {[navLinkItems, tab, getContextMenuItems, navigate],);+ const handleAccordionExpandedChange = useCallback(+ (accordionKeys: string[], expandedKeys: Key[]) => {+ updateSystemStatus({+ sidebarExpandedKeys: mergeSidebarExpandedKeys(+ sidebarExpandedKeys,+ accordionKeys,+ expandedKeys,+ ),+ });+ },+ [sidebarExpandedKeys, updateSystemStatus],+ );+// Render the flat list: group consecutive accordion items into an Accordion,// interleave non-accordion keys as nav links.const content = useMemo(() => {const elements: ReactElement[] = [];- let accGroup: ReactElement[] = [];+ let accGroup: { element: ReactElement; key: string }[] = [];const flushAccordion = () => {if (accGroup.length > 0) {+ const accordionKeys = accGroup.map((item) => item.key);+elements.push(<Accordion- defaultExpandedKeys={[GroupKey.Recents, GroupKey.Project, GroupKey.Agent]}+ expandedKeys={sidebarExpandedKeys}gap={8}key={`acc-${elements.length}`}+ onExpandedChange={(keys) => handleAccordionExpandedChange(accordionKeys, keys)}>- {accGroup}+ {accGroup.map((item) => item.element)}</Accordion>,);accGroup = [];@@ -148,7 +184,7 @@ const Body = memo(() => {for (const key of visibleKeys) {if (ACCORDION_KEYS.has(key)) {const comp = accordionComponents[key]?.(key);- if (comp) accGroup.push(comp);+ if (comp) accGroup.push({ element: comp, key });} else {flushAccordion();const link = renderNavLink(key);@@ -157,7 +193,7 @@ const Body = memo(() => {}flushAccordion();return elements;- }, [visibleKeys, renderNavLink]);+ }, [visibleKeys, renderNavLink, sidebarExpandedKeys, handleAccordionExpandedChange]);return (<Flexbox flex={1} gap={4} paddingInline={4}>diff --git a/src/store/global/actions/general.ts b/src/store/global/actions/general.tsindex f0c13b34788..0aaafff631d 100644--- a/src/store/global/actions/general.ts+++ b/src/store/global/actions/general.ts@@ -1,6 +1,6 @@import isEqual from 'fast-deep-equal';import { gt, parse, valid } from 'semver';-import { type SWRResponse } from 'swr';+import type { SWRResponse } from 'swr';import { SESSION_CHAT_TOPIC_URL } from '@/const/url';import { CURRENT_VERSION, isDesktop } from '@/const/version';@@ -8,15 +8,16 @@ import { useOnlyFetchOnceSWR } from '@/libs/swr';import { globalService } from '@/services/global';import { getElectronStoreState } from '@/store/electron';import { electronSyncSelectors } from '@/store/electron/selectors';-import { type SystemStatus } from '@/store/global/initialState';-import { type StoreSetter } from '@/store/types';-import { type LocaleMode } from '@/types/locale';+import type { SystemStatus } from '@/store/global/initialState';+import { DEFAULT_HOME_SIDEBAR_EXPANDED_KEYS } from '@/store/global/initialState';+import type { StoreSetter } from '@/store/types';+import type { LocaleMode } from '@/types/locale';import { switchLang } from '@/utils/client/switchLang';import { merge } from '@/utils/merge';import { setNamespace } from '@/utils/storeDebug';import { DEFAULT_HIDDEN_SECTIONS, DEFAULT_SIDEBAR_ITEMS } from '../selectors/systemStatus';-import { type GlobalStore } from '../store';+import type { GlobalStore } from '../store';const n = setNamespace('g');@@ -164,7 +165,11 @@ export class GlobalGeneralActionImpl {resetSidebarCustomization = (): void => {this.#get().updateSystemStatus(- { hiddenSidebarSections: DEFAULT_HIDDEN_SECTIONS, sidebarItems: DEFAULT_SIDEBAR_ITEMS },+ {+ hiddenSidebarSections: DEFAULT_HIDDEN_SECTIONS,+ sidebarExpandedKeys: DEFAULT_HOME_SIDEBAR_EXPANDED_KEYS,+ sidebarItems: DEFAULT_SIDEBAR_ITEMS,+ },n('resetSidebarCustomization'),);};diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.tsindex a98b5684c62..0dbcf634b4c 100644--- a/src/store/global/initialState.ts+++ b/src/store/global/initialState.ts@@ -102,6 +102,8 @@ export const DEFAULT_MODEL_DETAIL_PANEL_EXPANDED_KEYS = ['config',] as const satisfies readonly ModelDetailPanelExpandedKey[];+export const DEFAULT_HOME_SIDEBAR_EXPANDED_KEYS = ['recents', 'agent'];+export interface SystemStatus {/*** Agent Builder panel width@@ -223,6 +225,7 @@ export interface SystemStatus {/*** Flat ordered list of sidebar items.*/+ sidebarExpandedKeys?: string[];sidebarItems?: string[];/*** Legacy accordion-only ordering (recents/agent) from the pre-rework sidebar.@@ -369,6 +372,7 @@ export const INITIAL_STATUS = {showTaskAgentPanel: false,showVideoPanel: true,showVideoTopicPanel: true,+ sidebarExpandedKeys: [...DEFAULT_HOME_SIDEBAR_EXPANDED_KEYS],systemRoleExpandedMap: {},tokenDisplayFormatShort: true,topicPageSize: 20,diff --git a/src/store/global/selectors/systemStatus.test.ts b/src/store/global/selectors/systemStatus.test.tsindex 3307330d319..bb3b2763ef1 100644--- a/src/store/global/selectors/systemStatus.test.ts+++ b/src/store/global/selectors/systemStatus.test.ts@@ -4,6 +4,7 @@ import { merge } from '@/utils/merge';import type { GlobalState } from '../initialState';import {+ DEFAULT_HOME_SIDEBAR_EXPANDED_KEYS,DEFAULT_MODEL_DETAIL_PANEL_EXPANDED_KEYS,INITIAL_STATUS,initialState,@@ -193,6 +194,30 @@ describe('systemStatusSelectors', () => {});});+ describe('sidebarExpandedKeys', () => {+ it('should expand sidebar accordion sections by default', () => {+ const s: GlobalState = {+ ...initialState,+ status: {+ ...initialState.status,+ sidebarExpandedKeys: undefined,+ },+ };++ expect(systemStatusSelectors.sidebarExpandedKeys(s)).toEqual(+ DEFAULT_HOME_SIDEBAR_EXPANDED_KEYS,+ );+ });++ it('should preserve an empty stored preference when all sections are collapsed', () => {+ const s: GlobalState = merge(initialState, {+ status: { sidebarExpandedKeys: [] },+ });++ expect(systemStatusSelectors.sidebarExpandedKeys(s)).toEqual([]);+ });+ });+describe('reorderSidebarItems', () => {const DEFAULT = ['pages', 'recents', 'agent', 'community', 'resource', 'memory'];diff --git a/src/store/global/selectors/systemStatus.ts b/src/store/global/selectors/systemStatus.tsindex b232c9f063b..07e58fdcbe6 100644--- a/src/store/global/selectors/systemStatus.ts+++ b/src/store/global/selectors/systemStatus.ts@@ -1,5 +1,9 @@import type { GlobalState, ModelDetailPanelExpandedKey } from '../initialState';-import { DEFAULT_MODEL_DETAIL_PANEL_EXPANDED_KEYS, INITIAL_STATUS } from '../initialState';+import {+ DEFAULT_HOME_SIDEBAR_EXPANDED_KEYS,+ DEFAULT_MODEL_DETAIL_PANEL_EXPANDED_KEYS,+ INITIAL_STATUS,+} from '../initialState';export const systemStatus = (s: GlobalState) => s.status;@@ -43,6 +47,9 @@ export const DEFAULT_HIDDEN_SECTIONS: string[] = ['memory'];const hiddenSidebarSections = (s: GlobalState): string[] =>s.status.hiddenSidebarSections ?? DEFAULT_HIDDEN_SECTIONS;+const sidebarExpandedKeys = (s: GlobalState): string[] =>+ s.status.sidebarExpandedKeys ?? DEFAULT_HOME_SIDEBAR_EXPANDED_KEYS;+export const DEFAULT_SIDEBAR_ITEMS: string[] = ['tasks','pages',@@ -269,6 +276,7 @@ export const systemStatusSelectors = {taskKanbanHiddenColumns,taskKanbanHiddenPanelCollapsed,taskListViewOptions,+ sidebarExpandedKeys,sidebarItems,sessionGroupKeys,showChatHeader,