🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(memory): replace the contexts page with entity pages on real memory data (#21347)
Arvin Xu0119298d9a77
diff --git a/locales/en-US/memory.json b/locales/en-US/memory.jsonindex c89fb9fc616..99a3824bb84 100644--- a/locales/en-US/memory.json+++ b/locales/en-US/memory.json@@ -39,6 +39,70 @@"empty.description": "Memory retrieval is a gradual process. Please engage in more conversations to enrich the content available for recall. Try having deeper interactions with the agent to better capture and store valuable information.","empty.search": "No matching memories found","empty.title": "No Memories Yet",+ "entity.delete.cancel": "Cancel",+ "entity.delete.content": "This can't be undone. If a later conversation mentions it again, a new page may be created.",+ "entity.delete.failed": "Couldn't delete it. Please try again.",+ "entity.delete.ok": "Delete",+ "entity.delete.success": "Deleted \"{{title}}\"",+ "entity.delete.title": "Delete \"{{title}}\"?",+ "entity.error.desc": "The network or service is unavailable for now. Your memories are safe.",+ "entity.error.retry": "Retry",+ "entity.error.title": "Couldn't load contexts",+ "entity.firstRun.desc": "Projects, goals, relationships and events you mention in conversations each get a page: where things stand, what is next, and how they got here.",+ "entity.firstRun.title": "No contexts yet",+ "entity.header.back": "Back to \"{{title}}\"",+ "entity.header.delete": "Delete…",+ "entity.header.markDone": "Mark as completed",+ "entity.header.more": "More actions",+ "entity.header.reopen": "Mark as ongoing",+ "entity.header.statusFailed": "Couldn't change the status. Please try again.",+ "entity.kind.event": "Events",+ "entity.kind.event.example": "A trip, a job interview",+ "entity.kind.goal": "Goals",+ "entity.kind.goal.example": "Score 7 on IELTS, lose 5 kg",+ "entity.kind.other": "Other",+ "entity.kind.other.example": "Anything else you keep coming back to",+ "entity.kind.project": "Projects",+ "entity.kind.project.example": "A knowledge base migration, writing a book",+ "entity.kind.relationship": "Relationships",+ "entity.kind.relationship.example": "Your team, your family",+ "entity.list.clearSearch": "Clear search",+ "entity.list.loadMore": "Load older contexts",+ "entity.list.loadMoreRetry": "Couldn't load older contexts. Retry",+ "entity.list.loadedOf": "{{loaded}} / {{total}}",+ "entity.list.noMatch": "No contexts match \"{{keyword}}\"",+ "entity.list.pick": "Pick a context on the left",+ "entity.list.quiet": "On hold & finished",+ "entity.list.searchPlaceholder": "Search names, status or tags",+ "entity.list.title": "Contexts",+ "entity.now.cancel": "Cancel",+ "entity.now.edit": "Edit where this stands",+ "entity.now.empty": "Nothing recorded about where this stands yet.",+ "entity.now.save": "Save",+ "entity.now.saveFailed": "Couldn't save. Please try again.",+ "entity.now.title": "Now",+ "entity.now.updated": "Updated {{ago}}",+ "entity.related.contexts": "Related contexts",+ "entity.related.contextsExtra": "They mention the same people or things",+ "entity.related.mentioned": "People and things mentioned",+ "entity.related.shared": "Both mention {{names}}",+ "entity.status.aborted": "Aborted",+ "entity.status.active": "Ongoing",+ "entity.status.cancelled": "Cancelled",+ "entity.status.completed": "Completed",+ "entity.status.on_hold": "On hold",+ "entity.status.ongoing": "Ongoing",+ "entity.status.planned": "Planned",+ "entity.timeline.empty": "No activity mentions the people or things here yet. Activities are only linked to contexts by shared names, so this may stay empty.",+ "entity.timeline.mentions": "Mentions",+ "entity.timeline.past": "History",+ "entity.timeline.pastExtra": "{{count}} · linked by shared names, may be incomplete",+ "entity.timeline.planned": "Planned",+ "entity.timeline.recorded": "Recorded",+ "entity.timeline.showAll": "Show all {{count}}",+ "entity.timeline.undated": "TBD",+ "entity.timeline.upcoming": "Up next",+ "entity.untitled": "Untitled context","experience.actions.delete": "Delete","experience.actions.edit": "Edit","experience.defaultType": "Experience",diff --git a/locales/zh-CN/memory.json b/locales/zh-CN/memory.jsonindex 1a55ef4a89d..a45a2db1d73 100644--- a/locales/zh-CN/memory.json+++ b/locales/zh-CN/memory.json@@ -39,6 +39,70 @@"empty.description": "记忆的提取是渐进式的。积累更多对话,助理会更懂你。试着聊得更深入,让助理捕捉和存储有价值的信息","empty.search": "未找到匹配的记忆","empty.title": "暂无记忆",+ "entity.delete.cancel": "取消",+ "entity.delete.content": "删除后无法恢复。之后的对话里再提到它,可能会重新生成一页。",+ "entity.delete.failed": "删除没有成功,请重试",+ "entity.delete.ok": "删除",+ "entity.delete.success": "已删除「{{title}}」",+ "entity.delete.title": "删除「{{title}}」?",+ "entity.error.desc": "网络或服务暂时不可用,你的记忆没有丢失。",+ "entity.error.retry": "重试",+ "entity.error.title": "情境加载失败",+ "entity.firstRun.desc": "你在对话里提到的项目、目标、关系和事件,会各自整理成一页:现在怎样、接下来做什么、一路发生了什么。",+ "entity.firstRun.title": "还没有情境",+ "entity.header.back": "返回「{{title}}」",+ "entity.header.delete": "删除…",+ "entity.header.markDone": "标记为已完成",+ "entity.header.more": "更多操作",+ "entity.header.reopen": "标记为进行中",+ "entity.header.statusFailed": "状态没有改成功,请重试",+ "entity.kind.event": "事件",+ "entity.kind.event.example": "一次旅行、一场面试",+ "entity.kind.goal": "目标",+ "entity.kind.goal.example": "考到雅思 7 分、减重 5 公斤",+ "entity.kind.other": "其他",+ "entity.kind.other.example": "其他持续关注的事",+ "entity.kind.project": "项目",+ "entity.kind.project.example": "知识库迁移、写一本书",+ "entity.kind.relationship": "关系",+ "entity.kind.relationship.example": "和团队、家人的关系",+ "entity.list.clearSearch": "清除搜索",+ "entity.list.loadMore": "加载更早的情境",+ "entity.list.loadMoreRetry": "加载失败,点击重试",+ "entity.list.loadedOf": "{{loaded}} / {{total}}",+ "entity.list.noMatch": "没有找到和「{{keyword}}」有关的情境",+ "entity.list.pick": "从左侧选一个情境",+ "entity.list.quiet": "搁置与已结束",+ "entity.list.searchPlaceholder": "搜索名称、现状或标签",+ "entity.list.title": "情境",+ "entity.now.cancel": "取消",+ "entity.now.edit": "修改现状",+ "entity.now.empty": "还没有记下现在的情况。",+ "entity.now.save": "保存",+ "entity.now.saveFailed": "没有保存成功,请重试",+ "entity.now.title": "现在",+ "entity.now.updated": "更新于 {{ago}}",+ "entity.related.contexts": "相关情境",+ "entity.related.contextsExtra": "提到了相同的人或事物",+ "entity.related.mentioned": "提到的人和事物",+ "entity.related.shared": "都提到 {{names}}",+ "entity.status.aborted": "已中止",+ "entity.status.active": "进行中",+ "entity.status.cancelled": "已取消",+ "entity.status.completed": "已完成",+ "entity.status.on_hold": "搁置中",+ "entity.status.ongoing": "进行中",+ "entity.status.planned": "计划中",+ "entity.timeline.empty": "还没有活动提到这里的人和事物。活动和情境之间目前只能按名字关联,所以这里可能是空的。",+ "entity.timeline.mentions": "提到",+ "entity.timeline.past": "经过",+ "entity.timeline.pastExtra": "{{count}} 条 · 按提到的名字关联,可能不全",+ "entity.timeline.planned": "计划中",+ "entity.timeline.recorded": "记录于",+ "entity.timeline.showAll": "显示全部 {{count}} 条",+ "entity.timeline.undated": "待定",+ "entity.timeline.upcoming": "接下来",+ "entity.untitled": "未命名情境","experience.actions.delete": "删除","experience.actions.edit": "编辑","experience.defaultType": "经历",diff --git a/packages/database/src/models/userMemory/__tests__/activity.test.ts b/packages/database/src/models/userMemory/__tests__/activity.test.tsindex 2e54952991a..1adae9f0587 100644--- a/packages/database/src/models/userMemory/__tests__/activity.test.ts+++ b/packages/database/src/models/userMemory/__tests__/activity.test.ts@@ -155,6 +155,9 @@ describe('UserMemoryActivityModel', () => {status: 'completed',narrative: 'First activity narrative',notes: 'Some notes',+ associatedLocations: [{ name: 'Office' }],+ associatedObjects: [{ name: 'IELTS' }],+ associatedSubjects: [{ name: '陈老师', type: 'person' }],tags: ['tag1'],startsAt: new Date('2024-01-15T09:00:00Z'),capturedAt: new Date('2024-01-15T10:00:00Z'),@@ -208,6 +211,15 @@ describe('UserMemoryActivityModel', () => {expect(result.total).toBe(3);});+ it('returns the associated names, which pages link activities by', async () => {+ const result = await activityModel.queryList();+ const item = result.items.find((row) => row.id === 'list-activity-1');++ expect(item?.associatedSubjects).toEqual([{ name: '陈老师', type: 'person' }]);+ expect(item?.associatedObjects).toEqual([{ name: 'IELTS' }]);+ expect(item?.associatedLocations).toEqual([{ name: 'Office' }]);+ });+it('should return correct page and pageSize', async () => {const result = await activityModel.queryList({ page: 1, pageSize: 2 });diff --git a/packages/database/src/models/userMemory/activity.ts b/packages/database/src/models/userMemory/activity.tsindex 64c65122d28..17c25f22fb4 100644--- a/packages/database/src/models/userMemory/activity.ts+++ b/packages/database/src/models/userMemory/activity.ts@@ -138,6 +138,9 @@ export class UserMemoryActivityModel {const [rows, totalResult] = await Promise.all([this.db.select({+ associatedLocations: userMemoriesActivities.associatedLocations,+ associatedObjects: userMemoriesActivities.associatedObjects,+ associatedSubjects: userMemoriesActivities.associatedSubjects,capturedAt: userMemoriesActivities.capturedAt,createdAt: userMemoriesActivities.createdAt,endsAt: userMemoriesActivities.endsAt,diff --git a/packages/locales/src/default/memory.ts b/packages/locales/src/default/memory.tsindex c37fe194612..1dae984d1d9 100644--- a/packages/locales/src/default/memory.ts+++ b/packages/locales/src/default/memory.ts@@ -348,4 +348,71 @@ export default {'tab.search': 'Search','viewMode.masonry': 'Masonry','viewMode.timeline': 'Timeline',+ 'entity.delete.cancel': 'Cancel',+ 'entity.delete.content':+ "This can't be undone. If a later conversation mentions it again, a new page may be created.",+ 'entity.delete.failed': "Couldn't delete it. Please try again.",+ 'entity.delete.ok': 'Delete',+ 'entity.delete.success': 'Deleted "{{title}}"',+ 'entity.delete.title': 'Delete "{{title}}"?',+ 'entity.error.desc': 'The network or service is unavailable for now. Your memories are safe.',+ 'entity.error.retry': 'Retry',+ 'entity.error.title': "Couldn't load contexts",+ 'entity.firstRun.desc':+ 'Projects, goals, relationships and events you mention in conversations each get a page: where things stand, what is next, and how they got here.',+ 'entity.firstRun.title': 'No contexts yet',+ 'entity.header.back': 'Back to "{{title}}"',+ 'entity.header.delete': 'Delete…',+ 'entity.header.markDone': 'Mark as completed',+ 'entity.header.more': 'More actions',+ 'entity.header.reopen': 'Mark as ongoing',+ 'entity.header.statusFailed': "Couldn't change the status. Please try again.",+ 'entity.kind.event': 'Events',+ 'entity.kind.event.example': 'A trip, a job interview',+ 'entity.kind.goal': 'Goals',+ 'entity.kind.goal.example': 'Score 7 on IELTS, lose 5 kg',+ 'entity.kind.other': 'Other',+ 'entity.kind.other.example': 'Anything else you keep coming back to',+ 'entity.kind.project': 'Projects',+ 'entity.kind.project.example': 'A knowledge base migration, writing a book',+ 'entity.kind.relationship': 'Relationships',+ 'entity.kind.relationship.example': 'Your team, your family',+ 'entity.list.clearSearch': 'Clear search',+ 'entity.list.loadMore': 'Load older contexts',+ 'entity.list.loadMoreRetry': "Couldn't load older contexts. Retry",+ 'entity.list.loadedOf': '{{loaded}} / {{total}}',+ 'entity.list.noMatch': 'No contexts match "{{keyword}}"',+ 'entity.list.pick': 'Pick a context on the left',+ 'entity.list.quiet': 'On hold & finished',+ 'entity.list.searchPlaceholder': 'Search names, status or tags',+ 'entity.list.title': 'Contexts',+ 'entity.now.cancel': 'Cancel',+ 'entity.now.edit': 'Edit where this stands',+ 'entity.now.empty': 'Nothing recorded about where this stands yet.',+ 'entity.now.save': 'Save',+ 'entity.now.saveFailed': "Couldn't save. Please try again.",+ 'entity.now.title': 'Now',+ 'entity.now.updated': 'Updated {{ago}}',+ 'entity.related.contexts': 'Related contexts',+ 'entity.related.contextsExtra': 'They mention the same people or things',+ 'entity.related.mentioned': 'People and things mentioned',+ 'entity.related.shared': 'Both mention {{names}}',+ 'entity.status.aborted': 'Aborted',+ 'entity.status.active': 'Ongoing',+ 'entity.status.cancelled': 'Cancelled',+ 'entity.status.completed': 'Completed',+ 'entity.status.on_hold': 'On hold',+ 'entity.status.ongoing': 'Ongoing',+ 'entity.status.planned': 'Planned',+ 'entity.timeline.empty':+ 'No activity mentions the people or things here yet. Activities are only linked to contexts by shared names, so this may stay empty.',+ 'entity.timeline.mentions': 'Mentions',+ 'entity.timeline.past': 'History',+ 'entity.timeline.pastExtra': '{{count}} · linked by shared names, may be incomplete',+ 'entity.timeline.planned': 'Planned',+ 'entity.timeline.recorded': 'Recorded',+ 'entity.timeline.showAll': 'Show all {{count}}',+ 'entity.timeline.undated': 'TBD',+ 'entity.timeline.upcoming': 'Up next',+ 'entity.untitled': 'Untitled context',};diff --git a/packages/types/src/userMemory/activity.ts b/packages/types/src/userMemory/activity.tsindex 541821408a8..83f063e8424 100644--- a/packages/types/src/userMemory/activity.ts+++ b/packages/types/src/userMemory/activity.ts@@ -1,3 +1,4 @@+import type { UserMemoryActivity } from './layers';import type { BaseListItem, BaseListParams, BaseListResult } from './shared';export type ActivityListSort = 'capturedAt' | 'startsAt';@@ -7,7 +8,10 @@ export interface ActivityListParams extends BaseListParams {status?: string[];}-export interface ActivityListItem extends BaseListItem {+export interface ActivityListItem+ extends+ BaseListItem,+ Pick<UserMemoryActivity, 'associatedLocations' | 'associatedObjects' | 'associatedSubjects'> {endsAt: Date | null;narrative: string | null;notes: string | null;diff --git a/src/features/MemoryEntities/EntityList/ListItem.tsx b/src/features/MemoryEntities/EntityList/ListItem.tsxnew file mode 100644index 00000000000..e5dd8ae4190--- /dev/null+++ b/src/features/MemoryEntities/EntityList/ListItem.tsx@@ -0,0 +1,97 @@+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { memo } from 'react';++import KindIcon from '../components/KindIcon';+import { useEntityFormat } from '../format';+import { type MemoryEntity } from '../types';++const styles = stylex.create({+ row: {+ alignItems: 'flex-start',+ backgroundColor: {+ default: 'transparent',+ ':hover': cssVar.colorFillTertiary,+ },+ borderRadius: cssVar.borderRadius,+ borderStyle: 'none',+ color: cssVar.colorText,+ cursor: 'pointer',+ display: 'flex',+ gap: '12px',+ paddingBlock: '8px',+ paddingInline: '8px',+ textAlign: 'start',+ width: '100%',+ },+ active: {+ backgroundColor: {+ default: cssVar.colorFillSecondary,+ ':hover': cssVar.colorFillSecondary,+ },+ },+ muted: { opacity: 0.6 },+ body: { display: 'flex', flex: '1', flexDirection: 'column', gap: '2px', minWidth: 0 },+ titleLine: { alignItems: 'baseline', display: 'flex', gap: '8px' },+ title: {+ flex: '1',+ fontSize: '14px',+ fontWeight: 500,+ lineHeight: '20px',+ minWidth: 0,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ meta: {+ color: cssVar.colorTextTertiary,+ flexShrink: 0,+ fontSize: '12px',+ fontVariantNumeric: 'tabular-nums',+ },+ now: {+ color: cssVar.colorTextSecondary,+ fontSize: '12px',+ lineHeight: '18px',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+});++interface ListItemProps {+ active: boolean;+ entity: MemoryEntity;+ lastTouchedAt: string;+ muted?: boolean;+ onSelect: (id: string) => void;+}++/**+ * One row answers "what is it and how is it going": kind, title, the first line of "now", and+ * one time on the right that always means the same thing — when it last moved.+ */+const ListItem = memo<ListItemProps>(({ active, entity, lastTouchedAt, muted, onSelect }) => {+ const format = useEntityFormat();+ return (+ <button+ aria-current={active ? 'page' : undefined}+ type={'button'}+ {...stylex.props(styles.row, active && styles.active, muted && styles.muted)}+ onClick={() => onSelect(entity.id)}+ >+ <KindIcon kind={entity.kind} />+ <span {...stylex.props(styles.body)}>+ <span {...stylex.props(styles.titleLine)}>+ <span {...stylex.props(styles.title)}>{format.title(entity)}</span>+ <span {...stylex.props(styles.meta)}>{format.ago(lastTouchedAt)}</span>+ </span>+ <span {...stylex.props(styles.now)}>{entity.summary || entity.description}</span>+ </span>+ </button>+ );+});++ListItem.displayName = 'EntityListItem';++export default ListItem;diff --git a/src/features/MemoryEntities/EntityList/index.tsx b/src/features/MemoryEntities/EntityList/index.tsxnew file mode 100644index 00000000000..7529e4f3ddb--- /dev/null+++ b/src/features/MemoryEntities/EntityList/index.tsx@@ -0,0 +1,184 @@+import { Button, Empty, SearchBar } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { useDebounce } from 'ahooks';+import { SearchXIcon } from 'lucide-react';+import { memo, useMemo, useState } from 'react';++import { useEntityDataContext } from '../context';+import { lastTouchedOf, searchMatches } from '../derive';+import { useEntityFormat } from '../format';+import { CONTEXT_KINDS } from '../kinds';+import { useRemoteContextSearch } from '../useEntityData';+import { useSelection } from '../useSelection';+import ListItem from './ListItem';++const styles = stylex.create({+ root: {+ borderInlineEndColor: cssVar.colorBorderSecondary,+ borderInlineEndStyle: 'solid',+ borderInlineEndWidth: '1px',+ display: 'flex',+ flexDirection: 'column',+ flexShrink: 0,+ height: '100%',+ width: '320px',+ },+ head: {+ display: 'flex',+ flexDirection: 'column',+ gap: '12px',+ paddingBlockEnd: '8px',+ paddingBlockStart: '20px',+ paddingInline: '16px',+ },+ heading: { alignItems: 'baseline', display: 'flex', gap: '8px' },+ title: { fontSize: '17px', fontWeight: 600, margin: 0 },+ count: { color: cssVar.colorTextTertiary, fontSize: '13px' },+ scroll: {+ display: 'flex',+ flex: '1',+ flexDirection: 'column',+ gap: '20px',+ overflowY: 'auto',+ paddingBlockEnd: '24px',+ paddingBlockStart: '8px',+ paddingInline: '8px',+ },+ group: { display: 'flex', flexDirection: 'column', gap: '2px' },+ groupLabel: {+ alignItems: 'baseline',+ color: cssVar.colorTextTertiary,+ display: 'flex',+ fontSize: '12px',+ gap: '6px',+ paddingBlockEnd: '4px',+ paddingInline: '8px',+ },+ groupName: { color: cssVar.colorTextSecondary, fontWeight: 500 },+ noMatch: { paddingBlock: '48px' },+ more: { color: cssVar.colorTextSecondary, flexShrink: 0 },+});++const EntityList = memo(() => {+ const [keyword, setKeyword] = useState('');+ const format = useEntityFormat();+ const { t } = format;+ const {+ entities: contexts,+ hasMore,+ isLoadingMore,+ links,+ loadMore,+ loadMoreError,+ total,+ } = useEntityDataContext();++ // With pages still unloaded, a keyword also asks the server so older contexts can be found.+ // Clearing the keyword drops the search at once, so 「加载更早的情境」 pages the full list.+ const needle = keyword.trim();+ const debouncedNeedle = useDebounce(needle, { wait: 400 });+ const remoteMatches = useRemoteContextSearch(+ hasMore && needle ? debouncedNeedle || undefined : undefined,+ );+ const { select, selectedId } = useSelection();++ const groups = useMemo(() => {+ // Server hits stay in even when the match is in a field the list does not hold.+ const visible = searchMatches(+ contexts,+ needle,+ debouncedNeedle === needle ? remoteMatches : undefined,+ )+ .map((entity) => ({+ entity,+ lastTouchedAt: lastTouchedOf(entity, links),+ }))+ .sort((a, b) => b.lastTouchedAt.localeCompare(a.lastTouchedAt));++ const live = visible.filter((item) => item.entity.status === 'active');+ return [+ ...CONTEXT_KINDS.map((kind) => ({+ items: live.filter((item) => item.entity.kind === kind),+ key: kind,+ label: format.kind(kind),+ muted: false,+ })),+ {+ items: visible.filter((item) => item.entity.status !== 'active'),+ key: 'quiet',+ label: t('entity.list.quiet'),+ muted: true,+ },+ ].filter((group) => group.items.length > 0);+ }, [contexts, debouncedNeedle, format, links, needle, remoteMatches, t]);++ return (+ <aside aria-label={t('entity.list.title')} {...stylex.props(styles.root)}>+ <div {...stylex.props(styles.head)}>+ <div {...stylex.props(styles.heading)}>+ <h1 {...stylex.props(styles.title)}>{t('entity.list.title')}</h1>+ <span {...stylex.props(styles.count)}>+ {hasMore+ ? t('entity.list.loadedOf', { loaded: contexts.length, total })+ : contexts.length}+ </span>+ </div>+ <SearchBar+ allowClear+ placeholder={t('entity.list.searchPlaceholder')}+ value={keyword}+ variant={'filled'}+ onInputChange={setKeyword}+ />+ </div>+ <div {...stylex.props(styles.scroll)}>+ {groups.length === 0 ? (+ <div {...stylex.props(styles.noMatch)}>+ <Empty+ description={t('entity.list.noMatch', { keyword: needle })}+ icon={SearchXIcon}+ action={+ <Button onClick={() => setKeyword('')}>{t('entity.list.clearSearch')}</Button>+ }+ />+ </div>+ ) : (+ groups.map((group) => (+ <section aria-label={group.label} key={group.key} {...stylex.props(styles.group)}>+ <div {...stylex.props(styles.groupLabel)}>+ <span {...stylex.props(styles.groupName)}>{group.label}</span>+ <span>{group.items.length}</span>+ </div>+ {group.items.map((item) => (+ <ListItem+ active={item.entity.id === selectedId}+ entity={item.entity}+ key={item.entity.id}+ lastTouchedAt={item.lastTouchedAt}+ muted={group.muted}+ onSelect={select}+ />+ ))}+ </section>+ ))+ )}+ {hasMore && !needle && (+ <Button+ block+ loading={isLoadingMore}+ type={'text'}+ {...stylex.props(styles.more)}+ onClick={loadMore}+ >+ {t(loadMoreError ? 'entity.list.loadMoreRetry' : 'entity.list.loadMore')}+ </Button>+ )}+ </div>+ </aside>+ );+});++EntityList.displayName = 'EntityList';++export default EntityList;diff --git a/src/features/MemoryEntities/EntityPage/Header.tsx b/src/features/MemoryEntities/EntityPage/Header.tsxnew file mode 100644index 00000000000..9b0e9a0af7c--- /dev/null+++ b/src/features/MemoryEntities/EntityPage/Header.tsx@@ -0,0 +1,167 @@+import { ActionIcon, confirmModal, DropdownMenu, Icon, Tag, toast } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import {+ ArchiveIcon,+ ArrowLeftIcon,+ MoreHorizontalIcon,+ RotateCcwIcon,+ Trash2Icon,+} from 'lucide-react';+import { memo } from 'react';++import KindIcon from '../components/KindIcon';+import { useEntityDataContext } from '../context';+import { useEntityFormat } from '../format';+import { type MemoryEntity } from '../types';+import { useSelection } from '../useSelection';++const styles = stylex.create({+ root: { display: 'flex', flexDirection: 'column', gap: '16px' },+ back: {+ alignItems: 'center',+ alignSelf: 'flex-start',+ backgroundColor: 'transparent',+ borderStyle: 'none',+ color: {+ 'default': cssVar.colorTextTertiary,+ ':hover': cssVar.colorText,+ },+ cursor: 'pointer',+ display: 'inline-flex',+ fontSize: '13px',+ gap: '4px',+ marginInlineStart: '-2px',+ paddingBlock: 0,+ paddingInline: 0,+ },+ top: { alignItems: 'flex-start', display: 'flex', gap: '12px' },+ titles: { display: 'flex', flex: '1', flexDirection: 'column', gap: '4px', minWidth: 0 },+ eyebrow: {+ alignItems: 'center',+ color: cssVar.colorTextTertiary,+ display: 'flex',+ fontSize: '12px',+ gap: '8px',+ },+ title: { fontSize: '24px', fontWeight: 600, lineHeight: '32px', margin: 0 },+ tags: { color: cssVar.colorTextTertiary, fontSize: '12px' },+ summary: {+ color: cssVar.colorTextSecondary,+ fontSize: '14px',+ lineHeight: '22px',+ margin: 0,+ },+});++interface HeaderProps {+ entity: MemoryEntity;+}++const Header = memo<HeaderProps>(({ entity }) => {+ const { entities, remove, setStatus } = useEntityDataContext();+ const { back, ensureSelected, history, select } = useSelection();+ const backId = history.at(-1);+ const backTo = entities.find((e) => e.id === backId);+ const format = useEntityFormat();+ const { t } = format;+ const statusLabel = format.status(entity.statusValue);+ // The free-text type is shown when it says more than the kind it was folded into.+ const typeNote =+ entity.rawType && entity.rawType.toLowerCase() !== entity.kind ? entity.rawType : undefined;++ const handleStatus = async (value: string) => {+ ensureSelected(entity.id);+ try {+ await setStatus(entity.id, value);+ } catch {+ toast.error({ title: t('entity.header.statusFailed') });+ }+ };++ // The backend deletes for good, so this one asks first.+ const handleDelete = () =>+ confirmModal({+ cancelText: t('entity.delete.cancel'),+ content: t('entity.delete.content'),+ okButtonProps: { danger: true },+ okText: t('entity.delete.ok'),+ onOk: async () => {+ try {+ await remove(entity.id);+ select(entities.find((e) => e.id !== entity.id && e.status === 'active')?.id);+ toast.success({ title: t('entity.delete.success', { title: format.title(entity) }) });+ } catch {+ toast.error({ title: t('entity.delete.failed') });+ }+ },+ title: t('entity.delete.title', { title: format.title(entity) }),+ });++ return (+ <header {...stylex.props(styles.root)}>+ {backTo && (+ <button type={'button'} {...stylex.props(styles.back)} onClick={back}>+ <Icon icon={ArrowLeftIcon} size={14} />+ {t('entity.header.back', { title: format.title(backTo) })}+ </button>+ )}+ <div {...stylex.props(styles.top)}>+ <KindIcon kind={entity.kind} size={'lg'} />+ <div {...stylex.props(styles.titles)}>+ <div {...stylex.props(styles.eyebrow)}>+ <span>+ {format.kind(entity.kind)}+ {typeNote && ` · ${typeNote}`}+ </span>+ {statusLabel && <Tag size={'small'}>{statusLabel}</Tag>}+ </div>+ <h2 {...stylex.props(styles.title)}>{format.title(entity)}</h2>+ {entity.tags.length > 0 && (+ <span {...stylex.props(styles.tags)}>+ {entity.tags.map((tag) => `#${tag}`).join(' ')}+ </span>+ )}+ </div>+ <DropdownMenu+ items={[+ entity.status === 'closed'+ ? {+ icon: <Icon icon={RotateCcwIcon} />,+ key: 'reopen',+ label: t('entity.header.reopen'),+ onClick: () => handleStatus('ongoing'),+ }+ : {+ icon: <Icon icon={ArchiveIcon} />,+ key: 'close',+ label: t('entity.header.markDone'),+ onClick: () => handleStatus('completed'),+ },+ { type: 'divider' },+ {+ danger: true,+ icon: <Icon icon={Trash2Icon} />,+ key: 'delete',+ label: t('entity.header.delete'),+ onClick: handleDelete,+ },+ ]}+ >+ <ActionIcon+ aria-label={t('entity.header.more')}+ icon={MoreHorizontalIcon}+ title={t('entity.header.more')}+ />+ </DropdownMenu>+ </div>+ {entity.summary && entity.summary !== entity.description && (+ <p {...stylex.props(styles.summary)}>{entity.summary}</p>+ )}+ </header>+ );+});++Header.displayName = 'EntityHeader';++export default Header;diff --git a/src/features/MemoryEntities/EntityPage/NowSection.tsx b/src/features/MemoryEntities/EntityPage/NowSection.tsxnew file mode 100644index 00000000000..339f59ab1b1--- /dev/null+++ b/src/features/MemoryEntities/EntityPage/NowSection.tsx@@ -0,0 +1,112 @@+import { ActionIcon, Button, TextArea, toast } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { PencilIcon } from 'lucide-react';+import { memo, useState } from 'react';++import { useEntityDataContext } from '../context';+import { resolveDraft, useDraftStore } from '../drafts';+import { useEntityFormat } from '../format';+import { type MemoryEntity } from '../types';+import Section from './Section';++const styles = stylex.create({+ text: {+ color: cssVar.colorText,+ fontSize: '17px',+ lineHeight: '28px',+ margin: 0,+ whiteSpace: 'pre-wrap',+ },+ placeholder: { color: cssVar.colorTextTertiary, fontSize: '14px' },+ foot: {+ alignItems: 'center',+ color: cssVar.colorTextTertiary,+ display: 'flex',+ fontSize: '12px',+ gap: '4px',+ marginBlockStart: '-4px',+ },+ editActions: { display: 'flex', gap: '8px', justifyContent: 'flex-end' },+});++interface NowSectionProps {+ entity: MemoryEntity;+}++/**+ * The one sentence that is overwritten as things change. Older wording is not lost: it is what+ * the timeline below records.+ */+const NowSection = memo<NowSectionProps>(({ entity }) => {+ const format = useEntityFormat();+ const { t } = format;+ const { updateNow } = useEntityDataContext();+ const draft = useDraftStore((s) => s.drafts[entity.id]);+ const setStoredDraft = useDraftStore((s) => s.setDraft);+ const setDraft = (text?: string) => setStoredDraft(entity.id, text);+ const [saving, setSaving] = useState(false);+ const editing = draft !== undefined;++ const save = async () => {+ const { save: changed, value: next } = resolveDraft(draft, entity.description);+ if (!changed) return setDraft(undefined);+ setSaving(true);+ try {+ await updateNow(entity.id, next);+ setDraft(undefined);+ } catch {+ // Keep the draft so nothing typed is lost.+ toast.error({ title: t('entity.now.saveFailed') });+ } finally {+ setSaving(false);+ }+ };++ return (+ <Section title={t('entity.now.title')}>+ {editing ? (+ <>+ <TextArea+ autoFocus+ autoSize={{ maxRows: 8, minRows: 2 }}+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Escape') setDraft(undefined);+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) save();+ }}+ />+ <div {...stylex.props(styles.editActions)}>+ <Button size={'small'} onClick={() => setDraft(undefined)}>+ {t('entity.now.cancel')}+ </Button>+ <Button loading={saving} size={'small'} type={'primary'} onClick={save}>+ {t('entity.now.save')}+ </Button>+ </div>+ </>+ ) : (+ <>+ <p {...stylex.props(styles.text, !entity.description && styles.placeholder)}>+ {entity.description || t('entity.now.empty')}+ </p>+ <div {...stylex.props(styles.foot)}>+ <span>{t('entity.now.updated', { ago: format.ago(entity.updatedAt) })}</span>+ <ActionIcon+ aria-label={t('entity.now.edit')}+ icon={PencilIcon}+ size={'small'}+ title={t('entity.now.edit')}+ onClick={() => setDraft(entity.description)}+ />+ </div>+ </>+ )}+ </Section>+ );+});++NowSection.displayName = 'NowSection';++export default NowSection;diff --git a/src/features/MemoryEntities/EntityPage/Related.tsx b/src/features/MemoryEntities/EntityPage/Related.tsxnew file mode 100644index 00000000000..c498d7da03c--- /dev/null+++ b/src/features/MemoryEntities/EntityPage/Related.tsx@@ -0,0 +1,138 @@+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { memo } from 'react';++import Avatar from '@/components/Avatar';++import KindIcon from '../components/KindIcon';+import { useEntityDataContext } from '../context';+import { useEntityFormat } from '../format';+import { type MemoryEntity } from '../types';+import { useSelection } from '../useSelection';+import Section from './Section';++const styles = stylex.create({+ grid: {+ display: 'grid',+ gap: '4px',+ gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))',+ marginInline: '-8px',+ },+ item: {+ alignItems: 'center',+ backgroundColor: {+ default: 'transparent',+ ':hover': cssVar.colorFillTertiary,+ },+ borderRadius: cssVar.borderRadius,+ borderStyle: 'none',+ color: cssVar.colorText,+ cursor: 'pointer',+ display: 'flex',+ gap: '12px',+ paddingBlock: '8px',+ paddingInline: '8px',+ textAlign: 'start',+ },+ text: { display: 'flex', flexDirection: 'column', minWidth: 0 },+ name: {+ fontSize: '14px',+ fontWeight: 500,+ lineHeight: '20px',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ sub: {+ color: cssVar.colorTextTertiary,+ fontSize: '12px',+ lineHeight: '18px',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ names: { display: 'flex', flexWrap: 'wrap', gap: '8px' },+ chip: {+ alignItems: 'center',+ backgroundColor: cssVar.colorFillQuaternary,+ borderRadius: '999px',+ color: cssVar.colorTextSecondary,+ display: 'inline-flex',+ fontSize: '13px',+ gap: '6px',+ paddingBlock: '4px',+ paddingInlineEnd: '12px',+ paddingInlineStart: '4px',+ },+ chipPlain: { paddingInlineStart: '12px' },+ chipType: { color: cssVar.colorTextQuaternary, fontSize: '12px' },+});++/** Subject types the extractor uses for people. */+const PERSON_TYPES = new Set(['person', 'people', 'user', 'family', 'friend', 'colleague']);++interface RelatedProps {+ entity: MemoryEntity;+}++const Related = memo<RelatedProps>(({ entity }) => {+ const format = useEntityFormat();+ const { t } = format;+ const { entities, links } = useEntityDataContext();+ const { open } = useSelection();+ const typeOf = new Map(entity.names.map((n) => [n.name.toLowerCase(), n.type]));+ const mentioned = (links?.mentions.get(entity.id) ?? [])+ .filter((name) => name !== entity.title)+ .map((name) => ({ name, type: typeOf.get(name.toLowerCase()) }));+ const related = (links?.contexts.get(entity.id) ?? [])+ .map((link) => ({ ...link, target: entities.find((e) => e.id === link.targetId) }))+ .filter((item): item is typeof item & { target: MemoryEntity } => !!item.target)+ .slice(0, 8);++ return (+ <>+ {mentioned.length > 0 && (+ <Section title={t('entity.related.mentioned')}>+ <div {...stylex.props(styles.names)}>+ {mentioned.map(({ name, type }) => {+ const person = !!type && PERSON_TYPES.has(type.toLowerCase());+ return (+ <span key={name} {...stylex.props(styles.chip, !person && styles.chipPlain)}>+ {person && <Avatar avatar={undefined} name={name} shape={'circle'} size={20} title={name} />}+ {name}+ {type && !person && <span {...stylex.props(styles.chipType)}>{type}</span>}+ </span>+ );+ })}+ </div>+ </Section>+ )}+ {related.length > 0 && (+ <Section extra={t('entity.related.contextsExtra')} title={t('entity.related.contexts')}>+ <div {...stylex.props(styles.grid)}>+ {related.map(({ names, target }) => (+ <button+ key={target.id}+ type={'button'}+ {...stylex.props(styles.item)}+ onClick={() => open(target.id)}+ >+ <KindIcon kind={target.kind} />+ <span {...stylex.props(styles.text)}>+ <span {...stylex.props(styles.name)}>{format.title(target)}</span>+ <span {...stylex.props(styles.sub)}>+ {format.kind(target.kind)} · {t('entity.related.shared', { names: format.names(names) })}+ </span>+ </span>+ </button>+ ))}+ </div>+ </Section>+ )}+ </>+ );+});++Related.displayName = 'EntityRelated';++export default Related;diff --git a/src/features/MemoryEntities/EntityPage/Section.tsx b/src/features/MemoryEntities/EntityPage/Section.tsxnew file mode 100644index 00000000000..a450df2be3b--- /dev/null+++ b/src/features/MemoryEntities/EntityPage/Section.tsx@@ -0,0 +1,37 @@+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { memo, type ReactNode } from 'react';++const styles = stylex.create({+ root: { display: 'flex', flexDirection: 'column', gap: '12px' },+ head: { alignItems: 'baseline', display: 'flex', gap: '8px' },+ title: {+ color: cssVar.colorTextSecondary,+ fontSize: '13px',+ fontWeight: 600,+ letterSpacing: '0.02em',+ margin: 0,+ },+ extra: { color: cssVar.colorTextTertiary, fontSize: '12px' },+});++interface SectionProps {+ children: ReactNode;+ extra?: ReactNode;+ title: string;+}++/** Sections are separated by whitespace, not boxes: one column, read top to bottom. */+const Section = memo<SectionProps>(({ children, extra, title }) => (+ <section aria-label={title} {...stylex.props(styles.root)}>+ <div {...stylex.props(styles.head)}>+ <h3 {...stylex.props(styles.title)}>{title}</h3>+ {extra && <span {...stylex.props(styles.extra)}>{extra}</span>}+ </div>+ {children}+ </section>+));++Section.displayName = 'EntitySection';++export default Section;diff --git a/src/features/MemoryEntities/EntityPage/Timeline.tsx b/src/features/MemoryEntities/EntityPage/Timeline.tsxnew file mode 100644index 00000000000..3a83cf4edea--- /dev/null+++ b/src/features/MemoryEntities/EntityPage/Timeline.tsx@@ -0,0 +1,98 @@+import { Button } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { memo, useState } from 'react';++import { groupByMonth } from '../derive';+import { useEntityFormat } from '../format';+import { type MemoryActivity } from '../types';+import Section from './Section';+import TimelineEntry from './TimelineEntry';++const styles = stylex.create({+ list: { display: 'flex', flexDirection: 'column', gap: '20px' },+ month: { display: 'flex', flexDirection: 'column', gap: '16px' },+ monthLabel: {+ backgroundColor: cssVar.colorBgContainer,+ color: cssVar.colorTextTertiary,+ fontSize: '12px',+ fontWeight: 500,+ insetBlockStart: 0,+ paddingBlock: '6px',+ position: 'sticky',+ zIndex: 1,+ },+ empty: { color: cssVar.colorTextTertiary, fontSize: '13px', lineHeight: '20px', margin: 0 },+ more: { alignSelf: 'flex-start' },+});++/** Long timelines show the most recent entries first and expand on request. */+const PAST_PREVIEW = 12;++type Entry = { activity: MemoryActivity; names: string[] };++interface TimelineProps {+ entries: Entry[];+}++/**+ * Activities are not linked to contexts in the backend; these are the ones that mention a name+ * this page mentions. The header says so, and each entry shows which name matched.+ */+const Timeline = memo<TimelineProps>(({ entries }) => {+ const format = useEntityFormat();+ const { t } = format;+ const [expanded, setExpanded] = useState(false);+ const upcoming = entries.filter((e) => e.activity.planned);+ const past = entries.filter((e) => !e.activity.planned);+ const shown = expanded ? past : past.slice(0, PAST_PREVIEW);++ return (+ <>+ {upcoming.length > 0 && (+ <Section title={t('entity.timeline.upcoming')}>+ <div {...stylex.props(styles.list)}>+ {upcoming.map(({ activity, names }) => (+ <TimelineEntry upcoming activity={activity} key={activity.id} matched={names} />+ ))}+ </div>+ </Section>+ )}+ <Section+ extra={past.length > 0 ? t('entity.timeline.pastExtra', { count: past.length }) : undefined}+ title={t('entity.timeline.past')}+ >+ {past.length === 0 ? (+ <p {...stylex.props(styles.empty)}>+ {t('entity.timeline.empty')}+ </p>+ ) : (+ <div {...stylex.props(styles.list)}>+ {groupByMonth(shown, format.month).map((group) => (+ <div key={group.label} {...stylex.props(styles.month)}>+ <div {...stylex.props(styles.monthLabel)}>{group.label}</div>+ {group.entries.map(({ activity, names }) => (+ <TimelineEntry activity={activity} key={activity.id} matched={names} />+ ))}+ </div>+ ))}+ {past.length > shown.length && (+ <Button+ size={'small'}+ type={'text'}+ {...stylex.props(styles.more)}+ onClick={() => setExpanded(true)}+ >+ {t('entity.timeline.showAll', { count: past.length })}+ </Button>+ )}+ </div>+ )}+ </Section>+ </>+ );+});++Timeline.displayName = 'EntityTimeline';++export default Timeline;diff --git a/src/features/MemoryEntities/EntityPage/TimelineEntry.tsx b/src/features/MemoryEntities/EntityPage/TimelineEntry.tsxnew file mode 100644index 00000000000..ae4e3a4550e--- /dev/null+++ b/src/features/MemoryEntities/EntityPage/TimelineEntry.tsx@@ -0,0 +1,74 @@+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { memo } from 'react';++import { useEntityFormat } from '../format';+import { type MemoryActivity } from '../types';++const styles = stylex.create({+ row: { columnGap: '20px', display: 'grid', gridTemplateColumns: '64px 1fr' },+ date: {+ display: 'flex',+ flexDirection: 'column',+ fontVariantNumeric: 'tabular-nums',+ paddingBlockStart: '1px',+ },+ day: { fontSize: '16px', fontWeight: 600, lineHeight: '22px' },+ dayUpcoming: { fontSize: '14px' },+ inexact: { color: cssVar.colorTextSecondary, fontWeight: 400 },+ sub: { color: cssVar.colorTextTertiary, fontSize: '12px', lineHeight: '18px' },+ body: { display: 'flex', flexDirection: 'column', gap: '4px', minWidth: 0 },+ narrative: { color: cssVar.colorText, fontSize: '14px', lineHeight: '22px', margin: 0 },+ meta: { color: cssVar.colorTextTertiary, fontSize: '12px', lineHeight: '20px' },+ name: { color: cssVar.colorTextSecondary },+});++interface TimelineEntryProps {+ activity: MemoryActivity;+ /** The names that tied this entry to the page; shown so a wrong match is easy to spot. */+ matched: string[];+ upcoming?: boolean;+}++const TimelineEntry = memo<TimelineEntryProps>(({ activity, matched, upcoming }) => {+ const format = useEntityFormat();+ const { t } = format;+ const status =+ upcoming || activity.statusValue === 'completed' ? undefined : format.status(activity.statusValue);++ return (+ <div {...stylex.props(styles.row)}>+ <div {...stylex.props(styles.date)}>+ {upcoming ? (+ <>+ <span {...stylex.props(styles.day, styles.dayUpcoming)}>+ {activity.whenIsExact ? format.monthDay(activity.when) : t('entity.timeline.undated')}+ </span>+ <span {...stylex.props(styles.sub)}>{t('entity.timeline.planned')}</span>+ </>+ ) : (+ <>+ <span {...stylex.props(styles.day, !activity.whenIsExact && styles.inexact)}>+ {format.day(activity.when)}+ </span>+ <span {...stylex.props(styles.sub)}>+ {activity.whenIsExact ? format.weekday(activity.when) : t('entity.timeline.recorded')}+ </span>+ </>+ )}+ </div>+ <div {...stylex.props(styles.body)}>+ <p {...stylex.props(styles.narrative)}>{activity.narrative || activity.title}</p>+ <span {...stylex.props(styles.meta)}>+ {t('entity.timeline.mentions')}{' '}+ <span {...stylex.props(styles.name)}>{format.names(matched)}</span>+ {status && ` · ${status}`}+ </span>+ </div>+ </div>+ );+});++TimelineEntry.displayName = 'TimelineEntry';++export default TimelineEntry;diff --git a/src/features/MemoryEntities/EntityPage/index.tsx b/src/features/MemoryEntities/EntityPage/index.tsxnew file mode 100644index 00000000000..5199b65df91--- /dev/null+++ b/src/features/MemoryEntities/EntityPage/index.tsx@@ -0,0 +1,52 @@+import * as stylex from '@stylexjs/stylex';+import { memo } from 'react';++import { useEntityDataContext } from '../context';+import { type MemoryEntity } from '../types';+import Header from './Header';+import NowSection from './NowSection';+import Related from './Related';+import Timeline from './Timeline';++const styles = stylex.create({+ scroll: { flex: '1', height: '100%', minWidth: 0, overflowY: 'auto' },+ column: {+ display: 'flex',+ flexDirection: 'column',+ gap: '40px',+ marginInline: 'auto',+ maxWidth: '720px',+ paddingBlockEnd: '96px',+ paddingBlockStart: '40px',+ paddingInline: '48px',+ },+});++interface EntityPageProps {+ entity: MemoryEntity;+}++/**+ * One column in decision order: what it is → how it is now → what is next → how it got here →+ * what else it touches.+ */+const EntityPage = memo<EntityPageProps>(({ entity }) => {+ const { links } = useEntityDataContext();+ const entries = links?.activities.get(entity.id) ?? [];++ return (+ // Keyed by page so following a link starts at the top with no half-finished edit.+ <main aria-label={entity.title} key={entity.id} {...stylex.props(styles.scroll)}>+ <div {...stylex.props(styles.column)}>+ <Header entity={entity} />+ <NowSection entity={entity} />+ <Timeline entries={entries} />+ <Related entity={entity} />+ </div>+ </main>+ );+});++EntityPage.displayName = 'EntityPage';++export default EntityPage;diff --git a/src/features/MemoryEntities/adapt.test.ts b/src/features/MemoryEntities/adapt.test.tsnew file mode 100644index 00000000000..b99646af1f7--- /dev/null+++ b/src/features/MemoryEntities/adapt.test.ts@@ -0,0 +1,87 @@+import { describe, expect, it } from 'vitest';++import {+ fromActivityRow,+ fromContextRow,+ linkedEntityOf,+ mergeById,+ type RawContextItem,+ toEntity,+ uniqueById,+} from './adapt';++const row = (id: string, parent: string): RawContextItem => ({+ context: { currentStatus: 'ongoing', description: `${id} now`, id, title: id, type: 'project' },+ memory: { title: parent },+});++describe('uniqueById', () => {+ it('keeps one page per context when queryMemories returns it once per parent memory', () => {+ // A context whose userMemoryIds hold two live parents comes back twice from the join.+ const rows = [row('ctx-a', 'mem-1'), row('ctx-a', 'mem-2'), row('ctx-b', 'mem-3')];++ const entities = uniqueById(rows.map(toEntity));++ expect(entities.map((e) => e.id)).toEqual(['ctx-a', 'ctx-b']);+ });+});++describe('mergeById', () => {+ it('adds rows fetched later without duplicating loaded ones', () => {+ const loaded = [row('ctx-a', 'mem-1'), row('ctx-b', 'mem-2')].map(toEntity);+ const nextPage = [row('ctx-b', 'mem-2'), row('ctx-c', 'mem-4')].map(toEntity);++ expect(mergeById(loaded, nextPage).map((e) => e.id)).toEqual(['ctx-a', 'ctx-b', 'ctx-c']);+ });+});++describe('store rows', () => {+ it('reads a flattened context row from the memory store', () => {+ const entity = fromContextRow({+ currentStatus: 'on_hold',+ description: '等签证',+ id: 'ctx-trip',+ summary: 'Japan trip',+ tags: ['travel'],+ title: '日本旅行',+ type: 'trip',+ updatedAt: new Date('2026-10-01T00:00:00.000Z'),+ });++ expect(entity).toMatchObject({+ description: '等签证',+ id: 'ctx-trip',+ kind: 'event',+ status: 'dormant',+ summary: 'Japan trip',+ title: '日本旅行',+ updatedAt: '2026-10-01T00:00:00.000Z',+ });+ });++ it('keeps the associated names of an activity list row, which the timeline links by', () => {+ const activity = fromActivityRow({+ associatedObjects: [{ name: 'IELTS' }],+ associatedSubjects: [{ name: '陈老师' }],+ capturedAt: new Date('2026-09-01T00:00:00.000Z'),+ id: 'act-1',+ narrative: '模考 6.5',+ startsAt: null,+ status: 'planned',+ title: '雅思模考',+ });++ expect(activity.names.map((n) => n.name)).toEqual(['陈老师', 'IELTS']);+ expect(activity).toMatchObject({ planned: true, title: '雅思模考', whenIsExact: false });+ });+});++describe('linkedEntityOf', () => {+ it('reads the flattened row the memory detail replica keeps for a deep link', () => {+ const detail = { description: '等签证', id: 'ctx-old', title: '日本旅行', type: 'trip' };++ expect(linkedEntityOf(detail, 'ctx-old')).toMatchObject({ id: 'ctx-old', title: '日本旅行' });+ expect(linkedEntityOf(detail, 'ctx-other')).toBeUndefined();+ expect(linkedEntityOf(null, 'ctx-old')).toBeUndefined();+ });+});diff --git a/src/features/MemoryEntities/adapt.ts b/src/features/MemoryEntities/adapt.tsnew file mode 100644index 00000000000..bb311c2eb40--- /dev/null+++ b/src/features/MemoryEntities/adapt.ts@@ -0,0 +1,141 @@+import { kindOfType, statusOfValue } from './kinds';+import { type AssociatedName, type MemoryActivity, type MemoryEntity } from './types';++type Dateish = Date | string | null | undefined;+type NameRow = { name?: string | null; type?: string | null } | null;++/**+ * `queryMemories` selects every non-vector column, but its declared list-item types omit the+ * associated names and the activity narrative. These describe what actually arrives.+ */+export interface RawMemoryRow {+ capturedAt?: Dateish;+ createdAt?: Dateish;+ summary?: string | null;+ tags?: string[] | null;+ title?: string | null;+ updatedAt?: Dateish;+}++export interface RawContextItem {+ context: {+ associatedObjects?: NameRow[] | null;+ associatedSubjects?: NameRow[] | null;+ capturedAt?: Dateish;+ currentStatus?: string | null;+ description?: string | null;+ id: string;+ tags?: string[] | null;+ title?: string | null;+ type?: string | null;+ updatedAt?: Dateish;+ };+ memory: RawMemoryRow;+}++export interface RawActivityItem {+ activity: {+ associatedLocations?: NameRow[] | null;+ associatedObjects?: NameRow[] | null;+ associatedSubjects?: NameRow[] | null;+ capturedAt?: Dateish;+ id: string;+ narrative?: string | null;+ startsAt?: Dateish;+ status?: string | null;+ };+ memory: RawMemoryRow;+}++const iso = (...values: Dateish[]) => {+ for (const value of values) {+ if (!value) continue;+ const date = new Date(value);+ if (!Number.isNaN(date.getTime())) return date.toISOString();+ }+ return new Date(0).toISOString();+};++const namesOf = (...lists: (NameRow[] | null | undefined)[]): AssociatedName[] => {+ const seen = new Set<string>();+ const names: AssociatedName[] = [];+ for (const row of lists.flat()) {+ const name = row?.name?.trim();+ if (!name || seen.has(name.toLowerCase())) continue;+ seen.add(name.toLowerCase());+ names.push({ name, type: row?.type ?? undefined });+ }+ return names;+};++export const toEntity = ({ context, memory }: RawContextItem): MemoryEntity => ({+ capturedAt: iso(context.capturedAt, memory.capturedAt, memory.createdAt),+ description: context.description?.trim() || '',+ id: context.id,+ kind: kindOfType(context.type),+ names: namesOf(context.associatedSubjects, context.associatedObjects),+ rawType: context.type ?? undefined,+ status: statusOfValue(context.currentStatus),+ statusValue: context.currentStatus ?? undefined,+ summary: memory.summary?.trim() || '',+ tags: [...new Set([...(context.tags ?? []), ...(memory.tags ?? [])])],+ // Empty when neither row has one; the UI shows a translated placeholder.+ title: context.title?.trim() || memory.title?.trim() || '',+ updatedAt: iso(context.updatedAt, memory.updatedAt, context.capturedAt),+});++export const toActivity = ({ activity, memory }: RawActivityItem): MemoryActivity => ({+ id: activity.id,+ names: namesOf(+ activity.associatedSubjects,+ activity.associatedObjects,+ activity.associatedLocations,+ ),+ narrative: activity.narrative?.trim() || memory.summary?.trim() || '',+ // Only ~1% of planned activities carry a future date, so the status decides 「接下来」.+ planned: activity.status === 'planned',+ statusValue: activity.status ?? undefined,+ title: memory.title?.trim() || '',+ when: iso(activity.startsAt, activity.capturedAt, memory.capturedAt, memory.createdAt),+ whenIsExact: !!activity.startsAt,+});++/**+ * `queryMemories` joins contexts to their parent memories, so a context linked to several live+ * parents comes back once per parent. Keep the first row per id.+ */+export const uniqueById = <T extends { id: string }>(items: T[]): T[] => {+ const seen = new Set<string>();+ return items.filter((item) => {+ if (seen.has(item.id)) return false;+ seen.add(item.id);+ return true;+ });+};++/** Adds rows fetched later (server search hits) without duplicating loaded ones. */+export const mergeById = <T extends { id: string }>(current: T[], incoming: T[]): T[] =>+ uniqueById([...current, ...incoming]);++/**+ * The memory store keeps context rows flattened (`{ ...memory, ...context }`) and activity rows+ * as the activity list returns them; both carry what `toEntity` / `toActivity` read.+ */+export const fromContextRow = (row: object): MemoryEntity => {+ const flat = row as RawContextItem['context'] & RawMemoryRow;+ return toEntity({ context: flat, memory: flat });+};++export const fromActivityRow = (row: object): MemoryActivity => {+ const flat = row as RawActivityItem['activity'] & RawMemoryRow;+ return toActivity({ activity: flat, memory: flat });+};++/**+ * The memory detail replica keeps a flattened row (`{ ...memory, ...context }`), or `null`+ * once the server no longer has it. Only a row for the requested id is a page.+ */+export const linkedEntityOf = (detail: unknown, id: string): MemoryEntity | undefined =>+ detail && typeof detail === 'object' && (detail as { id?: unknown }).id === id+ ? fromContextRow(detail)+ : undefined;diff --git a/src/features/MemoryEntities/components/KindIcon.tsx b/src/features/MemoryEntities/components/KindIcon.tsxnew file mode 100644index 00000000000..770c2a1b67f--- /dev/null+++ b/src/features/MemoryEntities/components/KindIcon.tsx@@ -0,0 +1,33 @@+import { Icon } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';+import { memo } from 'react';++import { KIND_META, kindTint } from '../kinds';+import { type ContextKind } from '../types';++const styles = stylex.create({+ root: {+ alignItems: 'center',+ borderRadius: '6px',+ display: 'inline-flex',+ flexShrink: 0,+ justifyContent: 'center',+ },+ sm: { height: '24px', width: '24px' },+ lg: { borderRadius: '10px', height: '40px', width: '40px' },+});++interface KindIconProps {+ kind: ContextKind;+ size?: 'sm' | 'lg';+}++const KindIcon = memo<KindIconProps>(({ kind, size = 'sm' }) => (+ <span {...stylex.props(styles.root, styles[size], kindTint[kind])}>+ <Icon icon={KIND_META[kind].icon} size={size === 'lg' ? 20 : 14} />+ </span>+));++KindIcon.displayName = 'KindIcon';++export default KindIcon;diff --git a/src/features/MemoryEntities/context.ts b/src/features/MemoryEntities/context.tsnew file mode 100644index 00000000000..2a95ec77c9f--- /dev/null+++ b/src/features/MemoryEntities/context.ts@@ -0,0 +1,11 @@+import { createContext, use } from 'react';++import { type EntityDataApi } from './useEntityData';++export const EntityDataContext = createContext<EntityDataApi | null>(null);++export const useEntityDataContext = () => {+ const value = use(EntityDataContext);+ if (!value) throw new Error('useEntityDataContext must be used inside MemoryEntities');+ return value;+};diff --git a/src/features/MemoryEntities/derive.test.ts b/src/features/MemoryEntities/derive.test.tsnew file mode 100644index 00000000000..fc5d38435da--- /dev/null+++ b/src/features/MemoryEntities/derive.test.ts@@ -0,0 +1,50 @@+import { describe, expect, it } from 'vitest';++import { searchMatches } from './derive';+import { formatAgo } from './format';+import { type MemoryEntity } from './types';++const entity = (id: string, title: string, description = ''): MemoryEntity => ({+ capturedAt: '2026-10-01T00:00:00.000Z',+ description,+ id,+ kind: 'project',+ names: [],+ status: 'active',+ summary: '',+ tags: [],+ title,+ updatedAt: '2026-10-01T00:00:00.000Z',+});++describe('searchMatches', () => {+ it('keeps server hits whose match is in a field the list does not hold', () => {+ const loaded = [entity('a', 'Migration'), entity('b', 'Wedding')];+ // The server matched this one on its status / parent details, not title or description.+ const remote = [entity('old', 'Quarterly review')];++ expect(searchMatches(loaded, 'blocked', remote).map((e) => e.id)).toEqual(['old']);+ });++ it('combines local matches with server hits without duplicates', () => {+ const loaded = [entity('a', 'Composio swap'), entity('b', 'Wedding')];+ const remote = [entity('a', 'Composio swap'), entity('c', 'OAuth retro')];++ expect(searchMatches(loaded, 'composio', remote).map((e) => e.id)).toEqual(['a', 'c']);+ });++ it('shows everything loaded when there is no keyword', () => {+ const loaded = [entity('a', 'A'), entity('b', 'B')];+ expect(searchMatches(loaded, ' ', [entity('c', 'C')])).toBe(loaded);+ });+});++describe('formatAgo', () => {+ const now = new Date('2026-10-24T12:00:00');++ it('follows the user language', () => {+ expect(formatAgo('2026-10-21T09:00:00', 'en-US', now)).toBe('3 days ago');+ expect(formatAgo('2026-10-21T09:00:00', 'zh-CN', now)).toBe('3天前');+ expect(formatAgo('2026-10-24T08:00:00', 'en-US', now)).toBe('today');+ });+});diff --git a/src/features/MemoryEntities/derive.ts b/src/features/MemoryEntities/derive.tsnew file mode 100644index 00000000000..902f58facb6--- /dev/null+++ b/src/features/MemoryEntities/derive.ts@@ -0,0 +1,46 @@+import { mergeById } from './adapt';+import { type EntityLinks } from './link';+import { type MemoryActivity, type MemoryEntity } from './types';++export const groupByMonth = <T extends { activity: MemoryActivity }>(+ entries: T[],+ monthLabel: (iso: string) => string,+) => {+ const groups: { entries: T[]; label: string }[] = [];+ for (const entry of entries) {+ const label = monthLabel(entry.activity.when);+ const last = groups.at(-1);+ if (last?.label === label) last.entries.push(entry);+ else groups.push({ entries: [entry], label });+ }+ return groups;+};++/** When the page last moved: its newest linked activity, or its own last update. */+export const lastTouchedOf = (entity: MemoryEntity, links?: EntityLinks) => {+ const latest = links?.activities.get(entity.id)?.find((e) => !e.activity.planned)?.activity.when;+ return latest && latest > entity.updatedAt ? latest : entity.updatedAt;+};++const matchesKeyword = (entity: MemoryEntity, lower: string) =>+ [entity.title, entity.description, entity.summary, ...entity.tags].some((text) =>+ text.toLowerCase().includes(lower),+ );++/**+ * Contexts to show for a keyword: loaded ones that match locally, plus every server hit as is.+ * The server also searches fields the list does not hold (status, parent details), so its rows+ * are not filtered a second time.+ */+export const searchMatches = (+ contexts: MemoryEntity[],+ keyword: string,+ remote: MemoryEntity[] = [],+) => {+ const lower = keyword.trim().toLowerCase();+ if (!lower) return contexts;+ return mergeById(+ contexts.filter((e) => matchesKeyword(e, lower)),+ remote,+ );+};diff --git a/src/features/MemoryEntities/drafts.test.ts b/src/features/MemoryEntities/drafts.test.tsnew file mode 100644index 00000000000..d5d9bfa1488--- /dev/null+++ b/src/features/MemoryEntities/drafts.test.ts@@ -0,0 +1,31 @@+import { beforeEach, describe, expect, it } from 'vitest';++import { resolveDraft, useDraftStore } from './drafts';++describe('resolveDraft', () => {+ it('saves a cleared description instead of silently keeping the old one', () => {+ expect(resolveDraft(' ', 'Old description')).toEqual({ save: true, value: '' });+ });++ it('treats unchanged text as a no-op', () => {+ expect(resolveDraft(' Old description ', 'Old description')).toEqual({+ save: false,+ value: 'Old description',+ });+ });+});++describe('useDraftStore', () => {+ beforeEach(() => useDraftStore.setState({ drafts: {} }));++ it('keeps an unsaved edit per context across switching away and back', () => {+ const { setDraft } = useDraftStore.getState();+ setDraft('ctx-a', 'half-typed');+ setDraft('ctx-b', 'other page');++ expect(useDraftStore.getState().drafts).toEqual({ 'ctx-a': 'half-typed', 'ctx-b': 'other page' });++ setDraft('ctx-a');+ expect(useDraftStore.getState().drafts).toEqual({ 'ctx-b': 'other page' });+ });+});diff --git a/src/features/MemoryEntities/drafts.ts b/src/features/MemoryEntities/drafts.tsnew file mode 100644index 00000000000..3c2ca19808a--- /dev/null+++ b/src/features/MemoryEntities/drafts.ts@@ -0,0 +1,31 @@+import { create } from 'zustand';++interface DraftState {+ drafts: Record<string, string>;+ /** `undefined` ends editing for that context. */+ setDraft: (id: string, text?: string) => void;+}++/**+ * Unsaved 「现在」 edits, per context. Kept outside the page so following a link or picking+ * another context does not discard what was typed; coming back resumes the edit.+ */+export const useDraftStore = create<DraftState>()((set) => ({+ drafts: {},+ setDraft: (id, text) =>+ set((s) => {+ const drafts = { ...s.drafts };+ if (text === undefined) delete drafts[id];+ else drafts[id] = text;+ return { drafts };+ }),+}));++/**+ * What saving a draft should do. Only unchanged text is a no-op; clearing the field is a real+ * edit and is saved as an empty description.+ */+export const resolveDraft = (draft: string | undefined, current: string) => {+ const value = (draft ?? '').trim();+ return { save: value !== current, value };+};diff --git a/src/features/MemoryEntities/format.ts b/src/features/MemoryEntities/format.tsnew file mode 100644index 00000000000..d32ef2e3856--- /dev/null+++ b/src/features/MemoryEntities/format.ts@@ -0,0 +1,65 @@+import { useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { hasStatusLabel } from './kinds';+import { type ContextKind } from './types';++const DAY = 24 * 60 * 60 * 1000;++const startOfDay = (date: Date) => {+ const copy = new Date(date);+ copy.setHours(0, 0, 0, 0);+ return copy;+};++export const daysFromToday = (iso: string, now = new Date()) =>+ Math.round((startOfDay(new Date(iso)).getTime() - startOfDay(now).getTime()) / DAY);++/** Rough age for list rows: today, yesterday, N days / months / years ago. */+export const formatAgo = (iso: string, locale: string, now = new Date()) => {+ const rtf = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });+ const days = daysFromToday(iso, now);+ if (days > -30) return rtf.format(Math.min(days, 0), 'day');+ if (days > -365) return rtf.format(Math.round(days / 30), 'month');+ return rtf.format(Math.round(days / 365), 'year');+};++/** Dates, ages and labels in the user's language. */+export const useEntityFormat = () => {+ const { i18n, t } = useTranslation('memory');+ const locale = i18n.language;++ return useMemo(() => {+ const monthDay = new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'short' });+ const weekday = new Intl.DateTimeFormat(locale, { weekday: 'short' });+ const day = new Intl.DateTimeFormat(locale, { day: 'numeric' });+ const month = new Intl.DateTimeFormat(locale, { month: 'long' });+ const yearMonth = new Intl.DateTimeFormat(locale, { month: 'long', year: 'numeric' });+ const names = new Intl.ListFormat(locale, { style: 'narrow', type: 'unit' });++ return {+ ago: (iso: string) => formatAgo(iso, locale),+ day: (iso: string) => day.format(new Date(iso)),+ kind: (kind: ContextKind) => t(`entity.kind.${kind}`),+ kindExample: (kind: ContextKind) => t(`entity.kind.${kind}.example`),+ month: (iso: string) => {+ const date = new Date(iso);+ return date.getFullYear() === new Date().getFullYear()+ ? month.format(date)+ : yearMonth.format(date);+ },+ monthDay: (iso: string) => monthDay.format(new Date(iso)),+ names: (list: string[]) => names.format(list),+ /** Backend status in words; values outside the known enum are shown as written. */+ status: (value?: string): string | undefined => {+ if (!value) return undefined;+ return hasStatusLabel(value) ? t(`entity.status.${value}`) : value;+ },+ t,+ title: (entity: { title: string }) => entity.title || t('entity.untitled'),+ weekday: (iso: string) => weekday.format(new Date(iso)),+ };+ }, [locale, t]);+};++export type EntityFormat = ReturnType<typeof useEntityFormat>;diff --git a/src/features/MemoryEntities/index.tsx b/src/features/MemoryEntities/index.tsxnew file mode 100644index 00000000000..23065b45482--- /dev/null+++ b/src/features/MemoryEntities/index.tsx@@ -0,0 +1,68 @@+'use client';++import { Center, Empty } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';+import { LayersIcon } from 'lucide-react';+import { memo, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { EntityDataContext } from './context';+import { lastTouchedOf } from './derive';+import EntityList from './EntityList';+import EntityPage from './EntityPage';+import { ErrorState, FirstRunState, LoadingState } from './states';+import { useEntityData } from './useEntityData';+import { useSelection } from './useSelection';++const styles = stylex.create({+ root: { display: 'flex', height: '100%', width: '100%' },+});++/**+ * Memory → 情境 as entity pages: every context is one page, and the activities that mention+ * the same names form its timeline (the backend stores no direct link).+ */+const MemoryEntities = memo(() => {+ const { t } = useTranslation('memory');+ const { selectedId } = useSelection();+ const data = useEntityData(selectedId);+ const { linked } = data;+ const loaded = data.entities.find((e) => e.id === selectedId);++ // Nothing picked yet (or the pick was deleted): open the page that moved most recently.+ const entity = useMemo(() => {+ const picked = loaded ?? linked;+ if (picked) return picked;+ return data.entities+ .filter((e) => e.status === 'active')+ .sort((a, b) => lastTouchedOf(b, data.links).localeCompare(lastTouchedOf(a, data.links)))[0];+ }, [data.entities, data.links, linked, loaded]);++ let content;+ if (data.isLoading) content = <LoadingState />;+ else if (data.error && data.entities.length === 0) content = <ErrorState onRetry={data.retry} />;+ else if (data.entities.length === 0) content = <FirstRunState />;+ else+ content = (+ <>+ <EntityList />+ {entity ? (+ <EntityPage entity={entity} />+ ) : (+ <Center flex={1}>+ <Empty description={t('entity.list.pick')} icon={LayersIcon} />+ </Center>+ )}+ </>+ );++ return (+ <EntityDataContext value={data}>+ <div {...stylex.props(styles.root)}>{content}</div>+ </EntityDataContext>+ );+});++MemoryEntities.displayName = 'MemoryEntities';++export default MemoryEntities;diff --git a/src/features/MemoryEntities/kinds.ts b/src/features/MemoryEntities/kinds.tsnew file mode 100644index 00000000000..6752f3f1a9e--- /dev/null+++ b/src/features/MemoryEntities/kinds.ts@@ -0,0 +1,114 @@+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import {+ CalendarDaysIcon,+ FolderKanbanIcon,+ type LucideIcon,+ ShapesIcon,+ TargetIcon,+ UsersRoundIcon,+} from 'lucide-react';++import { type ContextKind, type EntityStatus } from './types';++interface KindMeta {+ icon: LucideIcon;+}++/** List order: what the user is driving first, then who and what happens around it. */+export const CONTEXT_KINDS: ContextKind[] = ['project', 'goal', 'relationship', 'event', 'other'];++export const KIND_META: Record<ContextKind, KindMeta> = {+ event: { icon: CalendarDaysIcon },+ goal: { icon: TargetIcon },+ other: { icon: ShapesIcon },+ project: { icon: FolderKanbanIcon },+ relationship: { icon: UsersRoundIcon },+};++/**+ * The extractor writes `type` as free text: project (34%), relationship, other, goal and event+ * cover ~76% of rows, the rest is a long tail. Map the tail onto the nearest kind by word.+ */+const KIND_BY_TYPE: Record<string, ContextKind> = {+ activity: 'event',+ crisis: 'event',+ creative_project: 'project',+ event: 'event',+ goal: 'goal',+ incident: 'event',+ infrastructure: 'project',+ people: 'relationship',+ person: 'relationship',+ plan: 'project',+ process: 'project',+ project: 'project',+ relationship: 'relationship',+ research: 'project',+ social: 'relationship',+ strategy: 'goal',+ task: 'project',+ trip: 'event',+ work: 'project',+ workflow: 'project',+ workplace: 'project',+};++export const kindOfType = (type?: string | null): ContextKind => {+ const key = type?.trim().toLowerCase().replaceAll(/[\s-]+/g, '_');+ if (!key) return 'other';+ if (KIND_BY_TYPE[key]) return KIND_BY_TYPE[key];+ if (key.includes('project')) return 'project';+ if (key.includes('goal')) return 'goal';+ if (key.includes('relation') || key.includes('family') || key.includes('friend'))+ return 'relationship';+ if (key.includes('event') || key.includes('trip')) return 'event';+ return 'other';+};++/**+ * Backend `currentStatus` values with a translated label (`entity.status.*`); anything else is+ * shown as written. Older rows (before the status enum) say `active`.+ */+const LABELLED_STATUS = [+ 'aborted',+ 'active',+ 'cancelled',+ 'completed',+ 'on_hold',+ 'ongoing',+ 'planned',+] as const;++export type LabelledStatus = (typeof LABELLED_STATUS)[number];++export const hasStatusLabel = (value: string): value is LabelledStatus =>+ (LABELLED_STATUS as readonly string[]).includes(value);++export const statusOfValue = (value?: string | null): EntityStatus => {+ switch (value) {+ case 'completed':+ case 'aborted':+ case 'cancelled': {+ return 'closed';+ }+ case 'on_hold': {+ return 'dormant';+ }+ default: {+ return 'active';+ }+ }+};++/**+ * One hue per kind, used only on the kind icon. Everything else on the page stays neutral,+ * so the colour reads as "which kind" and nothing more.+ */+export const kindTint = stylex.create({+ event: { backgroundColor: cssVar.orangeFillSecondary, color: cssVar.orange },+ goal: { backgroundColor: cssVar.greenFillSecondary, color: cssVar.green },+ other: { backgroundColor: cssVar.colorFillSecondary, color: cssVar.colorTextSecondary },+ project: { backgroundColor: cssVar.geekblueFillSecondary, color: cssVar.geekblue },+ relationship: { backgroundColor: cssVar.goldFillSecondary, color: cssVar.gold },+});diff --git a/src/features/MemoryEntities/link.test.ts b/src/features/MemoryEntities/link.test.tsnew file mode 100644index 00000000000..2ad0074d8e1--- /dev/null+++ b/src/features/MemoryEntities/link.test.ts@@ -0,0 +1,157 @@+import { describe, expect, it } from 'vitest';++import { hasStatusLabel, kindOfType, statusOfValue } from './kinds';+import { hubNamesOf, linkByNames, mentionsOf } from './link';+import { type MemoryActivity, type MemoryEntity } from './types';++const entity = (id: string, names: string[], title = id): MemoryEntity => ({+ capturedAt: '2026-10-01T00:00:00.000Z',+ description: '',+ id,+ kind: 'project',+ names: names.map((name) => ({ name })),+ status: 'active',+ summary: '',+ tags: [],+ title,+ updatedAt: '2026-10-01T00:00:00.000Z',+});++const activity = (id: string, names: string[], when = '2026-10-02T00:00:00.000Z'): MemoryActivity => ({+ id,+ names: names.map((name) => ({ name })),+ narrative: id,+ planned: false,+ title: id,+ when,+ whenIsExact: true,+});++describe('kindOfType', () => {+ it('folds the long tail of free-text types onto the five kinds', () => {+ expect(kindOfType('project')).toBe('project');+ expect(kindOfType('Creative Project')).toBe('project');+ expect(kindOfType('people')).toBe('relationship');+ expect(kindOfType('trip')).toBe('event');+ expect(kindOfType('goal')).toBe('goal');+ expect(kindOfType('phenomenon')).toBe('other');+ expect(kindOfType(null)).toBe('other');+ });+});++describe('statusOfValue', () => {+ it('collapses backend statuses into the list groups', () => {+ expect(statusOfValue('ongoing')).toBe('active');+ expect(statusOfValue('planned')).toBe('active');+ expect(statusOfValue('on_hold')).toBe('dormant');+ expect(statusOfValue('completed')).toBe('closed');+ expect(statusOfValue('cancelled')).toBe('closed');+ expect(statusOfValue(undefined)).toBe('active');+ });++ it('gives the legacy `active` value a translated label instead of showing it raw', () => {+ expect(hasStatusLabel('active')).toBe(true);+ expect(hasStatusLabel('on_hold')).toBe(true);+ expect(hasStatusLabel('something-new')).toBe(false);+ });+});++describe('linkByNames', () => {+ it('links an activity to the contexts that mention the same name, case-insensitively', () => {+ const links = linkByNames(+ [entity('ielts', ['陈老师', 'IELTS']), entity('kb', ['老王'])],+ [activity('mock-exam', ['ielts']), activity('weekly', ['老王'])],+ );++ expect(links.activities.get('ielts')?.map((e) => e.activity.id)).toEqual(['mock-exam']);+ expect(links.activities.get('ielts')?.[0].names).toEqual(['ielts']);+ expect(links.activities.get('kb')?.map((e) => e.activity.id)).toEqual(['weekly']);+ });++ it('matches an activity name against a context title', () => {+ const links = linkByNames([entity('c1', [], '雅思备考')], [activity('a1', ['雅思备考'])]);+ expect(links.activities.get('c1')?.map((e) => e.activity.id)).toEqual(['a1']);+ });++ it('ignores names that appear in most contexts, such as the user themselves', () => {+ const entities = [+ entity('a', ['Arvin', 'IELTS']),+ entity('b', ['Arvin', 'migration']),+ entity('c', ['Arvin', 'camera']),+ entity('d', ['Arvin']),+ ];+ expect(hubNamesOf(mentionsOf(entities, []))).toEqual(new Set(['arvin']));++ const links = linkByNames(entities, [activity('x', ['Arvin'])]);+ expect(links.activities.size).toBe(0);+ expect(links.contexts.get('a')).toEqual([]);+ expect(links.mentions.get('a')).not.toContain('Arvin');+ });++ it('finds activity names inside a context text when the context sends no names', () => {+ const ctx: MemoryEntity = {+ ...entity('cust', [], '中信已打入、三九未打入'),+ description: '计划用 CLI 作为切入点',+ };+ const links = linkByNames(+ [ctx, entity('other', [], '别的事')],+ [activity('visit', ['三九', 'CLI']), activity('noise', ['A'])],+ );++ expect(links.activities.get('cust')?.[0].names).toEqual(['三九', 'CLI']);+ // Single-character names are too noisy to match inside text.+ expect(links.mentions.get('cust')).not.toContain('A');+ });++ it('never links pages through role words such as Assistant or 用户', () => {+ const ctx: MemoryEntity = {+ ...entity('model', ['用户'], 'Training a model'),+ description: 'Raised when the assistant questioned the framing',+ };+ const links = linkByNames(+ [ctx, entity('x', []), entity('y', []), entity('z', [])],+ [activity('sidebar', ['Assistant', '用户'])],+ );++ expect(links.activities.size).toBe(0);+ });++ it('matches Latin names as whole words only', () => {+ const ctx: MemoryEntity = {+ ...entity('citic', [], '算力平台'),+ description: 'deliver training on the all-in-one machine; MacBook later',+ };+ const links = linkByNames(+ [ctx, entity('x', []), entity('y', []), entity('z', [])],+ [activity('apple-music', ['Mac']), activity('laptop', ['MacBook'])],+ );++ expect(links.activities.get('citic')?.map((e) => e.activity.id)).toEqual(['laptop']);+ });++ it('only takes Latin names from text when they read as proper nouns', () => {+ const ctx: MemoryEntity = {+ ...entity('skills', [], '外部数据生成 skills'),+ description: '评估把 Klavis 换成 Composio,同时整理 workspace 里的 git 配置',+ };+ const links = linkByNames(+ [ctx, entity('x', []), entity('y', []), entity('z', [])],+ [activity('swap', ['Composio']), activity('ws', ['workspace']), activity('g', ['git'])],+ );++ expect(links.activities.get('skills')?.map((e) => e.activity.id)).toEqual(['swap']);+ });++ it('relates contexts that share a name and orders each timeline newest first', () => {+ const links = linkByNames(+ [entity('wedding', ['林夏', '相机']), entity('camera', ['相机'])],+ [+ activity('old', ['相机'], '2026-01-01T00:00:00.000Z'),+ activity('new', ['相机'], '2026-09-01T00:00:00.000Z'),+ ],+ );++ expect(links.contexts.get('wedding')).toEqual([{ names: ['相机'], targetId: 'camera' }]);+ expect(links.activities.get('camera')?.map((e) => e.activity.id)).toEqual(['new', 'old']);+ });+});diff --git a/src/features/MemoryEntities/link.ts b/src/features/MemoryEntities/link.tsnew file mode 100644index 00000000000..e98f3a28ebf--- /dev/null+++ b/src/features/MemoryEntities/link.ts@@ -0,0 +1,188 @@+import { type MemoryActivity, type MemoryEntity, type NameLink } from './types';++const key = (name: string) => name.trim().toLowerCase();++/**+ * Names that show up in more than this share of a user's contexts (the user's own name, their+ * company) tie everything to everything. Sampled production data: with them dropped, ~22% of+ * contexts get at least one timeline entry, median 2.+ */+const HUB_SHARE = 0.2;+/**+ * Names found only by scanning a context's text are noisier (generic words such as 「仓库」+ * match anywhere), so they drop out at a lower share.+ */+const TEXT_HUB_SHARE = 0.05;+const HUB_MIN = 2;+/**+ * Role words the extractor records as participants on almost every activity. They are frequent+ * enough to mislink pages but often stay under the hub share for a single user.+ */+const STOP_NAMES = new Set([+ 'agent',+ 'ai',+ 'assistant',+ 'bot',+ 'me',+ 'system',+ 'user',+ 'the user',+ '助手',+ '助理',+ '我',+ '用户',+ '系统',+]);+/** Shorter names ("AI", "Go") match inside unrelated words. */+const MIN_TEXT_MATCH_LENGTH = 2;++const escape = (text: string) => text.replaceAll(/[$()*+.?[\\\]^{|}]/g, '\\$&');++/**+ * Latin names match as whole words ("Mac" must not hit "machine"); CJK text has no word+ * boundaries, so those names match as substrings.+ */+const wordPatterns = new Map<string, RegExp>();+/**+ * Whether a context's text mentions an activity name. CJK names have no word boundaries and+ * match as substrings. Latin names only count when they read as proper nouns ("Composio",+ * "LobeHub", not "workspace" or "git") and appear as whole words with the same casing.+ */+const containsName = (text: string, lowerText: string, label: string) => {+ if (!/[\dA-Z]/i.test(label)) return lowerText.includes(label.toLowerCase());+ if (!/[A-Z]/.test(label) || !text.includes(label)) return false;+ let pattern = wordPatterns.get(label);+ if (!pattern) {+ pattern = new RegExp(`(^|[^\\dA-Za-z])${escape(label)}($|[^\\dA-Za-z])`);+ wordPatterns.set(label, pattern);+ }+ return pattern.test(text);+};++const textOf = (entity: MemoryEntity) =>+ [entity.title, entity.summary, entity.description, ...entity.tags].join('\n');++/**+ * What a context mentions: its own associated names when the backend sends them, plus every+ * activity name that appears in its title, summary, description or tags. The second half keeps+ * pages linked while the list endpoint omits context names.+ */+export const mentionsOf = (entities: MemoryEntity[], activities: MemoryActivity[]) => {+ const vocabulary = new Map<string, string>();+ for (const activity of activities) {+ for (const n of activity.names) {+ const k = key(n.name);+ if ([...k].length < MIN_TEXT_MATCH_LENGTH || STOP_NAMES.has(k)) continue;+ // Keep the capitalised spelling when both appear, so proper nouns are recognised.+ const known = vocabulary.get(k);+ if (!known || (!/[A-Z]/.test(known) && /[A-Z]/.test(n.name))) vocabulary.set(k, n.name);+ }+ }++ const mentions: Mentions = new Map();+ for (const entity of entities) {+ const found = new Map<string, Mention>();+ for (const n of entity.names)+ if (!STOP_NAMES.has(key(n.name)))+ found.set(key(n.name), { fromText: false, label: n.name });+ found.set(key(entity.title), { fromText: false, label: entity.title });+ const text = textOf(entity);+ const lowerText = text.toLowerCase();+ for (const [k, label] of vocabulary)+ if (!found.has(k) && containsName(text, lowerText, label))+ found.set(k, { fromText: true, label });+ mentions.set(entity.id, found);+ }+ return mentions;+};++interface Mention {+ fromText: boolean;+ label: string;+}+type Mentions = Map<string, Map<string, Mention>>;++export const hubNamesOf = (mentions: Mentions) => {+ const counts = new Map<string, { any: number; text: number }>();+ for (const found of mentions.values()) {+ for (const [k, m] of found) {+ const c = counts.get(k) ?? { any: 0, text: 0 };+ c.any += 1;+ if (m.fromText) c.text += 1;+ counts.set(k, c);+ }+ }+ const limit = Math.max(HUB_MIN, mentions.size * HUB_SHARE);+ const textLimit = Math.max(HUB_MIN, mentions.size * TEXT_HUB_SHARE);+ return new Set(+ [...counts].filter(([, c]) => c.any > limit || c.text > textLimit).map(([k]) => k),+ );+};++export interface EntityLinks {+ /** contextId → activities that mention one of its names, most recent first. */+ activities: Map<string, { activity: MemoryActivity; names: string[] }[]>;+ /** contextId → other contexts sharing a name. */+ contexts: Map<string, NameLink[]>;+ /** contextId → names the page mentions, after dropping the ones every page mentions. */+ mentions: Map<string, string[]>;+}++/**+ * The backend stores no context ↔ activity link, so infer one from the names both mention.+ */+export const linkByNames = (+ entities: MemoryEntity[],+ activities: MemoryActivity[],+): EntityLinks => {+ const mentions = mentionsOf(entities, activities);+ const hubs = hubNamesOf(mentions);++ const nameIndex = new Map<string, string[]>();+ const kept = new Map<string, string[]>();+ for (const [id, found] of mentions) {+ const labels: string[] = [];+ for (const [k, { label }] of found) {+ if (hubs.has(k)) continue;+ labels.push(label);+ nameIndex.set(k, [...(nameIndex.get(k) ?? []), id]);+ }+ kept.set(id, labels);+ }++ const byContext = new Map<string, { activity: MemoryActivity; names: string[] }[]>();+ for (const activity of activities) {+ const hits = new Map<string, string[]>();+ for (const n of activity.names) {+ for (const id of nameIndex.get(key(n.name)) ?? []) {+ const names = hits.get(id) ?? [];+ if (!names.includes(n.name)) names.push(n.name);+ hits.set(id, names);+ }+ }+ for (const [id, names] of hits) {+ byContext.set(id, [...(byContext.get(id) ?? []), { activity, names }]);+ }+ }+ for (const list of byContext.values())+ list.sort((a, b) => b.activity.when.localeCompare(a.activity.when));++ const contexts = new Map<string, NameLink[]>();+ for (const [id, labels] of kept) {+ const shared = new Map<string, string[]>();+ for (const label of labels) {+ for (const targetId of nameIndex.get(key(label)) ?? []) {+ if (targetId === id) continue;+ shared.set(targetId, [...(shared.get(targetId) ?? []), label]);+ }+ }+ contexts.set(+ id,+ [...shared]+ .map(([targetId, names]) => ({ names: [...new Set(names)], targetId }))+ .sort((a, b) => b.names.length - a.names.length),+ );+ }++ return { activities: byContext, contexts, mentions: kept };+};diff --git a/src/features/MemoryEntities/states.tsx b/src/features/MemoryEntities/states.tsxnew file mode 100644index 00000000000..d9df860bf60--- /dev/null+++ b/src/features/MemoryEntities/states.tsx@@ -0,0 +1,146 @@+import { Button, Empty, Skeleton, SkeletonAvatar, SkeletonText } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { CloudOffIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import MemoryAnalysis from '@/routes/(main)/memory/features/MemoryAnalysis';++import KindIcon from './components/KindIcon';+import { useEntityFormat } from './format';+import { CONTEXT_KINDS } from './kinds';++const styles = stylex.create({+ center: {+ alignItems: 'center',+ display: 'flex',+ flex: '1',+ flexDirection: 'column',+ gap: '32px',+ justifyContent: 'center',+ paddingBlock: '48px',+ paddingInline: '24px',+ },+ intro: { display: 'flex', flexDirection: 'column', gap: '8px', maxWidth: '440px', textAlign: 'center' },+ title: { fontSize: '20px', fontWeight: 600, margin: 0 },+ desc: { color: cssVar.colorTextSecondary, fontSize: '14px', lineHeight: '22px', margin: 0 },+ analysis: { maxWidth: '320px', width: '100%' },+ kinds: {+ display: 'grid',+ gap: '8px',+ gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))',+ maxWidth: '600px',+ width: '100%',+ },+ kind: {+ alignItems: 'center',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadiusLG,+ borderStyle: 'solid',+ borderWidth: '1px',+ display: 'flex',+ gap: '12px',+ paddingBlock: '12px',+ paddingInline: '12px',+ },+ kindText: { display: 'flex', flexDirection: 'column', minWidth: 0 },+ kindLabel: { fontSize: '13px', fontWeight: 500 },+ kindExample: { color: cssVar.colorTextTertiary, fontSize: '12px' },+ loading: { display: 'flex', flex: '1', height: '100%' },+ loadingList: {+ borderInlineEndColor: cssVar.colorBorderSecondary,+ borderInlineEndStyle: 'solid',+ borderInlineEndWidth: '1px',+ display: 'flex',+ flexDirection: 'column',+ gap: '16px',+ paddingBlock: '20px',+ paddingInline: '16px',+ width: '320px',+ },+ loadingRow: { alignItems: 'flex-start', display: 'flex', gap: '12px' },+ loadingPage: {+ display: 'flex',+ flex: '1',+ flexDirection: 'column',+ gap: '40px',+ marginInline: 'auto',+ maxWidth: '720px',+ paddingBlock: '40px',+ paddingInline: '48px',+ },+});++/** First run: say what this page will hold, with one example per kind, and how to fill it. */+export const FirstRunState = memo(() => {+ const format = useEntityFormat();+ return (+ <div {...stylex.props(styles.center)}>+ <div {...stylex.props(styles.intro)}>+ <h2 {...stylex.props(styles.title)}>{format.t('entity.firstRun.title')}</h2>+ <p {...stylex.props(styles.desc)}>{format.t('entity.firstRun.desc')}</p>+ </div>+ <div {...stylex.props(styles.kinds)}>+ {CONTEXT_KINDS.map((kind) => (+ <div key={kind} {...stylex.props(styles.kind)}>+ <KindIcon kind={kind} />+ <span {...stylex.props(styles.kindText)}>+ <span {...stylex.props(styles.kindLabel)}>{format.kind(kind)}</span>+ <span {...stylex.props(styles.kindExample)}>{format.kindExample(kind)}</span>+ </span>+ </div>+ ))}+ </div>+ <div {...stylex.props(styles.analysis)}>+ <MemoryAnalysis />+ </div>+ </div>+);+});++FirstRunState.displayName = 'FirstRunState';++export const ErrorState = memo<{ onRetry: () => void }>(({ onRetry }) => {+ const { t } = useTranslation('memory');+ return (+ <div {...stylex.props(styles.center)}>+ <Empty+ description={t('entity.error.desc')}+ icon={CloudOffIcon}+ title={t('entity.error.title')}+ action={+ <Button type={'primary'} onClick={onRetry}>{t('entity.error.retry')}</Button>+ }+ />+ </div>+);+});++ErrorState.displayName = 'ErrorState';++/** Same frame as the loaded page, so nothing jumps when data arrives. */+export const LoadingState = memo(() => (+ <div aria-busy {...stylex.props(styles.loading)}>+ <div {...stylex.props(styles.loadingList)}>+ <Skeleton height={22} width={64} />+ <Skeleton height={32} radius={8} width={'100%'} />+ {Array.from({ length: 7 }, (_, i) => (+ <div key={i} {...stylex.props(styles.loadingRow)}>+ <SkeletonAvatar shape={'square'} size={24} />+ <SkeletonText fontSize={12} rows={2} width={['60%', '90%']} />+ </div>+ ))}+ </div>+ <div {...stylex.props(styles.loadingPage)}>+ <div {...stylex.props(styles.loadingRow)}>+ <SkeletonAvatar shape={'square'} size={40} />+ <SkeletonText fontSize={20} rows={2} width={['40%', '25%']} />+ </div>+ <SkeletonText fontSize={17} rows={3} width={['15%', '100%', '70%']} />+ <SkeletonText rows={6} width={['15%', '90%', '60%', '95%', '80%', '50%']} />+ </div>+ </div>+));++LoadingState.displayName = 'LoadingState';diff --git a/src/features/MemoryEntities/store.ts b/src/features/MemoryEntities/store.tsnew file mode 100644index 00000000000..46602ee8346--- /dev/null+++ b/src/features/MemoryEntities/store.ts@@ -0,0 +1,25 @@+import { create } from 'zustand';++interface EntityTrailState {+ clear: () => void;+ /** Pages left by following links, so the header can offer a way back. */+ history: string[];+ pop: () => string | undefined;+ push: (id: string) => void;+}++/**+ * The way back only. Which page is open lives in the URL (`?contextId=`, see `useSelection`),+ * so memory deep links, reloads and browser back all land on the same page.+ */+export const useEntityTrailStore = create<EntityTrailState>()((set, get) => ({+ clear: () => set({ history: [] }),+ history: [],+ pop: () => {+ const history = get().history;+ const last = history.at(-1);+ set({ history: history.slice(0, -1) });+ return last;+ },+ push: (id) => set((s) => ({ history: [...s.history, id] })),+}));diff --git a/src/features/MemoryEntities/types.ts b/src/features/MemoryEntities/types.tsnew file mode 100644index 00000000000..2ebd7916dea--- /dev/null+++ b/src/features/MemoryEntities/types.ts@@ -0,0 +1,53 @@+/**+ * Entity pages over the existing memory layers: every context is a page, and activities are the+ * timeline. The backend stores no link between the two, so the timeline is inferred from names+ * both sides mention (see `link.ts`).+ */+export type ContextKind = 'project' | 'goal' | 'relationship' | 'event' | 'other';++/** Collapsed from the backend `currentStatus` enum, which `statusLabel` keeps verbatim. */+export type EntityStatus = 'active' | 'dormant' | 'closed';++export interface AssociatedName {+ name: string;+ type?: string;+}++export interface MemoryEntity {+ capturedAt: string;+ /** Rich narrative of where things stand; the page's 「现在」. */+ description: string;+ id: string;+ kind: ContextKind;+ /** Names of the people, things and places the context mentions. */+ names: AssociatedName[];+ /** The free-text type the extractor wrote, e.g. `creative_project`. */+ rawType?: string;+ status: EntityStatus;+ /** Backend status as written: `ongoing`, `on_hold`, … */+ statusValue?: string;+ /** Concise overview from the parent memory row. */+ summary: string;+ tags: string[];+ title: string;+ updatedAt: string;+}++export interface MemoryActivity {+ id: string;+ names: AssociatedName[];+ narrative: string;+ planned: boolean;+ statusValue?: string;+ title: string;+ /** When it happened, or when it was recorded if the extractor left no date. */+ when: string;+ /** False when `when` is only the capture time. */+ whenIsExact: boolean;+}++/** A context ↔ activity or context ↔ context pair, and the names that tie them. */+export interface NameLink {+ names: string[];+ targetId: string;+}diff --git a/src/features/MemoryEntities/useEntityData.ts b/src/features/MemoryEntities/useEntityData.tsnew file mode 100644index 00000000000..860dba8b91f--- /dev/null+++ b/src/features/MemoryEntities/useEntityData.ts@@ -0,0 +1,124 @@+import { useMemo } from 'react';++import { memoryCRUDService } from '@/services/userMemory';+import { useUserMemoryStore } from '@/store/userMemory';+import { memoryListKey } from '@/store/userMemory/utils/replica';+import { LayersEnum } from '@/types/userMemory';++import { fromActivityRow, fromContextRow, linkedEntityOf, mergeById, uniqueById } from './adapt';+import { linkByNames } from './link';++/** The backend's page cap. One page covers the activities of ~99% of users. */+export const ENTITY_PAGE_SIZE = 100;++/** Entry key of the unfiltered context list in the memory store. */+const ALL_CONTEXTS = memoryListKey({});++/**+ * The entity pages read the memory store's replica-backed lists: contexts (one entry per+ * search, offset paging, optimistic delete with the offset repair) and activities, plus the+ * memory detail replica for a deep link outside the loaded pages. Edits patch every loaded and+ * persisted query, so the Memory portal and other memory pages see them too.+ */+export const useEntityData = (selectedId?: string) => {+ const useFetchContexts = useUserMemoryStore((s) => s.useFetchContexts);+ const useFetchActivities = useUserMemoryStore((s) => s.useFetchActivities);+ const useFetchMemoryDetail = useUserMemoryStore((s) => s.useFetchMemoryDetail);+ const loadMoreContexts = useUserMemoryStore((s) => s.loadMoreContexts);+ const deleteContext = useUserMemoryStore((s) => s.deleteContext);+ const updateContextEntity = useUserMemoryStore((s) => s.internal_updateContextEntity);++ const contexts = useFetchContexts({ pageSize: ENTITY_PAGE_SIZE });+ const activityList = useFetchActivities({ pageSize: ENTITY_PAGE_SIZE });+ // Read the unfiltered entry itself: the store's flat mirrors follow whichever query is+ // active, and a search in the list makes its own query active.+ const listState = useUserMemoryStore((s) => s.contextListEntries[ALL_CONTEXTS]);++ const contextRows = contexts.data?.items;+ const activityRows = activityList.data?.items;+ const entities = useMemo(+ () => uniqueById((contextRows ?? []).map(fromContextRow)),+ [contextRows],+ );+ const activities = useMemo(+ () => uniqueById((activityRows ?? []).map(fromActivityRow)),+ [activityRows],+ );+ const isLoading = (!contextRows && !contexts.error) || (!activityRows && !activityList.error);++ // A deep link (e.g. "open in memory" from a chat) may point past the loaded pages.+ const loaded = entities.some((e) => e.id === selectedId);+ const detail = useFetchMemoryDetail(+ !isLoading && !loaded && selectedId ? selectedId : null,+ LayersEnum.Context,+ );+ const linked = useMemo(+ () => (selectedId ? linkedEntityOf(detail.data, selectedId) : undefined),+ [detail.data, selectedId],+ );+ // The deep-linked page needs its timeline too, so it joins the loaded ones for linking.+ const links = useMemo(+ () =>+ contextRows && activityRows+ ? linkByNames(linked ? mergeById(entities, [linked]) : entities, activities)+ : undefined,+ [activities, activityRows, contextRows, entities, linked],+ );++ /** Rows in the lists are patched in place; a deep-linked row is refetched. */+ const afterEdit = async (id: string) => {+ if (linked?.id === id) await detail.mutate();+ };++ const updateNow = async (id: string, description: string) => {+ await memoryCRUDService.updateContext(id, { description });+ updateContextEntity(id, (row) => ({ ...row, description, updatedAt: new Date() }));+ await afterEdit(id);+ };++ const setStatus = async (id: string, currentStatus: string) => {+ await memoryCRUDService.updateContext(id, { currentStatus });+ updateContextEntity(id, (row) => ({ ...row, currentStatus }));+ await afterEdit(id);+ };++ /** Optimistic; rejects (after rolling back) when the server refuses. */+ const remove = (id: string) => deleteContext(id);++ return {+ activities,+ entities,+ error: contexts.error,+ /** The unfiltered list has pages not loaded yet. */+ hasMore: !!listState?.hasMore,+ isLoading,+ isLoadingMore: !!listState?.isLoadingMore,+ linked,+ links,+ loadMore: loadMoreContexts,+ loadMoreError: listState?.loadMoreError,+ remove,+ retry: () => {+ void contexts.mutate();+ void activityList.mutate();+ },+ setStatus,+ total: listState?.total ?? entities.length,+ updateNow,+ };+};++export type EntityDataApi = ReturnType<typeof useEntityData>;++/**+ * Server-side search through the context list's own query entry. Its rows are shown as matches+ * as they are: the server also searches fields the list does not hold (status, parent details).+ * An empty keyword reads the unfiltered entry, so the search query only becomes the store's+ * active one while a keyword is typed.+ */+export const useRemoteContextSearch = (q: string | undefined) => {+ const useFetchContexts = useUserMemoryStore((s) => s.useFetchContexts);+ const { data } = useFetchContexts({ pageSize: ENTITY_PAGE_SIZE, q });+ const rows = q ? data?.items : undefined;+ return useMemo(() => (rows ? uniqueById(rows.map(fromContextRow)) : undefined), [rows]);+};diff --git a/src/features/MemoryEntities/useSelection.test.tsx b/src/features/MemoryEntities/useSelection.test.tsxnew file mode 100644index 00000000000..a00a06c2924--- /dev/null+++ b/src/features/MemoryEntities/useSelection.test.tsx@@ -0,0 +1,56 @@+// @vitest-environment happy-dom+import { act, renderHook } from '@testing-library/react';+import { type ReactNode } from 'react';+import { MemoryRouter, useLocation } from 'react-router';+import { beforeEach, describe, expect, it } from 'vitest';++import { useEntityTrailStore } from './store';+import { useSelection } from './useSelection';++const setup = (url: string) => {+ const wrapper = ({ children }: { children: ReactNode }) => (+ <MemoryRouter initialEntries={[url]}>{children}</MemoryRouter>+ );+ return renderHook(() => ({ location: useLocation(), selection: useSelection() }), { wrapper });+};++describe('useSelection', () => {+ beforeEach(() => useEntityTrailStore.setState({ history: [] }));++ it('opens the context a memory deep link points at', () => {+ // The memory detail portal links here via getMemoryDetailPath(LayersEnum.Context, id).+ const { result } = setup('/memory/contexts?contextId=ctx-from-chat');+ expect(result.current.selection.selectedId).toBe('ctx-from-chat');+ });++ it('follows a link, keeps the way back in the URL trail, and returns', () => {+ const { result } = setup('/memory/contexts?contextId=ctx-a');++ act(() => result.current.selection.open('ctx-b'));+ expect(result.current.selection.selectedId).toBe('ctx-b');+ expect(result.current.location.search).toBe('?contextId=ctx-b');+ expect(result.current.selection.history).toEqual(['ctx-a']);++ act(() => result.current.selection.back());+ expect(result.current.selection.selectedId).toBe('ctx-a');+ expect(result.current.selection.history).toEqual([]);+ });++ it('pins the default page only when nothing is selected', () => {+ const { result } = setup('/memory/contexts');+ act(() => result.current.selection.ensureSelected('ctx-default'));+ expect(result.current.selection.selectedId).toBe('ctx-default');++ act(() => result.current.selection.ensureSelected('ctx-other'));+ expect(result.current.selection.selectedId).toBe('ctx-default');+ });++ it('starts a fresh trail when picking from the list', () => {+ const { result } = setup('/memory/contexts?contextId=ctx-a');+ act(() => result.current.selection.open('ctx-b'));+ act(() => result.current.selection.select('ctx-c'));++ expect(result.current.selection.selectedId).toBe('ctx-c');+ expect(result.current.selection.history).toEqual([]);+ });+});diff --git a/src/features/MemoryEntities/useSelection.ts b/src/features/MemoryEntities/useSelection.tsnew file mode 100644index 00000000000..430fdaba387--- /dev/null+++ b/src/features/MemoryEntities/useSelection.ts@@ -0,0 +1,41 @@+import { useQueryState } from '@/hooks/useQueryParam';++import { useEntityTrailStore } from './store';++/**+ * Same param the memory detail portal links to (`getMemoryDetailPath`), so "open in memory"+ * from a chat lands on that context.+ */+export const CONTEXT_ID_PARAM = 'contextId';++export const useSelection = () => {+ const [selectedId, setSelectedId] = useQueryState(CONTEXT_ID_PARAM, { clearOnDefault: true });+ const history = useEntityTrailStore((s) => s.history);+ const { clear, pop, push } = useEntityTrailStore.getState();++ return {+ back: () => {+ const previous = pop();+ if (previous) setSelectedId(previous);+ },+ /**+ * Keeps the page on screen when it was only shown as the default pick: changing its status+ * would otherwise make another context the default and swap the page mid-action.+ */+ ensureSelected: (id: string) => {+ if (!selectedId) setSelectedId(id);+ },+ history,+ /** Follows a link from the current page; keeps the way back. */+ open: (id: string) => {+ if (selectedId && selectedId !== id) push(selectedId);+ setSelectedId(id);+ },+ /** Picks a page from the list; starts a fresh trail. */+ select: (id?: string) => {+ clear();+ setSelectedId(id ?? null);+ },+ selectedId: selectedId || undefined,+ };+};diff --git a/src/routes/(main)/memory/contexts/contextsLoader.test.ts b/src/routes/(main)/memory/contexts/contextsLoader.test.tsdeleted file mode 100644index 425d1cf3861..00000000000--- a/src/routes/(main)/memory/contexts/contextsLoader.test.ts+++ /dev/null@@ -1,35 +0,0 @@-// @vitest-environment happy-dom-import type { LoaderFunctionArgs } from 'react-router';-import { afterEach, describe, expect, it, vi } from 'vitest';--import { useUserMemoryStore } from '@/store/userMemory';--import { contextListLoader } from './contextsLoader';--const argsOf = (url: string) => ({ request: new Request(url) }) as LoaderFunctionArgs;--describe('contextListLoader', () => {- afterEach(() => vi.restoreAllMocks());-- it('pre-hydrates the query the route URL encodes', async () => {- const preHydrate = vi- .spyOn(useUserMemoryStore.getState(), 'preHydrateContexts')- .mockResolvedValue(true);-- await expect(- contextListLoader(argsOf('https://app.lobehub.com/memory/contexts?q=foo')),- ).resolves.toBeNull();-- expect(preHydrate).toHaveBeenCalledWith({ q: 'foo' });- });-- it('pre-hydrates the unfiltered query for a bare URL', async () => {- const preHydrate = vi- .spyOn(useUserMemoryStore.getState(), 'preHydrateContexts')- .mockResolvedValue(true);-- await contextListLoader(argsOf('https://app.lobehub.com/memory/contexts'));-- expect(preHydrate).toHaveBeenCalledWith({ q: undefined });- });-});diff --git a/src/routes/(main)/memory/contexts/contextsLoader.ts b/src/routes/(main)/memory/contexts/contextsLoader.tsdeleted file mode 100644index ed4f8c580a6..00000000000--- a/src/routes/(main)/memory/contexts/contextsLoader.ts+++ /dev/null@@ -1,24 +0,0 @@-import type { LoaderFunctionArgs } from 'react-router';--import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaint';-import { useUserMemoryStore } from '@/store/userMemory';--/**- * Seed the persisted context page set for the query the route URL encodes.- *- * Route loaders run before React commits the route: the only point where the- * persisted list (an async read) can land before the page paints its loading- * skeleton. Only `q` is taken from the URL: the page's first paint is the- * timeline query, whose `sort` is undefined (the sort control only exists in- * grid mode, which is not part of the URL).- */-export const contextListLoader = async ({ request }: LoaderFunctionArgs): Promise<null> => {- const q = new URL(request.url).searchParams.get('q') || undefined;-- await settleWithin(- useUserMemoryStore.getState().preHydrateContexts({ q }),- PRE_PAINT_HYDRATE_TIMEOUT,- );-- return null;-};diff --git a/src/routes/(main)/memory/contexts/features/ContextDropdown.tsx b/src/routes/(main)/memory/contexts/features/ContextDropdown.tsxdeleted file mode 100644index 09552624b72..00000000000--- a/src/routes/(main)/memory/contexts/features/ContextDropdown.tsx+++ /dev/null@@ -1,70 +0,0 @@-import { DropdownMenu } from '@lobehub/ui';-import { ActionIcon, type ActionIconProps, confirmModal } from '@lobehub/ui';-import { MoreHorizontal, Pencil, Trash2 } from 'lucide-react';-import { type KeyboardEvent, type MouseEvent } from 'react';-import { memo } from 'react';-import { useTranslation } from 'react-i18next';--import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';-import { useUserMemoryStore } from '@/store/userMemory';--interface ContextDropdownProps {- id: string;- size?: ActionIconProps['size'];-}--const ContextDropdown = memo<ContextDropdownProps>(- ({ id, size = DESKTOP_HEADER_ICON_SMALL_SIZE }) => {- const { t } = useTranslation(['memory', 'common']);-- 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') {- confirmModal({- 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'),- });- }- };-- const menuItems = [- {- icon: <Pencil size={14} />,- key: 'edit',- label: t('context.actions.edit'),- onClick: handleMenuClick,- },- {- danger: true,- icon: <Trash2 size={14} />,- key: 'delete',- label: t('context.actions.delete'),- onClick: handleMenuClick,- },- ];-- return (- <DropdownMenu items={menuItems}>- <ActionIcon icon={MoreHorizontal} size={size} />- </DropdownMenu>- );- },-);--export default ContextDropdown;diff --git a/src/routes/(main)/memory/contexts/features/ContextRightPanel.tsx b/src/routes/(main)/memory/contexts/features/ContextRightPanel.tsxdeleted file mode 100644index 164b8f42a67..00000000000--- a/src/routes/(main)/memory/contexts/features/ContextRightPanel.tsx+++ /dev/null@@ -1,28 +0,0 @@-'use client';--import { memo } from 'react';--import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';-import { useQueryState } from '@/hooks/useQueryParam';-import DetailPanel from '@/routes/(main)/memory/features/DetailPanel';--import ContextDetail from './ContextDetail';-import ContextDropdown from './ContextDropdown';--const ContextRightPanel = memo(() => {- const [contextId] = useQueryState('contextId', { clearOnDefault: true });-- if (!contextId) return null;-- return (- <DetailPanel- header={{- right: <ContextDropdown id={contextId} size={DESKTOP_HEADER_ICON_SIZE} />,- }}- >- <ContextDetail id={contextId} />- </DetailPanel>- );-});--export default ContextRightPanel;diff --git a/src/routes/(main)/memory/contexts/features/List/GridView/ContextCard.tsx b/src/routes/(main)/memory/contexts/features/List/GridView/ContextCard.tsxdeleted file mode 100644index 0a4ce53f590..00000000000--- a/src/routes/(main)/memory/contexts/features/List/GridView/ContextCard.tsx+++ /dev/null@@ -1,47 +0,0 @@-import { cssVar } from '@lobehub/ui';-import { memo } from 'react';-import { useTranslation } from 'react-i18next';--import { type DisplayContextMemory } from '@/database/repositories/userMemory';-import GridCard from '@/routes/(main)/memory/features/GridView/GridCard';-import ProgressIcon from '@/routes/(main)/memory/features/ProgressIcon';--import ContextDropdown from '../../ContextDropdown';--interface ContextCardProps {- context: DisplayContextMemory;- onClick?: () => void;-}--const ContextCard = memo<ContextCardProps>(({ context, onClick }) => {- const { t } = useTranslation('memory');-- return (- <GridCard- actions={<ContextDropdown id={context.id} />}- capturedAt={context.capturedAt || context.updatedAt || context.createdAt}- cate={context.type}- title={context.title}- 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 ? cssVar.colorError : cssVar.colorWarning- }- />- </>- }- onClick={onClick}- >- {context.description}- </GridCard>- );-});--export default ContextCard;diff --git a/src/routes/(main)/memory/contexts/features/List/GridView/index.tsx b/src/routes/(main)/memory/contexts/features/List/GridView/index.tsxdeleted file mode 100644index 9545d780c41..00000000000--- a/src/routes/(main)/memory/contexts/features/List/GridView/index.tsx+++ /dev/null@@ -1,35 +0,0 @@-import { memo } from 'react';--import { type 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);- // Load-more progress / failure of the query on screen (footer + retry).- const isLoadingMore = useUserMemoryStore((s) => Boolean(s.contextListData?.isLoadingMore));- const loadMoreError = useUserMemoryStore((s) => s.contextListData?.loadMoreError);-- return (- <GridView- defaultColumnCount={2}- hasMore={contextsHasMore}- isLoading={isLoading || isLoadingMore}- items={contexts}- loadMoreError={loadMoreError}- renderItem={(context) => <ContextCard context={context} onClick={() => onClick(context)} />}- onLoadMore={loadMoreContexts}- />- );-});--export default ContextsGridView;diff --git a/src/routes/(main)/memory/contexts/features/List/TimelineView/ContextCard.tsx b/src/routes/(main)/memory/contexts/features/List/TimelineView/ContextCard.tsxdeleted file mode 100644index 12087fda4fd..00000000000--- a/src/routes/(main)/memory/contexts/features/List/TimelineView/ContextCard.tsx+++ /dev/null@@ -1,28 +0,0 @@-import { memo } from 'react';--import { type DisplayContextMemory } from '@/database/repositories/userMemory';-import TimeLineCard from '@/routes/(main)/memory/features/TimeLineView/TimeLineCard';--import ContextDropdown from '../../ContextDropdown';--interface ContextCardProps {- context: DisplayContextMemory;- onClick?: () => void;-}--const ContextCard = memo<ContextCardProps>(({ context, onClick }) => {- return (- <TimeLineCard- actions={<ContextDropdown id={context.id} />}- capturedAt={context.capturedAt || context.updatedAt || context.createdAt}- cate={context.type}- hashTags={context.tags}- title={context.title}- onClick={onClick}- >- {context.description}- </TimeLineCard>- );-});--export default ContextCard;diff --git a/src/routes/(main)/memory/contexts/features/List/TimelineView/index.tsx b/src/routes/(main)/memory/contexts/features/List/TimelineView/index.tsxdeleted file mode 100644index f7f14fa1c30..00000000000--- a/src/routes/(main)/memory/contexts/features/List/TimelineView/index.tsx+++ /dev/null@@ -1,43 +0,0 @@-'use client';--import { memo } from 'react';--import { type 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);- // Load-more progress / failure of the query on screen (footer + retry).- const isLoadingMore = useUserMemoryStore((s) => Boolean(s.contextListData?.isLoadingMore));- const loadMoreError = useUserMemoryStore((s) => s.contextListData?.loadMoreError);-- return (- <GenericTimelineView- data={contexts}- groupBy="day"- hasMore={contextsHasMore}- isLoading={isLoading || isLoadingMore}- loadMoreError={loadMoreError}- renderHeader={(periodKey) => <PeriodHeader groupBy="day" periodKey={periodKey} />}- renderItem={(context) => (- <TimelineItemWrapper>- <ContextCard context={context} onClick={() => onClick?.(context)} />- </TimelineItemWrapper>- )}- onLoadMore={loadMoreContexts}- />- );-});--export default ContextTimelineView;diff --git a/src/routes/(main)/memory/contexts/features/List/index.tsx b/src/routes/(main)/memory/contexts/features/List/index.tsxdeleted file mode 100644index 650d23f8b27..00000000000--- a/src/routes/(main)/memory/contexts/features/List/index.tsx+++ /dev/null@@ -1,49 +0,0 @@-import { memo } from 'react';-import { useTranslation } from 'react-i18next';--import { useQueryState } from '@/hooks/useQueryParam';-import MemoryAnalysis from '@/routes/(main)/memory/features/MemoryAnalysis';-import MemoryEmpty from '@/routes/(main)/memory/features/MemoryEmpty';-import { useGlobalStore } from '@/store/global';-import { useUserMemoryStore } from '@/store/userMemory';--import { type 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')}>- <MemoryAnalysis />- </MemoryEmpty>- );- }-- return viewMode === 'timeline' ? (- <TimelineView contexts={contexts} isLoading={isLoading} onClick={handleCardClick} />- ) : (- <GridView contexts={contexts} isLoading={isLoading} onClick={handleCardClick} />- );-});--export default ContextsList;diff --git a/src/routes/(main)/memory/contexts/index.tsx b/src/routes/(main)/memory/contexts/index.tsxindex 5e6b28bdfbc..9c7e832a1aa 100644--- a/src/routes/(main)/memory/contexts/index.tsx+++ b/src/routes/(main)/memory/contexts/index.tsx@@ -1,132 +1,3 @@-import { Flexbox, Icon, Tag } from '@lobehub/ui';-import { BrainCircuitIcon } from 'lucide-react';-import { type FC } from 'react';-import { memo, useCallback, useState } from 'react';-import { useTranslation } from 'react-i18next';+import MemoryEntities from '@/features/MemoryEntities';-import { MemoryListBoundary } from '@/features/Memory';-import NavHeader from '@/features/NavHeader';-import WideScreenContainer from '@/features/WideScreenContainer';-import WideScreenButton from '@/features/WideScreenContainer/WideScreenButton';-import { useQueryState } from '@/hooks/useQueryParam';-import ActionBar from '@/routes/(main)/memory/features/ActionBar';-import { SCROLL_PARENT_ID } from '@/routes/(main)/memory/features/TimeLineView/useScrollParent';-import { useUserMemoryStore } from '@/store/userMemory';--import EditableModal from '../features/EditableModal';-import FilterBar from '../features/FilterBar';-import Loading from '../features/Loading';-import { type ViewMode } from '../features/ViewModeSwitcher';-import ViewModeSwitcher 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: 'capturedAt' | 'scoreImpact' | 'scoreUrgency' =- sortValueRaw === 'scoreImpact' || sortValueRaw === 'scoreUrgency' ? sortValueRaw : 'capturedAt';-- const contextsPage = useUserMemoryStore((s) => s.contextsPage);- const contextsInit = useUserMemoryStore((s) => s.contextsInit);- const contextsTotal = useUserMemoryStore((s) => s.contextsTotal);- const useFetchContexts = useUserMemoryStore((s) => s.useFetchContexts);-- const sortOptions = [- { label: t('filter.sort.createdAt'), value: 'capturedAt' },- { label: t('filter.sort.scoreImpact'), value: 'scoreImpact' },- { label: t('filter.sort.scoreUrgency'), value: 'scoreUrgency' },- ];-- // Convert sort: capturedAt becomes undefined (backend default)- const apiSort =- sortValue === 'capturedAt' ? undefined : (sortValue as 'scoreImpact' | 'scoreUrgency');-- // Call SWR hook to fetch data- // Each search / sort is its own replica entry: the hook selects it before- // paint, so the previous query's rows never show under this one. `error` is- // this query's failure while it has nothing painted.- const { data, error, isLoading, mutate } = 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],- );-- return (- <Flexbox flex={1} height={'100%'}>- <NavHeader- left={- Boolean(contextsTotal) && (- <Tag icon={<Icon icon={BrainCircuitIcon} />}>{contextsTotal}</Tag>- )- }- right={- <ActionBar showAnalysis showPurge>- <ViewModeSwitcher value={viewMode} onChange={setViewMode} />- <WideScreenButton />- </ActionBar>- }- />- <Flexbox- height={'100%'}- id={SCROLL_PARENT_ID}- style={{ overflowY: 'auto', paddingBottom: '16vh' }}- width={'100%'}- >- <WideScreenContainer gap={32} paddingBlock={48}>- <FilterBar- searchValue={searchValue}- sortOptions={viewMode === 'grid' ? sortOptions : undefined}- sortValue={sortValue}- onSearch={handleSearch}- onSortChange={viewMode === 'grid' ? handleSortChange : undefined}- />- <MemoryListBoundary- data={data}- error={error}- isInitialized={contextsInit}- isLoading={isLoading}- loading={<Loading viewMode={viewMode} />}- onRetry={() => void mutate()}- >- <List isLoading={isLoading} searchValue={searchValue} viewMode={viewMode} />- </MemoryListBoundary>- </WideScreenContainer>- </Flexbox>- </Flexbox>- );-});--const Contexts: FC = () => {- return (- <>- <Flexbox horizontal height={'100%'} width={'100%'}>- <ContextsArea />- <ContextRightPanel />- </Flexbox>- <EditableModal />- </>- );-};--export default Contexts;+export default MemoryEntities;diff --git a/src/spa/router/contextListLoader.ts b/src/spa/router/contextListLoader.tsdeleted file mode 100644index 8644b523463..00000000000--- a/src/spa/router/contextListLoader.ts+++ /dev/null@@ -1,10 +0,0 @@-import type { LoaderFunctionArgs } from 'react-router';--// The route tables sit in the entry chunk's static graph; resolving the real-// loader on first use keeps the userMemory store in the contexts route's lazy-// chunks. The loader arguments carry the request, so the pre-hydrate can-// target the query the URL encodes.-export const contextListLoader = (args: LoaderFunctionArgs) =>- import('@/routes/(main)/memory/contexts/contextsLoader').then((module) =>- module.contextListLoader(args),- );diff --git a/src/spa/router/contextListLoader.wiring.test.ts b/src/spa/router/contextListLoader.wiring.test.tsdeleted file mode 100644index b259d4cefcc..00000000000--- a/src/spa/router/contextListLoader.wiring.test.ts+++ /dev/null@@ -1,44 +0,0 @@-// @vitest-environment happy-dom-import type { LoaderFunctionArgs, RouteObject } from 'react-router';-import { describe, expect, it, vi } from 'vitest';--import { contextListLoader } from './contextListLoader';-import { desktopRoutes } from './desktopRouter.config';--const loaderModule = vi.hoisted(() => ({ evaluated: false }));--// Evaluating the real loader means the userMemory store reached the entry-// chunk's first-screen graph.-vi.mock('@/routes/(main)/memory/contexts/contextsLoader', () => {- loaderModule.evaluated = true;- return { contextListLoader: vi.fn(async () => null) };-});--const flatten = (routes: RouteObject[]): RouteObject[] =>- routes.flatMap((route) => [route, ...(route.children ? flatten(route.children) : [])]);--describe('context list loader wiring', () => {- it('does not load the store-backed loader while the route tables load', () => {- expect(loaderModule.evaluated).toBe(false);- });-- it('pre-hydrates the context list on the desktop contexts route', () => {- const routes = flatten(desktopRoutes).filter((r) => r.path === 'contexts');-- expect(routes.length).toBeGreaterThan(0);-- expect(routes.map((r) => r.loader)).toEqual(routes.map(() => contextListLoader));- });-- it('delegates to the real loader on first use', async () => {- const { contextListLoader: realLoader } =- await import('@/routes/(main)/memory/contexts/contextsLoader');-- const args = {- request: new Request('https://app.lobehub.com/memory/contexts?q=foo'),- } as LoaderFunctionArgs;-- await expect(contextListLoader(args)).resolves.toBeNull();- expect(realLoader).toHaveBeenCalledWith(args);- });-});diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsxindex 1682d358881..84e174dc6a7 100644--- a/src/spa/router/desktopRouter.shared.tsx+++ b/src/spa/router/desktopRouter.shared.tsx@@ -63,7 +63,6 @@ import { activityListLoader } from '@/spa/router/activityListLoader';import { agentChatTopicListLoader } from '@/spa/router/agentChatTopicListLoader';import { agentDocumentListLoader } from '@/spa/router/agentDocumentListLoader';import { channelDataLoader } from '@/spa/router/channelDataLoader';-import { contextListLoader } from '@/spa/router/contextListLoader';import { identitiesListLoader } from '@/spa/router/identitiesListLoader';import { pageListLoader } from '@/spa/router/pageListLoader';import { preferenceListLoader } from '@/spa/router/preferenceListLoader';@@ -652,8 +651,6 @@ export const sharedMainAreaChildren: RouteObject[] = [handle: {meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryContexts' }),},- // Seed the persisted head page before the page paints (see `contextListLoader`).- loader: contextListLoader,path: 'contexts',},{