🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(page): share workspace documents by default and mark private ones with a lock (#21228)
Arvin Xu6404edcf34e4
diff --git a/apps/server/src/services/document/__tests__/createDocument.visibility.test.ts b/apps/server/src/services/document/__tests__/createDocument.visibility.test.tsnew file mode 100644index 00000000000..fb792d3a874--- /dev/null+++ b/apps/server/src/services/document/__tests__/createDocument.visibility.test.ts@@ -0,0 +1,51 @@+import { type LobeChatDatabase } from '@lobechat/database';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { DocumentModel } from '@/database/models/document';+import { FileModel } from '@/database/models/file';+import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';++import { DocumentService } from '../index';++vi.mock('@/server/modules/AgentRuntime/redis', () => ({ getAgentRuntimeRedisClient: () => null }));+vi.mock('@/database/models/document');+vi.mock('@/database/models/file');+vi.mock('@/database/models/knowledgeBase');+vi.mock('../../file');+vi.mock('../history');++describe('DocumentService.createDocument — workspace visibility default', () => {+ const documentModel = { create: vi.fn().mockResolvedValue({ id: 'doc-1' }) };++ beforeEach(() => {+ vi.mocked(DocumentModel).mockImplementation(function () {+ return documentModel as any;+ });+ vi.mocked(FileModel).mockImplementation(function () {+ return {} as any;+ });+ vi.mocked(KnowledgeBaseModel).mockImplementation(function () {+ return {} as any;+ });+ });++ it('leaves a standalone workspace page to the public schema default', async () => {+ // An agent writing through `lh doc create` passes no visibility; the page+ // must land in the workspace, not in the caller's private space.+ const service = new DocumentService({} as LobeChatDatabase, 'user-1', 'ws-1');+ await service.createDocument({ editorData: {}, title: 'Agent Report' });++ expect(documentModel.create).toHaveBeenCalledWith(+ expect.not.objectContaining({ visibility: 'private' }),+ );+ });++ it('keeps an explicit private visibility', async () => {+ const service = new DocumentService({} as LobeChatDatabase, 'user-1', 'ws-1');+ await service.createDocument({ editorData: {}, title: 'Draft', visibility: 'private' });++ expect(documentModel.create).toHaveBeenCalledWith(+ expect.objectContaining({ visibility: 'private' }),+ );+ });+});diff --git a/apps/server/src/services/document/index.ts b/apps/server/src/services/document/index.tsindex bdd9c3b32f4..91ee5bf7db3 100644--- a/apps/server/src/services/document/index.ts+++ b/apps/server/src/services/document/index.ts@@ -231,9 +231,11 @@ export class DocumentService {// Resolve visibility upfront so the KB mirror file uses the same policy// as the document. A library-root document inherits the KB visibility;// parent documents remain navigation-only and do not pass visibility or- // ACL to children. Personal mode leaves it undefined — the ownership- // filter ignores the column there — but still checks the library exists,- // so a wrong id fails as NOT_FOUND instead of a foreign-key violation.+ // ACL to children. Without a library or an explicit value it stays+ // undefined, so the row takes the schema default (`'public'` — workspace+ // documents are shared unless asked otherwise). Personal mode ignores the+ // column but still checks the library exists, so a wrong id fails as+ // NOT_FOUND instead of a foreign-key violation.let resolvedVisibility: 'private' | 'public' | undefined = visibility;if (knowledgeBaseId) {const knowledgeBase = await this.knowledgeBaseModel.findById(@@ -248,7 +250,6 @@ export class DocumentService {}if (this.workspaceId) resolvedVisibility = knowledgeBase.visibility;}- if (!resolvedVisibility && this.workspaceId) resolvedVisibility = 'private';let fileId: string | null = null;diff --git a/locales/en-US/file.json b/locales/en-US/file.jsonindex a272cd42b92..90e5fc892fe 100644--- a/locales/en-US/file.json+++ b/locales/en-US/file.json@@ -325,7 +325,7 @@"pageList.noResults": "No matching pages found","pageList.pageCount": "{{count}} pages in total","pageList.pageSizeItem": "{{count}} items",- "pageList.privateTitle": "Private",+ "pageList.privateTooltip": "Only visible to you","pageList.publishConfirm.ok": "Publish","pageList.publishConfirm.title": "Publish to workspace","pageList.publishError": "Failed to publish page",@@ -340,7 +340,6 @@"pageList.transferTo": "Move to…","pageList.transferWarning": "This is a one-way move; reverting requires another move.","pageList.untitled": "Untitled",- "pageList.workspaceTitle": "Workspace","portal.openInPageEditor": "Edit in Page","preview.downloadFile": "Download File","preview.raw": "Raw",diff --git a/locales/zh-CN/file.json b/locales/zh-CN/file.jsonindex 5c97a393ebf..9c81b655b11 100644--- a/locales/zh-CN/file.json+++ b/locales/zh-CN/file.json@@ -325,7 +325,7 @@"pageList.noResults": "未找到匹配的文稿","pageList.pageCount": "共 {{count}} 个文稿","pageList.pageSizeItem": "{{count}} 个条目",- "pageList.privateTitle": "私人",+ "pageList.privateTooltip": "仅自己可见","pageList.publishConfirm.ok": "发布","pageList.publishConfirm.title": "发布到工作区","pageList.publishError": "发布失败,请稍后再试",@@ -340,7 +340,6 @@"pageList.transferTo": "移动到…","pageList.transferWarning": "这是单向移动;恢复需要另一次移动。","pageList.untitled": "无标题",- "pageList.workspaceTitle": "工作区","portal.openInPageEditor": "在文稿中编辑","preview.downloadFile": "下载文件","preview.raw": "原文",diff --git a/packages/database/src/models/__tests__/document.privateVisibility.workspace.test.ts b/packages/database/src/models/__tests__/document.privateVisibility.workspace.test.tsindex 5247b33f70d..90b76780e14 100644--- a/packages/database/src/models/__tests__/document.privateVisibility.workspace.test.ts+++ b/packages/database/src/models/__tests__/document.privateVisibility.workspace.test.ts@@ -211,7 +211,7 @@ describe('DocumentModel — private/public cross-user isolation', () => {});describe('DocumentModel.create — workspace visibility defaults', () => {- it("defaults a top-level workspace document to 'private'", async () => {+ it("defaults a top-level workspace document to 'public'", async () => {const callerA = new DocumentModel(serverDB, userA, workspaceId);const created = await callerA.create({fileType: 'text/plain',@@ -221,7 +221,7 @@ describe('DocumentModel.create — workspace visibility defaults', () => {totalCharCount: 0,totalLineCount: 0,});- expect(created.visibility).toBe('private');+ expect(created.visibility).toBe('public');});it('does not inherit visibility from a parent document', async () => {@@ -233,8 +233,8 @@ describe('DocumentModel.create — workspace visibility defaults', () => {title: 'private-root',totalCharCount: 0,totalLineCount: 0,+ visibility: 'private',});- await callerA.setVisibility(root.id, 'public');const child = await callerA.create({fileType: 'text/plain',@@ -245,21 +245,21 @@ describe('DocumentModel.create — workspace visibility defaults', () => {totalCharCount: 0,totalLineCount: 0,});- expect(child.visibility).toBe('private');+ expect(child.visibility).toBe('public');});- it('honors an explicit visibility override at the top level', async () => {+ it('honors an explicit private visibility at the top level', async () => {const callerA = new DocumentModel(serverDB, userA, workspaceId);const created = await callerA.create({fileType: 'text/plain',source: 'inline',sourceType: 'api',- title: 'explicit-public',+ title: 'explicit-private',totalCharCount: 0,totalLineCount: 0,- visibility: 'public',+ visibility: 'private',});- expect(created.visibility).toBe('public');+ expect(created.visibility).toBe('private');});});@@ -273,6 +273,7 @@ describe('DocumentModel.publishToWorkspace', () => {title: 'pub-root',totalCharCount: 0,totalLineCount: 0,+ visibility: 'private',});const child = await callerA.create({fileType: 'text/plain',@@ -282,6 +283,7 @@ describe('DocumentModel.publishToWorkspace', () => {title: 'pub-child',totalCharCount: 0,totalLineCount: 0,+ visibility: 'private',});const grandchild = await callerA.create({fileType: 'text/plain',@@ -291,6 +293,7 @@ describe('DocumentModel.publishToWorkspace', () => {title: 'pub-grandchild',totalCharCount: 0,totalLineCount: 0,+ visibility: 'private',});expect(root.visibility).toBe('private');expect(child.visibility).toBe('private');@@ -312,6 +315,7 @@ describe('DocumentModel.publishToWorkspace', () => {title: 'owner-root',totalCharCount: 0,totalLineCount: 0,+ visibility: 'private',});const callerB = new DocumentModel(serverDB, userB, workspaceId);@@ -332,6 +336,7 @@ describe('DocumentModel.publishToWorkspace', () => {title: 'mixed-root',totalCharCount: 0,totalLineCount: 0,+ visibility: 'private',});await callerA.publishToWorkspace(root.id);@@ -354,6 +359,7 @@ describe('DocumentModel.setVisibility', () => {title: 'unpub-root',totalCharCount: 0,totalLineCount: 0,+ visibility: 'private',});const child = await callerA.create({fileType: 'text/plain',@@ -363,6 +369,7 @@ describe('DocumentModel.setVisibility', () => {title: 'unpub-child',totalCharCount: 0,totalLineCount: 0,+ visibility: 'private',});await callerA.publishToWorkspace(root.id);await callerA.publishToWorkspace(child.id);@@ -403,6 +410,7 @@ describe('DocumentModel.setVisibility', () => {title: 'idem-root',totalCharCount: 0,totalLineCount: 0,+ visibility: 'private',});await callerA.setVisibility(root.id, 'public');@@ -426,6 +434,7 @@ describe('DocumentModel.setVisibility', () => {title: 'ws-scoped-root',totalCharCount: 0,totalLineCount: 0,+ visibility: 'private',});// Same user, but personal scope (workspace_id IS NULL) — ownership() must@@ -449,6 +458,7 @@ describe('DocumentModel.update — independent parent visibility', () => {title: 'private-root-to-move',totalCharCount: 0,totalLineCount: 0,+ visibility: 'private',});const publicRoot = await callerA.create({fileType: 'custom/folder',@@ -475,6 +485,7 @@ describe('DocumentModel.update — independent parent visibility', () => {title: 'private-root-target',totalCharCount: 0,totalLineCount: 0,+ visibility: 'private',});const publicRoot = await callerA.create({fileType: 'custom/folder',@@ -501,6 +512,7 @@ describe('DocumentModel.update — independent parent visibility', () => {title: 'old-private-parent',totalCharCount: 0,totalLineCount: 0,+ visibility: 'private',});const newParent = await callerA.create({fileType: 'custom/folder',@@ -509,6 +521,7 @@ describe('DocumentModel.update — independent parent visibility', () => {title: 'new-private-parent',totalCharCount: 0,totalLineCount: 0,+ visibility: 'private',});const child = await callerA.create({fileType: 'text/plain',@@ -518,6 +531,7 @@ describe('DocumentModel.update — independent parent visibility', () => {title: 'moving-child',totalCharCount: 0,totalLineCount: 0,+ visibility: 'private',});await expect(callerA.update(child.id, { parentId: newParent.id })).resolves.toBeDefined();@@ -534,6 +548,7 @@ describe('DocumentModel.update — independent parent visibility', () => {title: 'visibility-strip',totalCharCount: 0,totalLineCount: 0,+ visibility: 'private',});expect(doc.visibility).toBe('private');diff --git a/packages/database/src/models/document.ts b/packages/database/src/models/document.tsindex 50534186189..3759aafe09e 100644--- a/packages/database/src/models/document.ts+++ b/packages/database/src/models/document.ts@@ -149,21 +149,10 @@ export class DocumentModel {};create = async (params: Omit<NewDocument, 'userId'>): Promise<DocumentItem> => {- // Workspace-mode default for visibility:- // - explicit visibility wins- // - user-authored Pages (`sourceType: 'api'`) default to- // `'private'` so workspace members start drafts in their own space and- // publish when ready- // - all other top-level rows (web crawls, file ingests, topic snapshots,- // agent-signal artifacts, …): leave the schema default (`'public'`) so- // existing behavior is preserved — these don't have a Pages-style- // draft / publish lifecycle and were workspace-shared from day one- // Personal mode leaves it to the schema default; the filter ignores it.- let visibility = params.visibility;- if (!visibility && this.workspaceId && params.sourceType === 'api') {- visibility = 'private';- }-+ // Workspace documents default to the schema's `'public'`: a workspace is a+ // collaborative space, so whatever a member (or an agent acting for them)+ // writes there is shared unless the caller explicitly asks for `'private'`.+ // Personal mode ignores the column.const result = (await this.db.insert(documents).values(@@ -172,7 +161,6 @@ export class DocumentModel {{...params,metadata: this.scopeMetadata(params.metadata),- ...(visibility ? { visibility } : {}),},),)diff --git a/packages/database/src/schemas/resourcePermission.ts b/packages/database/src/schemas/resourcePermission.tsindex 529cdc6aa38..a28eb5959a9 100644--- a/packages/database/src/schemas/resourcePermission.ts+++ b/packages/database/src/schemas/resourcePermission.ts@@ -53,12 +53,10 @@ export const RESOURCE_ACCESS_LEVELS_BY_TYPE = {* reads as a bug, not as a policy.** Documents default to `edit` for the same reason. Privacy for a written page- * is already carried by a separate channel: a page authored from the sidebar- * starts at `visibility: 'private'` (`DocumentModel.create`), so publishing one- * into the workspace is the creator *choosing* to collaborate, and grading that- * published page down to read-only by default contradicts the act that put it- * there. Documents that never had that draft phase (file ingests, crawls, topic- * snapshots) are workspace-shared material from the moment they exist.+ * is carried by a separate channel — its own `visibility` column, which a+ * creator sets to `'private'` explicitly — so a page left in the workspace is+ * material the creator chose to share, and grading it down to read-only by+ * default would contradict that.** Lowering a resource is one control away (the Permission page), and the* creator / workspace owners are unaffected either way.diff --git a/packages/locales/src/default/file.ts b/packages/locales/src/default/file.tsindex 77928f2d3be..4f0b481b80c 100644--- a/packages/locales/src/default/file.ts+++ b/packages/locales/src/default/file.ts@@ -361,14 +361,13 @@ export default {'pageList.noResults': 'No matching pages found','pageList.pageCount': '{{count}} pages in total','pageList.pageSizeItem': '{{count}} items',- 'pageList.privateTitle': 'Private',+ 'pageList.privateTooltip': 'Only visible to you','pageList.publishConfirm.ok': 'Publish','pageList.publishConfirm.title': 'Publish to workspace','pageList.publishError': 'Failed to publish page','pageList.publishSuccess': 'Page published to workspace','pageList.publishToWorkspace': 'Publish to workspace','pageList.title': 'Pages',- 'pageList.workspaceTitle': 'Workspace','pageList.transferConfirm': 'Move','pageList.transferDescription':'You can move to personal or workspaces that have permission to create a page.',diff --git a/src/features/HomeSidebar/hooks/useCreateMenuItems.tsx b/src/features/HomeSidebar/hooks/useCreateMenuItems.tsxindex b8d8e8354e6..129c2404f76 100644--- a/src/features/HomeSidebar/hooks/useCreateMenuItems.tsx+++ b/src/features/HomeSidebar/hooks/useCreateMenuItems.tsx@@ -15,7 +15,6 @@ import { useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';import useSWRMutation from 'swr/mutation';-import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { useGroupTemplates } from '@/components/ChatGroupWizard/templates';import { DEFAULT_CHAT_GROUP_CHAT_CONFIG } from '@/const/settings';import { openConnectAgentModal } from '@/features/ConnectAgent';@@ -53,7 +52,6 @@ export const useCreateMenuItems = () => {const { t: tFile } = useTranslation('file');const navigate = useWorkspaceAwareNavigate();- const activeWorkspaceId = useActiveWorkspaceId();const groupTemplates = useGroupTemplates();const { allowed: canCreate } = usePermission('create_content');@@ -413,17 +411,13 @@ export const useCreateMenuItems = () => {const untitledTitle = tFile('pageList.untitled');try {- // In workspace mode the server auto-defaults top-level `sourceType: 'api'`- // rows to `'private'`; pass it explicitly so the optimistic row lands in- // 私人 too, instead of flashing in 工作区 and jumping when the server replies.- const defaultVisibility = activeWorkspaceId ? 'private' : undefined;- const newPageId = await pageActions.createNewPage(untitledTitle, defaultVisibility);+ const newPageId = await pageActions.createNewPage(untitledTitle);navigate(`/page/${newPageId}`);} catch (error) {console.error('Failed to create page:', error);toast.error(tFile('pageList.createFailed'));}- }, [canCreate, tFile, navigate, activeWorkspaceId]);+ }, [canCreate, tFile, navigate]);/*** Create page menu itemdiff --git a/src/features/Pages/PageLayout/Body/List/Item/index.test.tsx b/src/features/Pages/PageLayout/Body/List/Item/index.test.tsxnew file mode 100644index 00000000000..f432f78327a--- /dev/null+++ b/src/features/Pages/PageLayout/Body/List/Item/index.test.tsx@@ -0,0 +1,78 @@+/**+ * @vitest-environment happy-dom+ */+import { render, screen } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import PageListItem from './index';++const state = vi.hoisted(() => ({+ activeWorkspaceId: undefined as string | undefined,+ visibility: undefined as 'private' | 'public' | null | undefined,+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ useActiveWorkspaceId: () => state.activeWorkspaceId,+}));++vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({+ useActiveWorkspaceSlug: () => undefined,+}));++vi.mock('@/const/version', () => ({ isDesktop: false }));++vi.mock('@/store/electron', () => ({+ useElectronStore: (selector: (s: { addTab: () => void }) => unknown) =>+ selector({ addTab: vi.fn() }),+}));++vi.mock('@/store/page', () => ({+ pageActions: { selectPage: vi.fn(), setRenamingPageId: vi.fn() },+ pageSelectors: {+ getDocumentById: () => () => ({+ id: 'doc-1',+ metadata: {},+ title: 'Weekly report',+ visibility: state.visibility,+ }),+ },+ usePageStore: (selector: (s: object) => unknown) =>+ selector({ renamingPageId: null, selectedPageId: null }),+}));++vi.mock('./Actions', () => ({ default: () => null }));+vi.mock('./Editing', () => ({ default: () => null }));+vi.mock('./useDropdownMenu', () => ({ useDropdownMenu: () => [] }));++describe('PageListItem visibility lock', () => {+ beforeEach(() => {+ state.activeWorkspaceId = 'ws-1';+ state.visibility = 'public';+ });++ it('marks a private workspace page with a lock', () => {+ state.visibility = 'private';+ render(<PageListItem pageId="doc-1" />);++ expect(screen.getByText('Weekly report')).toBeTruthy();+ expect(screen.getByLabelText('pageList.privateTooltip')).toBeTruthy();+ });++ it('shows no lock on a shared workspace page', () => {+ render(<PageListItem pageId="doc-1" />);++ expect(screen.queryByLabelText('pageList.privateTooltip')).toBeNull();+ });++ it('shows no lock outside a workspace', () => {+ state.activeWorkspaceId = undefined;+ state.visibility = 'private';+ render(<PageListItem pageId="doc-1" />);++ expect(screen.queryByLabelText('pageList.privateTooltip')).toBeNull();+ });+});diff --git a/src/features/Pages/PageLayout/Body/List/Item/index.tsx b/src/features/Pages/PageLayout/Body/List/Item/index.tsxindex 782fdde9724..8f8a5238bcb 100644--- a/src/features/Pages/PageLayout/Body/List/Item/index.tsx+++ b/src/features/Pages/PageLayout/Body/List/Item/index.tsx@@ -1,10 +1,11 @@import { HTML_DOCUMENT_FILE_TYPE } from '@lobechat/const';-import { Avatar, Icon } from '@lobehub/ui';-import { FileTextIcon, GlobeIcon } from 'lucide-react';+import { Avatar, createStaticStyles, cssVar, Icon, Tooltip } from '@lobehub/ui';+import { FileTextIcon, GlobeIcon, LockIcon } from 'lucide-react';import { type MouseEvent } from 'react';import { memo, useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';import { isDesktop } from '@/const/version';import NavItem from '@/features/NavPanel/components/NavItem';@@ -16,6 +17,29 @@ import Actions from './Actions';import Editing from './Editing';import { useDropdownMenu } from './useDropdownMenu';+// The lock sits right after the title instead of at the row's end: the end is+// where the hover actions overlay the row, which would hide the lock exactly+// when the pointer reaches it.+const styles = createStaticStyles(({ css }) => ({+ lock: css`+ flex: none;+ `,+ title: css`+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ titleRow: css`+ display: inline-flex;+ gap: 4px;+ align-items: center;++ max-width: 100%;++ vertical-align: middle;+ `,+}));+interface DocumentItemProps {className?: string;pageId: string;@@ -30,6 +54,9 @@ const PageListItem = memo<DocumentItemProps>(({ pageId, className }) => {const addTab = useElectronStore((s) => s.addTab);const activeWorkspaceSlug = useActiveWorkspaceSlug();+ // Visibility only means something inside a workspace; personal pages are+ // always the owner's alone, so they never carry the lock.+ const isPrivate = Boolean(useActiveWorkspaceId()) && document?.visibility === 'private';const active = selectedPageId === pageId;const title = document?.title || t('pageList.untitled');@@ -97,7 +124,24 @@ const PageListItem = memo<DocumentItemProps>(({ pageId, className }) => {href={`/page/${pageId}`}icon={icon}key={pageId}- title={title}+ title={+ isPrivate ? (+ <span className={styles.titleRow}>+ <span className={styles.title}>{title}</span>+ <Tooltip title={t('pageList.privateTooltip')}>+ <Icon+ aria-label={t('pageList.privateTooltip')}+ className={styles.lock}+ color={cssVar.colorTextDescription}+ icon={LockIcon}+ size={14}+ />+ </Tooltip>+ </span>+ ) : (+ title+ )+ }onClick={handleClick}onDoubleClick={handleDoubleClick}/>diff --git a/src/features/Pages/PageLayout/Body/List/index.tsx b/src/features/Pages/PageLayout/Body/List/index.tsxindex 20de04a4043..bc34072a2b3 100644--- a/src/features/Pages/PageLayout/Body/List/index.tsx+++ b/src/features/Pages/PageLayout/Body/List/index.tsx@@ -11,37 +11,17 @@ import { pageActions, pageSelectors, usePageStore } from '@/store/page';import Item from './Item';-interface PageListProps {- /**- * Bucket to render when the sidebar is in workspace mode. Omitting the prop- * renders the historical unified "All pages" list (personal mode).- */- visibility?: 'private' | 'workspace';-}--/**- * Sidebar page list. In workspace mode the same component drives each of the- * "Private" / "Workspace" accordions; personal mode collapses to a single- * unified list.- */-const PageList = memo<PageListProps>(({ visibility }) => {+const PageList = memo(() => {const { t } = useTranslation(['file', 'common']);- const [filteredDocuments, hasMore, isLoadingMore] = usePageStore((s) => {- let docs;- let more;- if (visibility === 'private') {- docs = pageSelectors.getPrivateFilteredDocumentsLimited(s);- more = pageSelectors.hasMorePrivateFilteredDocuments(s);- } else if (visibility === 'workspace') {- docs = pageSelectors.getWorkspaceFilteredDocumentsLimited(s);- more = pageSelectors.hasMoreWorkspaceFilteredDocuments(s);- } else {- docs = pageSelectors.getFilteredDocumentsLimited(s);- more = pageSelectors.hasMoreFilteredDocuments(s);- }- return [docs, more, pageSelectors.isLoadingMoreDocuments(s)] as const;- });+ const [filteredDocuments, hasMore, isLoadingMore] = usePageStore(+ (s) =>+ [+ pageSelectors.getFilteredDocumentsLimited(s),+ pageSelectors.hasMoreFilteredDocuments(s),+ pageSelectors.isLoadingMoreDocuments(s),+ ] as const,+ );return (<Flexbox gap={1}>diff --git a/src/features/Pages/PageLayout/Body/index.tsx b/src/features/Pages/PageLayout/Body/index.tsxindex 250f40f25b7..58852c20cbb 100644--- a/src/features/Pages/PageLayout/Body/index.tsx+++ b/src/features/Pages/PageLayout/Body/index.tsx@@ -7,27 +7,20 @@ import {AccordionRoot,accordionStyles,AccordionTrigger,- Block,- Center,ContextMenuTrigger,cx,Flexbox,- Icon,Spin,Text,} from '@lobehub/ui';-import { PlusIcon } from 'lucide-react';-import { memo, type ReactNode } from 'react';+import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import AsyncBoundary from '@/components/AsyncBoundary';import SkeletonList from '@/features/NavPanel/components/SkeletonList';import PageEmpty from '@/features/PageEmpty';-import { usePermission } from '@/hooks/usePermission';import { pageActions, pageSelectors, usePageStore } from '@/store/page';-import AddButton from '../Header/AddButton';import Actions from './Actions';import AllPagesDrawer from './AllPagesDrawer';import List from './List';@@ -35,17 +28,12 @@ import { useDropdownMenu } from './useDropdownMenu';export enum GroupKey {AllPages = 'all-pages',- PrivatePages = 'private-pages',- WorkspacePages = 'workspace-pages',}/**- * Page list sidebar.- *- * Workspace mode splits documents into two virtual roots — "Private" (only the- * creator sees them) and "Workspace" (shared with every member) — mirroring- * the Home sidebar's Private / Agent accordions. Personal mode collapses to- * the historical single accordion since `visibility` is meaningless there.+ * Page list sidebar: one list in both personal and workspace mode. Workspace+ * pages are shared by default; the ones their creator kept private carry a+ * lock on their row instead of living in a separate section.*/const Body = memo(() => {const { t } = useTranslation('file');@@ -61,167 +49,61 @@ const Body = memo(() => {const isPageListInit = usePageStore(pageSelectors.isPageListInit);const filteredDocumentsCount = usePageStore(pageSelectors.filteredDocumentsCount);- const privateCount = usePageStore(pageSelectors.privateFilteredDocumentsCount);- const workspaceCount = usePageStore(pageSelectors.workspaceFilteredDocumentsCount);const searchKeywords = usePageStore((s) => s.searchKeywords);const dropdownMenu = useDropdownMenu();const allPagesDrawerOpen = usePageStore((s) => s.allPagesDrawerOpen);- const activeWorkspaceId = useActiveWorkspaceId();const searchActive = Boolean(searchKeywords.trim());- // Empty-bucket call-to-action: a single "New Page" row that creates directly- // into the right visibility. Mirrors the Home sidebar's "创建助理" affordance- // — the bucket is empty but still actionable.- const { allowed: canCreate } = usePermission('create_content');- const untitledLabel = t('pageList.untitled');- const newPageLabel = t('addPage');-- const renderEmptyCreate = (visibility: 'private' | 'public') => (- <Block- horizontal- align={'center'}- clickable={canCreate}- gap={8}- height={36}- paddingInline={4}- style={canCreate ? { height: 36 } : { cursor: 'not-allowed', height: 36, opacity: 0.5 }}- variant={'borderless'}- onClick={() => canCreate && pageActions.createNewPage(untitledLabel, visibility)}- >- <Center flex={'none'} height={28} width={28}>- <Icon icon={PlusIcon} size={'small'} />- </Center>- <Text style={{ flex: 1 }} type={'secondary'}>- {newPageLabel}- </Text>- </Block>- );-- const renderNoResults = () => (- <Text- align="center"- fontSize={12}- style={{ paddingBlock: 12, paddingInline: 8 }}- type={'secondary'}- >- {t('pageList.noResults')}- </Text>- );-- // One accordion section: the header opens the page-list context menu, the- // action row reveals on hover, and the panel waits on the shared SWR load.- const renderSection = (section: {- action: ReactNode;- children: ReactNode;- count: number;- key: GroupKey;- title: string;- }) => (- <AccordionItem key={section.key} value={section.key}>- <ContextMenuTrigger items={dropdownMenu}>- <AccordionHeader>- <AccordionTrigger style={{ paddingBlock: 4, paddingInline: '8px 4px' }}>- <Flexbox horizontal align="center" gap={4}>- <Text ellipsis fontSize={12} type={'secondary'} weight={500}>- {section.title}- {section.count > 0 && ` ${section.count}`}- </Text>- {isValidating && <Spin size="small" variant="network" />}- </Flexbox>- </AccordionTrigger>- <Flexbox- horizontal- align="center"- gap={2}- className={cx(- 'accordion-action',- accordionStyles.action,- accordionStyles.actionBorderless,- )}- >- {section.action}- </Flexbox>- </AccordionHeader>- </ContextMenuTrigger>- <AccordionPanel>- <AsyncBoundary- data={isPageListInit || undefined}- error={error}- errorVariant={'inline'}- isLoading={!isPageListInit && !error}- loading={<SkeletonList />}- onRetry={() => revalidate()}- >- <Flexbox gap={1} paddingBlock={1}>- {section.children}- </Flexbox>- </AsyncBoundary>- </AccordionPanel>- </AccordionItem>- );-return (<Flexbox gap={1} paddingInline={4}>- {activeWorkspaceId ? (- <AccordionRoot- defaultValue={[GroupKey.PrivatePages, GroupKey.WorkspacePages]}- indicatorPlacement="inline"- style={{ gap: 2 }}- >- {renderSection({- action: (- <>+ <AccordionRoot+ defaultValue={[GroupKey.AllPages]}+ indicatorPlacement="inline"+ style={{ gap: 2 }}+ >+ <AccordionItem value={GroupKey.AllPages}>+ <ContextMenuTrigger items={dropdownMenu}>+ <AccordionHeader>+ <AccordionTrigger style={{ paddingBlock: 4, paddingInline: '8px 4px' }}>+ <Flexbox horizontal align="center" gap={4}>+ <Text ellipsis fontSize={12} type={'secondary'} weight={500}>+ {t('pageList.title')}+ {filteredDocumentsCount > 0 && ` ${filteredDocumentsCount}`}+ </Text>+ {isValidating && <Spin size="small" variant="network" />}+ </Flexbox>+ </AccordionTrigger>+ <Flexbox+ horizontal+ align="center"+ gap={2}+ className={cx(+ 'accordion-action',+ accordionStyles.action,+ accordionStyles.actionBorderless,+ )}+ ><Actions />- <AddButton compact visibility="private" />- </>- ),- children:- privateCount === 0 ? (- searchActive ? (- renderNoResults()- ) : (- renderEmptyCreate('private')- )- ) : (- <List visibility="private" />- ),- count: privateCount,- key: GroupKey.PrivatePages,- title: t('pageList.privateTitle'),- })}- {renderSection({- action: <AddButton compact visibility="public" />,- children:- workspaceCount === 0 ? (- searchActive ? (- renderNoResults()- ) : (- renderEmptyCreate('public')- )- ) : (- <List visibility="workspace" />- ),- count: workspaceCount,- key: GroupKey.WorkspacePages,- title: t('pageList.workspaceTitle'),- })}- </AccordionRoot>- ) : (- <AccordionRoot- defaultValue={[GroupKey.AllPages]}- indicatorPlacement="inline"- style={{ gap: 2 }}- >- {renderSection({- action: <Actions />,- children: filteredDocumentsCount === 0 ? <PageEmpty search={searchActive} /> : <List />,- count: filteredDocumentsCount,- key: GroupKey.AllPages,- title: t('pageList.title'),- })}- </AccordionRoot>- )}+ </Flexbox>+ </AccordionHeader>+ </ContextMenuTrigger>+ <AccordionPanel>+ <AsyncBoundary+ data={isPageListInit || undefined}+ error={error}+ errorVariant={'inline'}+ isLoading={!isPageListInit && !error}+ loading={<SkeletonList />}+ onRetry={() => revalidate()}+ >+ <Flexbox gap={1} paddingBlock={1}>+ {filteredDocumentsCount === 0 ? <PageEmpty search={searchActive} /> : <List />}+ </Flexbox>+ </AsyncBoundary>+ </AccordionPanel>+ </AccordionItem>+ </AccordionRoot><AllPagesDrawer open={allPagesDrawerOpen} onClose={pageActions.closeAllPagesDrawer} /></Flexbox>);diff --git a/src/features/Pages/PageLayout/Header/AddButton.tsx b/src/features/Pages/PageLayout/Header/AddButton.tsxindex e7255220c9e..b974a761fa9 100644--- a/src/features/Pages/PageLayout/Header/AddButton.tsx+++ b/src/features/Pages/PageLayout/Header/AddButton.tsx@@ -1,31 +1,14 @@'use client';import { ActionIcon } from '@lobehub/ui';-import { PlusIcon, SquarePenIcon } from 'lucide-react';+import { SquarePenIcon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';import { usePermission } from '@/hooks/usePermission';import { pageActions } from '@/store/page';-interface AddButtonProps {- /**- * Compact accordion-header variant: uses `+` icon at the `small` size so it- * sits comfortably next to `Actions` in the sidebar. The header-level entry- * (personal mode) omits this prop and gets the larger create-page icon.- */- compact?: boolean;- /**- * Force the new page's visibility. Used by the workspace-mode sidebar so- * each accordion header creates directly into its own bucket.- *- * Omit for the personal-mode / header-level entry — the server picks the- * default (`private` for top-level `api` docs).- */- visibility?: 'private' | 'public';-}--const AddButton = memo<AddButtonProps>(({ compact, visibility }) => {+const AddButton = memo(() => {const { t } = useTranslation('file');const { allowed: canCreate } = usePermission('create_content');@@ -33,22 +16,15 @@ const AddButton = memo<AddButtonProps>(({ compact, visibility }) => {if (!canCreate) return;const untitledTitle = t('pageList.untitled');- pageActions.createNewPage(untitledTitle, visibility);+ pageActions.createNewPage(untitledTitle);};return (<ActionIcondisabled={!canCreate}- icon={compact ? PlusIcon : SquarePenIcon}+ icon={SquarePenIcon}+ size={{ blockSize: 32, size: 18 }}title={t('header.newPageButton')}- size={- compact- ? 'small'- : {- blockSize: 32,- size: 18,- }- }onClick={handleNewDocument}/>);diff --git a/src/features/Pages/PageLayout/Header/index.tsx b/src/features/Pages/PageLayout/Header/index.tsxindex 089c8cef041..db8e6091c04 100644--- a/src/features/Pages/PageLayout/Header/index.tsx+++ b/src/features/Pages/PageLayout/Header/index.tsx@@ -5,7 +5,6 @@ import { SearchIcon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import NavItem from '@/features/NavPanel/components/NavItem';import SideBarHeaderLayout from '@/features/NavPanel/SideBarHeaderLayout';import { useGlobalStore } from '@/store/global';@@ -15,15 +14,11 @@ import AddButton from './AddButton';const Header = memo(() => {const { t } = useTranslation('common');const toggleCommandMenu = useGlobalStore((s) => s.toggleCommandMenu);- // In workspace mode the create button lives inside each accordion header- // (Private / Workspace) so the visibility bucket is picked at the source.- // Personal mode still has a single unified list, so keep the header entry.- const activeWorkspaceId = useActiveWorkspaceId();return (<><SideBarHeaderLayout- right={activeWorkspaceId ? undefined : <AddButton />}+ right={<AddButton />}breadcrumb={[{href: '/page',diff --git a/src/store/page/slices/list/selectors.test.ts b/src/store/page/slices/list/selectors.test.tsindex f21358c0998..f8c0bad5894 100644--- a/src/store/page/slices/list/selectors.test.ts+++ b/src/store/page/slices/list/selectors.test.ts@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import { DocumentSourceType, type LobeDocument } from '@/types/document';@@ -52,59 +52,20 @@ const createState = (documents: LobeDocument[], overrides: Partial<PageState> =...overrides,});-describe('listSelectors — private/workspace buckets', () => {- let state: PageState;-- beforeEach(() => {- state = createState([- doc('priv-a', 'private'),- doc('priv-b', 'private'),- doc('pub-a', 'public'),- doc('pub-b', null),- doc('pub-c', undefined),+describe('listSelectors — workspace visibility', () => {+ it('keeps private and shared pages in one list', () => {+ const state = createState([+ doc('priv-a', 'private', { createdAt: new Date('2026-01-03') }),+ doc('pub-a', 'public', { createdAt: new Date('2026-01-02') }),+ doc('legacy', null, { createdAt: new Date('2026-01-01') }),]);- });-- it('routes private-visibility docs into the private bucket', () => {- const ids = listSelectors.getPrivateFilteredDocuments(state).map((d) => d.id);- expect(ids.sort()).toEqual(['priv-a', 'priv-b']);- });- it('routes non-private docs (public/null/undefined) into the workspace bucket', () => {- // null and undefined visibility fall back to workspace-shared so historical- // docs pre-dating the column stay visible to every member.- const ids = listSelectors.getWorkspaceFilteredDocuments(state).map((d) => d.id);- expect(ids.sort()).toEqual(['pub-a', 'pub-b', 'pub-c']);- });-- it('exposes bucket counts', () => {- expect(listSelectors.privateFilteredDocumentsCount(state)).toBe(2);- expect(listSelectors.workspaceFilteredDocumentsCount(state)).toBe(3);- });-- it('honors the existing sourceType filter (drops file-uploaded docs from both buckets)', () => {- const stateWithFile = createState([- doc('priv-page', 'private'),- doc('priv-file', 'private', { sourceType: 'file' as DocumentSourceType }),- doc('pub-page', 'public'),- doc('pub-file', 'public', { sourceType: 'file' as DocumentSourceType }),- ]);-- expect(listSelectors.getPrivateFilteredDocuments(stateWithFile).map((d) => d.id)).toEqual([- 'priv-page',+ expect(listSelectors.getFilteredDocuments(state).map((d) => d.id)).toEqual([+ 'priv-a',+ 'pub-a',+ 'legacy',]);- expect(listSelectors.getWorkspaceFilteredDocuments(stateWithFile).map((d) => d.id)).toEqual([- 'pub-page',- ]);- });-- it('respects the sidebar page size cap for each bucket independently', () => {- const many = Array.from({ length: 25 }).map((_, i) =>- doc(`priv-${i}`, 'private', { createdAt: new Date(`2026-01-${(i % 28) + 1}`) }),- );- const state = createState(many);- expect(listSelectors.getPrivateFilteredDocumentsLimited(state)).toHaveLength(20);- expect(listSelectors.hasMorePrivateFilteredDocuments(state)).toBe(true);+ expect(listSelectors.filteredDocumentsCount(state)).toBe(3);});});diff --git a/src/store/page/slices/list/selectors.ts b/src/store/page/slices/list/selectors.tsindex 448f3e52c6c..ae727d5bc79 100644--- a/src/store/page/slices/list/selectors.ts+++ b/src/store/page/slices/list/selectors.ts@@ -60,35 +60,6 @@ const getFilteredDocuments = (s: PageState): LobeDocument[] => {const getFilteredDocumentsLimited = (s: PageState): LobeDocument[] =>getFilteredDocuments(s).slice(0, sidebarPageSize());-// Workspace-mode sidebar buckets: split filtered docs into "private" (creator-// only) and "workspace-shared". Personal-mode `visibility` is meaningless — the-// caller decides whether to render the flat list or the dual accordion.-const getPrivateFilteredDocuments = (s: PageState): LobeDocument[] =>- getFilteredDocuments(s).filter((doc) => doc.visibility === 'private');--const getWorkspaceFilteredDocuments = (s: PageState): LobeDocument[] =>- getFilteredDocuments(s).filter((doc) => doc.visibility !== 'private');--// Bucket-scoped, sidebar-sized page slices — mirror the Limited helper for the-// dual-accordion Pages sidebar so each bucket paginates independently.-const getPrivateFilteredDocumentsLimited = (s: PageState): LobeDocument[] =>- getPrivateFilteredDocuments(s).slice(0, sidebarPageSize());--const getWorkspaceFilteredDocumentsLimited = (s: PageState): LobeDocument[] =>- getWorkspaceFilteredDocuments(s).slice(0, sidebarPageSize());--const privateFilteredDocumentsCount = (s: PageState): number =>- getPrivateFilteredDocuments(s).length;--const workspaceFilteredDocumentsCount = (s: PageState): number =>- getWorkspaceFilteredDocuments(s).length;--const hasMorePrivateFilteredDocuments = (s: PageState): boolean =>- getPrivateFilteredDocuments(s).length > sidebarPageSize();--const hasMoreWorkspaceFilteredDocuments = (s: PageState): boolean =>- getWorkspaceFilteredDocuments(s).length > sidebarPageSize();-/*** 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@@ -119,17 +90,9 @@ export const listSelectors = {getDocumentById,getFilteredDocuments,getFilteredDocumentsLimited,- getPrivateFilteredDocuments,- getPrivateFilteredDocumentsLimited,- getWorkspaceFilteredDocuments,- getWorkspaceFilteredDocumentsLimited,hasMoreDocuments,hasMoreFilteredDocuments,- hasMorePrivateFilteredDocuments,- hasMoreWorkspaceFilteredDocuments,isDocumentsLoading,isLoadingMoreDocuments,isPageListInit,- privateFilteredDocumentsCount,- workspaceFilteredDocumentsCount,};