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: app ui page

arvinxx78d07c0504d2
diff --git a/src/app/[variants]/(main)/_layout/DesktopAutoOidcOnFirstOpen.tsx b/src/app/[variants]/(main)/_layout/DesktopAutoOidcOnFirstOpen.tsx
new file mode 100644
index 00000000000..ed34caf0a55
--- /dev/null
+++ b/src/app/[variants]/(main)/_layout/DesktopAutoOidcOnFirstOpen.tsx
@@ -0,0 +1,52 @@
+'use client';
+
+import { memo, useEffect } from 'react';
+
+import { useElectronStore } from '@/store/electron';
+import {
+ getDesktopAutoOidcFirstOpenHandled,
+ setDesktopAutoOidcFirstOpenHandled,
+} from '@/utils/electron/autoOidc';
+
+/**
+ * Desktop-only bootstrap: auto invoke OIDC authorization on the very first app open.
+ *
+ * Note: we intentionally keep this outside of `Connection` UI to avoid coupling business flow to UI.
+ */
+const DesktopAutoOidcOnFirstOpen = memo(() => {
+ const [isInitRemoteServerConfig, dataSyncConfig, useDataSyncConfig, connectRemoteServer] =
+ useElectronStore((s) => [
+ s.isInitRemoteServerConfig,
+ s.dataSyncConfig,
+ s.useDataSyncConfig,
+ s.connectRemoteServer,
+ ]);
+
+ // Ensure config is loaded early.
+ useDataSyncConfig();
+
+ useEffect(() => {
+ if (!isInitRemoteServerConfig) return;
+
+ // If already connected or not in cloud mode, don't auto-trigger.
+ if (dataSyncConfig.active) return;
+ if (dataSyncConfig.storageMode !== 'cloud') return;
+
+ if (getDesktopAutoOidcFirstOpenHandled()) return;
+ // If localStorage is unavailable, don't auto-invoke to avoid repeated prompts.
+ if (!setDesktopAutoOidcFirstOpenHandled()) return;
+
+ // This will trigger IPC -> main process -> `shell.openExternal(/oidc/auth...)`.
+ connectRemoteServer({ remoteServerUrl: dataSyncConfig.remoteServerUrl, storageMode: 'cloud' });
+ }, [
+ connectRemoteServer,
+ dataSyncConfig.active,
+ dataSyncConfig.remoteServerUrl,
+ dataSyncConfig.storageMode,
+ isInitRemoteServerConfig,
+ ]);
+
+ return null;
+});
+
+export default DesktopAutoOidcOnFirstOpen;
diff --git a/src/app/[variants]/(main)/_layout/DesktopLayoutContainer.tsx b/src/app/[variants]/(main)/_layout/DesktopLayoutContainer.tsx
new file mode 100644
index 00000000000..06b76198142
--- /dev/null
+++ b/src/app/[variants]/(main)/_layout/DesktopLayoutContainer.tsx
@@ -0,0 +1,45 @@
+import { useTheme } from 'antd-style';
+import { PropsWithChildren, memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { isDesktop } from '@/const/version';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+
+const DesktopLayoutContainer = memo<PropsWithChildren>(({ children }) => {
+ const theme = useTheme();
+ const [expand] = useGlobalStore((s) => [systemStatusSelectors.showLeftPanel(s)]);
+
+ return (
+ <Flexbox
+ height={'100%'}
+ padding={8}
+ style={{
+ overflow: 'hidden',
+ paddingLeft: expand ? 0 : 8,
+ paddingTop: isDesktop ? 0 : 8,
+ position: 'relative',
+ }}
+ width={'100%'}
+ >
+ <Flexbox
+ height={'100%'}
+ style={{
+ background: theme.colorBgContainer,
+ border: `1px solid ${theme.isDarkMode ? theme.colorBorderSecondary : theme.colorBorder}`,
+ borderRadius:
+ // macOS 26's darwin is 25
+ typeof window !== 'undefined' && (window.lobeEnv?.darwinMajorVersion ?? 0) >= 25
+ ? 12
+ : theme.borderRadius,
+ overflow: 'hidden',
+ position: 'relative',
+ }}
+ width={'100%'}
+ >
+ {children}
+ </Flexbox>
+ </Flexbox>
+ );
+});
+export default DesktopLayoutContainer;
diff --git a/src/app/[variants]/(main)/layouts/desktop/RegisterHotkeys.tsx b/src/app/[variants]/(main)/_layout/RegisterHotkeys.tsx
similarity index 100%
rename from src/app/[variants]/(main)/layouts/desktop/RegisterHotkeys.tsx
rename to src/app/[variants]/(main)/_layout/RegisterHotkeys.tsx
diff --git a/src/app/[variants]/(main)/_layout/index.tsx b/src/app/[variants]/(main)/_layout/index.tsx
new file mode 100644
index 00000000000..f1cccce0135
--- /dev/null
+++ b/src/app/[variants]/(main)/_layout/index.tsx
@@ -0,0 +1,80 @@
+'use client';
+
+import { useTheme } from 'antd-style';
+import dynamic from 'next/dynamic';
+import { Suspense, memo } from 'react';
+import { HotkeysProvider } from 'react-hotkeys-hook';
+import { Flexbox } from 'react-layout-kit';
+import { Outlet } from 'react-router-dom';
+
+import { DndContextWrapper } from '@/app/[variants]/(main)/resource/features/DndContextWrapper';
+import Loading from '@/components/Loading/BrandTextLoading';
+import { isDesktop } from '@/const/version';
+import { BANNER_HEIGHT } from '@/features/AlertBanner/CloudBanner';
+import DesktopNavigationBridge from '@/features/DesktopNavigationBridge';
+import TitleBar, { TITLE_BAR_HEIGHT } from '@/features/ElectronTitlebar';
+import HotkeyHelperPanel from '@/features/HotkeyHelperPanel';
+import NavPanel from '@/features/NavPanel';
+import { usePlatform } from '@/hooks/usePlatform';
+import { MarketAuthProvider } from '@/layout/AuthProvider/MarketAuth';
+import CmdkLazy from '@/layout/GlobalProvider/CmdkLazy';
+import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
+import { HotkeyScopeEnum } from '@/types/hotkey';
+
+import DesktopAutoOidcOnFirstOpen from './DesktopAutoOidcOnFirstOpen';
+import DesktopLayoutContainer from './DesktopLayoutContainer';
+import RegisterHotkeys from './RegisterHotkeys';
+
+const CloudBanner = dynamic(() => import('@/features/AlertBanner/CloudBanner'));
+
+const Layout = memo(() => {
+ const { isPWA } = usePlatform();
+ const theme = useTheme();
+ const { showCloudPromotion } = useServerConfigStore(featureFlagsSelectors);
+
+ return (
+ <HotkeysProvider initiallyActiveScopes={[HotkeyScopeEnum.Global]}>
+ <Suspense fallback={null}>
+ {isDesktop && <TitleBar />}
+ {isDesktop && <DesktopAutoOidcOnFirstOpen />}
+ {isDesktop && <DesktopNavigationBridge />}
+ {showCloudPromotion && <CloudBanner />}
+ </Suspense>
+ <DndContextWrapper>
+ <Flexbox
+ height={
+ isDesktop
+ ? `calc(100% - ${TITLE_BAR_HEIGHT}px)`
+ : showCloudPromotion
+ ? `calc(100% - ${BANNER_HEIGHT}px)`
+ : '100%'
+ }
+ horizontal
+ style={{
+ borderTop: isPWA ? `1px solid ${theme.colorBorder}` : undefined,
+ position: 'relative',
+ }}
+ width={'100%'}
+ >
+ <NavPanel />
+ <DesktopLayoutContainer>
+ <MarketAuthProvider isDesktop={isDesktop}>
+ <Suspense fallback={<Loading debugId="DesktopMainLayout > Outlet" />}>
+ <Outlet />
+ </Suspense>
+ </MarketAuthProvider>
+ </DesktopLayoutContainer>
+ </Flexbox>
+ </DndContextWrapper>
+ <Suspense fallback={null}>
+ <HotkeyHelperPanel />
+ <RegisterHotkeys />
+ <CmdkLazy />
+ </Suspense>
+ </HotkeysProvider>
+ );
+});
+
+Layout.displayName = 'DesktopMainLayout';
+
+export default Layout;
diff --git a/src/app/[variants]/(main)/changelog/_layout/Desktop/Container.tsx b/src/app/[variants]/(main)/changelog/_layout/Desktop/Container.tsx
deleted file mode 100644
index 986db04dc83..00000000000
--- a/src/app/[variants]/(main)/changelog/_layout/Desktop/Container.tsx
+++ /dev/null
@@ -1,35 +0,0 @@
-'use client';
-
-import { useTheme } from 'antd-style';
-import { PropsWithChildren, memo } from 'react';
-import { Flexbox } from 'react-layout-kit';
-
-const Container = memo<PropsWithChildren>(({ children }) => {
- const theme = useTheme();
-
- return (
- <Flexbox
- align={'center'}
- style={{
- background: theme.colorBgContainerSecondary,
- height: '100%',
- overflowX: 'hidden',
- overflowY: 'auto',
- }}
- width={'100%'}
- >
- <Flexbox
- gap={24}
- paddingBlock={24}
- paddingInline={16}
- style={{
- width: 'min(100%, 1024px)',
- }}
- >
- {children}
- </Flexbox>
- </Flexbox>
- );
-});
-
-export default Container;
diff --git a/src/app/[variants]/(main)/changelog/_layout/Desktop/index.tsx b/src/app/[variants]/(main)/changelog/_layout/Desktop/index.tsx
deleted file mode 100644
index 4c3a223ac24..00000000000
--- a/src/app/[variants]/(main)/changelog/_layout/Desktop/index.tsx
+++ /dev/null
@@ -1,20 +0,0 @@
-import { Outlet } from 'react-router-dom';
-
-import { Locales } from '@/locales/resources';
-
-import Hero from '../../features/Hero';
-import Container from './Container';
-
-const Layout = (props: { locale: Locales }) => {
- const { locale } = props;
- return (
- <Container>
- <Hero />
- <Outlet context={{ locale }} />
- </Container>
- );
-};
-
-Layout.displayName = 'DesktopChangelogLayout';
-
-export default Layout;
diff --git a/src/app/[variants]/(main)/changelog/_layout/Mobile/Header.tsx b/src/app/[variants]/(main)/changelog/_layout/Mobile/Header.tsx
deleted file mode 100644
index 14932280caa..00000000000
--- a/src/app/[variants]/(main)/changelog/_layout/Mobile/Header.tsx
+++ /dev/null
@@ -1,33 +0,0 @@
-'use client';
-
-import { ChatHeader } from '@lobehub/ui/mobile';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-import { useNavigate } from 'react-router-dom';
-
-import { mobileHeaderSticky } from '@/styles/mobileHeader';
-
-const Header = memo(() => {
- const { t } = useTranslation('changelog');
-
- const navigate = useNavigate();
- return (
- <ChatHeader
- center={
- <ChatHeader.Title
- title={
- <Flexbox align={'center'} gap={4} horizontal>
- {t('title')}
- </Flexbox>
- }
- />
- }
- onBackClick={() => navigate(-1)}
- showBackButton
- style={mobileHeaderSticky}
- />
- );
-});
-
-export default Header;
diff --git a/src/app/[variants]/(main)/changelog/_layout/Mobile/index.tsx b/src/app/[variants]/(main)/changelog/_layout/Mobile/index.tsx
deleted file mode 100644
index 24ab7799ddd..00000000000
--- a/src/app/[variants]/(main)/changelog/_layout/Mobile/index.tsx
+++ /dev/null
@@ -1,21 +0,0 @@
-import { Outlet } from 'react-router-dom';
-
-import MobileContentLayout from '@/components/server/MobileNavLayout';
-import { Locales } from '@/locales/resources';
-
-import Hero from '../../features/Hero';
-import Header from './Header';
-
-const Layout = (props: { locale: Locales }) => {
- const { locale } = props;
- return (
- <MobileContentLayout header={<Header />} padding={16}>
- <Hero />
- <Outlet context={{ locale }} />
- </MobileContentLayout>
- );
-};
-
-Layout.displayName = 'MobileChangelogLayout';
-
-export default Layout;
diff --git a/src/app/[variants]/(main)/changelog/features/GridLayout.tsx b/src/app/[variants]/(main)/changelog/features/GridLayout.tsx
deleted file mode 100644
index 31c2bd6c1a0..00000000000
--- a/src/app/[variants]/(main)/changelog/features/GridLayout.tsx
+++ /dev/null
@@ -1,22 +0,0 @@
-import { FC, PropsWithChildren, ReactNode } from 'react';
-import { Flexbox } from 'react-layout-kit';
-
-const GridLayout: FC<PropsWithChildren<{ date?: ReactNode; mobile?: boolean }>> = ({
- mobile,
- children,
- date,
-}) => {
- return (
- <Flexbox horizontal={!mobile} wrap={'wrap'}>
- <Flexbox flex={1} style={{ minWidth: 150, position: 'relative' }}>
- {date}
- </Flexbox>
- <Flexbox flex={3} gap={16} style={{ minWidth: 'min(600px, 100%)', position: 'relative' }}>
- {children}
- </Flexbox>
- {!mobile && <Flexbox flex={1} style={{ minWidth: 150, position: 'relative' }} />}
- </Flexbox>
- );
-};
-
-export default GridLayout;
diff --git a/src/app/[variants]/(main)/changelog/features/Hero.tsx b/src/app/[variants]/(main)/changelog/features/Hero.tsx
deleted file mode 100644
index 56fe9f3dd4a..00000000000
--- a/src/app/[variants]/(main)/changelog/features/Hero.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-'use client';
-
-import { useResponsive, useTheme } from 'antd-style';
-import Link from 'next/link';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-import urlJoin from 'url-join';
-
-import { BRANDING_NAME, SOCIAL_URL } from '@/const/branding';
-import { OFFICIAL_SITE } from '@/const/url';
-
-import GridLayout from './GridLayout';
-
-const Hero = memo(() => {
- const { t } = useTranslation('changelog');
- const theme = useTheme();
- const { mobile } = useResponsive();
- return (
- <GridLayout>
- <Flexbox gap={16} style={{ paddingTop: 32, zIndex: 1 }}>
- <h1 style={{ fontSize: mobile ? 28 : 40, fontWeight: 'bold', margin: 0 }}>{t('title')}</h1>
- <div style={{ fontSize: mobile ? 18 : 24, opacity: 0.6 }}>
- {t('description', { appName: BRANDING_NAME })}
- </div>
- <Flexbox gap={8} horizontal style={{ fontSize: 16 }}>
- <Link href={urlJoin(OFFICIAL_SITE, '/changelog/versions')} target={'_blank'}>
- {t('actions.versions')}
- </Link>
- <div style={{ color: theme.colorInfo }}>·</div>
- <Link href={SOCIAL_URL.x} target={'_blank'}>
- {t('actions.followOnX')}
- </Link>
- </Flexbox>
- </Flexbox>
- </GridLayout>
- );
-});
-
-export default Hero;
diff --git a/src/app/[variants]/(main)/changelog/features/Pagination.tsx b/src/app/[variants]/(main)/changelog/features/Pagination.tsx
deleted file mode 100644
index 7568a17ce41..00000000000
--- a/src/app/[variants]/(main)/changelog/features/Pagination.tsx
+++ /dev/null
@@ -1,54 +0,0 @@
-'use client';
-
-import { Icon } from '@lobehub/ui';
-import { createStyles } from 'antd-style';
-import { ChevronRightIcon } from 'lucide-react';
-import Link from 'next/link';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-import urlJoin from 'url-join';
-
-import { OFFICIAL_SITE } from '@/const/url';
-
-const useStyles = createStyles(({ css, token }) => ({
- button: css`
- border: 1px solid ${token.colorBorderSecondary};
- border-radius: ${token.borderRadiusLG}px;
-
- &:hover {
- background: ${token.colorFillTertiary};
- }
- `,
- desc: css`
- color: ${token.colorTextSecondary};
- `,
- title: css`
- font-size: 16px;
- font-weight: 500;
- `,
-}));
-
-const Pagination = memo(() => {
- const { t } = useTranslation('changelog');
- const { styles } = useStyles();
- return (
- <Flexbox gap={16} horizontal style={{ marginTop: 24 }} width={'100%'}>
- <Link
- href={urlJoin(OFFICIAL_SITE, '/changelog/page/2')}
- style={{ color: 'inherit', flex: 1 }}
- target={'_blank'}
- >
- <Flexbox align={'flex-end'} className={styles.button} gap={4} padding={16}>
- <Flexbox align={'center'} className={styles.desc} gap={4} horizontal>
- {t('pagination.next')}
- <Icon icon={ChevronRightIcon} />
- </Flexbox>
- <div className={styles.title}>{t('pagination.older')}</div>
- </Flexbox>
- </Link>
- </Flexbox>
- );
-});
-
-export default Pagination;
diff --git a/src/app/[variants]/(main)/changelog/features/Post.tsx b/src/app/[variants]/(main)/changelog/features/Post.tsx
deleted file mode 100644
index e482645dec9..00000000000
--- a/src/app/[variants]/(main)/changelog/features/Post.tsx
+++ /dev/null
@@ -1,59 +0,0 @@
-import { Typography } from '@lobehub/ui';
-import { Image } from '@lobehub/ui/mdx';
-import { Divider } from 'antd';
-import Link from 'next/link';
-import useSWR from 'swr';
-import urlJoin from 'url-join';
-
-import { CustomMDX } from '@/components/mdx';
-import { OFFICIAL_SITE } from '@/const/url';
-import { Locales } from '@/locales/resources';
-import { ChangelogService } from '@/server/services/changelog';
-import { ChangelogIndexItem } from '@/types/changelog';
-
-import GridLayout from './GridLayout';
-import PublishedTime from './PublishedTime';
-import VersionTag from './VersionTag';
-
-const Post = ({
- id,
- mobile,
- versionRange,
- locale,
-}: ChangelogIndexItem & { branch?: string; locale: Locales; mobile?: boolean }) => {
- const { data } = useSWR([`changelog-post-${id}`, locale], async () => {
- const changelogService = new ChangelogService();
- return await changelogService.getPostById(id, { locale });
- });
-
- if (!data || !data.title) return null;
-
- return (
- <>
- <Divider />
- <GridLayout
- date={
- <PublishedTime
- date={data.date.toISOString()}
- style={{ lineHeight: mobile ? undefined : '60px' }}
- template={'MMMM D, YYYY'}
- />
- }
- mobile={mobile}
- >
- <Typography headerMultiple={mobile ? 0.2 : 0.3}>
- <Link href={urlJoin(OFFICIAL_SITE, '/changelog', id)} style={{ color: 'inherit' }}>
- <h1 id={id}>{data.rawTitle || data.title}</h1>
- </Link>
- <Image alt={data.title} src={data.image} />
- <CustomMDX source={data.content} />
- <Link href={urlJoin(OFFICIAL_SITE, '/changelog', id)} style={{ color: 'inherit' }}>
- <VersionTag range={versionRange} />
- </Link>
- </Typography>
- </GridLayout>
- </>
- );
-};
-
-export default Post;
diff --git a/src/app/[variants]/(main)/changelog/features/PublishedTime.tsx b/src/app/[variants]/(main)/changelog/features/PublishedTime.tsx
deleted file mode 100644
index 76a33664ecc..00000000000
--- a/src/app/[variants]/(main)/changelog/features/PublishedTime.tsx
+++ /dev/null
@@ -1,50 +0,0 @@
-'use client';
-
-import { createStyles } from 'antd-style';
-import dayjs from 'dayjs';
-import 'dayjs/locale/zh.js';
-import { CSSProperties, FC } from 'react';
-import { useTranslation } from 'react-i18next';
-
-const useStyles = createStyles(({ css, token }) => {
- return {
- time: css`
- margin-block: calc(var(--lobe-markdown-margin-multiple) * 1em);
-
- font-size: 14px;
- line-height: var(--lobe-markdown-line-height);
- color: ${token.colorTextSecondary};
- letter-spacing: 0.02em;
- `,
- };
-});
-
-interface PrivacyUpdatedProps {
- className?: string;
- date: string;
- style?: CSSProperties;
- template?: string;
-}
-const PublishedTime: FC<PrivacyUpdatedProps> = ({
- date = new Date().toISOString(),
- style,
- className,
- template = 'dddd, MMMM D YYYY',
-}) => {
- const { i18n } = useTranslation();
- const { styles, cx } = useStyles();
- const time = dayjs(date).locale(i18n.language).format(template);
-
- return (
- <time
- aria-label={'published-date'}
- className={cx(styles.time, className)}
- dateTime={time}
- style={style}
- >
- {time}
- </time>
- );
-};
-
-export default PublishedTime;
diff --git a/src/app/[variants]/(main)/changelog/features/UpdateChangelogStatus.tsx b/src/app/[variants]/(main)/changelog/features/UpdateChangelogStatus.tsx
deleted file mode 100644
index 8a370d88a8d..00000000000
--- a/src/app/[variants]/(main)/changelog/features/UpdateChangelogStatus.tsx
+++ /dev/null
@@ -1,21 +0,0 @@
-'use client';
-
-import { memo, useEffect } from 'react';
-
-import { useGlobalStore } from '@/store/global';
-
-const UpdateChangelogStatus = memo<{ currentId?: string }>(({ currentId }) => {
- const [latestChangelogId, updateSystemStatus] = useGlobalStore((s) => [
- s.status.latestChangelogId,
- s.updateSystemStatus,
- ]);
-
- useEffect(() => {
- if (!currentId || currentId === latestChangelogId) return;
- updateSystemStatus({ latestChangelogId: currentId });
- }, [latestChangelogId, currentId]);
-
- return null;
-});
-
-export default UpdateChangelogStatus;
diff --git a/src/app/[variants]/(main)/changelog/index.tsx b/src/app/[variants]/(main)/changelog/index.tsx
deleted file mode 100644
index 16a74ca0960..00000000000
--- a/src/app/[variants]/(main)/changelog/index.tsx
+++ /dev/null
@@ -1,55 +0,0 @@
-import { Fragment } from 'react';
-import { Flexbox } from 'react-layout-kit';
-import { useOutletContext } from 'react-router-dom';
-import useSWR from 'swr';
-
-import NotFound from '@/components/404';
-import { Locales } from '@/locales/resources';
-import { ChangelogService } from '@/server/services/changelog';
-import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
-
-import GridLayout from './features/GridLayout';
-import Pagination from './features/Pagination';
-import Post from './features/Post';
-import UpdateChangelogStatus from './features/UpdateChangelogStatus';
-
-const Page = (props: { isMobile: boolean }) => {
- const { locale } = useOutletContext<{ locale: Locales }>();
- const { isMobile } = props;
- const { hideDocs } = useServerConfigStore(featureFlagsSelectors);
-
- const { data = [] } = useSWR('changelog-index', async () => {
- const changelogService = new ChangelogService();
- return await changelogService.getChangelogIndex();
- });
-
- if (hideDocs) return <NotFound />;
-
- if (!data) return <NotFound />;
-
- return (
- <>
- <Flexbox gap={isMobile ? 16 : 48}>
- {data?.map((item) => (
- <Fragment key={item.id}>
- <Post locale={locale} mobile={isMobile} {...item} />
- </Fragment>
- ))}
- </Flexbox>
- <GridLayout>
- <Pagination />
- </GridLayout>
- <UpdateChangelogStatus currentId={data[0]?.id} />
- </>
- );
-};
-
-const DesktopPage = () => {
- return <Page isMobile={false} />;
-};
-
-const MobilePage = () => {
- return <Page isMobile={true} />;
-};
-
-export { DesktopPage, MobilePage };
diff --git a/src/app/[variants]/(main)/changelog/loading.tsx b/src/app/[variants]/(main)/changelog/loading.tsx
deleted file mode 100644
index 14b2f7b8c18..00000000000
--- a/src/app/[variants]/(main)/changelog/loading.tsx
+++ /dev/null
@@ -1,3 +0,0 @@
-import { Skeleton } from 'antd';
-
-export default () => <Skeleton active paragraph={{ rows: 5 }} title={false} />;
diff --git a/src/app/[variants]/(main)/labs/index.tsx b/src/app/[variants]/(main)/labs/index.tsx
deleted file mode 100644
index d10fbb49e5e..00000000000
--- a/src/app/[variants]/(main)/labs/index.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-'use client';
-
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import { useUserStore } from '@/store/user';
-import { labPreferSelectors, preferenceSelectors } from '@/store/user/selectors';
-
-import Hero from './components/Hero';
-import LabCard from './components/LabCard';
-
-interface LabItem {
- checked: boolean;
- cover?: string;
- desc: string;
- key: string;
- title: string;
-}
-
-const LabsPage = memo(() => {
- const { t } = useTranslation('labs');
-
- const [
- isPreferenceInit,
- enableInputMarkdown,
- // enableGroupChat,
- updateLab,
- ] = useUserStore((s) => [
- preferenceSelectors.isPreferenceInit(s),
- labPreferSelectors.enableInputMarkdown(s),
- // labPreferSelectors.enableGroupChat(s),
- s.updateLab,
- ]);
-
- const labItems: LabItem[] = [
- {
- checked: enableInputMarkdown,
- cover: 'https://github.com/user-attachments/assets/0527a966-3d95-46b4-b880-c0f3fca18f02',
- desc: t('features.inputMarkdown.desc'),
- key: 'enableInputMarkdown',
- title: t('features.inputMarkdown.title'),
- },
- // {
- // checked: enableGroupChat,
- // cover: 'https://github.com/user-attachments/assets/72894d24-a96a-4d7c-a823-ff9e6a1a8b6d',
- // desc: t('features.groupChat.desc'),
- // key: 'groupChat',
- // title: t('features.groupChat.title'),
- // },
- ];
-
- return (
- <Flexbox gap={16} padding={8} style={{ alignItems: 'center', width: '100%' }}>
- <Hero />
-
- {labItems.map((item) => (
- <LabCard
- checked={item.checked}
- cover={item.cover}
- desc={item.desc}
- key={item.key}
- loading={!isPreferenceInit}
- onChange={(checked: boolean) => updateLab({ [item.key]: checked })}
- title={item.title}
- />
- ))}
- </Flexbox>
- );
-});
-
-LabsPage.displayName = 'LabsPage';
-
-export default LabsPage;
diff --git a/src/app/[variants]/(main)/layouts/desktop/DesktopLayoutContainer.tsx b/src/app/[variants]/(main)/layouts/desktop/DesktopLayoutContainer.tsx
deleted file mode 100644
index d6f9d5a17b4..00000000000
--- a/src/app/[variants]/(main)/layouts/desktop/DesktopLayoutContainer.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-import { useTheme } from 'antd-style';
-import { PropsWithChildren, Suspense, memo } from 'react';
-import { Flexbox } from 'react-layout-kit';
-
-import SideBar from './SideBar';
-
-const DesktopLayoutContainer = memo<PropsWithChildren>(({ children }) => {
- const theme = useTheme();
-
- return (
- <>
- <Suspense>
- <SideBar />
- </Suspense>
- <Flexbox
- style={{
- background: theme.colorBgLayout,
- borderInlineStart: `1px solid ${theme.colorBorderSecondary}`,
- borderStartStartRadius: 12,
- borderTop: `1px solid ${theme.colorBorderSecondary}`,
- overflow: 'hidden',
- }}
- width={'100%'}
- >
- {children}
- </Flexbox>
- </>
- );
-});
-export default DesktopLayoutContainer;
diff --git a/src/app/[variants]/(main)/layouts/desktop/SideBar/Avatar.test.tsx b/src/app/[variants]/(main)/layouts/desktop/SideBar/Avatar.test.tsx
deleted file mode 100644
index 0fd6318049b..00000000000
--- a/src/app/[variants]/(main)/layouts/desktop/SideBar/Avatar.test.tsx
+++ /dev/null
@@ -1,55 +0,0 @@
-import { act, fireEvent, render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import { useUserStore } from '@/store/user';
-
-import Avatar from './Avatar';
-
-// Mock UserAvatar and UserPanel components
-vi.mock('@/features/User/UserAvatar', () => ({
- default: vi.fn(() => <div>Mocked UserAvatar</div>),
-}));
-
-vi.mock('@/features/User/UserPanel', () => ({
- default: vi.fn(({ children }) => <div>Mocked UserPanel {children}</div>),
-}));
-
-beforeEach(() => {
- vi.clearAllMocks();
-});
-
-describe('Avatar', () => {
- it('should render UserAvatar and UserPanel when hideSettingsMoveGuide is true', () => {
- render(<Avatar />);
-
- expect(screen.getByText('Mocked UserPanel')).toBeInTheDocument();
- expect(screen.getByText('Mocked UserAvatar')).toBeInTheDocument();
- expect(screen.queryByText('userPanel.moveGuide')).not.toBeInTheDocument();
- });
-
- it('should render Tooltip with guide content when hideSettingsMoveGuide is false', () => {
- act(() => {
- useUserStore.getState().updateGuideState({ moveSettingsToAvatar: false });
- });
-
- render(<Avatar />);
-
- expect(screen.getByText('userPanel.moveGuide')).toBeInTheDocument();
- expect(screen.getByText('Mocked UserPanel')).toBeInTheDocument();
- expect(screen.getByText('Mocked UserAvatar')).toBeInTheDocument();
- });
-
- it('should call updateGuideState when close icon is clicked in Tooltip', () => {
- const updateGuideStateMock = vi.fn();
- act(() => {
- useUserStore.getState().updateGuideState({ moveSettingsToAvatar: false });
- useUserStore.setState({ updateGuideState: updateGuideStateMock });
- });
-
- render(<Avatar />);
-
- fireEvent.click(screen.getByRole('close-guide'));
-
- expect(updateGuideStateMock).toHaveBeenCalledWith({ moveSettingsToAvatar: true });
- });
-});
diff --git a/src/app/[variants]/(main)/layouts/desktop/SideBar/Avatar.tsx b/src/app/[variants]/(main)/layouts/desktop/SideBar/Avatar.tsx
deleted file mode 100644
index bc85ec3d69d..00000000000
--- a/src/app/[variants]/(main)/layouts/desktop/SideBar/Avatar.tsx
+++ /dev/null
@@ -1,56 +0,0 @@
-import { ActionIcon } from '@lobehub/ui';
-import { Tooltip } from 'antd';
-import { LucideX } from 'lucide-react';
-import { Suspense, memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import UserAvatar from '@/features/User/UserAvatar';
-import UserPanel from '@/features/User/UserPanel';
-import { useUserStore } from '@/store/user';
-import { preferenceSelectors } from '@/store/user/selectors';
-
-const Avatar = memo(() => {
- const { t } = useTranslation('common');
- const hideSettingsMoveGuide = useUserStore(preferenceSelectors.hideSettingsMoveGuide);
- const updateGuideState = useUserStore((s) => s.updateGuideState);
-
- const content = (
- <Suspense fallback={<UserAvatar />}>
- <UserPanel>
- <UserAvatar clickable />
- </UserPanel>
- </Suspense>
- );
-
- return hideSettingsMoveGuide ? (
- content
- ) : (
- <Tooltip
- color={'blue'}
- open
- placement={'right'}
- prefixCls={'guide'}
- title={
- <Flexbox align={'center'} gap={8} horizontal>
- <div style={{ lineHeight: '22px' }}>{t('userPanel.moveGuide')}</div>
- <ActionIcon
- icon={LucideX}
- onClick={() => {
- updateGuideState({ moveSettingsToAvatar: true });
- }}
- role={'close-guide'}
- size={'small'}
- style={{ color: 'inherit' }}
- />
- </Flexbox>
- }
- >
- {content}
- </Tooltip>
- );
-});
-
-Avatar.displayName = 'Avatar';
-
-export default Avatar;
diff --git a/src/app/[variants]/(main)/layouts/desktop/SideBar/BottomActions.tsx b/src/app/[variants]/(main)/layouts/desktop/SideBar/BottomActions.tsx
deleted file mode 100644
index 188b23a3891..00000000000
--- a/src/app/[variants]/(main)/layouts/desktop/SideBar/BottomActions.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-import { ActionIcon, ActionIconProps } from '@lobehub/ui';
-import { FlaskConical, Github } from 'lucide-react';
-import { memo } from 'react';
-import { Link } from 'react-router-dom';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-
-import { GITHUB } from '@/const/url';
-import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
-
-const ICON_SIZE: ActionIconProps['size'] = {
- blockSize: 36,
- size: 20,
- strokeWidth: 1.5,
-};
-
-const BottomActions = memo(() => {
- const { t } = useTranslation('common');
-
- const { hideGitHub } = useServerConfigStore(featureFlagsSelectors);
-
- return (
- <Flexbox gap={8}>
- {!hideGitHub && (
- <a aria-label={'GitHub'} href={GITHUB} rel="noopener noreferrer" target={'_blank'}>
- <ActionIcon
- icon={Github}
- size={ICON_SIZE}
- title={'GitHub'}
- tooltipProps={{ placement: 'right' }}
- />
- </a>
- )}
- <Link aria-label={t('labs')} to={'/labs'}>
- <ActionIcon
- icon={FlaskConical}
- size={ICON_SIZE}
- title={t('labs')}
- tooltipProps={{ placement: 'right' }}
- />
- </Link>
- </Flexbox>
- );
-});
-
-export default BottomActions;
diff --git a/src/app/[variants]/(main)/layouts/desktop/SideBar/PinList/index.tsx b/src/app/[variants]/(main)/layouts/desktop/SideBar/PinList/index.tsx
deleted file mode 100644
index 5e988da247a..00000000000
--- a/src/app/[variants]/(main)/layouts/desktop/SideBar/PinList/index.tsx
+++ /dev/null
@@ -1,128 +0,0 @@
-import { Avatar, ScrollShadow, Tooltip } from '@lobehub/ui';
-import { Divider } from 'antd';
-import { createStyles } from 'antd-style';
-import isEqual from 'fast-deep-equal';
-import { Flexbox } from 'react-layout-kit';
-import { Link } from 'react-router-dom';
-
-import { SESSION_CHAT_URL } from '@/const/url';
-import { usePinnedAgentState } from '@/hooks/usePinnedAgentState';
-import { useSwitchSession } from '@/hooks/useSwitchSession';
-import { useSessionStore } from '@/store/session';
-import { sessionHelpers } from '@/store/session/helpers';
-import { sessionSelectors } from '@/store/session/selectors';
-import { useUserStore } from '@/store/user';
-import { settingsSelectors } from '@/store/user/selectors';
-import { HotkeyEnum, KeyEnum } from '@/types/hotkey';
-
-const HANDLER_WIDTH = 4;
-
-const useStyles = createStyles(({ css, token }) => ({
- ink: css`
- &::before {
- content: '';
-
- position: absolute;
- inset-block-start: 50%;
- inset-inline: -9px;
- transform: translateY(-50%);
-
- width: 0;
- height: 8px;
- border-start-end-radius: ${HANDLER_WIDTH}px;
- border-end-end-radius: ${HANDLER_WIDTH}px;
-
- opacity: 0;
- background: ${token.colorPrimary};
-
- transition:
- height 150ms ${token.motionEaseInOut},
- width 150ms ${token.motionEaseInOut},
- opacity 200ms ${token.motionEaseInOut};
- }
-
- &:hover {
- &::before {
- width: ${HANDLER_WIDTH}px;
- height: 24px;
- opacity: 1;
- }
- }
- `,
- inkActive: css`
- &::before {
- width: ${HANDLER_WIDTH}px;
- height: 40px;
- opacity: 1;
- }
-
- &:hover {
- &::before {
- width: ${HANDLER_WIDTH}px;
- height: 40px;
- opacity: 1;
- }
- }
- `,
-}));
-
-const PinList = () => {
- const { styles, cx } = useStyles();
- const list = useSessionStore(sessionSelectors.pinnedSessions, isEqual);
- const [activeId] = useSessionStore((s) => [s.activeId]);
- const switchSession = useSwitchSession();
- const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.SwitchAgent));
- const hasList = list.length > 0;
- const [isPinned, { pinAgent }] = usePinnedAgentState();
-
- const switchAgent = (id: string) => {
- switchSession(id);
- pinAgent();
- };
-
- return (
- hasList && (
- <>
- <Divider style={{ marginBottom: 8, marginTop: 4 }} />
- <ScrollShadow height={'100%'} hideScrollBar={true} size={40}>
- <Flexbox gap={12} style={{ padding: '0' }}>
- {list.map((item, index) => (
- <Flexbox key={item.id} style={{ position: 'relative' }}>
- <Tooltip
- hotkey={
- index < 9 ? hotkey.replaceAll(KeyEnum.Number, String(index + 1)) : undefined
- }
- placement={'right'}
- title={sessionHelpers.getTitle(item.meta)}
- >
- <Link
- onClick={(e) => {
- e.preventDefault();
- switchAgent(item.id);
- }}
- to={SESSION_CHAT_URL(item.id)}
- >
- <Flexbox
- className={cx(
- styles.ink,
- isPinned && activeId === item.id ? styles.inkActive : undefined,
- )}
- >
- <Avatar
- avatar={sessionHelpers.getAvatar(item.meta)}
- background={item.meta.backgroundColor}
- size={40}
- />
- </Flexbox>
- </Link>
- </Tooltip>
- </Flexbox>
- ))}
- </Flexbox>
- </ScrollShadow>
- </>
- )
- );
-};
-
-export default PinList;
diff --git a/src/app/[variants]/(main)/layouts/desktop/SideBar/TopActions.test.tsx b/src/app/[variants]/(main)/layouts/desktop/SideBar/TopActions.test.tsx
deleted file mode 100644
index 10fe044d544..00000000000
--- a/src/app/[variants]/(main)/layouts/desktop/SideBar/TopActions.test.tsx
+++ /dev/null
@@ -1,141 +0,0 @@
-import { act, cleanup, fireEvent, render, renderHook, screen } from '@testing-library/react';
-import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
-
-import { DEFAULT_FEATURE_FLAGS, mapFeatureFlagsEnvToState } from '@/config/featureFlags';
-import { useGlobalStore } from '@/store/global';
-import { SidebarTabKey } from '@/store/global/initialState';
-import {
- Provider,
- createServerConfigStore,
- initServerConfigStore,
-} from '@/store/serverConfig/store';
-import { useSessionStore } from '@/store/session';
-
-import TopActions, { TopActionProps } from './TopActions';
-
-beforeAll(() => {
- initServerConfigStore({
- featureFlags: {
- ...mapFeatureFlagsEnvToState(DEFAULT_FEATURE_FLAGS),
- showMarket: true,
- showAiImage: true,
- },
- });
-});
-
-beforeEach(() => {
- vi.clearAllMocks();
-});
-
-afterEach(() => {
- createServerConfigStore().setState({
- featureFlags: {
- ...createServerConfigStore().getState().featureFlags,
- showMarket: true,
- showAiImage: true,
- },
- });
- cleanup();
-});
-
-vi.mock('react-router-dom', () => ({
- useNavigate: vi.fn(() => vi.fn()),
-}));
-
-vi.mock('@lobehub/ui', () => ({
- ActionIcon: vi.fn(({ title, onClick, icon }) => (
- <div data-testid={`action-icon-${icon?.name || 'unknown'}`} onClick={onClick}>
- {title}
- </div>
- )),
- combineKeys: vi.fn((keys) => keys.join('+')),
- KeyMapEnum: { Alt: 'alt', Ctrl: 'ctrl', Shift: 'shift' },
- Hotkey: vi.fn(({ keys = [] }) => <div>{keys}</div>),
-}));
-
-vi.mock('react-i18next', () => ({
- useTranslation: vi.fn(() => ({
- t: vi.fn((key) => key),
- })),
-}));
-
-const renderTopActions = (props: TopActionProps = {}) => {
- render(
- <Provider createStore={createServerConfigStore}>
- <TopActions {...props} />
- </Provider>,
- );
-};
-
-describe('TopActions', () => {
- it('should render Chat, AI Image and Market by default', () => {
- renderTopActions();
-
- expect(screen.getByText('tab.chat')).toBeInTheDocument();
- expect(screen.getByText('tab.aiImage')).toBeInTheDocument();
- expect(screen.getByText('tab.discover')).toBeInTheDocument();
- });
-
- it('should render only Chat icon when `-market` is set', () => {
- act(() => {
- createServerConfigStore().setState({
- featureFlags: {
- ...createServerConfigStore().getState().featureFlags,
- showMarket: false,
- },
- });
- });
-
- renderTopActions();
-
- expect(screen.getByText('tab.chat')).toBeInTheDocument();
- expect(screen.queryByText('tab.discover')).not.toBeInTheDocument();
- });
-
- it('should render File icon when `-knowledge_base` is set', () => {
- act(() => {
- createServerConfigStore().setState({
- featureFlags: {
- ...createServerConfigStore().getState().featureFlags,
- enableKnowledgeBase: false,
- },
- });
- });
-
- renderTopActions();
-
- expect(screen.getByText('tab.chat')).toBeInTheDocument();
- expect(screen.queryByText('tab.files')).not.toBeInTheDocument();
- });
-
- it('should not render AI Image icon when ai_image is disabled', () => {
- act(() => {
- createServerConfigStore().setState({
- featureFlags: {
- ...createServerConfigStore().getState().featureFlags,
- showAiImage: false,
- },
- });
- });
-
- renderTopActions();
-
- expect(screen.getByText('tab.chat')).toBeInTheDocument();
- expect(screen.queryByText('tab.aiImage')).not.toBeInTheDocument();
- });
-
- it('should switch back to previous active session', () => {
- act(() => {
- useSessionStore.setState({ activeId: '1' });
- });
-
- const { result: store } = renderHook(() => useGlobalStore((s) => s));
- const switchBackToChat = vi.spyOn(store.current, 'switchBackToChat');
-
- renderTopActions({ tab: SidebarTabKey.Discover });
- const chatIcon = screen.getByText('tab.chat');
- fireEvent.click(chatIcon);
-
- expect(switchBackToChat).toBeCalledWith('1');
- });
-});
diff --git a/src/app/[variants]/(main)/layouts/desktop/SideBar/TopActions.tsx b/src/app/[variants]/(main)/layouts/desktop/SideBar/TopActions.tsx
deleted file mode 100644
index 2bd939f3f43..00000000000
--- a/src/app/[variants]/(main)/layouts/desktop/SideBar/TopActions.tsx
+++ /dev/null
@@ -1,116 +0,0 @@
-import { ActionIcon, ActionIconProps, Hotkey } from '@lobehub/ui';
-import { Compass, FolderClosed, MessageSquare, Palette } from 'lucide-react';
-import { memo, useMemo, useTransition } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-import { useNavigate } from 'react-router-dom';
-
-import { INBOX_SESSION_ID } from '@/const/session';
-import { SESSION_CHAT_URL } from '@/const/url';
-import { usePinnedAgentState } from '@/hooks/usePinnedAgentState';
-import { useGlobalStore } from '@/store/global';
-import { SidebarTabKey } from '@/store/global/initialState';
-import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
-import { useSessionStore } from '@/store/session';
-import { useUserStore } from '@/store/user';
-import { settingsSelectors } from '@/store/user/selectors';
-import { HotkeyEnum } from '@/types/hotkey';
-
-const ICON_SIZE: ActionIconProps['size'] = {
- blockSize: 40,
- size: 24,
- strokeWidth: 2,
-};
-
-export interface TopActionProps {
- isPinned?: boolean | null;
- tab?: SidebarTabKey;
-}
-
-// TODO Change icons
-const TopActions = memo<TopActionProps>(({ tab, isPinned }) => {
- const { t } = useTranslation('common');
- const navigate = useNavigate();
- const [, startTransition] = useTransition();
- const [, { unpinAgent }] = usePinnedAgentState();
- const [switchBackToChat, isMobile] = useGlobalStore((s) => [s.switchBackToChat, s.isMobile]);
- const { showMarket, enableKnowledgeBase, showAiImage } =
- useServerConfigStore(featureFlagsSelectors);
- const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.NavigateToChat));
- const activeSessionId = useSessionStore((s) => s.activeId);
- const chatHref = useMemo(
- () => SESSION_CHAT_URL(activeSessionId || INBOX_SESSION_ID, isMobile),
- [activeSessionId, isMobile],
- );
-
- const isChatActive = tab === SidebarTabKey.Chat && !isPinned;
- const isKnowledgeActive = tab === SidebarTabKey.Knowledge;
- const isDiscoverActive = tab === SidebarTabKey.Discover;
- const isImageActive = tab === SidebarTabKey.Image;
-
- const handleNavigate = (path: string) => {
- startTransition(() => {
- navigate(path);
- });
- };
-
- return (
- <Flexbox gap={8}>
- <ActionIcon
- active={isChatActive}
- icon={MessageSquare}
- onClick={(e) => {
- if (e.metaKey || e.ctrlKey) {
- window.open(chatHref, '_blank');
- return;
- }
- e.preventDefault();
- startTransition(() => {
- switchBackToChat(activeSessionId);
- unpinAgent();
- });
- }}
- size={ICON_SIZE}
- title={
- <Flexbox align={'center'} gap={8} horizontal justify={'space-between'}>
- <span>{t('tab.chat')}</span>
- <Hotkey inverseTheme keys={hotkey} />
- </Flexbox>
- }
- tooltipProps={{ placement: 'right' }}
- />
- {enableKnowledgeBase && (
- <ActionIcon
- active={isKnowledgeActive}
- icon={FolderClosed}
- onClick={() => handleNavigate('/knowledge')}
- size={ICON_SIZE}
- title={t('tab.knowledgeBase')}
- tooltipProps={{ placement: 'right' }}
- />
- )}
- {showAiImage && (
- <ActionIcon
- active={isImageActive}
- icon={Palette}
- onClick={() => handleNavigate('/image')}
- size={ICON_SIZE}
- title={t('tab.aiImage')}
- tooltipProps={{ placement: 'right' }}
- />
- )}
- {showMarket && (
- <ActionIcon
- active={isDiscoverActive}
- icon={Compass}
- onClick={() => handleNavigate('/discover')}
- size={ICON_SIZE}
- title={t('tab.discover')}
- tooltipProps={{ placement: 'right' }}
- />
- )}
- </Flexbox>
- );
-});
-
-export default TopActions;
diff --git a/src/app/[variants]/(main)/layouts/desktop/SideBar/index.tsx b/src/app/[variants]/(main)/layouts/desktop/SideBar/index.tsx
deleted file mode 100644
index 9e97e1eade3..00000000000
--- a/src/app/[variants]/(main)/layouts/desktop/SideBar/index.tsx
+++ /dev/null
@@ -1,78 +0,0 @@
-'use client';
-
-import { SideNav } from '@lobehub/ui';
-import { useTheme } from 'antd-style';
-import { Suspense, memo } from 'react';
-
-import { isDesktop } from '@/const/version';
-import { useActiveTabKey } from '@/hooks/useActiveTabKey';
-import { useIsSingleMode } from '@/hooks/useIsSingleMode';
-import { usePinnedAgentState } from '@/hooks/usePinnedAgentState';
-import { useGlobalStore } from '@/store/global';
-import { systemStatusSelectors } from '@/store/global/selectors';
-import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
-import { electronStylish } from '@/styles/electron';
-
-import Avatar from './Avatar';
-import BottomActions from './BottomActions';
-import PinList from './PinList';
-import TopActions from './TopActions';
-
-const Top = () => {
- const [isPinned] = usePinnedAgentState();
- const sidebarKey = useActiveTabKey();
-
- return <TopActions isPinned={isPinned} tab={sidebarKey} />;
-};
-
-const Nav = memo(() => {
- const theme = useTheme();
- const isSingleMode = useIsSingleMode();
- const inZenMode = useGlobalStore(systemStatusSelectors.inZenMode);
- const { showPinList } = useServerConfigStore(featureFlagsSelectors);
-
- return (
- !inZenMode &&
- !isSingleMode && (
- <SideNav
- avatar={
- <div className={electronStylish.nodrag}>
- <Avatar />
- </div>
- }
- bottomActions={
- <div className={electronStylish.nodrag}>
- <BottomActions />
- </div>
- }
- className={electronStylish.draggable}
- style={{
- height: '100%',
- zIndex: 100,
- ...(isDesktop
- ? { background: 'transparent', borderInlineEnd: 0, paddingBlockStart: 8 }
- : { background: theme.colorBgLayout }),
- }}
- topActions={
- <Suspense>
- <div
- className={electronStylish.nodrag}
- style={{
- display: 'flex',
- flexDirection: 'column',
- maxHeight: isDesktop ? 'calc(100vh - 180px)' : 'calc(100vh - 150px)',
- }}
- >
- <Top />
- {showPinList && <PinList />}
- </div>
- </Suspense>
- }
- />
- )
- );
-});
-
-Nav.displayName = 'DesktopNav';
-
-export default Nav;
diff --git a/src/app/[variants]/(main)/layouts/desktop/index.tsx b/src/app/[variants]/(main)/layouts/desktop/index.tsx
deleted file mode 100644
index beb3b743201..00000000000
--- a/src/app/[variants]/(main)/layouts/desktop/index.tsx
+++ /dev/null
@@ -1,73 +0,0 @@
-'use client';
-
-import { useTheme } from 'antd-style';
-import dynamic from 'next/dynamic';
-import { Suspense, memo } from 'react';
-import { HotkeysProvider } from 'react-hotkeys-hook';
-import { Flexbox } from 'react-layout-kit';
-import { Outlet } from 'react-router-dom';
-
-import { isDesktop } from '@/const/version';
-import { BANNER_HEIGHT } from '@/features/AlertBanner/CloudBanner';
-import TitleBar, { TITLE_BAR_HEIGHT } from '@/features/ElectronTitlebar';
-import HotkeyHelperPanel from '@/features/HotkeyHelperPanel';
-import { usePlatform } from '@/hooks/usePlatform';
-import { Locales } from '@/locales/resources';
-import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
-import { HotkeyScopeEnum } from '@/types/hotkey';
-
-import DesktopLayoutContainer from './DesktopLayoutContainer';
-import RegisterHotkeys from './RegisterHotkeys';
-import SideBar from './SideBar';
-
-const CloudBanner = dynamic(() => import('@/features/AlertBanner/CloudBanner'));
-
-const Layout = memo((props: { locale: Locales }) => {
- const { locale } = props;
- const { isPWA } = usePlatform();
- const theme = useTheme();
-
- const { showCloudPromotion } = useServerConfigStore(featureFlagsSelectors);
- return (
- <HotkeysProvider initiallyActiveScopes={[HotkeyScopeEnum.Global]}>
- {isDesktop && <TitleBar />}
- {showCloudPromotion && <CloudBanner />}
- <Flexbox
- height={
- isDesktop
- ? `calc(100% - ${TITLE_BAR_HEIGHT}px)`
- : showCloudPromotion
- ? `calc(100% - ${BANNER_HEIGHT}px)`
- : '100%'
- }
- horizontal
- style={{
- borderTop: isPWA ? `1px solid ${theme.colorBorder}` : undefined,
- position: 'relative',
- }}
- width={'100%'}
- >
- {isDesktop ? (
- <DesktopLayoutContainer>
- <Outlet context={{ locale: locale }} />
- </DesktopLayoutContainer>
- ) : (
- <>
- <Suspense>
- <SideBar />
- </Suspense>
- <Outlet context={{ locale: locale }} />
- </>
- )}
- </Flexbox>
- <HotkeyHelperPanel />
- <Suspense>
- <RegisterHotkeys />
- </Suspense>
- </HotkeysProvider>
- );
-});
-
-Layout.displayName = 'DesktopMainLayout';
-
-export default Layout;
diff --git a/src/app/[variants]/(main)/layouts/index.tsx b/src/app/[variants]/(main)/layouts/index.tsx
deleted file mode 100644
index cb193c144f0..00000000000
--- a/src/app/[variants]/(main)/layouts/index.tsx
+++ /dev/null
@@ -1,11 +0,0 @@
-// Re-export desktop and mobile layouts for external use
-export { default as DesktopMainLayout } from './desktop';
-export { default as MobileMainLayout } from './mobile';
-
-// Re-export desktop components
-export { default as DesktopLayoutContainer } from './desktop/DesktopLayoutContainer';
-export { default as DesktopRegisterHotkeys } from './desktop/RegisterHotkeys';
-export { default as DesktopSideBar } from './desktop/SideBar';
-
-// Re-export mobile components
-export { default as MobileNavBar } from './mobile/NavBar';
diff --git a/src/app/[variants]/(main)/layouts/mobile/index.tsx b/src/app/[variants]/(main)/layouts/mobile/index.tsx
deleted file mode 100644
index e791a0e44fa..00000000000
--- a/src/app/[variants]/(main)/layouts/mobile/index.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-'use client';
-
-import dynamic from 'next/dynamic';
-import { memo } from 'react';
-import { Outlet, useLocation } from 'react-router-dom';
-
-import { withSuspense } from '@/components/withSuspense';
-import { useShowMobileWorkspace } from '@/hooks/useShowMobileWorkspace';
-import { Locales } from '@/locales/resources';
-import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
-
-import NavBar from './NavBar';
-
-const CloudBanner = dynamic(() => import('@/features/AlertBanner/CloudBanner'));
-const MOBILE_NAV_ROUTES = new Set([
- '/chat',
- '/discover',
- '/discover/assistant',
- '/discover/mcp',
- '/discover/plugin',
- '/discover/model',
- '/discover/provider',
- '/me',
-]);
-
-export const MobileMainLayout = memo((props: { locale: Locales }) => {
- const { locale } = props;
- const showMobileWorkspace = useShowMobileWorkspace();
- const location = useLocation();
- const pathname = location.pathname;
- const showNav = !showMobileWorkspace && MOBILE_NAV_ROUTES.has(pathname);
-
- const { showCloudPromotion } = useServerConfigStore(featureFlagsSelectors);
-
- return (
- <>
- {showCloudPromotion && <CloudBanner mobile />}
- <Outlet context={{ locale: locale }} />
- {showNav && <NavBar />}
- </>
- );
-});
-
-MobileMainLayout.displayName = 'MobileMainLayout';
-
-export default withSuspense(MobileMainLayout);
diff --git a/src/app/[variants]/(main)/memory/(home)/features/RoleTagCloud/TagCloudCanvas.tsx b/src/app/[variants]/(main)/memory/(home)/features/RoleTagCloud/TagCloudCanvas.tsx
new file mode 100644
index 00000000000..972862a3d79
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/(home)/features/RoleTagCloud/TagCloudCanvas.tsx
@@ -0,0 +1,492 @@
+import { Billboard, Html, OrbitControls, Text } from '@react-three/drei';
+import { Canvas, useFrame } from '@react-three/fiber';
+import { useTheme } from 'antd-style';
+import { Suspense, memo, useEffect, useMemo, useRef, useState } from 'react';
+import * as THREE from 'three';
+
+import { QueryTagsResult } from '@/database/models/userMemory';
+import UserAvatar from '@/features/User/UserAvatar';
+
+// 配置常量
+const CONFIG = {
+ // 连接线数量系数 (实际数量 = 标签数 * 系数)
+ CONNECTION_RATIO: 0.8,
+ // 最大连接线数量
+ MAX_CONNECTIONS: 40,
+
+ MAX_DURATION: 8,
+
+ // 连接线生命周期范围(秒)
+ MIN_DURATION: 2,
+ // 流动粒子数量(每条线)
+ PARTICLES_PER_LINE: 3,
+ // 新连接线生成概率(每次检查)
+ SPAWN_PROBABILITY: 0.3,
+ // 检查间隔(秒)
+ UPDATE_INTERVAL: 0.1,
+} as const;
+
+interface WordProps {
+ position: THREE.Vector3;
+ size: number;
+ text: string;
+}
+
+const Word = memo<WordProps>(
+ ({ position, text, size }) => {
+ const theme = useTheme();
+ const ref = useRef<any>(null);
+ const [hovered, setHovered] = useState(false);
+
+ const fontProps = {
+ 'fontSize': size * 0.6,
+ 'fontWeight': 600,
+ 'letterSpacing': -0.05,
+ 'lineHeight': 1,
+ 'material-toneMapped': false,
+ };
+
+ useEffect(() => {
+ if (hovered) document.body.style.cursor = 'pointer';
+ return () => {
+ document.body.style.cursor = 'auto';
+ };
+ }, [hovered]);
+
+ useFrame(() => {
+ if (ref.current) {
+ const targetColor = hovered ? theme.colorInfo : theme.colorText;
+ ref.current.material.color.lerp(new THREE.Color(targetColor), 0.1);
+ }
+ });
+
+ return (
+ <Billboard position={position}>
+ <Text
+ onPointerOut={() => setHovered(false)}
+ onPointerOver={(e) => {
+ e.stopPropagation();
+ setHovered(true);
+ }}
+ ref={ref}
+ {...fontProps}
+ >
+ {text}
+ </Text>
+ </Billboard>
+ );
+ },
+ (prevProps, nextProps) => {
+ // 只在 position、text、size 改变时才重新渲染
+ return (
+ prevProps.position === nextProps.position &&
+ prevProps.text === nextProps.text &&
+ prevProps.size === nextProps.size
+ );
+ },
+);
+
+interface ParticleProps {
+ end: THREE.Vector3;
+ index: number;
+ start: THREE.Vector3;
+}
+
+// 流动的光点粒子
+const FlowingParticle = memo<ParticleProps>(
+ ({ start, end, index }) => {
+ const theme = useTheme();
+ const ref = useRef<THREE.Mesh>(null);
+ const offset = useMemo(() => Math.random() * Math.PI * 2, []);
+
+ useFrame((state) => {
+ if (ref.current) {
+ const time = state.clock.getElapsedTime();
+ const speed = 0.5 + index * 0.1;
+ const progress = ((time * speed + offset) % (Math.PI * 2)) / (Math.PI * 2);
+
+ // 沿着线条移动
+ ref.current.position.lerpVectors(start, end, progress);
+
+ // 脉冲效果
+ const pulse = Math.sin(time * 3 + offset) * 0.5 + 1;
+ ref.current.scale.setScalar(pulse * 0.3);
+
+ // 渐变透明度(两端透明,中间明亮)
+ const alpha = Math.sin(progress * Math.PI) * 0.8;
+ if (ref.current.material instanceof THREE.MeshBasicMaterial) {
+ ref.current.material.opacity = alpha;
+ }
+ }
+ });
+
+ return (
+ <mesh ref={ref}>
+ <sphereGeometry args={[0.15, 8, 8]} />
+ <meshBasicMaterial color={theme.colorInfo} opacity={0.8} transparent />
+ </mesh>
+ );
+ },
+ (prevProps, nextProps) => {
+ // 只在 start、end 引用改变时才重新渲染
+ return (
+ prevProps.start === nextProps.start &&
+ prevProps.end === nextProps.end &&
+ prevProps.index === nextProps.index
+ );
+ },
+);
+
+interface ConnectionLineProps {
+ birthTime: number;
+ duration: number;
+ end: THREE.Vector3;
+ index: number;
+ start: THREE.Vector3;
+}
+
+const ConnectionLine = memo<ConnectionLineProps>(
+ ({ start, end, index, birthTime, duration }) => {
+ const theme = useTheme();
+ const lineRef = useRef<THREE.Line>(null);
+ const glowRef = useRef<THREE.Line>(null);
+
+ // 为每条线生成独特的相位偏移
+ const phaseOffset = useMemo(() => Math.random() * Math.PI * 2, []);
+
+ useFrame((state) => {
+ const time = state.clock.getElapsedTime();
+
+ // 在内部计算 lifeProgress
+ const elapsed = time - birthTime;
+ const lifeProgress = Math.min(Math.max(elapsed / duration, 0), 1);
+
+ if (lineRef.current) {
+ // 淡入淡出效果:基于生命周期进度
+ let lifeCycleOpacity = 1;
+ if (lifeProgress < 0.15) {
+ // 淡入阶段 (0-15%)
+ lifeCycleOpacity = lifeProgress / 0.15;
+ } else if (lifeProgress > 0.85) {
+ // 淡出阶段 (85%-100%)
+ lifeCycleOpacity = (1 - lifeProgress) / 0.15;
+ }
+
+ // 主线条:波动透明度 * 生命周期透明度
+ const baseOpacity = (Math.sin(time * 1.5 + phaseOffset) * 0.2 + 0.4) * lifeCycleOpacity;
+ (lineRef.current.material as THREE.LineBasicMaterial).opacity = baseOpacity;
+ }
+
+ if (glowRef.current) {
+ // 光晕效果
+ let lifeCycleOpacity = 1;
+ const elapsed = time - birthTime;
+ const lifeProgress = Math.min(Math.max(elapsed / duration, 0), 1);
+
+ if (lifeProgress < 0.15) {
+ lifeCycleOpacity = lifeProgress / 0.15;
+ } else if (lifeProgress > 0.85) {
+ lifeCycleOpacity = (1 - lifeProgress) / 0.15;
+ }
+
+ const glowOpacity = (Math.sin(time * 0.8 + phaseOffset) * 0.1 + 0.15) * lifeCycleOpacity;
+ (glowRef.current.material as THREE.LineBasicMaterial).opacity = glowOpacity;
+ }
+ });
+
+ // 创建渐变色线条
+ const { mainLine, glowLine } = useMemo(() => {
+ const points = [start, end];
+ const geom = new THREE.BufferGeometry().setFromPoints(points);
+
+ // 创建颜色渐变
+ const colorArray = new Float32Array(6); // 2 points * 3 (RGB)
+ const color1 = new THREE.Color(theme.colorPrimary);
+ const color2 = new THREE.Color(theme.colorInfo);
+
+ colorArray[0] = color1.r;
+ colorArray[1] = color1.g;
+ colorArray[2] = color1.b;
+ colorArray[3] = color2.r;
+ colorArray[4] = color2.g;
+ colorArray[5] = color2.b;
+
+ geom.setAttribute('color', new THREE.BufferAttribute(colorArray, 3));
+
+ // 创建主线条
+ const mainMaterial = new THREE.LineBasicMaterial({
+ color: theme.colorPrimary,
+ opacity: 0.4,
+ transparent: true,
+ vertexColors: true,
+ });
+ const main = new THREE.Line(geom, mainMaterial);
+
+ // 创建光晕线条
+ const glowMaterial = new THREE.LineBasicMaterial({
+ blending: THREE.AdditiveBlending,
+ color: theme.colorInfo,
+ opacity: 0.15,
+ transparent: true,
+ });
+ const glow = new THREE.Line(geom.clone(), glowMaterial);
+
+ return { geometry: geom, glowLine: glow, mainLine: main };
+ }, [start, end, theme.colorPrimary, theme.colorInfo]);
+
+ // 生成流动粒子
+ const particles = useMemo(() => {
+ return Array.from({ length: CONFIG.PARTICLES_PER_LINE }, (_, i) => (
+ <FlowingParticle end={end} index={i} key={`particle-${index}-${i}`} start={start} />
+ ));
+ }, [start, end, index]);
+
+ return (
+ <group>
+ {/* 主线条 */}
+ <primitive object={mainLine} ref={lineRef} />
+
+ {/* 光晕层 - 更粗更透明 */}
+ <primitive object={glowLine} ref={glowRef} />
+
+ {/* 流动粒子 */}
+ {particles}
+ </group>
+ );
+ },
+ (prevProps, nextProps) => {
+ // 只在 start、end 引用改变时才重新渲染
+ // birthTime 和 duration 对于同一个连接应该是不变的
+ return (
+ prevProps.start === nextProps.start &&
+ prevProps.end === nextProps.end &&
+ prevProps.birthTime === nextProps.birthTime &&
+ prevProps.duration === nextProps.duration
+ );
+ },
+);
+
+// 中心头像组件
+const CenterAvatar = memo(() => {
+ return (
+ <Html
+ center
+ position={[0, 0, 0]}
+ style={{
+ pointerEvents: 'none',
+ }}
+ >
+ <UserAvatar shape="circle" size={80} />
+ </Html>
+ );
+});
+
+interface CloudProps {
+ radius?: number;
+ tags: QueryTagsResult[];
+}
+
+const Cloud = memo<CloudProps>(({ tags, radius = 20 }) => {
+ const groupRef = useRef<THREE.Group>(null);
+
+ // 计算标签位置和大小
+ const wordsData = useMemo(() => {
+ if (!tags.length) return [];
+
+ const maxCount = Math.max(...tags.map((t) => t.count));
+ const minCount = Math.min(...tags.map((t) => t.count));
+ const countRange = maxCount - minCount || 1;
+
+ const spherical = new THREE.Spherical();
+ const data = tags.map((tag, i) => {
+ // 使用黄金角螺旋分布算法,使标签在球面上均匀分布
+ const phi = Math.acos(1 - (2 * (i + 0.5)) / tags.length);
+ const theta = Math.PI * (1 + Math.sqrt(5)) * i;
+
+ const position = new THREE.Vector3().setFromSpherical(spherical.set(radius, phi, theta));
+
+ // 根据 count 计算字体大小 (范围: 1.5 - 4)
+ const normalizedCount = (tag.count - minCount) / countRange;
+ const size = 1.5 + normalizedCount * 2.5;
+
+ return {
+ position,
+ size,
+ text: tag.tag,
+ };
+ });
+
+ return data;
+ }, [tags, radius]);
+
+ // 连接线数量
+ const connectionCount = useMemo(() => {
+ if (wordsData.length < 2) return 0;
+ return Math.min(Math.floor(wordsData.length * CONFIG.CONNECTION_RATIO), CONFIG.MAX_CONNECTIONS);
+ }, [wordsData.length]);
+
+ // 动态连接线状态
+ interface ConnectionState {
+ birthTime: number;
+ duration: number;
+ end: THREE.Vector3;
+ id: string;
+ start: THREE.Vector3;
+ }
+
+ const [connections, setConnections] = useState<ConnectionState[]>([]);
+ const lastUpdateTime = useRef(0);
+ const isInitialized = useRef(false);
+ const currentTime = useRef(0);
+ const connectionIdCounter = useRef(0);
+
+ // 生成一个随机连接
+ const generateRandomConnection = useMemo(
+ () => (currentTime: number) => {
+ if (wordsData.length < 2) return null;
+
+ const idx1 = Math.floor(Math.random() * wordsData.length);
+ let idx2 = Math.floor(Math.random() * wordsData.length);
+
+ let attempts = 0;
+ while (idx2 === idx1 && attempts < 50) {
+ idx2 = Math.floor(Math.random() * wordsData.length);
+ attempts++;
+ }
+
+ if (attempts >= 50) return null;
+
+ // 随机持续时间
+ const duration =
+ CONFIG.MIN_DURATION + Math.random() * (CONFIG.MAX_DURATION - CONFIG.MIN_DURATION);
+
+ // 生成唯一 ID
+ connectionIdCounter.current += 1;
+ const id = `conn-${connectionIdCounter.current}`;
+
+ return {
+ birthTime: currentTime,
+ duration,
+ end: wordsData[idx2].position,
+ id,
+ start: wordsData[idx1].position,
+ };
+ },
+ [wordsData],
+ );
+
+ // 当 wordsData 或 connectionCount 变化时重置初始化状态
+ useEffect(() => {
+ isInitialized.current = false;
+ setConnections([]);
+ }, [connectionCount]);
+
+ // 动态更新连接线
+ useFrame((state) => {
+ const time = state.clock.getElapsedTime();
+ currentTime.current = time;
+
+ // 初始化连接线(在第一帧)
+ if (!isInitialized.current && connectionCount > 0) {
+ isInitialized.current = true;
+ const initialConnections: ConnectionState[] = [];
+
+ for (let i = 0; i < connectionCount; i++) {
+ // 给初始连接线随机的起始时间,制造交错效果
+ const connection = generateRandomConnection(time - Math.random() * 2);
+ if (connection) {
+ initialConnections.push(connection);
+ }
+ }
+
+ setConnections(initialConnections);
+ lastUpdateTime.current = time;
+ return;
+ }
+
+ // 定期检查
+ if (time - lastUpdateTime.current > CONFIG.UPDATE_INTERVAL) {
+ lastUpdateTime.current = time;
+
+ setConnections((prev) => {
+ // 过滤掉已经过期的连接
+ const active = prev.filter((conn) => time - conn.birthTime < conn.duration);
+
+ // 如果连接数量不足,随机添加新连接
+ const needed = connectionCount - active.length;
+ if (
+ needed > 0 && // 随机决定这次是否添加新连接
+ Math.random() < CONFIG.SPAWN_PROBABILITY
+ ) {
+ const newConnection = generateRandomConnection(time);
+ if (newConnection) {
+ return [...active, newConnection];
+ }
+ }
+
+ return active;
+ });
+ }
+
+ // 自动旋转动画
+ if (groupRef.current) {
+ groupRef.current.rotation.y += 0.001;
+ groupRef.current.rotation.x += 0.0005;
+ }
+ });
+
+ return (
+ <group ref={groupRef} rotation={[0.3, 0.5, 0.1]}>
+ {/* 中心用户头像 */}
+ <CenterAvatar />
+
+ {/* 渲染连线 */}
+ {connections.map((connection, index) => (
+ <ConnectionLine
+ birthTime={connection.birthTime}
+ duration={connection.duration}
+ end={connection.end}
+ index={index}
+ key={connection.id}
+ start={connection.start}
+ />
+ ))}
+ {/* 渲染标签 */}
+ {wordsData.map((word, index) => (
+ <Word key={`word-${index}`} {...word} />
+ ))}
+ </group>
+ );
+});
+
+interface TagCloudCanvasProps {
+ tags: QueryTagsResult[];
+}
+
+const TagCloudCanvas = memo<TagCloudCanvasProps>(({ tags }) => {
+ const theme = useTheme();
+
+ if (!tags.length) return null;
+ return (
+ <Canvas camera={{ fov: 75, position: [0, 0, 35] }} dpr={[1, 2]}>
+ <color args={[theme.colorBgContainer]} attach="background" />
+ <fog args={[theme.colorBgLayout, 0, 80]} attach="fog" />
+ <ambientLight intensity={0.5} />
+ <pointLight intensity={1} position={[10, 10, 10]} />
+ <Suspense fallback={null}>
+ <Cloud radius={20} tags={tags} />
+ </Suspense>
+ <OrbitControls
+ autoRotate={false}
+ dampingFactor={0.05}
+ enableDamping
+ enablePan={false}
+ maxDistance={50}
+ minDistance={20}
+ rotateSpeed={0.5}
+ />
+ </Canvas>
+ );
+});
+
+export default TagCloudCanvas;
diff --git a/src/app/[variants]/(main)/memory/(home)/features/RoleTagCloud/index.tsx b/src/app/[variants]/(main)/memory/(home)/features/RoleTagCloud/index.tsx
new file mode 100644
index 00000000000..c63a21d930c
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/(home)/features/RoleTagCloud/index.tsx
@@ -0,0 +1,92 @@
+import { ActionIcon, Block } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { MaximizeIcon, MinimizeIcon } from 'lucide-react';
+import dynamic from 'next/dynamic';
+import { memo, useEffect, useState } from 'react';
+
+import Loading from '@/components/Loading/BrandTextLoading';
+import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
+import { QueryTagsResult } from '@/database/models/userMemory';
+
+const TagCloudCanvas = dynamic(() => import('./TagCloudCanvas'), {
+ loading: () => <Loading debugId={'TagCloud'} />,
+ ssr: false,
+});
+
+const useStyles = createStyles(({ css }) => ({
+ fullscreen: css`
+ position: absolute;
+ z-index: 10;
+ inset: 0;
+
+ width: 100%;
+ height: 100%;
+ border-radius: 0;
+ `,
+ fullscreenAnimation: css`
+ opacity: 0;
+ `,
+ icon: css`
+ position: absolute;
+ z-index: 10;
+ inset-block-start: 6px;
+ inset-inline-end: 6px;
+ `,
+ root: css`
+ position: relative;
+ overflow: hidden;
+ width: 100%;
+ height: 480px;
+
+ .fullscreen-icon {
+ opacity: 0;
+ }
+
+ &:hover {
+ .fullscreen-icon {
+ opacity: 1;
+ }
+ }
+ `,
+}));
+
+interface RoleTagCloudProps {
+ tags: QueryTagsResult[];
+}
+
+const RoleTagCloud = memo<RoleTagCloudProps>(({ tags }) => {
+ const [fullscreen, setFullscreen] = useState(false);
+ const [fullscreenAnimation, setFullscreenAnimation] = useState(false);
+ const { cx, styles } = useStyles();
+
+ useEffect(() => {
+ setFullscreenAnimation(true);
+ setTimeout(() => {
+ setFullscreenAnimation(false);
+ }, 500);
+ }, [fullscreen]);
+
+ if (!tags.length) return null;
+ return (
+ <Block
+ className={cx(
+ styles.root,
+ fullscreen && styles.fullscreen,
+ fullscreenAnimation && styles.fullscreenAnimation,
+ )}
+ variant={fullscreen ? 'borderless' : 'outlined'}
+ >
+ <ActionIcon
+ className={cx('fullscreen-icon', styles.icon)}
+ icon={fullscreen ? MinimizeIcon : MaximizeIcon}
+ onClick={() => {
+ setFullscreen(!fullscreen);
+ }}
+ size={DESKTOP_HEADER_ICON_SIZE}
+ />
+ <TagCloudCanvas tags={tags} />
+ </Block>
+ );
+});
+
+export default RoleTagCloud;
diff --git a/src/app/[variants]/(main)/memory/(home)/index.tsx b/src/app/[variants]/(main)/memory/(home)/index.tsx
new file mode 100644
index 00000000000..03595db9d53
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/(home)/index.tsx
@@ -0,0 +1,47 @@
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import MemoryEmpty from '@/app/[variants]/(main)/memory/features/MemoryEmpty';
+import { SCROLL_PARENT_ID } from '@/app/[variants]/(main)/memory/features/TimeLineView/useScrollParent';
+import Loading from '@/components/Loading/BrandTextLoading';
+import NavHeader from '@/features/NavHeader';
+import WideScreenContainer from '@/features/WideScreenContainer';
+import WideScreenButton from '@/features/WideScreenContainer/WideScreenButton';
+import { useUserMemoryStore } from '@/store/userMemory';
+
+import RoleTagCloud from './features/RoleTagCloud';
+
+const Home = memo(() => {
+ const useFetchTags = useUserMemoryStore((s) => s.useFetchTags);
+ const roles = useUserMemoryStore((s) => s.roles);
+ const { isLoading } = useFetchTags();
+
+ if (isLoading) return <Loading debugId={'Home'} />;
+
+ if (!roles || roles.length === 0) {
+ return <MemoryEmpty />;
+ }
+
+ return (
+ <Flexbox flex={1} height={'100%'}>
+ <NavHeader
+ right={<WideScreenButton />}
+ style={{
+ zIndex: 1,
+ }}
+ />
+ <Flexbox
+ height={'100%'}
+ id={SCROLL_PARENT_ID}
+ style={{ overflowY: 'auto', paddingBottom: '16vh' }}
+ width={'100%'}
+ >
+ <WideScreenContainer gap={32} paddingBlock={48}>
+ <RoleTagCloud tags={roles} />
+ </WideScreenContainer>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+export default Home;
diff --git a/src/app/[variants]/(main)/memory/_layout/Sidebar/Header/Nav.tsx b/src/app/[variants]/(main)/memory/_layout/Sidebar/Header/Nav.tsx
new file mode 100644
index 00000000000..7faadae78ac
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/_layout/Sidebar/Header/Nav.tsx
@@ -0,0 +1,126 @@
+'use client';
+
+import {
+ BrainCircuitIcon,
+ BubblesIcon,
+ HeartPulseIcon,
+ LightbulbIcon,
+ SearchIcon,
+ SignatureIcon,
+} from 'lucide-react';
+import { usePathname } from 'next/navigation';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+import { Link, useNavigate } from 'react-router-dom';
+
+import NavItem, { NavItemProps } from '@/features/NavPanel/components/NavItem';
+import { useGlobalStore } from '@/store/global';
+
+interface Item {
+ icon: NavItemProps['icon'];
+ key: string;
+ onClick?: () => void;
+ title: NavItemProps['title'];
+ url?: string;
+}
+
+enum MemoryTabKey {
+ Contexts = 'contexts',
+ Experiences = 'experiences',
+ Home = 'home',
+ Identities = 'identities',
+ Preferences = 'preferences',
+}
+
+const useActiveTabKey = () => {
+ const pathname = usePathname();
+ if (pathname === '/memory') return MemoryTabKey.Home;
+ return (pathname.split('/memory/').find(Boolean)! as MemoryTabKey) || MemoryTabKey.Home;
+};
+
+const Nav = memo(() => {
+ const tab = useActiveTabKey();
+ const navigate = useNavigate();
+ const { t } = useTranslation('memory');
+ const toggleCommandMenu = useGlobalStore((s) => s.toggleCommandMenu);
+
+ const items: Item[] = useMemo(
+ () => [
+ {
+ icon: SearchIcon,
+ key: 'search',
+ onClick: () => {
+ toggleCommandMenu(true);
+ },
+ title: t('tab.search'),
+ },
+ {
+ icon: BrainCircuitIcon,
+ key: MemoryTabKey.Home,
+ title: t('tab.home'),
+ url: '/memory',
+ },
+ {
+ icon: SignatureIcon,
+ key: MemoryTabKey.Identities,
+ title: t('tab.identities'),
+ url: '/memory/identities',
+ },
+ {
+ icon: BubblesIcon,
+ key: MemoryTabKey.Contexts,
+ title: t('tab.contexts'),
+ url: '/memory/contexts',
+ },
+ {
+ icon: HeartPulseIcon,
+ key: MemoryTabKey.Preferences,
+ title: t('tab.preferences'),
+ url: '/memory/preferences',
+ },
+ {
+ icon: LightbulbIcon,
+ key: MemoryTabKey.Experiences,
+ title: t('tab.experiences'),
+ url: '/memory/experiences',
+ },
+ ],
+ [t],
+ );
+
+ return (
+ <Flexbox gap={1} paddingInline={4}>
+ {items.map((item) => {
+ const content = (
+ <NavItem
+ active={tab === item.key}
+ icon={item.icon}
+ key={item.key}
+ onClick={item.onClick}
+ title={item.title}
+ />
+ );
+ if (!item.url) return content;
+
+ return (
+ <Link
+ key={item.key}
+ onClick={(e) => {
+ e.preventDefault();
+ item?.onClick?.();
+ if (item.url) {
+ navigate(item.url);
+ }
+ }}
+ to={item.url}
+ >
+ <NavItem active={tab === item.key} icon={item.icon} title={item.title} />
+ </Link>
+ );
+ })}
+ </Flexbox>
+ );
+});
+
+export default Nav;
diff --git a/src/app/[variants]/(main)/memory/_layout/Sidebar/Header/index.tsx b/src/app/[variants]/(main)/memory/_layout/Sidebar/Header/index.tsx
new file mode 100644
index 00000000000..5a668b50a71
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/_layout/Sidebar/Header/index.tsx
@@ -0,0 +1,27 @@
+'use client';
+
+import { PropsWithChildren, memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import SideBarHeaderLayout from '@/features/NavPanel/SideBarHeaderLayout';
+
+import Nav from './Nav';
+
+const Header = memo<PropsWithChildren>(() => {
+ const { t } = useTranslation('common');
+ return (
+ <>
+ <SideBarHeaderLayout
+ breadcrumb={[
+ {
+ href: '/memory',
+ title: t('tab.memory'),
+ },
+ ]}
+ />
+ <Nav />
+ </>
+ );
+});
+
+export default Header;
diff --git a/src/app/[variants]/(main)/memory/_layout/Sidebar/index.tsx b/src/app/[variants]/(main)/memory/_layout/Sidebar/index.tsx
new file mode 100644
index 00000000000..bcfcd69012f
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/_layout/Sidebar/index.tsx
@@ -0,0 +1,18 @@
+import React, { memo } from 'react';
+
+import { NavPanelPortal } from '@/features/NavPanel';
+import SideBarLayout from '@/features/NavPanel/SideBarLayout';
+
+import Header from './Header';
+
+const Sidebar = memo(() => {
+ return (
+ <NavPanelPortal navKey="memory">
+ <SideBarLayout header={<Header />} />
+ </NavPanelPortal>
+ );
+});
+
+Sidebar.displayName = 'MemorySidebar';
+
+export default Sidebar;
diff --git a/src/app/[variants]/(main)/memory/_layout/index.tsx b/src/app/[variants]/(main)/memory/_layout/index.tsx
new file mode 100644
index 00000000000..ae520a3832f
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/_layout/index.tsx
@@ -0,0 +1,33 @@
+'use client';
+
+import { useTheme } from 'antd-style';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+import { Outlet } from 'react-router-dom';
+
+import Sidebar from './Sidebar';
+
+const DesktopMemoryLayout = memo(() => {
+ const theme = useTheme();
+
+ return (
+ <>
+ <Sidebar />
+ <Flexbox
+ flex={1}
+ height={'100%'}
+ style={{
+ background: theme.colorBgContainer,
+ overflow: 'hidden',
+ position: 'relative',
+ }}
+ >
+ <Outlet />
+ </Flexbox>
+ </>
+ );
+});
+
+DesktopMemoryLayout.displayName = 'DesktopMemoryLayout';
+
+export default DesktopMemoryLayout;
diff --git a/src/app/[variants]/(main)/memory/contexts/features/ContextDropdown.tsx b/src/app/[variants]/(main)/memory/contexts/features/ContextDropdown.tsx
new file mode 100644
index 00000000000..0f16d2b97ba
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/contexts/features/ContextDropdown.tsx
@@ -0,0 +1,66 @@
+import { ActionIcon, ActionIconProps, Dropdown } from '@lobehub/ui';
+import { App } from 'antd';
+import { MoreHorizontal, Pencil, Trash2 } from 'lucide-react';
+import { KeyboardEvent, MouseEvent, memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useUserMemoryStore } from '@/store/userMemory';
+
+interface ContextDropdownProps {
+ id: string;
+ size?: ActionIconProps['size'];
+}
+
+const ContextDropdown = memo<ContextDropdownProps>(({ id, size = 'small' }) => {
+ const { t } = useTranslation(['memory', 'common']);
+ const { modal } = App.useApp();
+
+ const contexts = useUserMemoryStore((s) => s.contexts);
+ const deleteContext = useUserMemoryStore((s) => s.deleteContext);
+ const setEditingMemory = useUserMemoryStore((s) => s.setEditingMemory);
+
+ const handleMenuClick = (info: { domEvent: MouseEvent | KeyboardEvent; key: string }) => {
+ info.domEvent.stopPropagation();
+
+ if (info.key === 'edit') {
+ const context = contexts.find((c) => c.id === id);
+ if (context) {
+ setEditingMemory(id, context.description || '', 'context');
+ }
+ } else if (info.key === 'delete') {
+ modal.confirm({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: t('context.deleteConfirm'),
+ okButtonProps: { danger: true },
+ okText: t('confirm', { ns: 'common' }),
+ onOk: async () => {
+ await deleteContext(id);
+ },
+ title: t('context.deleteTitle'),
+ type: 'warning',
+ });
+ }
+ };
+
+ const menuItems = [
+ {
+ icon: <Pencil size={14} />,
+ key: 'edit',
+ label: t('context.actions.edit'),
+ },
+ {
+ danger: true,
+ icon: <Trash2 size={14} />,
+ key: 'delete',
+ label: t('context.actions.delete'),
+ },
+ ];
+
+ return (
+ <Dropdown menu={{ items: menuItems, onClick: handleMenuClick }} trigger={['click']}>
+ <ActionIcon icon={MoreHorizontal} size={size} />
+ </Dropdown>
+ );
+});
+
+export default ContextDropdown;
diff --git a/src/app/[variants]/(main)/memory/contexts/features/ContextRightPanel.tsx b/src/app/[variants]/(main)/memory/contexts/features/ContextRightPanel.tsx
new file mode 100644
index 00000000000..14d28b47595
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/contexts/features/ContextRightPanel.tsx
@@ -0,0 +1,97 @@
+'use client';
+
+import { Text, Tooltip } from '@lobehub/ui';
+import { Badge } from 'antd';
+import { useTheme } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Center, Flexbox } from 'react-layout-kit';
+
+import CateTag from '@/app/[variants]/(main)/memory/features/CateTag';
+import DetailLoading from '@/app/[variants]/(main)/memory/features/DetailLoading';
+import DetailPanel from '@/app/[variants]/(main)/memory/features/DetailPanel';
+import HashTags from '@/app/[variants]/(main)/memory/features/HashTags';
+import HighlightedContent from '@/app/[variants]/(main)/memory/features/HighlightedContent';
+import ProgressIcon from '@/app/[variants]/(main)/memory/features/ProgressIcon';
+import SourceLink from '@/app/[variants]/(main)/memory/features/SourceLink';
+import Time from '@/app/[variants]/(main)/memory/features/Time';
+import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
+import { useQueryState } from '@/hooks/useQueryParam';
+import { useUserMemoryStore } from '@/store/userMemory';
+import { LayersEnum } from '@/types/userMemory';
+
+import ContextDropdown from './ContextDropdown';
+
+const ContextRightPanel = memo(() => {
+ const theme = useTheme();
+ const [contextId] = useQueryState('contextId', { clearOnDefault: true });
+ const useFetchMemoryDetail = useUserMemoryStore((s) => s.useFetchMemoryDetail);
+ const { t } = useTranslation('memory');
+ const { data: context, isLoading } = useFetchMemoryDetail(contextId, LayersEnum.Context);
+
+ if (!contextId) return null;
+
+ let content;
+ if (isLoading) content = <DetailLoading />;
+ if (context)
+ content = (
+ <>
+ <CateTag cate={context.type} />
+ <Text
+ as={'h1'}
+ fontSize={20}
+ style={{
+ lineHeight: 1.4,
+ marginBottom: 0,
+ }}
+ weight={'bold'}
+ >
+ {context.title}
+ <Tooltip title={context.currentStatus}>
+ <Center flex={'none'} height={20} style={{ display: 'inline-flex' }} width={20}>
+ <Badge
+ status="processing"
+ style={{ marginLeft: 8 }}
+ styles={{
+ indicator: { alignSelf: 'center', marginBottom: 4 },
+ }}
+ />
+ </Center>
+ </Tooltip>
+ </Text>
+ <Flexbox align="center" gap={16} horizontal>
+ <ProgressIcon
+ format={(percent) => `${t('filter.sort.scoreImpact')}: ${percent}%`}
+ percent={(context.scoreImpact ?? 0) * 100}
+ showInfo
+ />
+ <ProgressIcon
+ format={(percent) => `${t('filter.sort.scoreUrgency')}: ${percent}%`}
+ percent={(context.scoreUrgency ?? 0) * 100}
+ showInfo
+ strokeColor={(context.scoreUrgency ?? 0) >= 0.7 ? theme.colorError : theme.colorWarning}
+ />
+ </Flexbox>
+ <Flexbox align="center" gap={16} horizontal justify="space-between">
+ <SourceLink source={context.source} />
+ <Time updatedAt={context.createdAt} />
+ </Flexbox>
+ <HighlightedContent>{context.description}</HighlightedContent>
+ <HashTags hashTags={context.tags} />
+ </>
+ );
+
+ return (
+ <DetailPanel
+ header={{
+ right: contextId ? (
+ <ContextDropdown id={contextId} size={DESKTOP_HEADER_ICON_SIZE} />
+ ) : undefined,
+ }}
+ >
+ {content}
+ </DetailPanel>
+ );
+});
+
+export default ContextRightPanel;
diff --git a/src/app/[variants]/(main)/memory/contexts/features/List/GridView/ContextCard.tsx b/src/app/[variants]/(main)/memory/contexts/features/List/GridView/ContextCard.tsx
new file mode 100644
index 00000000000..b907b04cf4a
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/contexts/features/List/GridView/ContextCard.tsx
@@ -0,0 +1,46 @@
+import { useTheme } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import GridCard from '@/app/[variants]/(main)/memory/features/GridView/GridCard';
+import ProgressIcon from '@/app/[variants]/(main)/memory/features/ProgressIcon';
+import { DisplayContextMemory } from '@/database/repositories/userMemory';
+
+import ContextDropdown from '../../ContextDropdown';
+
+interface ContextCardProps {
+ context: DisplayContextMemory;
+ onClick?: () => void;
+}
+
+const ContextCard = memo<ContextCardProps>(({ context, onClick }) => {
+ const { t } = useTranslation('memory');
+ const theme = useTheme();
+
+ return (
+ <GridCard
+ actions={<ContextDropdown id={context.id} />}
+ badges={
+ <>
+ <ProgressIcon
+ format={(percent) => `${t('filter.sort.scoreImpact')}: ${percent}%`}
+ percent={(context.scoreImpact ?? 0) * 100}
+ />
+ <ProgressIcon
+ format={(percent) => `${t('filter.sort.scoreUrgency')}: ${percent}%`}
+ percent={(context.scoreUrgency ?? 0) * 100}
+ strokeColor={(context.scoreUrgency ?? 0) >= 0.7 ? theme.colorError : theme.colorWarning}
+ />
+ </>
+ }
+ cate={context.type}
+ onClick={onClick}
+ title={context.title}
+ updatedAt={context.updatedAt || context.createdAt}
+ >
+ {context.description}
+ </GridCard>
+ );
+});
+
+export default ContextCard;
diff --git a/src/app/[variants]/(main)/memory/contexts/features/List/GridView/index.tsx b/src/app/[variants]/(main)/memory/contexts/features/List/GridView/index.tsx
new file mode 100644
index 00000000000..8a3566fcfe3
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/contexts/features/List/GridView/index.tsx
@@ -0,0 +1,31 @@
+import { memo } from 'react';
+
+import { DisplayContextMemory } from '@/database/repositories/userMemory';
+import { useUserMemoryStore } from '@/store/userMemory';
+
+import { GridView } from '../../../../features/GridView';
+import ContextCard from './ContextCard';
+
+interface GridViewProps {
+ contexts: DisplayContextMemory[];
+ isLoading?: boolean;
+ onClick: (context: DisplayContextMemory) => void;
+}
+
+const ContextsGridView = memo<GridViewProps>(({ contexts, isLoading, onClick }) => {
+ const loadMoreContexts = useUserMemoryStore((s) => s.loadMoreContexts);
+ const contextsHasMore = useUserMemoryStore((s) => s.contextsHasMore);
+
+ return (
+ <GridView
+ defaultColumnCount={2}
+ hasMore={contextsHasMore}
+ isLoading={isLoading}
+ items={contexts}
+ onLoadMore={loadMoreContexts}
+ renderItem={(context) => <ContextCard context={context} onClick={() => onClick(context)} />}
+ />
+ );
+});
+
+export default ContextsGridView;
diff --git a/src/app/[variants]/(main)/memory/contexts/features/List/TimelineView/ContextCard.tsx b/src/app/[variants]/(main)/memory/contexts/features/List/TimelineView/ContextCard.tsx
new file mode 100644
index 00000000000..9a993dcc6be
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/contexts/features/List/TimelineView/ContextCard.tsx
@@ -0,0 +1,28 @@
+import { memo } from 'react';
+
+import TimeLineCard from '@/app/[variants]/(main)/memory/features/TimeLineView/TimeLineCard';
+import { DisplayContextMemory } from '@/database/repositories/userMemory';
+
+import ContextDropdown from '../../ContextDropdown';
+
+interface ContextCardProps {
+ context: DisplayContextMemory;
+ onClick?: () => void;
+}
+
+const ContextCard = memo<ContextCardProps>(({ context, onClick }) => {
+ return (
+ <TimeLineCard
+ actions={<ContextDropdown id={context.id} />}
+ cate={context.type}
+ hashTags={context.tags}
+ onClick={onClick}
+ title={context.title}
+ updatedAt={context.updatedAt || context.createdAt}
+ >
+ {context.description}
+ </TimeLineCard>
+ );
+});
+
+export default ContextCard;
diff --git a/src/app/[variants]/(main)/memory/contexts/features/List/TimelineView/index.tsx b/src/app/[variants]/(main)/memory/contexts/features/List/TimelineView/index.tsx
new file mode 100644
index 00000000000..97d65a55b07
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/contexts/features/List/TimelineView/index.tsx
@@ -0,0 +1,39 @@
+'use client';
+
+import { memo } from 'react';
+
+import { DisplayContextMemory } from '@/database/repositories/userMemory';
+import { useUserMemoryStore } from '@/store/userMemory';
+
+import { TimelineView as GenericTimelineView } from '../../../../features/TimeLineView';
+import { PeriodHeader, TimelineItemWrapper } from '../../../../features/TimeLineView/PeriodGroup';
+import ContextCard from './ContextCard';
+
+interface ContextTimelineViewProps {
+ contexts: DisplayContextMemory[];
+ isLoading?: boolean;
+ onClick?: (context: DisplayContextMemory) => void;
+}
+
+const ContextTimelineView = memo<ContextTimelineViewProps>(({ contexts, isLoading, onClick }) => {
+ const loadMoreContexts = useUserMemoryStore((s) => s.loadMoreContexts);
+ const contextsHasMore = useUserMemoryStore((s) => s.contextsHasMore);
+
+ return (
+ <GenericTimelineView
+ data={contexts}
+ groupBy="day"
+ hasMore={contextsHasMore}
+ isLoading={isLoading}
+ onLoadMore={loadMoreContexts}
+ renderHeader={(periodKey) => <PeriodHeader groupBy="day" periodKey={periodKey} />}
+ renderItem={(context) => (
+ <TimelineItemWrapper>
+ <ContextCard context={context} onClick={() => onClick?.(context)} />
+ </TimelineItemWrapper>
+ )}
+ />
+ );
+});
+
+export default ContextTimelineView;
diff --git a/src/app/[variants]/(main)/memory/contexts/features/List/index.tsx b/src/app/[variants]/(main)/memory/contexts/features/List/index.tsx
new file mode 100644
index 00000000000..686aa7890ac
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/contexts/features/List/index.tsx
@@ -0,0 +1,44 @@
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import MemoryEmpty from '@/app/[variants]/(main)/memory/features/MemoryEmpty';
+import { useQueryState } from '@/hooks/useQueryParam';
+import { useGlobalStore } from '@/store/global';
+import { useUserMemoryStore } from '@/store/userMemory';
+
+import { ViewMode } from '../../../features/ViewModeSwitcher';
+import GridView from './GridView';
+import TimelineView from './TimelineView';
+
+interface ContextsListProps {
+ isLoading?: boolean;
+ searchValue?: string;
+ viewMode: ViewMode;
+}
+
+const ContextsList = memo<ContextsListProps>(({ isLoading, searchValue, viewMode }) => {
+ const { t } = useTranslation(['memory', 'common']);
+ const toggleRightPanel = useGlobalStore((s) => s.toggleRightPanel);
+ const [, setContextId] = useQueryState('contextId', { clearOnDefault: true });
+
+ const contexts = useUserMemoryStore((s) => s.contexts);
+
+ const handleCardClick = (context: any) => {
+ setContextId(context.id);
+ toggleRightPanel(true);
+ };
+
+ const isEmpty = contexts.length === 0;
+
+ if (isEmpty) {
+ return <MemoryEmpty search={Boolean(searchValue)} title={t('context.empty')} />;
+ }
+
+ return viewMode === 'timeline' ? (
+ <TimelineView contexts={contexts} isLoading={isLoading} onClick={handleCardClick} />
+ ) : (
+ <GridView contexts={contexts} isLoading={isLoading} onClick={handleCardClick} />
+ );
+});
+
+export default ContextsList;
diff --git a/src/app/[variants]/(main)/memory/contexts/index.tsx b/src/app/[variants]/(main)/memory/contexts/index.tsx
new file mode 100644
index 00000000000..f5edb67b32c
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/contexts/index.tsx
@@ -0,0 +1,132 @@
+import { Icon, Tag } from '@lobehub/ui';
+import { BrainCircuitIcon } from 'lucide-react';
+import { memo, useCallback, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { SCROLL_PARENT_ID } from '@/app/[variants]/(main)/memory/features/TimeLineView/useScrollParent';
+import NavHeader from '@/features/NavHeader';
+import WideScreenContainer from '@/features/WideScreenContainer';
+import WideScreenButton from '@/features/WideScreenContainer/WideScreenButton';
+import { useQueryState } from '@/hooks/useQueryParam';
+import { useUserMemoryStore } from '@/store/userMemory';
+
+import EditableModal from '../features/EditableModal';
+import FilterBar from '../features/FilterBar';
+import Loading from '../features/Loading';
+import ViewModeSwitcher, { ViewMode } from '../features/ViewModeSwitcher';
+import ContextRightPanel from './features/ContextRightPanel';
+import List from './features/List';
+
+const ContextsArea = memo(() => {
+ const { t } = useTranslation('memory');
+ const [viewMode, setViewMode] = useState<ViewMode>('timeline');
+ const [searchValueRaw, setSearchValueRaw] = useQueryState('q', { clearOnDefault: true });
+ const [sortValueRaw, setSortValueRaw] = useQueryState('sort', { clearOnDefault: true });
+
+ const searchValue = searchValueRaw || '';
+ const sortValue = (sortValueRaw as 'createdAt' | 'scoreImpact' | 'scoreUrgency') || 'createdAt';
+
+ const contextsPage = useUserMemoryStore((s) => s.contextsPage);
+ const contextsInit = useUserMemoryStore((s) => s.contextsInit);
+ const contextsTotal = useUserMemoryStore((s) => s.contextsTotal);
+ const contextsSearchLoading = useUserMemoryStore((s) => s.contextsSearchLoading);
+ const useFetchContexts = useUserMemoryStore((s) => s.useFetchContexts);
+ const resetContextsList = useUserMemoryStore((s) => s.resetContextsList);
+
+ const sortOptions = [
+ { label: t('filter.sort.createdAt'), value: 'createdAt' },
+ { label: t('filter.sort.scoreImpact'), value: 'scoreImpact' },
+ { label: t('filter.sort.scoreUrgency'), value: 'scoreUrgency' },
+ ];
+
+ // 转换 sort:createdAt 转为 undefined(后端默认)
+ const apiSort =
+ sortValue === 'createdAt' ? undefined : (sortValue as 'scoreImpact' | 'scoreUrgency');
+
+ // 当搜索或排序变化时重置列表
+ useEffect(() => {
+ if (!apiSort) return;
+ const sort = viewMode === 'grid' ? apiSort : undefined;
+ resetContextsList({ q: searchValue || undefined, sort });
+ }, [searchValue, apiSort, viewMode]);
+
+ // 调用 SWR hook 获取数据
+ const { isLoading } = useFetchContexts({
+ page: contextsPage,
+ pageSize: 12,
+ q: searchValue || undefined,
+ sort: viewMode === 'grid' ? apiSort : undefined,
+ });
+
+ // Handle search and sort changes
+ const handleSearch = useCallback(
+ (value: string) => {
+ setSearchValueRaw(value || null);
+ },
+ [setSearchValueRaw],
+ );
+
+ const handleSortChange = useCallback(
+ (sort: string) => {
+ setSortValueRaw(sort);
+ },
+ [setSortValueRaw],
+ );
+
+ // 显示 loading:搜索/重置中 或 首次加载中
+ const showLoading = contextsSearchLoading || !contextsInit;
+
+ return (
+ <Flexbox flex={1} height={'100%'}>
+ <NavHeader
+ left={
+ Boolean(contextsTotal) && (
+ <Tag icon={<Icon icon={BrainCircuitIcon} />}>{contextsTotal}</Tag>
+ )
+ }
+ right={
+ <>
+ <ViewModeSwitcher onChange={setViewMode} value={viewMode} />
+ <WideScreenButton />
+ </>
+ }
+ />
+ <Flexbox
+ height={'100%'}
+ id={SCROLL_PARENT_ID}
+ style={{ overflowY: 'auto', paddingBottom: '16vh' }}
+ width={'100%'}
+ >
+ <WideScreenContainer gap={32} paddingBlock={48}>
+ <FilterBar
+ onSearch={handleSearch}
+ onSortChange={viewMode === 'grid' ? handleSortChange : undefined}
+ searchValue={searchValue}
+ sortOptions={viewMode === 'grid' ? sortOptions : undefined}
+ sortValue={sortValue}
+ />
+ {showLoading ? (
+ <Loading viewMode={viewMode} />
+ ) : (
+ <List isLoading={isLoading} searchValue={searchValue} viewMode={viewMode} />
+ )}
+ </WideScreenContainer>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+const Contexts = memo(() => {
+ return (
+ <>
+ <Flexbox height={'100%'} horizontal width={'100%'}>
+ <ContextsArea />
+ <ContextRightPanel />
+ </Flexbox>
+ <EditableModal />
+ </>
+ );
+});
+
+export default Contexts;
diff --git a/src/app/[variants]/(main)/memory/experiences/features/ExperienceDropdown.tsx b/src/app/[variants]/(main)/memory/experiences/features/ExperienceDropdown.tsx
new file mode 100644
index 00000000000..3733d173689
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/experiences/features/ExperienceDropdown.tsx
@@ -0,0 +1,66 @@
+import { ActionIcon, ActionIconProps, Dropdown } from '@lobehub/ui';
+import { App } from 'antd';
+import { MoreHorizontal, Pencil, Trash2 } from 'lucide-react';
+import { KeyboardEvent, MouseEvent, memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useUserMemoryStore } from '@/store/userMemory';
+
+interface ExperienceDropdownProps {
+ id: string;
+ size?: ActionIconProps['size'];
+}
+
+const ExperienceDropdown = memo<ExperienceDropdownProps>(({ id, size = 'small' }) => {
+ const { t } = useTranslation(['memory', 'common']);
+ const { modal } = App.useApp();
+
+ const experiences = useUserMemoryStore((s) => s.experiences);
+ const deleteExperience = useUserMemoryStore((s) => s.deleteExperience);
+ const setEditingMemory = useUserMemoryStore((s) => s.setEditingMemory);
+
+ const handleMenuClick = (info: { domEvent: MouseEvent | KeyboardEvent; key: string }) => {
+ info.domEvent.stopPropagation();
+
+ if (info.key === 'edit') {
+ const experience = experiences.find((e) => e.id === id);
+ if (experience) {
+ setEditingMemory(id, experience.keyLearning || '', 'experience');
+ }
+ } else if (info.key === 'delete') {
+ modal.confirm({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: t('experience.deleteConfirm'),
+ okButtonProps: { danger: true },
+ okText: t('confirm', { ns: 'common' }),
+ onOk: async () => {
+ await deleteExperience(id);
+ },
+ title: t('experience.deleteTitle'),
+ type: 'warning',
+ });
+ }
+ };
+
+ const menuItems = [
+ {
+ icon: <Pencil size={14} />,
+ key: 'edit',
+ label: t('experience.actions.edit'),
+ },
+ {
+ danger: true,
+ icon: <Trash2 size={14} />,
+ key: 'delete',
+ label: t('experience.actions.delete'),
+ },
+ ];
+
+ return (
+ <Dropdown menu={{ items: menuItems, onClick: handleMenuClick }} trigger={['click']}>
+ <ActionIcon icon={MoreHorizontal} size={size} />
+ </Dropdown>
+ );
+});
+
+export default ExperienceDropdown;
diff --git a/src/app/[variants]/(main)/memory/experiences/features/ExperienceRightPanel.tsx b/src/app/[variants]/(main)/memory/experiences/features/ExperienceRightPanel.tsx
new file mode 100644
index 00000000000..699a36e5647
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/experiences/features/ExperienceRightPanel.tsx
@@ -0,0 +1,189 @@
+'use client';
+
+import { Avatar, Text } from '@lobehub/ui';
+import { Steps } from 'antd';
+import { createStyles } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import CateTag from '@/app/[variants]/(main)/memory/features/CateTag';
+import DetailLoading from '@/app/[variants]/(main)/memory/features/DetailLoading';
+import DetailPanel from '@/app/[variants]/(main)/memory/features/DetailPanel';
+import HashTags from '@/app/[variants]/(main)/memory/features/HashTags';
+import HighlightedContent from '@/app/[variants]/(main)/memory/features/HighlightedContent';
+import ProgressIcon from '@/app/[variants]/(main)/memory/features/ProgressIcon';
+import SourceLink from '@/app/[variants]/(main)/memory/features/SourceLink';
+import Time from '@/app/[variants]/(main)/memory/features/Time';
+import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
+import { useQueryState } from '@/hooks/useQueryParam';
+import { useUserMemoryStore } from '@/store/userMemory';
+import { LayersEnum } from '@/types/userMemory';
+
+import ExperienceDropdown from './ExperienceDropdown';
+
+const useStyles = createStyles(({ css, token }) => ({
+ content: css`
+ font-size: 14px;
+ line-height: 1.8;
+ color: ${token.colorText};
+ white-space: pre-wrap;
+ `,
+ stepsContainer: css`
+ .ant-steps-item-content {
+ min-height: auto;
+ }
+
+ .ant-steps-item-description {
+ padding-block-end: 16px !important;
+ }
+ `,
+}));
+
+const ExperienceRightPanel = memo(() => {
+ const { t } = useTranslation('memory');
+ const { styles, theme } = useStyles();
+ const [experienceId] = useQueryState('experienceId', { clearOnDefault: true });
+ const useFetchMemoryDetail = useUserMemoryStore((s) => s.useFetchMemoryDetail);
+
+ const { data: experience, isLoading } = useFetchMemoryDetail(experienceId, LayersEnum.Experience);
+
+ if (!experienceId) return null;
+
+ let content;
+ if (isLoading) content = <DetailLoading />;
+ if (experience) {
+ content = (
+ <>
+ <CateTag cate={experience.type} />
+ <Text
+ as={'h1'}
+ fontSize={20}
+ style={{
+ lineHeight: 1.4,
+ marginBottom: 0,
+ }}
+ weight={'bold'}
+ >
+ {experience.title}
+ </Text>
+ <Flexbox align="center" gap={16} horizontal justify="space-between">
+ <ProgressIcon
+ format={(percent) => `${t('filter.sort.scoreConfidence')}: ${percent}%`}
+ percent={(experience.scoreConfidence ?? 0) * 100}
+ showInfo
+ />
+ </Flexbox>
+ <Flexbox align="center" gap={16} horizontal justify="space-between">
+ <SourceLink source={experience.source} />
+ <Time updatedAt={experience.createdAt} />
+ </Flexbox>
+
+ {experience.keyLearning && (
+ <HighlightedContent>{experience.keyLearning}</HighlightedContent>
+ )}
+
+ <Steps
+ className={styles.stepsContainer}
+ current={null as any}
+ direction="vertical"
+ items={[
+ {
+ description: <HighlightedContent>{experience.situation}</HighlightedContent>,
+ icon: (
+ <Avatar
+ avatar={'S'}
+ shadow
+ shape={'square'}
+ size={24}
+ style={{
+ border: `1px solid ${theme.colorBorderSecondary}`,
+ }}
+ />
+ ),
+ title: (
+ <Text as={'h4'} fontSize={12} type={'secondary'} weight={500}>
+ {t('experience.steps.situation')}
+ </Text>
+ ),
+ },
+ {
+ description: <HighlightedContent>{experience.reasoning}</HighlightedContent>,
+ icon: (
+ <Avatar
+ avatar={'T'}
+ shadow
+ shape={'square'}
+ size={24}
+ style={{
+ border: `1px solid ${theme.colorBorderSecondary}`,
+ }}
+ />
+ ),
+ title: (
+ <Text as={'h4'} fontSize={12} type={'secondary'} weight={500}>
+ {t('experience.steps.task')}
+ </Text>
+ ),
+ },
+ {
+ description: <HighlightedContent>{experience.action}</HighlightedContent>,
+ icon: (
+ <Avatar
+ avatar={'A'}
+ shadow
+ shape={'square'}
+ size={24}
+ style={{
+ border: `1px solid ${theme.colorBorderSecondary}`,
+ }}
+ />
+ ),
+ title: (
+ <Text as={'h4'} fontSize={12} type={'secondary'} weight={500}>
+ {t('experience.steps.action')}
+ </Text>
+ ),
+ },
+ {
+ description: <HighlightedContent>{experience.possibleOutcome}</HighlightedContent>,
+ icon: (
+ <Avatar
+ avatar={'R'}
+ shadow
+ shape={'square'}
+ size={24}
+ style={{
+ border: `1px solid ${theme.colorBorderSecondary}`,
+ }}
+ />
+ ),
+ title: (
+ <Text as={'h4'} fontSize={12} type={'secondary'} weight={500}>
+ {t('experience.steps.result')}
+ </Text>
+ ),
+ },
+ ]}
+ size="small"
+ />
+
+ <HashTags hashTags={experience.tags} />
+ </>
+ );
+ }
+
+ return (
+ <DetailPanel
+ header={{
+ right: experienceId ? (
+ <ExperienceDropdown id={experienceId} size={DESKTOP_HEADER_ICON_SIZE} />
+ ) : undefined,
+ }}
+ >
+ {content}
+ </DetailPanel>
+ );
+});
+
+export default ExperienceRightPanel;
diff --git a/src/app/[variants]/(main)/memory/experiences/features/List/GridView/ExperienceCard.tsx b/src/app/[variants]/(main)/memory/experiences/features/List/GridView/ExperienceCard.tsx
new file mode 100644
index 00000000000..9d31b1af01c
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/experiences/features/List/GridView/ExperienceCard.tsx
@@ -0,0 +1,41 @@
+import dayjs from 'dayjs';
+import relativeTime from 'dayjs/plugin/relativeTime';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import GridCard from '@/app/[variants]/(main)/memory/features/GridView/GridCard';
+import ProgressIcon from '@/app/[variants]/(main)/memory/features/ProgressIcon';
+import { DisplayExperienceMemory } from '@/database/repositories/userMemory';
+
+import ExperienceDropdown from '../../ExperienceDropdown';
+
+dayjs.extend(relativeTime);
+
+interface ExperienceCardProps {
+ experience: DisplayExperienceMemory;
+ onClick: (experience: DisplayExperienceMemory) => void;
+}
+
+const ExperienceCard = memo<ExperienceCardProps>(({ experience, onClick }) => {
+ const { t } = useTranslation('memory');
+
+ return (
+ <GridCard
+ actions={<ExperienceDropdown id={experience.id} />}
+ badges={
+ <ProgressIcon
+ format={(percent) => `${t('filter.sort.scoreConfidence')}: ${percent}%`}
+ percent={(experience.scoreConfidence ?? 0) * 100}
+ />
+ }
+ cate={experience.type}
+ onClick={() => onClick(experience)}
+ title={experience.title}
+ updatedAt={experience.updatedAt || experience.createdAt}
+ >
+ {experience.keyLearning || experience.situation}
+ </GridCard>
+ );
+});
+
+export default ExperienceCard;
diff --git a/src/app/[variants]/(main)/memory/experiences/features/List/GridView/index.tsx b/src/app/[variants]/(main)/memory/experiences/features/List/GridView/index.tsx
new file mode 100644
index 00000000000..2b55e94290a
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/experiences/features/List/GridView/index.tsx
@@ -0,0 +1,32 @@
+import { memo } from 'react';
+
+import { DisplayExperienceMemory } from '@/database/repositories/userMemory';
+import { useUserMemoryStore } from '@/store/userMemory';
+
+import { GridView } from '../../../../features/GridView';
+import ExperienceCard from './ExperienceCard';
+
+interface GridViewProps {
+ experiences: DisplayExperienceMemory[];
+ isLoading?: boolean;
+ onClick: (experience: DisplayExperienceMemory) => void;
+}
+
+const ExperiencesGridView = memo<GridViewProps>(({ experiences, isLoading, onClick }) => {
+ const loadMoreExperiences = useUserMemoryStore((s) => s.loadMoreExperiences);
+ const experiencesHasMore = useUserMemoryStore((s) => s.experiencesHasMore);
+
+ return (
+ <GridView
+ hasMore={experiencesHasMore}
+ isLoading={isLoading}
+ items={experiences}
+ onLoadMore={loadMoreExperiences}
+ renderItem={(experience) => (
+ <ExperienceCard experience={experience} onClick={() => onClick(experience)} />
+ )}
+ />
+ );
+});
+
+export default ExperiencesGridView;
diff --git a/src/app/[variants]/(main)/memory/experiences/features/List/TimelineView/ExperienceCard.tsx b/src/app/[variants]/(main)/memory/experiences/features/List/TimelineView/ExperienceCard.tsx
new file mode 100644
index 00000000000..ab9e00b1a39
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/experiences/features/List/TimelineView/ExperienceCard.tsx
@@ -0,0 +1,28 @@
+import { memo } from 'react';
+
+import TimeLineCard from '@/app/[variants]/(main)/memory/features/TimeLineView/TimeLineCard';
+import { DisplayExperienceMemory } from '@/database/repositories/userMemory';
+
+import ExperienceDropdown from '../../ExperienceDropdown';
+
+interface ExperienceCardProps {
+ experience: DisplayExperienceMemory;
+ onClick: (experience: DisplayExperienceMemory) => void;
+}
+
+const ExperienceCard = memo<ExperienceCardProps>(({ experience, onClick }) => {
+ return (
+ <TimeLineCard
+ actions={<ExperienceDropdown id={experience.id} />}
+ cate={experience.type}
+ hashTags={experience.tags}
+ onClick={() => onClick(experience)}
+ title={experience.title}
+ updatedAt={experience.updatedAt || experience.createdAt}
+ >
+ {experience.keyLearning || experience.situation}
+ </TimeLineCard>
+ );
+});
+
+export default ExperienceCard;
diff --git a/src/app/[variants]/(main)/memory/experiences/features/List/TimelineView/index.tsx b/src/app/[variants]/(main)/memory/experiences/features/List/TimelineView/index.tsx
new file mode 100644
index 00000000000..f3db78f9bc3
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/experiences/features/List/TimelineView/index.tsx
@@ -0,0 +1,41 @@
+'use client';
+
+import { memo } from 'react';
+
+import { DisplayExperienceMemory } from '@/database/repositories/userMemory';
+import { useUserMemoryStore } from '@/store/userMemory';
+
+import { TimelineView as GenericTimelineView } from '../../../../features/TimeLineView';
+import { PeriodHeader, TimelineItemWrapper } from '../../../../features/TimeLineView/PeriodGroup';
+import ExperienceCard from './ExperienceCard';
+
+interface ExperienceTimelineViewProps {
+ experiences: DisplayExperienceMemory[];
+ isLoading?: boolean;
+ onCardClick: (experience: DisplayExperienceMemory) => void;
+}
+
+const ExperienceTimelineView = memo<ExperienceTimelineViewProps>(
+ ({ experiences, isLoading, onCardClick }) => {
+ const loadMoreExperiences = useUserMemoryStore((s) => s.loadMoreExperiences);
+ const experiencesHasMore = useUserMemoryStore((s) => s.experiencesHasMore);
+
+ return (
+ <GenericTimelineView
+ data={experiences}
+ groupBy="day"
+ hasMore={experiencesHasMore}
+ isLoading={isLoading}
+ onLoadMore={loadMoreExperiences}
+ renderHeader={(periodKey) => <PeriodHeader groupBy="day" periodKey={periodKey} />}
+ renderItem={(experience) => (
+ <TimelineItemWrapper>
+ <ExperienceCard experience={experience} onClick={onCardClick} />
+ </TimelineItemWrapper>
+ )}
+ />
+ );
+ },
+);
+
+export default ExperienceTimelineView;
diff --git a/src/app/[variants]/(main)/memory/experiences/features/List/index.tsx b/src/app/[variants]/(main)/memory/experiences/features/List/index.tsx
new file mode 100644
index 00000000000..e3915258ff6
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/experiences/features/List/index.tsx
@@ -0,0 +1,43 @@
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import MemoryEmpty from '@/app/[variants]/(main)/memory/features/MemoryEmpty';
+import { useQueryState } from '@/hooks/useQueryParam';
+import { useGlobalStore } from '@/store/global';
+import { useUserMemoryStore } from '@/store/userMemory';
+
+import { ViewMode } from '../../../features/ViewModeSwitcher';
+import GridView from './GridView';
+import TimelineView from './TimelineView';
+
+interface ExperiencesListProps {
+ isLoading?: boolean;
+ searchValue?: string;
+ viewMode: ViewMode;
+}
+
+const ExperiencesList = memo<ExperiencesListProps>(({ isLoading, searchValue, viewMode }) => {
+ const { t } = useTranslation(['memory', 'common']);
+ const [, setExperienceId] = useQueryState('experienceId', { clearOnDefault: true });
+ const toggleRightPanel = useGlobalStore((s) => s.toggleRightPanel);
+ const experiences = useUserMemoryStore((s) => s.experiences);
+
+ const handleCardClick = (experience: any) => {
+ setExperienceId(experience.id);
+ toggleRightPanel(true);
+ };
+
+ const isEmpty = experiences.length === 0;
+
+ if (isEmpty) {
+ return <MemoryEmpty search={Boolean(searchValue)} title={t('experience.empty')} />;
+ }
+
+ return viewMode === 'timeline' ? (
+ <TimelineView experiences={experiences} isLoading={isLoading} onCardClick={handleCardClick} />
+ ) : (
+ <GridView experiences={experiences} isLoading={isLoading} onClick={handleCardClick} />
+ );
+});
+
+export default ExperiencesList;
diff --git a/src/app/[variants]/(main)/memory/experiences/index.tsx b/src/app/[variants]/(main)/memory/experiences/index.tsx
new file mode 100644
index 00000000000..392ee8651ba
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/experiences/index.tsx
@@ -0,0 +1,130 @@
+import { Icon, Tag } from '@lobehub/ui';
+import { BrainCircuitIcon } from 'lucide-react';
+import { memo, useCallback, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { SCROLL_PARENT_ID } from '@/app/[variants]/(main)/memory/features/TimeLineView/useScrollParent';
+import NavHeader from '@/features/NavHeader';
+import WideScreenContainer from '@/features/WideScreenContainer';
+import WideScreenButton from '@/features/WideScreenContainer/WideScreenButton';
+import { useQueryState } from '@/hooks/useQueryParam';
+import { useUserMemoryStore } from '@/store/userMemory';
+
+import EditableModal from '../features/EditableModal';
+import FilterBar from '../features/FilterBar';
+import Loading from '../features/Loading';
+import ViewModeSwitcher, { ViewMode } from '../features/ViewModeSwitcher';
+import ExperienceRightPanel from './features/ExperienceRightPanel';
+import List from './features/List';
+
+const ExperiencesArea = memo(() => {
+ const { t } = useTranslation('memory');
+ const [viewMode, setViewMode] = useState<ViewMode>('timeline');
+ const [searchValueRaw, setSearchValueRaw] = useQueryState('q', { clearOnDefault: true });
+ const [sortValueRaw, setSortValueRaw] = useQueryState('sort', { clearOnDefault: true });
+
+ const searchValue = searchValueRaw || '';
+ const sortValue = (sortValueRaw as 'createdAt' | 'scoreConfidence') || 'createdAt';
+
+ const experiencesPage = useUserMemoryStore((s) => s.experiencesPage);
+ const experiencesInit = useUserMemoryStore((s) => s.experiencesInit);
+ const experiencesTotal = useUserMemoryStore((s) => s.experiencesTotal);
+ const experiencesSearchLoading = useUserMemoryStore((s) => s.experiencesSearchLoading);
+ const useFetchExperiences = useUserMemoryStore((s) => s.useFetchExperiences);
+ const resetExperiencesList = useUserMemoryStore((s) => s.resetExperiencesList);
+
+ const sortOptions = [
+ { label: t('filter.sort.createdAt'), value: 'createdAt' },
+ { label: t('filter.sort.scoreConfidence'), value: 'scoreConfidence' },
+ ];
+
+ // 转换 sort:createdAt 转为 undefined(后端默认)
+ const apiSort = sortValue === 'createdAt' ? undefined : (sortValue as 'scoreConfidence');
+
+ // 当搜索或排序变化时重置列表
+ useEffect(() => {
+ if (!apiSort) return;
+ const sort = viewMode === 'grid' ? apiSort : undefined;
+ resetExperiencesList({ q: searchValue || undefined, sort });
+ }, [searchValue, apiSort, viewMode]);
+
+ // 调用 SWR hook 获取数据
+ const { isLoading } = useFetchExperiences({
+ page: experiencesPage,
+ pageSize: 12,
+ q: searchValue || undefined,
+ sort: viewMode === 'grid' ? apiSort : undefined,
+ });
+
+ // Handle search and sort changes
+ const handleSearch = useCallback(
+ (value: string) => {
+ setSearchValueRaw(value || null);
+ },
+ [setSearchValueRaw],
+ );
+
+ const handleSortChange = useCallback(
+ (sort: string) => {
+ setSortValueRaw(sort);
+ },
+ [setSortValueRaw],
+ );
+
+ // 显示 loading:搜索/重置中 或 首次加载中
+ const showLoading = experiencesSearchLoading || !experiencesInit;
+
+ return (
+ <Flexbox flex={1} height={'100%'}>
+ <NavHeader
+ left={
+ Boolean(experiencesTotal) && (
+ <Tag icon={<Icon icon={BrainCircuitIcon} />}>{experiencesTotal}</Tag>
+ )
+ }
+ right={
+ <>
+ <ViewModeSwitcher onChange={setViewMode} value={viewMode} />
+ <WideScreenButton />
+ </>
+ }
+ />
+ <Flexbox
+ height={'100%'}
+ id={SCROLL_PARENT_ID}
+ style={{ overflowY: 'auto', paddingBottom: '16vh' }}
+ width={'100%'}
+ >
+ <WideScreenContainer gap={32} paddingBlock={48}>
+ <FilterBar
+ onSearch={handleSearch}
+ onSortChange={viewMode === 'grid' ? handleSortChange : undefined}
+ searchValue={searchValue}
+ sortOptions={viewMode === 'grid' ? sortOptions : undefined}
+ sortValue={sortValue}
+ />
+ {showLoading ? (
+ <Loading viewMode={viewMode} />
+ ) : (
+ <List isLoading={isLoading} searchValue={searchValue} viewMode={viewMode} />
+ )}
+ </WideScreenContainer>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+const Experiences = memo(() => {
+ return (
+ <>
+ <Flexbox height={'100%'} horizontal width={'100%'}>
+ <ExperiencesArea />
+ <ExperienceRightPanel />
+ </Flexbox>
+ <EditableModal />
+ </>
+ );
+});
+
+export default Experiences;
diff --git a/src/app/[variants]/(main)/memory/features/CateTag.tsx b/src/app/[variants]/(main)/memory/features/CateTag.tsx
new file mode 100644
index 00000000000..74854ae0d2b
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/features/CateTag.tsx
@@ -0,0 +1,28 @@
+import { Tag } from '@lobehub/ui';
+import { memo } from 'react';
+
+import { useCateColor } from './useCateColor';
+
+interface CateTagProps {
+ cate?: string | null;
+}
+
+const CateTag = memo<CateTagProps>(({ cate }) => {
+ const cateColor = useCateColor(cate);
+ return (
+ <Tag
+ size={'large'}
+ style={{
+ background: cateColor?.backgroundColor,
+ borderRadius: 16,
+ color: cateColor?.color,
+ flex: 'none',
+ fontWeight: 500,
+ }}
+ >
+ {cate?.toUpperCase() || 'CHORE'}
+ </Tag>
+ );
+});
+
+export default CateTag;
diff --git a/src/app/[variants]/(main)/memory/features/DetailLoading.tsx b/src/app/[variants]/(main)/memory/features/DetailLoading.tsx
new file mode 100644
index 00000000000..074f5351358
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/features/DetailLoading.tsx
@@ -0,0 +1,20 @@
+import { Skeleton } from '@lobehub/ui';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+const DetailLoading = memo(() => {
+ return (
+ <>
+ <Skeleton.Button active shape={'round'} size={'small'} width={64} />
+ <Skeleton.Title active fontSize={20} lineHeight={1.4} />
+ <Skeleton.Tags active count={2} />
+ <Flexbox align="center" gap={16} horizontal justify="space-between">
+ <Skeleton.Tags active />
+ <Skeleton.Tags active />
+ </Flexbox>
+ <Skeleton.Paragraph active fontSize={16} rows={6} />
+ </>
+ );
+});
+
+export default DetailLoading;
diff --git a/src/app/[variants]/(main)/memory/features/DetailPanel.tsx b/src/app/[variants]/(main)/memory/features/DetailPanel.tsx
new file mode 100644
index 00000000000..8218aa90c03
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/features/DetailPanel.tsx
@@ -0,0 +1,44 @@
+import { memo } from 'react';
+import { Flexbox, FlexboxProps } from 'react-layout-kit';
+
+import NavHeader, { NavHeaderProps } from '@/features/NavHeader';
+import RightPanel from '@/features/RightPanel';
+import ToggleRightPanelButton from '@/features/RightPanel/ToggleRightPanelButton';
+
+interface DetailPanelProps extends FlexboxProps {
+ header?: NavHeaderProps;
+}
+
+const DetailPanel = memo<DetailPanelProps>(({ children, style, header, ...rest }) => {
+ return (
+ <RightPanel defaultWidth={480} maxWidth={640} minWidth={300}>
+ <NavHeader
+ {...header}
+ left={
+ <>
+ <ToggleRightPanelButton />
+ {header?.left}
+ </>
+ }
+ />
+ <Flexbox
+ flex={1}
+ gap={16}
+ height={'100%'}
+ paddingInline={16}
+ style={{
+ minWidth: 300,
+ overflowY: 'auto',
+ paddingBottom: 64,
+ paddingTop: 16,
+ ...style,
+ }}
+ {...rest}
+ >
+ {children}
+ </Flexbox>
+ </RightPanel>
+ );
+});
+
+export default DetailPanel;
diff --git a/src/app/[variants]/(main)/memory/features/EditableModal/Typobar.tsx b/src/app/[variants]/(main)/memory/features/EditableModal/Typobar.tsx
new file mode 100644
index 00000000000..cb6500bcf85
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/features/EditableModal/Typobar.tsx
@@ -0,0 +1,151 @@
+import { HotkeyEnum, IEditor, getHotkeyById } from '@lobehub/editor';
+import { useEditorState } from '@lobehub/editor/react';
+import {
+ ChatInputActionBar,
+ ChatInputActions,
+ type ChatInputActionsProps,
+ CodeLanguageSelect,
+} from '@lobehub/editor/react';
+import { useTheme } from 'antd-style';
+import {
+ BoldIcon,
+ CodeXmlIcon,
+ ItalicIcon,
+ ListIcon,
+ ListOrderedIcon,
+ ListTodoIcon,
+ MessageSquareQuote,
+ SigmaIcon,
+ SquareDashedBottomCodeIcon,
+ StrikethroughIcon,
+ UnderlineIcon,
+} from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const TypoBar = memo<{ editor?: IEditor }>(({ editor }) => {
+ const { t } = useTranslation('editor');
+ const editorState = useEditorState(editor);
+ const theme = useTheme();
+
+ const items: ChatInputActionsProps['items'] = useMemo(
+ () =>
+ [
+ {
+ active: editorState.isBold,
+ icon: BoldIcon,
+ key: 'bold',
+ label: t('typobar.bold'),
+ onClick: editorState.bold,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.Bold).keys },
+ },
+ {
+ active: editorState.isItalic,
+ icon: ItalicIcon,
+ key: 'italic',
+ label: t('typobar.italic'),
+ onClick: editorState.italic,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.Italic).keys },
+ },
+ {
+ active: editorState.isUnderline,
+ icon: UnderlineIcon,
+ key: 'underline',
+ label: t('typobar.underline'),
+ onClick: editorState.underline,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.Underline).keys },
+ },
+ {
+ active: editorState.isStrikethrough,
+ icon: StrikethroughIcon,
+ key: 'strikethrough',
+ label: t('typobar.strikethrough'),
+ onClick: editorState.strikethrough,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.Strikethrough).keys },
+ },
+ {
+ type: 'divider',
+ },
+
+ {
+ icon: ListIcon,
+ key: 'bulletList',
+ label: t('typobar.bulletList'),
+ onClick: editorState.bulletList,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.BulletList).keys },
+ },
+ {
+ icon: ListOrderedIcon,
+ key: 'numberlist',
+ label: t('typobar.numberList'),
+ onClick: editorState.numberList,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.NumberList).keys },
+ },
+ {
+ icon: ListTodoIcon,
+ key: 'tasklist',
+ label: t('typobar.taskList'),
+ onClick: editorState.checkList,
+ },
+ {
+ type: 'divider',
+ },
+ {
+ active: editorState.isBlockquote,
+ icon: MessageSquareQuote,
+ key: 'blockquote',
+ label: t('typobar.blockquote'),
+ onClick: editorState.blockquote,
+ },
+ {
+ type: 'divider',
+ },
+ {
+ icon: SigmaIcon,
+ key: 'math',
+ label: t('typobar.tex'),
+ onClick: editorState.insertMath,
+ },
+ {
+ active: editorState.isCode,
+ icon: CodeXmlIcon,
+ key: 'code',
+ label: t('typobar.code'),
+ onClick: editorState.code,
+ tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.CodeInline).keys },
+ },
+ {
+ icon: SquareDashedBottomCodeIcon,
+ key: 'codeblock',
+ label: t('typobar.codeblock'),
+ onClick: editorState.codeblock,
+ },
+ editorState.isCodeblock && {
+ children: (
+ <CodeLanguageSelect
+ onSelect={(value) => editorState.updateCodeblockLang(value)}
+ value={editorState.codeblockLang}
+ />
+ ),
+ disabled: !editorState.isCodeblock,
+ key: 'codeblockLang',
+ },
+ ].filter(Boolean) as ChatInputActionsProps['items'],
+ [editorState],
+ );
+
+ return (
+ <ChatInputActionBar
+ left={<ChatInputActions items={items} />}
+ style={{
+ background: theme.colorFillQuaternary,
+ borderTopLeftRadius: 8,
+ borderTopRightRadius: 8,
+ }}
+ />
+ );
+});
+
+TypoBar.displayName = 'TypoBar';
+
+export default TypoBar;
diff --git a/src/app/[variants]/(main)/memory/features/EditableModal/index.tsx b/src/app/[variants]/(main)/memory/features/EditableModal/index.tsx
new file mode 100644
index 00000000000..820ac19510b
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/features/EditableModal/index.tsx
@@ -0,0 +1,128 @@
+import {
+ ReactCodePlugin,
+ ReactCodeblockPlugin,
+ ReactHRPlugin,
+ ReactLinkHighlightPlugin,
+ ReactListPlugin,
+ ReactMathPlugin,
+ ReactTablePlugin,
+} from '@lobehub/editor';
+import { Editor, useEditor } from '@lobehub/editor/react';
+import { Modal } from '@lobehub/ui';
+import { memo, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { useUserStore } from '@/store/user';
+import { labPreferSelectors } from '@/store/user/slices/preference/selectors';
+import { useUserMemoryStore } from '@/store/userMemory';
+import { LayersEnum } from '@/types/userMemory';
+
+import TypoBar from './Typobar';
+
+const EditableModal = memo(() => {
+ const { t } = useTranslation('common');
+ const editor = useEditor();
+ const [confirmLoading, setConfirmLoading] = useState(false);
+ const editingMemoryId = useUserMemoryStore((s) => s.editingMemoryId);
+ const editingMemoryContent = useUserMemoryStore((s) => s.editingMemoryContent);
+ const editingMemoryLayer = useUserMemoryStore((s) => s.editingMemoryLayer);
+ const clearEditingMemory = useUserMemoryStore((s) => s.clearEditingMemory);
+ const updateMemory = useUserMemoryStore((s) => s.updateMemory);
+
+ const enableRichRender = useUserStore(labPreferSelectors.enableInputMarkdown);
+
+ const richRenderProps = useMemo(
+ () =>
+ !enableRichRender
+ ? {
+ enablePasteMarkdown: false,
+ markdownOption: {
+ bold: false,
+ code: false,
+ header: false,
+ italic: false,
+ quote: false,
+ strikethrough: false,
+ underline: false,
+ underlineStrikethrough: false,
+ },
+ }
+ : {
+ plugins: [
+ ReactListPlugin,
+ ReactCodePlugin,
+ ReactCodeblockPlugin,
+ ReactHRPlugin,
+ ReactLinkHighlightPlugin,
+ ReactTablePlugin,
+ ReactMathPlugin,
+ ],
+ },
+ [enableRichRender],
+ );
+
+ const layerMap = {
+ context: LayersEnum.Context,
+ experience: LayersEnum.Experience,
+ identity: LayersEnum.Identity,
+ preference: LayersEnum.Preference,
+ };
+
+ return (
+ <Modal
+ cancelText={t('cancel')}
+ closable={false}
+ confirmLoading={confirmLoading}
+ destroyOnHidden
+ okText={t('ok')}
+ onCancel={clearEditingMemory}
+ onOk={async () => {
+ if (!editor || !editingMemoryId || !editingMemoryLayer) return;
+ setConfirmLoading(true);
+ const newValue = editor.getDocument('markdown') as unknown as string;
+ await updateMemory(editingMemoryId, newValue, layerMap[editingMemoryLayer]);
+ setConfirmLoading(false);
+ }}
+ open={!!editingMemoryId}
+ styles={{
+ body: {
+ overflow: 'hidden',
+ padding: 0,
+ },
+ }}
+ title={null}
+ width={'min(90vw, 960px)'}
+ >
+ <TypoBar editor={editor} />
+ <Flexbox
+ onClick={() => {
+ editor.focus();
+ }}
+ paddingBlock={16}
+ paddingInline={48}
+ style={{ cursor: 'text', maxHeight: '80vh', minHeight: '50vh', overflowY: 'auto' }}
+ >
+ <Editor
+ autoFocus
+ content={''}
+ editor={editor}
+ onInit={(editor) => {
+ if (!editor) return;
+ try {
+ editor?.setDocument('markdown', editingMemoryContent);
+ } catch {}
+ }}
+ style={{
+ paddingBottom: 120,
+ }}
+ type={'text'}
+ variant={'chat'}
+ {...richRenderProps}
+ />
+ </Flexbox>
+ </Modal>
+ );
+});
+
+export default EditableModal;
diff --git a/src/app/[variants]/(main)/memory/features/FilterBar.tsx b/src/app/[variants]/(main)/memory/features/FilterBar.tsx
new file mode 100644
index 00000000000..3dbfca0a5e8
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/features/FilterBar.tsx
@@ -0,0 +1,53 @@
+import { Icon, SearchBar, Select } from '@lobehub/ui';
+import { ArrowDownNarrowWide, Search } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+interface SortOption {
+ label: string;
+ value: string;
+}
+
+interface FilterBarProps {
+ onSearch: (value: string) => void;
+ onSortChange?: (sort: string) => void;
+ searchValue: string;
+ sortOptions?: SortOption[];
+ sortValue?: string;
+}
+
+const FilterBar = memo<FilterBarProps>(
+ ({ searchValue, onSearch, sortValue, onSortChange, sortOptions }) => {
+ const { t } = useTranslation('memory');
+
+ return (
+ <Flexbox align={'center'} gap={12} horizontal>
+ <SearchBar
+ allowClear
+ defaultValue={searchValue}
+ onInputChange={(v) => {
+ if (!v) {
+ onSearch(v);
+ }
+ }}
+ onSearch={(v) => onSearch(v)}
+ placeholder={t('filter.search')}
+ prefix={<Search size={16} />}
+ style={{ flex: 1 }}
+ />
+ {sortOptions && sortOptions.length > 0 && onSortChange && (
+ <Select
+ onChange={(value) => onSortChange(value as string)}
+ options={sortOptions}
+ prefix={<Icon icon={ArrowDownNarrowWide} style={{ marginRight: 4 }} />}
+ style={{ minWidth: 150 }}
+ value={sortValue}
+ />
+ )}
+ </Flexbox>
+ );
+ },
+);
+
+export default FilterBar;
diff --git a/src/app/[variants]/(main)/memory/features/GridView/GridCard.tsx b/src/app/[variants]/(main)/memory/features/GridView/GridCard.tsx
new file mode 100644
index 00000000000..fd466c01448
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/features/GridView/GridCard.tsx
@@ -0,0 +1,190 @@
+import { Block, Tag, Text } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { ReactNode, memo } from 'react';
+import { Center, Flexbox } from 'react-layout-kit';
+
+import HashTags from '../HashTags';
+import Time from '../Time';
+import { useCateColor } from '../useCateColor';
+
+const ACTION_CLASSNAME = 'memory-masonry-actions';
+
+const useStyles = createStyles(({ css, token }) => ({
+ actions: css`
+ transition: opacity 0.15s ease;
+ `,
+ masonryCard: css`
+ cursor: pointer;
+ position: relative;
+ background: ${token.colorFillQuaternary};
+ box-shadow: 0 0 0 1px ${token.colorFillTertiary} inset;
+ .${ACTION_CLASSNAME} {
+ opacity: 0;
+ }
+
+ &:hover {
+ .${ACTION_CLASSNAME} {
+ opacity: 1;
+ }
+ }
+ `,
+}));
+
+interface GridCardProps {
+ actions?: ReactNode;
+ badges?: ReactNode;
+ cate?: string | null;
+ children?: ReactNode;
+ footer?: ReactNode;
+ hashTags?: string[] | null;
+ onClick?: () => void;
+ title?: ReactNode;
+ titleAddon?: ReactNode;
+ updatedAt?: Date | number | string;
+}
+
+const GridCard = memo<GridCardProps>(
+ ({
+ title,
+ titleAddon,
+ cate,
+ children,
+ actions,
+ onClick,
+ hashTags,
+ badges,
+ footer,
+ updatedAt,
+ }) => {
+ const { theme, cx, styles } = useStyles();
+ const cateColor = useCateColor(cate);
+ return (
+ <Block
+ className={styles.masonryCard}
+ gap={4}
+ height={'100%'}
+ onClick={onClick}
+ padding={4}
+ style={{
+ background: cateColor?.backgroundColor,
+ }}
+ variant={'filled'}
+ >
+ <Block
+ flex={1}
+ gap={12}
+ paddingBlock={16}
+ paddingInline={12}
+ style={{
+ boxShadow: `0 4px 16px -4px ${cateColor?.shadowColor || 'rgba(0, 0, 0, 0.2)'}`,
+ overflow: 'hidden',
+ position: 'relative',
+ }}
+ variant={'outlined'}
+ >
+ {(title || titleAddon) && (
+ <>
+ <Flexbox align={'center'} gap={8} horizontal wrap={'wrap'}>
+ {title && typeof title === 'string' ? (
+ <Text
+ as={'h2'}
+ ellipsis={{ rows: 2 }}
+ fontSize={16}
+ style={{ lineHeight: 1.5, margin: 0 }}
+ weight={500}
+ >
+ {title}
+ </Text>
+ ) : (
+ title
+ )}
+ </Flexbox>
+ {typeof titleAddon === 'string' ? (
+ <Tag variant="borderless">{titleAddon}</Tag>
+ ) : (
+ titleAddon
+ )}
+ </>
+ )}
+ {typeof children === 'string' ? (
+ <Text as={'p'} color={theme.colorTextSecondary} ellipsis={{ rows: 4 }}>
+ {children}
+ </Text>
+ ) : (
+ children
+ )}
+ <HashTags hashTags={hashTags} />
+ <Flexbox
+ align={'center'}
+ gap={12}
+ horizontal
+ justify={'space-between'}
+ style={{
+ overflow: 'hidden',
+ position: 'relative',
+ }}
+ >
+ {footer}
+ <Time updatedAt={updatedAt} />
+ </Flexbox>
+ </Block>
+ <Flexbox
+ align={'center'}
+ horizontal
+ justify={'space-between'}
+ paddingBlock={8}
+ paddingInline={8}
+ style={{ overflow: 'hidden', position: 'relative' }}
+ width={'100%'}
+ >
+ <Flexbox
+ align={'center'}
+ flex={1}
+ gap={8}
+ horizontal
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ }}
+ style={{
+ overflow: 'hidden',
+ }}
+ >
+ {badges}
+ </Flexbox>
+ <Center flex={'none'}>
+ <Text
+ align={'center'}
+ color={cateColor?.backgroundTextColor || theme.colorTextSecondary}
+ style={{
+ opacity: 0.5,
+ }}
+ weight={'bold'}
+ >
+ {cate?.toUpperCase() || 'CHORE'}
+ </Text>
+ </Center>
+ <Flexbox
+ align={'center'}
+ className={cx(ACTION_CLASSNAME, styles.actions)}
+ flex={1}
+ gap={4}
+ horizontal
+ justify={'flex-end'}
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ }}
+ style={{
+ overflow: 'hidden',
+ }}
+ >
+ {actions}
+ </Flexbox>
+ </Flexbox>
+ </Block>
+ );
+ },
+);
+
+export default GridCard;
diff --git a/src/app/[variants]/(main)/memory/features/GridView/index.tsx b/src/app/[variants]/(main)/memory/features/GridView/index.tsx
new file mode 100644
index 00000000000..8249cc63877
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/features/GridView/index.tsx
@@ -0,0 +1,95 @@
+import { DivProps, Grid } from '@lobehub/ui';
+import { ReactNode, forwardRef, memo } from 'react';
+import { VirtuosoGrid } from 'react-virtuoso';
+
+import Loading from '@/app/[variants]/(main)/memory/features/Loading';
+
+import { useScrollParent } from '../TimeLineView/useScrollParent';
+
+interface GridViewProps<T> {
+ /**
+ * Default column count (rows in Grid component)
+ * Will be responsive based on window width
+ */
+ defaultColumnCount?: number;
+ /**
+ * Whether there are more items to load
+ */
+ hasMore?: boolean;
+ /**
+ * Whether data is currently loading
+ */
+ isLoading?: boolean;
+ items: T[];
+ /**
+ * Max item width in pixels
+ */
+ maxItemWidth?: number;
+ /**
+ * Callback when end is reached
+ */
+ onLoadMore?: () => void;
+ renderItem: (item: T, actions: ItemActions<T>) => ReactNode;
+}
+
+interface ItemActions<T> {
+ onClick?: (item: T) => void;
+ onDelete?: (id: string) => void;
+ onEdit?: (id: string) => void;
+}
+
+function GridViewInner<T extends { id: string }>({
+ items,
+ defaultColumnCount = 3,
+ maxItemWidth = 240,
+ hasMore,
+ isLoading,
+ onLoadMore,
+ renderItem,
+}: GridViewProps<T>) {
+ const scrollParent = useScrollParent();
+
+ if (!items || items.length === 0) {
+ return null;
+ }
+
+ return (
+ <VirtuosoGrid
+ components={{
+ Footer: isLoading
+ ? () => <Loading rows={defaultColumnCount} viewMode={'grid'} />
+ : undefined,
+ List: forwardRef<HTMLDivElement, DivProps>((props, ref) => (
+ <Grid
+ gap={8}
+ maxItemWidth={maxItemWidth}
+ ref={ref}
+ rows={defaultColumnCount}
+ {...props}
+ />
+ )),
+ }}
+ customScrollParent={scrollParent}
+ data={items}
+ endReached={hasMore && onLoadMore ? onLoadMore : undefined}
+ increaseViewportBy={typeof window !== 'undefined' ? window.innerHeight : 0}
+ itemContent={(index, item) => {
+ if (!item || !item.id) {
+ return null;
+ }
+
+ const actions: ItemActions<T> = {
+ onClick: undefined,
+ onDelete: undefined,
+ onEdit: undefined,
+ };
+
+ return renderItem(item, actions);
+ }}
+ overscan={48}
+ style={{ minHeight: '100%' }}
+ />
+ );
+}
+
+export const GridView = memo(GridViewInner) as typeof GridViewInner;
diff --git a/src/app/[variants]/(main)/memory/features/HashTags.tsx b/src/app/[variants]/(main)/memory/features/HashTags.tsx
new file mode 100644
index 00000000000..d897c1f1f47
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/features/HashTags.tsx
@@ -0,0 +1,38 @@
+import { Icon, Tag } from '@lobehub/ui';
+import { useTheme } from 'antd-style';
+import { HashIcon } from 'lucide-react';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+interface HashTagsProps {
+ hashTags?: string[] | null;
+}
+
+const HashTags = memo<HashTagsProps>(({ hashTags }) => {
+ const theme = useTheme();
+ if (!hashTags || hashTags.length === 0) return;
+ return (
+ hashTags &&
+ hashTags.length > 0 && (
+ <Flexbox horizontal wrap="wrap">
+ {hashTags.map((tag, index) => (
+ <Tag
+ icon={<Icon icon={HashIcon} />}
+ key={index}
+ style={{
+ color: theme.colorTextDescription,
+ gap: 2,
+ marginRight: 12,
+ paddingInline: 0,
+ }}
+ variant={'borderless'}
+ >
+ {tag}
+ </Tag>
+ ))}
+ </Flexbox>
+ )
+ );
+});
+
+export default HashTags;
diff --git a/src/app/[variants]/(main)/memory/features/HighlightedContent.tsx b/src/app/[variants]/(main)/memory/features/HighlightedContent.tsx
new file mode 100644
index 00000000000..ebe8db51946
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/features/HighlightedContent.tsx
@@ -0,0 +1,37 @@
+import { Markdown, Text } from '@lobehub/ui';
+import { useTheme } from 'antd-style';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+interface HighlightedContentProps {
+ children?: string | null;
+ title?: string | null;
+}
+
+const HighlightedContent = memo<HighlightedContentProps>(({ title, children }) => {
+ const theme = useTheme();
+ if (!children) return;
+ const content = (
+ <Markdown
+ fontSize={14}
+ style={{
+ color: theme.colorText,
+ overflow: 'visible',
+ }}
+ variant={'chat'}
+ >
+ {children || ''}
+ </Markdown>
+ );
+
+ if (!title) return content;
+
+ return (
+ <Flexbox gap={8}>
+ <Text weight={500}>{title}</Text>
+ {content}
+ </Flexbox>
+ );
+});
+
+export default HighlightedContent;
diff --git a/src/app/[variants]/(main)/memory/features/Loading.tsx b/src/app/[variants]/(main)/memory/features/Loading.tsx
new file mode 100644
index 00000000000..6a8aa01f100
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/features/Loading.tsx
@@ -0,0 +1,54 @@
+import { Grid, Skeleton } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { ViewMode } from './ViewModeSwitcher';
+
+const useStyles = createStyles(({ css, token }) => ({
+ card: css`
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+
+ padding: 16px;
+ border: 1px solid ${token.colorBorderSecondary};
+ border-radius: ${token.borderRadiusLG}px;
+
+ background: ${token.colorBgContainer};
+ `,
+}));
+
+const Loading = memo<{ rows?: number; viewMode?: ViewMode }>(({ viewMode, rows = 3 }) => {
+ const { styles } = useStyles();
+
+ if (viewMode === 'timeline') {
+ return (
+ <Flexbox gap={24} paddingBlock={24} style={{ paddingLeft: 32 }}>
+ {Array.from({ length: 3 }).map((_, i) => (
+ <Flexbox gap={8} key={i}>
+ <Skeleton.Title active fontSize={18} lineHeight={1.4} width={'30%'} />
+ <Skeleton.Paragraph active rows={4} style={{ marginBottom: 0 }} />
+ </Flexbox>
+ ))}
+ </Flexbox>
+ );
+ }
+
+ return (
+ <Grid gap={12} maxItemWidth={240} paddingBlock={8} rows={rows}>
+ {Array.from({ length: 6 }).map((_, i) => (
+ <Flexbox className={styles.card} key={i}>
+ <Skeleton.Title active fontSize={16} lineHeight={1.4} width={'80%'} />
+ <Skeleton.Paragraph active rows={5} style={{ marginBottom: 0 }} />
+ <Flexbox gap={8} horizontal>
+ <Skeleton.Button active size={'small'} style={{ height: 20, width: 60 }} />
+ <Skeleton.Button active size={'small'} style={{ height: 20, width: 50 }} />
+ </Flexbox>
+ </Flexbox>
+ ))}
+ </Grid>
+ );
+});
+
+export default Loading;
diff --git a/src/app/[variants]/(main)/memory/features/MemoryEmpty.tsx b/src/app/[variants]/(main)/memory/features/MemoryEmpty.tsx
new file mode 100644
index 00000000000..f2b142de0d0
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/features/MemoryEmpty.tsx
@@ -0,0 +1,28 @@
+import { Empty, EmptyProps } from '@lobehub/ui';
+import { BrainCircuitIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Center } from 'react-layout-kit';
+
+const MemoryEmpty = memo<EmptyProps & { search?: boolean }>(({ search, title, ...rest }) => {
+ const { t } = useTranslation('memory');
+ return (
+ <Center height="100%" style={{ minHeight: '50vh' }} width="100%">
+ <Empty
+ description={search ? t('empty.search') : t('empty.description')}
+ descriptionProps={{
+ fontSize: 14,
+ }}
+ icon={BrainCircuitIcon}
+ style={{
+ maxWidth: 400,
+ }}
+ title={search ? undefined : title || t('empty.title')}
+ type={search ? 'default' : 'page'}
+ {...rest}
+ />
+ </Center>
+ );
+});
+
+export default MemoryEmpty;
diff --git a/src/app/[variants]/(main)/memory/features/ProgressIcon.tsx b/src/app/[variants]/(main)/memory/features/ProgressIcon.tsx
new file mode 100644
index 00000000000..a04769ccb1e
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/features/ProgressIcon.tsx
@@ -0,0 +1,39 @@
+import { Text, Tooltip } from '@lobehub/ui';
+import { Progress, ProgressProps } from 'antd';
+import { useTheme } from 'antd-style';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+interface ProgressIconProps extends Omit<ProgressProps, 'percent'> {
+ percent?: number | null;
+}
+
+const ProgressIcon = memo<ProgressIconProps>(({ showInfo, format, percent, ...rest }) => {
+ const theme = useTheme();
+ if (typeof percent !== 'number') return;
+
+ const content = (
+ <Progress
+ format={format}
+ percent={percent}
+ showInfo={false}
+ size={[2, 12]}
+ steps={5}
+ {...rest}
+ />
+ );
+
+ if (showInfo)
+ return (
+ <Flexbox align={'center'} gap={8} horizontal>
+ {content}
+ <Text color={theme.colorTextSecondary} fontSize={12}>
+ {format?.(percent)}
+ </Text>
+ </Flexbox>
+ );
+
+ return <Tooltip title={format?.(percent)}>{content}</Tooltip>;
+});
+
+export default ProgressIcon;
diff --git a/src/app/[variants]/(main)/memory/features/SourceLink.tsx b/src/app/[variants]/(main)/memory/features/SourceLink.tsx
new file mode 100644
index 00000000000..7fd6ab24c35
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/features/SourceLink.tsx
@@ -0,0 +1,52 @@
+import { Button, Icon, Text } from '@lobehub/ui';
+import { useTheme } from 'antd-style';
+import { Link2 } from 'lucide-react';
+import Link from 'next/link';
+import { memo } from 'react';
+import { useNavigate } from 'react-router-dom';
+
+import { MemorySource } from '@/database/repositories/userMemory';
+
+const SourceLink = memo<{ source?: MemorySource | null }>(({ source }) => {
+ const theme = useTheme();
+ const navigate = useNavigate();
+
+ if (!source) return;
+
+ const title = source.title || source.id?.replace('tpc_', '').slice(0, 8);
+
+ return (
+ <Link
+ href={`/agent/${source.agentId}?topicId=${source.id}`}
+ onClick={(e) => {
+ if (!source) return;
+ e.stopPropagation();
+ e.preventDefault();
+ navigate(`/agent/${source.agentId}?topicId=${source.id}`);
+ }}
+ style={{
+ flex: 1,
+ maxWidth: '100%',
+ overflow: 'hidden',
+ }}
+ >
+ <Button
+ icon={<Icon icon={Link2} />}
+ size={'small'}
+ style={{
+ flex: 1,
+ maxWidth: '100%',
+ overflow: 'hidden',
+ }}
+ title={title}
+ type={'text'}
+ >
+ <Text color={theme.colorTextSecondary} ellipsis>
+ {title}
+ </Text>
+ </Button>
+ </Link>
+ );
+});
+
+export default SourceLink;
diff --git a/src/app/[variants]/(main)/memory/features/Time.tsx b/src/app/[variants]/(main)/memory/features/Time.tsx
new file mode 100644
index 00000000000..b674adb0537
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/features/Time.tsx
@@ -0,0 +1,27 @@
+import { Text } from '@lobehub/ui';
+import dayjs from 'dayjs';
+import relativeTime from 'dayjs/plugin/relativeTime';
+import { memo } from 'react';
+
+dayjs.extend(relativeTime);
+
+interface TimeProps {
+ updatedAt?: Date | number | string;
+}
+
+const Time = memo<TimeProps>(({ updatedAt }) => {
+ if (!updatedAt) return;
+ return (
+ <Text
+ as={'time'}
+ fontSize={12}
+ style={{ display: 'block', flex: 'none' }}
+ title={dayjs(updatedAt).format('YYYY-MM-DD HH:mm')}
+ type={'secondary'}
+ >
+ {dayjs(updatedAt).fromNow()}
+ </Text>
+ );
+});
+
+export default Time;
diff --git a/src/app/[variants]/(main)/memory/features/TimeLineView/PeriodGroup.tsx b/src/app/[variants]/(main)/memory/features/TimeLineView/PeriodGroup.tsx
new file mode 100644
index 00000000000..ce7b49af618
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/features/TimeLineView/PeriodGroup.tsx
@@ -0,0 +1,74 @@
+'use client';
+
+import { Text } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import dayjs from 'dayjs';
+import { ReactNode, memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { GroupBy } from './index';
+
+const useStyles = createStyles(({ css, token }) => ({
+ itemWrapper: css`
+ position: relative;
+ padding-inline-start: 24px;
+ `,
+ periodHeader: css`
+ position: sticky;
+ z-index: 10;
+ inset-block-start: 0;
+
+ color: ${token.colorTextSecondary};
+
+ background: ${token.colorBgContainer};
+ `,
+ timelineDot: css`
+ position: absolute;
+ inset-block-start: 20px;
+ inset-inline-start: 0;
+
+ width: 16px;
+ height: 16px;
+ border: 1px solid ${token.colorBorder};
+ border-radius: 50%;
+
+ background: ${token.colorBgElevated};
+ box-shadow: 0 2px 4px -2px rgba(0, 0, 0, 40%);
+ `,
+}));
+
+interface PeriodHeaderProps {
+ groupBy?: GroupBy;
+
+ periodKey: string;
+}
+
+export const PeriodHeader = memo<PeriodHeaderProps>(({ periodKey, groupBy = 'day' }) => {
+ const { styles } = useStyles();
+
+ const periodName =
+ groupBy === 'month'
+ ? dayjs(`${periodKey}-01`).format('MMMM YYYY')
+ : dayjs(periodKey).format('MMMM D, YYYY');
+
+ return (
+ <Flexbox align={'center'} className={styles.periodHeader} gap={12} horizontal paddingBlock={8}>
+ <Text weight={500}>{periodName}</Text>
+ </Flexbox>
+ );
+});
+
+interface TimelineItemWrapperProps {
+ children: ReactNode;
+}
+
+export const TimelineItemWrapper = memo<TimelineItemWrapperProps>(({ children }) => {
+ const { styles } = useStyles();
+
+ return (
+ <div className={styles.itemWrapper}>
+ <div className={styles.timelineDot} />
+ {children}
+ </div>
+ );
+});
diff --git a/src/app/[variants]/(main)/memory/features/TimeLineView/TimeLineCard.tsx b/src/app/[variants]/(main)/memory/features/TimeLineView/TimeLineCard.tsx
new file mode 100644
index 00000000000..e9bba71fdfe
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/features/TimeLineView/TimeLineCard.tsx
@@ -0,0 +1,112 @@
+import { Block, Icon, Tag, Text } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { Link2 } from 'lucide-react';
+import { ReactNode, memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import CateTag from '../CateTag';
+import HashTags from '../HashTags';
+import Time from '../Time';
+
+const ACTION_CLASSNAME = 'memory-actions';
+
+const useStyles = createStyles(({ css }) => ({
+ actions: css`
+ transition: opacity 0.15s ease;
+ `,
+ timelineCard: css`
+ position: relative;
+ .${ACTION_CLASSNAME} {
+ opacity: 0;
+ }
+
+ &:hover {
+ .${ACTION_CLASSNAME} {
+ opacity: 1;
+ }
+ }
+ `,
+}));
+
+interface TimeLineCardProps {
+ actions?: ReactNode;
+ cate?: string | null;
+ children?: ReactNode;
+ hashTags?: string[] | null;
+ onClick?: () => void;
+ title?: ReactNode;
+ titleAddon?: ReactNode;
+ updatedAt?: Date | number | string;
+}
+
+const TimeLineCard = memo<TimeLineCardProps>(
+ ({ title, titleAddon, cate, children, actions, onClick, updatedAt, hashTags }) => {
+ const { theme, cx, styles } = useStyles();
+ return (
+ <Block
+ className={styles.timelineCard}
+ clickable
+ gap={12}
+ onClick={onClick}
+ padding={16}
+ variant={'borderless'}
+ >
+ {(title || titleAddon) && (
+ <Flexbox
+ align={'center'}
+ gap={4}
+ horizontal
+ style={{
+ overflow: 'hidden',
+ }}
+ width={'100%'}
+ wrap={'wrap'}
+ >
+ {title && typeof title === 'string' ? (
+ <Text as={'h2'} fontSize={16} style={{ lineHeight: 1.5, margin: 0 }} weight={500}>
+ {title}
+ </Text>
+ ) : (
+ title
+ )}
+ {typeof titleAddon === 'string' ? (
+ <Tag icon={<Icon icon={Link2} />} variant="borderless">
+ {titleAddon}
+ </Tag>
+ ) : (
+ titleAddon
+ )}
+ </Flexbox>
+ )}
+ {typeof children === 'string' ? (
+ <Text as={'p'} color={theme.colorTextSecondary} ellipsis={{ rows: 3 }}>
+ {children}
+ </Text>
+ ) : (
+ children
+ )}
+ <HashTags hashTags={hashTags} />
+ <Flexbox align={'center'} gap={8} horizontal justify={'space-between'}>
+ <Flexbox align={'center'} gap={8} horizontal>
+ <CateTag cate={cate} />
+ <Time updatedAt={updatedAt} />
+ </Flexbox>
+ <Flexbox
+ align={'center'}
+ className={cx(ACTION_CLASSNAME, styles.actions)}
+ gap={4}
+ horizontal
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ }}
+ >
+ {actions}
+ </Flexbox>
+ </Flexbox>
+ </Block>
+ );
+ },
+);
+
+export default TimeLineCard;
diff --git a/src/app/[variants]/(main)/memory/features/TimeLineView/index.tsx b/src/app/[variants]/(main)/memory/features/TimeLineView/index.tsx
new file mode 100644
index 00000000000..92ebfe48470
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/features/TimeLineView/index.tsx
@@ -0,0 +1,150 @@
+'use client';
+
+import { createStyles } from 'antd-style';
+import dayjs from 'dayjs';
+import { ReactNode, memo, useMemo } from 'react';
+import { GroupedVirtuoso } from 'react-virtuoso';
+
+import Loading from '@/app/[variants]/(main)/memory/features/Loading';
+
+import { useScrollParent } from './useScrollParent';
+
+const useStyles = createStyles(({ css, token, isDarkMode }) => ({
+ timelineContainer: css`
+ position: relative;
+ height: 100%;
+ `,
+ timelineLine: css`
+ position: absolute;
+ inset-block: 0;
+ inset-inline-start: 8px;
+
+ width: 1px;
+ height: 100%;
+
+ background: ${isDarkMode ? token.colorFillQuaternary : token.colorFillSecondary};
+ `,
+}));
+
+export type GroupBy = 'day' | 'month';
+
+interface TimelineViewProps<T extends { createdAt: Date | string; id: string }> {
+ data: T[];
+ /**
+ * Custom date field extractor for grouping
+ * Used when the date to group by is not `createdAt`
+ */
+ getDateForGrouping?: (item: T) => Date | string;
+ /**
+ * Group items by 'day' (YYYY-MM-DD) or 'month' (YYYY-MM)
+ * @default 'day'
+ */
+ groupBy?: GroupBy;
+ /**
+ * Whether there are more items to load
+ */
+ hasMore?: boolean;
+ /**
+ * Whether data is currently loading
+ */
+ isLoading?: boolean;
+ /**
+ * Callback when end is reached
+ */
+ onLoadMore?: () => void;
+ renderHeader: (periodKey: string, itemCount: number) => ReactNode;
+ renderItem: (item: T) => ReactNode;
+}
+
+function TimelineViewInner<T extends { createdAt: Date | string; id: string }>({
+ data,
+ groupBy = 'day',
+ getDateForGrouping,
+ hasMore,
+ isLoading,
+ onLoadMore,
+ renderHeader,
+ renderItem,
+}: TimelineViewProps<T>) {
+ const { styles } = useStyles();
+ const scrollParent = useScrollParent();
+
+ const { groupCounts, sortedPeriods, groupedItems } = useMemo(() => {
+ const format = groupBy === 'month' ? 'YYYY-MM' : 'YYYY-MM-DD';
+
+ // Group by period
+ const groupedByPeriod = data.reduce(
+ (acc, item) => {
+ const dateValue = getDateForGrouping ? getDateForGrouping(item) : item.createdAt;
+ const date = dayjs(dateValue);
+ const periodKey = date.format(format);
+
+ if (!acc[periodKey]) {
+ acc[periodKey] = [];
+ }
+ acc[periodKey].push(item);
+ return acc;
+ },
+ {} as Record<string, T[]>,
+ );
+
+ // Sort periods descending
+ const periods = Object.keys(groupedByPeriod).sort((a, b) => b.localeCompare(a));
+
+ // Create group counts and sorted items
+ const counts: number[] = [];
+ const items: T[] = [];
+
+ for (const periodKey of periods) {
+ const periodData = groupedByPeriod[periodKey];
+
+ // Sort items within period by date descending
+ const sortedItems = [...periodData].sort((a, b) => {
+ const dateA = getDateForGrouping ? getDateForGrouping(a) : a.createdAt;
+ const dateB = getDateForGrouping ? getDateForGrouping(b) : b.createdAt;
+ return dayjs(dateB).valueOf() - dayjs(dateA).valueOf();
+ });
+
+ counts.push(sortedItems.length);
+ items.push(...sortedItems);
+ }
+
+ return {
+ groupCounts: counts,
+ groupedItems: items,
+ sortedPeriods: periods,
+ };
+ }, [data, groupBy, getDateForGrouping]);
+
+ if (!data || data.length === 0) {
+ return null;
+ }
+
+ return (
+ <div className={styles.timelineContainer}>
+ <div className={styles.timelineLine} />
+ <GroupedVirtuoso
+ components={{
+ Footer: isLoading ? () => <Loading viewMode={'timeline'} /> : undefined,
+ }}
+ customScrollParent={scrollParent}
+ endReached={hasMore && onLoadMore ? onLoadMore : undefined}
+ groupContent={(index) => {
+ const periodKey = sortedPeriods[index];
+ const itemCount = groupCounts[index];
+ return renderHeader(periodKey, itemCount);
+ }}
+ groupCounts={groupCounts}
+ increaseViewportBy={typeof window !== 'undefined' ? window.innerHeight : 0}
+ itemContent={(index) => {
+ const item = groupedItems[index];
+ return renderItem(item);
+ }}
+ overscan={24}
+ style={{ minHeight: '100%' }}
+ />
+ </div>
+ );
+}
+
+export const TimelineView = memo(TimelineViewInner) as typeof TimelineViewInner;
diff --git a/src/app/[variants]/(main)/memory/features/TimeLineView/useScrollParent.ts b/src/app/[variants]/(main)/memory/features/TimeLineView/useScrollParent.ts
new file mode 100644
index 00000000000..cf8dbc19ce1
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/features/TimeLineView/useScrollParent.ts
@@ -0,0 +1,19 @@
+import { useEffect, useState } from 'react';
+
+import { isOnServerSide } from '@/utils/env';
+
+export const SCROLL_PARENT_ID = 'memory-scroll';
+
+export const useScrollParent = () => {
+ const [parent, setParent] = useState<HTMLDivElement>();
+
+ useEffect(() => {
+ if (isOnServerSide) return;
+ const scrollParent = document.querySelector(`#${SCROLL_PARENT_ID}`);
+ if (scrollParent) {
+ setParent(scrollParent as HTMLDivElement);
+ }
+ }, []);
+
+ return parent;
+};
diff --git a/src/app/[variants]/(main)/memory/features/ViewModeSwitcher.tsx b/src/app/[variants]/(main)/memory/features/ViewModeSwitcher.tsx
new file mode 100644
index 00000000000..7314c252945
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/features/ViewModeSwitcher.tsx
@@ -0,0 +1,40 @@
+'use client';
+
+import { ActionIcon } from '@lobehub/ui';
+import { CalendarDaysIcon, LayoutDashboardIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
+
+export type ViewMode = 'timeline' | 'grid';
+
+interface ViewModeSwitcherProps {
+ onChange: (mode: ViewMode) => void;
+ value: ViewMode;
+}
+
+const ViewModeSwitcher = memo<ViewModeSwitcherProps>(({ value, onChange }) => {
+ const { t } = useTranslation('memory');
+
+ return (
+ <>
+ <ActionIcon
+ active={value === 'timeline'}
+ icon={CalendarDaysIcon}
+ onClick={() => onChange('timeline')}
+ size={DESKTOP_HEADER_ICON_SIZE}
+ title={t('viewMode.timeline')}
+ />
+ <ActionIcon
+ active={value === 'grid'}
+ icon={LayoutDashboardIcon}
+ onClick={() => onChange('grid')}
+ size={DESKTOP_HEADER_ICON_SIZE}
+ title={t('viewMode.masonry')}
+ />
+ </>
+ );
+});
+
+export default ViewModeSwitcher;
diff --git a/src/app/[variants]/(main)/memory/features/useCateColor.ts b/src/app/[variants]/(main)/memory/features/useCateColor.ts
new file mode 100644
index 00000000000..286f5f8acf8
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/features/useCateColor.ts
@@ -0,0 +1,56 @@
+import { useTheme } from 'antd-style';
+import { darken, lighten, mix, rgba, saturate } from 'polished';
+import { useMemo } from 'react';
+
+function getStableRandom(str: string, min = 0, max = 100) {
+ if (min > max) {
+ return 0;
+ }
+
+ let hash = 0;
+ for (let i = 0; i < str.length; i++) {
+ const char = str.charCodeAt(i);
+ hash = (hash << 5) - hash + char;
+ hash = hash & hash;
+ }
+
+ hash = Math.abs(hash);
+ const range = max - min + 1;
+ return min + (hash % range);
+}
+
+export const useCateColor = (cate?: string | null) => {
+ const theme = useTheme();
+
+ const colors = [
+ theme.volcano,
+ theme.orange,
+ theme.gold,
+ theme.green,
+ theme.cyan,
+ theme.blue,
+ theme.geekblue,
+ theme.purple,
+ theme.magenta,
+ theme.pink,
+ ];
+
+ return useMemo(() => {
+ if (!cate) return undefined;
+ const index = getStableRandom(cate, 0, colors.length - 1);
+ const color = saturate(
+ theme.isDarkMode ? 0.25 : 0.5,
+ mix(
+ theme.isDarkMode ? 0.06 : 0.05,
+ colors[index],
+ theme.isDarkMode ? theme.colorBgContainer : theme.colorBgLayout,
+ ),
+ );
+ return {
+ backgroundColor: color,
+ backgroundTextColor: theme.isDarkMode ? lighten(0.5, color) : darken(0.5, color),
+ color: theme.isDarkMode ? lighten(0.4, color) : darken(0.6, color),
+ shadowColor: rgba(darken(0.6, color), theme.isDarkMode ? 0.5 : 0.2),
+ };
+ }, [cate, colors, theme]);
+};
diff --git a/src/app/[variants]/(main)/memory/identities/features/IdentityDropdown.tsx b/src/app/[variants]/(main)/memory/identities/features/IdentityDropdown.tsx
new file mode 100644
index 00000000000..26f1b0517d9
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/identities/features/IdentityDropdown.tsx
@@ -0,0 +1,66 @@
+import { ActionIcon, ActionIconProps, Dropdown } from '@lobehub/ui';
+import { App } from 'antd';
+import { MoreHorizontal, Pencil, Trash2 } from 'lucide-react';
+import { KeyboardEvent, MouseEvent, memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useUserMemoryStore } from '@/store/userMemory';
+
+interface IdentityDropdownProps {
+ id: string;
+ size?: ActionIconProps['size'];
+}
+
+const IdentityDropdown = memo<IdentityDropdownProps>(({ id, size = 'small' }) => {
+ const { t } = useTranslation(['memory', 'common']);
+ const { modal } = App.useApp();
+
+ const identities = useUserMemoryStore((s) => s.identities);
+ const deleteIdentity = useUserMemoryStore((s) => s.deleteIdentity);
+ const setEditingMemory = useUserMemoryStore((s) => s.setEditingMemory);
+
+ const handleMenuClick = (info: { domEvent: MouseEvent | KeyboardEvent; key: string }) => {
+ info.domEvent.stopPropagation();
+
+ if (info.key === 'edit') {
+ const identity = identities.find((i) => i.id === id);
+ if (identity) {
+ setEditingMemory(id, identity.description || '', 'identity');
+ }
+ } else if (info.key === 'delete') {
+ modal.confirm({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: t('identity.list.deleteContent'),
+ okButtonProps: { danger: true },
+ okText: t('delete', { ns: 'common' }),
+ onOk: async () => {
+ await deleteIdentity(id);
+ },
+ title: t('identity.list.confirmDelete'),
+ type: 'warning',
+ });
+ }
+ };
+
+ const menuItems = [
+ {
+ icon: <Pencil size={14} />,
+ key: 'edit',
+ label: t('edit', { ns: 'common' }),
+ },
+ {
+ danger: true,
+ icon: <Trash2 size={14} />,
+ key: 'delete',
+ label: t('delete', { ns: 'common' }),
+ },
+ ];
+
+ return (
+ <Dropdown menu={{ items: menuItems, onClick: handleMenuClick }} trigger={['click']}>
+ <ActionIcon icon={MoreHorizontal} size={size} />
+ </Dropdown>
+ );
+});
+
+export default IdentityDropdown;
diff --git a/src/app/[variants]/(main)/memory/identities/features/IdentityRightPanel.tsx b/src/app/[variants]/(main)/memory/identities/features/IdentityRightPanel.tsx
new file mode 100644
index 00000000000..ce61a7fbc7b
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/identities/features/IdentityRightPanel.tsx
@@ -0,0 +1,64 @@
+'use client';
+
+import { Text } from '@lobehub/ui';
+import { memo } from 'react';
+
+import CateTag from '@/app/[variants]/(main)/memory/features/CateTag';
+import DetailLoading from '@/app/[variants]/(main)/memory/features/DetailLoading';
+import DetailPanel from '@/app/[variants]/(main)/memory/features/DetailPanel';
+import HashTags from '@/app/[variants]/(main)/memory/features/HashTags';
+import HighlightedContent from '@/app/[variants]/(main)/memory/features/HighlightedContent';
+import Time from '@/app/[variants]/(main)/memory/features/Time';
+import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
+import { useQueryState } from '@/hooks/useQueryParam';
+import { useUserMemoryStore } from '@/store/userMemory';
+import { LayersEnum } from '@/types/userMemory';
+
+import IdentityDropdown from './IdentityDropdown';
+
+const IdentityRightPanel = memo(() => {
+ const [identityId] = useQueryState('identityId', { clearOnDefault: true });
+ const useFetchMemoryDetail = useUserMemoryStore((s) => s.useFetchMemoryDetail);
+
+ const { data: identity, isLoading } = useFetchMemoryDetail(identityId, LayersEnum.Identity);
+
+ if (!identityId) return null;
+
+ let content;
+ if (isLoading) content = <DetailLoading />;
+ if (identity) {
+ content = (
+ <>
+ <CateTag cate={identity.type} />
+ <Text
+ as={'h1'}
+ fontSize={20}
+ style={{
+ lineHeight: 1.4,
+ marginBottom: 0,
+ }}
+ weight={'bold'}
+ >
+ {identity.role || identity.relationship || 'Identity'}
+ </Text>
+ <Time updatedAt={identity.updatedAt || identity.createdAt} />
+ {identity.description && <HighlightedContent>{identity.description}</HighlightedContent>}
+ <HashTags hashTags={identity.tags} />
+ </>
+ );
+ }
+
+ return (
+ <DetailPanel
+ header={{
+ right: identityId ? (
+ <IdentityDropdown id={identityId} size={DESKTOP_HEADER_ICON_SIZE} />
+ ) : undefined,
+ }}
+ >
+ {content}
+ </DetailPanel>
+ );
+});
+
+export default IdentityRightPanel;
diff --git a/src/app/[variants]/(main)/memory/identities/features/List/GridView/IdentityCard.tsx b/src/app/[variants]/(main)/memory/identities/features/List/GridView/IdentityCard.tsx
new file mode 100644
index 00000000000..5a5fe4a18e1
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/identities/features/List/GridView/IdentityCard.tsx
@@ -0,0 +1,27 @@
+import { memo } from 'react';
+
+import GridCard from '@/app/[variants]/(main)/memory/features/GridView/GridCard';
+import { DisplayIdentityMemory } from '@/database/repositories/userMemory';
+
+import IdentityDropdown from '../../IdentityDropdown';
+
+interface IdentityCardProps {
+ identity: DisplayIdentityMemory;
+ onClick?: (identity: DisplayIdentityMemory) => void;
+}
+
+const IdentityCard = memo<IdentityCardProps>(({ identity, onClick }) => {
+ return (
+ <GridCard
+ actions={<IdentityDropdown id={identity.id} />}
+ cate={identity.type}
+ hashTags={identity.tags}
+ onClick={() => onClick?.(identity)}
+ title={identity.role}
+ >
+ {identity.description}
+ </GridCard>
+ );
+});
+
+export default IdentityCard;
diff --git a/src/app/[variants]/(main)/memory/identities/features/List/GridView/index.tsx b/src/app/[variants]/(main)/memory/identities/features/List/GridView/index.tsx
new file mode 100644
index 00000000000..191529e691b
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/identities/features/List/GridView/index.tsx
@@ -0,0 +1,32 @@
+import { memo } from 'react';
+
+import { DisplayIdentityMemory } from '@/database/repositories/userMemory';
+import { useUserMemoryStore } from '@/store/userMemory';
+
+import { GridView } from '../../../../features/GridView';
+import IdentityCard from './IdentityCard';
+
+interface GridViewProps {
+ identities: DisplayIdentityMemory[];
+ isLoading?: boolean;
+ onClick?: (identity: DisplayIdentityMemory) => void;
+}
+
+const IdentityGridView = memo<GridViewProps>(({ identities, isLoading, onClick }) => {
+ const loadMoreIdentities = useUserMemoryStore((s) => s.loadMoreIdentities);
+ const identitiesHasMore = useUserMemoryStore((s) => s.identitiesHasMore);
+
+ return (
+ <GridView
+ hasMore={identitiesHasMore}
+ isLoading={isLoading}
+ items={identities}
+ onLoadMore={loadMoreIdentities}
+ renderItem={(identity) => (
+ <IdentityCard identity={identity} onClick={() => onClick?.(identity)} />
+ )}
+ />
+ );
+});
+
+export default IdentityGridView;
diff --git a/src/app/[variants]/(main)/memory/identities/features/List/TimelineView/IdentityCard.tsx b/src/app/[variants]/(main)/memory/identities/features/List/TimelineView/IdentityCard.tsx
new file mode 100644
index 00000000000..a071fb5f15f
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/identities/features/List/TimelineView/IdentityCard.tsx
@@ -0,0 +1,28 @@
+import { memo } from 'react';
+
+import TimeLineCard from '@/app/[variants]/(main)/memory/features/TimeLineView/TimeLineCard';
+import { DisplayIdentityMemory } from '@/database/repositories/userMemory';
+
+import IdentityDropdown from '../../IdentityDropdown';
+
+interface IdentityCardProps {
+ identity: DisplayIdentityMemory;
+ onClick?: (identity: DisplayIdentityMemory) => void;
+}
+
+const IdentityCard = memo<IdentityCardProps>(({ identity, onClick }) => {
+ return (
+ <TimeLineCard
+ actions={<IdentityDropdown id={identity.id} />}
+ cate={identity.type}
+ hashTags={identity.tags}
+ onClick={() => onClick?.(identity)}
+ title={identity.role}
+ updatedAt={identity.updatedAt || identity.createdAt}
+ >
+ {identity.description}
+ </TimeLineCard>
+ );
+});
+
+export default IdentityCard;
diff --git a/src/app/[variants]/(main)/memory/identities/features/List/TimelineView/index.tsx b/src/app/[variants]/(main)/memory/identities/features/List/TimelineView/index.tsx
new file mode 100644
index 00000000000..24d85ab2669
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/identities/features/List/TimelineView/index.tsx
@@ -0,0 +1,38 @@
+import { memo } from 'react';
+
+import { DisplayIdentityMemory } from '@/database/repositories/userMemory';
+import { useUserMemoryStore } from '@/store/userMemory';
+
+import { TimelineView as GenericTimelineView } from '../../../../features/TimeLineView';
+import { PeriodHeader, TimelineItemWrapper } from '../../../../features/TimeLineView/PeriodGroup';
+import IdentityCard from './IdentityCard';
+
+interface TimelineViewProps {
+ identities: DisplayIdentityMemory[];
+ isLoading?: boolean;
+ onClick?: (identity: DisplayIdentityMemory) => void;
+}
+
+const TimelineView = memo<TimelineViewProps>(({ identities, isLoading, onClick }) => {
+ const loadMoreIdentities = useUserMemoryStore((s) => s.loadMoreIdentities);
+ const identitiesHasMore = useUserMemoryStore((s) => s.identitiesHasMore);
+
+ return (
+ <GenericTimelineView
+ data={identities}
+ getDateForGrouping={(identity) => identity.episodicDate || identity.createdAt}
+ groupBy="month"
+ hasMore={identitiesHasMore}
+ isLoading={isLoading}
+ onLoadMore={loadMoreIdentities}
+ renderHeader={(periodKey) => <PeriodHeader groupBy="month" periodKey={periodKey} />}
+ renderItem={(identity) => (
+ <TimelineItemWrapper>
+ <IdentityCard identity={identity} onClick={() => onClick?.(identity)} />
+ </TimelineItemWrapper>
+ )}
+ />
+ );
+});
+
+export default TimelineView;
diff --git a/src/app/[variants]/(main)/memory/identities/features/List/index.tsx b/src/app/[variants]/(main)/memory/identities/features/List/index.tsx
new file mode 100644
index 00000000000..a3c5003738d
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/identities/features/List/index.tsx
@@ -0,0 +1,41 @@
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useQueryState } from '@/hooks/useQueryParam';
+import { useGlobalStore } from '@/store/global';
+import { useUserMemoryStore } from '@/store/userMemory';
+
+import MemoryEmpty from '../../../features/MemoryEmpty';
+import { ViewMode } from '../../../features/ViewModeSwitcher';
+import GridView from './GridView';
+import TimelineView from './TimelineView';
+
+export type IdentityType = 'all' | 'demographic' | 'personal' | 'professional';
+
+interface IdentitiesListProps {
+ isLoading?: boolean;
+ searchValue?: string;
+ viewMode: ViewMode;
+}
+
+const IdentitiesList = memo<IdentitiesListProps>(({ isLoading, searchValue, viewMode }) => {
+ const { t } = useTranslation(['memory', 'common']);
+ const [, setIdentityId] = useQueryState('identityId', { clearOnDefault: true });
+ const toggleRightPanel = useGlobalStore((s) => s.toggleRightPanel);
+ const identities = useUserMemoryStore((s) => s.identities);
+
+ const handleCardClick = (identity: any) => {
+ setIdentityId(identity.id);
+ toggleRightPanel(true);
+ };
+
+ if (!identities || identities.length === 0)
+ return <MemoryEmpty search={Boolean(searchValue)} title={t('identity.empty')} />;
+
+ if (viewMode === 'timeline')
+ return <TimelineView identities={identities} isLoading={isLoading} onClick={handleCardClick} />;
+
+ return <GridView identities={identities} isLoading={isLoading} onClick={handleCardClick} />;
+});
+
+export default IdentitiesList;
diff --git a/src/app/[variants]/(main)/memory/identities/features/SegmentedBar.tsx b/src/app/[variants]/(main)/memory/identities/features/SegmentedBar.tsx
new file mode 100644
index 00000000000..8a3db6c7d84
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/identities/features/SegmentedBar.tsx
@@ -0,0 +1,29 @@
+import { Segmented } from '@lobehub/ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { IdentityType } from './List';
+
+interface SegmentedBarProps {
+ onTypeChange: (type: IdentityType) => void;
+ typeValue: IdentityType;
+}
+
+const SegmentedBar = memo<SegmentedBarProps>(({ typeValue, onTypeChange }) => {
+ const { t } = useTranslation('memory');
+
+ return (
+ <Segmented
+ onChange={(value) => onTypeChange(value as IdentityType)}
+ options={[
+ { label: t('identity.filter.type.all'), value: 'all' },
+ { label: t('identity.filter.type.personal'), value: 'personal' },
+ { label: t('identity.filter.type.professional'), value: 'professional' },
+ { label: t('identity.filter.type.demographic'), value: 'demographic' },
+ ]}
+ value={typeValue}
+ />
+ );
+});
+
+export default SegmentedBar;
diff --git a/src/app/[variants]/(main)/memory/identities/index.tsx b/src/app/[variants]/(main)/memory/identities/index.tsx
new file mode 100644
index 00000000000..45cf9d59c00
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/identities/index.tsx
@@ -0,0 +1,118 @@
+import { Icon, Tag } from '@lobehub/ui';
+import { BrainCircuitIcon } from 'lucide-react';
+import { memo, useCallback, useEffect, useState } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import CommonFilterBar from '@/app/[variants]/(main)/memory/features/FilterBar';
+import NavHeader from '@/features/NavHeader';
+import WideScreenContainer from '@/features/WideScreenContainer';
+import WideScreenButton from '@/features/WideScreenContainer/WideScreenButton';
+import { useQueryState } from '@/hooks/useQueryParam';
+import { useUserMemoryStore } from '@/store/userMemory';
+import { TypesEnum } from '@/types/userMemory';
+
+import EditableModal from '../features/EditableModal';
+import Loading from '../features/Loading';
+import { SCROLL_PARENT_ID } from '../features/TimeLineView/useScrollParent';
+import ViewModeSwitcher, { ViewMode } from '../features/ViewModeSwitcher';
+import IdentityRightPanel from './features/IdentityRightPanel';
+import List, { IdentityType } from './features/List';
+import SegmentedBar from './features/SegmentedBar';
+
+const IdentitiesArea = memo(() => {
+ const [viewMode, setViewMode] = useState<ViewMode>('timeline');
+ const [searchValueRaw, setSearchValueRaw] = useQueryState('q', { clearOnDefault: true });
+ const [typeFilterRaw, setTypeFilterRaw] = useQueryState('type', { clearOnDefault: true });
+
+ const searchValue = searchValueRaw || '';
+ const typeFilter = (typeFilterRaw as IdentityType) || 'all';
+
+ const identitiesPage = useUserMemoryStore((s) => s.identitiesPage);
+ const identitiesInit = useUserMemoryStore((s) => s.identitiesInit);
+ const identitiesTotal = useUserMemoryStore((s) => s.identitiesTotal);
+ const identitiesSearchLoading = useUserMemoryStore((s) => s.identitiesSearchLoading);
+ const useFetchIdentities = useUserMemoryStore((s) => s.useFetchIdentities);
+ const resetIdentitiesList = useUserMemoryStore((s) => s.resetIdentitiesList);
+
+ // 当搜索或类型变化时重置列表
+ useEffect(() => {
+ const types = typeFilter === 'all' ? undefined : [typeFilter as TypesEnum];
+ resetIdentitiesList({ q: searchValue || undefined, types });
+ }, [searchValue, typeFilter]);
+
+ // 调用 SWR hook 获取数据
+ const { isLoading } = useFetchIdentities({
+ page: identitiesPage,
+ pageSize: 12,
+ q: searchValue || undefined,
+ types: typeFilter === 'all' ? undefined : [typeFilter as TypesEnum],
+ });
+
+ // Handle search and type changes
+ const handleSearch = useCallback(
+ (value: string) => {
+ setSearchValueRaw(value || null);
+ },
+ [setSearchValueRaw],
+ );
+
+ const handleTypeChange = useCallback(
+ (type: IdentityType) => {
+ setTypeFilterRaw(type === 'all' ? null : type);
+ },
+ [setTypeFilterRaw],
+ );
+
+ // 显示 loading:搜索/重置中 或 首次加载中
+ const showLoading = identitiesSearchLoading || !identitiesInit;
+
+ return (
+ <Flexbox flex={1} height={'100%'}>
+ <NavHeader
+ left={
+ Boolean(identitiesTotal) && (
+ <Tag icon={<Icon icon={BrainCircuitIcon} />}>{identitiesTotal}</Tag>
+ )
+ }
+ right={
+ <>
+ <ViewModeSwitcher onChange={setViewMode} value={viewMode} />
+ <WideScreenButton />
+ </>
+ }
+ />
+ <Flexbox
+ height={'100%'}
+ id={SCROLL_PARENT_ID}
+ style={{ overflowY: 'auto', paddingBottom: '16vh' }}
+ width={'100%'}
+ >
+ <WideScreenContainer gap={32} paddingBlock={48}>
+ <Flexbox align={'center'} gap={12} horizontal justify={'space-between'}>
+ <SegmentedBar onTypeChange={handleTypeChange} typeValue={typeFilter} />
+ <CommonFilterBar onSearch={handleSearch} searchValue={searchValue} />
+ </Flexbox>
+ {showLoading ? (
+ <Loading viewMode={viewMode} />
+ ) : (
+ <List isLoading={isLoading} searchValue={searchValue} viewMode={viewMode} />
+ )}
+ </WideScreenContainer>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+const Identities = memo(() => {
+ return (
+ <>
+ <Flexbox height={'100%'} horizontal width={'100%'}>
+ <IdentitiesArea />
+ <IdentityRightPanel />
+ </Flexbox>
+ <EditableModal />
+ </>
+ );
+});
+
+export default Identities;
diff --git a/src/app/[variants]/(main)/memory/preferences/features/List/GridView/PreferenceCard.tsx b/src/app/[variants]/(main)/memory/preferences/features/List/GridView/PreferenceCard.tsx
new file mode 100644
index 00000000000..2819d44a837
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/preferences/features/List/GridView/PreferenceCard.tsx
@@ -0,0 +1,41 @@
+import dayjs from 'dayjs';
+import relativeTime from 'dayjs/plugin/relativeTime';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import GridCard from '@/app/[variants]/(main)/memory/features/GridView/GridCard';
+import ProgressIcon from '@/app/[variants]/(main)/memory/features/ProgressIcon';
+import { DisplayPreferenceMemory } from '@/database/repositories/userMemory';
+
+import PreferenceDropdown from '../../PreferenceDropdown';
+
+dayjs.extend(relativeTime);
+
+interface PreferenceCardProps {
+ onClick?: () => void;
+ preference: DisplayPreferenceMemory;
+}
+
+const PreferenceCard = memo<PreferenceCardProps>(({ preference, onClick }) => {
+ const { t } = useTranslation('memory');
+
+ return (
+ <GridCard
+ actions={<PreferenceDropdown id={preference.id} />}
+ badges={
+ <ProgressIcon
+ format={(percent) => `${t('filter.sort.scorePriority')}: ${percent}%`}
+ percent={(preference.scorePriority ?? 0) * 100}
+ />
+ }
+ cate={preference.type}
+ onClick={onClick}
+ title={preference.title}
+ updatedAt={preference.updatedAt || preference.createdAt}
+ >
+ {preference.conclusionDirectives}
+ </GridCard>
+ );
+});
+
+export default PreferenceCard;
diff --git a/src/app/[variants]/(main)/memory/preferences/features/List/GridView/index.tsx b/src/app/[variants]/(main)/memory/preferences/features/List/GridView/index.tsx
new file mode 100644
index 00000000000..8f8abe1ac47
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/preferences/features/List/GridView/index.tsx
@@ -0,0 +1,32 @@
+import { memo } from 'react';
+
+import { DisplayPreferenceMemory } from '@/database/repositories/userMemory';
+import { useUserMemoryStore } from '@/store/userMemory';
+
+import { GridView } from '../../../../features/GridView';
+import PreferenceCard from './PreferenceCard';
+
+interface GridViewProps {
+ isLoading?: boolean;
+ onClick: (preference: DisplayPreferenceMemory) => void;
+ preferences: DisplayPreferenceMemory[];
+}
+
+const PreferenceGridView = memo<GridViewProps>(({ preferences, isLoading, onClick }) => {
+ const loadMorePreferences = useUserMemoryStore((s) => s.loadMorePreferences);
+ const preferencesHasMore = useUserMemoryStore((s) => s.preferencesHasMore);
+
+ return (
+ <GridView
+ hasMore={preferencesHasMore}
+ isLoading={isLoading}
+ items={preferences}
+ onLoadMore={loadMorePreferences}
+ renderItem={(preference) => (
+ <PreferenceCard onClick={() => onClick(preference)} preference={preference} />
+ )}
+ />
+ );
+});
+
+export default PreferenceGridView;
diff --git a/src/app/[variants]/(main)/memory/preferences/features/List/TimelineView/PreferenceCard.tsx b/src/app/[variants]/(main)/memory/preferences/features/List/TimelineView/PreferenceCard.tsx
new file mode 100644
index 00000000000..0757f326ed2
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/preferences/features/List/TimelineView/PreferenceCard.tsx
@@ -0,0 +1,28 @@
+import { memo } from 'react';
+
+import TimeLineCard from '@/app/[variants]/(main)/memory/features/TimeLineView/TimeLineCard';
+import { DisplayPreferenceMemory } from '@/database/repositories/userMemory';
+
+import PreferenceDropdown from '../../PreferenceDropdown';
+
+interface PreferenceCardProps {
+ onClick?: () => void;
+ preference: DisplayPreferenceMemory;
+}
+
+const PreferenceCard = memo<PreferenceCardProps>(({ preference, onClick }) => {
+ return (
+ <TimeLineCard
+ actions={<PreferenceDropdown id={preference.id} />}
+ cate={preference.type}
+ hashTags={preference.tags}
+ onClick={onClick}
+ title={preference.title}
+ updatedAt={preference.updatedAt || preference.createdAt}
+ >
+ {preference.conclusionDirectives}
+ </TimeLineCard>
+ );
+});
+
+export default PreferenceCard;
diff --git a/src/app/[variants]/(main)/memory/preferences/features/List/TimelineView/index.tsx b/src/app/[variants]/(main)/memory/preferences/features/List/TimelineView/index.tsx
new file mode 100644
index 00000000000..98141b7d4b6
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/preferences/features/List/TimelineView/index.tsx
@@ -0,0 +1,41 @@
+'use client';
+
+import { memo } from 'react';
+
+import { DisplayPreferenceMemory } from '@/database/repositories/userMemory';
+import { useUserMemoryStore } from '@/store/userMemory';
+
+import { TimelineView as GenericTimelineView } from '../../../../features/TimeLineView';
+import { PeriodHeader, TimelineItemWrapper } from '../../../../features/TimeLineView/PeriodGroup';
+import PreferenceCard from './PreferenceCard';
+
+interface PreferenceTimelineViewProps {
+ isLoading?: boolean;
+ onClick?: (preference: DisplayPreferenceMemory) => void;
+ preferences: DisplayPreferenceMemory[];
+}
+
+const PreferenceTimelineView = memo<PreferenceTimelineViewProps>(
+ ({ preferences, isLoading, onClick }) => {
+ const loadMorePreferences = useUserMemoryStore((s) => s.loadMorePreferences);
+ const preferencesHasMore = useUserMemoryStore((s) => s.preferencesHasMore);
+
+ return (
+ <GenericTimelineView
+ data={preferences}
+ groupBy="day"
+ hasMore={preferencesHasMore}
+ isLoading={isLoading}
+ onLoadMore={loadMorePreferences}
+ renderHeader={(periodKey) => <PeriodHeader groupBy="day" periodKey={periodKey} />}
+ renderItem={(preference) => (
+ <TimelineItemWrapper>
+ <PreferenceCard onClick={() => onClick?.(preference)} preference={preference} />
+ </TimelineItemWrapper>
+ )}
+ />
+ );
+ },
+);
+
+export default PreferenceTimelineView;
diff --git a/src/app/[variants]/(main)/memory/preferences/features/List/index.tsx b/src/app/[variants]/(main)/memory/preferences/features/List/index.tsx
new file mode 100644
index 00000000000..173514ba947
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/preferences/features/List/index.tsx
@@ -0,0 +1,43 @@
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import MemoryEmpty from '@/app/[variants]/(main)/memory/features/MemoryEmpty';
+import { useQueryState } from '@/hooks/useQueryParam';
+import { useGlobalStore } from '@/store/global';
+import { useUserMemoryStore } from '@/store/userMemory';
+
+import { ViewMode } from '../../../features/ViewModeSwitcher';
+import GridView from './GridView';
+import TimelineView from './TimelineView';
+
+interface PreferencesListProps {
+ isLoading?: boolean;
+ searchValue?: string;
+ viewMode: ViewMode;
+}
+
+const PreferencesList = memo<PreferencesListProps>(({ isLoading, searchValue, viewMode }) => {
+ const { t } = useTranslation(['memory', 'common']);
+ const [, setPreferenceId] = useQueryState('preferenceId', { clearOnDefault: true });
+ const toggleRightPanel = useGlobalStore((s) => s.toggleRightPanel);
+ const preferences = useUserMemoryStore((s) => s.preferences);
+
+ const handleCardClick = (preference: any) => {
+ setPreferenceId(preference.id);
+ toggleRightPanel(true);
+ };
+
+ const isEmpty = preferences.length === 0;
+
+ if (isEmpty) {
+ return <MemoryEmpty search={Boolean(searchValue)} title={t('preference.empty')} />;
+ }
+
+ return viewMode === 'timeline' ? (
+ <TimelineView isLoading={isLoading} onClick={handleCardClick} preferences={preferences} />
+ ) : (
+ <GridView isLoading={isLoading} onClick={handleCardClick} preferences={preferences} />
+ );
+});
+
+export default PreferencesList;
diff --git a/src/app/[variants]/(main)/memory/preferences/features/PreferenceDropdown.tsx b/src/app/[variants]/(main)/memory/preferences/features/PreferenceDropdown.tsx
new file mode 100644
index 00000000000..7b676dc6604
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/preferences/features/PreferenceDropdown.tsx
@@ -0,0 +1,66 @@
+import { ActionIcon, ActionIconProps, Dropdown } from '@lobehub/ui';
+import { App } from 'antd';
+import { MoreHorizontal, Pencil, Trash2 } from 'lucide-react';
+import { KeyboardEvent, MouseEvent, memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useUserMemoryStore } from '@/store/userMemory';
+
+interface PreferenceDropdownProps {
+ id: string;
+ size?: ActionIconProps['size'];
+}
+
+const PreferenceDropdown = memo<PreferenceDropdownProps>(({ id, size = 'small' }) => {
+ const { t } = useTranslation(['memory', 'common']);
+ const { modal } = App.useApp();
+
+ const preferences = useUserMemoryStore((s) => s.preferences);
+ const deletePreference = useUserMemoryStore((s) => s.deletePreference);
+ const setEditingMemory = useUserMemoryStore((s) => s.setEditingMemory);
+
+ const handleMenuClick = (info: { domEvent: MouseEvent | KeyboardEvent; key: string }) => {
+ info.domEvent.stopPropagation();
+
+ if (info.key === 'edit') {
+ const preference = preferences.find((p) => p.id === id);
+ if (preference) {
+ setEditingMemory(id, preference.conclusionDirectives || '', 'preference');
+ }
+ } else if (info.key === 'delete') {
+ modal.confirm({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: t('preference.deleteConfirm'),
+ okButtonProps: { danger: true },
+ okText: t('confirm', { ns: 'common' }),
+ onOk: async () => {
+ await deletePreference(id);
+ },
+ title: t('preference.deleteTitle'),
+ type: 'warning',
+ });
+ }
+ };
+
+ const menuItems = [
+ {
+ icon: <Pencil size={14} />,
+ key: 'edit',
+ label: t('preference.actions.edit'),
+ },
+ {
+ danger: true,
+ icon: <Trash2 size={14} />,
+ key: 'delete',
+ label: t('preference.actions.delete'),
+ },
+ ];
+
+ return (
+ <Dropdown menu={{ items: menuItems, onClick: handleMenuClick }} trigger={['click']}>
+ <ActionIcon icon={MoreHorizontal} size={size} />
+ </Dropdown>
+ );
+});
+
+export default PreferenceDropdown;
diff --git a/src/app/[variants]/(main)/memory/preferences/features/PreferenceRightPanel.tsx b/src/app/[variants]/(main)/memory/preferences/features/PreferenceRightPanel.tsx
new file mode 100644
index 00000000000..5136be7d1bb
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/preferences/features/PreferenceRightPanel.tsx
@@ -0,0 +1,104 @@
+'use client';
+
+import { Block, Icon, Text } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { BotIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import CateTag from '@/app/[variants]/(main)/memory/features/CateTag';
+import DetailLoading from '@/app/[variants]/(main)/memory/features/DetailLoading';
+import DetailPanel from '@/app/[variants]/(main)/memory/features/DetailPanel';
+import HashTags from '@/app/[variants]/(main)/memory/features/HashTags';
+import HighlightedContent from '@/app/[variants]/(main)/memory/features/HighlightedContent';
+import ProgressIcon from '@/app/[variants]/(main)/memory/features/ProgressIcon';
+import SourceLink from '@/app/[variants]/(main)/memory/features/SourceLink';
+import Time from '@/app/[variants]/(main)/memory/features/Time';
+import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
+import { useQueryState } from '@/hooks/useQueryParam';
+import { useUserMemoryStore } from '@/store/userMemory';
+import { LayersEnum } from '@/types/userMemory';
+
+import PreferenceDropdown from './PreferenceDropdown';
+
+const useStyles = createStyles(({ css, token }) => ({
+ suggestionsTitle: css`
+ font-size: 12px;
+ font-weight: 500;
+ color: ${token.colorTextSecondary};
+ `,
+}));
+
+const PreferenceRightPanel = memo(() => {
+ const { t } = useTranslation('memory');
+ const { styles } = useStyles();
+ const [preferenceId] = useQueryState('preferenceId', { clearOnDefault: true });
+ const useFetchMemoryDetail = useUserMemoryStore((s) => s.useFetchMemoryDetail);
+
+ const { data: preference, isLoading } = useFetchMemoryDetail(preferenceId, LayersEnum.Preference);
+
+ if (!preferenceId) return null;
+
+ let content;
+ if (isLoading) content = <DetailLoading />;
+ if (preference) {
+ content = (
+ <>
+ <CateTag cate={preference.type} />
+ <Text
+ as={'h1'}
+ fontSize={20}
+ style={{
+ lineHeight: 1.4,
+ marginBottom: 0,
+ }}
+ weight={'bold'}
+ >
+ {preference.title || preference.type || t('preference.defaultType')}
+ </Text>
+ <Flexbox align="center" gap={16} horizontal justify="space-between">
+ <ProgressIcon
+ format={(percent) => `${t('filter.sort.scorePriority')}: ${percent}%`}
+ percent={(preference.scorePriority ?? 0) * 100}
+ showInfo
+ />
+ </Flexbox>
+ <Flexbox align="center" gap={16} horizontal justify="space-between">
+ <SourceLink source={preference.source} />
+ <Time updatedAt={preference.createdAt} />
+ </Flexbox>
+
+ {preference.conclusionDirectives && (
+ <HighlightedContent>{preference.conclusionDirectives}</HighlightedContent>
+ )}
+
+ {preference.suggestions && (
+ <Block gap={8} padding={16} variant={'filled'}>
+ <Flexbox align={'center'} className={styles.suggestionsTitle} gap={6} horizontal>
+ <Icon icon={BotIcon} size={16} />
+ <span>{t('preference.suggestions')}</span>
+ </Flexbox>
+ <HighlightedContent>{preference.suggestions}</HighlightedContent>
+ </Block>
+ )}
+
+ <HashTags hashTags={preference.tags} />
+ </>
+ );
+ }
+
+ return (
+ <DetailPanel
+ header={{
+ right: preferenceId ? (
+ <PreferenceDropdown id={preferenceId} size={DESKTOP_HEADER_ICON_SIZE} />
+ ) : undefined,
+ }}
+ >
+ {content}
+ </DetailPanel>
+ );
+});
+
+export default PreferenceRightPanel;
diff --git a/src/app/[variants]/(main)/memory/preferences/index.tsx b/src/app/[variants]/(main)/memory/preferences/index.tsx
new file mode 100644
index 00000000000..67e997c1a56
--- /dev/null
+++ b/src/app/[variants]/(main)/memory/preferences/index.tsx
@@ -0,0 +1,130 @@
+import { Icon, Tag } from '@lobehub/ui';
+import { BrainCircuitIcon } from 'lucide-react';
+import { memo, useCallback, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { SCROLL_PARENT_ID } from '@/app/[variants]/(main)/memory/features/TimeLineView/useScrollParent';
+import NavHeader from '@/features/NavHeader';
+import WideScreenContainer from '@/features/WideScreenContainer';
+import WideScreenButton from '@/features/WideScreenContainer/WideScreenButton';
+import { useQueryState } from '@/hooks/useQueryParam';
+import { useUserMemoryStore } from '@/store/userMemory';
+
+import EditableModal from '../features/EditableModal';
+import FilterBar from '../features/FilterBar';
+import Loading from '../features/Loading';
+import ViewModeSwitcher, { ViewMode } from '../features/ViewModeSwitcher';
+import List from './features/List';
+import PreferenceRightPanel from './features/PreferenceRightPanel';
+
+const PreferencesArea = memo(() => {
+ const { t } = useTranslation('memory');
+ const [viewMode, setViewMode] = useState<ViewMode>('timeline');
+ const [searchValueRaw, setSearchValueRaw] = useQueryState('q', { clearOnDefault: true });
+ const [sortValueRaw, setSortValueRaw] = useQueryState('sort', { clearOnDefault: true });
+
+ const searchValue = searchValueRaw || '';
+ const sortValue = (sortValueRaw as 'createdAt' | 'scorePriority') || 'createdAt';
+
+ const preferencesPage = useUserMemoryStore((s) => s.preferencesPage);
+ const preferencesInit = useUserMemoryStore((s) => s.preferencesInit);
+ const preferencesTotal = useUserMemoryStore((s) => s.preferencesTotal);
+ const preferencesSearchLoading = useUserMemoryStore((s) => s.preferencesSearchLoading);
+ const useFetchPreferences = useUserMemoryStore((s) => s.useFetchPreferences);
+ const resetPreferencesList = useUserMemoryStore((s) => s.resetPreferencesList);
+
+ const sortOptions = [
+ { label: t('filter.sort.createdAt'), value: 'createdAt' },
+ { label: t('filter.sort.scorePriority'), value: 'scorePriority' },
+ ];
+
+ // 转换 sort:createdAt 转为 undefined(后端默认)
+ const apiSort = sortValue === 'createdAt' ? undefined : (sortValue as 'scorePriority');
+
+ // 当搜索或排序变化时重置列表
+ useEffect(() => {
+ if (!apiSort) return;
+ const sort = viewMode === 'grid' ? apiSort : undefined;
+ resetPreferencesList({ q: searchValue || undefined, sort });
+ }, [searchValue, apiSort, viewMode]);
+
+ // 调用 SWR hook 获取数据
+ const { isLoading } = useFetchPreferences({
+ page: preferencesPage,
+ pageSize: 12,
+ q: searchValue || undefined,
+ sort: viewMode === 'grid' ? apiSort : undefined,
+ });
+
+ // Handle search and sort changes
+ const handleSearch = useCallback(
+ (value: string) => {
+ setSearchValueRaw(value || null);
+ },
+ [setSearchValueRaw],
+ );
+
+ const handleSortChange = useCallback(
+ (sort: string) => {
+ setSortValueRaw(sort);
+ },
+ [setSortValueRaw],
+ );
+
+ // 显示 loading:搜索/重置中 或 首次加载中
+ const showLoading = preferencesSearchLoading || !preferencesInit;
+
+ return (
+ <Flexbox flex={1} height={'100%'}>
+ <NavHeader
+ left={
+ Boolean(preferencesTotal) && (
+ <Tag icon={<Icon icon={BrainCircuitIcon} />}>{preferencesTotal}</Tag>
+ )
+ }
+ right={
+ <>
+ <ViewModeSwitcher onChange={setViewMode} value={viewMode} />
+ <WideScreenButton />
+ </>
+ }
+ />
+ <Flexbox
+ height={'100%'}
+ id={SCROLL_PARENT_ID}
+ style={{ overflowY: 'auto', paddingBottom: '16vh' }}
+ width={'100%'}
+ >
+ <WideScreenContainer gap={32} paddingBlock={48}>
+ <FilterBar
+ onSearch={handleSearch}
+ onSortChange={viewMode === 'grid' ? handleSortChange : undefined}
+ searchValue={searchValue}
+ sortOptions={viewMode === 'grid' ? sortOptions : undefined}
+ sortValue={sortValue}
+ />
+ {showLoading ? (
+ <Loading viewMode={viewMode} />
+ ) : (
+ <List isLoading={isLoading} searchValue={searchValue} viewMode={viewMode} />
+ )}
+ </WideScreenContainer>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+const Preferences = memo(() => {
+ return (
+ <>
+ <Flexbox height={'100%'} horizontal width={'100%'}>
+ <PreferencesArea />
+ <PreferenceRightPanel />
+ </Flexbox>
+ <EditableModal />
+ </>
+ );
+});
+
+export default Preferences;
diff --git a/src/app/[variants]/(main)/profile/(home)/desktop.tsx b/src/app/[variants]/(main)/profile/(home)/desktop.tsx
deleted file mode 100644
index 7699dedbebe..00000000000
--- a/src/app/[variants]/(main)/profile/(home)/desktop.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-'use client';
-
-import { Skeleton } from 'antd';
-import dynamic from 'next/dynamic';
-import { memo } from 'react';
-
-import { enableClerk } from '@/const/auth';
-
-import ProfileClient from './Client';
-
-const ClerkProfile = dynamic(() => import('../features/ClerkProfile'), {
- loading: () => (
- <div style={{ flex: 1 }}>
- <Skeleton paragraph={{ rows: 8 }} title={false} />
- </div>
- ),
-});
-
-const DesktopProfileHomePage = memo(() => {
- const mobile = false;
- return enableClerk ? <ClerkProfile mobile={mobile} /> : <ProfileClient mobile={mobile} />;
-});
-
-DesktopProfileHomePage.displayName = 'DesktopProfileHomePage';
-
-export default DesktopProfileHomePage;
diff --git a/src/app/[variants]/(main)/profile/(home)/index.tsx b/src/app/[variants]/(main)/profile/(home)/index.tsx
deleted file mode 100644
index 261701ea56f..00000000000
--- a/src/app/[variants]/(main)/profile/(home)/index.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-'use client';
-
-import { Skeleton } from 'antd';
-import dynamic from 'next/dynamic';
-import { memo } from 'react';
-
-import { enableClerk } from '@/const/auth';
-
-import ProfileClient from './Client';
-
-const ClerkProfile = dynamic(() => import('../features/ClerkProfile'), {
- loading: () => (
- <div style={{ flex: 1 }}>
- <Skeleton paragraph={{ rows: 8 }} title={false} />
- </div>
- ),
-});
-
-const MobileProfileHomePage = memo(() => {
- const mobile = true;
- return enableClerk ? <ClerkProfile mobile={mobile} /> : <ProfileClient mobile={mobile} />;
-});
-
-MobileProfileHomePage.displayName = 'MobileProfileHomePage';
-
-export default MobileProfileHomePage;
diff --git a/src/app/[variants]/(main)/profile/@category/default.tsx b/src/app/[variants]/(main)/profile/@category/default.tsx
deleted file mode 100644
index 6177d698b50..00000000000
--- a/src/app/[variants]/(main)/profile/@category/default.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-import { Suspense } from 'react';
-
-import SkeletonLoading from '@/components/Loading/SkeletonLoading';
-
-import CategoryContent from './features/CategoryContent';
-
-const Category = () => {
- return (
- <Suspense fallback={<SkeletonLoading paragraph={{ rows: 7 }} title={false} />}>
- <CategoryContent />
- </Suspense>
- );
-};
-
-Category.displayName = 'SettingCategory';
-
-export default Category;
diff --git a/src/app/[variants]/(main)/profile/@category/features/CategoryContent.tsx b/src/app/[variants]/(main)/profile/@category/features/CategoryContent.tsx
deleted file mode 100644
index 4c90b68c8a8..00000000000
--- a/src/app/[variants]/(main)/profile/@category/features/CategoryContent.tsx
+++ /dev/null
@@ -1,32 +0,0 @@
-'use client';
-
-import { memo } from 'react';
-import { useLocation, useNavigate } from 'react-router-dom';
-import urlJoin from 'url-join';
-
-import Menu from '@/components/Menu';
-import { ProfileTabs } from '@/store/global/initialState';
-
-import { useCategory } from '../../hooks/useCategory';
-
-const CategoryContent = memo(() => {
- const location = useLocation();
- const navigate = useNavigate();
- const activeTab = location.pathname.split('/').at(-1);
- const cateItems = useCategory();
-
- return (
- <Menu
- compact
- items={cateItems}
- onClick={({ key }) => {
- const activeKey = key === ProfileTabs.Profile ? '/' : key;
- navigate(urlJoin('/profile', activeKey));
- }}
- selectable
- selectedKeys={activeTab ? [activeTab] : []}
- />
- );
-});
-
-export default CategoryContent;
diff --git a/src/app/[variants]/(main)/profile/_layout/Desktop/Header.tsx b/src/app/[variants]/(main)/profile/_layout/Desktop/Header.tsx
deleted file mode 100644
index be22d1fc6c8..00000000000
--- a/src/app/[variants]/(main)/profile/_layout/Desktop/Header.tsx
+++ /dev/null
@@ -1,86 +0,0 @@
-'use client';
-
-import { ActionIcon } from '@lobehub/ui';
-import { ChatHeader } from '@lobehub/ui/chat';
-import { Drawer, type DrawerProps } from 'antd';
-import { createStyles } from 'antd-style';
-import { Menu } from 'lucide-react';
-import { ReactNode, memo, useState } from 'react';
-import { Flexbox } from 'react-layout-kit';
-
-import BrandWatermark from '@/components/BrandWatermark';
-
-const useStyles = createStyles(({ token, css }) => ({
- container: css`
- position: relative;
- flex: none;
- height: 54px;
- background: ${token.colorBgContainer};
- `,
- title: css`
- font-size: 18px;
- font-weight: 700;
- line-height: 1.2;
- `,
-}));
-
-interface HeaderProps extends Pick<DrawerProps, 'getContainer'> {
- children: ReactNode;
- title: ReactNode;
-}
-
-const Header = memo<HeaderProps>(({ children, getContainer, title }) => {
- const [open, setOpen] = useState(false);
- const { styles, theme } = useStyles();
-
- return (
- <>
- <ChatHeader
- className={styles.container}
- left={
- <ChatHeader.Title
- title={
- <Flexbox align={'center'} className={styles.title} gap={4} horizontal>
- <ActionIcon
- color={theme.colorText}
- icon={Menu}
- onClick={() => setOpen(true)}
- size={{ blockSize: 32, size: 18 }}
- />
- {title}
- </Flexbox>
- }
- />
- }
- />
- <Drawer
- bodyStyle={{
- display: 'flex',
- flexDirection: 'column',
- gap: 20,
- justifyContent: 'space-between',
- padding: 16,
- }}
- getContainer={getContainer}
- headerStyle={{ display: 'none' }}
- maskStyle={{ background: 'transparent' }}
- onClick={() => setOpen(false)}
- onClose={() => setOpen(false)}
- open={open}
- placement={'left'}
- rootStyle={{ position: 'absolute' }}
- style={{
- background: theme.colorBgContainer,
- borderRight: `1px solid ${theme.colorSplit}`,
- }}
- width={260}
- zIndex={10}
- >
- {children}
- <BrandWatermark paddingInline={12} />
- </Drawer>
- </>
- );
-});
-
-export default Header;
diff --git a/src/app/[variants]/(main)/profile/_layout/Desktop/SideBar.tsx b/src/app/[variants]/(main)/profile/_layout/Desktop/SideBar.tsx
deleted file mode 100644
index b416a707704..00000000000
--- a/src/app/[variants]/(main)/profile/_layout/Desktop/SideBar.tsx
+++ /dev/null
@@ -1,44 +0,0 @@
-'use client';
-
-import { createStyles } from 'antd-style';
-import { Suspense } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox, FlexboxProps } from 'react-layout-kit';
-
-import BrandWatermark from '@/components/BrandWatermark';
-import CircleLoading from '@/components/Loading/CircleLoading';
-import PanelTitle from '@/components/PanelTitle';
-
-const useStyles = createStyles(({ token, css }) => ({
- container: css`
- padding-block: 0 16px;
- padding-inline: 12px;
- border-inline-end: 1px solid ${token.colorBorderSecondary};
- background: ${token.colorBgLayout};
- `,
-}));
-
-interface SidebarLayoutProps extends FlexboxProps {
- desc?: string;
- title?: string;
-}
-
-const SidebarLayout = ({ children, className, title, desc, ...rest }: SidebarLayoutProps) => {
- const { cx, styles } = useStyles();
- const { t } = useTranslation('auth');
- return (
- <Flexbox
- className={cx(styles.container, className)}
- flex={'none'}
- gap={20}
- width={280}
- {...rest}
- >
- <PanelTitle desc={desc || t('header.desc')} title={title || t('header.title')} />
- <Suspense fallback={<CircleLoading />}>{children}</Suspense>
- <BrandWatermark paddingInline={12} />
- </Flexbox>
- );
-};
-
-export default SidebarLayout;
diff --git a/src/app/[variants]/(main)/profile/_layout/Desktop/index.tsx b/src/app/[variants]/(main)/profile/_layout/Desktop/index.tsx
deleted file mode 100644
index c452887f253..00000000000
--- a/src/app/[variants]/(main)/profile/_layout/Desktop/index.tsx
+++ /dev/null
@@ -1,53 +0,0 @@
-'use client';
-
-import { useResponsive } from 'antd-style';
-import { memo, useRef } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Outlet } from 'react-router-dom';
-import { Flexbox } from 'react-layout-kit';
-
-import Footer from '@/features/Setting/Footer';
-import SettingContainer from '@/features/Setting/SettingContainer';
-import { useActiveProfileKey } from '@/hooks/useActiveTabKey';
-
-import { LayoutProps } from '../type';
-import Header from './Header';
-import SideBar from './SideBar';
-
-const Layout = memo<Omit<LayoutProps, 'children'>>(({ category }) => {
- const ref = useRef<any>(null);
- const { md = true } = useResponsive();
- const { t } = useTranslation('auth');
- const activeKey = useActiveProfileKey();
-
- return (
- <Flexbox
- height={'100%'}
- horizontal={md}
- ref={ref}
- style={{ position: 'relative' }}
- width={'100%'}
- >
- {md ? (
- <SideBar>{category}</SideBar>
- ) : (
- <Header getContainer={() => ref.current} title={<>{t(`tab.${activeKey}`)}</>}>
- {category}
- </Header>
- )}
- <SettingContainer
- addonAfter={<Footer />}
- style={{
- paddingBlock: 24,
- paddingInline: 32,
- }}
- >
- <Outlet />
- </SettingContainer>
- </Flexbox>
- );
-});
-
-Layout.displayName = 'DesktopProfileLayout';
-
-export default Layout;
diff --git a/src/app/[variants]/(main)/profile/_layout/DesktopWrapper.tsx b/src/app/[variants]/(main)/profile/_layout/DesktopWrapper.tsx
deleted file mode 100644
index d105cf87904..00000000000
--- a/src/app/[variants]/(main)/profile/_layout/DesktopWrapper.tsx
+++ /dev/null
@@ -1,14 +0,0 @@
-'use client';
-
-import { memo } from 'react';
-
-import Category from '../@category/default';
-import Desktop from './Desktop';
-
-const DesktopProfileWrapper = memo(() => {
- return <Desktop category={<Category />} />;
-});
-
-DesktopProfileWrapper.displayName = 'DesktopProfileWrapper';
-
-export default DesktopProfileWrapper;
diff --git a/src/app/[variants]/(main)/profile/_layout/Mobile/Header.tsx b/src/app/[variants]/(main)/profile/_layout/Mobile/Header.tsx
deleted file mode 100644
index fc29fc8d4ae..00000000000
--- a/src/app/[variants]/(main)/profile/_layout/Mobile/Header.tsx
+++ /dev/null
@@ -1,44 +0,0 @@
-'use client';
-
-import { ChatHeader } from '@lobehub/ui/mobile';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Flexbox } from 'react-layout-kit';
-import { useNavigate } from 'react-router-dom';
-
-import { useActiveProfileKey } from '@/hooks/useActiveTabKey';
-import { mobileHeaderSticky } from '@/styles/mobileHeader';
-
-import ShareButton from '../../stats/features/ShareButton';
-
-const Header = memo(() => {
- const { t } = useTranslation('auth');
-
- const navigate = useNavigate();
- const activeSettingsKey = useActiveProfileKey();
- const isStats = activeSettingsKey === 'stats';
-
- const handleBackClick = () => {
- navigate('/me/profile');
- };
-
- return (
- <ChatHeader
- center={
- <ChatHeader.Title
- title={
- <Flexbox align={'center'} gap={8} horizontal>
- <span style={{ lineHeight: 1.2 }}> {t(`tab.${activeSettingsKey}`)}</span>
- </Flexbox>
- }
- />
- }
- onBackClick={handleBackClick}
- right={isStats ? <ShareButton mobile /> : undefined}
- showBackButton
- style={mobileHeaderSticky}
- />
- );
-});
-
-export default Header;
diff --git a/src/app/[variants]/(main)/profile/_layout/type.ts b/src/app/[variants]/(main)/profile/_layout/type.ts
deleted file mode 100644
index 05c8d56f9d7..00000000000
--- a/src/app/[variants]/(main)/profile/_layout/type.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { ReactNode } from 'react';
-
-export interface LayoutProps {
- category: ReactNode;
- children: ReactNode;
-}
diff --git a/src/app/[variants]/(main)/profile/apikey/index.tsx b/src/app/[variants]/(main)/profile/apikey/index.tsx
deleted file mode 100644
index 2e4f36ddfcc..00000000000
--- a/src/app/[variants]/(main)/profile/apikey/index.tsx
+++ /dev/null
@@ -1,18 +0,0 @@
-import NotFound from '@/components/404';
-import { serverFeatureFlags } from '@/config/featureFlags';
-
-import Page from '../../settings/system-agent';
-import Client from './Client';
-
-
-const page = () => {
- const { showApiKeyManage } = serverFeatureFlags();
-
- if (!showApiKeyManage) return <NotFound />;
-
- return <Client />;
-};
-
-Page.displayName = 'ApiKey';
-
-export default page;
diff --git a/src/app/[variants]/(main)/profile/hooks/useCategory.tsx b/src/app/[variants]/(main)/profile/hooks/useCategory.tsx
deleted file mode 100644
index d861200fefc..00000000000
--- a/src/app/[variants]/(main)/profile/hooks/useCategory.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-import { Icon } from '@lobehub/ui';
-import { BadgeCentIcon, ChartColumnBigIcon, KeyIcon, ShieldCheck, UserCircle } from 'lucide-react';
-import { Link } from 'react-router-dom';
-import { useTranslation } from 'react-i18next';
-
-import type { MenuProps } from '@/components/Menu';
-import { ProfileTabs } from '@/store/global/initialState';
-import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
-import { useUserStore } from '@/store/user';
-import { authSelectors } from '@/store/user/slices/auth/selectors';
-
-export const useCategory = () => {
- const { t } = useTranslation('auth');
- const [isLoginWithClerk] = useUserStore((s) => [authSelectors.isLoginWithClerk(s)]);
- const { showApiKeyManage } = useServerConfigStore(featureFlagsSelectors);
-
- const cateItems: MenuProps['items'] = [
- {
- icon: <Icon icon={UserCircle} />,
- key: ProfileTabs.Profile,
- label: (
- <Link onClick={(e) => e.preventDefault()} to={'/profile'}>
- {t('tab.profile')}
- </Link>
- ),
- },
- isLoginWithClerk && {
- icon: <Icon icon={ShieldCheck} />,
- key: ProfileTabs.Security,
- label: (
- <Link onClick={(e) => e.preventDefault()} to={'/profile/security'}>
- {t('tab.security')}
- </Link>
- ),
- },
- {
- icon: <Icon icon={ChartColumnBigIcon} />,
- key: ProfileTabs.Stats,
- label: (
- <Link onClick={(e) => e.preventDefault()} to={'/profile/stats'}>
- {t('tab.stats')}
- </Link>
- ),
- },
- !!showApiKeyManage && {
- icon: <Icon icon={KeyIcon} />,
- key: ProfileTabs.APIKey,
- label: (
- <Link onClick={(e) => e.preventDefault()} to={'/profile/apikey'}>
- {t('tab.apikey')}
- </Link>
- ),
- },
- {
- icon: <Icon icon={BadgeCentIcon} />,
- key: ProfileTabs.Usage,
- label: (
- <Link onClick={(e) => e.preventDefault()} to={'/profile/usage'}>
- {t('tab.usage')}
- </Link>
- ),
- },
- ].filter(Boolean) as MenuProps['items'];
-
- return cateItems;
-};
diff --git a/src/app/[variants]/(main)/profile/security/index.tsx b/src/app/[variants]/(main)/profile/security/index.tsx
deleted file mode 100644
index cece287837f..00000000000
--- a/src/app/[variants]/(main)/profile/security/index.tsx
+++ /dev/null
@@ -1,29 +0,0 @@
-'use client';
-
-import { Skeleton } from 'antd';
-import dynamic from 'next/dynamic';
-import { memo } from 'react';
-import { Navigate } from 'react-router-dom';
-
-import { enableClerk } from '@/const/auth';
-
-const ClerkProfile = dynamic(() => import('../features/ClerkProfile'), {
- loading: () => (
- <div style={{ flex: 1 }}>
- <Skeleton paragraph={{ rows: 8 }} title={false} />
- </div>
- ),
-});
-
-const MobileProfileSecurityPage = memo(() => {
- const mobile = true;
- return enableClerk ? <ClerkProfile mobile={mobile} /> : <Navigate replace to="/profile" />;
-});
-
-
-const DesktopProfileSecurityPage = memo(() => {
- const mobile = false;
- return enableClerk ? <ClerkProfile mobile={mobile} /> : <Navigate replace to="/profile" />;
-});
-
-export { DesktopProfileSecurityPage,MobileProfileSecurityPage };
diff --git a/src/app/[variants]/(main)/profile/stats/index.tsx b/src/app/[variants]/(main)/profile/stats/index.tsx
deleted file mode 100644
index 14c496c4e3c..00000000000
--- a/src/app/[variants]/(main)/profile/stats/index.tsx
+++ /dev/null
@@ -1,20 +0,0 @@
-'use client';
-
-import { memo } from 'react';
-
-import StatsClient from './Client';
-
-const MobileProfileStatsPage = memo(() => {
- const mobile = true;
- return <StatsClient mobile={mobile} />;
-});
-
-MobileProfileStatsPage.displayName = 'MobileProfileStatsPage';
-
-
-const DesktopProfileStatsPage = memo(() => {
- const mobile = false;
- return <StatsClient mobile={mobile} />;
-});
-
-export { DesktopProfileStatsPage,MobileProfileStatsPage };
diff --git a/src/app/[variants]/(main)/profile/usage/features/components/UsageBarChart.tsx b/src/app/[variants]/(main)/profile/usage/features/components/UsageBarChart.tsx
deleted file mode 100644
index 8405bbd3218..00000000000
--- a/src/app/[variants]/(main)/profile/usage/features/components/UsageBarChart.tsx
+++ /dev/null
@@ -1,48 +0,0 @@
-import { Divider, Typography } from 'antd'
-import { Flexbox } from 'react-layout-kit';
-import { BarChart, ChartTooltipFrame, ChartTooltipRow, type BarChartProps } from '@lobehub/charts';
-
-export const UsageBarChart = ({ ...props }: BarChartProps) => (
- <BarChart
- {...props}
- customTooltip={({ active, payload, label, valueFormatter }) => {
- if (active && payload) {
- return (
- <ChartTooltipFrame>
- <Flexbox
- horizontal
- justify={'space-between'}
- paddingBlock={8}
- paddingInline={16}
- >
- <Typography.Paragraph ellipsis style={{ margin: 0 }}>
- {label}
- </Typography.Paragraph>
- <span style={{ fontWeight: 'bold' }}>
- {payload.reduce((acc: number, cur: any) => acc + cur.value, 0)}
- </span>
- </Flexbox>
- <Divider style={{ margin: 0 }} />
- <Flexbox
- gap={4}
- paddingBlock={8}
- paddingInline={16}
- style={{ flexDirection: 'column-reverse', marginTop: 4 }}
- >
- {payload.map(({ value, color, name }: any, idx: number) => (
- typeof value === 'number' && value > 0 ?
- <ChartTooltipRow
- color={color}
- key={`id-${idx}`}
- name={name}
- value={(valueFormatter as any)?.(value)}
- /> : null
- ))}
- </Flexbox>
- </ChartTooltipFrame>
- );
- }
- return null;
- }}
- />
-)
\ No newline at end of file
diff --git a/src/app/[variants]/(main)/profile/usage/index.tsx b/src/app/[variants]/(main)/profile/usage/index.tsx
deleted file mode 100644
index efd1be3786c..00000000000
--- a/src/app/[variants]/(main)/profile/usage/index.tsx
+++ /dev/null
@@ -1,13 +0,0 @@
-
-import Client from './Client';
-
-
-const MobileProfileUsagePage = async () => {
- return <Client mobile={true} />;
-};
-
-const DesktopProfileUsagePage = async () => {
- return <Client mobile={false} />;
-};
-
-export { DesktopProfileUsagePage,MobileProfileUsagePage };
diff --git a/src/app/loading.tsx b/src/app/loading.tsx
new file mode 100644
index 00000000000..ebc597b1e42
--- /dev/null
+++ b/src/app/loading.tsx
@@ -0,0 +1,3 @@
+import Loading from '@/components/Loading/BrandTextLoading';
+
+export default () => <Loading debugId="App Root" />;
diff --git a/src/app/manifest.ts b/src/app/manifest.ts
index a87d0f6cc4d..d364a289364 100644
--- a/src/app/manifest.ts
+++ b/src/app/manifest.ts
@@ -1,4 +1,4 @@
-import { kebabCase } from 'lodash-es';
+import { kebabCase } from 'es-toolkit/compat';
import type { MetadataRoute } from 'next';
import { BRANDING_LOGO_URL, BRANDING_NAME } from '@/const/branding';
diff --git a/src/app/market-auth-callback/layout.tsx b/src/app/market-auth-callback/layout.tsx
deleted file mode 100644
index 872f8242da7..00000000000
--- a/src/app/market-auth-callback/layout.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-import { cookies, headers } from 'next/headers';
-import { ReactNode } from 'react';
-import { isRtlLang } from 'rtl-detect';
-import { NuqsAdapter } from 'nuqs/adapters/next/app';
-
-
-import { DEFAULT_LANG, LOBE_LOCALE_COOKIE } from '@/const/locale';
-import GlobalLayout from '@/layout/GlobalProvider';
-import { Locales } from '@/locales/resources';
-import { parseBrowserLanguage } from '@/utils/locale';
-
-interface RootLayoutProps {
- children: ReactNode;
-}
-
-const RootLayout = async ({ children }: RootLayoutProps) => {
- // 获取 locale:优先级为 cookie > 浏览器语言 > 默认语言
- const cookieStore = await cookies();
- const headersList = await headers();
- const cookieLocale = cookieStore.get(LOBE_LOCALE_COOKIE)?.value as Locales | undefined;
- const browserLanguage = parseBrowserLanguage(headersList, DEFAULT_LANG);
- const locale = (cookieLocale || browserLanguage || DEFAULT_LANG) as Locales;
-
- const direction = isRtlLang(locale) ? 'rtl' : 'ltr';
-
- return (
- <html dir={direction} lang={locale} suppressHydrationWarning>
- <body>
- <NuqsAdapter>
- <GlobalLayout appearance="auto" isMobile={false} locale={locale}>
- {children}
- </GlobalLayout>
- </NuqsAdapter>
- </body>
- </html>
- );
-};
-
-export default RootLayout;
diff --git a/src/app/robots.tsx b/src/app/robots.tsx
index 90efbb08de8..50bdafa2dd8 100644
--- a/src/app/robots.tsx
+++ b/src/app/robots.tsx
@@ -13,15 +13,15 @@ const robots = (): MetadataRoute.Robots => {
host: getCanonicalUrl(),
rules: [
{
- allow: ['/discover/*'],
+ allow: ['/community/*'],
userAgent: ['Facebot', 'facebookexternalhit'],
},
{
- allow: ['/discover/*'],
+ allow: ['/community/*'],
userAgent: 'LinkedInBot',
},
{
- allow: ['/discover/*'],
+ allow: ['/community/*'],
userAgent: 'Twitterbot',
},
{
diff --git a/src/libs/oidc-provider/jwt.ts b/src/libs/oidc-provider/jwt.ts
index c4d2d98b54a..7a62ef94dbc 100644
--- a/src/libs/oidc-provider/jwt.ts
+++ b/src/libs/oidc-provider/jwt.ts
@@ -1,6 +1,5 @@
import { TRPCError } from '@trpc/server';
import debug from 'debug';
-import { importJWK, jwtVerify } from 'jose';
import { oidcEnv } from '@/envs/oidc';
@@ -76,6 +75,8 @@ const getVerificationKey = async () => {
(key) => (publicKeyJwk as any)[key] === undefined && delete (publicKeyJwk as any)[key],
);
+ const { importJWK } = await import('jose');
+
// 现在,无论在哪个环境下,`importJWK` 都会将这个对象正确地识别为一个公钥。
return await importJWK(publicKeyJwk, 'RS256');
} catch (error) {
@@ -97,6 +98,7 @@ export const validateOIDCJWT = async (token: string) => {
const publicKey = await getVerificationKey();
// 验证 JWT
+ const { jwtVerify } = await import('jose');
const { payload } = await jwtVerify(token, publicKey, {
algorithms: ['RS256'],
// 可以添加其他验证选项,如 issuer、audience 等
diff --git a/src/services/__tests__/models.test.ts b/src/services/__tests__/models.test.ts
index d2096f308b9..32f85ef7f45 100644
--- a/src/services/__tests__/models.test.ts
+++ b/src/services/__tests__/models.test.ts
@@ -3,14 +3,14 @@ import { Mock, beforeEach, describe, expect, it, vi } from 'vitest';
import { aiProviderSelectors } from '@/store/aiInfra';
import { createHeaderWithAuth } from '../_auth';
-import { initializeWithClientStore } from '../chat/clientModelRuntime';
import { resolveRuntimeProvider } from '../chat/helper';
+import { initializeWithClientStore } from '../chat/mecha';
import { ModelsService } from '../models';
vi.stubGlobal('fetch', vi.fn());
vi.mock('@/const/version', () => ({
- isDeprecatedEdition: false,
+ isDesktop: false,
}));
vi.mock('../_auth', () => ({
@@ -21,7 +21,7 @@ vi.mock('../chat/helper', () => ({
resolveRuntimeProvider: vi.fn((provider: string) => provider),
}));
-vi.mock('../chat/clientModelRuntime', () => ({
+vi.mock('../chat/mecha', () => ({
initializeWithClientStore: vi.fn(),
}));
diff --git a/src/services/agentRuntime/__tests__/client.test.ts b/src/services/agentRuntime/__tests__/client.test.ts
new file mode 100644
index 00000000000..94dc36352d7
--- /dev/null
+++ b/src/services/agentRuntime/__tests__/client.test.ts
@@ -0,0 +1,228 @@
+// @vitest-environment happy-dom
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agentRuntimeClient } from '../client';
+
+// Mock fetchEventSource
+const mockFetchEventSource = vi.fn();
+vi.mock('@lobechat/utils/client', () => ({
+ fetchEventSource: (url: string, options: any) => mockFetchEventSource(url, options),
+}));
+
+describe('AgentRuntimeClient', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('createStreamConnection', () => {
+ it('should create connection with correct URL and parameters', () => {
+ const operationId = 'agent_1758302563222_0g28qmdmu';
+
+ agentRuntimeClient.createStreamConnection(operationId, {
+ includeHistory: false,
+ lastEventId: '0',
+ });
+
+ expect(mockFetchEventSource).toHaveBeenCalledWith(
+ '/api/agent/stream?includeHistory=false&lastEventId=0&operationId=agent_1758302563222_0g28qmdmu',
+ expect.objectContaining({
+ headers: {
+ 'Cache-Control': 'no-cache',
+ 'Last-Event-ID': '0',
+ },
+ signal: expect.any(AbortSignal),
+ }),
+ );
+ });
+
+ it('should handle complete agent runtime lifecycle with real stream data', async () => {
+ const operationId = 'agent_1758302563222_abc';
+ const events: any[] = [];
+ let connectCalled = false;
+ let disconnectCalled = false;
+
+ // Capture the callbacks passed to fetchEventSource
+ mockFetchEventSource.mockImplementation((url: string, options: any) => {
+ // Simulate connection opening
+ setTimeout(() => {
+ options.onopen?.({ ok: true, status: 200, statusText: 'OK' });
+ }, 10);
+
+ // Simulate receiving events
+ setTimeout(() => {
+ const streamEvents = [
+ `{"lastEventId":"0","operationId":"${operationId}","timestamp":1758302567925,"type":"connected"}`,
+ `{"type":"agent_runtime_init","stepIndex":0,"operationId":"${operationId}","data":{"agentConfig":{"enableSearch":true}},"timestamp":1758302564421}`,
+ `{"type":"stream_start","stepIndex":0,"operationId":"${operationId}","data":{"messageId":"msg1","model":"gpt-4"},"timestamp":1758302574552}`,
+ `{"type":"stream_chunk","stepIndex":0,"operationId":"${operationId}","data":{"content":"Hello"},"timestamp":1758302578042}`,
+ `{"type":"stream_end","stepIndex":0,"operationId":"${operationId}","data":{"finalContent":"Hello world"},"timestamp":1758302626595}`,
+ `{"type":"agent_runtime_end","stepIndex":0,"operationId":"${operationId}","data":{"status":"completed"},"timestamp":1758302631030}`,
+ ];
+
+ streamEvents.forEach((eventData) => {
+ options.onmessage?.({ data: eventData, event: 'message' });
+ });
+ }, 20);
+ });
+
+ agentRuntimeClient.createStreamConnection(operationId, {
+ includeHistory: false,
+ onConnect: () => {
+ connectCalled = true;
+ },
+ onDisconnect: () => {
+ disconnectCalled = true;
+ },
+ onEvent: (event) => {
+ events.push(event);
+ },
+ });
+
+ // Wait for all events
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ expect(connectCalled).toBe(true);
+ expect(events).toHaveLength(6);
+
+ // Verify event sequence
+ expect(events[0].type).toBe('connected');
+ expect(events[1].type).toBe('agent_runtime_init');
+ expect(events[2].type).toBe('stream_start');
+ expect(events[3].type).toBe('stream_chunk');
+ expect(events[4].type).toBe('stream_end');
+ expect(events[5].type).toBe('agent_runtime_end');
+
+ // Verify operationId consistency
+ events.forEach((event) => {
+ expect(event.operationId).toBe(operationId);
+ });
+ });
+
+ it('should handle heartbeat events correctly', async () => {
+ const operationId = 'test-operation';
+ const events: any[] = [];
+
+ mockFetchEventSource.mockImplementation((url: string, options: any) => {
+ setTimeout(() => {
+ const heartbeatData = `{"operationId":"${operationId}","timestamp":1758302597927,"type":"heartbeat"}`;
+ options.onmessage?.({ data: heartbeatData, event: 'message' });
+ }, 10);
+ });
+
+ agentRuntimeClient.createStreamConnection(operationId, {
+ onEvent: (event) => {
+ events.push(event);
+ },
+ });
+
+ await new Promise((resolve) => setTimeout(resolve, 30));
+
+ expect(events).toHaveLength(1);
+ expect(events[0].type).toBe('heartbeat');
+ expect(events[0].operationId).toBe(operationId);
+ });
+
+ it('should handle connection errors', async () => {
+ const operationId = 'test-operation';
+ let errorOccurred = false;
+
+ mockFetchEventSource.mockImplementation((url: string, options: any) => {
+ setTimeout(() => {
+ options.onerror?.(new Error('Connection failed'));
+ }, 10);
+ });
+
+ agentRuntimeClient.createStreamConnection(operationId, {
+ onError: (error) => {
+ errorOccurred = true;
+ expect(error.message).toBe('Connection failed');
+ },
+ });
+
+ await new Promise((resolve) => setTimeout(resolve, 30));
+
+ expect(errorOccurred).toBe(true);
+ });
+
+ it('should handle malformed JSON gracefully', async () => {
+ const operationId = 'test-operation';
+ const events: any[] = [];
+ let errorOccurred = false;
+
+ mockFetchEventSource.mockImplementation((url: string, options: any) => {
+ setTimeout(() => {
+ options.onmessage?.({ data: 'invalid json', event: 'message' });
+ }, 10);
+ });
+
+ agentRuntimeClient.createStreamConnection(operationId, {
+ onEvent: (event) => {
+ events.push(event);
+ },
+ onError: (error) => {
+ errorOccurred = true;
+ },
+ });
+
+ await new Promise((resolve) => setTimeout(resolve, 30));
+
+ expect(events).toHaveLength(0);
+ expect(errorOccurred).toBe(true);
+ });
+
+ it('should call onDisconnect when connection is closed', async () => {
+ const operationId = 'test-operation';
+ let disconnectCalled = false;
+
+ mockFetchEventSource.mockImplementation((url: string, options: any) => {
+ setTimeout(() => {
+ options.onclose?.();
+ }, 10);
+ });
+
+ agentRuntimeClient.createStreamConnection(operationId, {
+ onDisconnect: () => {
+ disconnectCalled = true;
+ },
+ });
+
+ await new Promise((resolve) => setTimeout(resolve, 30));
+
+ expect(disconnectCalled).toBe(true);
+ });
+
+ it('should include correct parameters in URL', () => {
+ const operationId = 'test-operation-123';
+
+ agentRuntimeClient.createStreamConnection(operationId, {
+ includeHistory: true,
+ lastEventId: '12345',
+ });
+
+ expect(mockFetchEventSource).toHaveBeenCalledWith(
+ '/api/agent/stream?includeHistory=true&lastEventId=12345&operationId=test-operation-123',
+ expect.any(Object),
+ );
+ });
+
+ it('should use default parameters when not provided', () => {
+ const operationId = 'test-operation';
+
+ agentRuntimeClient.createStreamConnection(operationId);
+
+ expect(mockFetchEventSource).toHaveBeenCalledWith(
+ '/api/agent/stream?includeHistory=false&lastEventId=0&operationId=test-operation',
+ expect.any(Object),
+ );
+ });
+
+ it('should return AbortController for cancellation', () => {
+ const operationId = 'test-operation';
+
+ const controller = agentRuntimeClient.createStreamConnection(operationId);
+
+ expect(controller).toBeInstanceOf(AbortController);
+ expect(controller.signal).toBeInstanceOf(AbortSignal);
+ });
+ });
+});
diff --git a/src/services/agentRuntime/client.ts b/src/services/agentRuntime/client.ts
new file mode 100644
index 00000000000..e5c595af621
--- /dev/null
+++ b/src/services/agentRuntime/client.ts
@@ -0,0 +1,77 @@
+import { fetchEventSource } from '@lobechat/utils/client';
+import debug from 'debug';
+
+import { StreamConnectionOptions, StreamEvent } from './type';
+
+const log = debug('lobe-agent-runtime:client');
+
+/**
+ * Agent Client Service for communicating with durable agents
+ */
+class AgentRuntimeClient {
+ private baseUrl = '/api/agent';
+
+ /**
+ * Create a streaming connection to receive real-time agent events
+ */
+ createStreamConnection(
+ operationId: string,
+ options: StreamConnectionOptions = {},
+ ): AbortController {
+ const {
+ includeHistory = false,
+ lastEventId = '0',
+ onEvent,
+ onError,
+ onConnect,
+ onDisconnect,
+ } = options;
+
+ const params = new URLSearchParams({
+ includeHistory: includeHistory.toString(),
+ lastEventId,
+ operationId,
+ });
+
+ const controller = new AbortController();
+
+ fetchEventSource(`${this.baseUrl}/stream?${params}`, {
+ headers: {
+ 'Cache-Control': 'no-cache',
+ 'Last-Event-ID': lastEventId,
+ },
+ onclose: () => {
+ log(`Stream connection closed for operation ${operationId}`);
+ onDisconnect?.();
+ },
+ onerror: (error) => {
+ console.error(`[AgentClientService] Stream error for operation ${operationId}:`, error);
+ onError?.(error instanceof Error ? error : new Error('Stream connection error'));
+ },
+ onmessage: (event) => {
+ try {
+ const data = JSON.parse(event.data) as StreamEvent;
+ log(`Received event: ${event.event || 'message'}`, event.data);
+
+ onEvent?.(data);
+ } catch (error) {
+ console.error('[AgentClientService] Failed to parse stream event:', error);
+ onError?.(new Error('Failed to parse stream event'));
+ }
+ },
+ onopen: async (response) => {
+ if (response.ok) {
+ log(`Stream connection opened for operation ${operationId}`);
+ onConnect?.();
+ } else {
+ throw new Error(`Failed to open stream: ${response.status} ${response.statusText}`);
+ }
+ },
+ signal: controller.signal,
+ });
+
+ return controller;
+ }
+}
+
+export const agentRuntimeClient = new AgentRuntimeClient();
diff --git a/src/services/agentRuntime/index.ts b/src/services/agentRuntime/index.ts
new file mode 100644
index 00000000000..6c5287e6124
--- /dev/null
+++ b/src/services/agentRuntime/index.ts
@@ -0,0 +1,97 @@
+import { UIChatMessage } from '@lobechat/types';
+
+import { createAgentToolsEngine } from '@/helpers/toolEngineering';
+import { lambdaClient } from '@/libs/trpc/client';
+import { HumanInterventionRequest } from '@/services/agentRuntime/type';
+import { contextEngineering } from '@/services/chat/mecha';
+import { getAgentStoreState } from '@/store/agent';
+import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';
+
+export { agentRuntimeClient } from './client';
+export * from './type';
+
+interface AgentOperationRequest {
+ appSessionId?: string;
+ autoStart?: boolean;
+ messages: UIChatMessage[];
+ threadId?: string;
+ topicId?: string;
+ userMessageId: string;
+}
+
+class AgentRuntimeService {
+ createOperation = async (data: AgentOperationRequest) => {
+ const agentStoreState = getAgentStoreState();
+ const agentConfig = agentSelectors.currentAgentConfig(agentStoreState);
+ const chatConfig = agentChatConfigSelectors.currentChatConfig(agentStoreState);
+
+ const modelRuntimeConfig = {
+ model: agentConfig.model,
+ provider: agentConfig.provider!,
+ };
+
+ const toolsEngine = createAgentToolsEngine({
+ model: agentConfig.model,
+ provider: agentConfig.provider!,
+ });
+
+ const { tools, enabledToolIds } = toolsEngine.generateToolsDetailed({
+ model: agentConfig.model,
+ provider: agentConfig.provider!,
+ toolIds: agentConfig.plugins,
+ });
+
+ // Apply context engineering with preprocessing configuration
+ const llmMessages = await contextEngineering({
+ enableHistoryCount: agentChatConfigSelectors.enableHistoryCount(agentStoreState),
+ // include user messages
+ historyCount: agentChatConfigSelectors.historyCount(agentStoreState) + 2,
+ inputTemplate: chatConfig.inputTemplate,
+ messages: data.messages as any,
+ ...modelRuntimeConfig,
+ systemRole: agentConfig.systemRole,
+ tools: enabledToolIds,
+ });
+
+ const toolManifestMap = Object.fromEntries(
+ toolsEngine.getEnabledPluginManifests(enabledToolIds).entries(),
+ );
+
+ return await lambdaClient.aiAgent.createOperation.mutate({
+ ...data,
+ agentConfig: {
+ enableSearch: agentChatConfigSelectors.isAgentEnableSearch(agentStoreState),
+ maxSteps: 50,
+ // costLimit: agentChatConfig.costLimit,
+ // enableRAG: false,
+ // humanApprovalRequired: agentChatConfig.humanApprovalRequired || false,
+ },
+ messages: llmMessages,
+ modelRuntimeConfig,
+ toolManifestMap,
+ tools,
+ });
+ };
+
+ /**
+ * Get operation status
+ */
+ async getOperationStatus(operationId: string, includeHistory = false): Promise<any> {
+ return await lambdaClient.aiAgent.getOperationStatus.query({ includeHistory, operationId });
+ }
+
+ /**
+ * Handle human intervention
+ */
+ async handleHumanIntervention(request: HumanInterventionRequest): Promise<any> {
+ return await lambdaClient.aiAgent.processHumanIntervention.mutate({
+ action: request.action,
+ data: request.data,
+ operationId: request.operationId,
+ reason: request.reason,
+ stepIndex: 0, // Default to 0 since it's not provided in the request type
+ });
+ }
+}
+
+export const agentRuntimeService = new AgentRuntimeService();
diff --git a/src/services/agentRuntime/type.ts b/src/services/agentRuntime/type.ts
new file mode 100644
index 00000000000..d28854ca802
--- /dev/null
+++ b/src/services/agentRuntime/type.ts
@@ -0,0 +1,72 @@
+import { OpenAIChatMessage } from '@/types/openai/chat';
+
+export interface StreamEvent {
+ data?: any;
+ operationId?: string;
+ stepIndex?: number;
+ timestamp: number;
+ type:
+ | 'connected'
+ | 'agent_runtime_init' // Agent runtime initialization
+ | 'agent_runtime_end' // Agent runtime finished (signals stream should close)
+ | 'stream_start'
+ | 'stream_chunk'
+ | 'stream_end'
+ | 'step_start'
+ | 'step_complete'
+ | 'error'
+ | 'heartbeat';
+}
+
+export interface StreamConnectionOptions {
+ includeHistory?: boolean;
+ lastEventId?: string;
+ onConnect?: () => void;
+ onDisconnect?: () => void;
+ onError?: (error: Error) => void;
+ onEvent?: (event: StreamEvent) => void;
+}
+
+export interface AgentOperationRequest {
+ agentConfig?: {
+ [key: string]: any;
+ costLimit?: {
+ currency: string;
+ maxTotalCost: number;
+ onExceeded: 'stop' | 'interrupt' | 'continue';
+ };
+ enableRAG?: boolean;
+ enableSearch?: boolean;
+ humanApprovalRequired?: boolean;
+ maxSteps?: number;
+ };
+ appSessionId?: string;
+ autoStart?: boolean;
+ messages: OpenAIChatMessage[];
+ modelRuntimeConfig: {
+ [key: string]: any;
+ model: string;
+ provider: string;
+ };
+ userMessageId: string;
+}
+
+export interface AgentOperationResponse {
+ autoStart: boolean;
+ createdAt: string;
+ firstStep?: {
+ context?: any;
+ messageId?: string;
+ scheduled: boolean;
+ };
+ operationId: string;
+ status: string;
+ success: boolean;
+}
+
+export interface HumanInterventionRequest {
+ action: 'approve' | 'reject' | 'input' | 'select';
+ data?: any;
+ operationId: string;
+ reason?: string;
+}