Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(docs): sidebar view options, full page list and artifact rendering (#21548)

LiJianc03f40b479e4
diff --git a/apps/server/src/routers/lambda/document.ts b/apps/server/src/routers/lambda/document.ts
index 21f5298bb0b..e1a10c168c7 100644
--- a/apps/server/src/routers/lambda/document.ts
+++ b/apps/server/src/routers/lambda/document.ts
@@ -507,6 +507,7 @@ export const documentRouter = router({
current: z.number().optional(),
fileTypes: z.array(z.string()).optional(),
pageSize: z.number().max(100).optional(),
+ sortBy: z.enum(['createdAt', 'title', 'updatedAt']).optional(),
sourceTypes: z.array(z.string()).optional(),
standaloneOnly: z.boolean().optional(),
})
diff --git a/apps/server/src/services/document/index.ts b/apps/server/src/services/document/index.ts
index ad203fe7ab3..4c18867c28d 100644
--- a/apps/server/src/services/document/index.ts
+++ b/apps/server/src/services/document/index.ts
@@ -21,7 +21,7 @@ import debug from 'debug';
import { and, eq, sql } from 'drizzle-orm';
import isEqual from 'fast-deep-equal';
-import { DocumentModel } from '@/database/models/document';
+import { DocumentModel, type DocumentQuerySortBy } from '@/database/models/document';
import { FileModel } from '@/database/models/file';
import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';
import { buildWorkspaceWhere } from '@/database/utils/workspace';
@@ -365,6 +365,7 @@ export class DocumentService {
excludeKnowledgeBaseIds?: string[];
fileTypes?: string[];
pageSize?: number;
+ sortBy?: DocumentQuerySortBy;
sourceTypes?: string[];
standaloneOnly?: boolean;
}) {
diff --git a/locales/en-US/file.json b/locales/en-US/file.json
index 10b8516a990..7c02654721d 100644
--- a/locales/en-US/file.json
+++ b/locales/en-US/file.json
@@ -63,6 +63,22 @@
"docs.section.home": "Home",
"docs.section.library": "Knowledge Bases",
"docs.section.works": "Works",
+ "docs.sectionView.emptyFiltered": "No pages match this filter",
+ "docs.sectionView.filter": "Show",
+ "docs.sectionView.group": "Group",
+ "docs.sectionView.groupBy.byTime": "By date",
+ "docs.sectionView.groupBy.byType": "By type",
+ "docs.sectionView.groupBy.none": "None",
+ "docs.sectionView.openFullList": "Open full list",
+ "docs.sectionView.pageSize": "Items shown",
+ "docs.sectionView.sort": "Sort",
+ "docs.sectionView.sortBy.createdAt": "Date created",
+ "docs.sectionView.sortBy.title": "Title",
+ "docs.sectionView.sortBy.updatedAt": "Last updated",
+ "docs.sectionView.title": "View options",
+ "docs.sectionView.type.all": "All",
+ "docs.sectionView.type.artifact": "Artifacts",
+ "docs.sectionView.type.page": "Pages",
"docs.shared.empty": "No pages shared by teammates yet",
"docs.shared.title": "Shared docs",
"docs.viewAllPages": "View all",
@@ -243,6 +259,7 @@
"notSupportGuide.features.libraries.title": "Knowledge Base",
"notSupportGuide.title": "The current deployment mode does not support file management",
"pageEditor.addIcon": "Add Icon",
+ "pageEditor.artifactTag": "Artifact",
"pageEditor.autoSaveMessage": "Your page is saved automatically. No need to save manually.",
"pageEditor.chooseIcon": "Choose Icon",
"pageEditor.comments.anchor.add": "Comment",
diff --git a/locales/zh-CN/file.json b/locales/zh-CN/file.json
index c2ef035107f..43074576c74 100644
--- a/locales/zh-CN/file.json
+++ b/locales/zh-CN/file.json
@@ -63,6 +63,22 @@
"docs.section.home": "主页",
"docs.section.library": "知识库",
"docs.section.works": "产物",
+ "docs.sectionView.emptyFiltered": "没有符合筛选条件的文档",
+ "docs.sectionView.filter": "显示",
+ "docs.sectionView.group": "分组",
+ "docs.sectionView.groupBy.byTime": "按时间",
+ "docs.sectionView.groupBy.byType": "按类型",
+ "docs.sectionView.groupBy.none": "不分组",
+ "docs.sectionView.openFullList": "展开完整列表",
+ "docs.sectionView.pageSize": "显示条目",
+ "docs.sectionView.sort": "排序",
+ "docs.sectionView.sortBy.createdAt": "创建时间",
+ "docs.sectionView.sortBy.title": "标题",
+ "docs.sectionView.sortBy.updatedAt": "最近更新",
+ "docs.sectionView.title": "显示选项",
+ "docs.sectionView.type.all": "全部",
+ "docs.sectionView.type.artifact": "Artifact",
+ "docs.sectionView.type.page": "文稿",
"docs.shared.empty": "暂无团队成员共享的文稿",
"docs.shared.title": "共享文档",
"docs.viewAllPages": "查看全部",
@@ -243,6 +259,7 @@
"notSupportGuide.features.libraries.title": "资源库",
"notSupportGuide.title": "当前部署模式不支持文件管理",
"pageEditor.addIcon": "添加图标",
+ "pageEditor.artifactTag": "Artifact",
"pageEditor.autoSaveMessage": "文稿会自动保存,无需手动保存",
"pageEditor.chooseIcon": "选择图标",
"pageEditor.comments.anchor.add": "评论",
diff --git a/packages/database/src/models/__tests__/document.queryFilters.workspace.test.ts b/packages/database/src/models/__tests__/document.queryFilters.workspace.test.ts
index a5a30eb481b..5cf1f230076 100644
--- a/packages/database/src/models/__tests__/document.queryFilters.workspace.test.ts
+++ b/packages/database/src/models/__tests__/document.queryFilters.workspace.test.ts
@@ -201,3 +201,46 @@ describe('DocumentModel.query — standaloneOnly vs library-backed parsed files'
});
});
});
+
+describe('DocumentModel.query — sortBy', () => {
+ beforeEach(async () => {
+ const at = (day: number) => new Date(`2026-10-${String(day).padStart(2, '0')}T00:00:00Z`);
+ // Created order b → c → a, updated order c → a → b, title order a → b → c.
+ for (const [id, createdDay, updatedDay] of [
+ ['page-a', 3, 5],
+ ['page-b', 1, 4],
+ ['page-c', 2, 6],
+ ] as const) {
+ await serverDB.insert(documents).values({
+ createdAt: at(createdDay),
+ fileType: 'custom/document',
+ id,
+ source: 'document',
+ sourceType: 'api',
+ title: id,
+ totalCharCount: 0,
+ totalLineCount: 0,
+ updatedAt: at(updatedDay),
+ userId: userA,
+ workspaceId,
+ });
+ }
+ });
+
+ const orderedIds = async (sortBy?: 'createdAt' | 'title' | 'updatedAt') => {
+ const result = await new DocumentModel(serverDB, userA, workspaceId).query({ sortBy });
+ return result.items.map((item) => item.id);
+ };
+
+ it('lists the most recently updated first by default', async () => {
+ expect(await orderedIds()).toEqual(['page-c', 'page-a', 'page-b']);
+ });
+
+ it('lists the newest created first for createdAt', async () => {
+ expect(await orderedIds('createdAt')).toEqual(['page-a', 'page-c', 'page-b']);
+ });
+
+ it('lists titles A→Z for title', async () => {
+ expect(await orderedIds('title')).toEqual(['page-a', 'page-b', 'page-c']);
+ });
+});
diff --git a/packages/database/src/models/document.ts b/packages/database/src/models/document.ts
index 85b3d5784c5..248322a0cd5 100644
--- a/packages/database/src/models/document.ts
+++ b/packages/database/src/models/document.ts
@@ -61,11 +61,18 @@ export interface QueryDocumentParams {
excludeKnowledgeBaseIds?: string[];
fileTypes?: string[];
pageSize?: number;
+ /**
+ * Row order: `updatedAt` (default) and `createdAt` list the newest first,
+ * `title` lists A→Z. Ties fall back to the id so offset pages never overlap.
+ */
+ sortBy?: DocumentQuerySortBy;
sourceTypes?: string[];
/** Keep only documents that live outside every knowledge base. */
standaloneOnly?: boolean;
}
+export type DocumentQuerySortBy = 'createdAt' | 'title' | 'updatedAt';
+
export const DOCUMENT_TRANSFER_FOREIGN_ROWS =
'Document subtree contains content created by other users';
@@ -190,6 +197,7 @@ export class DocumentModel {
pageSize = 9999,
excludeKnowledgeBaseIds,
fileTypes,
+ sortBy = 'updatedAt',
sourceTypes,
standaloneOnly,
}: QueryDocumentParams = {}): Promise<{
@@ -255,6 +263,13 @@ export class DocumentModel {
}
const whereCondition = and(...conditions);
+ const orderBy =
+ sortBy === 'title'
+ ? [asc(documents.title), desc(documents.updatedAt), asc(documents.id)]
+ : [
+ desc(sortBy === 'createdAt' ? documents.createdAt : documents.updatedAt),
+ asc(documents.id),
+ ];
// Fetch items and total count in parallel
// Optimize: Exclude large JSONB fields (content, pages, editorData) for better performance
@@ -287,7 +302,7 @@ export class DocumentModel {
})
.from(documents)
.where(whereCondition)
- .orderBy(desc(documents.updatedAt))
+ .orderBy(...orderBy)
.limit(pageSize)
.offset(offset),
this.db
diff --git a/packages/database/src/repositories/knowledge/__tests__/homeItems.test.ts b/packages/database/src/repositories/knowledge/__tests__/homeItems.test.ts
index f31cb338e3e..d3e93a346f1 100644
--- a/packages/database/src/repositories/knowledge/__tests__/homeItems.test.ts
+++ b/packages/database/src/repositories/knowledge/__tests__/homeItems.test.ts
@@ -125,6 +125,7 @@ beforeEach(async () => {
page({ id: 'home-page-mate', minutes: 6, userId: mate }),
page({ id: 'home-page-mate-private', minutes: 0, userId: mate, visibility: 'private' }),
page({ fileType: 'custom/folder', id: 'home-folder', minutes: 0, userId: me }),
+ page({ fileType: 'custom/html', id: 'home-artifact-mine', minutes: 3.5, userId: me }),
]);
});
@@ -139,6 +140,7 @@ describe('KnowledgeRepo.queryHomeItems', () => {
'home-file-mine',
'home-file-restricted',
'home-page-mine',
+ 'home-artifact-mine',
'home-file-mate',
'home-page-kb',
'home-page-mate',
@@ -157,6 +159,7 @@ describe('KnowledgeRepo.queryHomeItems', () => {
expect(await ids({ creator: 'self' })).toEqual([
'home-file-mine',
'home-page-mine',
+ 'home-artifact-mine',
'home-page-kb',
]);
});
diff --git a/packages/database/src/repositories/knowledge/index.ts b/packages/database/src/repositories/knowledge/index.ts
index 0474dd626c2..33dad566d99 100644
--- a/packages/database/src/repositories/knowledge/index.ts
+++ b/packages/database/src/repositories/knowledge/index.ts
@@ -2,6 +2,7 @@ import {
AGENT_ARTIFACT_SOURCE_TYPES,
CUSTOM_DOCUMENT_FILE_TYPE,
CUSTOM_FOLDER_FILE_TYPE,
+ HTML_DOCUMENT_FILE_TYPE,
MARKDOWN_MIME_TYPES,
RESOURCE_CONTENT_PREVIEW_SOURCE_LENGTH,
} from '@lobechat/const';
@@ -603,7 +604,7 @@ export class KnowledgeRepo {
}
/**
- * The Docs home list: pages and uploaded documents (pdf / office / text; no
+ * The Docs home list: pages (rich text and HTML artifacts) and uploaded documents (pdf / office / text; no
* media, raw data or page-backing rows) together, newest update first,
* wherever they live (a knowledge base or not; rows carry `knowledgeBaseIds`
* for the location column). `creator` narrows to the caller's own rows
@@ -643,7 +644,9 @@ export class KnowledgeRepo {
const documentArm = this.documentArm(
[
creatorFilter(d.userId),
- eq(d.fileType, CUSTOM_DOCUMENT_FILE_TYPE),
+ // HTML pages (artifacts) are pages too; leaving them out hid every
+ // agent-written report from the list.
+ inArray(d.fileType, [CUSTOM_DOCUMENT_FILE_TYPE, HTML_DOCUMENT_FILE_TYPE]),
excludeKnowledgeBaseIds?.length
? or(isNull(d.knowledgeBaseId), notInArray(d.knowledgeBaseId, excludeKnowledgeBaseIds))
: undefined,
diff --git a/packages/locales/src/default/file.ts b/packages/locales/src/default/file.ts
index 5ab4c8c8011..e4d9bec0485 100644
--- a/packages/locales/src/default/file.ts
+++ b/packages/locales/src/default/file.ts
@@ -69,6 +69,22 @@ export default {
'docs.section.home': 'Home',
'docs.section.library': 'Knowledge Bases',
'docs.section.works': 'Works',
+ 'docs.sectionView.emptyFiltered': 'No pages match this filter',
+ 'docs.sectionView.filter': 'Show',
+ 'docs.sectionView.group': 'Group',
+ 'docs.sectionView.groupBy.byTime': 'By date',
+ 'docs.sectionView.groupBy.byType': 'By type',
+ 'docs.sectionView.groupBy.none': 'None',
+ 'docs.sectionView.openFullList': 'Open full list',
+ 'docs.sectionView.pageSize': 'Items shown',
+ 'docs.sectionView.sort': 'Sort',
+ 'docs.sectionView.sortBy.createdAt': 'Date created',
+ 'docs.sectionView.sortBy.title': 'Title',
+ 'docs.sectionView.sortBy.updatedAt': 'Last updated',
+ 'docs.sectionView.title': 'View options',
+ 'docs.sectionView.type.all': 'All',
+ 'docs.sectionView.type.artifact': 'Artifacts',
+ 'docs.sectionView.type.page': 'Pages',
'docs.shared.empty': 'No pages shared by teammates yet',
'docs.shared.title': 'Shared docs',
'docs.viewAllPages': 'View all',
@@ -272,6 +288,7 @@ export default {
'imageViewer.zoomIn': 'Zoom in',
'imageViewer.zoomOut': 'Zoom out',
'pageEditor.addIcon': 'Add Icon',
+ 'pageEditor.artifactTag': 'Artifact',
'pageEditor.autoSaveMessage': 'Your page is saved automatically. No need to save manually.',
'pageEditor.chooseIcon': 'Choose Icon',
'pageEditor.comments.anchor.add': 'Comment',
diff --git a/packages/utils/src/client/topic.ts b/packages/utils/src/client/topic.ts
index 170195f4bf5..a2e004aca62 100644
--- a/packages/utils/src/client/topic.ts
+++ b/packages/utils/src/client/topic.ts
@@ -18,7 +18,8 @@ import isYesterday from 'dayjs/plugin/isYesterday';
dayjs.extend(isToday);
dayjs.extend(isYesterday);
-const getTopicGroupId = (timestamp: number): TimeGroupId => {
+/** Time bucket of a timestamp: today, yesterday, this week, this month, a month or a year. */
+export const getTimeGroupId = (timestamp: number): TimeGroupId => {
const date = dayjs(timestamp);
const now = dayjs();
@@ -51,8 +52,8 @@ const getTopicGroupId = (timestamp: number): TimeGroupId => {
return `${date.year()}`;
};
-// Ensure group sorting
-const sortGroups = (groups: GroupedTopic[]): GroupedTopic[] => {
+/** Orders time buckets newest first: the fixed buckets, then months and years. */
+export const sortTimeGroups = <T extends { id: string }>(groups: T[]): T[] => {
const orderMap = new Map<string, number>([
['today', 0],
['yesterday', 1],
@@ -97,7 +98,7 @@ const groupTopicsByField = (
const groupsMap = new Map<TimeGroupId, ChatTopic[]>();
for (const topic of sortedTopics) {
- const groupId = getTopicGroupId(getTopicSortTime(topic, field));
+ const groupId = getTimeGroupId(getTopicSortTime(topic, field));
const existing = groupsMap.get(groupId);
if (existing) {
existing.push(topic);
@@ -111,7 +112,7 @@ const groupTopicsByField = (
id,
}));
- return sortGroups(result);
+ return sortTimeGroups(result);
};
export const groupTopicsByTime = (topics: ChatTopic[]) => groupTopicsByField(topics, 'createdAt');
diff --git a/src/features/PageEditor/Header/index.tsx b/src/features/PageEditor/Header/index.tsx
index 64d9da9e450..1383c8299fa 100644
--- a/src/features/PageEditor/Header/index.tsx
+++ b/src/features/PageEditor/Header/index.tsx
@@ -7,9 +7,17 @@ import {
cssVar,
DropdownMenu,
Flexbox,
+ Icon,
+ Tag,
Text,
} from '@lobehub/ui';
-import { ArrowLeftIcon, MessageSquareTextIcon, MoreHorizontal, SparklesIcon } from 'lucide-react';
+import {
+ ArrowLeftIcon,
+ GlobeIcon,
+ MessageSquareTextIcon,
+ MoreHorizontal,
+ SparklesIcon,
+} from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -22,6 +30,7 @@ import { usePermission } from '@/hooks/usePermission';
import { useDocumentComments } from '../DocumentComments/context';
import EditingIndicator from '../EditingIndicator';
+import { useIsHtmlPage } from '../HtmlPageBody';
import { usePageAgentPanelControl } from '../RightPanel/OverrideContext';
import { selectors, usePageEditorStore } from '../store';
import Breadcrumb from './Breadcrumb';
@@ -46,6 +55,7 @@ const Header = memo(() => {
s.onBack,
]);
const rightPanelMode = usePageEditorStore(selectors.rightPanelMode);
+ const isHtmlPage = useIsHtmlPage(documentId);
const { allowed: hasEditPermission } = usePermission('edit_own_content');
const { expand: showPageAgentPanel, toggle: togglePageAgentPanel } = usePageAgentPanelControl();
const { menuItems } = useMenu();
@@ -80,7 +90,15 @@ const Header = memo(() => {
</Text>
</>
)}
- {documentId && <AutoSaveHint documentId={documentId} style={{ marginLeft: 6 }} />}
+ {/* An artifact's body is never edited here, so a save status would only
+ ever read "latest version"; name what the page is instead. */}
+ {isHtmlPage ? (
+ <Tag icon={<Icon icon={GlobeIcon} />} style={{ marginLeft: 6 }}>
+ {t('pageEditor.artifactTag')}
+ </Tag>
+ ) : (
+ documentId && <AutoSaveHint documentId={documentId} style={{ marginLeft: 6 }} />
+ )}
</>
}
right={
diff --git a/src/features/PageEditor/HtmlPageBody.tsx b/src/features/PageEditor/HtmlPageBody.tsx
index 53539a83188..ba363337bd7 100644
--- a/src/features/PageEditor/HtmlPageBody.tsx
+++ b/src/features/PageEditor/HtmlPageBody.tsx
@@ -1,12 +1,26 @@
'use client';
import { HTML_DOCUMENT_FILE_TYPE } from '@lobechat/const';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { HtmlDocumentFrame } from '@/components/HtmlPreview';
import { useDocumentStore } from '@/store/document';
import { usePageEditorStore } from './store';
+const styles = stylex.create({
+ // The artifact keeps its own background; the frame edge marks where it ends
+ // against either theme.
+ frame: {
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: 12,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ overflow: 'hidden',
+ },
+});
+
/** Whether the loaded page is an HTML page rather than a rich-text one. */
export const useIsHtmlPage = (documentId: string | undefined) =>
useDocumentStore(
@@ -29,7 +43,11 @@ const HtmlPageBody = () => {
if (!data) return null;
- return <HtmlDocumentFrame content={data.content ?? ''} title={data.title ?? undefined} />;
+ return (
+ <div {...stylex.props(styles.frame)}>
+ <HtmlDocumentFrame content={data.content ?? ''} title={data.title ?? undefined} />
+ </div>
+ );
};
export default HtmlPageBody;
diff --git a/src/features/PageEditor/PageEditor.tsx b/src/features/PageEditor/PageEditor.tsx
index d358603a6f2..fee0e024b31 100644
--- a/src/features/PageEditor/PageEditor.tsx
+++ b/src/features/PageEditor/PageEditor.tsx
@@ -70,6 +70,11 @@ const shouldRestoreEditorScroll = ({
!isUserInteractingWithEditor;
const styles = StyleSheet.create({
+ artifactContent: {
+ minWidth: 0,
+ paddingBlock: 24,
+ paddingInline: 24,
+ },
contentWrapper: {
containerType: 'inline-size',
display: 'flex',
@@ -378,42 +383,49 @@ const PageEditorCanvas = memo<PageEditorCanvasProps>((props) => {
width={'100%'}
onScroll={handleEditorScroll}
>
- <WideScreenContainer
- wrapperStyle={{ cursor: editable && !isHtmlPage ? 'text' : 'default' }}
- onChange={notifyEditorLayoutChange}
- onClick={() => {
- if (!editable || isHtmlPage) return;
-
- editor?.focus();
- }}
- >
- <Flexbox
- className={overrideStyles.editorContent}
- flex={1}
- ref={editorContentRef}
- style={editorContentStyle}
- {...{ [GUTTER_COLUMN_ATTRIBUTE]: true }}
- >
- <TitleSection />
- <PageMetaBar />
- {/* Surfaces local heartbeat health (unstable/lost) for the holder.
- Suppressed when LockedAlert is showing — see LockStatusBanner. */}
- <LockStatusBanner />
- {/* Prominent in-body notice when another member holds the lock; the
- compact status badge lives in the Header (EditingIndicator). */}
- <LockedAlert />
- {isHtmlPage ? (
- <HtmlPageBody />
- ) : (
- <>
- <EditorCanvas askCopilotTarget={askCopilotTarget} />
- <BlockCommentMarker hostRef={editorContentRef} />
- </>
- )}
- {documentId && <DocumentLikes documentId={documentId} key={documentId} />}
- <DocumentComments />
+ {isHtmlPage ? (
+ // An artifact is a finished, self-styled page: it gets the pane's full
+ // width instead of the reading column, and no editable title above it
+ // (the header carries the title; the HTML has its own heading).
+ <Flexbox flex={1} gap={24} ref={editorContentRef} style={styles.artifactContent}>
+ <HtmlPageBody />
+ <WideScreenContainer>
+ {documentId && <DocumentLikes documentId={documentId} key={documentId} />}
+ <DocumentComments />
+ </WideScreenContainer>
</Flexbox>
- </WideScreenContainer>
+ ) : (
+ <WideScreenContainer
+ wrapperStyle={{ cursor: editable ? 'text' : 'default' }}
+ onChange={notifyEditorLayoutChange}
+ onClick={() => {
+ if (!editable) return;
+
+ editor?.focus();
+ }}
+ >
+ <Flexbox
+ className={overrideStyles.editorContent}
+ flex={1}
+ ref={editorContentRef}
+ style={editorContentStyle}
+ {...{ [GUTTER_COLUMN_ATTRIBUTE]: true }}
+ >
+ <TitleSection />
+ <PageMetaBar />
+ {/* Surfaces local heartbeat health (unstable/lost) for the holder.
+ Suppressed when LockedAlert is showing — see LockStatusBanner. */}
+ <LockStatusBanner />
+ {/* Prominent in-body notice when another member holds the lock; the
+ compact status badge lives in the Header (EditingIndicator). */}
+ <LockedAlert />
+ <EditorCanvas askCopilotTarget={askCopilotTarget} />
+ <BlockCommentMarker hostRef={editorContentRef} />
+ {documentId && <DocumentLikes documentId={documentId} key={documentId} />}
+ <DocumentComments />
+ </Flexbox>
+ </WideScreenContainer>
+ )}
</Flexbox>
{!isHtmlPage && (
<TableOfContents contentRef={editorContentRef} scrollRef={contentWrapperRef} />
diff --git a/src/features/ResourceHome/Home/HomeList.tsx b/src/features/ResourceHome/Home/HomeList.tsx
index acb4ef43a1c..6a8bd0d8635 100644
--- a/src/features/ResourceHome/Home/HomeList.tsx
+++ b/src/features/ResourceHome/Home/HomeList.tsx
@@ -4,7 +4,7 @@ import { Avatar, Empty, Flexbox, Icon } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
import dayjs from 'dayjs';
-import { FileTextIcon, FolderOpenIcon, HardDriveIcon, UsersIcon } from 'lucide-react';
+import { FileTextIcon, FolderOpenIcon, GlobeIcon, HardDriveIcon, UsersIcon } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -21,6 +21,7 @@ import { knowledgeBaseSelectors, useKnowledgeBaseStore } from '@/store/library';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/slices/auth/selectors';
+import { isArtifactPage } from '../Layout/Body/PageSection/group';
import { docsFilePath, docsPagePath } from '../paths';
/** Title, location, owner, created, updated — the time columns stay fixed-width. */
@@ -227,7 +228,7 @@ const HomeList = memo<HomeListProps>(({ onTabChange, tab }) => {
row.emoji ? (
<Avatar avatar={row.emoji} size={20} />
) : (
- <Icon icon={FileTextIcon} size={18} />
+ <Icon icon={isArtifactPage(row) ? GlobeIcon : FileTextIcon} size={18} />
)
) : (
<FileIcon fileName={row.name} fileType={row.fileType} size={20} />
diff --git a/src/features/ResourceHome/Layout/Body/PageSection/FullListDrawer.tsx b/src/features/ResourceHome/Layout/Body/PageSection/FullListDrawer.tsx
new file mode 100644
index 00000000000..98d09a59244
--- /dev/null
+++ b/src/features/ResourceHome/Layout/Body/PageSection/FullListDrawer.tsx
@@ -0,0 +1,153 @@
+'use client';
+
+import { ActionIcon, DropdownMenu, Flexbox, Text } from '@lobehub/ui';
+import { ListFilter } from 'lucide-react';
+import { memo, useCallback, useMemo, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+import { VList, type VListHandle } from 'virtua';
+
+import AsyncBoundary from '@/components/AsyncBoundary';
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import SideBarDrawer from '@/features/NavPanel/SideBarDrawer';
+import { pageActions, pageSelectors, usePageStore } from '@/store/page';
+import type { PageSectionScope } from '@/store/page/projection';
+
+import { groupPageRows } from './group';
+import GroupTitle from './GroupTitle';
+import PageRow from './PageRow';
+import { buildPageTree } from './tree';
+import { useOpenPage } from './useOpenPage';
+import { isSectionNarrowed, useSectionView, useSectionViewMenu } from './useSectionView';
+
+/** Load the next page once the viewport bottom is this many rows from the end. */
+const LOAD_MORE_THRESHOLD = 8;
+
+const FullListContent = memo<{ scope: PageSectionScope }>(({ scope }) => {
+ const { t } = useTranslation('file');
+ const [view] = useSectionView(scope);
+ const { openPage, openPageId } = useOpenPage();
+ const virtuaRef = useRef<VListHandle>(null);
+
+ const params = useMemo(
+ () => ({ scope, sortBy: view.sortBy, type: view.type }),
+ [scope, view.sortBy, view.type],
+ );
+ const { error, revalidate } = pageActions.useFetchPageSectionList(params);
+ const list = usePageStore(pageSelectors.pageSectionList(scope));
+
+ // Group titles and rows share one virtual list.
+ const entries = useMemo(() => {
+ if (!list) return undefined;
+ return groupPageRows(buildPageTree(list.items), view).flatMap(({ id, rows }) => [
+ ...(id === 'all' ? [] : [{ id, kind: 'title' as const }]),
+ ...rows.map((row) => ({ ...row, kind: 'row' as const })),
+ ]);
+ }, [list, view]);
+
+ const hasMore = !!list?.hasMore;
+ const isLoadingMore = !!list?.isLoadingMore;
+ const count = entries?.length ?? 0;
+
+ const handleScroll = useCallback(() => {
+ const ref = virtuaRef.current;
+ if (!ref || !hasMore || isLoadingMore) return;
+
+ const bottomIndex = ref.findItemIndex(ref.scrollOffset + ref.viewportSize);
+ if (bottomIndex + LOAD_MORE_THRESHOLD >= count) {
+ void pageActions.loadMorePageSectionList(params);
+ }
+ }, [count, hasMore, isLoadingMore, params]);
+
+ return (
+ <AsyncBoundary
+ data={entries}
+ error={error}
+ errorVariant={'inline'}
+ isEmpty={entries?.length === 0}
+ isLoading={entries === undefined && !error}
+ loading={<SkeletonList paddingInline={8} rows={6} />}
+ empty={
+ <Text fontSize={12} style={{ padding: 12 }} type={'secondary'}>
+ {t(
+ isSectionNarrowed(view)
+ ? 'docs.sectionView.emptyFiltered'
+ : scope === 'mine'
+ ? 'docs.myDocs.empty'
+ : 'docs.shared.empty',
+ )}
+ </Text>
+ }
+ onRetry={() => revalidate()}
+ >
+ <VList
+ bufferSize={typeof window !== 'undefined' ? window.innerHeight : 0}
+ ref={virtuaRef}
+ style={{ height: '100%' }}
+ onScroll={handleScroll}
+ >
+ {entries?.map((entry) =>
+ entry.kind === 'title' ? (
+ <Flexbox key={`title-${entry.id}`} paddingInline={4}>
+ <GroupTitle id={entry.id} />
+ </Flexbox>
+ ) : (
+ <Flexbox key={entry.doc.id} paddingBlock={1} paddingInline={4}>
+ <PageRow
+ depth={entry.depth}
+ doc={entry.doc}
+ isOpen={openPageId === entry.doc.id}
+ onOpen={openPage}
+ />
+ </Flexbox>
+ ),
+ )}
+ {isLoadingMore && <SkeletonList paddingInline={8} rows={3} />}
+ </VList>
+ </AsyncBoundary>
+ );
+});
+
+FullListContent.displayName = 'PageSectionFullListContent';
+
+interface FullListDrawerProps {
+ onClose: () => void;
+ open: boolean;
+ scope: PageSectionScope;
+ title: string;
+}
+
+/**
+ * Every page of one section, opened beside the sidebar. The section itself
+ * only shows its first rows; this panel pages through the rest with the same
+ * sort, grouping and type filter.
+ */
+const FullListDrawer = memo<FullListDrawerProps>(({ open, onClose, scope, title }) => {
+ const { t } = useTranslation('file');
+ const [view] = useSectionView(scope);
+ const viewMenu = useSectionViewMenu(scope, { showPageSize: false });
+
+ return (
+ <SideBarDrawer
+ open={open}
+ title={title}
+ action={
+ <DropdownMenu items={viewMenu}>
+ <ActionIcon
+ active={isSectionNarrowed(view)}
+ icon={ListFilter}
+ size={'small'}
+ title={t('docs.sectionView.title')}
+ />
+ </DropdownMenu>
+ }
+ onClose={onClose}
+ >
+ {/* Mounted only while open, so a closed panel never pages the list. */}
+ {open && <FullListContent scope={scope} />}
+ </SideBarDrawer>
+ );
+});
+
+FullListDrawer.displayName = 'PageSectionFullListDrawer';
+
+export default FullListDrawer;
diff --git a/src/features/ResourceHome/Layout/Body/PageSection/GroupTitle.tsx b/src/features/ResourceHome/Layout/Body/PageSection/GroupTitle.tsx
new file mode 100644
index 00000000000..4d9e574b33a
--- /dev/null
+++ b/src/features/ResourceHome/Layout/Body/PageSection/GroupTitle.tsx
@@ -0,0 +1,32 @@
+'use client';
+
+import { Text } from '@lobehub/ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { formatTimeGroupId } from '@/features/AgentSidebar/Topic/TopicListContent/ByTimeMode/timeGroupTitle';
+
+/** Label above one group of section rows: a time bucket, or Pages / Artifacts. */
+const GroupTitle = memo<{ id: string }>(({ id }) => {
+ const { t } = useTranslation(['file', 'topic']);
+
+ const label =
+ id === 'page' || id === 'artifact'
+ ? t(`docs.sectionView.type.${id}`)
+ : (formatTimeGroupId(id) ?? t(`groupTitle.byTime.${id}` as any, { ns: 'topic' }));
+
+ return (
+ <Text
+ ellipsis
+ fontSize={12}
+ style={{ paddingBlock: '8px 2px', paddingInline: 8 }}
+ type={'secondary'}
+ >
+ {label}
+ </Text>
+ );
+});
+
+GroupTitle.displayName = 'PageSectionGroupTitle';
+
+export default GroupTitle;
diff --git a/src/features/ResourceHome/Layout/Body/PageSection/PageRow.tsx b/src/features/ResourceHome/Layout/Body/PageSection/PageRow.tsx
new file mode 100644
index 00000000000..f5cb664ffef
--- /dev/null
+++ b/src/features/ResourceHome/Layout/Body/PageSection/PageRow.tsx
@@ -0,0 +1,87 @@
+'use client';
+
+import { Avatar, Icon } from '@lobehub/ui';
+import { FileTextIcon, GlobeIcon } from 'lucide-react';
+import { memo, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import NavItem from '@/features/NavPanel/components/NavItem';
+import Actions from '@/features/Pages/PageLayout/Body/List/Item/Actions';
+import { useDropdownMenu } from '@/features/Pages/PageLayout/Body/List/Item/useDropdownMenu';
+import { pageActions, usePageStore } from '@/store/page';
+import type { LobeDocument } from '@/types/document';
+
+import { docsPagePath } from '../../../paths';
+import { isArtifactPage } from './group';
+import RenameInput from './RenameInput';
+
+const INDENT_PER_LEVEL = 12;
+
+interface PageRowProps {
+ depth: number;
+ doc: LobeDocument;
+ isOpen: boolean;
+ onOpen: (id: string) => void;
+}
+
+/**
+ * One page row. It carries the same actions as the old Pages sidebar — hover
+ * menu and right-click menu — because Docs is now the only place a page is
+ * listed, so rename / duplicate / delete have to live here. An artifact (an
+ * HTML page) takes the chat's HTML-artifact icon so it never reads as text.
+ */
+const PageRow = memo<PageRowProps>(({ depth, doc, isOpen, onOpen }) => {
+ const { t } = useTranslation('file');
+ const emoji = doc.metadata?.emoji;
+ const title = doc.title || t('pageList.untitled');
+ const editing = usePageStore((s) => s.renamingPageId === doc.id);
+
+ const toggleEditing = useCallback(
+ (visible?: boolean) => pageActions.setRenamingPageId(visible ? doc.id : null),
+ [doc.id],
+ );
+ const dropdownMenu = useDropdownMenu({ pageId: doc.id, toggleEditing });
+
+ return (
+ <NavItem
+ actions={<Actions dropdownMenu={dropdownMenu} />}
+ active={isOpen}
+ contextMenuItems={dropdownMenu}
+ // While the field is open the row is not a link: clicks there belong to
+ // the field, and an anchor would follow `href` and drop the edit.
+ href={editing ? undefined : docsPagePath(doc.id)}
+ style={depth ? { paddingInlineStart: 8 + depth * INDENT_PER_LEVEL } : undefined}
+ icon={
+ emoji ? (
+ <Avatar avatar={emoji} size={20} />
+ ) : (
+ <Icon
+ icon={isArtifactPage(doc) ? GlobeIcon : FileTextIcon}
+ size={{ size: 16, strokeWidth: 1.5 }}
+ />
+ )
+ }
+ title={
+ editing ? (
+ <RenameInput
+ id={doc.id}
+ title={title}
+ onDone={() => pageActions.setRenamingPageId(null)}
+ />
+ ) : (
+ title
+ )
+ }
+ onClick={() => {
+ // While the inline field is open a click belongs to the input, not to
+ // navigation — opening the page here would drop the edit.
+ if (editing) return;
+ onOpen(doc.id);
+ }}
+ />
+ );
+});
+
+PageRow.displayName = 'PageRow';
+
+export default PageRow;
diff --git a/src/features/ResourceHome/Layout/Body/PageSection/group.test.ts b/src/features/ResourceHome/Layout/Body/PageSection/group.test.ts
new file mode 100644
index 00000000000..ba5657c3251
--- /dev/null
+++ b/src/features/ResourceHome/Layout/Body/PageSection/group.test.ts
@@ -0,0 +1,82 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { groupPageRows } from './group';
+import { buildPageTree } from './tree';
+
+const NOW = new Date('2026-10-23T12:00:00');
+
+const page = (
+ id: string,
+ {
+ created,
+ html,
+ parentId,
+ updated,
+ }: {
+ created?: string;
+ html?: boolean;
+ parentId?: string;
+ updated: string;
+ },
+) => ({
+ createdAt: new Date(created ?? updated),
+ fileType: html ? 'custom/html' : 'custom/document',
+ id,
+ parentId,
+ updatedAt: new Date(updated),
+});
+
+const summarize = (groups: ReturnType<typeof groupPageRows>) =>
+ groups.map(({ id, rows }) => [id, rows.map(({ doc }) => doc.id)]);
+
+describe('groupPageRows', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(NOW);
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('keeps every row in one group when ungrouped', () => {
+ const rows = buildPageTree([page('a', { updated: '2026-10-23T09:00:00' })]);
+
+ expect(summarize(groupPageRows(rows, { groupBy: 'none', sortBy: 'updatedAt' }))).toEqual([
+ ['all', ['a']],
+ ]);
+ });
+
+ it('returns no groups for an empty list', () => {
+ expect(groupPageRows([], { groupBy: 'none', sortBy: 'updatedAt' })).toEqual([]);
+ });
+
+ it('puts pages before artifacts and keeps a sub-page under its parent', () => {
+ const rows = buildPageTree([
+ page('report', { html: true, updated: '2026-10-23T10:00:00' }),
+ page('notes', { updated: '2026-10-23T09:00:00' }),
+ page('notes-chart', { html: true, parentId: 'notes', updated: '2026-10-23T08:00:00' }),
+ ]);
+
+ expect(summarize(groupPageRows(rows, { groupBy: 'byType', sortBy: 'updatedAt' }))).toEqual([
+ ['page', ['notes', 'notes-chart']],
+ ['artifact', ['report']],
+ ]);
+ });
+
+ it('buckets by the sorted date, newest bucket first', () => {
+ const rows = buildPageTree([
+ page('title-a', { created: '2026-10-23T09:00:00', updated: '2026-09-01T09:00:00' }),
+ page('title-b', { created: '2026-10-22T09:00:00', updated: '2026-10-23T08:00:00' }),
+ ]);
+
+ expect(summarize(groupPageRows(rows, { groupBy: 'byTime', sortBy: 'title' }))).toEqual([
+ ['today', ['title-b']],
+ ['2026-09', ['title-a']],
+ ]);
+ expect(summarize(groupPageRows(rows, { groupBy: 'byTime', sortBy: 'createdAt' }))).toEqual([
+ ['today', ['title-a']],
+ ['yesterday', ['title-b']],
+ ]);
+ });
+});
diff --git a/src/features/ResourceHome/Layout/Body/PageSection/group.ts b/src/features/ResourceHome/Layout/Body/PageSection/group.ts
new file mode 100644
index 00000000000..18fc0d41d80
--- /dev/null
+++ b/src/features/ResourceHome/Layout/Body/PageSection/group.ts
@@ -0,0 +1,66 @@
+import { HTML_DOCUMENT_FILE_TYPE } from '@lobechat/const';
+
+import type { DocsPageSectionView } from '@/store/global/initialState';
+import { getTimeGroupId, sortTimeGroups } from '@/utils/client/topic';
+
+import type { PageTreeRow } from './tree';
+
+interface GroupableDoc {
+ createdAt: Date;
+ fileType: string;
+ id: string;
+ parentId?: string | null;
+ updatedAt: Date;
+}
+
+export interface PageRowGroup<T extends GroupableDoc> {
+ /** `all` when ungrouped, a time bucket id, or `page` / `artifact`. */
+ id: string;
+ rows: PageTreeRow<T>[];
+}
+
+/** Whether a page is an artifact: a self-contained HTML page, not rich text. */
+export const isArtifactPage = (doc: { fileType?: string | null }): boolean =>
+ doc.fileType === HTML_DOCUMENT_FILE_TYPE;
+
+const TYPE_GROUP_ORDER = ['page', 'artifact'];
+
+/**
+ * Split tree rows into the section's groups. A sub-page stays under its parent,
+ * so only top-level rows decide the group. Time buckets follow the sorted date
+ * (`updatedAt` unless the list is sorted by creation); a title sort keeps the
+ * A→Z order inside each bucket.
+ */
+export const groupPageRows = <T extends GroupableDoc>(
+ rows: PageTreeRow<T>[],
+ { groupBy, sortBy }: Pick<DocsPageSectionView, 'groupBy' | 'sortBy'>,
+): PageRowGroup<T>[] => {
+ if (groupBy === 'none') return rows.length > 0 ? [{ id: 'all', rows }] : [];
+
+ const groupOf = (doc: T): string => {
+ if (groupBy === 'byType') return isArtifactPage(doc) ? 'artifact' : 'page';
+
+ const date = sortBy === 'createdAt' ? doc.createdAt : doc.updatedAt;
+ return getTimeGroupId(new Date(date).getTime());
+ };
+
+ const groups = new Map<string, PageTreeRow<T>[]>();
+ let current: PageTreeRow<T>[] = [];
+
+ for (const row of rows) {
+ if (row.depth === 0) {
+ const id = groupOf(row.doc);
+ current = groups.get(id) ?? [];
+ groups.set(id, current);
+ }
+ current.push(row);
+ }
+
+ const result = [...groups].map(([id, groupRows]) => ({ id, rows: groupRows }));
+
+ if (groupBy === 'byType') {
+ return result.sort((a, b) => TYPE_GROUP_ORDER.indexOf(a.id) - TYPE_GROUP_ORDER.indexOf(b.id));
+ }
+
+ return sortTimeGroups(result);
+};
diff --git a/src/features/ResourceHome/Layout/Body/PageSection/index.tsx b/src/features/ResourceHome/Layout/Body/PageSection/index.tsx
index 9a54f2cddfd..0b92a7db072 100644
--- a/src/features/ResourceHome/Layout/Body/PageSection/index.tsx
+++ b/src/features/ResourceHome/Layout/Body/PageSection/index.tsx
@@ -7,102 +7,32 @@ import {
accordionStyles,
AccordionTrigger,
ActionIcon,
- Avatar,
cx,
+ DropdownMenu,
Flexbox,
- Icon,
Spin,
Text,
toast,
Tooltip,
} from '@lobehub/ui';
-import { FileTextIcon, MoreHorizontal, SquarePenIcon } from 'lucide-react';
-import { memo, useCallback, useMemo, useState } from 'react';
+import { ListFilter, MoreHorizontal, PanelRightOpenIcon, SquarePenIcon } from 'lucide-react';
+import { Fragment, memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import AsyncBoundary from '@/components/AsyncBoundary';
import EmptyNavItem from '@/features/NavPanel/components/EmptyNavItem';
import NavItem from '@/features/NavPanel/components/NavItem';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
-import Actions from '@/features/Pages/PageLayout/Body/List/Item/Actions';
-import { useDropdownMenu } from '@/features/Pages/PageLayout/Body/List/Item/useDropdownMenu';
-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
-import { useActiveLocation } from '@/hooks/useActiveLocation';
import { usePermission } from '@/hooks/usePermission';
import { pageActions, pageSelectors, usePageStore } from '@/store/page';
import type { PageSectionScope } from '@/store/page/projection';
-import type { LobeDocument } from '@/types/document';
-import { docsPagePath, resolveResourceRoute } from '../../../paths';
-import RenameInput from './RenameInput';
+import { groupPageRows } from './group';
+import GroupTitle from './GroupTitle';
+import PageRow from './PageRow';
import { buildPageTree } from './tree';
-
-/** Rows a section shows; the rest are in the Docs home list. */
-const SECTION_LIMIT = 20;
-const INDENT_PER_LEVEL = 12;
-
-interface PageRowProps {
- depth: number;
- doc: LobeDocument;
- isOpen: boolean;
- onOpen: (id: string) => void;
-}
-
-/**
- * One page row. It carries the same actions as the old Pages sidebar — hover
- * menu and right-click menu — because Docs is now the only place a page is
- * listed, so rename / duplicate / delete have to live here.
- */
-const PageRow = memo<PageRowProps>(({ depth, doc, isOpen, onOpen }) => {
- const { t } = useTranslation('file');
- const emoji = doc.metadata?.emoji;
- const title = doc.title || t('pageList.untitled');
- const editing = usePageStore((s) => s.renamingPageId === doc.id);
-
- const toggleEditing = useCallback(
- (visible?: boolean) => pageActions.setRenamingPageId(visible ? doc.id : null),
- [doc.id],
- );
- const dropdownMenu = useDropdownMenu({ pageId: doc.id, toggleEditing });
-
- return (
- <NavItem
- actions={<Actions dropdownMenu={dropdownMenu} />}
- active={isOpen}
- contextMenuItems={dropdownMenu}
- // While the field is open the row is not a link: clicks there belong to
- // the field, and an anchor would follow `href` and drop the edit.
- href={editing ? undefined : docsPagePath(doc.id)}
- style={depth ? { paddingInlineStart: 8 + depth * INDENT_PER_LEVEL } : undefined}
- icon={
- emoji ? (
- <Avatar avatar={emoji} size={20} />
- ) : (
- <Icon icon={FileTextIcon} size={{ size: 16, strokeWidth: 1.5 }} />
- )
- }
- title={
- editing ? (
- <RenameInput
- id={doc.id}
- title={title}
- onDone={() => pageActions.setRenamingPageId(null)}
- />
- ) : (
- title
- )
- }
- onClick={() => {
- // While the inline field is open a click belongs to the input, not to
- // navigation — opening the page here would drop the edit.
- if (editing) return;
- onOpen(doc.id);
- }}
- />
- );
-});
-
-PageRow.displayName = 'PageRow';
+import { useOpenPage } from './useOpenPage';
+import { isSectionNarrowed, useSectionView, useSectionViewMenu } from './useSectionView';
interface PageSectionProps {
itemKey: string;
@@ -116,21 +46,28 @@ interface PageSectionProps {
*/
const PageSection = memo<PageSectionProps>(({ itemKey, scope }) => {
const { t } = useTranslation('file');
- const navigate = useWorkspaceAwareNavigate();
const [creating, setCreating] = useState(false);
const { allowed: canCreate, reason } = usePermission('create_content');
-
- const { error, isValidating, revalidate } = pageActions.useFetchPageSection(scope, SECTION_LIMIT);
+ const [view] = useSectionView(scope);
+ const viewMenu = useSectionViewMenu(scope);
+
+ const { error, isValidating, revalidate } = pageActions.useFetchPageSection({
+ limit: view.pageSize,
+ scope,
+ sortBy: view.sortBy,
+ type: view.type,
+ });
const docs = usePageStore(pageSelectors.pageSection(scope));
- const rows = useMemo(() => (docs ? buildPageTree(docs.slice(0, SECTION_LIMIT)) : docs), [docs]);
- const hasMore = (docs?.length ?? 0) > SECTION_LIMIT;
+ const groups = useMemo(
+ () => (docs ? groupPageRows(buildPageTree(docs.slice(0, view.pageSize)), view) : undefined),
+ [docs, view],
+ );
+ const hasMore = (docs?.length ?? 0) > view.pageSize;
+ const openFullList = () => pageActions.openSectionFullList(scope);
// Pages open over the Docs home, keeping the user in Docs.
- const location = useActiveLocation();
- const openedView = resolveResourceRoute(location.pathname, new URLSearchParams(location.search));
- const openFileId = openedView.kind === 'page' ? openedView.id : null;
- const openPage = (id: string) => navigate(docsPagePath(id));
+ const { openPage, openPageId } = useOpenPage();
const handleCreate = async () => {
if (!canCreate || creating) return;
@@ -162,6 +99,13 @@ const PageSection = memo<PageSectionProps>(({ itemKey, scope }) => {
/>
);
+ const narrowed = isSectionNarrowed(view);
+ const actionsClassName = cx(
+ 'accordion-action',
+ accordionStyles.action,
+ accordionStyles.actionBorderless,
+ );
+
return (
<AccordionItem value={itemKey}>
<AccordionHeader>
@@ -170,31 +114,50 @@ const PageSection = memo<PageSectionProps>(({ itemKey, scope }) => {
<Text ellipsis fontSize={12} type={'secondary'} weight={500}>
{title}
</Text>
- {isValidating && !!rows?.length && <Spin size={'small'} variant={'network'} />}
+ {isValidating && !!groups?.length && <Spin size={'small'} variant={'network'} />}
</Flexbox>
</AccordionTrigger>
- {scope === 'mine' && (
- <div
- className={cx(
- 'accordion-action',
- accordionStyles.action,
- accordionStyles.actionBorderless,
- )}
- >
- {canCreate ? createButton : <Tooltip title={reason}>{createButton}</Tooltip>}
- </div>
- )}
+ {/* A type filter hides pages: keep its trigger on screen, not hover-only. */}
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={actionsClassName}
+ gap={2}
+ style={narrowed ? { opacity: 1 } : undefined}
+ >
+ <DropdownMenu items={viewMenu}>
+ <ActionIcon
+ active={narrowed}
+ icon={ListFilter}
+ size={'small'}
+ title={t('docs.sectionView.title')}
+ />
+ </DropdownMenu>
+ <ActionIcon
+ aria-label={t('docs.sectionView.openFullList')}
+ icon={PanelRightOpenIcon}
+ size={'small'}
+ title={t('docs.sectionView.openFullList')}
+ onClick={openFullList}
+ />
+ {scope === 'mine' &&
+ (canCreate ? createButton : <Tooltip title={reason}>{createButton}</Tooltip>)}
+ </Flexbox>
</AccordionHeader>
<AccordionPanel>
<AsyncBoundary
- data={rows}
+ data={groups}
error={error}
errorVariant={'inline'}
- isEmpty={rows?.length === 0}
- isLoading={rows === undefined && !error}
+ isEmpty={groups?.length === 0}
+ isLoading={groups === undefined && !error}
loading={<SkeletonList paddingInline={4} rows={3} />}
empty={
- scope === 'mine' ? (
+ narrowed ? (
+ <Text fontSize={12} style={{ paddingInline: 12 }} type={'secondary'}>
+ {t('docs.sectionView.emptyFiltered')}
+ </Text>
+ ) : scope === 'mine' ? (
<EmptyNavItem
disabled={!canCreate}
title={t('docs.myDocs.empty')}
@@ -209,23 +172,28 @@ const PageSection = memo<PageSectionProps>(({ itemKey, scope }) => {
onRetry={() => revalidate()}
>
<Flexbox gap={1} paddingInline={4}>
- {rows?.map(({ depth, doc }) => (
- <PageRow
- depth={depth}
- doc={doc}
- isOpen={openFileId === doc.id}
- key={doc.id}
- onOpen={openPage}
- />
+ {groups?.map(({ id, rows }) => (
+ <Fragment key={id}>
+ {id !== 'all' && <GroupTitle id={id} />}
+ {rows.map(({ depth, doc }) => (
+ <PageRow
+ depth={depth}
+ doc={doc}
+ isOpen={openPageId === doc.id}
+ key={doc.id}
+ onOpen={openPage}
+ />
+ ))}
+ </Fragment>
))}
{hasMore && (
<NavItem
icon={MoreHorizontal}
title={t('docs.viewAllPages')}
- // Opens the paged all-pages drawer rather than the Docs home,
- // whose mixed recent list is capped and mixes files in — an
- // older page pushed out of both lists would be unreachable.
- onClick={() => pageActions.openAllPagesDrawer()}
+ // Opens the section's paged full list rather than the Docs
+ // home, whose mixed recent list is capped and mixes files in —
+ // an older page pushed out of both lists would be unreachable.
+ onClick={openFullList}
/>
)}
</Flexbox>
diff --git a/src/features/ResourceHome/Layout/Body/PageSection/useOpenPage.ts b/src/features/ResourceHome/Layout/Body/PageSection/useOpenPage.ts
new file mode 100644
index 00000000000..f83cb20426e
--- /dev/null
+++ b/src/features/ResourceHome/Layout/Body/PageSection/useOpenPage.ts
@@ -0,0 +1,18 @@
+import { useCallback } from 'react';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useActiveLocation } from '@/hooks/useActiveLocation';
+
+import { docsPagePath, resolveResourceRoute } from '../../../paths';
+
+/** The page open over the Docs home, and how a row opens one without leaving Docs. */
+export const useOpenPage = () => {
+ const navigate = useWorkspaceAwareNavigate();
+ const location = useActiveLocation();
+ const openedView = resolveResourceRoute(location.pathname, new URLSearchParams(location.search));
+ const openPageId = openedView.kind === 'page' ? openedView.id : null;
+
+ const openPage = useCallback((id: string) => navigate(docsPagePath(id)), [navigate]);
+
+ return { openPage, openPageId };
+};
diff --git a/src/features/ResourceHome/Layout/Body/PageSection/useSectionView.tsx b/src/features/ResourceHome/Layout/Body/PageSection/useSectionView.tsx
new file mode 100644
index 00000000000..267da12c250
--- /dev/null
+++ b/src/features/ResourceHome/Layout/Body/PageSection/useSectionView.tsx
@@ -0,0 +1,111 @@
+import type { DropdownItem } from '@lobehub/ui';
+import { Icon } from '@lobehub/ui';
+import { LucideCheck } from 'lucide-react';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useGlobalStore } from '@/store/global';
+import {
+ DEFAULT_DOCS_PAGE_SECTION_VIEW,
+ type DocsPageSectionKey,
+ type DocsPageSectionView,
+} from '@/store/global/initialState';
+import { systemStatusSelectors } from '@/store/global/selectors';
+
+const SORT_OPTIONS: DocsPageSectionView['sortBy'][] = ['updatedAt', 'createdAt', 'title'];
+const GROUP_OPTIONS: DocsPageSectionView['groupBy'][] = ['none', 'byTime', 'byType'];
+const TYPE_OPTIONS: DocsPageSectionView['type'][] = ['all', 'page', 'artifact'];
+const PAGE_SIZE_OPTIONS = [10, 20, 40, 60];
+
+/** One section's persisted list options and their setter. */
+export const useSectionView = (scope: DocsPageSectionKey) => {
+ const view = useGlobalStore(systemStatusSelectors.docsPageSectionView(scope));
+ const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
+
+ const setView = useCallback(
+ (patch: Partial<DocsPageSectionView>) =>
+ updateSystemStatus({ docsPageSectionViews: { [scope]: patch } }),
+ [scope, updateSystemStatus],
+ );
+
+ return [view, setView] as const;
+};
+
+/** A type filter hides pages, so the trigger must not read as the whole list. */
+export const isSectionNarrowed = (view: DocsPageSectionView) =>
+ view.type !== DEFAULT_DOCS_PAGE_SECTION_VIEW.type;
+
+interface SectionViewMenuOptions {
+ /** The full list always pages through everything; only the sidebar caps its rows. */
+ showPageSize?: boolean;
+}
+
+/** Sort / group / type / row-count items for a section's view-options menu. */
+export const useSectionViewMenu = (
+ scope: DocsPageSectionKey,
+ { showPageSize = true }: SectionViewMenuOptions = {},
+): (() => DropdownItem[]) => {
+ const { t } = useTranslation(['file', 'common']);
+ const [view, setView] = useSectionView(scope);
+
+ return useCallback(() => {
+ const check = (selected: boolean) => (selected ? <Icon icon={LucideCheck} /> : <div />);
+
+ const items: DropdownItem[] = [
+ {
+ children: SORT_OPTIONS.map((sortBy) => ({
+ icon: check(view.sortBy === sortBy),
+ key: `sort-${sortBy}`,
+ label: t(`docs.sectionView.sortBy.${sortBy}`),
+ onClick: () => setView({ sortBy }),
+ })),
+ key: 'sort',
+ label: t('docs.sectionView.sort'),
+ type: 'group',
+ },
+ { type: 'divider' },
+ {
+ children: GROUP_OPTIONS.map((groupBy) => ({
+ icon: check(view.groupBy === groupBy),
+ key: `group-${groupBy}`,
+ label: t(`docs.sectionView.groupBy.${groupBy}`),
+ onClick: () => setView({ groupBy }),
+ })),
+ key: 'group',
+ label: t('docs.sectionView.group'),
+ type: 'group',
+ },
+ { type: 'divider' },
+ {
+ children: TYPE_OPTIONS.map((type) => ({
+ icon: check(view.type === type),
+ key: `type-${type}`,
+ label: t(`docs.sectionView.type.${type}`),
+ onClick: () => setView({ type }),
+ })),
+ key: 'type',
+ label: t('docs.sectionView.filter'),
+ type: 'group',
+ },
+ ];
+
+ if (showPageSize) {
+ items.push(
+ { type: 'divider' },
+ {
+ children: PAGE_SIZE_OPTIONS.map((pageSize) => ({
+ icon: check(view.pageSize === pageSize),
+ key: `pageSize-${pageSize}`,
+ label: t('pageSizeItem', { count: pageSize, ns: 'common' }),
+ onClick: () => setView({ pageSize }),
+ })),
+ key: 'pageSize',
+ label: t('docs.sectionView.pageSize'),
+ type: 'group',
+ },
+ );
+ }
+
+ return items;
+ }, [setView, showPageSize, t, view]);
+};
diff --git a/src/features/ResourceHome/Layout/SidebarContent.tsx b/src/features/ResourceHome/Layout/SidebarContent.tsx
index 195a78a240c..4686c8e0d79 100644
--- a/src/features/ResourceHome/Layout/SidebarContent.tsx
+++ b/src/features/ResourceHome/Layout/SidebarContent.tsx
@@ -2,32 +2,38 @@
import { AccordionRoot, Flexbox } from '@lobehub/ui';
import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import SideBarLayout from '@/features/NavPanel/SideBarLayout';
-import AllPagesDrawer from '@/features/Pages/PageLayout/Body/AllPagesDrawer';
import { pageActions, usePageStore } from '@/store/page';
import SidebarBody from './Body';
import PageSection from './Body/PageSection';
+import FullListDrawer from './Body/PageSection/FullListDrawer';
import Header from './Header';
/**
- * Every page, not just the first 20 a section lists. The sections only carry a
- * capped slice, and the home dashboard's mixed list is capped too, so without
- * this drawer an older page pushed out of the slice has no listing that can
- * reach it.
+ * Every page of a section, not just the first rows it lists. The sections only
+ * carry a capped slice, and the home dashboard's mixed list is capped too, so
+ * without this panel an older page pushed out of the slice has no listing that
+ * can reach it. One panel serves both sections; the last one opened wins.
*/
-const AllPagesDrawerHost = memo(() => {
- // The drawer pages the global page list, which the sections never load — they
- // read their own capped projection.
- pageActions.useFetchDocuments();
- const open = usePageStore((s) => s.allPagesDrawerOpen);
+const FullListDrawerHost = memo(() => {
+ const { t } = useTranslation('file');
+ const [open, scope] = usePageStore((s) => [s.sectionFullListOpen, s.sectionFullListScope]);
- return <AllPagesDrawer open={open} onClose={pageActions.closeAllPagesDrawer} />;
+ return (
+ <FullListDrawer
+ open={open}
+ scope={scope}
+ title={t(scope === 'mine' ? 'docs.myDocs.title' : 'docs.shared.title')}
+ onClose={pageActions.closeSectionFullList}
+ />
+ );
});
-AllPagesDrawerHost.displayName = 'DocsAllPagesDrawerHost';
+FullListDrawerHost.displayName = 'DocsFullListDrawerHost';
export enum GroupKey {
Library = 'library',
@@ -60,7 +66,7 @@ const ResourceSidebarContent = memo(() => {
{workspaceId && <PageSection itemKey={GroupKey.Shared} scope={'shared'} />}
</AccordionRoot>
</Flexbox>
- <AllPagesDrawerHost />
+ <FullListDrawerHost />
</>
}
/>
diff --git a/src/features/ResourceManager/index.tsx b/src/features/ResourceManager/index.tsx
index 0710676dbfe..bdbd4e49bb9 100644
--- a/src/features/ResourceManager/index.tsx
+++ b/src/features/ResourceManager/index.tsx
@@ -14,6 +14,7 @@ import dynamic from '@/libs/next/dynamic';
import { invalidateDocumentMutation } from '@/services/document/invalidation';
import { useFileStore } from '@/store/file';
import { documentSelectors } from '@/store/file/slices/document/selectors';
+import { pageSelectors, usePageStore } from '@/store/page';
import FileEditor from './components/Editor';
import Explorer from './components/Explorer';
@@ -85,6 +86,12 @@ const ResourceManager = memo<ResourceManagerProps>(({ content, explorerHero }) =
]);
const currentDocument = useFileStore(documentSelectors.getDocumentById(currentViewItemId));
+ // The sidebar row the page was opened from already knows its title and emoji;
+ // without it the header reads "Untitled" until the page fetch lands.
+ const [listedTitle, listedEmoji] = usePageStore((s) => {
+ const row = pageSelectors.getDocumentById(currentViewItemId)(s);
+ return [row?.title, row?.metadata?.emoji as string | undefined] as const;
+ });
const useFetchDocumentDetail = useFileStore((s) => s.useFetchDocumentDetail);
const { allowed: canUpload } = usePermission('create_content');
const uploadTopLevel = useTopLevelFileUpload();
@@ -159,10 +166,10 @@ const ResourceManager = memo<ResourceManagerProps>(({ content, explorerHero }) =
{mode === 'page' && (
<Flexbox className={styles.pageEditorOverlay}>
<PageEditor
- emoji={currentDocument?.metadata?.emoji as string | undefined}
+ emoji={(currentDocument?.metadata?.emoji as string | undefined) ?? listedEmoji}
knowledgeBaseId={libraryId}
pageId={currentViewItemId}
- title={currentDocument?.title}
+ title={currentDocument?.title ?? (listedTitle || undefined)}
onBack={handleBack}
onEmojiChange={handleMetadataSaved}
onTitleChange={handleMetadataSaved}
diff --git a/src/services/document/index.ts b/src/services/document/index.ts
index 83730ad80fc..50058ddb9da 100644
--- a/src/services/document/index.ts
+++ b/src/services/document/index.ts
@@ -169,6 +169,7 @@ export class DocumentService {
current?: number;
fileTypes?: string[];
pageSize?: number;
+ sortBy?: 'createdAt' | 'title' | 'updatedAt';
sourceTypes?: string[];
standaloneOnly?: boolean;
}): Promise<{ items: DocumentItem[]; total: number }> {
diff --git a/src/store/document/slices/editor/action.identity.test.ts b/src/store/document/slices/editor/action.identity.test.ts
index 80433c156f4..e5f872d5d45 100644
--- a/src/store/document/slices/editor/action.identity.test.ts
+++ b/src/store/document/slices/editor/action.identity.test.ts
@@ -164,10 +164,14 @@ describe('document identity and metadata-only saves', () => {
});
it('syncs editor changes once the editor holding the document is in the store', async () => {
- const { editor } = makeEditor('B typed');
+ const { editor, spy } = makeEditor('');
seed('B', '', editor);
await useDocumentStore.getState().onEditorInit(editor, 'B');
+ // The user types after the body loaded.
+ spy.getDocument.mockImplementation((format: string) =>
+ format === 'json' ? body('B typed') : 'B typed',
+ );
useDocumentStore.getState().handleContentChange();
expect(useDocumentStore.getState().documents.B.content).toBe('B typed');
diff --git a/src/store/document/slices/editor/action.ts b/src/store/document/slices/editor/action.ts
index c75995b1aed..887eaf1b076 100644
--- a/src/store/document/slices/editor/action.ts
+++ b/src/store/document/slices/editor/action.ts
@@ -111,7 +111,11 @@ export class EditorActionImpl {
const markdownChanged = markdown !== doc.lastSavedContent;
const editorDataChanged = !isEqual(editorData, doc.lastSavedEditorData);
- const contentChanged = markdownChanged || editorDataChanged;
+ const isLoadedBody =
+ !!doc.loadedBody &&
+ markdown === doc.loadedBody.content &&
+ isEqual(editorData, doc.loadedBody.editorData);
+ const contentChanged = !isLoadedBody && (markdownChanged || editorDataChanged);
internal_dispatchDocument(
{
@@ -262,6 +266,8 @@ export class EditorActionImpl {
lastSavedContent: content,
lastSavedEditorData: editorData,
lastUpdatedTime: updatedAt,
+ // The editor reloads the adopted body and records it again.
+ loadedBody: undefined,
saveBlockedByLock: false,
saveStatus: 'saved',
},
@@ -286,6 +292,48 @@ export class EditorActionImpl {
this.#loadDocumentIntoEditor(editor, doc);
this.#editorDocumentIds.set(editor, documentId);
+ if (!doc.isDirty) this.#adoptLoadedBody(editor, documentId);
+ };
+
+ /**
+ * Record the body the editor just loaded as unedited. Loading is not
+ * byte-stable: markdown is parsed into a fresh tree with new node ids, and the
+ * editor's own markdown need not match the stored text. A page an agent or
+ * the CLI wrote has no editorData at all, so without this the load itself
+ * reads as an edit — opening the page marks it dirty, autosaves it and holds
+ * navigation behind a "Saving…" toast although the user changed nothing.
+ *
+ * `lastSaved*` keeps the server's body: conflict reconciliation compares
+ * remote rows against it, and a normalized copy there would make a remote
+ * title-only change look like a body change and discard local edits.
+ */
+ #adoptLoadedBody = (editor: IEditor, documentId: string): void => {
+ try {
+ const markdown = this.getPersistedMarkdown(
+ documentId,
+ (editor.getDocument('markdown') as unknown as string) || '',
+ );
+ const editorData = editor.getDocument('json');
+ if (!isValidEditorData(editorData)) return;
+
+ // The load's own change event already queued an autosave of this body.
+ this.#get().cancelDebouncedSave(documentId);
+ this.#get().internal_dispatchDocument(
+ {
+ id: documentId,
+ type: 'updateDocument',
+ value: {
+ content: markdown,
+ editorData,
+ isDirty: false,
+ loadedBody: { content: markdown, editorData },
+ },
+ },
+ 'adoptLoadedBody',
+ );
+ } catch (error) {
+ console.error('[DocumentStore] Failed to read the loaded body:', error);
+ }
};
#loadDocumentIntoEditor = (editor: IEditor, doc: EditorContentState): void => {
@@ -465,6 +513,8 @@ export class EditorActionImpl {
!isEqual(current?.editorData, currentEditorData),
lastSavedContent: currentContent,
lastSavedEditorData: structuredClone(currentEditorData),
+ // The saved body is now the editor's own serialization.
+ loadedBody: undefined,
}
: {}),
...(savedAt ? { lastUpdatedTime: savedAt } : {}),
diff --git a/src/store/document/slices/editor/initialState.ts b/src/store/document/slices/editor/initialState.ts
index 370c108708f..9e3b8db54fc 100644
--- a/src/store/document/slices/editor/initialState.ts
+++ b/src/store/document/slices/editor/initialState.ts
@@ -52,6 +52,14 @@ export interface EditorContentState {
* Last updated time
*/
lastUpdatedTime: Date | null;
+ /**
+ * The body as the editor serialized it right after loading it. Loading is not
+ * byte-stable (fresh node ids, the editor's own markdown export), so a body
+ * equal to this is unedited even when it differs from `lastSaved*`. Only the
+ * dirty check reads it; `lastSaved*` stays the server's body, which conflict
+ * reconciliation compares remote rows against. Cleared once a save lands.
+ */
+ loadedBody?: { content: string; editorData: unknown };
/**
* Edit-session id that currently owns this document's collaborative lock.
* Used by workspace page saves to prove the client still holds the lease.
diff --git a/src/store/document/slices/editor/onEditorInit.loadedBaseline.test.ts b/src/store/document/slices/editor/onEditorInit.loadedBaseline.test.ts
new file mode 100644
index 00000000000..07b4cd07ef1
--- /dev/null
+++ b/src/store/document/slices/editor/onEditorInit.loadedBaseline.test.ts
@@ -0,0 +1,181 @@
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { documentService } from '@/services/document';
+
+import { useDocumentStore } from '../../store';
+
+vi.mock('@/services/document', () => ({
+ documentService: {
+ acquireDocumentLock: vi.fn().mockResolvedValue({ holderId: null, lockedByOther: false }),
+ releaseDocumentLock: vi.fn().mockResolvedValue(undefined),
+ getDocumentById: vi.fn().mockResolvedValue(null),
+ updateDocument: vi.fn().mockResolvedValue({
+ historyAppended: false,
+ id: 'doc-1',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ }),
+ },
+}));
+
+vi.mock('@/services/notebook', () => ({
+ notebookService: { updateDocument: vi.fn().mockResolvedValue({}) },
+}));
+
+/** The tree the editor builds from markdown: fresh node ids, its own markdown export. */
+const PARSED_TREE = {
+ root: {
+ children: [{ children: [{ text: 'Title', type: 'text' }], id: 'n-1', type: 'heading' }],
+ type: 'root',
+ },
+};
+
+/**
+ * A Lexical-like editor: `setDocument` swaps the body and fires the update
+ * listener synchronously, the way `InternalEditor` reports the load as a change.
+ */
+const createLoadingEditor = (onLoad: () => void) => {
+ let loaded = false;
+ return {
+ getDocument: vi.fn((type: string) => {
+ if (!loaded) return type === 'markdown' ? '' : null;
+ return type === 'markdown' ? '# Title\n' : PARSED_TREE;
+ }),
+ setDocument: vi.fn(() => {
+ loaded = true;
+ onLoad();
+ }),
+ };
+};
+
+describe('onEditorInit — the loaded body is the clean baseline', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.mocked(documentService.updateDocument).mockClear();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('does not mark a markdown-only page dirty or autosave it just for opening it', async () => {
+ const { result } = renderHook(() => useDocumentStore());
+ const editor = createLoadingEditor(() => useDocumentStore.getState().handleContentChange());
+
+ act(() => {
+ // A page written by an agent or the CLI: markdown, no editorData.
+ result.current.initDocumentWithEditor({
+ content: '# Title',
+ documentId: 'doc-1',
+ editor: editor as any,
+ editorData: null,
+ sourceType: 'page',
+ });
+ useDocumentStore.setState({ activeDocumentId: 'doc-1', editor: editor as any });
+ });
+
+ await act(async () => {
+ await result.current.onEditorInit(editor as any, 'doc-1');
+ });
+
+ expect(useDocumentStore.getState().documents['doc-1'].isDirty).toBe(false);
+
+ await act(async () => {
+ await vi.runAllTimersAsync();
+ });
+
+ expect(documentService.updateDocument).not.toHaveBeenCalled();
+ expect(useDocumentStore.getState().documents['doc-1'].saveStatus).not.toBe('saving');
+ });
+
+ it('still saves an edit made after the page loaded', async () => {
+ const { result } = renderHook(() => useDocumentStore());
+ const editor = createLoadingEditor(() => useDocumentStore.getState().handleContentChange());
+
+ act(() => {
+ result.current.initDocumentWithEditor({
+ content: '# Title',
+ documentId: 'doc-1',
+ editor: editor as any,
+ editorData: null,
+ sourceType: 'page',
+ });
+ useDocumentStore.setState({ activeDocumentId: 'doc-1', editor: editor as any });
+ });
+
+ await act(async () => {
+ await result.current.onEditorInit(editor as any, 'doc-1');
+ });
+
+ editor.getDocument.mockImplementation((type: string) =>
+ type === 'markdown'
+ ? '# Title\n\nNew line\n'
+ : {
+ root: {
+ ...PARSED_TREE.root,
+ children: [
+ ...PARSED_TREE.root.children,
+ { children: [{ text: 'New line', type: 'text' }], id: 'n-2', type: 'paragraph' },
+ ],
+ },
+ },
+ );
+
+ act(() => {
+ useDocumentStore.getState().handleContentChange();
+ });
+
+ expect(useDocumentStore.getState().documents['doc-1'].isDirty).toBe(true);
+
+ await act(async () => {
+ await vi.runAllTimersAsync();
+ });
+
+ expect(documentService.updateDocument).toHaveBeenCalledWith(
+ expect.objectContaining({ content: '# Title\n\nNew line\n', id: 'doc-1' }),
+ );
+ });
+
+ it('keeps local edits when a newer remote row carries the same server body', async () => {
+ const { result } = renderHook(() => useDocumentStore());
+ const editor = createLoadingEditor(() => useDocumentStore.getState().handleContentChange());
+
+ act(() => {
+ result.current.initDocumentWithEditor({
+ content: '# Title',
+ documentId: 'doc-1',
+ editor: editor as any,
+ editorData: null,
+ sourceType: 'page',
+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),
+ });
+ useDocumentStore.setState({ activeDocumentId: 'doc-1', editor: editor as any });
+ });
+
+ await act(async () => {
+ await result.current.onEditorInit(editor as any, 'doc-1');
+ });
+
+ editor.getDocument.mockImplementation((type: string) =>
+ type === 'markdown' ? '# Title\n\nLocal edit\n' : { root: { children: [], type: 'root' } },
+ );
+ act(() => {
+ useDocumentStore.getState().handleContentChange();
+ });
+
+ // Another session renamed the page: newer row, unchanged markdown-only body.
+ let outcome: string | undefined;
+ act(() => {
+ outcome = useDocumentStore.getState().reconcileRemote('doc-1', {
+ content: '# Title',
+ editorData: null,
+ updatedAt: new Date('2026-01-02T00:00:00.000Z'),
+ } as any);
+ });
+
+ expect(outcome).toBe('rebased');
+ const doc = useDocumentStore.getState().documents['doc-1'];
+ expect(doc.isDirty).toBe(true);
+ expect(doc.content).toBe('# Title\n\nLocal edit\n');
+ });
+});
diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.ts
index 41d80e5dcad..cde159f1383 100644
--- a/src/store/global/initialState.ts
+++ b/src/store/global/initialState.ts
@@ -163,6 +163,27 @@ export interface AgentDocumentSort {
order: 'asc' | 'desc';
}
+/** Which Docs sidebar page section a view setting belongs to. */
+export type DocsPageSectionKey = 'mine' | 'shared';
+
+/** How a Docs sidebar page section (My docs / Shared docs) lists its pages. */
+export interface DocsPageSectionView {
+ /** `byTime` buckets rows by the sorted date; `byType` puts artifacts apart from pages. */
+ groupBy: 'byTime' | 'byType' | 'none';
+ /** Rows the section loads and shows; the rest are one click away in the full list. */
+ pageSize: number;
+ sortBy: 'createdAt' | 'title' | 'updatedAt';
+ /** `artifact` keeps HTML pages only, `page` keeps rich-text pages only. */
+ type: 'all' | 'artifact' | 'page';
+}
+
+export const DEFAULT_DOCS_PAGE_SECTION_VIEW: DocsPageSectionView = {
+ groupBy: 'none',
+ pageSize: 20,
+ sortBy: 'updatedAt',
+ type: 'all',
+};
+
/** How the sidebar project list is ordered; `manual` follows the shared drag order. */
export type ProjectListSortBy = 'manual' | 'createdAt' | 'updatedAt';
@@ -225,6 +246,11 @@ export interface SystemStatus {
* in the Home inbox. Append-only and capped, see `appendDismissedIslandKey`.
*/
dismissedIslandItemKeys?: string[];
+ /**
+ * List options of each Docs sidebar page section, kept apart so narrowing
+ * Shared docs never changes what My docs shows.
+ */
+ docsPageSectionViews?: Partial<Record<DocsPageSectionKey, Partial<DocsPageSectionView>>>;
/**
* Per-agent expanded state of the agent sidebar's top-level sections
* (Tasks / Topic), keyed by agentId. Lets each agent remember its own
diff --git a/src/store/global/selectors/systemStatus.ts b/src/store/global/selectors/systemStatus.ts
index 72b7ae22acd..51e40873427 100644
--- a/src/store/global/selectors/systemStatus.ts
+++ b/src/store/global/selectors/systemStatus.ts
@@ -2,6 +2,8 @@ import { type TopicGroupMode } from '@/types/topic';
import type {
AgentDocumentSort,
+ DocsPageSectionKey,
+ DocsPageSectionView,
GlobalState,
ModelDetailPanelExpandedKey,
ProjectListSortBy,
@@ -10,6 +12,7 @@ import type {
WorkspaceOverridableField,
} from '../initialState';
import {
+ DEFAULT_DOCS_PAGE_SECTION_VIEW,
DEFAULT_HOME_SIDEBAR_EXPANDED_KEYS,
INITIAL_STATUS,
MODEL_DETAIL_PANEL_EXPANDABLE_KEYS,
@@ -93,6 +96,15 @@ const collapsedTopicGroupKeys =
(s: GlobalState): string[] | undefined =>
s.status.collapsedTopicGroupKeysByMode?.[mode];
+const docsPageSectionView =
+ (section: DocsPageSectionKey) =>
+ (s: GlobalState): DocsPageSectionView => {
+ const stored = s.status.docsPageSectionViews?.[section];
+ return stored
+ ? { ...DEFAULT_DOCS_PAGE_SECTION_VIEW, ...stored }
+ : DEFAULT_DOCS_PAGE_SECTION_VIEW;
+ };
+
const projectTopicSubGroupMode =
(groupId: string) =>
(s: GlobalState): ProjectTopicSubGroupMode =>
@@ -509,6 +521,7 @@ export const systemStatusSelectors = {
disabledModelProvidersSortType,
disabledModelsSortType,
expandInputActionbar,
+ docsPageSectionView,
filePanelWidth,
getAgentSystemRoleExpanded,
groupAgentBuilderPanelWidth,
diff --git a/src/store/page/action.list.test.ts b/src/store/page/action.list.test.ts
index b6e6a3112f1..01e8c260411 100644
--- a/src/store/page/action.list.test.ts
+++ b/src/store/page/action.list.test.ts
@@ -67,7 +67,7 @@ const lobeDoc = (id: string, overrides: Partial<LobeDocument> = {}): LobeDocumen
});
/** The replica sync queries the slice registered with the SWR driver. */
-const syncCalls = async (name: 'pageDetail' | 'pageList' | 'pageSection') => {
+const syncCalls = async (name: 'pageDetail' | 'pageList' | 'pageSection' | 'pageSectionList') => {
const { useClientDataSWR } = await import('@/libs/swr');
return vi
.mocked(useClientDataSWR)
@@ -142,7 +142,14 @@ describe('pageActions — useFetchDocuments', () => {
describe('pageActions — useFetchPageSection', () => {
it('lists authored pages only, never parsed uploads', async () => {
- renderHook(() => pageActions.useFetchPageSection('mine', 20));
+ renderHook(() =>
+ pageActions.useFetchPageSection({
+ limit: 20,
+ scope: 'mine',
+ sortBy: 'updatedAt',
+ type: 'all',
+ }),
+ );
const [call] = await syncCalls('pageSection');
vi.mocked(documentService.queryDocuments).mockResolvedValue({
@@ -164,12 +171,61 @@ describe('pageActions — useFetchPageSection', () => {
const docs = (await call.fetcher()) as LobeDocument[];
expect(documentService.queryDocuments).toHaveBeenCalledWith(
- expect.objectContaining({ creator: 'self', sourceTypes: [DocumentSourceType.API] }),
+ expect.objectContaining({
+ creator: 'self',
+ sortBy: 'updatedAt',
+ sourceTypes: [DocumentSourceType.API],
+ }),
);
expect(docs.map((doc) => doc.id)).toEqual(['docs_page', 'docs_library_page']);
});
});
+describe('pageActions — section view options', () => {
+ it('asks the server for artifacts only, in the section sort', async () => {
+ renderHook(() =>
+ pageActions.useFetchPageSection({
+ limit: 10,
+ scope: 'mine',
+ sortBy: 'title',
+ type: 'artifact',
+ }),
+ );
+ const [call] = await syncCalls('pageSection');
+ vi.mocked(documentService.queryDocuments).mockResolvedValue({ items: [], total: 0 });
+
+ await call.fetcher();
+
+ expect(documentService.queryDocuments).toHaveBeenCalledWith(
+ expect.objectContaining({ fileTypes: ['custom/html'], pageSize: 11, sortBy: 'title' }),
+ );
+ });
+
+ it('pages the full list of a section with the same filters', async () => {
+ renderHook(() =>
+ pageActions.useFetchPageSectionList({ scope: 'shared', sortBy: 'createdAt', type: 'page' }),
+ );
+ const [call] = await syncCalls('pageSectionList');
+ vi.mocked(documentService.queryDocuments).mockResolvedValue({
+ items: [row('docs_a')],
+ total: 1,
+ });
+
+ const page = (await call.fetcher()) as { items: LobeDocument[] };
+
+ expect(documentService.queryDocuments).toHaveBeenCalledWith(
+ expect.objectContaining({
+ creator: 'others',
+ current: 0,
+ fileTypes: ['custom/document'],
+ sortBy: 'createdAt',
+ standaloneOnly: true,
+ }),
+ );
+ expect(page.items.map((item) => item.id)).toEqual(['docs_a']);
+ });
+});
+
describe('pageActions — preHydrate', () => {
it('seeds the list from the persisted row before anything mounts', async () => {
const { pageListResource } = await import('./projection');
diff --git a/src/store/page/action.ts b/src/store/page/action.ts
index 618a96ec299..118bc816df5 100644
--- a/src/store/page/action.ts
+++ b/src/store/page/action.ts
@@ -15,6 +15,8 @@ import { currentPageSize, PagePrivateAction } from './privateAction';
import {
documentItemToLobeDocument,
PAGE_LIST_KEY,
+ type PageSectionListParams,
+ type PageSectionParams,
type PageSectionScope,
TEMP_PAGE_ID_PREFIX,
} from './projection';
@@ -69,8 +71,16 @@ export class PageActionImpl {
};
/** The Docs sidebar's My docs / Shared sections; rows via `pageSelectors.pageSection`. */
- useFetchPageSection = (scope: PageSectionScope, limit: number): ReplicaSyncResult =>
- this.#private.section.useSync({ limit, scope });
+ useFetchPageSection = (params: PageSectionParams): ReplicaSyncResult =>
+ this.#private.section.useSync(params);
+
+ /** A section's full list, paged; rows via `pageSelectors.pageSectionList`. */
+ useFetchPageSectionList = (params: PageSectionListParams | null): ReplicaSyncResult =>
+ this.#private.sectionList.useSync(params);
+
+ loadMorePageSectionList = async (params: PageSectionListParams): Promise<void> => {
+ await this.#private.sectionList.loadMore(params.scope, params);
+ };
useFetchPageDetail = (pageId?: string | null): ReplicaSyncResult =>
this.#private.detail.useSync(pageId || null);
@@ -121,6 +131,18 @@ export class PageActionImpl {
this.#set({ allPagesDrawerOpen: false }, false, n('closeAllPagesDrawer'));
};
+ openSectionFullList = (scope: PageSectionScope): void => {
+ this.#set(
+ { sectionFullListOpen: true, sectionFullListScope: scope },
+ false,
+ n('openSectionFullList'),
+ );
+ };
+
+ closeSectionFullList = (): void => {
+ this.#set({ sectionFullListOpen: false }, false, n('closeSectionFullList'));
+ };
+
openAllPagesDrawer = (): void => {
this.#set({ allPagesDrawerOpen: true }, false, n('openAllPagesDrawer'));
};
diff --git a/src/store/page/initialState.ts b/src/store/page/initialState.ts
index 7c45e123f15..326e84efd43 100644
--- a/src/store/page/initialState.ts
+++ b/src/store/page/initialState.ts
@@ -1,5 +1,6 @@
import { type NavigateFunction } from 'react-router';
+import type { PageSectionScope } from './projection';
import { initialPageCrudState, type PageCrudSliceState } from './slices/crud/initialState';
import { initialPageListState, type PageListSliceState } from './slices/list/initialState';
import {
@@ -15,6 +16,10 @@ export interface PageUiState {
navigate?: NavigateFunction;
/** Search keywords for filtering pages in the sidebar. */
searchKeywords: string;
+ /** Whether a Docs sidebar section's full list is open beside the sidebar. */
+ sectionFullListOpen: boolean;
+ /** The section the full list shows; kept on close so the panel animates out intact. */
+ sectionFullListScope: PageSectionScope;
/** Filter to show only pages not in any library. */
showOnlyPagesNotInLibrary: boolean;
}
@@ -34,5 +39,7 @@ export const initialState: PageState = {
...initialPageCrudState,
...initialPageSelectionState,
searchKeywords: '',
+ sectionFullListOpen: false,
+ sectionFullListScope: 'mine',
showOnlyPagesNotInLibrary: false,
};
diff --git a/src/store/page/privateAction.ts b/src/store/page/privateAction.ts
index 3029faceb92..9bf8cd27111 100644
--- a/src/store/page/privateAction.ts
+++ b/src/store/page/privateAction.ts
@@ -19,6 +19,8 @@ import {
pageDetailResource,
pageListResource,
type PageListValue,
+ pageSectionListResource,
+ type PageSectionListValue,
pageSectionResource,
type PageSectionScope,
} from './projection';
@@ -36,6 +38,7 @@ export class PagePrivateAction {
readonly entity;
readonly list;
readonly section;
+ readonly sectionList;
constructor(set: Setter, get: () => PageState) {
this.#get = get;
@@ -72,8 +75,20 @@ export class PagePrivateAction {
stateKey: 'pageSectionReplica',
view: recordLens<PageState, LobeDocument[]>('pageSectionMap'),
});
+ this.sectionList = createReplicaSlice(pageSectionListResource, {
+ actionPrefix: 'pageSectionList',
+ get,
+ set,
+ stateKey: 'pageSectionListReplica',
+ view: recordLens<PageState, PageSectionListValue>('pageSectionListMap'),
+ });
// A rename or delete in the editor reaches the sidebar sections' rows too.
- this.entity = linkReplicaEntity<LobeDocument>([this.list, this.detail, this.section]);
+ this.entity = linkReplicaEntity<LobeDocument>([
+ this.list,
+ this.detail,
+ this.section,
+ this.sectionList,
+ ]);
}
insertListRow = (doc: LobeDocument): void => {
@@ -107,9 +122,10 @@ export class PagePrivateAction {
revalidateList = (): Promise<unknown> =>
Promise.all([
this.list.revalidate(PAGE_LIST_KEY),
- ...(['mine', 'shared'] satisfies PageSectionScope[]).map((scope) =>
+ ...(['mine', 'shared'] satisfies PageSectionScope[]).flatMap((scope) => [
this.section.revalidate(scope),
- ),
+ this.sectionList.revalidate(scope),
+ ]),
]);
preHydrateList = (): Promise<boolean> => {
diff --git a/src/store/page/projection.ts b/src/store/page/projection.ts
index e10dc2665ef..e19ec0ff141 100644
--- a/src/store/page/projection.ts
+++ b/src/store/page/projection.ts
@@ -1,8 +1,14 @@
-import { PAGE_DOCUMENT_FILE_TYPES, PAGE_DOCUMENT_SOURCE_TYPES } from '@lobechat/const';
+import {
+ CUSTOM_DOCUMENT_FILE_TYPE,
+ HTML_DOCUMENT_FILE_TYPE,
+ PAGE_DOCUMENT_FILE_TYPES,
+ PAGE_DOCUMENT_SOURCE_TYPES,
+} from '@lobechat/const';
import type { DocumentItem } from '@lobechat/database/schemas';
import { definePagedReplica, defineReplica, type ReplicaPagedData } from '@/libs/replica';
import { documentService } from '@/services/document';
+import type { DocsPageSectionKey, DocsPageSectionView } from '@/store/global/initialState';
import { DocumentSourceType, type LobeDocument } from '@/types/document';
/**
@@ -142,9 +148,15 @@ export const pageDetailResource = defineReplica<string, LobeDocument, LobeDocume
* (private ones never reach another member). Both narrow inside the query, so a
* section shows a full head page instead of whatever survives a client filter.
*/
-export type PageSectionScope = 'mine' | 'shared';
+export type PageSectionScope = DocsPageSectionKey;
-export interface PageSectionParams {
+/** What a section lists and in which order; the section's view settings decide it. */
+export interface PageSectionFilter {
+ sortBy: DocsPageSectionView['sortBy'];
+ type: DocsPageSectionView['type'];
+}
+
+export interface PageSectionParams extends PageSectionFilter {
/** Rows shown; one more is fetched so the section knows whether to offer "View all". */
limit: number;
scope: PageSectionScope;
@@ -158,25 +170,73 @@ export interface PageSectionParams {
*/
const PAGE_SECTION_SOURCE_TYPES: string[] = [DocumentSourceType.API];
-export const pageSectionResource = defineReplica<PageSectionParams, LobeDocument[]>({
- fetcher: async ({ limit, scope }) => {
- const result = await documentService.queryDocuments({
- creator: scope === 'mine' ? 'self' : 'others',
- current: 0,
- fileTypes: PAGE_DOCUMENT_FILE_TYPES,
- pageSize: limit + 1,
- sourceTypes: PAGE_SECTION_SOURCE_TYPES,
- standaloneOnly: true,
- });
-
- return result.items
+const SECTION_FILE_TYPES: Record<PageSectionFilter['type'], string[]> = {
+ all: PAGE_DOCUMENT_FILE_TYPES,
+ artifact: [HTML_DOCUMENT_FILE_TYPE],
+ page: [CUSTOM_DOCUMENT_FILE_TYPE],
+};
+
+/** One offset page of a section's rows, narrowed by scope and type on the server. */
+const fetchSectionPage = async (
+ { scope, sortBy, type }: PageSectionFilter & { scope: PageSectionScope },
+ current: number,
+ pageSize: number,
+): Promise<{ items: LobeDocument[]; total: number }> => {
+ const result = await documentService.queryDocuments({
+ creator: scope === 'mine' ? 'self' : 'others',
+ current,
+ fileTypes: SECTION_FILE_TYPES[type],
+ pageSize,
+ sortBy,
+ sourceTypes: PAGE_SECTION_SOURCE_TYPES,
+ standaloneOnly: true,
+ });
+
+ return {
+ items: result.items
.filter((doc) => PAGE_SECTION_SOURCE_TYPES.includes(doc.sourceType))
.filter(isAllowedPageDocument)
- .map(documentItemToLobeDocument);
- },
+ .map(documentItemToLobeDocument),
+ total: result.total,
+ };
+};
+
+export const pageSectionResource = defineReplica<PageSectionParams, LobeDocument[]>({
+ fetcher: async ({ limit, ...params }) => (await fetchSectionPage(params, 0, limit + 1)).items,
key: ({ scope }) => scope,
name: 'pageSection',
+ // The cached head only paints for the list options it was fetched under.
+ query: ({ limit, sortBy, type }) => ({ limit, sortBy, type }),
storage: 'localStorage',
- // v2 drops section caches that still hold parsed uploads.
- version: 2,
+ // v3 keys the cache by the section's list options.
+ version: 3,
+});
+
+/** Rows per page of a section's full list. */
+export const PAGE_SECTION_LIST_PAGE_SIZE = 30;
+
+export interface PageSectionListParams extends PageSectionFilter {
+ scope: PageSectionScope;
+}
+
+export type PageSectionListValue = ReplicaPagedData<LobeDocument, number>;
+
+/**
+ * Every page of one section, paged forward for the full-list panel. The
+ * sidebar section only carries its capped head; this is how an older page is
+ * still reachable.
+ */
+export const pageSectionListResource = definePagedReplica<
+ PageSectionListParams,
+ LobeDocument,
+ number,
+ PageSectionListValue
+>({
+ fetchPage: (params, cursor) => fetchSectionPage(params, cursor ?? 0, PAGE_SECTION_LIST_PAGE_SIZE),
+ key: ({ scope }) => scope,
+ name: 'pageSectionList',
+ paging: pagePaging,
+ query: ({ sortBy, type }) => ({ sortBy, type }),
+ storage: 'indexedDB',
+ version: 1,
});
diff --git a/src/store/page/selectors.ts b/src/store/page/selectors.ts
index d19573f9185..776974f1904 100644
--- a/src/store/page/selectors.ts
+++ b/src/store/page/selectors.ts
@@ -5,7 +5,11 @@ import { listSelectors } from './slices/list';
/** One Docs sidebar page section (`mine` / `shared`); `undefined` until first read. */
const pageSection = (scope: PageSectionScope) => (s: PageState) => s.pageSectionMap[scope];
+/** A section's full paged list (the full-list panel); `undefined` until first read. */
+const pageSectionList = (scope: PageSectionScope) => (s: PageState) => s.pageSectionListMap[scope];
+
export const pageSelectors = {
...listSelectors,
pageSection,
+ pageSectionList,
};
diff --git a/src/store/page/slices/list/initialState.ts b/src/store/page/slices/list/initialState.ts
index 8929ec991a0..3058969543b 100644
--- a/src/store/page/slices/list/initialState.ts
+++ b/src/store/page/slices/list/initialState.ts
@@ -1,7 +1,7 @@
import { createReplicaState, type ReplicaState } from '@/libs/replica';
import type { LobeDocument } from '@/types/document';
-import type { PageListValue } from '../../projection';
+import type { PageListValue, PageSectionListValue } from '../../projection';
export interface PageListSliceState {
/**
@@ -19,6 +19,10 @@ export interface PageListSliceState {
pageListMap: Record<string, PageListValue>;
/** Local-first bookkeeping for `pageListMap`. */
pageListReplica: ReplicaState<PageListValue>;
+ /** Every page of a section, paged for the full-list panel (`pageSectionListMap[mine|shared]`). */
+ pageSectionListMap: Record<string, PageSectionListValue>;
+ /** Local-first bookkeeping for `pageSectionListMap`. */
+ pageSectionListReplica: ReplicaState<PageSectionListValue>;
/** The Docs sidebar's page sections (`pageSectionMap[mine|shared]`). */
pageSectionMap: Record<string, LobeDocument[]>;
/** Local-first bookkeeping for `pageSectionMap`. */
@@ -30,6 +34,8 @@ export const initialPageListState: PageListSliceState = {
pageDetailReplica: createReplicaState(),
pageListMap: {},
pageListReplica: createReplicaState(),
+ pageSectionListMap: {},
+ pageSectionListReplica: createReplicaState(),
pageSectionMap: {},
pageSectionReplica: createReplicaState(),
};
diff --git a/src/store/page/slices/list/selectors.ts b/src/store/page/slices/list/selectors.ts
index 5667fc5e408..40e71a59086 100644
--- a/src/store/page/slices/list/selectors.ts
+++ b/src/store/page/slices/list/selectors.ts
@@ -63,7 +63,7 @@ const getFilteredDocumentsLimited = (s: PageState): LobeDocument[] =>
/**
* One page as the loaded list holds it, falling back to the by-id projection
* for pages outside it (mobile mounts no sidebar; a deep link may land before
- * the list fetches), and finally to a Docs sidebar section.
+ * the list fetches), and finally to a Docs sidebar section or its full list.
*
* The sections load their own rows (`pageSectionMap`), so on a fresh Docs load
* a page can be on screen while the flat list has not fetched it yet. Rename,
@@ -82,9 +82,15 @@ const getDocumentById = (docId: string | undefined) => (s: PageState) => {
const detailRow = s.pageDetailMap[docId];
if (detailRow) return detailRow;
- return Object.values(s.pageSectionMap)
+ const sectionRow = Object.values(s.pageSectionMap)
.flat()
.find((doc) => doc.id === docId);
+ if (sectionRow) return sectionRow;
+
+ // The full-list panel pages older rows that no section head holds.
+ return Object.values(s.pageSectionListMap)
+ .flatMap((list) => list.items)
+ .find((doc) => doc.id === docId);
};
const hasMoreDocuments = (s: PageState): boolean => Boolean(pageList(s)?.hasMore);