🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(resource): restructure Resources into Docs (#21373)
Arvin Xu7a8c675cc87b
diff --git a/apps/server/src/routers/lambda/__tests__/knowledgeBase.test.ts b/apps/server/src/routers/lambda/__tests__/knowledgeBase.test.tsindex e6bd81fe228..11127f6758c 100644--- a/apps/server/src/routers/lambda/__tests__/knowledgeBase.test.ts+++ b/apps/server/src/routers/lambda/__tests__/knowledgeBase.test.ts@@ -171,6 +171,38 @@ describe('knowledgeBaseRouter', () => {});});+ it('merges a cover into the stored settings without dropping other settings', async () => {+ mockKnowledgeBaseModelFindById.mockResolvedValue({+ id: 'kb-1',+ settings: { cover: 'preset:old', topK: 5 },+ userId: 'test-user',+ visibility: 'public',+ workspaceId: 'workspace-active',+ });++ await caller.updateKnowledgeBase({ id: 'kb-1', value: { cover: 'preset:aurora' } });++ expect(mockKnowledgeBaseModelUpdate).toHaveBeenCalledWith('kb-1', {+ settings: { cover: 'preset:aurora', topK: 5 },+ });+ });++ it('clears the cover back to the generated default on null', async () => {+ mockKnowledgeBaseModelFindById.mockResolvedValue({+ id: 'kb-1',+ settings: { cover: 'preset:old', topK: 5 },+ userId: 'test-user',+ visibility: 'public',+ workspaceId: 'workspace-active',+ });++ await caller.updateKnowledgeBase({ id: 'kb-1', value: { cover: null } });++ expect(mockKnowledgeBaseModelUpdate).toHaveBeenCalledWith('kb-1', {+ settings: { topK: 5 },+ });+ });+it('does not update a restricted library that the member cannot browse', async () => {routerMocks.assertKnowledgeBaseBrowsable.mockRejectedValue(new Error('denied'));diff --git a/apps/server/src/routers/lambda/document.ts b/apps/server/src/routers/lambda/document.tsindex 595badda457..3672c143e0d 100644--- a/apps/server/src/routers/lambda/document.ts+++ b/apps/server/src/routers/lambda/document.ts@@ -499,10 +499,12 @@ export const documentRouter = router({.input(z.object({+ creator: z.enum(['others', 'self']).optional(),current: z.number().optional(),fileTypes: z.array(z.string()).optional(),pageSize: z.number().max(100).optional(),sourceTypes: z.array(z.string()).optional(),+ standaloneOnly: z.boolean().optional(),}).optional(),)diff --git a/apps/server/src/routers/lambda/file/index.procedures.test.ts b/apps/server/src/routers/lambda/file/index.procedures.test.tsindex cf680403a9e..f7ec0ac6cc4 100644--- a/apps/server/src/routers/lambda/file/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/file/index.procedures.test.ts@@ -35,6 +35,7 @@ function expected(): Array<['getKnowledgeItemStatusesByIds', 'query', 12],['getKnowledgeItems', 'query', 12],['getReadableUrl', 'query', 12],+ ['homeItems', 'query', 12],['publishFileToWorkspace', 'mutation', 13],['recentFiles', 'query', 12],['recentPages', 'query', 12],diff --git a/apps/server/src/routers/lambda/file/knowledgeItems.ts b/apps/server/src/routers/lambda/file/knowledgeItems.tsindex d69d07feba2..c9b8e8a2b60 100644--- a/apps/server/src/routers/lambda/file/knowledgeItems.ts+++ b/apps/server/src/routers/lambda/file/knowledgeItems.ts@@ -153,6 +153,7 @@ export const knowledgeItemsRouter = router({fileType: item.fileType,finishEmbedding: status.finishEmbedding,id: item.id,+ knowledgeBaseIds: item.knowledgeBaseIds,metadata: item.metadata,name: item.name,size: item.size,diff --git a/apps/server/src/routers/lambda/file/queries.ts b/apps/server/src/routers/lambda/file/queries.tsindex 6cefddc8b22..2174a1a6575 100644--- a/apps/server/src/routers/lambda/file/queries.ts+++ b/apps/server/src/routers/lambda/file/queries.ts@@ -190,6 +190,43 @@ export const queriesRouter = router({return resultFiles;}),+ /**+ * The Docs home list. `recent` is everything in scope, `mine` the caller's+ * own rows, `shared` what other workspace members shared. Slim rows only:+ * the list never renders a body, chunk status or a storage URL.+ */+ homeItems: fileProcedure+ .input(+ z.object({+ limit: z.number().int().positive().max(100).optional(),+ tab: z.enum(['recent', 'mine', 'shared']),+ }),+ )+ .query(async ({ ctx, input }) => {+ if (input.tab === 'shared' && !ctx.workspaceId) return [];++ const excludeKnowledgeBaseIds = ctx.workspaceId+ ? await getRestrictedKnowledgeBaseIds(ctx)+ : undefined;+ const items = await ctx.knowledgeRepo.queryHomeItems({+ creator: input.tab === 'mine' ? 'self' : input.tab === 'shared' ? 'others' : undefined,+ excludeKnowledgeBaseIds,+ limit: input.limit ?? 50,+ });++ return items.map((item) => ({+ createdAt: item.createdAt,+ fileType: item.fileType,+ id: item.id,+ knowledgeBaseIds: item.knowledgeBaseIds ?? [],+ metadata: item.metadata,+ name: item.name,+ sourceType: item.sourceType,+ updatedAt: item.updatedAt,+ uploader: item.uploader,+ userId: item.userId,+ }));+ }),recentPages: fileProcedure.input(zdiff --git a/apps/server/src/routers/lambda/knowledgeBase.ts b/apps/server/src/routers/lambda/knowledgeBase.tsindex f05ebd70327..8001f4cd570 100644--- a/apps/server/src/routers/lambda/knowledgeBase.ts+++ b/apps/server/src/routers/lambda/knowledgeBase.ts@@ -43,10 +43,24 @@ import {*/const updatableKnowledgeBaseFields = z.object({avatar: z.string().nullish(),+ /** Cover image (preset key or uploaded URL); `null` restores the generated default. */+ cover: z.string().nullish(),description: z.string().nullish(),name: z.string().optional(),});+/**+ * The cover lives in the `settings` jsonb next to other library settings, so an+ * edit merges into the stored object instead of replacing it.+ */+export const mergeKnowledgeBaseCover = (+ settings: unknown,+ cover: string | null | undefined,+): Record<string, unknown> => {+ const { cover: _previous, ...rest } = (settings as Record<string, unknown> | null) ?? {};+ return cover ? { ...rest, cover } : rest;+};+const assertKnowledgeItemsAccessible = async (ctx: {documentModel: DocumentModel;@@ -132,6 +146,7 @@ export const knowledgeBaseRouter = router({.input(z.object({avatar: z.string().optional(),+ cover: z.string().optional(),description: z.string().optional(),name: z.string(),visibility: z.enum(['private', 'public']).optional(),@@ -142,6 +157,7 @@ export const knowledgeBaseRouter = router({avatar: input.avatar,description: input.description,name: input.name,+ settings: input.cover ? { cover: input.cover } : undefined,visibility: input.visibility,});@@ -496,6 +512,12 @@ export const knowledgeBaseRouter = router({workspaceId: existing.workspaceId ?? null,});- return ctx.knowledgeBaseModel.update(input.id, input.value);+ const { cover, ...value } = input.value;+ return ctx.knowledgeBaseModel.update(+ input.id,+ cover === undefined+ ? value+ : { ...value, settings: mergeKnowledgeBaseCover(existing.settings, cover) },+ );}),});diff --git a/apps/server/src/services/document/index.ts b/apps/server/src/services/document/index.tsindex 91ee5bf7db3..ad203fe7ab3 100644--- a/apps/server/src/services/document/index.ts+++ b/apps/server/src/services/document/index.ts@@ -360,11 +360,13 @@ export class DocumentService {* Query documents with pagination*/async queryDocuments(params?: {+ creator?: 'others' | 'self';current?: number;excludeKnowledgeBaseIds?: string[];fileTypes?: string[];pageSize?: number;sourceTypes?: string[];+ standaloneOnly?: boolean;}) {return this.documentModel.query(params);}diff --git a/e2e/src/steps/page/docs-home.ts b/e2e/src/steps/page/docs-home.tsnew file mode 100644index 00000000000..a9e0b18f52d--- /dev/null+++ b/e2e/src/steps/page/docs-home.ts@@ -0,0 +1,42 @@+/**+ * Docs home navigation helpers shared by the page step files.+ *+ * Pages live in Docs now (`/resource`). A returning user also gets the one-time+ * "Pages and Resources are now Docs" notice, which is a modal and therefore+ * intercepts clicks on the quick actions underneath it — every page scenario+ * timed out on the create step until the notice was dismissed.+ *+ * The notice mounts only after the user preference is loaded, so it can appear+ * a few seconds *after* the Docs home itself renders. Every helper that clicks+ * inside Docs therefore re-checks for it instead of dismissing it once and+ * assuming it stays gone.+ */+import type { CustomWorld } from '../../support/world';++const NOTICE_TITLE = /Pages and Resources are now Docs|页面和资源已合并为 Docs/;+const NOTICE_CONFIRM = /^(Got it|知道了|我知道了)$/;++/** How long to wait for a late-mounting notice before deciding it is absent. */+const NOTICE_APPEAR_TIMEOUT = 4000;++/** Dismiss the merge notice when it is on screen; a no-op otherwise. */+export async function dismissDocsMergeNotice(+ world: CustomWorld,+ appearTimeout: number = NOTICE_APPEAR_TIMEOUT,+): Promise<void> {+ const title = world.page.getByText(NOTICE_TITLE).first();++ await title.waitFor({ state: 'visible', timeout: appearTimeout }).catch(() => {});+ if (!(await title.isVisible().catch(() => false))) return;++ const confirm = world.page.getByRole('button', { name: NOTICE_CONFIRM }).first();+ await confirm.click({ timeout: 5000 }).catch(() => {});+ await title.waitFor({ state: 'hidden', timeout: 5000 }).catch(() => {});+}++/** Load the Docs home with any one-time notice out of the way. */+export async function openDocsHome(world: CustomWorld): Promise<void> {+ await world.page.goto('/resource');+ await world.page.waitForLoadState('domcontentloaded', { timeout: 15_000 });+ await dismissDocsMergeNotice(world);+}diff --git a/e2e/src/steps/page/editor-meta.steps.ts b/e2e/src/steps/page/editor-meta.steps.tsindex 779b1652d20..24edc3664aa 100644--- a/e2e/src/steps/page/editor-meta.steps.ts+++ b/e2e/src/steps/page/editor-meta.steps.ts@@ -4,10 +4,11 @@* Step definitions for Page editor title and emoji editing E2E tests*/import { Given, Then, When } from '@cucumber/cucumber';-import { expect } from '@playwright/test';+import { expect, type Locator } from '@playwright/test';import type { CustomWorld } from '../../support/world';import { WAIT_TIMEOUT } from '../../support/world';+import { openDocsHome } from './docs-home';async function waitForPageWorkspaceReady(world: CustomWorld): Promise<void> {const loadingSelectors = ['[aria-label="Loading"]', '.lobe-brand-loading'];@@ -29,9 +30,12 @@ async function waitForPageWorkspaceReady(world: CustomWorld): Promise<void> {}const readyCandidates = [+ // Pages live inside Docs now: the Docs home quick action renders a FilePlus2+ // icon, while the sidebar section keeps the SquarePen one.+ world.page.locator(':is(button, [role="button"]):has(svg.lucide-file-plus-2)').first(),world.page.locator(':is(button, [role="button"]):has(svg.lucide-square-pen)').first(),world.page.locator('input[placeholder*="Search"], input[placeholder*="搜索"]').first(),- world.page.locator('a[href^="/page/"]').first(),+ world.page.locator('a[href*="/resource/page/"]').first(),];for (const candidate of readyCandidates) {@@ -50,6 +54,9 @@ async function clickNewPageButton(world: CustomWorld): Promise<void> {await waitForPageWorkspaceReady(world);const candidates = [+ // Pages live inside Docs now: the home quick action renders a FilePlus2 icon,+ // while the sidebar section keeps the SquarePen one.+ world.page.locator(':is(button, [role="button"]):has(svg.lucide-file-plus-2)').first(),world.page.locator(':is(button, [role="button"]):has(svg.lucide-square-pen)').first(),world.page.locator('svg.lucide-square-pen')@@ -83,8 +90,7 @@ Given('用户打开一个文稿编辑器', async function (this: CustomWorld) {console.log(' 📍 Step: 创建并打开一个文稿...');// Navigate to page module- await this.page.goto('/page');- await this.page.waitForLoadState('domcontentloaded', { timeout: 15_000 });+ await openDocsHome(this);await waitForPageWorkspaceReady(this);// Create a new page via UI@@ -92,7 +98,7 @@ Given('用户打开一个文稿编辑器', async function (this: CustomWorld) {await this.page.waitForTimeout(1500);// Wait for navigation to page editor- await this.page.waitForURL(/\/page\/.+/, { timeout: WAIT_TIMEOUT });+ await this.page.waitForURL(/\/resource\/page\/.+/, { timeout: WAIT_TIMEOUT });await this.page.waitForLoadState('domcontentloaded');await this.page.waitForTimeout(500);@@ -103,14 +109,13 @@ Given('用户打开一个带有 Emoji 的文稿', async function (this: CustomWoconsole.log(' 📍 Step: 创建并打开一个带 Emoji 的文稿...');// First create and open a page- await this.page.goto('/page');- await this.page.waitForLoadState('domcontentloaded', { timeout: 15_000 });+ await openDocsHome(this);await waitForPageWorkspaceReady(this);await clickNewPageButton(this);await this.page.waitForTimeout(1500);- await this.page.waitForURL(/\/page\/.+/, { timeout: WAIT_TIMEOUT });+ await this.page.waitForURL(/\/resource\/page\/.+/, { timeout: WAIT_TIMEOUT });await this.page.waitForLoadState('domcontentloaded');await this.page.waitForTimeout(500);@@ -229,11 +234,35 @@ When('用户选择一个 Emoji', async function (this: CustomWorld) {When('用户点击已有的 Emoji 图标', async function (this: CustomWorld) {console.log(' 📍 Step: 点击已有的 Emoji 图标...');- // The emoji is displayed in an Avatar component with square shape- // Look for the emoji display element near the title- const emojiAvatar = this.page.locator('[class*="Avatar"]').first();- if ((await emojiAvatar.count()) > 0) {- await emojiAvatar.click();+ // The setup step can leave the picker open over the title; a pointer aimed+ // through it never lands on the emoji, so dismiss it first.+ await this.page.keyboard.press('Escape');+ await this.page.waitForTimeout(300);++ // Docs lists every page in the sidebar with an Avatar for its emoji, so a+ // bare `[class*="Avatar"]` matches a nav row instead of the editor's title.+ // Take the first Avatar that is not inside a page link.+ const avatars = this.page.locator('[class*="Avatar"]');+ const avatarCount = await avatars.count();+ let emojiAvatar: Locator | null = null;++ for (let i = 0; i < avatarCount; i += 1) {+ const candidate = avatars.nth(i);++ const insideNavRow = await candidate.evaluate((node) =>+ Boolean(node.closest('a[href*="/resource/page/"]')),+ );++ if (!insideNavRow) {+ emojiAvatar = candidate;+ break;+ }+ }++ if (emojiAvatar) {+ // Bounded: an unreachable target should fail the step fast instead of+ // eating the whole 30s budget inside Playwright's default retry window.+ await emojiAvatar.click({ timeout: 5000 });} else {// Fallback: look for span with emojiconst emojiSpan = this.page@@ -241,7 +270,7 @@ When('用户点击已有的 Emoji 图标', async function (this: CustomWorld) {.filter({ hasText: /^[\u{1F300}-\u{1F9FF}]$/u }).first();if ((await emojiSpan.count()) > 0) {- await emojiSpan.click();+ await emojiSpan.click({ timeout: 5000 });}}diff --git a/e2e/src/steps/page/page-crud.steps.ts b/e2e/src/steps/page/page-crud.steps.tsindex 0373d51692c..a3c46c04140 100644--- a/e2e/src/steps/page/page-crud.steps.ts+++ b/e2e/src/steps/page/page-crud.steps.ts@@ -12,6 +12,7 @@ import { expect } from '@playwright/test';import type { CustomWorld } from '../../support/world';import { WAIT_TIMEOUT } from '../../support/world';+import { dismissDocsMergeNotice, openDocsHome } from './docs-home';// ============================================// Helper Functions@@ -118,9 +119,12 @@ async function waitForPageWorkspaceReady(world: CustomWorld): Promise<void> {// The new-page button is rendered by `@lobehub/ui` ActionIcon as a// `<div role="button">` rather than a native `<button>`, so match either.const readyCandidates = [+ // Pages live inside Docs now: the Docs home quick action renders a FilePlus2+ // icon, while the sidebar section keeps the SquarePen one.+ world.page.locator(':is(button, [role="button"]):has(svg.lucide-file-plus-2)').first(),world.page.locator(':is(button, [role="button"]):has(svg.lucide-square-pen)').first(),world.page.locator('input[placeholder*="Search"], input[placeholder*="搜索"]').first(),- world.page.locator('a[href^="/page/"]').first(),+ world.page.locator('a[href*="/resource/page/"]').first(),];for (const candidate of readyCandidates) {@@ -136,9 +140,15 @@ async function waitForPageWorkspaceReady(world: CustomWorld): Promise<void> {}async function clickNewPageButton(world: CustomWorld): Promise<void> {+ // The one-time "Pages and Resources are now Docs" notice is a modal: while it+ // is up, the click lands on the mask and no page is created.+ await dismissDocsMergeNotice(world, 1500);await waitForPageWorkspaceReady(world);const candidates = [+ // Pages live inside Docs now: the home quick action renders a FilePlus2 icon,+ // while the sidebar section keeps the SquarePen one.+ world.page.locator(':is(button, [role="button"]):has(svg.lucide-file-plus-2)').first(),world.page.locator(':is(button, [role="button"]):has(svg.lucide-square-pen)').first(),world.page.locator('svg.lucide-square-pen')@@ -164,40 +174,71 @@ async function clickNewPageButton(world: CustomWorld): Promise<void> {throw new Error('Could not find new page button');}+/**+ * Wait for whatever rename UI the row opened and return its input.+ *+ * Docs renames a page inline — the field takes the place of the row title — and+ * it is tagged so the step never has to guess between the other inputs on the+ * screen (sidebar search, home chat box, editor title). The legacy popover shape+ * is still accepted for surfaces that have not moved to Docs yet.+ *+ * Each shape gets a bounded wait: scanning every `input` on the page and+ * filtering by placeholder used to burn the whole 30s step budget without ever+ * reaching the rename field.+ */+async function findRenameInput(world: CustomWorld) {+ const shapes = [+ '[data-testid="page-rename-input"]',+ '.ant-popover-inner input, .ant-popover-content input, .ant-popover input',+ ];++ for (const selector of shapes) {+ const input = world.page.locator(selector).first();++ try {+ await input.waitFor({ state: 'visible', timeout: 5000 });++ return input;+ } catch {+ // Try the next rename shape.+ }+ }++ return null;+}+// ============================================// Given Steps// ============================================Given('用户在 Page 页面', { timeout: 30_000 }, async function (this: CustomWorld) {console.log(' 📍 Step: 导航到 Page 页面...');- await this.page.goto('/page');- await this.page.waitForLoadState('domcontentloaded', { timeout: 15_000 });+ await openDocsHome(this);await waitForPageWorkspaceReady(this);console.log(' ✅ 已进入 Page 页面');});-Given('用户在 Page 页面有一个文稿', async function (this: CustomWorld) {+Given('用户在 Page 页面有一个文稿', { timeout: 60_000 }, async function (this: CustomWorld) {console.log(' 📍 Step: 导航到 Page 页面...');- await this.page.goto('/page');- await this.page.waitForLoadState('domcontentloaded', { timeout: 15_000 });+ await openDocsHome(this);console.log(' 📍 Step: 通过 UI 创建新文稿...');await clickNewPageButton(this);await this.page.waitForTimeout(1500);// Wait for the new page to be created and URL to change- await this.page.waitForURL(/\/page\/.+/, { timeout: WAIT_TIMEOUT });+ await this.page.waitForURL(/\/resource\/page\/.+/, { timeout: WAIT_TIMEOUT });// Create a unique title for this test pageconst uniqueTitle = `E2E Page ${Date.now()}`;console.log(` 📍 Step: 重命名为唯一标题 "${uniqueTitle}"...`);// Find the new page in sidebar (use link selector to avoid matching editor title)- // Sidebar page items are rendered as <a href="/page/xxx"> links+ // Sidebar page items are rendered as <a href="/resource/page/xxx"> links// Debug: check how many links exist- const allPageLinks = this.page.locator('a[href^="/page/"]');+ const allPageLinks = this.page.locator('a[href*="/resource/page/"]');const linkCount = await allPageLinks.count();console.log(` 📍 Debug: Found ${linkCount} page links in sidebar`);@@ -225,43 +266,14 @@ Given('用户在 Page 页面有一个文稿', async function (this: CustomWorld)console.log(' 📍 Debug: Clicked rename option');await this.page.waitForTimeout(800);- // Wait for rename popover to appear and find the input- // Try multiple selectors for the input- const inputSelectors = [- '.ant-popover input',- '.ant-popover-content input',- '[class*="popover"] input',- 'input[placeholder]',- ];-- let popoverInput = null;- for (const selector of inputSelectors) {- const inputs = this.page.locator(selector);- const count = await inputs.count();- console.log(` 📍 Debug: Selector "${selector}" found ${count} inputs`);- if (count > 0) {- // Find the visible one- for (let i = 0; i < count; i++) {- const input = inputs.nth(i);- if (await input.isVisible()) {- const placeholder = await input.getAttribute('placeholder');- // Skip search input- if (placeholder && (placeholder.includes('Search') || placeholder.includes('搜索'))) {- continue;- }- popoverInput = input;- break;- }- }- if (popoverInput) break;- }- }+ // Wait for the rename field to appear+ const popoverInput = await findRenameInput(this);if (!popoverInput) {- throw new Error('Could not find popover input for renaming');+ throw new Error(+ 'Could not find rename input: expected [data-testid="page-rename-input"] inline or a popover input',+ );}-- console.log(' 📍 Debug: Popover input found');await expect(popoverInput).toBeVisible({ timeout: 5000 });// Clear and input the unique name@@ -285,26 +297,28 @@ Given('用户在 Page 页面有一个文稿', async function (this: CustomWorld)console.log(` ✅ 找到文稿: ${uniqueTitle}`);});-Given('用户在 Page 页面有一个文稿 {string}', async function (this: CustomWorld, title: string) {+Given('用户在 Page 页面有一个文稿 {string}', { timeout: 60_000 }, async function (+ this: CustomWorld,+ title: string,+) {console.log(' 📍 Step: 导航到 Page 页面...');- await this.page.goto('/page');- await this.page.waitForLoadState('domcontentloaded', { timeout: 15_000 });+ await openDocsHome(this);console.log(' 📍 Step: 通过 UI 创建新文稿...');await clickNewPageButton(this);await this.page.waitForTimeout(1500);// Wait for the new page to be created- await this.page.waitForURL(/\/page\/.+/, { timeout: WAIT_TIMEOUT });+ await this.page.waitForURL(/\/resource\/page\/.+/, { timeout: WAIT_TIMEOUT });// Default title is "无标题" (Untitled) - support both languagesconst defaultTitleRegex = /^(无标题|Untitled)$/;console.log(` 📍 Step: 通过右键菜单重命名文稿为 "${title}"...`);// Find the new page in sidebar (use link selector to avoid matching editor title)- // Sidebar page items are rendered as <a href="/page/xxx"> links+ // Sidebar page items are rendered as <a href="/resource/page/xxx"> linksconst pageItem = this.page- .locator('a[href^="/page/"]')+ .locator('a[href*="/resource/page/"]').filter({ hasText: defaultTitleRegex }).first();await expect(pageItem).toBeVisible({ timeout: 5000 });@@ -319,36 +333,13 @@ Given('用户在 Page 页面有一个文稿 {string}', async function (this: Cusawait renameOption.click();await this.page.waitForTimeout(800);- // Wait for rename popover to appear and find the input- const inputSelectors = [- '.ant-popover input',- '.ant-popover-content input',- '[class*="popover"] input',- 'input[placeholder]',- ];-- let popoverInput = null;- for (const selector of inputSelectors) {- const inputs = this.page.locator(selector);- const count = await inputs.count();- if (count > 0) {- for (let i = 0; i < count; i++) {- const input = inputs.nth(i);- if (await input.isVisible()) {- const placeholder = await input.getAttribute('placeholder');- if (placeholder && (placeholder.includes('Search') || placeholder.includes('搜索'))) {- continue;- }- popoverInput = input;- break;- }- }- if (popoverInput) break;- }- }+ // Wait for the rename field to appear+ const popoverInput = await findRenameInput(this);if (!popoverInput) {- throw new Error('Could not find popover input for renaming');+ throw new Error(+ 'Could not find rename input: expected [data-testid="page-rename-input"] inline or a popover input',+ );}await expect(popoverInput).toBeVisible({ timeout: 5000 });diff --git a/locales/en-US/common.json b/locales/en-US/common.jsonindex c866db65b08..87c7406426e 100644--- a/locales/en-US/common.json+++ b/locales/en-US/common.json@@ -133,7 +133,7 @@"cmdk.openSettings": "Open Settings","cmdk.pages": "Pages","cmdk.painting": "Image",- "cmdk.resource": "Resources",+ "cmdk.resource": "Docs","cmdk.search.agent": "Agent","cmdk.search.agents": "Agents","cmdk.search.assistant": "Agent",@@ -480,7 +480,7 @@"tab.me": "Me","tab.memory": "Memory","tab.pages": "Pages",- "tab.resource": "Resources",+ "tab.resource": "Docs","tab.search": "Search","tab.setting": "Settings","tab.tasks": "Tasks",diff --git a/locales/en-US/electron.json b/locales/en-US/electron.jsonindex d305e40432f..66184a4a518 100644--- a/locales/en-US/electron.json+++ b/locales/en-US/electron.json@@ -57,11 +57,13 @@"navigation.resourceAll": "All","navigation.resourceAudios": "Audio","navigation.resourceDocuments": "Documents",+ "navigation.resourceDrive": "Drive","navigation.resourceFiles": "Files","navigation.resourceImages": "Images","navigation.resourcePages": "Pages","navigation.resourceVideos": "Videos",- "navigation.resources": "Resources",+ "navigation.resourceWorks": "Works",+ "navigation.resources": "Docs","navigation.selfLearning": "Self-evolving","navigation.settings": "Settings","navigation.sharedAgent": "Shared Agent",diff --git a/locales/en-US/file.json b/locales/en-US/file.jsonindex 44b2a9ebe94..10b8516a990 100644--- a/locales/en-US/file.json+++ b/locales/en-US/file.json@@ -16,12 +16,65 @@"detail.data.embedding.success": "Completed","detail.data.embeddingStatus": "embedding","detail.data.noChunk": "No chunk",+ "docs.allLibraries": "All knowledge bases",+ "docs.cover.defaultHint": "A cover is generated if you skip this",+ "docs.cover.reset": "Use default",+ "docs.cover.tooLarge": "Cover images must be 5 MB or smaller",+ "docs.cover.upload": "Upload image",+ "docs.cover.uploadFailed": "Cover upload failed. Please try again.",+ "docs.drive.all": "All",+ "docs.drive.inLibraries": "In knowledge base: {{names}}",+ "docs.home.columns.createdAt": "Created",+ "docs.home.columns.location": "Location",+ "docs.home.columns.owner": "Owner",+ "docs.home.columns.title": "Title",+ "docs.home.columns.updatedAt": "Updated",+ "docs.home.empty.mine": "You have not created any pages or files yet",+ "docs.home.empty.recent": "Nothing here yet. Create a page or upload a file to get started.",+ "docs.home.empty.shared": "Nothing has been shared with you yet",+ "docs.home.quick.newKnowledgeBase.desc": "Organize files and pages by topic",+ "docs.home.quick.newKnowledgeBase.title": "New knowledge base",+ "docs.home.quick.newPage.desc": "Start writing a new page",+ "docs.home.quick.newPage.title": "New page",+ "docs.home.quick.upload.desc": "Upload files from your computer",+ "docs.home.quick.upload.title": "Upload",+ "docs.home.tabs.mine": "Created by me",+ "docs.home.tabs.recent": "Recently updated",+ "docs.home.tabs.shared": "Shared with me",+ "docs.library.emptyDesc": "Gather related files and pages into a knowledge base to share them with your team and Agents",+ "docs.library.emptyTitle": "No knowledge bases yet",+ "docs.library.noDescription": "No description",+ "docs.library.updatedAt": "Updated {{time}}",+ "docs.mergeNotice.confirm": "Got it",+ "docs.mergeNotice.drive.desc": "Every file you uploaded, sorted by type, including files filed into knowledge bases.",+ "docs.mergeNotice.drive.title": "Files are in Drive",+ "docs.mergeNotice.intro": "Pages and Resources are now one place: Docs. Here is where everything moved.",+ "docs.mergeNotice.knowledgeBase.desc": "Your libraries are now called knowledge bases, each with its own cover.",+ "docs.mergeNotice.knowledgeBase.title": "Libraries are Knowledge Bases",+ "docs.mergeNotice.links.desc": "Links you saved to pages and resources open the same content in Docs.",+ "docs.mergeNotice.links.title": "Old links still work",+ "docs.mergeNotice.pages.desc": "Pages you wrote are under My docs in the sidebar; pages teammates shared are under Shared docs.",+ "docs.mergeNotice.pages.title": "Pages are in My docs",+ "docs.mergeNotice.title": "Pages and Resources are now Docs",+ "docs.myDocs.empty": "Create a page",+ "docs.myDocs.title": "My docs",+ "docs.recentLibraries": "Recent knowledge bases",+ "docs.section.drive": "Drive",+ "docs.section.home": "Home",+ "docs.section.library": "Knowledge Bases",+ "docs.section.works": "Works",+ "docs.shared.empty": "No pages shared by teammates yet",+ "docs.shared.title": "Shared docs",+ "docs.viewAllPages": "View all",+ "docs.works.all": "All",+ "docs.works.document": "Documents",+ "docs.works.task": "Tasks","empty": "No files or folders have been uploaded yet.","header.actions.builtInBlockList.filtered": "{{ignored}} files filtered (out of {{total}} total)","header.actions.connect": "Connect...","header.actions.createFolderError": "Failed to create folder","header.actions.creatingFolder": "Creating folder...",- "header.actions.deleteLibrary": "Delete Library",+ "header.actions.deleteLibrary": "Delete Knowledge Base","header.actions.gitignore.apply": "Apply Rules","header.actions.gitignore.cancel": "Ignore Rules","header.actions.gitignore.content": ".gitignore file detected ({{count}} files in total). Would you like to apply the ignore rules?",@@ -44,10 +97,10 @@"header.actions.uploadFolder.creatingFolders": "Creating folder structure...","header.newPageButton": "New Page","header.uploadButton": "Upload",- "home.libraries": "Libraries",+ "home.libraries": "Knowledge Bases","home.recentFiles": "Recent Files","home.recentPages": "Recent Pages",- "home.uploadEntries.library.title": "Create New Library",+ "home.uploadEntries.library.title": "Create New Knowledge Base","home.viewAll": "View all","imageViewer.ai.brushSize": "Brush size","imageViewer.ai.cancelled": "Edit cancelled. The original image is unchanged.",@@ -135,7 +188,7 @@"imageViewer.saveAsNew": "Save as new image","imageViewer.saveFailed": "Failed to save the image","imageViewer.saved": "Saved as {{name}}",- "imageViewer.savedNotInLibrary": "Saved as {{name}}, but it could not be added to the original's library. Add it from the file menu.",+ "imageViewer.savedNotInLibrary": "Saved as {{name}}, but it could not be added to the original's knowledge base. Add it from the file menu.","imageViewer.saving": "Saving…","imageViewer.tool.annotate": "Annotate","imageViewer.tool.comment": "Comment",@@ -147,38 +200,38 @@"imageViewer.zoom": "Zoom","imageViewer.zoomIn": "Zoom in","imageViewer.zoomOut": "Zoom out",- "library.backToResources": "Back to Resources",+ "library.backToResources": "Back to Docs","library.hierarchy.empty.desc": "Add files or create a folder to get started","library.hierarchy.empty.title": "Nothing here yet","library.hierarchy.search.noResults": "No matching files or pages","library.hierarchy.search.placeholder": "Search","library.import.action": "Import to workspace…",- "library.import.failed": "Failed to import library.",- "library.import.success": "Library imported to {{name}}.",- "library.import.tooltip": "Fork this library into a workspace. Files are shared by reference; the original stays in your personal space.",- "library.list.confirmRemoveLibrary": "Deleting this library permanently deletes files used only by it. Files that also belong to other libraries remain there. This action cannot be undone.",+ "library.import.failed": "Failed to import knowledge base.",+ "library.import.success": "Knowledge base imported to {{name}}.",+ "library.import.tooltip": "Fork this knowledge base into a workspace. Files are shared by reference; the original stays in your personal space.",+ "library.list.confirmRemoveLibrary": "Deleting this knowledge base permanently deletes files used only by it. Files that also belong to other knowledge bases remain there. This action cannot be undone.","library.list.copyDescription": "You can copy to personal or workspaces that have permission to create a knowledge base.",- "library.list.copyFailed": "Failed to copy library",- "library.list.copySuccess": "Library copied",- "library.list.copyTitle": "Copy library",+ "library.list.copyFailed": "Failed to copy knowledge base",+ "library.list.copySuccess": "Knowledge base copied",+ "library.list.copyTitle": "Copy knowledge base","library.list.copyTo": "Copy to…",- "library.list.empty": "Click <1>+</1> to create a new library",+ "library.list.empty": "Click <1>+</1> to create a new knowledge base","library.list.transferDescription": "You can move to personal or workspaces that have permission to create a knowledge base.",- "library.list.transferFailed": "Failed to move library",- "library.list.transferSuccess": "Library moved",- "library.list.transferTitle": "Move library",+ "library.list.transferFailed": "Failed to move knowledge base",+ "library.list.transferSuccess": "Knowledge base moved",+ "library.list.transferTitle": "Move knowledge base","library.list.transferTo": "Move to…",- "library.new": "New Library",- "library.privateEmpty": "Create a private library",+ "library.new": "New Knowledge Base",+ "library.privateEmpty": "Create a private knowledge base","library.publish": "Publish to workspace","library.publishConfirm.title": "Publish knowledge base to workspace?",- "library.title": "Library",- "library.workspaceEmpty": "Create a workspace library",+ "library.title": "Knowledge Base",+ "library.workspaceEmpty": "Create a workspace knowledge base","listView.uploadedBy": "Uploaded by {{name}}","loadMore": "Load More","menu.allFiles": "All Files","menu.allPages": "All Pages",- "networkError": "Failed to retrieve libraries. Please check your network connection and try again.",+ "networkError": "Failed to retrieve knowledge bases. Please check your network connection and try again.","notFound.desc": "This file does not exist or is no longer accessible — it may have been deleted or set to private by its owner.","notFound.title": "File Unavailable","notSupportGuide.desc": "The current deployment mode does not support file management. Switch to <1>server database deployment mode</1>, or use <3>LobeHub Cloud</3>.",@@ -186,8 +239,8 @@"notSupportGuide.features.allKind.title": "Multiple File Type Parsing","notSupportGuide.features.embeddings.desc": "Utilizes high-performance vector models to vectorize text chunks, enabling semantic search of file content.","notSupportGuide.features.embeddings.title": "Vector Semantics",- "notSupportGuide.features.libraries.desc": "Create Libraries and add files to build your own Library.",- "notSupportGuide.features.libraries.title": "Library",+ "notSupportGuide.features.libraries.desc": "Create Knowledge Bases and add files to build your own Knowledge Base.",+ "notSupportGuide.features.libraries.title": "Knowledge Base","notSupportGuide.title": "The current deployment mode does not support file management","pageEditor.addIcon": "Add Icon","pageEditor.autoSaveMessage": "Your page is saved automatically. No need to save manually.",@@ -198,7 +251,7 @@"pageEditor.comments.anchor.missing": "Original removed","pageEditor.comments.anchor.remove": "Remove quote","pageEditor.comments.attachments.add": "Add",- "pageEditor.comments.attachments.chooseLibrary": "Choose from Library",+ "pageEditor.comments.attachments.chooseLibrary": "Choose from Knowledge Base","pageEditor.comments.author.deactivated": "Deactivated user","pageEditor.comments.author.former": "Former member","pageEditor.comments.cancel": "Cancel",@@ -303,7 +356,7 @@"pageEditor.menu.importDocument": "Import Page","pageEditor.menu.move": "Move to…","pageEditor.menu.pin": "Pin Page",- "pageEditor.noAccess.description": "This page is private, or it’s in a library you can’t access. Ask its creator or a library manager for access.",+ "pageEditor.noAccess.description": "This page is private, or it’s in a knowledge base you can’t access. Ask its creator or a knowledge base manager for access.","pageEditor.noAccess.title": "You don’t have access to this page","pageEditor.saveFailed": "Failed to save the page, please try again later","pageEditor.saving": "Saving...",diff --git a/locales/en-US/knowledgeBase.json b/locales/en-US/knowledgeBase.jsonindex 270b01c46eb..ecfa23eefe8 100644--- a/locales/en-US/knowledgeBase.json+++ b/locales/en-US/knowledgeBase.json@@ -1,23 +1,24 @@{"addToKnowledgeBase.addSuccess": "File added successfully",- "addToKnowledgeBase.alreadyExists": "This file is already in the library",+ "addToKnowledgeBase.alreadyExists": "This file is already in the knowledge base","addToKnowledgeBase.confirm": "Add",- "addToKnowledgeBase.error": "Failed to add file to Library",- "addToKnowledgeBase.id.placeholder": "Please select a library to add to",- "addToKnowledgeBase.id.required": "Please select a library",- "addToKnowledgeBase.id.title": "Target Library",- "addToKnowledgeBase.title": "Add to Library",+ "addToKnowledgeBase.error": "Failed to add file to Knowledge Base",+ "addToKnowledgeBase.id.placeholder": "Please select a knowledge base to add to",+ "addToKnowledgeBase.id.required": "Please select a knowledge base",+ "addToKnowledgeBase.id.title": "Target Knowledge Base",+ "addToKnowledgeBase.title": "Add to Knowledge Base","addToKnowledgeBase.totalFiles": "{{count}} files selected","createNew.confirm": "Create New",- "createNew.description.label": "Library Description (Optional)",- "createNew.description.placeholder": "Description helps LLM understand your library better",+ "createNew.cover.label": "Cover",+ "createNew.description.label": "Knowledge Base Description (Optional)",+ "createNew.description.placeholder": "Description helps LLM understand your knowledge base better","createNew.edit.confirm": "Save Changes",- "createNew.edit.title": "Edit Library",+ "createNew.edit.title": "Edit Knowledge Base","createNew.formTitle": "Basic Information",- "createNew.name.placeholder": "Library name",- "createNew.name.required": "Please enter a library name",- "createNew.title": "Create New Library",- "moveToKnowledgeBase.error": "Failed to move file to Library",+ "createNew.name.placeholder": "Knowledge base name",+ "createNew.name.required": "Please enter a knowledge base name",+ "createNew.title": "Create New Knowledge Base",+ "moveToKnowledgeBase.error": "Failed to move file to Knowledge Base","moveToKnowledgeBase.success": "File moved successfully","tab.evals": "Evaluations","tab.files": "Files",diff --git a/locales/zh-CN/common.json b/locales/zh-CN/common.jsonindex 844f3ac31d2..973eca7b3f4 100644--- a/locales/zh-CN/common.json+++ b/locales/zh-CN/common.json@@ -133,7 +133,7 @@"cmdk.openSettings": "打开设置","cmdk.pages": "文稿","cmdk.painting": "图片",- "cmdk.resource": "资源",+ "cmdk.resource": "云文档","cmdk.search.agent": "助理","cmdk.search.agents": "助理","cmdk.search.assistant": "助理",@@ -480,7 +480,7 @@"tab.me": "我","tab.memory": "记忆","tab.pages": "文稿",- "tab.resource": "资源",+ "tab.resource": "云文档","tab.search": "搜索","tab.setting": "设置","tab.tasks": "任务",diff --git a/locales/zh-CN/electron.json b/locales/zh-CN/electron.jsonindex d63e02d7c77..12d9e72c68e 100644--- a/locales/zh-CN/electron.json+++ b/locales/zh-CN/electron.json@@ -57,11 +57,13 @@"navigation.resourceAll": "全部","navigation.resourceAudios": "语音","navigation.resourceDocuments": "文档",+ "navigation.resourceDrive": "云盘","navigation.resourceFiles": "文件","navigation.resourceImages": "图片","navigation.resourcePages": "文稿","navigation.resourceVideos": "视频",- "navigation.resources": "资源",+ "navigation.resourceWorks": "产物",+ "navigation.resources": "云文档","navigation.selfLearning": "自进化","navigation.settings": "设置","navigation.sharedAgent": "分享助手",diff --git a/locales/zh-CN/file.json b/locales/zh-CN/file.jsonindex b91fa6079f4..c2ef035107f 100644--- a/locales/zh-CN/file.json+++ b/locales/zh-CN/file.json@@ -16,6 +16,59 @@"detail.data.embedding.success": "已完成","detail.data.embeddingStatus": "向量化","detail.data.noChunk": "无分块",+ "docs.allLibraries": "全部知识库",+ "docs.cover.defaultHint": "不选择时将自动生成封面",+ "docs.cover.reset": "恢复默认",+ "docs.cover.tooLarge": "封面图片不能超过 5 MB",+ "docs.cover.upload": "上传图片",+ "docs.cover.uploadFailed": "封面上传失败,请重试",+ "docs.drive.all": "全部",+ "docs.drive.inLibraries": "所属知识库:{{names}}",+ "docs.home.columns.createdAt": "创建时间",+ "docs.home.columns.location": "位置",+ "docs.home.columns.owner": "所有者",+ "docs.home.columns.title": "标题",+ "docs.home.columns.updatedAt": "更新时间",+ "docs.home.empty.mine": "你还没有创建文稿或文件",+ "docs.home.empty.recent": "还没有内容,新建一篇文稿或上传文件开始吧",+ "docs.home.empty.shared": "还没有人与你共享内容",+ "docs.home.quick.newKnowledgeBase.desc": "按主题整理文件和文稿",+ "docs.home.quick.newKnowledgeBase.title": "新建知识库",+ "docs.home.quick.newPage.desc": "开始撰写一篇文稿",+ "docs.home.quick.newPage.title": "新建文稿",+ "docs.home.quick.upload.desc": "上传本地文件",+ "docs.home.quick.upload.title": "上传",+ "docs.home.tabs.mine": "我创建的",+ "docs.home.tabs.recent": "最近更新",+ "docs.home.tabs.shared": "与我共享",+ "docs.library.emptyDesc": "把相关的文件和文稿收进知识库,供团队和助理一起使用",+ "docs.library.emptyTitle": "还没有知识库",+ "docs.library.noDescription": "暂无简介",+ "docs.library.updatedAt": "更新于 {{time}}",+ "docs.mergeNotice.confirm": "知道了",+ "docs.mergeNotice.drive.desc": "所有上传过的文件按类型归在这里,已放进知识库的文件也能看到。",+ "docs.mergeNotice.drive.title": "文件在「云盘」",+ "docs.mergeNotice.intro": "「文稿」和「资源」已经合并为「云文档」,原来的内容都还在,位置如下:",+ "docs.mergeNotice.knowledgeBase.desc": "原来的资源库现在叫「知识库」,并且支持设置封面。",+ "docs.mergeNotice.knowledgeBase.title": "资源库改名为「知识库」",+ "docs.mergeNotice.links.desc": "之前收藏或分享的文稿、资源链接会自动打开云文档里的对应内容。",+ "docs.mergeNotice.links.title": "旧链接仍然可用",+ "docs.mergeNotice.pages.desc": "你写的文稿在侧栏的「我的文档」,同事共享的文稿在「共享文档」。",+ "docs.mergeNotice.pages.title": "文稿在「我的文档」",+ "docs.mergeNotice.title": "「文稿」和「资源」已合并为「云文档」",+ "docs.myDocs.empty": "新建文稿",+ "docs.myDocs.title": "我的文档",+ "docs.recentLibraries": "最近知识库",+ "docs.section.drive": "云盘",+ "docs.section.home": "主页",+ "docs.section.library": "知识库",+ "docs.section.works": "产物",+ "docs.shared.empty": "暂无团队成员共享的文稿",+ "docs.shared.title": "共享文档",+ "docs.viewAllPages": "查看全部",+ "docs.works.all": "全部",+ "docs.works.document": "文档",+ "docs.works.task": "任务","empty": "这里还没有文件或文件夹。先上传一个文件,或创建文稿开始整理","header.actions.builtInBlockList.filtered": "已过滤 {{ignored}} 个文件(共 {{total}} 个文件)","header.actions.connect": "连接…",@@ -147,7 +200,7 @@"imageViewer.zoom": "缩放","imageViewer.zoomIn": "放大","imageViewer.zoomOut": "缩小",- "library.backToResources": "返回资源库",+ "library.backToResources": "返回云文档","library.hierarchy.empty.desc": "上传文件或新建文件夹开始整理","library.hierarchy.empty.title": "这里还没有内容","library.hierarchy.search.noResults": "没有匹配的文件或页面",diff --git a/locales/zh-CN/knowledgeBase.json b/locales/zh-CN/knowledgeBase.jsonindex a370cf2daf0..9ff0ba423c3 100644--- a/locales/zh-CN/knowledgeBase.json+++ b/locales/zh-CN/knowledgeBase.json@@ -9,6 +9,7 @@"addToKnowledgeBase.title": "添加到资源库","addToKnowledgeBase.totalFiles": "已选择 {{count}} 个文件","createNew.confirm": "新建",+ "createNew.cover.label": "封面","createNew.description.label": "库描述(可选)","createNew.description.placeholder": "描述有助于大语言模型更好地理解您的库","createNew.edit.confirm": "保存修改",diff --git a/packages/database/src/models/__tests__/document.queryFilters.workspace.test.ts b/packages/database/src/models/__tests__/document.queryFilters.workspace.test.tsnew file mode 100644index 00000000000..a5a30eb481b--- /dev/null+++ b/packages/database/src/models/__tests__/document.queryFilters.workspace.test.ts@@ -0,0 +1,203 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import {+ documents,+ files,+ knowledgeBaseFiles,+ knowledgeBases,+ users,+ workspaces,+} from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { DocumentModel } from '../document';++const serverDB: LobeChatDatabase = await getTestDB();++const userA = 'doc-query-filters-user-a';+const userB = 'doc-query-filters-user-b';++let workspaceId = '';++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userA }, { id: userB }]);+ const [ws] = await serverDB+ .insert(workspaces)+ .values({ name: 'doc-query-filters-ws', primaryOwnerId: userA, slug: 'doc-query-filters-ws' })+ .returning();+ workspaceId = ws.id;+ await serverDB.insert(knowledgeBases).values({+ id: 'kb-query-filters',+ name: 'KB',+ userId: userA,+ visibility: 'public',+ workspaceId,+ });+});++afterEach(async () => {+ await serverDB.delete(documents);+ await serverDB.delete(knowledgeBases);+ await serverDB.delete(workspaces);+ await serverDB.delete(users);+});++const insertPage = async (params: {+ id: string;+ knowledgeBaseId?: string;+ userId: string;+ visibility: 'private' | 'public';+}) => {+ await serverDB.insert(documents).values({+ fileType: 'custom/document',+ id: params.id,+ knowledgeBaseId: params.knowledgeBaseId ?? null,+ source: 'document',+ sourceType: 'api',+ title: params.id,+ totalCharCount: 0,+ totalLineCount: 0,+ userId: params.userId,+ visibility: params.visibility,+ workspaceId,+ });+};++const queryIds = async (userId: string, params: Parameters<DocumentModel['query']>[0]) => {+ const result = await new DocumentModel(serverDB, userId, workspaceId).query(params);+ return { ids: result.items.map((item) => item.id).sort(), total: result.total };+};++describe('DocumentModel.query — creator / standaloneOnly filters', () => {+ beforeEach(async () => {+ await insertPage({ id: 'a-standalone', userId: userA, visibility: 'public' });+ await insertPage({ id: 'a-private', userId: userA, visibility: 'private' });+ await insertPage({+ id: 'a-in-kb',+ knowledgeBaseId: 'kb-query-filters',+ userId: userA,+ visibility: 'public',+ });+ await insertPage({ id: 'b-standalone', userId: userB, visibility: 'public' });+ await insertPage({ id: 'b-private', userId: userB, visibility: 'private' });+ await insertPage({+ id: 'b-in-kb',+ knowledgeBaseId: 'kb-query-filters',+ userId: userB,+ visibility: 'public',+ });+ });++ it("lists the caller's own standalone pages for creator=self", async () => {+ expect(await queryIds(userA, { creator: 'self', standaloneOnly: true })).toEqual({+ ids: ['a-private', 'a-standalone'],+ total: 2,+ });+ });++ it("lists other members' public standalone pages for creator=others", async () => {+ expect(await queryIds(userA, { creator: 'others', standaloneOnly: true })).toEqual({+ ids: ['b-standalone'],+ total: 1,+ });+ });++ it('keeps knowledge-base pages when standaloneOnly is not set', async () => {+ expect(await queryIds(userA, { creator: 'self' })).toEqual({+ ids: ['a-in-kb', 'a-private', 'a-standalone'],+ total: 3,+ });+ });++ it('applies no creator narrowing by default', async () => {+ expect(await queryIds(userA, { standaloneOnly: true })).toEqual({+ ids: ['a-private', 'a-standalone', 'b-standalone'],+ total: 3,+ });+ });+});++describe('DocumentModel.query — standaloneOnly vs library-backed parsed files', () => {+ beforeEach(async () => {+ // A file that lives inside a library, and one that never joined a library.+ await serverDB.insert(files).values([+ {+ fileType: 'application/pdf',+ id: 'file-in-library',+ name: 'in-library.pdf',+ size: 1,+ url: 'https://example.com/in-library.pdf',+ userId: userA,+ workspaceId,+ },+ {+ fileType: 'application/pdf',+ id: 'file-standalone',+ name: 'standalone.pdf',+ size: 1,+ url: 'https://example.com/standalone.pdf',+ userId: userA,+ workspaceId,+ },+ ]);++ await serverDB.insert(knowledgeBaseFiles).values({+ fileId: 'file-in-library',+ knowledgeBaseId: 'kb-query-filters',+ userId: userA,+ workspaceId,+ });++ // Parsing a library file yields a document with `fileId` but no `knowledgeBaseId`.+ await serverDB.insert(documents).values([+ {+ fileId: 'file-in-library',+ fileType: 'application/pdf',+ id: 'a-parsed-from-library',+ knowledgeBaseId: null,+ source: 'document',+ sourceType: 'file',+ title: 'a-parsed-from-library',+ totalCharCount: 0,+ totalLineCount: 0,+ userId: userA,+ visibility: 'public',+ workspaceId,+ },+ {+ fileId: 'file-standalone',+ fileType: 'application/pdf',+ id: 'a-own-file',+ knowledgeBaseId: null,+ source: 'document',+ sourceType: 'file',+ title: 'a-own-file',+ totalCharCount: 0,+ totalLineCount: 0,+ userId: userA,+ visibility: 'public',+ workspaceId,+ },+ ]);+ });++ afterEach(async () => {+ await serverDB.delete(knowledgeBaseFiles);+ });++ it('leaves out a parsed file whose backing file belongs to a library', async () => {+ expect(await queryIds(userA, { creator: 'self', standaloneOnly: true })).toEqual({+ ids: ['a-own-file'],+ total: 1,+ });+ });++ it('keeps the library-backed parsed file when standaloneOnly is not set', async () => {+ expect(await queryIds(userA, { creator: 'self' })).toEqual({+ ids: ['a-own-file', 'a-parsed-from-library'],+ total: 2,+ });+ });+});diff --git a/packages/database/src/models/document.ts b/packages/database/src/models/document.tsindex 3759aafe09e..85b3d5784c5 100644--- a/packages/database/src/models/document.ts+++ b/packages/database/src/models/document.ts@@ -47,6 +47,11 @@ import { documentOriginalCharCount } from '../utils/originalCharCount';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';export interface QueryDocumentParams {+ /**+ * Narrow by creator: `self` keeps the caller's own documents, `others` keeps+ * documents other workspace members created (still subject to visibility).+ */+ creator?: 'others' | 'self';current?: number;/*** Knowledge-base ids whose documents must be dropped from the listing —@@ -57,6 +62,8 @@ export interface QueryDocumentParams {fileTypes?: string[];pageSize?: number;sourceTypes?: string[];+ /** Keep only documents that live outside every knowledge base. */+ standaloneOnly?: boolean;}export const DOCUMENT_TRANSFER_FOREIGN_ROWS =@@ -178,11 +185,13 @@ export class DocumentModel {};query = async ({+ creator,current = 0,pageSize = 9999,excludeKnowledgeBaseIds,fileTypes,sourceTypes,+ standaloneOnly,}: QueryDocumentParams = {}): Promise<{items: DocumentItem[];total: number;@@ -194,6 +203,25 @@ export class DocumentModel {conditions.push(inArray(documents.fileType, fileTypes));}+ if (creator === 'self') conditions.push(eq(documents.userId, this.userId));+ if (creator === 'others') conditions.push(ne(documents.userId, this.userId));++ if (standaloneOnly) {+ conditions.push(+ isNull(documents.knowledgeBaseId),+ // Parsed files taken from a library keep `knowledgeBaseId` null, so the+ // `knowledgeBaseId` check alone still lets them through. A document that+ // is backed by a file living in a library is not standalone either.+ or(+ isNull(documents.fileId),+ notInArray(+ documents.fileId,+ this.db.select({ fileId: knowledgeBaseFiles.fileId }).from(knowledgeBaseFiles),+ ),+ )!,+ );+ }+if (excludeKnowledgeBaseIds?.length) {conditions.push(or(diff --git a/packages/database/src/repositories/knowledge/__tests__/driveListing.test.ts b/packages/database/src/repositories/knowledge/__tests__/driveListing.test.tsnew file mode 100644index 00000000000..fe2aecada99--- /dev/null+++ b/packages/database/src/repositories/knowledge/__tests__/driveListing.test.ts@@ -0,0 +1,141 @@+// @vitest-environment node+import { beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { documents, files, knowledgeBaseFiles, knowledgeBases } from '../../../schemas/file';+import { users } from '../../../schemas/user';+import type { LobeChatDatabase } from '../../../type';+import { KnowledgeRepo } from '../index';++const userId = 'drive-listing-user';++const serverDB: LobeChatDatabase = await getTestDB();++let knowledgeRepo: KnowledgeRepo;++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }]);+ knowledgeRepo = new KnowledgeRepo(serverDB, userId);++ await serverDB.insert(knowledgeBases).values([+ { id: 'drive-kb-1', name: 'KB One', userId },+ { id: 'drive-kb-2', name: 'KB Two', userId },+ ]);+ await serverDB.insert(files).values([+ {+ fileType: 'application/pdf',+ id: 'drive-kb-file',+ name: 'in-two-kbs.pdf',+ size: 100,+ url: 'drive-kb-file-url',+ userId,+ },+ {+ fileType: 'application/pdf',+ id: 'drive-loose-file',+ name: 'loose.pdf',+ size: 100,+ url: 'drive-loose-file-url',+ userId,+ },+ ]);+ await serverDB.insert(knowledgeBaseFiles).values([+ { fileId: 'drive-kb-file', knowledgeBaseId: 'drive-kb-1', userId },+ { fileId: 'drive-kb-file', knowledgeBaseId: 'drive-kb-2', userId },+ ]);+ await serverDB.insert(documents).values([+ {+ content: 'page',+ fileType: 'custom/document',+ filename: 'standalone-page',+ id: 'drive-page',+ source: 'document',+ sourceType: 'api',+ totalCharCount: 4,+ totalLineCount: 1,+ userId,+ },+ {+ content: '',+ fileType: 'custom/folder',+ filename: 'nested-folder',+ id: 'drive-folder',+ source: 'document',+ sourceType: 'document',+ title: 'nested-folder',+ totalCharCount: 0,+ totalLineCount: 0,+ userId,+ },+ {+ content: 'kb page',+ fileType: 'custom/document',+ filename: 'kb-page',+ id: 'drive-kb-page',+ knowledgeBaseId: 'drive-kb-1',+ source: 'document',+ sourceType: 'api',+ totalCharCount: 7,+ totalLineCount: 1,+ userId,+ },+ ]);+ // The folder has to exist first: `files.parent_id` references `documents.id`.+ await serverDB.insert(files).values([+ {+ fileType: 'application/pdf',+ id: 'drive-nested-file',+ name: 'nested.pdf',+ parentId: 'drive-folder',+ size: 100,+ url: 'drive-nested-file-url',+ userId,+ },+ ]);+});++describe('KnowledgeRepo.query — drive listing', () => {+ it('lists uploaded files and the folders holding them, but never pages, for filesOnly', async () => {+ const results = await knowledgeRepo.query({+ filesOnly: true,+ // The drive root, exactly as the explorer asks for it.+ parentId: null,+ showFilesInKnowledgeBase: true,+ });++ // The folder at the root is the only way into its children, so the drive has+ // to keep it; pages belong to the sidebar's Docs sections.+ expect(results.map((item) => item.id).sort()).toEqual([+ 'drive-folder',+ 'drive-kb-file',+ 'drive-loose-file',+ ]);+ });++ it('keeps a nested file reachable from its folder', async () => {+ const results = await knowledgeRepo.query({+ filesOnly: true,+ parentId: 'drive-folder',+ showFilesInKnowledgeBase: true,+ });++ expect(results.map((item) => item.id)).toEqual(['drive-nested-file']);+ });++ it('reports every knowledge base a file belongs to', async () => {+ const results = await knowledgeRepo.query({ filesOnly: true, showFilesInKnowledgeBase: true });+ const byId = Object.fromEntries(results.map((item) => [item.id, item]));++ expect(byId['drive-kb-file'].knowledgeBaseIds?.sort()).toEqual(['drive-kb-1', 'drive-kb-2']);+ expect(byId['drive-loose-file'].knowledgeBaseIds).toEqual([]);+ });++ it('reports the knowledge base of a document row in the combined listing', async () => {+ const results = await knowledgeRepo.query({ showFilesInKnowledgeBase: true });+ const byId = Object.fromEntries(results.map((item) => [item.id, item]));++ expect(byId['drive-page'].knowledgeBaseIds).toEqual([]);+ expect(byId['drive-kb-page'].knowledgeBaseIds).toEqual(['drive-kb-1']);+ });+});diff --git a/packages/database/src/repositories/knowledge/__tests__/homeItems.test.ts b/packages/database/src/repositories/knowledge/__tests__/homeItems.test.tsnew file mode 100644index 00000000000..65af13c9c3d--- /dev/null+++ b/packages/database/src/repositories/knowledge/__tests__/homeItems.test.ts@@ -0,0 +1,164 @@+// @vitest-environment node+import { beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { documents, files, knowledgeBaseFiles, knowledgeBases } from '../../../schemas/file';+import { users } from '../../../schemas/user';+import { workspaces } from '../../../schemas/workspace';+import type { LobeChatDatabase } from '../../../type';+import { KnowledgeRepo } from '../index';++const me = 'home-items-me';+const mate = 'home-items-mate';++const serverDB: LobeChatDatabase = await getTestDB();++let workspaceId = '';++const minutesAgo = (n: number) => new Date(Date.now() - n * 60_000);++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: me }, { id: mate }]);+ const [ws] = await serverDB+ .insert(workspaces)+ .values({ name: 'home-items', primaryOwnerId: me, slug: 'home-items' })+ .returning();+ workspaceId = ws.id;++ await serverDB.insert(knowledgeBases).values([+ { id: 'home-kb', name: 'KB', userId: me, visibility: 'public', workspaceId },+ {+ id: 'home-kb-restricted',+ name: 'Restricted',+ userId: mate,+ visibility: 'public',+ workspaceId,+ },+ ]);++ await serverDB.insert(files).values([+ {+ fileType: 'application/pdf',+ id: 'home-file-mine',+ name: 'mine.pdf',+ size: 1,+ updatedAt: minutesAgo(1),+ url: 'u1',+ userId: me,+ workspaceId,+ },+ {+ fileType: 'image/png',+ id: 'home-file-mate',+ name: 'mate.png',+ size: 1,+ updatedAt: minutesAgo(4),+ url: 'u2',+ userId: mate,+ workspaceId,+ },+ {+ fileType: 'text/plain',+ id: 'home-file-restricted',+ name: 'restricted.txt',+ size: 1,+ updatedAt: minutesAgo(2),+ url: 'u3',+ userId: mate,+ workspaceId,+ },+ ]);+ await serverDB.insert(knowledgeBaseFiles).values([+ { fileId: 'home-file-mine', knowledgeBaseId: 'home-kb', userId: me, workspaceId },+ {+ fileId: 'home-file-restricted',+ knowledgeBaseId: 'home-kb-restricted',+ userId: mate,+ workspaceId,+ },+ ]);++ const page = (params: {+ fileType?: string;+ id: string;+ knowledgeBaseId?: string;+ minutes: number;+ userId: string;+ visibility?: 'private' | 'public';+ }) => ({+ fileType: params.fileType ?? 'custom/document',+ filename: params.id,+ id: params.id,+ knowledgeBaseId: params.knowledgeBaseId ?? null,+ source: 'document',+ sourceType: 'api' as const,+ title: params.id,+ totalCharCount: 1,+ totalLineCount: 1,+ updatedAt: minutesAgo(params.minutes),+ userId: params.userId,+ visibility: params.visibility ?? 'public',+ workspaceId,+ });++ await serverDB+ .insert(documents)+ .values([+ page({ id: 'home-page-mine', minutes: 3, userId: me }),+ page({ id: 'home-page-kb', knowledgeBaseId: 'home-kb', minutes: 5, userId: me }),+ 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 }),+ ]);+});++const ids = async (params: Parameters<KnowledgeRepo['queryHomeItems']>[0]) =>+ (await new KnowledgeRepo(serverDB, me, workspaceId).queryHomeItems(params)).map(+ (item) => item.id,+ );++describe('KnowledgeRepo.queryHomeItems', () => {+ it('mixes pages and files, newest update first, without folders or private rows of others', async () => {+ expect(await ids({})).toEqual([+ 'home-file-mine',+ 'home-file-restricted',+ 'home-page-mine',+ 'home-file-mate',+ 'home-page-kb',+ 'home-page-mate',+ ]);+ });++ it("narrows to the caller's own rows", async () => {+ expect(await ids({ creator: 'self' })).toEqual([+ 'home-file-mine',+ 'home-page-mine',+ 'home-page-kb',+ ]);+ });++ it('narrows to rows other members shared', async () => {+ expect(await ids({ creator: 'others' })).toEqual([+ 'home-file-restricted',+ 'home-file-mate',+ 'home-page-mate',+ ]);+ });++ it('drops rows of restricted knowledge bases and reports each row location', async () => {+ const items = await new KnowledgeRepo(serverDB, me, workspaceId).queryHomeItems({+ excludeKnowledgeBaseIds: ['home-kb-restricted'],+ });++ expect(items.map((item) => item.id)).not.toContain('home-file-restricted');+ const byId = Object.fromEntries(items.map((item) => [item.id, item]));+ expect(byId['home-file-mine'].knowledgeBaseIds).toEqual(['home-kb']);+ expect(byId['home-page-kb'].knowledgeBaseIds).toEqual(['home-kb']);+ expect(byId['home-page-mine'].knowledgeBaseIds).toEqual([]);+ });++ it('honours the limit', async () => {+ expect(await ids({ limit: 2 })).toEqual(['home-file-mine', 'home-file-restricted']);+ });+});diff --git a/packages/database/src/repositories/knowledge/index.ts b/packages/database/src/repositories/knowledge/index.tsindex f4c2435ea55..5a69114cbd8 100644--- a/packages/database/src/repositories/knowledge/index.ts+++ b/packages/database/src/repositories/knowledge/index.ts@@ -92,6 +92,11 @@ const fileArmColumns = {fileType: f.fileType,// A file that backs a derived page is addressed by the page id.id: sql<string>`COALESCE(${d.id}, ${f.id})`.as('id'),+ knowledgeBaseIds: sql<+ string[]+ >`ARRAY(SELECT ${knowledgeBaseFiles.knowledgeBaseId} FROM ${knowledgeBaseFiles} WHERE ${knowledgeBaseFiles.fileId} = ${f.id})`.as(+ 'knowledge_base_ids',+ ),metadata: sql<Record<string, any> | null>`COALESCE(${d.metadata}, ${f.metadata})`.as('metadata'),name: f.name,size: f.size,@@ -131,6 +136,11 @@ const documentArmColumns = {fileId: d.fileId,fileType: d.fileType,id: d.id,+ knowledgeBaseIds: sql<+ string[]+ >`CASE WHEN ${d.knowledgeBaseId} IS NULL THEN ARRAY[]::text[] ELSE ARRAY[${d.knowledgeBaseId}] END`.as(+ 'knowledge_base_ids',+ ),metadata: d.metadata,name: sql<string>`COALESCE(${d.title}, ${d.filename}, 'Untitled')`.as('name'),size: sql<number>`${d.totalCharCount}`.as('size'),@@ -171,6 +181,7 @@ interface KnowledgeRow {fileId: string | null;fileType: string;id: string;+ knowledgeBaseIds: string[] | null;metadata: Record<string, any> | null;name: string;size: number;@@ -206,6 +217,8 @@ export interface KnowledgeItem {fileId?: string | null;fileType: string;id: string;+ /** Knowledge bases the row is filed into (empty when it lives outside every base). */+ knowledgeBaseIds?: string[];metadata?: Record<string, any> | null;name: string;size: number;@@ -283,6 +296,7 @@ const toKnowledgeItem = (row: KnowledgeRow): KnowledgeItem => ({fileId: row.fileId,fileType: row.fileType,id: row.id,+ knowledgeBaseIds: row.knowledgeBaseIds ?? [],metadata: toJson(row.metadata),name: row.name,size: Number(row.size),@@ -454,6 +468,7 @@ export class KnowledgeRepo {excludeKnowledgeBaseIds,includeContent = true,includeContentPreview = false,+ filesOnly,knowledgeBaseId,showFilesInKnowledgeBase,parentId,@@ -523,6 +538,11 @@ export class KnowledgeRepo {!knowledgeBaseId && excludeKnowledgeBaseIds?.length? or(isNull(d.knowledgeBaseId), notInArray(d.knowledgeBaseId, excludeKnowledgeBaseIds)): undefined,+ // The drive lists uploaded files plus the folders that hold them: a folder+ // row is the only way into its children, so dropping it strands every+ // nested file. Pages still live in their own sidebar sections, and this+ // filter is what keeps them out of the drive.+ filesOnly ? eq(d.fileType, CUSTOM_FOLDER_FILE_TYPE) : undefined,],includeContent,includeContentPreview,@@ -582,6 +602,62 @@ export class KnowledgeRepo {return rows.map(toKnowledgeItem);}+ /**+ * The Docs home list: pages and uploaded files 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+ * (`self`) or to what other workspace members shared (`others`); private rows+ * of other members never pass the ownership scope in the first place.+ * Folders, page-backing file rows and rows of restricted knowledge bases are+ * excluded in SQL, so `limit` is never eaten by rows filtered out later.+ */+ async queryHomeItems({+ creator,+ excludeKnowledgeBaseIds,+ limit = 50,+ }: {+ creator?: 'others' | 'self';+ excludeKnowledgeBaseIds?: string[];+ limit?: number;+ } = {}): Promise<KnowledgeItem[]> {+ const creatorFilter = (column: AnyPgColumn) =>+ creator === 'self'+ ? eq(column, this.userId)+ : creator === 'others'+ ? ne(column, this.userId)+ : undefined;++ const fileArm = this.fileArm(+ [+ creatorFilter(f.userId),+ ne(f.fileType, CUSTOM_DOCUMENT_FILE_TYPE),+ excludeKnowledgeBaseIds?.length+ ? this.notInKnowledgeBases(excludeKnowledgeBaseIds)+ : undefined,+ ],+ undefined,+ undefined,+ false,+ );++ const documentArm = this.documentArm(+ [+ creatorFilter(d.userId),+ eq(d.fileType, CUSTOM_DOCUMENT_FILE_TYPE),+ excludeKnowledgeBaseIds?.length+ ? or(isNull(d.knowledgeBaseId), notInArray(d.knowledgeBaseId, excludeKnowledgeBaseIds))+ : undefined,+ ],+ false,+ );++ const rows = await unionAll(fileArm, documentArm)+ .orderBy(this.orderBy(SortType.Desc, 'updatedAt'))+ .limit(limit);++ return rows.map(toKnowledgeItem);+ }+/*** Delete item by id - routes to appropriate model based on sourceType*/diff --git a/packages/locales/src/default/common.ts b/packages/locales/src/default/common.tsindex 97c331a2402..eebcb1f1a6d 100644--- a/packages/locales/src/default/common.ts+++ b/packages/locales/src/default/common.ts@@ -173,7 +173,7 @@ export default {'cmdk.painting': 'Image',- 'cmdk.resource': 'Resources',+ 'cmdk.resource': 'Docs','cmdk.search.agent': 'Agent',@@ -605,7 +605,7 @@ export default {'tab.me': 'Me','tab.memory': 'Memory','tab.pages': 'Pages',- 'tab.resource': 'Resources',+ 'tab.resource': 'Docs','tab.search': 'Search','tab.setting': 'Settings','tab.tasks': 'Tasks',diff --git a/packages/locales/src/default/electron.ts b/packages/locales/src/default/electron.tsindex ad80d338252..9919822ca21 100644--- a/packages/locales/src/default/electron.ts+++ b/packages/locales/src/default/electron.ts@@ -1,4 +1,6 @@export default {+ 'navigation.resourceDrive': 'Drive',+ 'navigation.resourceWorks': 'Works','startupUpdate.requiredTitle': 'Update required','startupUpdate.requiredDescription': 'This version has a security issue. Update to continue.','startupUpdate.checking': 'Checking for updates…',@@ -45,7 +47,7 @@ export default {'navigation.projects': 'Projects','navigation.provider': 'Provider','navigation.recentView': 'Recent pages',- 'navigation.resources': 'Resources',+ 'navigation.resources': 'Docs','navigation.resourceAll': 'All','navigation.resourceAudios': 'Audio','navigation.resourceDocuments': 'Documents',diff --git a/packages/locales/src/default/file.ts b/packages/locales/src/default/file.tsindex 3c0a947f003..5ab4c8c8011 100644--- a/packages/locales/src/default/file.ts+++ b/packages/locales/src/default/file.ts@@ -16,6 +16,65 @@ export default {'detail.data.embedding.processing': 'In progress','detail.data.embedding.success': 'Completed','detail.data.embeddingStatus': 'embedding',+ 'docs.allLibraries': 'All knowledge bases',+ 'docs.cover.defaultHint': 'A cover is generated if you skip this',+ 'docs.cover.reset': 'Use default',+ 'docs.cover.tooLarge': 'Cover images must be 5 MB or smaller',+ 'docs.cover.upload': 'Upload image',+ 'docs.cover.uploadFailed': 'Cover upload failed. Please try again.',+ 'docs.drive.all': 'All',+ 'docs.drive.inLibraries': 'In knowledge base: {{names}}',+ 'docs.home.columns.createdAt': 'Created',+ 'docs.home.columns.location': 'Location',+ 'docs.home.columns.owner': 'Owner',+ 'docs.home.columns.title': 'Title',+ 'docs.home.columns.updatedAt': 'Updated',+ 'docs.home.empty.mine': 'You have not created any pages or files yet',+ 'docs.home.empty.recent': 'Nothing here yet. Create a page or upload a file to get started.',+ 'docs.home.empty.shared': 'Nothing has been shared with you yet',+ 'docs.home.quick.newKnowledgeBase.desc': 'Organize files and pages by topic',+ 'docs.home.quick.newKnowledgeBase.title': 'New knowledge base',+ 'docs.home.quick.newPage.desc': 'Start writing a new page',+ 'docs.home.quick.newPage.title': 'New page',+ 'docs.home.quick.upload.desc': 'Upload files from your computer',+ 'docs.home.quick.upload.title': 'Upload',+ 'docs.home.tabs.mine': 'Created by me',+ 'docs.home.tabs.recent': 'Recently updated',+ 'docs.home.tabs.shared': 'Shared with me',+ 'docs.library.emptyDesc':+ 'Gather related files and pages into a knowledge base to share them with your team and Agents',+ 'docs.library.emptyTitle': 'No knowledge bases yet',+ 'docs.library.noDescription': 'No description',+ 'docs.library.updatedAt': 'Updated {{time}}',+ 'docs.mergeNotice.confirm': 'Got it',+ 'docs.mergeNotice.drive.desc':+ 'Every file you uploaded, sorted by type, including files filed into knowledge bases.',+ 'docs.mergeNotice.drive.title': 'Files are in Drive',+ 'docs.mergeNotice.intro':+ 'Pages and Resources are now one place: Docs. Here is where everything moved.',+ 'docs.mergeNotice.knowledgeBase.desc':+ 'Your libraries are now called knowledge bases, each with its own cover.',+ 'docs.mergeNotice.knowledgeBase.title': 'Libraries are Knowledge Bases',+ 'docs.mergeNotice.links.desc':+ 'Links you saved to pages and resources open the same content in Docs.',+ 'docs.mergeNotice.links.title': 'Old links still work',+ 'docs.mergeNotice.pages.desc':+ 'Pages you wrote are under My docs in the sidebar; pages teammates shared are under Shared docs.',+ 'docs.mergeNotice.pages.title': 'Pages are in My docs',+ 'docs.mergeNotice.title': 'Pages and Resources are now Docs',+ 'docs.myDocs.empty': 'Create a page',+ 'docs.myDocs.title': 'My docs',+ 'docs.recentLibraries': 'Recent knowledge bases',+ 'docs.section.drive': 'Drive',+ 'docs.section.home': 'Home',+ 'docs.section.library': 'Knowledge Bases',+ 'docs.section.works': 'Works',+ 'docs.shared.empty': 'No pages shared by teammates yet',+ 'docs.shared.title': 'Shared docs',+ 'docs.viewAllPages': 'View all',+ 'docs.works.all': 'All',+ 'docs.works.document': 'Documents',+ 'docs.works.task': 'Tasks','empty': 'No files or folders have been uploaded yet.','header.actions.builtInBlockList.filtered': '{{ignored}} files filtered (out of {{total}} total)','notFound.desc':@@ -24,7 +83,7 @@ export default {'header.actions.connect': 'Connect...','header.actions.createFolderError': 'Failed to create folder','header.actions.creatingFolder': 'Creating folder...',- 'header.actions.deleteLibrary': 'Delete Library',+ 'header.actions.deleteLibrary': 'Delete Knowledge Base','header.actions.gitignore.apply': 'Apply Rules','header.actions.gitignore.cancel': 'Ignore Rules','header.actions.gitignore.content':@@ -50,47 +109,47 @@ export default {'header.newPageButton': 'New Page','header.uploadButton': 'Upload','listView.uploadedBy': 'Uploaded by {{name}}',- 'home.libraries': 'Libraries',+ 'home.libraries': 'Knowledge Bases','home.recentFiles': 'Recent Files','home.recentPages': 'Recent Pages',- 'home.uploadEntries.library.title': 'Create New Library',+ 'home.uploadEntries.library.title': 'Create New Knowledge Base','home.viewAll': 'View all','library.hierarchy.empty.desc': 'Add files or create a folder to get started','library.hierarchy.empty.title': 'Nothing here yet','library.hierarchy.search.noResults': 'No matching files or pages','library.hierarchy.search.placeholder': 'Search','library.import.action': 'Import to workspace…',- 'library.import.failed': 'Failed to import library.',- 'library.import.success': 'Library imported to {{name}}.',+ 'library.import.failed': 'Failed to import knowledge base.',+ 'library.import.success': 'Knowledge base imported to {{name}}.','library.import.tooltip':- 'Fork this library into a workspace. Files are shared by reference; the original stays in your personal space.',- 'library.privateEmpty': 'Create a private library',+ 'Fork this knowledge base into a workspace. Files are shared by reference; the original stays in your personal space.',+ 'library.privateEmpty': 'Create a private knowledge base','library.list.confirmRemoveLibrary':- 'Deleting this library permanently deletes files used only by it. Files that also belong to other libraries remain there. This action cannot be undone.',+ 'Deleting this knowledge base permanently deletes files used only by it. Files that also belong to other knowledge bases remain there. This action cannot be undone.','library.list.copyDescription':'You can copy to personal or workspaces that have permission to create a knowledge base.',- 'library.list.copyFailed': 'Failed to copy library',- 'library.list.copySuccess': 'Library copied',- 'library.list.copyTitle': 'Copy library',+ 'library.list.copyFailed': 'Failed to copy knowledge base',+ 'library.list.copySuccess': 'Knowledge base copied',+ 'library.list.copyTitle': 'Copy knowledge base','library.list.copyTo': 'Copy to…',- 'library.list.empty': 'Click <1>+</1> to create a new library',+ 'library.list.empty': 'Click <1>+</1> to create a new knowledge base','library.list.transferDescription':'You can move to personal or workspaces that have permission to create a knowledge base.',- 'library.list.transferFailed': 'Failed to move library',- 'library.list.transferSuccess': 'Library moved',- 'library.list.transferTitle': 'Move library',+ 'library.list.transferFailed': 'Failed to move knowledge base',+ 'library.list.transferSuccess': 'Knowledge base moved',+ 'library.list.transferTitle': 'Move knowledge base','library.list.transferTo': 'Move to…',- 'library.new': 'New Library',- 'library.backToResources': 'Back to Resources',+ 'library.new': 'New Knowledge Base',+ 'library.backToResources': 'Back to Docs','library.publish': 'Publish to workspace','library.publishConfirm.title': 'Publish knowledge base to workspace?',- 'library.title': 'Library',- 'library.workspaceEmpty': 'Create a workspace library',+ 'library.title': 'Knowledge Base',+ 'library.workspaceEmpty': 'Create a workspace knowledge base','loadMore': 'Load More','menu.allFiles': 'All Files','menu.allPages': 'All Pages','networkError':- 'Failed to retrieve libraries. Please check your network connection and try again.',+ 'Failed to retrieve knowledge bases. Please check your network connection and try again.','notSupportGuide.desc':'The current deployment mode does not support file management. Switch to <1>server database deployment mode</1>, or use <3>LobeHub Cloud</3>.','notSupportGuide.features.allKind.desc':@@ -100,8 +159,8 @@ export default {'Utilizes high-performance vector models to vectorize text chunks, enabling semantic search of file content.','notSupportGuide.features.embeddings.title': 'Vector Semantics','notSupportGuide.features.libraries.desc':- 'Create Libraries and add files to build your own Library.',- 'notSupportGuide.features.libraries.title': 'Library',+ 'Create Knowledge Bases and add files to build your own Knowledge Base.',+ 'notSupportGuide.features.libraries.title': 'Knowledge Base','notSupportGuide.title': 'The current deployment mode does not support file management','imageViewer.ai.brushSize': 'Brush size','imageViewer.ai.cancelled': 'Edit cancelled. The original image is unchanged.',@@ -205,7 +264,7 @@ export default {'imageViewer.saveFailed': 'Failed to save the image','imageViewer.saved': 'Saved as {{name}}','imageViewer.savedNotInLibrary':- "Saved as {{name}}, but it could not be added to the original's library. Add it from the file menu.",+ "Saved as {{name}}, but it could not be added to the original's knowledge base. Add it from the file menu.",'imageViewer.saving': 'Saving…','imageViewer.version.label': 'Versions','imageViewer.version.original': 'Original',@@ -223,7 +282,7 @@ export default {'pageEditor.comments.author.deactivated': 'Deactivated user','pageEditor.comments.author.former': 'Former member','pageEditor.comments.attachments.add': 'Add',- 'pageEditor.comments.attachments.chooseLibrary': 'Choose from Library',+ 'pageEditor.comments.attachments.chooseLibrary': 'Choose from Knowledge Base','pageEditor.comments.cancel': 'Cancel','pageEditor.comments.createFailed': 'Failed to publish comment. Your draft is still here.','pageEditor.comments.deepLinkLoadFailed': 'Failed to load the linked comment. Try again.',@@ -338,7 +397,7 @@ export default {'pageEditor.menu.move': 'Move to…','pageEditor.menu.pin': 'Pin Page','pageEditor.noAccess.description':- 'This page is private, or it’s in a library you can’t access. Ask its creator or a library manager for access.',+ 'This page is private, or it’s in a knowledge base you can’t access. Ask its creator or a knowledge base manager for access.','pageEditor.noAccess.title': 'You don’t have access to this page','pageEditor.saveFailed': 'Failed to save the page, please try again later','pageEditor.saving': 'Saving...',diff --git a/packages/locales/src/default/knowledgeBase.ts b/packages/locales/src/default/knowledgeBase.tsindex d513d8d6fad..222ec86b4c0 100644--- a/packages/locales/src/default/knowledgeBase.ts+++ b/packages/locales/src/default/knowledgeBase.ts@@ -1,24 +1,26 @@export default {'addToKnowledgeBase.addSuccess': 'File added successfully',- 'addToKnowledgeBase.alreadyExists': 'This file is already in the library',+ 'addToKnowledgeBase.alreadyExists': 'This file is already in the knowledge base','addToKnowledgeBase.confirm': 'Add',- 'addToKnowledgeBase.error': 'Failed to add file to Library',- 'addToKnowledgeBase.id.placeholder': 'Please select a library to add to',- 'addToKnowledgeBase.id.required': 'Please select a library',- 'addToKnowledgeBase.id.title': 'Target Library',- 'addToKnowledgeBase.title': 'Add to Library',+ 'addToKnowledgeBase.error': 'Failed to add file to Knowledge Base',+ 'addToKnowledgeBase.id.placeholder': 'Please select a knowledge base to add to',+ 'addToKnowledgeBase.id.required': 'Please select a knowledge base',+ 'addToKnowledgeBase.id.title': 'Target Knowledge Base',+ 'addToKnowledgeBase.title': 'Add to Knowledge Base','addToKnowledgeBase.totalFiles': '{{count}} files selected',- 'moveToKnowledgeBase.error': 'Failed to move file to Library',+ 'createNew.cover.label': 'Cover',+ 'moveToKnowledgeBase.error': 'Failed to move file to Knowledge Base','moveToKnowledgeBase.success': 'File moved successfully','createNew.confirm': 'Create New','createNew.edit.confirm': 'Save Changes',- 'createNew.edit.title': 'Edit Library',- 'createNew.description.label': 'Library Description (Optional)',- 'createNew.description.placeholder': 'Description helps LLM understand your library better',+ 'createNew.edit.title': 'Edit Knowledge Base',+ 'createNew.description.label': 'Knowledge Base Description (Optional)',+ 'createNew.description.placeholder':+ 'Description helps LLM understand your knowledge base better','createNew.formTitle': 'Basic Information',- 'createNew.name.placeholder': 'Library name',- 'createNew.name.required': 'Please enter a library name',- 'createNew.title': 'Create New Library',+ 'createNew.name.placeholder': 'Knowledge base name',+ 'createNew.name.required': 'Please enter a knowledge base name',+ 'createNew.title': 'Create New Knowledge Base','tab.evals': 'Evaluations','tab.files': 'Files','tab.settings': 'Settings',diff --git a/packages/types/src/files/list.ts b/packages/types/src/files/list.tsindex 0a21c6fdb1e..071985dbed4 100644--- a/packages/types/src/files/list.ts+++ b/packages/types/src/files/list.ts@@ -34,6 +34,8 @@ export interface FileListItem {fileType: string;finishEmbedding: boolean;id: string;+ /** Knowledge bases the row is filed into. */+ knowledgeBaseIds?: string[];/*** Metadata (for notes/documents)*/@@ -87,6 +89,8 @@ const MAX_RESOURCE_LIST_PAGE_SIZE = 100;export const QueryFileListSchema = z.object({category: z.string().optional(),+ /** Keep pages out of the listing: the drive lists uploaded files and their folders. */+ filesOnly: z.boolean().optional(),/** Return a bounded server-generated plain-text preview for preview surfaces. */includeContentPreview: z.boolean().optional(),knowledgeBaseId: z.string().optional(),@@ -115,6 +119,7 @@ export type QueryFileListSchemaType = z.infer<typeof QueryFileListSchema>;export interface QueryFileListParams {category?: string;+ filesOnly?: boolean;includeContentPreview?: boolean;knowledgeBaseId?: string;limit?: number;diff --git a/packages/types/src/knowledgeBase/index.ts b/packages/types/src/knowledgeBase/index.tsindex 6ad166a8fcf..672bbf5432f 100644--- a/packages/types/src/knowledgeBase/index.ts+++ b/packages/types/src/knowledgeBase/index.ts@@ -31,6 +31,8 @@ export interface KnowledgeBaseItem {export interface CreateKnowledgeBaseParams {avatar?: string;+ /** Cover image: a preset key (`preset:<id>`) or an uploaded image URL. */+ cover?: string;description?: string;name: string;/** Workspace-scoped visibility for a newly created KB. Derived from the current resource-mode. */diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.tsindex aef88d5bd10..744f28089bf 100644--- a/packages/types/src/user/preference.ts+++ b/packages/types/src/user/preference.ts@@ -139,6 +139,11 @@ export interface LobeUser {}export const UserGuideSchema = z.object({+ /**+ * Pages and Resources were merged into Docs; set once the notice is acknowledged+ */+ docsMerged: z.boolean().optional(),+/*** Move the settings button to the avatar dropdown*/diff --git a/scripts/stylexMigration/legacyFiles.json b/scripts/stylexMigration/legacyFiles.jsonindex ac81e221bbe..0fcd1a078c6 100644--- a/scripts/stylexMigration/legacyFiles.json+++ b/scripts/stylexMigration/legacyFiles.json@@ -1010,12 +1010,6 @@"src/features/ProtocolUrlHandler/InstallPlugin/ConfigDisplay.tsx","src/features/RecommendTaskTemplates/style.ts","src/features/Recommendations/style.ts",- "src/features/ResourceHome/Home/Libraries.tsx",- "src/features/ResourceHome/Home/RecentFiles.tsx",- "src/features/ResourceHome/Home/RecentPages.tsx",- "src/features/ResourceHome/Home/RecentWorks.tsx",- "src/features/ResourceHome/Home/SectionTitle.tsx",- "src/features/ResourceHome/Home/index.tsx","src/features/ResourceHome/Layout/style.ts","src/features/ResourceLibrary/Layout/Header/LibraryHead.tsx","src/features/ResourceLibrary/Layout/style.ts",diff --git a/src/components/LibIcon/Locked.tsx b/src/components/LibIcon/Locked.tsxindex 0cc28267926..a416bee8db1 100644--- a/src/components/LibIcon/Locked.tsx+++ b/src/components/LibIcon/Locked.tsx@@ -35,7 +35,7 @@ interface LockedLibIconProps {}/**- * The shared "restricted library" visual: the library keeps its folder icon+ * The shared "restricted library" visual: the library keeps its own icon* (it is shared workspace content), and a small corner lock says members* cannot open it. Use this everywhere a member-restricted KB renders an icon,* so the state reads the same across sidebar, cards, and pickers.diff --git a/src/components/LibIcon/StatusIcon.tsx b/src/components/LibIcon/StatusIcon.tsxindex bd676d63440..921bd7ed4b7 100644--- a/src/components/LibIcon/StatusIcon.tsx+++ b/src/components/LibIcon/StatusIcon.tsx@@ -30,8 +30,8 @@ interface LibraryStatusIconProps {/*** One semantic icon mapping for every library identity surface:- * private → lock, member-restricted workspace library → folder + lock,- * ordinary workspace library → folder.+ * private → lock, member-restricted workspace library → library icon + lock,+ * ordinary workspace library → library icon.*/const LibraryStatusIcon = memo<LibraryStatusIconProps>(({ memberRestricted, size = 20, visibility }) => {diff --git a/src/components/LibIcon/index.tsx b/src/components/LibIcon/index.tsxindex 0e197c527dc..f5e11597f8b 100644--- a/src/components/LibIcon/index.tsx+++ b/src/components/LibIcon/index.tsx@@ -1,12 +1,16 @@import { cssVar, Icon } from '@lobehub/ui';-import { FolderIcon } from 'lucide-react';+import { LibraryBigIcon } from 'lucide-react';import { memo } from 'react';interface LibIconProps {size?: number;}+/**+ * A knowledge base reads as a bookshelf, not a folder: folders are what a+ * knowledge base contains, and the two must not look alike in the same list.+ */const LibIcon = memo<LibIconProps>(({ size = 20 }) => {- return <Icon color={cssVar.geekblue} fill={cssVar.geekblue3} icon={FolderIcon} size={size} />;+ return <Icon color={cssVar.geekblue} icon={LibraryBigIcon} size={size} />;});export default LibIcon;diff --git a/src/components/Skeleton/ResourceHome.tsx b/src/components/Skeleton/ResourceHome.tsxindex 7d238bf5afa..315fa797a8d 100644--- a/src/components/Skeleton/ResourceHome.tsx+++ b/src/components/Skeleton/ResourceHome.tsx@@ -9,10 +9,8 @@ import SkeletonBar from './Bar';* the placeholder never swaps shape between chunk load and data load.*/export const RESOURCE_HOME_SECTIONS = {- files: { count: 4, itemHeight: 160, minItemWidth: 180 },libraries: { count: 4, itemHeight: 52, minItemWidth: 200 },- pages: { count: 3, itemHeight: 64, minItemWidth: 240 },- works: { count: 3, itemHeight: 220, minItemWidth: 260 },+ quickActions: { count: 3, itemHeight: 66, minItemWidth: 220 },} as const;interface SectionSkeletonProps {@@ -42,9 +40,9 @@ export const ResourceSectionSkeleton = ({const styles = createStaticStyles(({ css }) => ({content: css`width: 100%;- max-width: 1080px;+ max-width: 1200px;margin-inline: auto;- padding-block: 32px 64px;+ padding-block: 24px 64px;padding-inline: 32px;`,header: css`@@ -56,10 +54,19 @@ const styles = createStaticStyles(({ css }) => ({`,}));-const Section = (props: SectionSkeletonProps) => (+/** Mirrors the Docs home: quick actions, then the tabbed list. */+const ListSkeleton = () => (<Flexbox gap={12}>- <SkeletonBar height={18} width={112} />- <ResourceSectionSkeleton {...props} />+ <Flexbox horizontal gap={24}>+ <SkeletonBar height={20} width={72} />+ <SkeletonBar height={20} width={72} />+ <SkeletonBar height={20} width={72} />+ </Flexbox>+ <Flexbox gap={8}>+ {Array.from({ length: 8 }).map((_, index) => (+ <SkeletonBar height={36} key={index} />+ ))}+ </Flexbox></Flexbox>);@@ -78,11 +85,9 @@ const ResourceHomeSkeleton = () => (<SkeletonBar height={28} width={88} /></Flexbox><div className={styles.scroll}>- <Flexbox className={styles.content} gap={40}>- <Section {...RESOURCE_HOME_SECTIONS.libraries} />- <Section {...RESOURCE_HOME_SECTIONS.works} />- <Section {...RESOURCE_HOME_SECTIONS.pages} />- <Section {...RESOURCE_HOME_SECTIONS.files} />+ <Flexbox className={styles.content} gap={28}>+ <ResourceSectionSkeleton {...RESOURCE_HOME_SECTIONS.quickActions} />+ <ListSkeleton /></Flexbox></div></Flexbox>diff --git a/src/features/LibraryCover/CoverPicker.tsx b/src/features/LibraryCover/CoverPicker.tsxnew file mode 100644index 00000000000..65680069629--- /dev/null+++ b/src/features/LibraryCover/CoverPicker.tsx@@ -0,0 +1,136 @@+'use client';++import { Button, Flexbox, Text, toast } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { ImageUpIcon } from 'lucide-react';+import { memo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useFileStore } from '@/store/file';++import LibraryCover from './index';+import { LIBRARY_COVER_PRESETS, presetCoverValue, resolveLibraryCover } from './presets';++/** Covers are banners, not documents; a larger image only slows every card down. */+const MAX_COVER_SIZE = 5 * 1024 * 1024;++const styles = stylex.create({+ swatch: {+ cursor: 'pointer',+ overflow: 'hidden',+ height: '40px',+ padding: 0,+ borderWidth: '2px',+ borderStyle: 'solid',+ borderColor: { 'default': 'transparent', ':hover': cssVar.colorBorder },+ borderRadius: cssVar.borderRadius,+ transitionProperty: 'border-color',+ transitionDuration: '0.2s',+ transitionTimingFunction: cssVar.motionEaseInOut,+ },+ swatchActive: {+ borderColor: { 'default': cssVar.colorPrimary, ':hover': cssVar.colorPrimary },+ },+ swatches: {+ display: 'grid',+ gridTemplateColumns: 'repeat(4, 1fr)',+ gap: '8px',+ },+});++const swatchProps = (active: boolean, background: string) => {+ const props = stylex.props(styles.swatch, active && styles.swatchActive);+ return { className: props.className, style: { ...props.style, backgroundImage: background } };+};++interface CoverPickerProps {+ /** Stored cover value; empty means the generated default. */+ onChange: (cover: string | null) => void;+ /** Library id (or a draft seed) that picks the default cover. */+ seed: string;+ value?: string | null;+}++/** Choose a library cover: a preset gradient, an uploaded image, or the default. */+const CoverPicker = memo<CoverPickerProps>(({ onChange, seed, value }) => {+ const { t } = useTranslation('file');+ const uploadWithProgress = useFileStore((s) => s.uploadWithProgress);+ const inputRef = useRef<HTMLInputElement>(null);+ const [uploading, setUploading] = useState(false);++ const resolved = resolveLibraryCover(value, seed);+ const activePresetId = value && resolved.kind === 'preset' ? resolved.presetId : null;++ const handleUpload = async (file: File) => {+ if (file.size > MAX_COVER_SIZE) {+ toast.error(t('docs.cover.tooLarge'));+ return;+ }+ setUploading(true);+ try {+ const result = await uploadWithProgress({ file });+ if (!result?.url) {+ toast.error(t('docs.cover.uploadFailed'));+ return;+ }+ onChange(result.url);+ } catch (error) {+ console.error('[CoverPicker] cover upload failed:', error);+ toast.error(t('docs.cover.uploadFailed'));+ } finally {+ setUploading(false);+ }+ };++ return (+ <Flexbox gap={12}>+ <LibraryCover cover={value} height={72} seed={seed} style={{ borderRadius: 8 }} />+ <div {...stylex.props(styles.swatches)}>+ {LIBRARY_COVER_PRESETS.map((preset) => (+ <button+ aria-label={preset.id}+ key={preset.id}+ {...swatchProps(activePresetId === preset.id, preset.background)}+ type={'button'}+ onClick={() => onChange(presetCoverValue(preset.id))}+ />+ ))}+ </div>+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>+ <Button+ icon={ImageUpIcon}+ loading={uploading}+ size={'small'}+ onClick={() => inputRef.current?.click()}+ >+ {t('docs.cover.upload')}+ </Button>+ {value ? (+ <Button size={'small'} type={'text'} onClick={() => onChange(null)}>+ {t('docs.cover.reset')}+ </Button>+ ) : (+ <Text fontSize={12} type={'secondary'}>+ {t('docs.cover.defaultHint')}+ </Text>+ )}+ </Flexbox>+ <input+ accept={'image/*'}+ ref={inputRef}+ style={{ display: 'none' }}+ type={'file'}+ onChange={(e) => {+ const file = e.target.files?.[0];+ e.target.value = '';+ if (file) void handleUpload(file);+ }}+ />+ </Flexbox>+ );+});++CoverPicker.displayName = 'CoverPicker';++export default CoverPicker;diff --git a/src/features/LibraryCover/index.tsx b/src/features/LibraryCover/index.tsxnew file mode 100644index 00000000000..7ca5a61f02d--- /dev/null+++ b/src/features/LibraryCover/index.tsx@@ -0,0 +1,65 @@+'use client';++import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { type CSSProperties, memo, type ReactNode } from 'react';++import { resolveLibraryCover } from './presets';++export * from './presets';++const styles = stylex.create({+ cover: {+ position: 'relative',+ overflow: 'hidden',+ flex: 'none',+ width: '100%',+ backgroundColor: cssVar.colorFillTertiary,+ },+ image: {+ position: 'absolute',+ inset: 0,+ width: '100%',+ height: '100%',+ objectFit: 'cover',+ },+});++interface LibraryCoverProps {+ children?: ReactNode;+ /** Stored cover value (`preset:<id>` or an image URL). */+ cover?: string | null;+ height?: number | string;+ /** Picks the default cover when none is stored — the library id. */+ seed: string;+ style?: CSSProperties;+}++const LibraryCover = memo<LibraryCoverProps>(({ children, cover, height = 120, seed, style }) => {+ const resolved = resolveLibraryCover(cover, seed);++ const coverProps = stylex.props(styles.cover);++ return (+ <div+ className={coverProps.className}+ style={{+ ...coverProps.style,+ // A gradient preset is the background; an image sits on the neutral fill,+ // which is also what a broken image URL degrades to.+ ...(resolved.kind === 'preset' ? { backgroundImage: resolved.background } : {}),+ height,+ ...style,+ }}+ >+ {resolved.kind === 'image' && (+ <img alt="" src={resolved.url} {...stylex.props(styles.image)} />+ )}+ {children}+ </div>+ );+});++LibraryCover.displayName = 'LibraryCover';++export default LibraryCover;diff --git a/src/features/LibraryCover/presets.test.ts b/src/features/LibraryCover/presets.test.tsnew file mode 100644index 00000000000..94b6828d0c2--- /dev/null+++ b/src/features/LibraryCover/presets.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it } from 'vitest';++import {+ defaultCoverPreset,+ LIBRARY_COVER_PRESETS,+ libraryCoverOf,+ presetCoverValue,+ resolveLibraryCover,+} from './presets';++describe('resolveLibraryCover', () => {+ it('renders a chosen preset', () => {+ expect(resolveLibraryCover(presetCoverValue('dusk'), 'kb-1')).toMatchObject({+ kind: 'preset',+ presetId: 'dusk',+ });+ });++ it('renders an uploaded image', () => {+ expect(resolveLibraryCover('https://cdn.test/cover.png', 'kb-1')).toEqual({+ kind: 'image',+ url: 'https://cdn.test/cover.png',+ });+ expect(resolveLibraryCover('/f/file-1', 'kb-1')).toEqual({ kind: 'image', url: '/f/file-1' });+ });++ it.each([undefined, '', 'preset:unknown', 'javascript:alert(1)', 42])(+ 'falls back to the default cover for %s',+ (cover) => {+ expect(resolveLibraryCover(cover, 'kb-1')).toMatchObject({+ kind: 'preset',+ presetId: defaultCoverPreset('kb-1').id,+ });+ },+ );+});++describe('defaultCoverPreset', () => {+ it('is stable for a seed and spreads across presets', () => {+ expect(defaultCoverPreset('kb-1')).toBe(defaultCoverPreset('kb-1'));++ const picked = new Set(Array.from({ length: 40 }, (_, i) => defaultCoverPreset(`kb-${i}`).id));+ expect(picked.size).toBeGreaterThan(LIBRARY_COVER_PRESETS.length / 2);+ });+});++describe('libraryCoverOf', () => {+ it('reads the cover from untyped settings', () => {+ expect(libraryCoverOf({ cover: 'preset:sky' })).toBe('preset:sky');+ expect(libraryCoverOf(null)).toBeUndefined();+ expect(libraryCoverOf({ cover: 1 })).toBeUndefined();+ });+});diff --git a/src/features/LibraryCover/presets.ts b/src/features/LibraryCover/presets.tsnew file mode 100644index 00000000000..6e7843e20a4--- /dev/null+++ b/src/features/LibraryCover/presets.ts@@ -0,0 +1,61 @@+/**+ * Library covers are stored as a string in `knowledge_bases.settings.cover`:+ * `preset:<id>` for a built-in gradient, otherwise an uploaded image URL. A+ * library without one gets a preset picked from its id, so every card has a+ * stable, distinct cover from the moment it is created.+ */+export const COVER_PRESET_PREFIX = 'preset:';++export interface LibraryCoverPreset {+ background: string;+ id: string;+}++export const LIBRARY_COVER_PRESETS: LibraryCoverPreset[] = [+ { background: 'linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%)', id: 'sky' },+ { background: 'linear-gradient(135deg, #fbc2eb 0%, #a6c1ee 100%)', id: 'aurora' },+ { background: 'linear-gradient(135deg, #fddb92 0%, #d1fdff 100%)', id: 'dawn' },+ { background: 'linear-gradient(135deg, #f6d365 0%, #fda085 100%)', id: 'sunset' },+ { background: 'linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%)', id: 'mint' },+ { background: 'linear-gradient(135deg, #d4fc79 0%, #96e6a1 100%)', id: 'meadow' },+ { background: 'linear-gradient(135deg, #cfd9df 0%, #e2ebf0 100%)', id: 'mist' },+ { background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', id: 'dusk' },+];++const PRESET_BY_ID = new Map(LIBRARY_COVER_PRESETS.map((preset) => [preset.id, preset]));++export const presetCoverValue = (id: string) => `${COVER_PRESET_PREFIX}${id}`;++const hashSeed = (seed: string): number => {+ let hash = 0;+ for (let i = 0; i < seed.length; i++) hash = (hash * 31 + seed.charCodeAt(i)) | 0;+ return Math.abs(hash);+};++/** The preset a library without a chosen cover shows, stable for its id. */+export const defaultCoverPreset = (seed: string): LibraryCoverPreset =>+ LIBRARY_COVER_PRESETS[hashSeed(seed) % LIBRARY_COVER_PRESETS.length];++export type ResolvedLibraryCover =+ { background: string; kind: 'preset'; presetId: string } | { kind: 'image'; url: string };++/** What a stored cover value renders as; unknown or empty values fall back to the default. */+export const resolveLibraryCover = (cover: unknown, seed: string): ResolvedLibraryCover => {+ if (typeof cover === 'string' && cover) {+ if (cover.startsWith(COVER_PRESET_PREFIX)) {+ const preset = PRESET_BY_ID.get(cover.slice(COVER_PRESET_PREFIX.length));+ if (preset) return { background: preset.background, kind: 'preset', presetId: preset.id };+ } else if (/^(?:https?:|\/|data:image\/)/.test(cover)) {+ return { kind: 'image', url: cover };+ }+ }++ const preset = defaultCoverPreset(seed);+ return { background: preset.background, kind: 'preset', presetId: preset.id };+};++/** The cover a library item stores, read defensively from its untyped settings. */+export const libraryCoverOf = (settings: unknown): string | undefined => {+ const cover = (settings as { cover?: unknown } | null | undefined)?.cover;+ return typeof cover === 'string' ? cover : undefined;+};diff --git a/src/features/LibraryGallery/LibraryCard.tsx b/src/features/LibraryGallery/LibraryCard.tsxnew file mode 100644index 00000000000..b67708bcaad--- /dev/null+++ b/src/features/LibraryGallery/LibraryCard.tsx@@ -0,0 +1,134 @@+'use client';++import { Flexbox, Icon, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import dayjs from 'dayjs';+import { PlusIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import LibraryStatusIcon from '@/components/LibIcon/StatusIcon';+import LibraryCover, { libraryCoverOf } from '@/features/LibraryCover';+import type { KnowledgeBaseItem } from '@/types/knowledgeBase';++export const libraryCardStyles = stylex.create({+ card: {+ cursor: 'pointer',+ overflow: 'hidden',+ display: 'flex',+ flexDirection: 'column',+ padding: 0,+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: { 'default': cssVar.colorBorderSecondary, ':hover': cssVar.colorBorder },+ borderRadius: cssVar.borderRadiusLG,+ textAlign: 'start',+ backgroundColor: cssVar.colorBgContainer,+ boxShadow: { 'default': 'none', ':hover': cssVar.boxShadowTertiary },+ transitionProperty: 'border-color, box-shadow',+ transitionDuration: '0.2s',+ transitionTimingFunction: cssVar.motionEaseInOut,+ },+ createCard: {+ cursor: { 'default': 'pointer', ':disabled': 'not-allowed' },+ display: 'flex',+ flexDirection: 'column',+ gap: '8px',+ alignItems: 'center',+ justifyContent: 'center',+ minHeight: '196px',+ borderWidth: '1px',+ borderStyle: 'dashed',+ borderColor: { 'default': cssVar.colorBorder, ':hover': cssVar.colorTextQuaternary },+ borderRadius: cssVar.borderRadiusLG,+ color: { 'default': cssVar.colorTextSecondary, ':hover': cssVar.colorText },+ backgroundColor: 'transparent',+ opacity: { 'default': 1, ':disabled': 0.5 },+ transitionProperty: 'border-color, color',+ transitionDuration: '0.2s',+ transitionTimingFunction: cssVar.motionEaseInOut,+ },+ description: {+ overflow: 'hidden',+ display: '-webkit-box',+ WebkitBoxOrient: 'vertical',+ WebkitLineClamp: 2,+ minHeight: '40px',+ fontSize: '13px',+ lineHeight: '20px',+ color: cssVar.colorTextSecondary,+ },+ grid: {+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))',+ gap: '16px',+ },+ name: {+ overflow: 'hidden',+ fontSize: '14px',+ fontWeight: 600,+ color: cssVar.colorText,+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+});++const styles = libraryCardStyles;++interface LibraryCardProps {+ library: KnowledgeBaseItem;+ onOpen: (id: string) => void;+}++/** A library as a cover card: cover, name, description, visibility and last update. */+export const LibraryCard = memo<LibraryCardProps>(({ library, onOpen }) => {+ const { t } = useTranslation('file');++ return (+ <button type={'button'} {...stylex.props(styles.card)} onClick={() => onOpen(library.id)}>+ <LibraryCover cover={libraryCoverOf(library.settings)} height={88} seed={library.id} />+ <Flexbox gap={6} paddingBlock={12} paddingInline={14} width={'100%'}>+ <Flexbox horizontal align={'center'} gap={6}>+ <LibraryStatusIcon+ memberRestricted={(library as { memberRestricted?: boolean }).memberRestricted}+ size={16}+ visibility={library.visibility}+ />+ <span {...stylex.props(styles.name)}>{library.name}</span>+ </Flexbox>+ <div {...stylex.props(styles.description)}>+ {library.description || t('docs.library.noDescription')}+ </div>+ <Text fontSize={12} type={'secondary'}>+ {t('docs.library.updatedAt', { time: dayjs(library.updatedAt).fromNow() })}+ </Text>+ </Flexbox>+ </button>+ );+});++LibraryCard.displayName = 'LibraryCard';++interface CreateLibraryCardProps {+ disabled?: boolean;+ onCreate: () => void;+}++export const CreateLibraryCard = memo<CreateLibraryCardProps>(({ disabled, onCreate }) => {+ const { t } = useTranslation('file');++ return (+ <button+ disabled={disabled}+ type={'button'}+ {...stylex.props(styles.createCard)}+ onClick={onCreate}+ >+ <Icon icon={PlusIcon} size={20} />+ {t('library.new')}+ </button>+ );+});++CreateLibraryCard.displayName = 'CreateLibraryCard';diff --git a/src/features/LibraryGallery/index.tsx b/src/features/LibraryGallery/index.tsxnew file mode 100644index 00000000000..88c6bc08f53--- /dev/null+++ b/src/features/LibraryGallery/index.tsx@@ -0,0 +1,131 @@+'use client';++import { Button, cssVar, Empty, Flexbox } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';+import { LibraryBigIcon, PlusIcon } from 'lucide-react';+import { memo, useLayoutEffect } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncBoundary from '@/components/AsyncBoundary';+import {+ RESOURCE_HOME_SECTIONS,+ ResourceSectionSkeleton,+} from '@/components/Skeleton/ResourceHome';+import { useCreateNewModal } from '@/features/LibraryModal';+import NavHeader from '@/features/NavHeader';+import { useResourceManagerStore } from '@/features/ResourceManager/store';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { usePermission } from '@/hooks/usePermission';+import { knowledgeBaseSelectors, useKnowledgeBaseStore } from '@/store/library';++import { CreateLibraryCard, LibraryCard, libraryCardStyles } from './LibraryCard';++const styles = stylex.create({+ content: {+ width: '100%',+ maxWidth: '1200px',+ marginInline: 'auto',+ paddingBlockStart: '32px',+ paddingBlockEnd: '64px',+ paddingInline: '32px',+ },+ scroll: {+ overflowX: 'hidden',+ overflowY: 'auto',+ flex: '1',+ },+});++/**+ * Every library of the current Docs mode as a cover card — the library index.+ * The sidebar keeps only the few opened most recently.+ */+const LibraryGallery = memo(() => {+ const { t } = useTranslation('file');+ const navigate = useWorkspaceAwareNavigate();+ const { allowed: canCreate, reason } = usePermission('create_content');+ const { open: openCreateLibrary } = useCreateNewModal();+ const setLibraryId = useResourceManagerStore((s) => s.setLibraryId);+ // Coming back from a library, its id must not keep scoping uploads and lists.+ useLayoutEffect(() => {+ setLibraryId(undefined);+ }, [setLibraryId]);++ // Same surface as the sidebar: the Private / Workspace mode narrows the list.+ const listVisibility = useResourceManagerStore((s) => s.listVisibility);+ const visibility = listVisibility === 'private' ? ('private' as const) : ('public' as const);+ const useFetchKnowledgeBaseList = useKnowledgeBaseStore((s) => s.useFetchKnowledgeBaseList);+ const { error, isHydrated, revalidate } = useFetchKnowledgeBaseList(visibility);+ const data = useKnowledgeBaseStore(knowledgeBaseSelectors.getKnowledgeBaseList(visibility));++ const openLibrary = (id: string) => {+ setLibraryId(id);+ navigate(`/resource/library/${id}`);+ };++ const handleCreate = () => {+ if (!canCreate) return;+ openCreateLibrary({ onSuccess: openLibrary });+ };++ return (+ <Flexbox height={'100%'}>+ <NavHeader+ left={<Flexbox style={{ marginLeft: 8 }}>{t('docs.section.library')}</Flexbox>}+ style={{ borderBottom: `1px solid ${cssVar.colorBorderSecondary}` }}+ right={+ <Button+ disabled={!canCreate}+ icon={PlusIcon}+ size={'small'}+ title={canCreate ? undefined : reason}+ onClick={handleCreate}+ >+ {t('library.new')}+ </Button>+ }+ />+ <div {...stylex.props(styles.scroll)}>+ <div {...stylex.props(styles.content)}>+ <AsyncBoundary+ data={data}+ error={error}+ isEmpty={data?.length === 0}+ isLoading={!data && (!isHydrated || !error)}+ loading={<ResourceSectionSkeleton {...RESOURCE_HOME_SECTIONS.libraries} />}+ empty={+ <Empty+ description={t('docs.library.emptyDesc')}+ icon={LibraryBigIcon}+ title={t('docs.library.emptyTitle')}+ action={+ <Button+ disabled={!canCreate}+ icon={PlusIcon}+ size={'middle'}+ type={'primary'}+ onClick={handleCreate}+ >+ {t('library.new')}+ </Button>+ }+ />+ }+ onRetry={() => revalidate()}+ >+ <div {...stylex.props(libraryCardStyles.grid)}>+ {data?.map((library) => (+ <LibraryCard key={library.id} library={library} onOpen={openLibrary} />+ ))}+ <CreateLibraryCard disabled={!canCreate} onCreate={handleCreate} />+ </div>+ </AsyncBoundary>+ </div>+ </div>+ </Flexbox>+ );+});++LibraryGallery.displayName = 'LibraryGallery';++export default LibraryGallery;diff --git a/src/features/LibraryModal/CreateNew/CreateForm.tsx b/src/features/LibraryModal/CreateNew/CreateForm.tsxindex 5fec52f68cd..88ab5cbbee3 100644--- a/src/features/LibraryModal/CreateNew/CreateForm.tsx+++ b/src/features/LibraryModal/CreateNew/CreateForm.tsx@@ -3,13 +3,15 @@ import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';+import { defaultCoverPreset, presetCoverValue } from '@/features/LibraryCover';+import CoverPicker from '@/features/LibraryCover/CoverPicker';import { useResourceManagerStore } from '@/features/ResourceManager/store';import { buildLibraryPath } from '@/features/ResourceManager/utils/resourcePath';import { useKnowledgeBaseStore } from '@/store/library';interface CreateFormProps {id?: string;- initialValues?: { name?: string; description?: string };+ initialValues?: { cover?: string; description?: string; name?: string };onClose?: () => void;onSuccess?: (id: string) => void;}@@ -19,6 +21,11 @@ const CreateForm = memo<CreateFormProps>(({ id, initialValues, onClose, onSuccesconst [loading, setLoading] = useState(false);const [name, setName] = useState(initialValues?.name || '');const [description, setDescription] = useState(initialValues?.description || '');+ // A new library has no id yet; a per-form seed keeps the previewed default+ // cover identical to the one it is created with.+ const [draftSeed] = useState(() => id ?? `draft-${Math.random().toString(36).slice(2)}`);+ const [cover, setCover] = useState<string | null>(initialValues?.cover ?? null);+ const updateKnowledgeBaseCover = useKnowledgeBaseStore((s) => s.updateKnowledgeBaseCover);const createNewKnowledgeBase = useKnowledgeBaseStore((s) => s.createNewKnowledgeBase);const updateKnowledgeBase = useKnowledgeBaseStore((s) => s.updateKnowledgeBase);// Derive KB visibility from the current sidebar mode: "private space" →@@ -48,11 +55,13 @@ const CreateForm = memo<CreateFormProps>(({ id, initialValues, onClose, onSucces// library private just because its description was edited from the// Private tab. Publish / make-private have their own guarded entries.await updateKnowledgeBase(id, values);+ if (cover !== (initialValues?.cover ?? null)) await updateKnowledgeBaseCover(id, cover);setLoading(false);onClose?.();} else {const newId = await createNewKnowledgeBase({...values,+ cover: cover ?? presetCoverValue(defaultCoverPreset(draftSeed).id),visibility: listVisibility === 'private' ? ('private' as const) : ('public' as const),});setLoading(false);@@ -90,6 +99,10 @@ const CreateForm = memo<CreateFormProps>(({ id, initialValues, onClose, onSuccesonChange={(e) => setDescription(e.target.value)}/></Flexbox>+ <Flexbox gap={8}>+ <label style={{ fontSize: 14 }}>{t('createNew.cover.label')}</label>+ <CoverPicker seed={draftSeed} value={cover} onChange={setCover} />+ </Flexbox><Button block loading={loading} type={'primary'} onClick={handleSubmit}>{isEditMode ? t('createNew.edit.confirm') : t('createNew.confirm')}</Button>diff --git a/src/features/LibraryModal/CreateNew/index.tsx b/src/features/LibraryModal/CreateNew/index.tsxindex 0b62dd912f2..d65cdf98595 100644--- a/src/features/LibraryModal/CreateNew/index.tsx+++ b/src/features/LibraryModal/CreateNew/index.tsx@@ -6,7 +6,7 @@ import CreateForm from './CreateForm';interface ModalContentProps {id?: string;- initialValues?: { name?: string; description?: string };+ initialValues?: { cover?: string; description?: string; name?: string };onSuccess?: (id: string) => void;}@@ -20,7 +20,7 @@ ModalContent.displayName = 'KnowledgeBaseCreateModalContent';interface OpenParams {id?: string;- initialValues?: { name?: string; description?: string };+ initialValues?: { cover?: string; description?: string; name?: string };onSuccess?: (id: string) => void;}diff --git a/src/features/NavPanel/routeKey.test.ts b/src/features/NavPanel/routeKey.test.tsindex a6461c3b717..a237e93e6e1 100644--- a/src/features/NavPanel/routeKey.test.ts+++ b/src/features/NavPanel/routeKey.test.ts@@ -18,7 +18,10 @@ describe('resolveNavPanelKey', () => {['/lobe-team/settings/general', 'lobe-team', 'workspace-settings'],['/lobe-team/community', 'lobe-team', 'discover'],['/lobe-team/resource', 'lobe-team', 'resource'],- ['/lobe-team/resource/library', 'lobe-team', 'resourceLibrary'],+ // The library gallery keeps the Docs sidebar; one library has its own.+ ['/lobe-team/resource/library', 'lobe-team', 'resource'],+ ['/lobe-team/resource/library/kb-1', 'lobe-team', 'resourceLibrary'],+ ['/resource/library/kb-1/folder', null, 'resourceLibrary'],['/lobe-team/memory', 'lobe-team', 'memory'],['/lobe-team/eval', 'lobe-team', 'eval'],['/lobe-team/eval/bench/benchmark-1', 'lobe-team', 'evalBench'],diff --git a/src/features/NavPanel/routeKey.ts b/src/features/NavPanel/routeKey.tsindex 94353d1beb6..49d0cce7745 100644--- a/src/features/NavPanel/routeKey.ts+++ b/src/features/NavPanel/routeKey.ts@@ -46,7 +46,9 @@ export const resolveNavPanelKey = (}case 'resource': {- return childSegment === 'library' ? 'resourceLibrary' : 'resource';+ // `/resource/library` is the library gallery under the Docs sidebar; only+ // a concrete library (`/resource/library/:id`) owns the library sidebar.+ return childSegment === 'library' && grandchildSegment ? 'resourceLibrary' : 'resource';}case 'video': {diff --git a/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.test.tsx b/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.test.tsxindex 7915351ed4f..ba0d65ceab0 100644--- a/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.test.tsx+++ b/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.test.tsx@@ -121,6 +121,55 @@ describe('Page list item dropdown menu', () => {});});+ it('stops a menu click from reaching the row that opened it', () => {+ // A page row is a link. If the menu click keeps bubbling the row navigates,+ // which unmounts the inline rename field before it can be typed into.+ const toggleEditing = vi.fn();+ const { result } = renderHook(() => useDropdownMenu({ pageId: 'page-1', toggleEditing }));+ const rename = getMenuItem(result.current(), 'rename');++ const domEvent = { stopPropagation: vi.fn() };+ (rename?.onClick as unknown as (info: { domEvent: typeof domEvent }) => void)({ domEvent });++ expect(domEvent.stopPropagation).toHaveBeenCalledTimes(1);+ expect(toggleEditing).toHaveBeenCalledWith(true);+ });++ it('keeps the row click from firing for destructive menu actions too', () => {+ const { result } = renderHook(() =>+ useDropdownMenu({ pageId: 'page-1', toggleEditing: vi.fn() }),+ );++ for (const key of ['duplicate', 'delete']) {+ const domEvent = { stopPropagation: vi.fn() };+ const item = getMenuItem(result.current(), key);++ (item?.onClick as unknown as (info: { domEvent: typeof domEvent }) => void)({ domEvent });++ expect(domEvent.stopPropagation).toHaveBeenCalledTimes(1);+ }+ });++ it('keeps the row click from firing for injected transfer actions', () => {+ // Business builds hand these entries over with a plain `onClick`; they run+ // through the same wrapper so "Move" cannot navigate the row either.+ const transfer = vi.fn();+ useDocumentTransferMenuItemMock.mockReturnValueOnce([+ { key: 'move', label: 'Move', onClick: transfer },+ ] as never);++ const { result } = renderHook(() =>+ useDropdownMenu({ pageId: 'page-1', toggleEditing: vi.fn() }),+ );+ const move = getMenuItem(result.current(), 'move');+ const domEvent = { stopPropagation: vi.fn() };++ (move?.onClick as unknown as (info: { domEvent: typeof domEvent }) => void)({ domEvent });++ expect(domEvent.stopPropagation).toHaveBeenCalledTimes(1);+ expect(transfer).toHaveBeenCalledTimes(1);+ });+it('disables page management actions for workspace viewers', () => {permissionMock.create_content = false;permissionMock.edit_own_content = false;diff --git a/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.tsx b/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.tsxindex b147eed7dcc..9588861c4e3 100644--- a/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.tsx+++ b/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.tsx@@ -22,6 +22,41 @@ interface ActionProps {toggleEditing: (visible?: boolean) => void;}+/**+ * `DropdownMenu` / `ContextMenu` hand each item an `info` object carrying the+ * originating DOM event (the published `DropdownItem.onClick` type says+ * `MouseEventHandler`, the runtime contract does not).+ */+interface MenuClickInfo {+ domEvent?: { stopPropagation: () => void };+}++/**+ * A page row is itself a link, so a menu click that keeps bubbling runs the+ * row's own `onClick` and navigates away. That unmounts the row — and the inline+ * rename field with it — before anything can be typed, which is why "Rename"+ * appeared to do nothing. Close the handler over the row and stop the event.+ */+const stopRowClick =+ (run: () => void) =>+ (info?: MenuClickInfo) => {+ info?.domEvent?.stopPropagation();+ run();+ };++/**+ * Business builds inject their own transfer entries (Move to a library, …).+ * They arrive with the caller's plain `onClick`, so they have to go through the+ * same wrapper — otherwise choosing one of them still reaches the row link and+ * navigates away, which is the exact defect the local actions no longer have.+ */+const wrapMenuItems = (items: DropdownItem[] | undefined | null): DropdownItem[] =>+ (items ?? []).map((item) =>+ item && 'onClick' in item && typeof item.onClick === 'function'+ ? ({ ...item, onClick: stopRowClick(item.onClick as () => void) } as DropdownItem)+ : item,+ );+export const useDropdownMenu = ({ pageId, toggleEditing }: ActionProps): (() => DropdownItem[]) => {const { t } = useTranslation(['common', 'file']);@@ -129,11 +164,11 @@ export const useDropdownMenu = ({ pageId, toggleEditing }: ActionProps): (() =>icon: <Icon icon={PanelTop} />,key: 'openInNewTab',label: t('pageList.actions.openInNewTab', { ns: 'file' }),- onClick: () => {+ onClick: stopRowClick(() => {const url = buildWorkspaceAwarePath(`/page/${pageId}`, activeWorkspaceSlug);addTab(url);navigate(url, { escape: true });- },+ }),},{ type: 'divider' as const },]@@ -143,20 +178,20 @@ export const useDropdownMenu = ({ pageId, toggleEditing }: ActionProps): (() =>icon: <Icon icon={Pencil} />,key: 'rename',label: t('rename'),- onClick: () => {+ onClick: stopRowClick(() => {if (!canEditPage) return;toggleEditing(true);- },+ }),},{disabled: !canCreatePage,icon: <Icon icon={CopyPlus} />,key: 'duplicate',label: t('pageList.duplicate', { ns: 'file' }),- onClick: handleDuplicate,+ onClick: stopRowClick(handleDuplicate),},...(transferMenuItems && transferMenuItems.length > 0- ? [{ type: 'divider' as const }, ...transferMenuItems]+ ? [{ type: 'divider' as const }, ...wrapMenuItems(transferMenuItems)]: []),...(canPublish? [@@ -165,7 +200,7 @@ export const useDropdownMenu = ({ pageId, toggleEditing }: ActionProps): (() =>icon: <Icon icon={UsersIcon} />,key: 'publishToWorkspace',label: t('pageList.publishToWorkspace', { ns: 'file' }),- onClick: handlePublish,+ onClick: stopRowClick(handlePublish),},]: []),@@ -176,7 +211,7 @@ export const useDropdownMenu = ({ pageId, toggleEditing }: ActionProps): (() =>icon: <Icon icon={EyeOffIcon} />,key: 'makePrivate',label: t('makePrivate'),- onClick: handleMakePrivate,+ onClick: stopRowClick(handleMakePrivate),},]: []),@@ -187,7 +222,7 @@ export const useDropdownMenu = ({ pageId, toggleEditing }: ActionProps): (() =>icon: <Icon icon={Trash2} />,key: 'delete',label: t('delete'),- onClick: handleDelete,+ onClick: stopRowClick(handleDelete),},].filter(Boolean) as DropdownItem[],[diff --git a/src/features/Pages/PagesToDocsRedirect.tsx b/src/features/Pages/PagesToDocsRedirect.tsxnew file mode 100644index 00000000000..43e9c3e9126--- /dev/null+++ b/src/features/Pages/PagesToDocsRedirect.tsx@@ -0,0 +1,30 @@+'use client';++import { memo, useLayoutEffect } from 'react';+import { useLocation, useParams } from 'react-router';++import { docsPagePath, RESOURCE_HOME_PATH } from '@/features/ResourceHome/paths';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { getIdFromIdentifier } from '@/utils/identifier';++/**+ * Pages live in Docs now: `/page` lands on the Docs home and `/page/:id` opens+ * the page inside Docs. Every existing link (recents, search, mentions, shares)+ * keeps working through this redirect; the query string is carried along.+ */+const PagesToDocsRedirect = memo(() => {+ const { id } = useParams<{ id?: string }>();+ const { search } = useLocation();+ const navigate = useWorkspaceAwareNavigate();++ useLayoutEffect(() => {+ const target = id ? docsPagePath(getIdFromIdentifier(id, 'docs')) : RESOURCE_HOME_PATH;+ navigate(`${target}${search}`, { replace: true });+ }, [id, navigate, search]);++ return null;+});++PagesToDocsRedirect.displayName = 'PagesToDocsRedirect';++export default PagesToDocsRedirect;diff --git a/src/features/ResourceHome/Home/HomeList.tsx b/src/features/ResourceHome/Home/HomeList.tsxnew file mode 100644index 00000000000..acb4ef43a1c--- /dev/null+++ b/src/features/ResourceHome/Home/HomeList.tsx@@ -0,0 +1,265 @@+'use client';++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 { memo, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import AsyncBoundary from '@/components/AsyncBoundary';+import FileIcon from '@/components/FileIcon';+import LibIcon from '@/components/LibIcon';+import SkeletonBar from '@/components/Skeleton/Bar';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useHomeStore } from '@/store/home';+import type { DocsHomeRow, DocsHomeTab } from '@/store/home/slices/recent/projection';+import { homeRecentSelectors } from '@/store/home/slices/recent/selectors';+import { knowledgeBaseSelectors, useKnowledgeBaseStore } from '@/store/library';+import { useUserStore } from '@/store/user';+import { userProfileSelectors } from '@/store/user/slices/auth/selectors';++import { docsFilePath, docsPagePath } from '../paths';++/** Title, location, owner, created, updated — the time columns stay fixed-width. */+const COLUMNS = 'minmax(0, 3fr) minmax(0, 1.4fr) minmax(0, 1.1fr) 132px 132px';++const styles = stylex.create({+ cell: {+ overflow: 'hidden',+ minWidth: 0,+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ header: {+ display: 'grid',+ gridTemplateColumns: COLUMNS,+ gap: '16px',+ paddingBlock: '8px',+ paddingInline: '12px',+ borderBlockEndWidth: '1px',+ borderBlockEndStyle: 'solid',+ borderBlockEndColor: cssVar.colorBorderSecondary,+ fontSize: '12px',+ color: cssVar.colorTextTertiary,+ },+ meta: {+ fontSize: '13px',+ color: cssVar.colorTextSecondary,+ },+ name: {+ fontSize: '14px',+ color: cssVar.colorText,+ },+ row: {+ cursor: 'pointer',+ display: 'grid',+ gridTemplateColumns: COLUMNS,+ gap: '16px',+ alignItems: 'center',+ width: '100%',+ paddingBlock: '10px',+ paddingInline: '12px',+ borderWidth: 0,+ borderBlockEndWidth: '1px',+ borderBlockEndStyle: 'solid',+ borderBlockEndColor: cssVar.colorBorderSecondary,+ textAlign: 'start',+ backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillQuaternary },+ },+ tab: {+ cursor: 'pointer',+ paddingBlock: '6px',+ paddingInline: 0,+ borderWidth: 0,+ borderBlockEndWidth: '2px',+ borderBlockEndStyle: 'solid',+ borderBlockEndColor: 'transparent',+ fontSize: '14px',+ color: { 'default': cssVar.colorTextSecondary, ':hover': cssVar.colorText },+ backgroundColor: 'transparent',+ },+ tabActive: {+ borderBlockEndColor: cssVar.colorPrimary,+ fontWeight: 500,+ color: { 'default': cssVar.colorPrimary, ':hover': cssVar.colorPrimary },+ },+});++const formatTime = (value: Date | string) => {+ const date = dayjs(value);+ if (date.isSame(dayjs(), 'day')) return date.format('HH:mm');+ return date.isSame(dayjs(), 'year') ? date.format('MM-DD HH:mm') : date.format('YYYY-MM-DD');+};++interface LocationProps {+ libraryNames: Map<string, string>;+ myId?: string;+ row: DocsHomeRow;+}++/** Where the row lives: its knowledge base, else the drive (files) or a page section. */+const Location = memo<LocationProps>(({ libraryNames, myId, row }) => {+ const { t } = useTranslation('file');+ const names = row.knowledgeBaseIds.flatMap((id) => libraryNames.get(id) ?? []);++ if (row.knowledgeBaseIds.length > 0) {+ return (+ <Flexbox horizontal align={'center'} gap={6} {...stylex.props(styles.cell, styles.meta)}>+ <LibIcon size={14} />+ <span {...stylex.props(styles.cell)}>+ {names.length > 0 ? names.join(', ') : t('docs.section.library')}+ </span>+ </Flexbox>+ );+ }++ const [icon, label] =+ row.kind === 'file'+ ? [HardDriveIcon, t('docs.section.drive')]+ : row.userId && myId && row.userId !== myId+ ? [UsersIcon, t('docs.shared.title')]+ : [FolderOpenIcon, t('docs.myDocs.title')];++ return (+ <Flexbox horizontal align={'center'} gap={6} {...stylex.props(styles.cell, styles.meta)}>+ <Icon icon={icon} size={14} />+ <span {...stylex.props(styles.cell)}>{label}</span>+ </Flexbox>+ );+});++Location.displayName = 'DocsHomeLocation';++const TABS: DocsHomeTab[] = ['recent', 'mine', 'shared'];++interface HomeListProps {+ onTabChange: (tab: DocsHomeTab) => void;+ tab: DocsHomeTab;+}++/**+ * The Docs home list: pages and files together, newest update first, with+ * where each one lives and who owns it. Pages and files both open inside Docs+ * (`/resource/page/:id`, `/resource/file/:id`).+ */+const HomeList = memo<HomeListProps>(({ onTabChange, tab }) => {+ const { t } = useTranslation('file');+ const navigate = useWorkspaceAwareNavigate();+ const workspaceId = useActiveWorkspaceId();+ const myId = useUserStore(userProfileSelectors.userId);++ const { error, revalidate } = useHomeStore((s) => s.useFetchDocsHome)(tab);+ const rows = useHomeStore(homeRecentSelectors.docsHome(tab));++ const useFetchKnowledgeBaseList = useKnowledgeBaseStore((s) => s.useFetchKnowledgeBaseList);+ useFetchKnowledgeBaseList();+ const libraries = useKnowledgeBaseStore(knowledgeBaseSelectors.getKnowledgeBaseList());+ const libraryNames = useMemo(+ () => new Map((libraries ?? []).map((library) => [library.id, library.name])),+ [libraries],+ );++ // "Shared with me" only means something inside a workspace.+ const tabs = workspaceId ? TABS : TABS.filter((key) => key !== 'shared');++ const open = (row: DocsHomeRow) =>+ navigate(row.kind === 'page' ? docsPagePath(row.id) : docsFilePath(row.id));++ return (+ <Flexbox gap={12}>+ <Flexbox horizontal gap={24} role={'tablist'}>+ {tabs.map((key) => (+ <button+ aria-selected={tab === key}+ key={key}+ role={'tab'}+ type={'button'}+ {...stylex.props(styles.tab, tab === key && styles.tabActive)}+ onClick={() => onTabChange(key)}+ >+ {t(`docs.home.tabs.${key}`)}+ </button>+ ))}+ </Flexbox>++ <div>+ <div {...stylex.props(styles.header)}>+ <span>{t('docs.home.columns.title')}</span>+ <span>{t('docs.home.columns.location')}</span>+ <span>{t('docs.home.columns.owner')}</span>+ <span>{t('docs.home.columns.createdAt')}</span>+ <span>{t('docs.home.columns.updatedAt')}</span>+ </div>+ <AsyncBoundary+ data={rows}+ error={error}+ errorVariant={'inline'}+ isEmpty={rows?.length === 0}+ isLoading={rows === undefined && !error}+ empty={+ <Empty+ description={t(`docs.home.empty.${tab}`)}+ icon={FileTextIcon}+ style={{ paddingBlock: 48 }}+ />+ }+ loading={+ <Flexbox gap={8} paddingBlock={12}>+ {Array.from({ length: 6 }).map((_, index) => (+ <SkeletonBar height={36} key={index} />+ ))}+ </Flexbox>+ }+ onRetry={() => revalidate()}+ >+ {rows?.map((row) => (+ <button+ key={row.id}+ type={'button'}+ {...stylex.props(styles.row)}+ onClick={() => open(row)}+ >+ <Flexbox horizontal align={'center'} gap={10} {...stylex.props(styles.cell)}>+ {row.kind === 'page' ? (+ row.emoji ? (+ <Avatar avatar={row.emoji} size={20} />+ ) : (+ <Icon icon={FileTextIcon} size={18} />+ )+ ) : (+ <FileIcon fileName={row.name} fileType={row.fileType} size={20} />+ )}+ <span {...stylex.props(styles.cell, styles.name)}>+ {row.name || t('pageList.untitled')}+ </span>+ </Flexbox>+ <Location libraryNames={libraryNames} myId={myId} row={row} />+ <Flexbox+ horizontal+ align={'center'}+ gap={6}+ {...stylex.props(styles.cell, styles.meta)}+ >+ {row.owner && (+ <>+ <Avatar avatar={row.owner.avatar || row.owner.name} size={18} />+ <span {...stylex.props(styles.cell)}>{row.owner.name}</span>+ </>+ )}+ </Flexbox>+ <span {...stylex.props(styles.meta)}>{formatTime(row.createdAt)}</span>+ <span {...stylex.props(styles.meta)}>{formatTime(row.updatedAt)}</span>+ </button>+ ))}+ </AsyncBoundary>+ </div>+ </Flexbox>+ );+});++HomeList.displayName = 'DocsHomeList';++export default HomeList;diff --git a/src/features/ResourceHome/Home/Libraries.tsx b/src/features/ResourceHome/Home/Libraries.tsxdeleted file mode 100644index 0e603cc310a..00000000000--- a/src/features/ResourceHome/Home/Libraries.tsx+++ /dev/null@@ -1,180 +0,0 @@-'use client';--import { createStaticStyles, Flexbox, Icon } from '@lobehub/ui';-import { PlusIcon } from 'lucide-react';-import { memo } from 'react';-import { useTranslation } from 'react-i18next';--import AsyncError from '@/components/AsyncError';-import LibraryStatusIcon from '@/components/LibIcon/StatusIcon';-import {- RESOURCE_HOME_SECTIONS,- ResourceSectionSkeleton,-} from '@/components/Skeleton/ResourceHome';-import { useCreateNewModal } from '@/features/LibraryModal';-import { useResourceManagerStore } from '@/features/ResourceManager/store';-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { usePermission } from '@/hooks/usePermission';-import { knowledgeBaseSelectors, useKnowledgeBaseStore } from '@/store/library';--import { getLibraryListAsyncState } from '../Layout/Body/LibraryList/state';-import SectionTitle from './SectionTitle';--const styles = createStaticStyles(({ css, cssVar }) => ({- chip: css`- cursor: pointer;-- display: flex;- gap: 10px;- align-items: center;-- min-width: 0;- padding-block: 14px;- padding-inline: 16px;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadiusLG};-- text-align: start;-- background: ${cssVar.colorFillQuaternary};-- transition: all 0.2s ${cssVar.motionEaseInOut};-- &:hover {- border-color: ${cssVar.colorBorder};- background: ${cssVar.colorFillTertiary};- }- `,- createChip: css`- cursor: pointer;-- display: flex;- gap: 8px;- align-items: center;- justify-content: center;-- padding-block: 14px;- padding-inline: 16px;- border: 1px dashed ${cssVar.colorBorder};- border-radius: ${cssVar.borderRadiusLG};-- color: ${cssVar.colorTextSecondary};-- background: transparent;-- transition: all 0.2s ${cssVar.motionEaseInOut};-- &:hover {- border-color: ${cssVar.colorTextQuaternary};- color: ${cssVar.colorText};- }-- &:disabled {- cursor: not-allowed;- opacity: 0.5;- }- `,- grid: css`- display: grid;- grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));- gap: 12px;- `,- name: css`- overflow: hidden;-- font-size: 13px;- font-weight: 500;- color: ${cssVar.colorText};- text-overflow: ellipsis;- white-space: nowrap;- `,-}));--/**- * How many libraries the quick-access row shows. The list is ordered by last- * update, so this is "the ones you are working in"; the sidebar stays the full- * index, which is why the home page must not repeat every library here.- */-const MAX_LIBRARIES = 9;--/**- * Quick access to the user's libraries — the everyday entry point of the- * library home, and the page's only library list.- */-const Libraries = memo(() => {- const { t } = useTranslation('file');- const navigate = useWorkspaceAwareNavigate();- const { allowed: canCreate } = usePermission('create_content');-- const listVisibility = useResourceManagerStore((s) => s.listVisibility);- const visibility = listVisibility === 'private' ? ('private' as const) : ('public' as const);-- const useFetchKnowledgeBaseList = useKnowledgeBaseStore((s) => s.useFetchKnowledgeBaseList);- const { error, isHydrated, isValidating, revalidate } = useFetchKnowledgeBaseList(visibility);- // The rows are read from the replica view; the hook only orchestrates fetching.- const data = useKnowledgeBaseStore(knowledgeBaseSelectors.getKnowledgeBaseList(visibility));- // A fresh scope has no persisted row yet, so `!isHydrated` keeps the skeleton- // up until the first local read completes and the network sync lands.- const { isLoading: showSkeleton } = getLibraryListAsyncState({- data,- isLoading: !isHydrated,- isValidating,- });-- const setLibraryId = useResourceManagerStore((s) => s.setLibraryId);- const { open: openCreateLibrary } = useCreateNewModal();-- const handleCreate = () => {- if (!canCreate) return;- openCreateLibrary({- onSuccess: (id) => {- navigate(`/resource/library/${id}`);- },- });- };-- return (- <Flexbox gap={12}>- <SectionTitle title={t('home.libraries')} />- {error && !data?.length ? (- <AsyncError error={error} variant={'inline'} onRetry={() => void revalidate()} />- ) : showSkeleton ? (- <ResourceSectionSkeleton {...RESOURCE_HOME_SECTIONS.libraries} />- ) : (- <div className={styles.grid}>- {data?.slice(0, MAX_LIBRARIES).map((item) => (- <button- className={styles.chip}- key={item.id}- type={'button'}- onClick={() => {- setLibraryId(item.id);- navigate(`/resource/library/${item.id}`);- }}- >- <LibraryStatusIcon- memberRestricted={(item as { memberRestricted?: boolean }).memberRestricted}- size={18}- visibility={item.visibility}- />- <span className={styles.name}>{item.name}</span>- </button>- ))}- <button- className={styles.createChip}- disabled={!canCreate}- type={'button'}- onClick={handleCreate}- >- <Icon icon={PlusIcon} size={16} />- {t('home.uploadEntries.library.title')}- </button>- </div>- )}- </Flexbox>- );-});--Libraries.displayName = 'Libraries';--export default Libraries;diff --git a/src/features/ResourceHome/Home/QuickActions.tsx b/src/features/ResourceHome/Home/QuickActions.tsxnew file mode 100644index 00000000000..a82925f7c06--- /dev/null+++ b/src/features/ResourceHome/Home/QuickActions.tsx@@ -0,0 +1,167 @@+'use client';++import { Icon, toast } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { FilePlus2Icon, LibraryBigIcon, type LucideIcon, UploadIcon } from 'lucide-react';+import { memo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useCreateNewModal } from '@/features/LibraryModal';+import { useTopLevelFileUpload } from '@/features/ResourceManager/hooks/useTopLevelFileUpload';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { usePermission } from '@/hooks/usePermission';+import { pageActions } from '@/store/page';++import { docsPagePath } from '../paths';++const styles = stylex.create({+ action: {+ cursor: { 'default': 'pointer', ':disabled': 'not-allowed' },+ display: 'flex',+ gap: '12px',+ alignItems: 'center',+ paddingBlock: '14px',+ paddingInline: '16px',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: { 'default': cssVar.colorBorderSecondary, ':hover': cssVar.colorBorder },+ borderRadius: cssVar.borderRadiusLG,+ textAlign: 'start',+ backgroundColor: { 'default': cssVar.colorBgContainer, ':hover': cssVar.colorFillQuaternary },+ opacity: { 'default': 1, ':disabled': 0.5 },+ transitionProperty: 'border-color, background-color',+ transitionDuration: '0.2s',+ transitionTimingFunction: cssVar.motionEaseInOut,+ },+ desc: {+ fontSize: '12px',+ color: cssVar.colorTextTertiary,+ },+ grid: {+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))',+ gap: '12px',+ },+ icon: {+ display: 'flex',+ flex: 'none',+ alignItems: 'center',+ justifyContent: 'center',+ width: '36px',+ height: '36px',+ borderRadius: cssVar.borderRadius,+ color: cssVar.colorPrimary,+ backgroundColor: cssVar.colorPrimaryBg,+ },+ title: {+ fontSize: '14px',+ fontWeight: 500,+ color: cssVar.colorText,+ },+});++interface ActionProps {+ desc: string;+ disabled?: boolean;+ icon: LucideIcon;+ loading?: boolean;+ onClick: () => void;+ title: string;+}++const Action = memo<ActionProps>(({ desc, disabled, icon, loading, onClick, title }) => (+ <button+ disabled={disabled || loading}+ type={'button'}+ {...stylex.props(styles.action)}+ onClick={onClick}+ >+ <span {...stylex.props(styles.icon)}>+ <Icon icon={icon} size={18} spin={loading && icon === UploadIcon} />+ </span>+ <span>+ <div {...stylex.props(styles.title)}>{title}</div>+ <div {...stylex.props(styles.desc)}>{desc}</div>+ </span>+ </button>+));++Action.displayName = 'QuickAction';++interface QuickActionsProps {+ /** Called once a page or file lands, so the list below can refresh. */+ onCreated?: () => void;+}++/** The three ways to add something to Docs: write, upload, organize. */+const QuickActions = memo<QuickActionsProps>(({ onCreated }) => {+ const { t } = useTranslation('file');+ const navigate = useWorkspaceAwareNavigate();+ const { allowed: canCreate, reason } = usePermission('create_content');+ const upload = useTopLevelFileUpload();+ const { open: openCreateLibrary } = useCreateNewModal();+ const inputRef = useRef<HTMLInputElement>(null);+ const [creatingPage, setCreatingPage] = useState(false);++ const createPage = async () => {+ setCreatingPage(true);+ try {+ const page = await pageActions.createPage({ title: t('pageList.untitled') });+ navigate(docsPagePath(page.id));+ void pageActions.refreshDocuments();+ onCreated?.();+ } catch (error) {+ console.error('[QuickActions] failed to create a page:', error);+ toast.error(t('operationFailed', { ns: 'common' }));+ } finally {+ setCreatingPage(false);+ }+ };++ return (+ <div {...stylex.props(styles.grid)} title={canCreate ? undefined : reason}>+ <Action+ desc={t('docs.home.quick.newPage.desc')}+ disabled={!canCreate}+ icon={FilePlus2Icon}+ loading={creatingPage}+ title={t('docs.home.quick.newPage.title')}+ onClick={createPage}+ />+ <Action+ desc={t('docs.home.quick.upload.desc')}+ disabled={!canCreate}+ icon={UploadIcon}+ title={t('docs.home.quick.upload.title')}+ onClick={() => inputRef.current?.click()}+ />+ <Action+ desc={t('docs.home.quick.newKnowledgeBase.desc')}+ disabled={!canCreate}+ icon={LibraryBigIcon}+ title={t('docs.home.quick.newKnowledgeBase.title')}+ onClick={() =>+ openCreateLibrary({ onSuccess: (id) => navigate(`/resource/library/${id}`) })+ }+ />+ <input+ multiple+ ref={inputRef}+ style={{ display: 'none' }}+ type={'file'}+ onChange={async (e) => {+ const files = [...(e.target.files ?? [])];+ e.target.value = '';+ if (files.length === 0) return;+ await upload(files);+ onCreated?.();+ }}+ />+ </div>+ );+});++QuickActions.displayName = 'QuickActions';++export default QuickActions;diff --git a/src/features/ResourceHome/Home/RecentFiles.tsx b/src/features/ResourceHome/Home/RecentFiles.tsxdeleted file mode 100644index bd7db2ab245..00000000000--- a/src/features/ResourceHome/Home/RecentFiles.tsx+++ /dev/null@@ -1,149 +0,0 @@-'use client';--import { createStaticStyles, Flexbox } from '@lobehub/ui';-import dayjs from 'dayjs';-import { memo } from 'react';-import { useTranslation } from 'react-i18next';--import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';-import AsyncError from '@/components/AsyncError';-import FileIcon from '@/components/FileIcon';-import {- RESOURCE_HOME_SECTIONS,- ResourceSectionSkeleton,-} from '@/components/Skeleton/ResourceHome';-import { useResourceManagerStore } from '@/features/ResourceManager/store';-import { getResourceQueryVisibility } from '@/features/ResourceManager/store/selectors';-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { useHomeStore } from '@/store/home';-import { homeRecentSelectors } from '@/store/home/selectors';-import { FilesTabs } from '@/types/files';--import SectionTitle from './SectionTitle';--const styles = createStaticStyles(({ css, cssVar }) => ({- card: css`- cursor: pointer;-- overflow: hidden;- display: flex;- flex-direction: column;-- padding: 0;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadiusLG};-- text-align: start;-- background: ${cssVar.colorBgContainer};-- transition: all 0.2s ${cssVar.motionEaseInOut};-- &:hover {- border-color: ${cssVar.colorBorder};- box-shadow: ${cssVar.boxShadowTertiary};- }- `,- grid: css`- display: grid;- grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));- gap: 12px;- `,- meta: css`- font-size: 12px;- color: ${cssVar.colorTextQuaternary};- `,- name: css`- overflow: hidden;-- font-size: 13px;- font-weight: 500;- color: ${cssVar.colorText};- text-overflow: ellipsis;- white-space: nowrap;- `,- preview: css`- display: flex;- align-items: center;- justify-content: center;-- aspect-ratio: 16 / 10;- width: 100%;- border-block-end: 1px solid ${cssVar.colorBorderSecondary};-- background: ${cssVar.colorFillQuaternary};- `,- thumbnail: css`- width: 100%;- height: 100%;- object-fit: cover;- `,-}));--const formatTime = (date: Date | string) =>- dayjs().diff(dayjs(date), 'd') < 7 ? dayjs(date).fromNow() : dayjs(date).format('YYYY-MM-DD');--const RecentFiles = memo(() => {- const { t } = useTranslation('file');- const navigate = useWorkspaceAwareNavigate();- const workspaceId = useActiveWorkspaceId();- const listVisibility = useResourceManagerStore((s) => s.listVisibility);- const visibility = workspaceId- ? getResourceQueryVisibility(undefined, listVisibility)- : undefined;-- // A replica partitioned by user + workspace: a reload paints the last cards- // from the local copy while the server confirms them.- const { error, isValidating, revalidate } = useHomeStore((s) => s.useFetchResourceRecentFiles)({- visibility,- });- const data = useHomeStore(homeRecentSelectors.resourceFiles({ visibility }));- const isLoading = data === undefined && !error;-- if (!isLoading && !error && !data?.length) return null;-- return (- <Flexbox gap={12}>- <SectionTitle- loading={isValidating && !!data?.length}- title={t('home.recentFiles')}- viewAllUrl={`/resource/${FilesTabs.All}`}- />- {error && !data?.length ? (- <AsyncError error={error} variant={'inline'} onRetry={() => void revalidate()} />- ) : isLoading ? (- <ResourceSectionSkeleton {...RESOURCE_HOME_SECTIONS.files} />- ) : (- <div className={styles.grid}>- {data?.map((item) => {- const isImage = item.fileType?.startsWith('image');- return (- <button- className={styles.card}- key={item.id}- type={'button'}- onClick={() => navigate(`/resource?file=${item.id}`)}- >- <div className={styles.preview}>- {isImage && item.url ? (- <img alt={item.name} className={styles.thumbnail} src={item.url} />- ) : (- <FileIcon fileName={item.name} fileType={item.fileType} size={40} />- )}- </div>- <Flexbox gap={4} padding={12}>- <span className={styles.name}>{item.name}</span>- <span className={styles.meta}>{formatTime(item.createdAt)}</span>- </Flexbox>- </button>- );- })}- </div>- )}- </Flexbox>- );-});--RecentFiles.displayName = 'RecentFiles';--export default RecentFiles;diff --git a/src/features/ResourceHome/Home/RecentPages.tsx b/src/features/ResourceHome/Home/RecentPages.tsxdeleted file mode 100644index 27731995e19..00000000000--- a/src/features/ResourceHome/Home/RecentPages.tsx+++ /dev/null@@ -1,135 +0,0 @@-'use client';--import { createStaticStyles, Flexbox, Icon } from '@lobehub/ui';-import dayjs from 'dayjs';-import { FileTextIcon } from 'lucide-react';-import { memo } from 'react';-import { useTranslation } from 'react-i18next';--import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';-import AsyncError from '@/components/AsyncError';-import {- RESOURCE_HOME_SECTIONS,- ResourceSectionSkeleton,-} from '@/components/Skeleton/ResourceHome';-import { useResourceManagerStore } from '@/features/ResourceManager/store';-import { getResourceQueryVisibility } from '@/features/ResourceManager/store/selectors';-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { useHomeStore } from '@/store/home';-import { homeRecentSelectors } from '@/store/home/selectors';--import SectionTitle from './SectionTitle';--const styles = createStaticStyles(({ css, cssVar }) => ({- card: css`- cursor: pointer;-- display: flex;- gap: 12px;- align-items: center;-- padding-block: 12px;- padding-inline: 16px;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadiusLG};-- text-align: start;-- background: ${cssVar.colorBgContainer};-- transition: all 0.2s ${cssVar.motionEaseInOut};-- &:hover {- border-color: ${cssVar.colorBorder};- box-shadow: ${cssVar.boxShadowTertiary};- }- `,- emoji: css`- font-size: 20px;- line-height: 1;- `,- grid: css`- display: grid;- grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));- gap: 12px;- `,- meta: css`- font-size: 12px;- color: ${cssVar.colorTextQuaternary};- `,- title: css`- overflow: hidden;-- font-size: 13px;- font-weight: 500;- color: ${cssVar.colorText};- text-overflow: ellipsis;- white-space: nowrap;- `,-}));--const formatTime = (date: Date | string) =>- dayjs().diff(dayjs(date), 'd') < 7 ? dayjs(date).fromNow() : dayjs(date).format('YYYY-MM-DD');--const RecentPages = memo(() => {- const { t } = useTranslation('file');- const navigate = useWorkspaceAwareNavigate();- const workspaceId = useActiveWorkspaceId();- const listVisibility = useResourceManagerStore((s) => s.listVisibility);- const visibility = workspaceId- ? getResourceQueryVisibility(undefined, listVisibility)- : undefined;-- // A replica partitioned by user + workspace: a reload paints the last cards- // from the local copy while the server confirms them.- const { error, isValidating, revalidate } = useHomeStore((s) => s.useFetchResourceRecentPages)({- visibility,- });- const data = useHomeStore(homeRecentSelectors.resourcePages({ visibility }));- const isLoading = data === undefined && !error;-- if (!isLoading && !error && !data?.length) return null;-- return (- <Flexbox gap={12}>- <SectionTitle- loading={isValidating && !!data?.length}- title={t('home.recentPages')}- viewAllUrl={'/resource/page'}- />- {error && !data?.length ? (- <AsyncError error={error} variant={'inline'} onRetry={() => void revalidate()} />- ) : isLoading ? (- <ResourceSectionSkeleton {...RESOURCE_HOME_SECTIONS.pages} />- ) : (- <div className={styles.grid}>- {data?.map((item) => {- const { emoji } = item;- return (- <button- className={styles.card}- key={item.id}- type={'button'}- onClick={() => navigate(`/resource?file=${item.id}`)}- >- {emoji ? (- <span className={styles.emoji}>{emoji}</span>- ) : (- <Icon icon={FileTextIcon} size={20} />- )}- <Flexbox gap={2} style={{ minWidth: 0 }}>- <span className={styles.title}>{item.name}</span>- <span className={styles.meta}>{formatTime(item.updatedAt)}</span>- </Flexbox>- </button>- );- })}- </div>- )}- </Flexbox>- );-});--RecentPages.displayName = 'RecentPages';--export default RecentPages;diff --git a/src/features/ResourceHome/Home/RecentWorks.test.tsx b/src/features/ResourceHome/Home/RecentWorks.test.tsxdeleted file mode 100644index 5c313bfe2df..00000000000--- a/src/features/ResourceHome/Home/RecentWorks.test.tsx+++ /dev/null@@ -1,47 +0,0 @@-/**- * @vitest-environment happy-dom- */-import { render, screen } from '@testing-library/react';-import { describe, expect, it, vi } from 'vitest';--import RecentWorks from './RecentWorks';--const mocks = vi.hoisted(() => ({- openWork: vi.fn(),- reload: vi.fn(),-}));--vi.mock('react-i18next', () => ({- useTranslation: () => ({ t: (key: string) => key }),-}));--vi.mock('@/features/WorkGallery/hooks', () => ({- useWorkspaceWorksInfinite: () => ({- error: undefined,- isLoadingInitial: false,- items: [{ id: 'wk_1' }, { id: 'wk_2' }, { id: 'wk_3' }, { id: 'wk_4' }],- reload: mocks.reload,- }),-}));--vi.mock('@/features/WorkGallery/useOpenWork', () => ({- useOpenWork: () => mocks.openWork,-}));--vi.mock('@/features/WorkGallery/WorkPreviewCard', () => ({- default: ({ item }: { item: { id: string } }) => <div data-testid={`card-${item.id}`} />,-}));--vi.mock('./SectionTitle', () => ({- default: () => null,-}));--describe('RecentWorks', () => {- it('shows only the freshest three works', () => {- render(<RecentWorks />);-- expect(screen.getByTestId('card-wk_1')).toBeTruthy();- expect(screen.getByTestId('card-wk_3')).toBeTruthy();- expect(screen.queryByTestId('card-wk_4')).toBeNull();- });-});diff --git a/src/features/ResourceHome/Home/RecentWorks.tsx b/src/features/ResourceHome/Home/RecentWorks.tsxdeleted file mode 100644index bf5cdcde654..00000000000--- a/src/features/ResourceHome/Home/RecentWorks.tsx+++ /dev/null@@ -1,58 +0,0 @@-'use client';--import { createStaticStyles, Flexbox } from '@lobehub/ui';-import { memo } from 'react';-import { useTranslation } from 'react-i18next';--import AsyncError from '@/components/AsyncError';-import {- RESOURCE_HOME_SECTIONS,- ResourceSectionSkeleton,-} from '@/components/Skeleton/ResourceHome';-import { useWorkspaceWorksInfinite } from '@/features/WorkGallery/hooks';-import { useOpenWork } from '@/features/WorkGallery/useOpenWork';-import WorkPreviewCard from '@/features/WorkGallery/WorkPreviewCard';--import SectionTitle from './SectionTitle';--const styles = createStaticStyles(({ css }) => ({- grid: css`- display: grid;- grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));- gap: 12px;- `,-}));--/** The dashboard shows only the freshest works; the full gallery lives at /resource/works. */-const MAX_RECENT_WORKS = 3;--const RecentWorks = memo(() => {- const { t } = useTranslation('file');- const openWork = useOpenWork();-- const { error, items, isLoadingInitial, reload } = useWorkspaceWorksInfinite('all');- const recent = items.slice(0, MAX_RECENT_WORKS);-- if (!isLoadingInitial && !error && recent.length === 0) return null;-- return (- <Flexbox gap={12}>- <SectionTitle title={t('work.group')} viewAllUrl={'/resource/works'} />- {error && recent.length === 0 ? (- <AsyncError error={error} variant={'inline'} onRetry={reload} />- ) : isLoadingInitial ? (- <ResourceSectionSkeleton {...RESOURCE_HOME_SECTIONS.works} />- ) : (- <div className={styles.grid}>- {recent.map((item) => (- <WorkPreviewCard item={item} key={item.id} onOpen={openWork} />- ))}- </div>- )}- </Flexbox>- );-});--RecentWorks.displayName = 'RecentWorks';--export default RecentWorks;diff --git a/src/features/ResourceHome/Home/SectionTitle.tsx b/src/features/ResourceHome/Home/SectionTitle.tsxdeleted file mode 100644index 26242346508..00000000000--- a/src/features/ResourceHome/Home/SectionTitle.tsx+++ /dev/null@@ -1,61 +0,0 @@-'use client';--import { createStaticStyles, Flexbox, Spin } from '@lobehub/ui';-import { memo } from 'react';-import { useTranslation } from 'react-i18next';--import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';--const styles = createStaticStyles(({ css, cssVar }) => ({- title: css`- margin: 0;- font-size: 15px;- font-weight: 600;- color: ${cssVar.colorText};- `,- viewAll: css`- cursor: pointer;-- border: none;-- font-size: 13px;- color: ${cssVar.colorTextSecondary};-- background: none;-- &:hover {- color: ${cssVar.colorText};- }- `,-}));--interface SectionTitleProps {- /** The cards are the local copy and a refresh is in flight. */- loading?: boolean;- title: string;- /** Target path of the "view all" affordance; omitted when there is no fuller view. */- viewAllUrl?: string;-}--const SectionTitle = memo<SectionTitleProps>(({ loading, title, viewAllUrl }) => {- const { t } = useTranslation('file');- const navigate = useWorkspaceAwareNavigate();-- return (- <Flexbox horizontal align={'center'} justify={'space-between'}>- <Flexbox horizontal align={'center'} gap={8}>- <h2 className={styles.title}>{title}</h2>- {loading && <Spin size="small" variant="network" />}- </Flexbox>- {viewAllUrl && (- <button className={styles.viewAll} type={'button'} onClick={() => navigate(viewAllUrl)}>- {t('home.viewAll')}- </button>- )}- </Flexbox>- );-});--SectionTitle.displayName = 'SectionTitle';--export default SectionTitle;diff --git a/src/features/ResourceHome/Home/index.tsx b/src/features/ResourceHome/Home/index.tsxindex f8600b980cd..c39ddb960e6 100644--- a/src/features/ResourceHome/Home/index.tsx+++ b/src/features/ResourceHome/Home/index.tsx@@ -1,52 +1,55 @@'use client';-import { createStaticStyles, cssVar, Flexbox } from '@lobehub/ui';-import { memo } from 'react';+import { Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';import NavHeader from '@/features/NavHeader';import AddButton from '@/features/ResourceManager/components/Header/AddButton';--import Libraries from './Libraries';-import RecentFiles from './RecentFiles';-import RecentPages from './RecentPages';-import RecentWorks from './RecentWorks';--const styles = createStaticStyles(({ css }) => ({- content: css`- width: 100%;- max-width: 1080px;- margin-inline: auto;- padding-block: 32px 64px;- padding-inline: 32px;- `,- scroll: css`- overflow: hidden auto;- flex: 1;- `,-}));+import { useHomeStore } from '@/store/home';+import type { DocsHomeTab } from '@/store/home/slices/recent/projection';++import HomeList from './HomeList';+import QuickActions from './QuickActions';++const styles = stylex.create({+ content: {+ width: '100%',+ maxWidth: '1200px',+ marginInline: 'auto',+ paddingBlockStart: '24px',+ paddingBlockEnd: '64px',+ paddingInline: '32px',+ },+ scroll: {+ overflowX: 'hidden',+ overflowY: 'auto',+ flex: '1',+ },+});/**- * The library-style landing page of /resource: libraries (once — the sidebar- * holds the full index), then works → recent pages → recent files, instead of- * the flat all-files table (which now lives at /resource/all).+ * The Docs home: three ways to add something, then everything in Docs as one+ * list — recently updated, created by me, or shared by teammates.*/const ResourceHomeDashboard = memo(() => {const { t } = useTranslation('file');+ const [tab, setTab] = useState<DocsHomeTab>('recent');+ const refreshDocsHome = useHomeStore((s) => s.refreshDocsHome);return (<Flexbox height={'100%'}><NavHeader- left={<Flexbox style={{ marginLeft: 8 }}>{t('resource')}</Flexbox>}+ left={<Flexbox style={{ marginLeft: 8 }}>{t('docs.section.home')}</Flexbox>}right={<AddButton />}style={{ borderBottom: `1px solid ${cssVar.colorBorderSecondary}` }}/>- <div className={styles.scroll}>- <Flexbox className={styles.content} gap={40}>- <Libraries />- <RecentWorks />- <RecentPages />- <RecentFiles />+ <div {...stylex.props(styles.scroll)}>+ <Flexbox gap={28} {...stylex.props(styles.content)}>+ <QuickActions onCreated={() => void refreshDocsHome()} />+ <HomeList tab={tab} onTabChange={setTab} /></Flexbox></div></Flexbox>diff --git a/src/features/ResourceHome/Layout/Body/LibraryList/Item/useDropdownMenu.tsx b/src/features/ResourceHome/Layout/Body/LibraryList/Item/useDropdownMenu.tsxindex d94f732e2b5..b83426bc3d3 100644--- a/src/features/ResourceHome/Layout/Body/LibraryList/Item/useDropdownMenu.tsx+++ b/src/features/ResourceHome/Layout/Body/LibraryList/Item/useDropdownMenu.tsx@@ -6,6 +6,7 @@ import { useTranslation } from 'react-i18next';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { useKnowledgeBaseTransferMenuItem } from '@/business/client/hooks/useKnowledgeBaseTransferMenuItem';+import { libraryCoverOf } from '@/features/LibraryCover/presets';import { useCreateNewModal } from '@/features/LibraryModal';import VisibilityConfirmContent from '@/features/VisibilityConfirmContent';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';@@ -104,9 +105,20 @@ export const useDropdownMenu = ({const handleEditDescription = useCallback(() => {if (!canEdit) return;+ // The cover rides on the loaded list row, not on this sidebar item's props.+ const { knowledgeBaseDetailMap, knowledgeBaseListMap } = useKnowledgeBaseStore.getState();+ const library =+ knowledgeBaseDetailMap[id] ??+ Object.values(knowledgeBaseListMap)+ .flat()+ .find((item) => item.id === id);open({id,- initialValues: { description: description || '', name },+ initialValues: {+ cover: libraryCoverOf(library?.settings),+ description: description || '',+ name,+ },});}, [canEdit, description, id, name, open]);diff --git a/src/features/ResourceHome/Layout/Body/LibraryList/index.tsx b/src/features/ResourceHome/Layout/Body/LibraryList/index.tsxindex 72e42fe7c11..a84c4166128 100644--- a/src/features/ResourceHome/Layout/Body/LibraryList/index.tsx+++ b/src/features/ResourceHome/Layout/Body/LibraryList/index.tsx@@ -1,23 +1,28 @@'use client';import { Flexbox } from '@lobehub/ui';-import { memo } from 'react';+import { ArrowRightIcon } from 'lucide-react';+import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';import AsyncBoundary from '@/components/AsyncBoundary';import { useCreateNewModal } from '@/features/LibraryModal';import EmptyNavItem from '@/features/NavPanel/components/EmptyNavItem';+import NavItem from '@/features/NavPanel/components/NavItem';import SkeletonList from '@/features/NavPanel/components/SkeletonList';import { useResourceManagerStore } from '@/features/ResourceManager/store';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { usePermission } from '@/hooks/usePermission';import { knowledgeBaseSelectors, useKnowledgeBaseStore } from '@/store/library';+import { LIBRARY_INDEX_PATH } from '../../../paths';+import { pickRecentLibraries, useLibraryVisits } from '../../../recentLibraries';import Item from './Item';import { getLibraryListAsyncState } from './state';/**- * Show library list in the sidebar+ * The sidebar's "Recent libraries" shortcut list: the few libraries opened most+ * recently on this device. The full index is the library gallery.*/const LibraryList = memo(() => {const { t } = useTranslation('file');@@ -37,6 +42,8 @@ const LibraryList = memo(() => {// §1.1 failure-as-empty): read `error` / `revalidate` and branch first.const { error, isHydrated, isValidating, revalidate } = useFetchKnowledgeBaseList(visibility);const data = useKnowledgeBaseStore(knowledgeBaseSelectors.getKnowledgeBaseList(visibility));+ const visits = useLibraryVisits();+ const recent = useMemo(() => (data ? pickRecentLibraries(data, visits) : data), [data, visits]);const navigate = useWorkspaceAwareNavigate();@@ -78,7 +85,7 @@ const LibraryList = memo(() => {onRetry={() => revalidate()}><Flexbox gap={1} paddingInline={4}>- {data?.map((item) => (+ {recent?.map((item) => (<Itemdescription={item.description}id={item.id}@@ -90,6 +97,11 @@ const LibraryList = memo(() => {visibility={item.visibility}/>))}+ <NavItem+ icon={ArrowRightIcon}+ title={t('docs.allLibraries')}+ onClick={() => navigate(LIBRARY_INDEX_PATH)}+ /></Flexbox></AsyncBoundary>);diff --git a/src/features/ResourceHome/Layout/Body/PageSection/RenameInput.test.tsx b/src/features/ResourceHome/Layout/Body/PageSection/RenameInput.test.tsxnew file mode 100644index 00000000000..76fcbbf0b02--- /dev/null+++ b/src/features/ResourceHome/Layout/Body/PageSection/RenameInput.test.tsx@@ -0,0 +1,69 @@+/**+ * @vitest-environment happy-dom+ */+import { fireEvent, render, screen } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import RenameInput from './RenameInput';++const renamePage = vi.hoisted(() => vi.fn(async () => {}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock('@/store/page', () => ({+ pageActions: { renamePage },+}));++describe('Docs page rename field', () => {+ beforeEach(() => {+ renamePage.mockClear();+ });++ it('stays open when focus is taken away from the row', () => {+ // The row menu hands focus back to its trigger after the field mounts. A+ // blur-commit closed the field here, which is what made "Rename" look dead.+ const onDone = vi.fn();+ render(<RenameInput id={'page-1'} title={'Weekly report'} onDone={onDone} />);++ fireEvent.blur(screen.getByTestId('page-rename-input'));++ expect(onDone).not.toHaveBeenCalled();+ expect(renamePage).not.toHaveBeenCalled();+ expect(screen.getByTestId('page-rename-input')).toBeTruthy();+ });++ it('commits the typed title when the pointer lands outside the row', async () => {+ const onDone = vi.fn();+ render(<RenameInput id={'page-1'} title={'Weekly report'} onDone={onDone} />);++ fireEvent.change(screen.getByTestId('page-rename-input'), {+ target: { value: 'Renamed report' },+ });+ fireEvent.pointerDown(document.body);++ expect(renamePage).toHaveBeenCalledWith('page-1', 'Renamed report');+ await vi.waitFor(() => expect(onDone).toHaveBeenCalled());+ });++ it('keeps the field open for a pointer landing inside it', () => {+ const onDone = vi.fn();+ render(<RenameInput id={'page-1'} title={'Weekly report'} onDone={onDone} />);++ const input = screen.getByTestId('page-rename-input');+ fireEvent.pointerDown(input);++ expect(onDone).not.toHaveBeenCalled();+ });++ it('does not write when the title is unchanged', async () => {+ const onDone = vi.fn();+ render(<RenameInput id={'page-1'} title={'Weekly report'} onDone={onDone} />);++ fireEvent.pointerDown(document.body);++ expect(renamePage).not.toHaveBeenCalled();+ await vi.waitFor(() => expect(onDone).toHaveBeenCalled());+ });+});diff --git a/src/features/ResourceHome/Layout/Body/PageSection/RenameInput.tsx b/src/features/ResourceHome/Layout/Body/PageSection/RenameInput.tsxnew file mode 100644index 00000000000..8b4598522be--- /dev/null+++ b/src/features/ResourceHome/Layout/Body/PageSection/RenameInput.tsx@@ -0,0 +1,119 @@+'use client';++import { Input, preventDefaultAndStopPropagation, stopPropagation } from '@lobehub/ui';+import { type KeyboardEvent, memo, useCallback, useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { pageActions } from '@/store/page';++interface RenameInputProps {+ id: string;+ /** Closes the editor; the store clears `renamingPageId` on commit itself. */+ onDone: () => void;+ title: string;+}++/**+ * Inline rename field for a page row, the same shape knowledge-base rows use.+ * It replaces the row title instead of opening a popover: the row is only a few+ * dozen pixels tall inside a scrollable sidebar, and a popover anchored to a+ * zero-size node landed nowhere the user could see.+ */+const RenameInput = memo<RenameInputProps>(({ id, title, onDone }) => {+ const { t } = useTranslation('file');++ const [value, setValue] = useState(title);+ const inputRef = useRef<HTMLInputElement>(null);+ const containerRef = useRef<HTMLSpanElement>(null);+ const submittingRef = useRef(false);++ useEffect(() => {+ setValue(title);+ submittingRef.current = false;++ queueMicrotask(() => {+ inputRef.current?.focus();+ inputRef.current?.select();+ });+ }, [title]);++ const handleUpdate = useCallback(async () => {+ if (submittingRef.current) return;+ submittingRef.current = true;++ const next = value.trim();+ if (next && next !== title) {+ // `renamePage` clears `renamingPageId` in its own `finally`.+ await pageActions.renamePage(id, next);+ }++ onDone();+ }, [id, onDone, title, value]);++ /**+ * Dismissal is driven by a pointer landing outside the field, not by focus.+ * Opening the field from the row menu hands focus back to the menu trigger a+ * few hundred milliseconds later — and React can re-render the row while the+ * menu closes — so a blur-commit closed the field before it could be typed+ * into. A document-level `pointerdown` has neither dependency: the field stays+ * open until the user actually clicks somewhere else.+ */+ useEffect(() => {+ const handlePointerDown = (event: PointerEvent) => {+ const container = containerRef.current;+ if (!container || !(event.target instanceof Node)) return;+ // A pointer inside the field belongs to the field, not to the dismissal:+ // clicking the field to place the caret must not end the edit.+ if (container.contains(event.target)) return;++ void handleUpdate();+ };++ // Capture phase: a row click navigates, and its handler may unmount us first.+ document.addEventListener('pointerdown', handlePointerDown, true);++ return () => document.removeEventListener('pointerdown', handlePointerDown, true);+ }, [handleUpdate]);++ const handleKeyDown = useCallback(+ (e: KeyboardEvent<HTMLInputElement>) => {+ if (e.key === 'Escape') {+ e.preventDefault();+ e.stopPropagation();+ onDone();+ }+ },+ [onDone],+ );++ return (+ <span ref={containerRef} style={{ display: 'block', width: '100%' }}>+ <Input+ autoFocus+ data-testid={'page-rename-input'}+ maxLength={64}+ placeholder={t('pageEditor.titlePlaceholder')}+ ref={inputRef}+ size={'small'}+ style={{ width: '100%' }}+ value={value}+ onChange={(e) => setValue(e.target.value)}+ // The field can sit inside the row's link, so the click that places the+ // caret has to cancel the anchor's default action too. Stopping the+ // React event alone still lets the browser follow `href`, and the+ // resulting navigation unmounts the field mid-edit.+ onClick={preventDefaultAndStopPropagation}+ onKeyDown={handleKeyDown}+ // No `preventDefault` here: the anchor's navigation is the click's+ // default action, while a mousedown default is the focus move that+ // puts the caret in the field.+ onMouseDown={stopPropagation}+ onPressEnter={() => void handleUpdate()}+ />+ </span>+ );+});++RenameInput.displayName = 'PageRenameInput';++export default RenameInput;diff --git a/src/features/ResourceHome/Layout/Body/PageSection/index.tsx b/src/features/ResourceHome/Layout/Body/PageSection/index.tsxnew file mode 100644index 00000000000..9a54f2cddfd--- /dev/null+++ b/src/features/ResourceHome/Layout/Body/PageSection/index.tsx@@ -0,0 +1,240 @@+'use client';++import {+ AccordionHeader,+ AccordionItem,+ AccordionPanel,+ accordionStyles,+ AccordionTrigger,+ ActionIcon,+ Avatar,+ cx,+ Flexbox,+ Icon,+ Spin,+ Text,+ toast,+ Tooltip,+} from '@lobehub/ui';+import { FileTextIcon, MoreHorizontal, SquarePenIcon } from 'lucide-react';+import { memo, useCallback, 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 { 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';++interface PageSectionProps {+ itemKey: string;+ scope: PageSectionScope;+}++/**+ * A sidebar section of standalone pages (pages filed into a library open from+ * the library). `mine` is the caller's own pages and offers "new page";+ * `shared` is what other workspace members published.+ */+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 docs = usePageStore(pageSelectors.pageSection(scope));++ const rows = useMemo(() => (docs ? buildPageTree(docs.slice(0, SECTION_LIMIT)) : docs), [docs]);+ const hasMore = (docs?.length ?? 0) > SECTION_LIMIT;++ // 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 handleCreate = async () => {+ if (!canCreate || creating) return;+ setCreating(true);+ try {+ // `createPage` (not `createNewPage`) so the Pages module's own navigation+ // never takes the user out of Docs.+ const page = await pageActions.createPage({ title: t('pageList.untitled') });+ openPage(page.id);+ void pageActions.refreshDocuments();+ } catch (error) {+ console.error('[PageSection] failed to create a page:', error);+ toast.error(t('operationFailed', { ns: 'common' }));+ } finally {+ setCreating(false);+ }+ };++ const title = t(scope === 'mine' ? 'docs.myDocs.title' : 'docs.shared.title');++ const createButton = (+ <ActionIcon+ disabled={!canCreate}+ icon={SquarePenIcon}+ loading={creating}+ size={'small'}+ title={canCreate ? t('header.newPageButton') : undefined}+ onClick={handleCreate}+ />+ );++ return (+ <AccordionItem value={itemKey}>+ <AccordionHeader>+ <AccordionTrigger style={{ paddingBlock: 4, paddingInline: '8px 4px' }}>+ <Flexbox horizontal align={'center'} gap={4}>+ <Text ellipsis fontSize={12} type={'secondary'} weight={500}>+ {title}+ </Text>+ {isValidating && !!rows?.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>+ )}+ </AccordionHeader>+ <AccordionPanel>+ <AsyncBoundary+ data={rows}+ error={error}+ errorVariant={'inline'}+ isEmpty={rows?.length === 0}+ isLoading={rows === undefined && !error}+ loading={<SkeletonList paddingInline={4} rows={3} />}+ empty={+ scope === 'mine' ? (+ <EmptyNavItem+ disabled={!canCreate}+ title={t('docs.myDocs.empty')}+ onClick={handleCreate}+ />+ ) : (+ <Text fontSize={12} style={{ paddingInline: 12 }} type={'secondary'}>+ {t('docs.shared.empty')}+ </Text>+ )+ }+ 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}+ />+ ))}+ {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()}+ />+ )}+ </Flexbox>+ </AsyncBoundary>+ </AccordionPanel>+ </AccordionItem>+ );+});++PageSection.displayName = 'PageSection';++export default PageSection;diff --git a/src/features/ResourceHome/Layout/Body/PageSection/tree.test.ts b/src/features/ResourceHome/Layout/Body/PageSection/tree.test.tsnew file mode 100644index 00000000000..0afffc77bee--- /dev/null+++ b/src/features/ResourceHome/Layout/Body/PageSection/tree.test.ts@@ -0,0 +1,36 @@+import { describe, expect, it } from 'vitest';++import { buildPageTree } from './tree';++const rowsOf = (docs: { id: string; parentId?: string | null }[]) =>+ buildPageTree(docs).map(({ depth, doc }) => `${'-'.repeat(depth)}${doc.id}`);++describe('buildPageTree', () => {+ it('keeps a flat list flat and in order', () => {+ expect(rowsOf([{ id: 'b' }, { id: 'a', parentId: null }])).toEqual(['b', 'a']);+ });++ it('nests a page under its parent', () => {+ expect(+ rowsOf([+ { id: 'child', parentId: 'parent' },+ { id: 'other' },+ { id: 'parent' },+ { id: 'grandchild', parentId: 'child' },+ ]),+ ).toEqual(['other', 'parent', '-child', '--grandchild']);+ });++ it('treats a page whose parent is not listed as a root', () => {+ expect(rowsOf([{ id: 'orphan', parentId: 'missing' }])).toEqual(['orphan']);+ });++ it('still lists pages caught in a parent cycle', () => {+ expect(+ rowsOf([+ { id: 'a', parentId: 'b' },+ { id: 'b', parentId: 'a' },+ ]),+ ).toEqual(['a', '-b']);+ });+});diff --git a/src/features/ResourceHome/Layout/Body/PageSection/tree.ts b/src/features/ResourceHome/Layout/Body/PageSection/tree.tsnew file mode 100644index 00000000000..9b9e10bf2bc--- /dev/null+++ b/src/features/ResourceHome/Layout/Body/PageSection/tree.ts@@ -0,0 +1,45 @@+interface TreeNode {+ id: string;+ parentId?: string | null;+}++export interface PageTreeRow<T extends TreeNode> {+ depth: number;+ doc: T;+}++/**+ * Flatten a page list into display rows: each page follows its parent, one+ * level deeper. A page whose parent is not in the list is a root. Input order+ * (most recently updated first) is kept among siblings.+ */+export const buildPageTree = <T extends TreeNode>(docs: T[]): PageTreeRow<T>[] => {+ const ids = new Set(docs.map((doc) => doc.id));+ const children = new Map<string, T[]>();+ const roots: T[] = [];++ for (const doc of docs) {+ if (doc.parentId && doc.parentId !== doc.id && ids.has(doc.parentId)) {+ const siblings = children.get(doc.parentId);+ if (siblings) siblings.push(doc);+ else children.set(doc.parentId, [doc]);+ } else {+ roots.push(doc);+ }+ }++ const rows: PageTreeRow<T>[] = [];+ const visited = new Set<string>();+ const visit = (doc: T, depth: number) => {+ // A parent cycle would otherwise recurse forever.+ if (visited.has(doc.id)) return;+ visited.add(doc.id);+ rows.push({ depth, doc });+ for (const child of children.get(doc.id) ?? []) visit(child, depth + 1);+ };+ for (const root of roots) visit(root, 0);+ // Pages caught in a parent cycle have no root; list them rather than drop them.+ for (const doc of docs) visit(doc, 0);++ return rows;+};diff --git a/src/features/ResourceHome/Layout/Body/index.tsx b/src/features/ResourceHome/Layout/Body/index.tsxindex 9e082b78901..cc769c44038 100644--- a/src/features/ResourceHome/Layout/Body/index.tsx+++ b/src/features/ResourceHome/Layout/Body/index.tsx@@ -50,7 +50,7 @@ const SidebarBody = memo<{ itemKey: string }>(({ itemKey }) => {<AccordionHeader><AccordionTrigger style={{ paddingBlock: 4, paddingInline: '8px 4px' }}><Text ellipsis fontSize={12} type={'secondary'} weight={500}>- {t('library.title')}+ {t('docs.recentLibraries')}</Text></AccordionTrigger><divdiff --git a/src/features/ResourceHome/Layout/Header/CategoryMenu.tsx b/src/features/ResourceHome/Layout/Header/CategoryMenu.tsxindex f0044c2e438..55220084cf7 100644--- a/src/features/ResourceHome/Layout/Header/CategoryMenu.tsx+++ b/src/features/ResourceHome/Layout/Header/CategoryMenu.tsx@@ -3,14 +3,10 @@import { Flexbox } from '@lobehub/ui';import {ClipboardListIcon,- FilePenIcon,- FilesIcon,- FileText,+ HardDriveIcon,HouseIcon,- ImageIcon,+ LibraryBigIcon,type LucideIcon,- Mic2,- SquarePlay,} from 'lucide-react';import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -21,125 +17,69 @@ import NavItem from '@/features/NavPanel/components/NavItem';import { useResourceManagerStore } from '@/features/ResourceManager/store';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { useActiveLocation } from '@/hooks/useActiveLocation';-import { FilesTabs } from '@/types/files';-import { isResourceCategoryActive } from './categoryActive';+import {+ type DocsSection,+ DRIVE_PATH,+ LIBRARY_INDEX_PATH,+ resolveDocsSection,+ RESOURCE_HOME_PATH,+ WORKS_PATH,+} from '../../paths';-interface CategoryItem {+interface SectionItem {icon: LucideIcon;- isBusiness?: boolean;- key: string;+ key: DocsSection;title: string;url: string;}+/**+ * The four Docs sections. Each owns a clearly separate pool — recent activity,+ * every uploaded file, libraries, Agent output — instead of one mixed list of+ * file types, libraries and business entities.+ */const CategoryMenu = memo(() => {const { t } = useTranslation('file');- const [activeKey, setMode] = useResourceManagerStore((s) => [s.category, s.setMode]);+ const setMode = useResourceManagerStore((s) => s.setMode);const navigate = useWorkspaceAwareNavigate();- const businessCategories = useBusinessResourceCategories();const location = useActiveLocation();+ // Business Works types keep their own routes but belong to Works.+ const businessCategories = useBusinessResourceCategories();+ const activeSection = resolveDocsSection(+ location.pathname,+ businessCategories.map((category) => category.url),+ );- // Two groups below the fixed Home entry: file-based categories (uploaded- // files by type) and LobeHub business entities (pages, works, webpages),- // separated by a gap. The flat everything-list stays reachable at- // /resource/all (the home page's "view all" target) but is not a nav entry —- // browsing starts from a category, not from an undifferentiated pile.- const groups = useMemo(+ const items = useMemo<SectionItem[]>(() => [- [- {- icon: HouseIcon,- key: FilesTabs.Home,- title: t('tab.home'),- url: '/resource',- },- ],- // file-based categories — Files (the misc raw-data bucket) sits last- [- {- icon: FileText,- key: FilesTabs.Documents,- title: t('tab.documents'),- url: '/resource/documents',- },- {- icon: ImageIcon,- key: FilesTabs.Images,- title: t('tab.images'),- url: '/resource/images',- },- {- icon: SquarePlay,- key: FilesTabs.Videos,- title: t('tab.videos'),- url: '/resource/videos',- },- {- icon: Mic2,- key: FilesTabs.Audios,- title: t('tab.audios'),- url: '/resource/audios',- },- {- icon: FilesIcon,- key: FilesTabs.Files,- title: t('tab.files'),- url: '/resource/files',- },- ],- // LobeHub business entities- [- {- icon: FilePenIcon,- key: FilesTabs.Pages,- title: t('tab.pages'),- url: '/resource/page',- },- {- icon: ClipboardListIcon,- key: 'works',- title: t('work.group'),- url: '/resource/works',- },- // The Websites entry is hidden for now (the category route and the- // reading-card view stay reachable at /resource/websites) — re-add it- // here once web clippings ship as a first-class flow.- ...businessCategories.map((category) => ({- icon: category.icon,- isBusiness: true,- key: category.key,- // Business categories carry a chat-namespace key but the type narrows to a- // string at this seam; cast so t() accepts the dynamic key.- title: t(category.titleKey as never) as string,- url: category.url,- })),- ] as CategoryItem[],+ { icon: HouseIcon, key: 'home', title: t('docs.section.home'), url: RESOURCE_HOME_PATH },+ { icon: HardDriveIcon, key: 'drive', title: t('docs.section.drive'), url: DRIVE_PATH },+ {+ icon: LibraryBigIcon,+ key: 'library',+ title: t('docs.section.library'),+ url: LIBRARY_INDEX_PATH,+ },+ { icon: ClipboardListIcon, key: 'works', title: t('docs.section.works'), url: WORKS_PATH },],- [t, businessCategories],+ [t],);return (- <Flexbox gap={12} paddingInline={4}>- {groups.map((group, groupIndex) => (- <Flexbox gap={1} key={groupIndex}>- {group.map((item) => {- const isActive = isResourceCategoryActive(item, activeKey, location.pathname);- return (- <Link- key={item.key}- to={item.url}- onClick={(e) => {- e.preventDefault();- setMode('explorer');- navigate(item.url, { replace: true });- }}- >- <NavItem active={isActive} icon={item.icon} title={item.title} />- </Link>- );- })}- </Flexbox>+ <Flexbox gap={1} paddingInline={4}>+ {items.map((item) => (+ <Link+ key={item.key}+ to={item.url}+ onClick={(e) => {+ e.preventDefault();+ setMode('explorer');+ navigate(item.url);+ }}+ >+ <NavItem active={activeSection === item.key} icon={item.icon} title={item.title} />+ </Link>))}</Flexbox>);diff --git a/src/features/ResourceHome/Layout/Header/categoryActive.test.ts b/src/features/ResourceHome/Layout/Header/categoryActive.test.tsdeleted file mode 100644index 426c4e2dcbf..00000000000--- a/src/features/ResourceHome/Layout/Header/categoryActive.test.ts+++ /dev/null@@ -1,55 +0,0 @@-import { describe, expect, it } from 'vitest';--import { FilesTabs } from '@/types/files';--import { isResourceCategoryActive } from './categoryActive';--const home = { key: FilesTabs.Home, url: '/resource' };--describe('isResourceCategoryActive', () => {- it.each(['/resource', '/resource/', '/team/resource', '/team/resource/'])(- 'highlights Home on the resource dashboard at %s',- (pathname) => {- expect(isResourceCategoryActive(home, FilesTabs.Home, pathname)).toBe(true);- },- );-- it.each([- '/resource/page',- '/resource/page/',- '/resource/images',- '/resource/all',- '/resource/works',- '/resource/works/',- '/resource/library/library-1',- '/resource/library/library-1/permission',- '/team/resource/page',- '/team/resource/library/library-1',- ])('does not highlight Home on %s when the store still selects Home', (pathname) => {- expect(isResourceCategoryActive(home, FilesTabs.Home, pathname)).toBe(false);- });-- it('preserves the selected file category', () => {- expect(- isResourceCategoryActive(- { key: FilesTabs.Pages, url: '/resource/page' },- FilesTabs.Pages,- '/resource/page',- ),- ).toBe(true);- });-- it('highlights Works and suppresses the stored file category on the gallery', () => {- const pathname = '/team/resource/works';- expect(- isResourceCategoryActive({ key: 'works', url: '/resource/works' }, FilesTabs.Home, pathname),- ).toBe(true);- expect(- isResourceCategoryActive(- { key: FilesTabs.Pages, url: '/resource/page' },- FilesTabs.Pages,- pathname,- ),- ).toBe(false);- });-});diff --git a/src/features/ResourceHome/Layout/Header/categoryActive.ts b/src/features/ResourceHome/Layout/Header/categoryActive.tsdeleted file mode 100644index b4f122cbb9c..00000000000--- a/src/features/ResourceHome/Layout/Header/categoryActive.ts+++ /dev/null@@ -1,22 +0,0 @@-import { FilesTabs } from '@/types/files';--interface ResourceCategoryItem {- isBusiness?: boolean;- key: string;- url: string;-}--export const isResourceCategoryActive = (- item: ResourceCategoryItem,- activeKey: string,- pathname: string,-): boolean => {- const worksActive = pathname.endsWith('/resource/works');-- if (item.key === 'works') return worksActive;- if (item.key === FilesTabs.Home) {- return activeKey === FilesTabs.Home && /\/resource\/?$/.test(pathname);- }-- return !worksActive && (item.isBusiness ? pathname === item.url : activeKey === item.key);-};diff --git a/src/features/ResourceHome/Layout/SidebarContent.tsx b/src/features/ResourceHome/Layout/SidebarContent.tsxindex ed3ab0909ed..195a78a240c 100644--- a/src/features/ResourceHome/Layout/SidebarContent.tsx+++ b/src/features/ResourceHome/Layout/SidebarContent.tsx@@ -3,31 +3,69 @@import { AccordionRoot, Flexbox } from '@lobehub/ui';import { memo } from 'react';+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 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.+ */+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);++ return <AllPagesDrawer open={open} onClose={pageActions.closeAllPagesDrawer} />;+});++AllPagesDrawerHost.displayName = 'DocsAllPagesDrawerHost';+export enum GroupKey {Library = 'library',+ MyDocs = 'my-docs',+ Shared = 'shared-docs',}-const ResourceSidebarContent = memo(() => (- <SideBarLayout- header={<Header />}- body={- <Flexbox paddingBlock={8} paddingInline={4}>- <AccordionRoot- defaultValue={[GroupKey.Library]}- indicatorPlacement="inline"- style={{ gap: 8 }}- >- <SidebarBody itemKey={GroupKey.Library} />- </AccordionRoot>- </Flexbox>- }- />-));+const DEFAULT_OPEN = [GroupKey.Library, GroupKey.MyDocs, GroupKey.Shared];++/**+ * Docs sidebar: the four sections in the header, then shortcuts — recent+ * libraries, the caller's own pages and (in a workspace) pages teammates shared.+ */+const ResourceSidebarContent = memo(() => {+ const workspaceId = useActiveWorkspaceId();++ return (+ <SideBarLayout+ header={<Header />}+ body={+ <>+ <Flexbox paddingBlock={8} paddingInline={4}>+ <AccordionRoot+ defaultValue={DEFAULT_OPEN}+ indicatorPlacement="inline"+ style={{ gap: 8 }}+ >+ <SidebarBody itemKey={GroupKey.Library} />+ <PageSection itemKey={GroupKey.MyDocs} scope={'mine'} />+ {workspaceId && <PageSection itemKey={GroupKey.Shared} scope={'shared'} />}+ </AccordionRoot>+ </Flexbox>+ <AllPagesDrawerHost />+ </>+ }+ />+ );+});ResourceSidebarContent.displayName = 'ResourceSidebarContent';diff --git a/src/features/ResourceHome/MergeNotice/Content.tsx b/src/features/ResourceHome/MergeNotice/Content.tsxnew file mode 100644index 00000000000..a8c8ebf60c3--- /dev/null+++ b/src/features/ResourceHome/MergeNotice/Content.tsx@@ -0,0 +1,73 @@+'use client';++import { Button, Flexbox, Icon, Text, useModalContext } from '@lobehub/ui';+import {+ FileTextIcon,+ HardDriveIcon,+ LibraryBigIcon,+ Link2Icon,+ type LucideIcon,+} from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++interface PointProps {+ desc: string;+ icon: LucideIcon;+ title: string;+}++const Point = memo<PointProps>(({ desc, icon, title }) => (+ <Flexbox horizontal align={'flex-start'} gap={12}>+ <Icon icon={icon} size={18} style={{ flex: 'none', marginBlockStart: 2 }} />+ <Flexbox gap={2}>+ <Text weight={500}>{title}</Text>+ <Text fontSize={13} type={'secondary'}>+ {desc}+ </Text>+ </Flexbox>+ </Flexbox>+));++Point.displayName = 'DocsMergePoint';++/** Where things moved when Pages and Resources became Docs. */+export const DocsMergeNoticeContent = memo(() => {+ const { t } = useTranslation('file');+ const { close } = useModalContext();++ return (+ <Flexbox gap={20}>+ <Text type={'secondary'}>{t('docs.mergeNotice.intro')}</Text>+ <Flexbox gap={14}>+ <Point+ desc={t('docs.mergeNotice.pages.desc')}+ icon={FileTextIcon}+ title={t('docs.mergeNotice.pages.title')}+ />+ <Point+ desc={t('docs.mergeNotice.drive.desc')}+ icon={HardDriveIcon}+ title={t('docs.mergeNotice.drive.title')}+ />+ <Point+ desc={t('docs.mergeNotice.knowledgeBase.desc')}+ icon={LibraryBigIcon}+ title={t('docs.mergeNotice.knowledgeBase.title')}+ />+ <Point+ desc={t('docs.mergeNotice.links.desc')}+ icon={Link2Icon}+ title={t('docs.mergeNotice.links.title')}+ />+ </Flexbox>+ <Flexbox horizontal justify={'flex-end'}>+ <Button type={'primary'} onClick={() => close()}>+ {t('docs.mergeNotice.confirm')}+ </Button>+ </Flexbox>+ </Flexbox>+ );+});++DocsMergeNoticeContent.displayName = 'DocsMergeNoticeContent';diff --git a/src/features/ResourceHome/MergeNotice/decide.test.ts b/src/features/ResourceHome/MergeNotice/decide.test.tsnew file mode 100644index 00000000000..062adf8b0ec--- /dev/null+++ b/src/features/ResourceHome/MergeNotice/decide.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from 'vitest';++import { decideMergeNotice } from './decide';++describe('decideMergeNotice', () => {+ it('waits until the user state has loaded', () => {+ expect(decideMergeNotice({ hasConversation: true, ready: false, seen: false })).toBe('wait');+ });++ it('shows the notice once to a returning user who chatted before', () => {+ expect(decideMergeNotice({ hasConversation: true, ready: true, seen: false })).toBe('show');+ expect(decideMergeNotice({ hasConversation: true, ready: true, seen: true })).toBe('none');+ });++ it('shows it to a workspace-only user whose pages or files are here', () => {+ expect(+ decideMergeNotice({ hasContent: true, hasConversation: false, ready: true, seen: false }),+ ).toBe('show');+ });++ it('waits for the content check before treating someone as new', () => {+ expect(decideMergeNotice({ hasConversation: false, ready: true, seen: false })).toBe('wait');+ });++ it('marks it seen for a newcomer with nothing here, without showing it', () => {+ expect(+ decideMergeNotice({ hasContent: false, hasConversation: false, ready: true, seen: false }),+ ).toBe('mark-seen');+ });+});diff --git a/src/features/ResourceHome/MergeNotice/decide.ts b/src/features/ResourceHome/MergeNotice/decide.tsnew file mode 100644index 00000000000..4b58f4a8595--- /dev/null+++ b/src/features/ResourceHome/MergeNotice/decide.ts@@ -0,0 +1,36 @@+export type MergeNoticeDecision = 'mark-seen' | 'show' | 'wait' | 'none';++interface MergeNoticeInput {+ /**+ * Pages or files exist in the current scope; `undefined` while unknown. This+ * catches users who only ever worked inside a workspace, whose personal+ * conversation count is zero.+ */+ hasContent?: boolean;+ /** The user has chatted before (personal-scope messages or agents). */+ hasConversation: boolean;+ /** User state (and with it the preference) has loaded. */+ ready: boolean;+ /** The notice was already acknowledged. */+ seen: boolean;+}++/**+ * Who sees "Pages and Resources are now Docs": only people who knew the old+ * layout — they chatted before, or have pages or files here — and only once.+ * A newcomer with nothing here never knew either, so their first Docs visit+ * marks the notice seen instead; otherwise it would surface after their first+ * chat and announce a change they never experienced.+ */+export const decideMergeNotice = ({+ hasContent,+ hasConversation,+ ready,+ seen,+}: MergeNoticeInput): MergeNoticeDecision => {+ if (!ready) return 'wait';+ if (seen) return 'none';+ if (hasConversation || hasContent) return 'show';+ // No conversation: wait for the content check before calling them new.+ return hasContent === undefined ? 'wait' : 'mark-seen';+};diff --git a/src/features/ResourceHome/MergeNotice/index.tsx b/src/features/ResourceHome/MergeNotice/index.tsxnew file mode 100644index 00000000000..9035cd9d157--- /dev/null+++ b/src/features/ResourceHome/MergeNotice/index.tsx@@ -0,0 +1,66 @@+'use client';++import { createModal } from '@lobehub/ui';+import { t } from 'i18next';+import { useEffect, useRef } from 'react';++import { useHomeStore } from '@/store/home';+import { homeRecentSelectors } from '@/store/home/slices/recent/selectors';+import { useUserStore } from '@/store/user';+import { preferenceSelectors } from '@/store/user/selectors';++import { DocsMergeNoticeContent } from './Content';+import { decideMergeNotice } from './decide';++const openDocsMergeNotice = (onClosed: () => void) =>+ createModal({+ content: <DocsMergeNoticeContent />,+ footer: null,+ maskClosable: true,+ // Any dismissal counts as read: the button, Esc, the backdrop or the ✕.+ onOpenChangeComplete: (open) => {+ if (!open) onClosed();+ },+ title: t('docs.mergeNotice.title', { ns: 'file' }),+ width: 'min(92vw, 480px)',+ });++/**+ * Tells a returning user, once, that Pages and Resources are now Docs. Mounted+ * in the Docs layout, so it greets them whether they open Docs directly or land+ * here through an old `/page` link. The acknowledgement is a user preference,+ * so it does not reappear on another device.+ */+export const useDocsMergeNotice = () => {+ const ready = useUserStore((s) => s.isUserStateInit);+ const hasConversation = useUserStore((s) => s.isUserHasConversation);+ const seen = useUserStore(preferenceSelectors.docsMergedNoticeSeen);+ const updateGuideState = useUserStore((s) => s.updateGuideState);+ const handled = useRef(false);++ // Only someone without a personal conversation needs the content check; it+ // reuses the Docs home list, so the home page reads it from the same cache.+ const checkContent = ready && !seen && !hasConversation;+ useHomeStore((s) => s.useFetchDocsHome)('recent', checkContent);+ const rows = useHomeStore(homeRecentSelectors.docsHome('recent'));++ const decision = decideMergeNotice({+ hasContent: rows === undefined ? undefined : rows.length > 0,+ hasConversation,+ ready,+ seen,+ });++ useEffect(() => {+ if (handled.current) return;+ const markSeen = () => void updateGuideState({ docsMerged: true });++ if (decision === 'show') {+ handled.current = true;+ openDocsMergeNotice(markSeen);+ } else if (decision === 'mark-seen') {+ handled.current = true;+ markSeen();+ }+ }, [decision, updateGuideState]);+};diff --git a/src/features/ResourceHome/Skeleton.tsx b/src/features/ResourceHome/Skeleton.tsxindex 37eb2d5cc88..8ef1abf508c 100644--- a/src/features/ResourceHome/Skeleton.tsx+++ b/src/features/ResourceHome/Skeleton.tsx@@ -4,6 +4,10 @@ import { Flexbox } from '@lobehub/ui';import { useLocation, useSearchParams } from 'react-router';import SkeletonBar from '@/components/Skeleton/Bar';+import {+ RESOURCE_HOME_SECTIONS,+ ResourceSectionSkeleton,+} from '@/components/Skeleton/ResourceHome';import ListViewSkeleton from '@/features/ResourceManager/components/Explorer/ListView/Skeleton';import MasonryViewSkeleton from '@/features/ResourceManager/components/Explorer/MasonryView/Skeleton';import { useMasonryColumnCount } from '@/features/ResourceManager/components/Explorer/useMasonryColumnCount';@@ -19,6 +23,12 @@ const ResourceCategorySkeleton = ({ chrome = 'page' }: RouteSkeletonProps) => {const view = resolveResourceSkeletonView(pathname, searchParams.get('view'));if (view === 'works') return <WorkGallerySkeleton />;+ if (view === 'libraries')+ return (+ <Flexbox aria-busy flex={1} padding={32}>+ <ResourceSectionSkeleton {...RESOURCE_HOME_SECTIONS.libraries} />+ </Flexbox>+ );return (<Flexbox aria-busy flex={1} height={'100%'} style={{ minHeight: 0, overflow: 'hidden' }}>diff --git a/src/features/ResourceHome/index.test.ts b/src/features/ResourceHome/index.test.tsdeleted file mode 100644index 4a91cea02dc..00000000000--- a/src/features/ResourceHome/index.test.ts+++ /dev/null@@ -1,20 +0,0 @@-import { describe, expect, it } from 'vitest';--import { resolveResourcePathCategory } from './index';--describe('resolveResourcePathCategory', () => {- it.each(['all', 'documents', 'images', 'videos', 'audios', 'files', 'page'])(- 'recovers the %s category for a static resource route',- (category) => {- expect(resolveResourcePathCategory(undefined, `/resource/${category}`)).toBe(category);- },- );-- it('preserves a dynamic category param when one exists', () => {- expect(resolveResourcePathCategory('websites', '/resource/websites')).toBe('websites');- });-- it('keeps the resource dashboard uncategorized', () => {- expect(resolveResourcePathCategory(undefined, '/resource')).toBeUndefined();- });-});diff --git a/src/features/ResourceHome/index.tsx b/src/features/ResourceHome/index.tsxindex e7130e516aa..33333365306 100644--- a/src/features/ResourceHome/index.tsx+++ b/src/features/ResourceHome/index.tsx@@ -1,92 +1,36 @@'use client';import { memo, useLayoutEffect } from 'react';-import { useLocation, useParams, useSearchParams } from 'react-router';+import { useLocation, useSearchParams } from 'react-router';import ResourceManager from '@/features/ResourceManager';import { useInitFileCheck } from '@/features/ResourceManager/hooks/useInitFileCheck';import { useResourceManagerStore } from '@/features/ResourceManager/store';import WorkGallery from '@/features/WorkGallery';-import { parseWorkGalleryKey } from '@/features/WorkGallery/const';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { FilesTabs } from '@/types/files';import HomeDashboard from './Home';--/**- * Path segment → category for routes that own one: /resource/all,- * /resource/page (derived pages/notes), /resource/documents, …- */-export const CATEGORY_BY_SEGMENT: Record<string, FilesTabs> = {- all: FilesTabs.All,- audios: FilesTabs.Audios,- documents: FilesTabs.Documents,- files: FilesTabs.Files,- images: FilesTabs.Images,- page: FilesTabs.Pages,- videos: FilesTabs.Videos,- websites: FilesTabs.Websites,-};--const SEGMENT_BY_CATEGORY = Object.fromEntries(- Object.entries(CATEGORY_BY_SEGMENT).map(([segment, category]) => [category, segment]),-);--/** Canonical path for a category, e.g. /resource/page for Pages. */-export const resourceCategoryPath = (category: FilesTabs): string =>- SEGMENT_BY_CATEGORY[category] ? `/resource/${SEGMENT_BY_CATEGORY[category]}` : '/resource';--export const resolveResourcePathCategory = (- category: string | undefined,- pathname: string,-): string | undefined => category ?? pathname.match(/\/resource\/([^/]+)\/?$/)?.[1];--/** Path segment of the cross-topic Work gallery: /resource/works */-export const WORKS_PATH_SEGMENT = 'works';+import { resolveResourceRoute } from './paths';const ResourceHomePage = memo(() => {const [searchParams] = useSearchParams();const location = useLocation();- const params = useParams<{ category?: string }>();const navigate = useWorkspaceAwareNavigate();const [setCategory, setLibraryId] = useResourceManagerStore((s) => [s.setCategory,s.setLibraryId,]);- // Category-specific route metadata uses static sibling routes, so recover- // their segment from the pathname when React Router has no :category param.- const pathCategory = resolveResourcePathCategory(params.category, location.pathname);- const segmentCategory = pathCategory ? CATEGORY_BY_SEGMENT[pathCategory] : undefined;- const isValidPathCategory = segmentCategory !== undefined;- // The Work gallery owns its own path segment; `?works=<key>` narrows it- // (task / document / linear / github), defaulting to the combined view.- const isWorksPath = pathCategory === WORKS_PATH_SEGMENT;- const worksKey = isWorksPath ? (parseWorkGalleryKey(searchParams.get('works')) ?? 'all') : null;- // The bare /resource route is the library home dashboard; explorer views- // live under /resource/<category> (the all-files list at /resource/all).- const categoryParam = segmentCategory ?? FilesTabs.Home;-- // Legacy URLs used `?category=<x>` / `?works=<key>` on the bare /resource- // route; canonical forms are now /resource/<x> and /resource/works.- const legacyCategory = searchParams.get('category');- const legacyWorksKey = isWorksPath ? null : parseWorkGalleryKey(searchParams.get('works'));- const isInvalidPath = !!pathCategory && !isValidPathCategory && !isWorksPath;+ const view = resolveResourceRoute(location.pathname, searchParams);+ const redirectTo = view.kind === 'redirect' ? view.to : null;+ // The bare /resource route is the home dashboard (an opened page or file is+ // overlaid on it); the drive lists files by category under /resource/drive.+ const categoryParam = view.kind === 'drive' ? view.category : FilesTabs.Home;useLayoutEffect(() => {- if (legacyWorksKey) {- navigate(- legacyWorksKey === 'all' ? '/resource/works' : `/resource/works?works=${legacyWorksKey}`,- { replace: true },- );- return;- }- if (legacyCategory) {- navigate(resourceCategoryPath(legacyCategory as FilesTabs), { replace: true });- return;- }- if (isInvalidPath) navigate('/resource', { replace: true });- }, [legacyWorksKey, legacyCategory, isInvalidPath, navigate]);+ if (redirectTo) navigate(redirectTo, { replace: true });+ }, [redirectTo, navigate]);// Clear libraryId when on home route using useLayoutEffect// useLayoutEffect runs synchronously before browser paint, ensuring state is cleared@@ -112,12 +56,13 @@ const ResourceHomePage = memo(() => {}}, [categoryParam, setCategory, location.pathname]);- // Sync file view mode from URL- useInitFileCheck();+ // Sync the open item from the URL: `/resource/{file,page}/:id` paths, or+ // the drive explorer's own `?file=` preview.+ useInitFileCheck(view.kind === 'file' || view.kind === 'page' ? view.id : null);- if (worksKey) return <WorkGallery galleryKey={worksKey} />;+ if (view.kind === 'works') return <WorkGallery galleryKey={view.galleryKey} />;- return <ResourceManager content={isValidPathCategory ? undefined : <HomeDashboard />} />;+ return <ResourceManager content={view.kind === 'drive' ? undefined : <HomeDashboard />} />;});ResourceHomePage.displayName = 'ResourceHomePage';diff --git a/src/features/ResourceHome/paths.test.ts b/src/features/ResourceHome/paths.test.tsnew file mode 100644index 00000000000..0ac4ea64c2a--- /dev/null+++ b/src/features/ResourceHome/paths.test.ts@@ -0,0 +1,125 @@+import { describe, expect, it } from 'vitest';++import { FilesTabs } from '@/types/files';++import {+ docsFilePath,+ docsPagePath,+ driveCategoryPath,+ resolveDocsSection,+ resolveResourceRoute,+} from './paths';++const route = (pathname: string, search = '') =>+ resolveResourceRoute(pathname, new URLSearchParams(search));++describe('resolveResourceRoute', () => {+ it('renders the home dashboard at the Docs root', () => {+ expect(route('/resource')).toEqual({ kind: 'home' });+ expect(route('/team/resource/')).toEqual({ kind: 'home' });+ });++ it('lists every file at the drive root', () => {+ expect(route('/resource/drive')).toEqual({ category: FilesTabs.All, kind: 'drive' });+ });++ it.each([+ ['documents', FilesTabs.Documents],+ ['images', FilesTabs.Images],+ ['videos', FilesTabs.Videos],+ ['audios', FilesTabs.Audios],+ ['files', FilesTabs.Files],+ ['websites', FilesTabs.Websites],+ ])('resolves the drive %s category', (segment, category) => {+ expect(route(`/team/resource/drive/${segment}`)).toEqual({ category, kind: 'drive' });+ });++ it('sends an unknown drive category back to the drive root', () => {+ expect(route('/resource/drive/bogus')).toEqual({ kind: 'redirect', to: '/resource/drive' });+ });++ it('resolves the Works gallery and its narrowing key', () => {+ expect(route('/resource/works')).toEqual({ galleryKey: 'all', kind: 'works' });+ expect(route('/resource/works', 'works=task')).toEqual({ galleryKey: 'task', kind: 'works' });+ });++ it.each([+ ['/resource/all', '/resource/drive'],+ ['/resource/images', '/resource/drive/images'],+ ['/team/resource/documents', '/resource/drive/documents'],+ ['/resource/page', '/resource'],+ ])('redirects the legacy %s path to %s', (pathname, to) => {+ expect(route(pathname)).toEqual({ kind: 'redirect', to });+ });++ it('redirects legacy query parameters', () => {+ expect(route('/resource', 'category=images')).toEqual({+ kind: 'redirect',+ to: '/resource/drive/images',+ });+ expect(route('/resource', 'works=document')).toEqual({+ kind: 'redirect',+ to: '/resource/works?works=document',+ });+ });++ it('sends an unknown section home', () => {+ expect(route('/resource/bogus')).toEqual({ kind: 'redirect', to: '/resource' });+ });+});++describe('driveCategoryPath', () => {+ it('maps the all-files view to the drive root', () => {+ expect(driveCategoryPath(FilesTabs.All)).toBe('/resource/drive');+ expect(driveCategoryPath(FilesTabs.Images)).toBe('/resource/drive/images');+ });+});++describe('resolveDocsSection', () => {+ it.each([+ ['/resource', 'home'],+ ['/team/resource/drive/images', 'drive'],+ ['/resource/library', 'library'],+ ['/resource/library/kb-1/folder', 'library'],+ ['/resource/works', 'works'],+ ])('maps %s to %s', (pathname, section) => {+ expect(resolveDocsSection(pathname)).toBe(section);+ });++ it('treats business Works routes as part of Works', () => {+ expect(resolveDocsSection('/team/resource/extra', ['/resource/extra'])).toBe('works');+ expect(resolveDocsSection('/resource/extra')).toBeNull();+ });+});++describe('docsPagePath / docsFilePath', () => {+ it('opens a page at /resource/page/<short id> instead of the Pages module', () => {+ expect(docsPagePath('docs_abc')).toBe('/resource/page/abc');+ });++ it('opens a file at /resource/file/<id>', () => {+ expect(docsFilePath('file_1')).toBe('/resource/file/file_1');+ });+});++describe('resolveResourceRoute — opened items', () => {+ it('resolves a page path back to the full document id', () => {+ expect(route('/team/resource/page/abc')).toEqual({ id: 'docs_abc', kind: 'page' });+ expect(route('/resource/page/docs_abc')).toEqual({ id: 'docs_abc', kind: 'page' });+ });++ it('resolves a file path', () => {+ expect(route('/resource/file/file_1')).toEqual({ id: 'file_1', kind: 'file' });+ });++ it('moves the legacy ?file= home link to the file path', () => {+ expect(route('/resource', 'file=docs_abc')).toEqual({+ kind: 'redirect',+ to: '/resource/file/docs_abc',+ });+ });++ it('keeps the bare legacy /resource/page going home', () => {+ expect(route('/resource/page')).toEqual({ kind: 'redirect', to: '/resource' });+ });+});diff --git a/src/features/ResourceHome/paths.ts b/src/features/ResourceHome/paths.tsnew file mode 100644index 00000000000..5a15a2d116e--- /dev/null+++ b/src/features/ResourceHome/paths.ts@@ -0,0 +1,138 @@+import { parseWorkGalleryKey, type WorkGalleryKey } from '@/features/WorkGallery/const';+import { FilesTabs } from '@/types/files';+import { getIdFromIdentifier, standardizeIdentifier } from '@/utils/identifier';++/**+ * Docs (`/resource`) has four sections: the home dashboard, the drive (every+ * uploaded file by type), the library gallery and the Works gallery. Paths are+ * written without the workspace prefix; navigation adds it.+ */+export const RESOURCE_HOME_PATH = '/resource';+export const DRIVE_PATH = '/resource/drive';+export const LIBRARY_INDEX_PATH = '/resource/library';+export const WORKS_PATH = '/resource/works';++/** Path segment → drive category: /resource/drive/documents, /resource/drive/images, … */+export const DRIVE_CATEGORY_BY_SEGMENT: Record<string, FilesTabs> = {+ audios: FilesTabs.Audios,+ documents: FilesTabs.Documents,+ files: FilesTabs.Files,+ images: FilesTabs.Images,+ videos: FilesTabs.Videos,+ websites: FilesTabs.Websites,+};++const DRIVE_SEGMENT_BY_CATEGORY = Object.fromEntries(+ Object.entries(DRIVE_CATEGORY_BY_SEGMENT).map(([segment, category]) => [category, segment]),+) as Partial<Record<FilesTabs, string>>;++/** Canonical drive path for a category; the drive root lists every file. */+export const driveCategoryPath = (category: FilesTabs): string => {+ const segment = DRIVE_SEGMENT_BY_CATEGORY[category];+ return segment ? `${DRIVE_PATH}/${segment}` : DRIVE_PATH;+};++/**+ * Where a page opens inside Docs: `/resource/page/<id>`, with the short id the+ * Pages module used (`docs_` prefix dropped), so writing a page never leaves Docs.+ */+export const docsPagePath = (pageId: string): string =>+ `${RESOURCE_HOME_PATH}/page/${encodeURIComponent(standardizeIdentifier(pageId))}`;++/** Where an uploaded file opens inside Docs: `/resource/file/<id>`. */+export const docsFilePath = (fileId: string): string =>+ `${RESOURCE_HOME_PATH}/file/${encodeURIComponent(fileId)}`;++export type ResourceRouteView =+ | { kind: 'home' }+ | { category: FilesTabs; kind: 'drive' }+ | { galleryKey: WorkGalleryKey; kind: 'works' }+ /** A page or file opened over the Docs home; `id` is the full row id. */+ | { id: string; kind: 'file' | 'page' }+ | { kind: 'redirect'; to: string };++/** The segments after `/resource`, ignoring a workspace prefix and trailing slash. */+const resourceSegments = (pathname: string): string[] | null => {+ const match = pathname.match(/\/resource(?:\/(.*))?$/);+ if (!match) return null;+ return match[1] ? match[1].split('/').filter(Boolean) : [];+};++/** Where a pre-Docs URL (`/resource/<category>`, `?category=`, `?works=`) now lives. */+const legacyRedirect = (segments: string[], searchParams: URLSearchParams): string | null => {+ const legacyWorksKey = parseWorkGalleryKey(searchParams.get('works'));+ if (legacyWorksKey && segments[0] !== 'works') {+ return legacyWorksKey === 'all' ? WORKS_PATH : `${WORKS_PATH}?works=${legacyWorksKey}`;+ }++ // The Docs home opened items as `/resource?file=<id>` before they had paths.+ const legacyFile = searchParams.get('file');+ if (legacyFile && segments.length === 0) return docsFilePath(legacyFile);++ const legacyCategory = searchParams.get('category');+ if (legacyCategory && segments.length === 0) {+ return driveCategoryPath(legacyCategory as FilesTabs);+ }++ if (segments.length !== 1) return null;+ const [segment] = segments;+ if (segment === 'all') return DRIVE_PATH;+ // Pages left the drive: they live in the sidebar's My docs / Shared sections.+ if (segment === 'page') return RESOURCE_HOME_PATH;+ if (DRIVE_CATEGORY_BY_SEGMENT[segment]) return `${DRIVE_PATH}/${segment}`;++ return null;+};++/** Resolve what the Docs home route renders for a URL. */+export const resolveResourceRoute = (+ pathname: string,+ searchParams: URLSearchParams,+): ResourceRouteView => {+ const segments = resourceSegments(pathname) ?? [];++ const redirect = legacyRedirect(segments, searchParams);+ if (redirect) return { kind: 'redirect', to: redirect };++ if (segments.length === 0) return { kind: 'home' };++ const [section, sub, ...rest] = segments;++ if (section === 'works' && !sub) {+ return { galleryKey: parseWorkGalleryKey(searchParams.get('works')) ?? 'all', kind: 'works' };+ }++ if ((section === 'page' || section === 'file') && sub && rest.length === 0) {+ const id = decodeURIComponent(sub);+ return { id: section === 'page' ? getIdFromIdentifier(id, 'docs') : id, kind: section };+ }++ if (section === 'drive' && rest.length === 0) {+ if (!sub) return { category: FilesTabs.All, kind: 'drive' };+ const category = DRIVE_CATEGORY_BY_SEGMENT[sub];+ return category ? { category, kind: 'drive' } : { kind: 'redirect', to: DRIVE_PATH };+ }++ return { kind: 'redirect', to: RESOURCE_HOME_PATH };+};++export type DocsSection = 'drive' | 'home' | 'library' | 'works';++/**+ * Which top-level Docs section a pathname belongs to. Business routes under+ * Works are listed by the caller.+ */+export const resolveDocsSection = (+ pathname: string,+ worksPaths: readonly string[] = [],+): DocsSection | null => {+ const segments = resourceSegments(pathname);+ if (!segments) return null;+ const [section] = segments;+ if (!section) return 'home';+ if (section === 'drive') return 'drive';+ if (section === 'library') return 'library';+ if (section === 'works') return 'works';+ if (worksPaths.includes(`${RESOURCE_HOME_PATH}/${section}`)) return 'works';+ return null;+};diff --git a/src/features/ResourceHome/recentLibraries.test.ts b/src/features/ResourceHome/recentLibraries.test.tsnew file mode 100644index 00000000000..899e69f1853--- /dev/null+++ b/src/features/ResourceHome/recentLibraries.test.ts@@ -0,0 +1,49 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it } from 'vitest';++import { pickRecentLibraries, recordLibraryVisit, useLibraryVisits } from './recentLibraries';++const lib = (id: string, updatedAt: string) => ({ id, updatedAt });++describe('pickRecentLibraries', () => {+ const libraries = [+ lib('a', '2026-01-01'),+ lib('b', '2026-03-01'),+ lib('c', '2026-02-01'),+ lib('d', '2026-04-01'),+ ];++ it('orders opened libraries by their last visit', () => {+ const picked = pickRecentLibraries(libraries, { a: 300, c: 200 }, 2);++ expect(picked.map((item) => item.id)).toEqual(['a', 'c']);+ });++ it('fills the remaining slots with unvisited libraries by update time', () => {+ const picked = pickRecentLibraries(libraries, { a: 300 }, 3);++ expect(picked.map((item) => item.id)).toEqual(['a', 'd', 'b']);+ });++ it('ignores visits to libraries outside the current list', () => {+ const picked = pickRecentLibraries(libraries, { gone: 999 }, 1);++ expect(picked.map((item) => item.id)).toEqual(['d']);+ });+});++describe('recordLibraryVisit', () => {+ beforeEach(() => {+ window.localStorage.clear();+ });++ it('updates subscribers with the latest visit', () => {+ const { result } = renderHook(() => useLibraryVisits());+ expect(result.current).toEqual({});++ act(() => recordLibraryVisit('kb-1', 100));+ act(() => recordLibraryVisit('kb-2', 200));++ expect(result.current).toEqual({ 'kb-1': 100, 'kb-2': 200 });+ });+});diff --git a/src/features/ResourceHome/recentLibraries.ts b/src/features/ResourceHome/recentLibraries.tsnew file mode 100644index 00000000000..cfd23d9bce4--- /dev/null+++ b/src/features/ResourceHome/recentLibraries.ts@@ -0,0 +1,93 @@+import { useSyncExternalStore } from 'react';++/**+ * Local record of when each library was last opened, for the Docs sidebar's+ * "Recent libraries" section. Device-local on purpose: it orders a shortcut+ * list and carries no meaning worth a server round-trip. Library ids are+ * globally unique and the section intersects them with the active scope's+ * list, so one map serves every workspace.+ */+const STORAGE_KEY = 'LOBE_DOCS_RECENT_LIBRARIES';+const CHANGE_EVENT = 'lobe-docs-recent-libraries';+/** Visits kept; older entries fall off so the map stays bounded. */+const MAX_ENTRIES = 50;++export const RECENT_LIBRARY_LIMIT = 5;++export type LibraryVisits = Record<string, number>;++const EMPTY_VISITS: LibraryVisits = {};++let cachedRaw: string | null = null;+let cachedVisits: LibraryVisits = EMPTY_VISITS;++const readVisits = (): LibraryVisits => {+ if (typeof window === 'undefined') return EMPTY_VISITS;+ let raw: string | null;+ try {+ raw = window.localStorage.getItem(STORAGE_KEY);+ } catch {+ return EMPTY_VISITS;+ }+ if (raw === cachedRaw) return cachedVisits;++ cachedRaw = raw;+ try {+ const parsed = raw ? JSON.parse(raw) : null;+ cachedVisits = parsed && typeof parsed === 'object' ? (parsed as LibraryVisits) : EMPTY_VISITS;+ } catch {+ cachedVisits = EMPTY_VISITS;+ }+ return cachedVisits;+};++export const recordLibraryVisit = (libraryId: string, now: number = Date.now()): void => {+ if (typeof window === 'undefined' || !libraryId) return;++ const entries = Object.entries({ ...readVisits(), [libraryId]: now })+ .sort(([, a], [, b]) => b - a)+ .slice(0, MAX_ENTRIES);++ try {+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(Object.fromEntries(entries)));+ } catch {+ // Storage full or blocked: the section falls back to update order.+ return;+ }+ window.dispatchEvent(new Event(CHANGE_EVENT));+};++const subscribe = (onChange: () => void) => {+ const onStorage = (event: StorageEvent) => {+ if (event.key === STORAGE_KEY) onChange();+ };+ window.addEventListener(CHANGE_EVENT, onChange);+ window.addEventListener('storage', onStorage);+ return () => {+ window.removeEventListener(CHANGE_EVENT, onChange);+ window.removeEventListener('storage', onStorage);+ };+};++export const useLibraryVisits = (): LibraryVisits =>+ useSyncExternalStore(subscribe, readVisits, () => EMPTY_VISITS);++const timeOf = (value: Date | string | number | undefined): number =>+ value === undefined ? 0 : new Date(value).getTime() || 0;++/**+ * The libraries the section lists: most recently opened first; libraries never+ * opened on this device follow by last update, so a fresh device still shows a+ * useful shortcut list.+ */+export const pickRecentLibraries = <T extends { id: string; updatedAt?: Date | string }>(+ libraries: T[],+ visits: LibraryVisits,+ limit: number = RECENT_LIBRARY_LIMIT,+): T[] =>+ [...libraries]+ .sort((a, b) => {+ const visitDiff = (visits[b.id] ?? 0) - (visits[a.id] ?? 0);+ return visitDiff !== 0 ? visitDiff : timeOf(b.updatedAt) - timeOf(a.updatedAt);+ })+ .slice(0, limit);diff --git a/src/features/ResourceHome/skeletonView.test.ts b/src/features/ResourceHome/skeletonView.test.tsindex e6547feb5f5..aadc2e4fed7 100644--- a/src/features/ResourceHome/skeletonView.test.ts+++ b/src/features/ResourceHome/skeletonView.test.ts@@ -4,10 +4,12 @@ import { resolveResourceSkeletonView } from './skeletonView';describe('resolveResourceSkeletonView', () => {it.each([- ['/resource/files', null, 'list'],- ['/resource/images', null, 'masonry'],- ['/resource/images', 'list', 'list'],+ ['/resource/drive', null, 'list'],+ ['/resource/drive/files', null, 'list'],+ ['/resource/drive/images', null, 'masonry'],+ ['/resource/drive/images', 'list', 'list'],['/resource/works', null, 'works'],+ ['/team/resource/library', null, 'libraries'],])('uses the settled view for %s', (pathname, requestedView, expected) => {expect(resolveResourceSkeletonView(pathname, requestedView)).toBe(expected);});diff --git a/src/features/ResourceHome/skeletonView.ts b/src/features/ResourceHome/skeletonView.tsindex 040d17adf5f..37c18483bb5 100644--- a/src/features/ResourceHome/skeletonView.ts+++ b/src/features/ResourceHome/skeletonView.ts@@ -1,7 +1,7 @@import { getDefaultResourceViewMode } from '@/features/ResourceManager/components/Explorer/viewMode';import type { FilesTabs } from '@/types/files';-export type ResourceSkeletonView = 'list' | 'masonry' | 'works';+export type ResourceSkeletonView = 'libraries' | 'list' | 'masonry' | 'works';export const resolveResourceSkeletonView = (pathname: string,@@ -10,6 +10,7 @@ export const resolveResourceSkeletonView = (const segment = pathname.split('/').findLast(Boolean);if (segment === 'works') return 'works';+ if (segment === 'library') return 'libraries';if (requestedView === 'list' || requestedView === 'masonry') return requestedView;return getDefaultResourceViewMode(segment as FilesTabs);diff --git a/src/features/ResourceLibrary/Layout/index.tsx b/src/features/ResourceLibrary/Layout/index.tsxindex 10d9d081ac0..1a8df830422 100644--- a/src/features/ResourceLibrary/Layout/index.tsx+++ b/src/features/ResourceLibrary/Layout/index.tsx@@ -1,11 +1,12 @@'use client';import { Button, Flexbox } from '@lobehub/ui';-import { type FC } from 'react';+import { type FC, useEffect } from 'react';import { useTranslation } from 'react-i18next';import { Outlet, useParams } from 'react-router';import AsyncError from '@/components/AsyncError';+import { recordLibraryVisit } from '@/features/ResourceHome/recentLibraries';import RegisterHotkeys from '@/features/ResourceLibrary/RegisterHotkeys';import { useKnowledgeBaseItem } from '@/features/ResourceManager/hooks/useKnowledgeItem';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';@@ -21,6 +22,11 @@ const LibraryLayout: FC = () => {// Same SWR key as the page content's fetch, so this costs no extra request.const { error } = useKnowledgeBaseItem(id || '');+ // Orders the Docs sidebar's "Recent libraries" shortcut list.+ useEffect(() => {+ if (id && !error) recordLibraryVisit(id);+ }, [id, error]);+// A restricted KB (resource-permission `use` level) 403s for members. Catch// it at the layout so the route shows one error page in the content area// (the nav slot stays an idle skeleton), instead of the sidebar and thediff --git a/src/features/ResourceLibrary/LibraryHero.tsx b/src/features/ResourceLibrary/LibraryHero.tsxnew file mode 100644index 00000000000..8602752d7dd--- /dev/null+++ b/src/features/ResourceLibrary/LibraryHero.tsx@@ -0,0 +1,65 @@+'use client';++import { Flexbox, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import LibraryStatusIcon from '@/components/LibIcon/StatusIcon';+import type { KnowledgeBaseItem } from '@/types/knowledgeBase';++const styles = stylex.create({+ description: {+ overflow: 'hidden',+ display: '-webkit-box',+ WebkitBoxOrient: 'vertical',+ WebkitLineClamp: 2,+ maxWidth: '720px',+ fontSize: '13px',+ lineHeight: '20px',+ color: cssVar.colorTextSecondary,+ },+ title: {+ margin: 0,+ fontSize: '22px',+ fontWeight: 600,+ color: cssVar.colorText,+ },+});++interface LibraryHeroProps {+ library: KnowledgeBaseItem;+}++/**+ * The top of a knowledge base's root view: its name and description. The cover+ * belongs to the gallery card; it is changed from the edit form, not here.+ */+const LibraryHero = memo<LibraryHeroProps>(({ library }) => {+ const { t } = useTranslation('file');++ return (+ <Flexbox flex={'none'} gap={6} paddingBlock={20} paddingInline={24}>+ <Flexbox horizontal align={'center'} gap={8}>+ <LibraryStatusIcon+ memberRestricted={(library as { memberRestricted?: boolean }).memberRestricted}+ size={20}+ visibility={library.visibility}+ />+ <h1 {...stylex.props(styles.title)}>{library.name}</h1>+ </Flexbox>+ {library.description ? (+ <div {...stylex.props(styles.description)}>{library.description}</div>+ ) : (+ <Text fontSize={13} type={'secondary'}>+ {t('docs.library.noDescription')}+ </Text>+ )}+ </Flexbox>+ );+});++LibraryHero.displayName = 'LibraryHero';++export default LibraryHero;diff --git a/src/features/ResourceLibrary/index.tsx b/src/features/ResourceLibrary/index.tsxindex 754632caa27..c155c78dfd7 100644--- a/src/features/ResourceLibrary/index.tsx+++ b/src/features/ResourceLibrary/index.tsx@@ -14,8 +14,10 @@ import { useKnowledgeBaseItem } from '@/features/ResourceManager/hooks/useKnowleimport { useResourceManagerStore } from '@/features/ResourceManager/store';import { isForbiddenError } from '@/utils/forbiddenError';+import LibraryHero from './LibraryHero';+const MainContent = memo(() => {- const { id: knowledgeBaseId } = useParams<{ id: string }>();+ const { id: knowledgeBaseId, slug } = useParams<{ id: string; slug?: string }>();const location = useLocation();const setLibraryId = useResourceManagerStore((s) => s.setLibraryId);@@ -58,7 +60,8 @@ const MainContent = memo(() => {if (!data) return <NotFound />;- return <ResourceManager />;+ // The cover header belongs to the library's root, not to every folder in it.+ return <ResourceManager explorerHero={slug ? undefined : <LibraryHero library={data} />} />;});MainContent.displayName = 'LibraryMainContent';diff --git a/src/features/ResourceManager/Layout/index.tsx b/src/features/ResourceManager/Layout/index.tsxindex e169f43b1f2..40c125bfda9 100644--- a/src/features/ResourceManager/Layout/index.tsx+++ b/src/features/ResourceManager/Layout/index.tsx@@ -3,9 +3,13 @@import { type FC } from 'react';import { Outlet } from 'react-router';+import { useDocsMergeNotice } from '@/features/ResourceHome/MergeNotice';+import RegisterHotkeys from './RegisterHotkeys';const ResourceLayout: FC = () => {+ useDocsMergeNotice();+return (<><Outlet />diff --git a/src/features/ResourceManager/components/Explorer/Header/DriveCategoryTabs.tsx b/src/features/ResourceManager/components/Explorer/Header/DriveCategoryTabs.tsxnew file mode 100644index 00000000000..6cf79079881--- /dev/null+++ b/src/features/ResourceManager/components/Explorer/Header/DriveCategoryTabs.tsx@@ -0,0 +1,55 @@+'use client';++import { Segmented } from '@lobehub/ui';+import { memo, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { driveCategoryPath } from '@/features/ResourceHome/paths';+import { useResourceManagerStore } from '@/features/ResourceManager/store';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { FilesTabs } from '@/types/files';++/** File types the drive filters by; `Files` (the misc raw-data bucket) sits last. */+const DRIVE_CATEGORIES = [+ FilesTabs.All,+ FilesTabs.Documents,+ FilesTabs.Images,+ FilesTabs.Videos,+ FilesTabs.Audios,+ FilesTabs.Files,+] as const;++/**+ * The drive's file-type switch. It lives in the content header rather than the+ * sidebar so the sidebar keeps only the four Docs sections.+ */+const DriveCategoryTabs = memo(() => {+ const { t } = useTranslation('file');+ const [category, setMode] = useResourceManagerStore((s) => [s.category, s.setMode]);+ const navigate = useWorkspaceAwareNavigate();++ const options = useMemo(+ () =>+ DRIVE_CATEGORIES.map((value) => ({+ label: value === FilesTabs.All ? t('docs.drive.all') : t(`tab.${value}`),+ value,+ })),+ [t],+ );++ return (+ <Segmented+ options={options}+ size={'small'}+ value={category}+ onChange={(value) => {+ setMode('explorer');+ navigate(driveCategoryPath(value as FilesTabs), { replace: true });+ }}+ />+ );+});++DriveCategoryTabs.displayName = 'DriveCategoryTabs';++export default DriveCategoryTabs;diff --git a/src/features/ResourceManager/components/Explorer/Header/index.tsx b/src/features/ResourceManager/components/Explorer/Header/index.tsxindex a575ef6a775..268f302ea7f 100644--- a/src/features/ResourceManager/components/Explorer/Header/index.tsx+++ b/src/features/ResourceManager/components/Explorer/Header/index.tsx@@ -13,7 +13,6 @@ import { getExplorerSelectedCount } from '@/features/ResourceManager/store/selecimport { openWorkspaceDeleteAllModal } from '@/features/WorkspaceDeleteAllModal';import { usePermission } from '@/hooks/usePermission';import { useFileStore } from '@/store/file';-import { FilesTabs } from '@/types/files';import AddButton from '../../Header/AddButton';import BatchActionsDropdown from '../ToolBar/BatchActionsDropdown';@@ -21,6 +20,7 @@ import SortDropdown from '../ToolBar/SortDropdown';import SourceFilter from '../ToolBar/SourceFilter';import ViewSwitcher from '../ToolBar/ViewSwitcher';import Breadcrumb from './Breadcrumb';+import DriveCategoryTabs from './DriveCategoryTabs';import SearchInput from './SearchInput';/**@@ -60,7 +60,7 @@ const Header = memo(() => {const isWorkspaceDeleteAll = !!activeWorkspaceId && selectAllState === 'all';const batchTransferActions = useFileBatchTransferActions(selectCount);- // If no libraryId, show category name or "Resource" for All+ // Outside a library the explorer is the drive: its header switches file typesconst leftContent = hasSelected ? (<Flexbox horizontal align={'center'} gap={8} style={{ marginLeft: 0 }}>{libraryId ? (@@ -163,10 +163,8 @@ const Header = memo(() => {/></Flexbox>) : !libraryId ? (- <Flexbox style={{ marginLeft: 8 }}>- {category === FilesTabs.All- ? t('resource', { ns: 'file' })- : t(`tab.${category as FilesTabs}` as any, { ns: 'file' })}+ <Flexbox style={{ marginLeft: 4 }}>+ <DriveCategoryTabs /></Flexbox>) : (<Flexbox horizontal align={'center'} gap={4} style={{ marginLeft: 8 }}>diff --git a/src/features/ResourceManager/components/Explorer/LibraryTags.tsx b/src/features/ResourceManager/components/Explorer/LibraryTags.tsxnew file mode 100644index 00000000000..c0b4c7c66bf--- /dev/null+++ b/src/features/ResourceManager/components/Explorer/LibraryTags.tsx@@ -0,0 +1,61 @@+'use client';++import { Tag, Tooltip } from '@lobehub/ui';+import { memo, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { knowledgeBaseSelectors, useKnowledgeBaseStore } from '@/store/library';++interface LibraryTagsProps {+ knowledgeBaseIds?: string[];+}++const stopPropagation = (e: { stopPropagation: () => void }) => e.stopPropagation();++/**+ * The libraries a drive row is filed into. The drive lists every file, so the+ * tag is what tells "already organized" apart from loose uploads. Libraries the+ * caller cannot list (a teammate's private one) are left out.+ */+const LibraryTags = memo<LibraryTagsProps>(({ knowledgeBaseIds }) => {+ const { t } = useTranslation('file');+ const navigate = useWorkspaceAwareNavigate();+ const libraries = useKnowledgeBaseStore(knowledgeBaseSelectors.getKnowledgeBaseList());++ const names = useMemo(() => {+ if (!knowledgeBaseIds?.length || !libraries) return [];+ const byId = new Map(libraries.map((library) => [library.id, library.name]));+ return knowledgeBaseIds.flatMap((id) => {+ const name = byId.get(id);+ return name ? [{ id, name }] : [];+ });+ }, [knowledgeBaseIds, libraries]);++ if (names.length === 0) return null;++ const [first, ...rest] = names;++ return (+ <Tooltip title={t('docs.drive.inLibraries', { names: names.map((n) => n.name).join(', ') })}>+ <Tag+ size={'small'}+ style={{ cursor: 'pointer', flex: 'none', maxWidth: 160 }}+ onPointerDown={stopPropagation}+ onClick={(e) => {+ e.stopPropagation();+ navigate(`/resource/library/${first.id}`);+ }}+ >+ <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>+ {first.name}+ </span>+ {rest.length > 0 && ` +${rest.length}`}+ </Tag>+ </Tooltip>+ );+});++LibraryTags.displayName = 'LibraryTags';++export default LibraryTags;diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemName.tsx b/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemName.tsxindex 6468d29dc26..a15a9cfa4d2 100644--- a/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemName.tsx+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemName.tsx@@ -3,6 +3,7 @@ import { FileText, FolderIcon, LockIcon } from 'lucide-react';import FileIcon from '@/components/FileIcon';+import LibraryTags from '../../LibraryTags';import { styles } from './styles';import TruncatedFileName from './TruncatedFileName';@@ -20,6 +21,8 @@ interface FileListItemNameProps {*/isPrivate?: boolean;isRenaming: boolean;+ /** Libraries the row is filed into, tagged after the name in the drive. */+ knowledgeBaseIds?: string[];name: string;onRenameCancel: () => void;onRenameConfirm: () => void;@@ -37,6 +40,7 @@ const FileListItemName = ({isPage,isPrivate,isRenaming,+ knowledgeBaseIds,name,onRenameCancel,onRenameConfirm,@@ -91,7 +95,10 @@ const FileListItemName = ({}}/>) : (- <TruncatedFileName className={styles.name} name={name || fallbackName} />+ <>+ <TruncatedFileName className={styles.name} name={name || fallbackName} />+ <LibraryTags knowledgeBaseIds={knowledgeBaseIds} />+ </>)}</Flexbox>);diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx b/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsxindex e8880bb264a..50b93f1222a 100644--- a/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx@@ -154,6 +154,7 @@ const FileListItem = ({finishEmbedding,id,index,+ knowledgeBaseIds,metadata,name,onSelectedChange,@@ -345,6 +346,7 @@ const FileListItem = ({isPage={isPage}isPrivate={isPrivate}isRenaming={isRenaming}+ knowledgeBaseIds={resourceManagerState.libraryId ? undefined : knowledgeBaseIds}name={name}privateTooltip={t('resources.visibility.privateTooltip', { ns: 'chat' })}renamingValue={renamingValue}diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsxindex 725471df61b..6fd3337fabb 100644--- a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx+++ b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx@@ -29,6 +29,7 @@ import { type FileListItem } from '@/types/files';import { useFileItemClick, useFileItemDoubleClick } from '../../hooks/useFileItemClick';import DropdownMenu from '../../ItemDropdown/DropdownMenu';import { useFileItemDropdown } from '../../ItemDropdown/useFileItemDropdown';+import LibraryTags from '../../LibraryTags';import AudioFileItem from './AudioFileItem';import DefaultFileItem from './DefaultFileItem';import ImageFileItem from './ImageFileItem';@@ -136,6 +137,14 @@ const styles = createStaticStyles(({ css }) => ({* point of the badge is that a private card is recognisable at a glance while* scanning a library that mixes both scopes.*/+ libraryBadge: css`+ position: absolute;+ z-index: 2;+ inset-block-end: 8px;+ inset-inline-end: 8px;++ max-width: calc(100% - 56px);+ `,privateBadge: css`position: absolute;z-index: 2;@@ -216,6 +225,7 @@ const MasonryFileItem = memo<MasonryFileItemProps>(chunkingStatus,onSelectedChange,knowledgeBaseId,+ knowledgeBaseIds,size,onOpen,metadata,@@ -406,6 +416,12 @@ const MasonryFileItem = memo<MasonryFileItemProps>(<DropdownMenu items={menuItems} /></div>+ {!knowledgeBaseId && !!knowledgeBaseIds?.length && (+ <div className={styles.libraryBadge}>+ <LibraryTags knowledgeBaseIds={knowledgeBaseIds} />+ </div>+ )}+{isPrivate && (<Tooltip title={t('resources.visibility.privateTooltip', { ns: 'chat' })}><div className={styles.privateBadge}>diff --git a/src/features/ResourceManager/components/Explorer/index.test.tsx b/src/features/ResourceManager/components/Explorer/index.test.tsxindex 8fecb89ba77..5dc10aaa63e 100644--- a/src/features/ResourceManager/components/Explorer/index.test.tsx+++ b/src/features/ResourceManager/components/Explorer/index.test.tsx@@ -93,16 +93,17 @@ describe('ResourceExplorer', () => {mocks.useFetchResources.mockReturnValue({ isLoading: false, isValidating: false });});- it('keeps library contents excluded from the All resource query', () => {+ it('lists every uploaded file, library ones included, and no pages in the drive', () => {render(<ResourceExplorer />);expect(mocks.useFetchResources).toHaveBeenCalledWith(expect.objectContaining({category: FilesTabs.All,+ filesOnly: true,includeContentPreview: false,libraryId: undefined,parentId: null,- showFilesInKnowledgeBase: false,+ showFilesInKnowledgeBase: true,}),);});@@ -154,4 +155,18 @@ describe('ResourceExplorer', () => {}),);});++ it('lists the library own rows, pages and folders included, inside a library', () => {+ mocks.resourceManagerState.libraryId = 'kb-shared';++ render(<ResourceExplorer />);++ expect(mocks.useFetchResources).toHaveBeenCalledWith(+ expect.objectContaining({+ filesOnly: false,+ libraryId: 'kb-shared',+ showFilesInKnowledgeBase: false,+ }),+ );+ });});diff --git a/src/features/ResourceManager/components/Explorer/index.tsx b/src/features/ResourceManager/components/Explorer/index.tsxindex 5790f7d9410..0033f48dbcc 100644--- a/src/features/ResourceManager/components/Explorer/index.tsx+++ b/src/features/ResourceManager/components/Explorer/index.tsx@@ -1,7 +1,7 @@'use client';import { Flexbox } from '@lobehub/ui';-import { memo, useMemo } from 'react';+import { memo, type ReactNode, useMemo } from 'react';import AsyncBoundary from '@/components/AsyncBoundary';import { useFolderPath } from '@/features/ResourceManager/hooks/useFolderPath';@@ -32,7 +32,12 @@ import { useCheckTaskStatus } from './useCheckTaskStatus';* It's a un-reusable component for business logic only.* So we depend on context, not props.*/-const ResourceExplorer = memo(() => {+interface ResourceExplorerProps {+ /** Rendered between the toolbar and the list (a library's cover header). */+ hero?: ReactNode;+}++const ResourceExplorer = memo<ResourceExplorerProps>(({ hero }) => {// Sync store state with URL query parametersuseResourceManagerUrlSync();@@ -66,10 +71,13 @@ const ResourceExplorer = memo(() => {// Only use category filter when NOT in a specific library// When viewing a library, show all items regardless of categorycategory: libraryId ? undefined : category,+ // Outside a library the explorer is the drive: every uploaded file,+ // including those filed into libraries (tagged on the row), and no pages.+ filesOnly: !libraryId,includeContentPreview: viewMode === 'masonry',libraryId,parentId: currentFolderSlug || null,- showFilesInKnowledgeBase: false,+ showFilesInKnowledgeBase: !libraryId,sortType,sorter,sourceFilter,@@ -136,6 +144,7 @@ const ResourceExplorer = memo(() => {<KnowledgeBaseListProvider><Flexbox height={'100%'}><Header />+ {hero}<Flexbox horizontal flex={1} style={{ minHeight: 0, overflow: 'hidden' }}><div style={{ flex: 1, overflow: 'hidden', position: 'relative', minWidth: 0 }}>{/*diff --git a/src/features/ResourceManager/hooks/useInitFileCheck.ts b/src/features/ResourceManager/hooks/useInitFileCheck.tsindex fea8cf93dde..5ed84d2dd2b 100644--- a/src/features/ResourceManager/hooks/useInitFileCheck.ts+++ b/src/features/ResourceManager/hooks/useInitFileCheck.ts@@ -12,16 +12,19 @@ import { useResourceManagerStore } from '../store';/*** Used for initial loading only, handle URL like:*- * /resource?file=xxxxxx+ * /resource/drive?file=xxxxxx+ *+ * `pathFileId` is the item a route path names (`/resource/file/:id`,+ * `/resource/page/:id`); it wins over the `?file=` query.*/-export const useInitFileCheck = () => {+export const useInitFileCheck = (pathFileId?: string | null) => {const [searchParams] = useSearchParams();const [setMode, setCurrentViewItemId] = useResourceManagerStore((s) => [s.setMode,s.setCurrentViewItemId,]);- const fileId = searchParams.get('file');+ const fileId = pathFileId ?? searchParams.get('file');const useFetchKnowledgeItem = useFileStore((s) => s.useFetchKnowledgeItem);const { data: fileData } = useFetchKnowledgeItem(fileId || undefined);diff --git a/src/features/ResourceManager/index.tsx b/src/features/ResourceManager/index.tsxindex aaed7b176a2..0710676dbfe 100644--- a/src/features/ResourceManager/index.tsx+++ b/src/features/ResourceManager/index.tsx@@ -2,11 +2,13 @@import { createStaticStyles, Flexbox, useTheme } from '@lobehub/ui';import { memo, type ReactNode, useCallback, useMemo } from 'react';-import { useSearchParams } from 'react-router';+import { useLocation, useSearchParams } from 'react-router';import DragUploadZone from '@/components/DragUploadZone';import { PageEditor } from '@/features/PageEditor';+import { RESOURCE_HOME_PATH } from '@/features/ResourceHome/paths';import { useResourceManagerStore } from '@/features/ResourceManager/store';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { usePermission } from '@/hooks/usePermission';import dynamic from '@/libs/next/dynamic';import { invalidateDocumentMutation } from '@/services/document/invalidation';@@ -48,6 +50,9 @@ const styles = createStaticStyles(({ css, cssVar }) => {};});+/** A page or file opened over the Docs home by path. */+const OPENED_ITEM_PATH = /\/resource\/(?:file|page)\/[^/]+\/?$/;+export type ResourceManagerMode = 'editor' | 'explorer' | 'page';/**@@ -61,11 +66,15 @@ interface ResourceManagerProps {* dashboard) while keeping the editor overlays, upload dock and drag zone.*/content?: ReactNode;+ /** Shown above the Explorer list, e.g. the library cover at a library's root. */+ explorerHero?: ReactNode;}-const ResourceManager = memo<ResourceManagerProps>(({ content }) => {+const ResourceManager = memo<ResourceManagerProps>(({ content, explorerHero }) => {const theme = useTheme();const [, setSearchParams] = useSearchParams();+ const location = useLocation();+ const navigate = useWorkspaceAwareNavigate();const [mode, currentViewItemId, libraryId, setMode, setCurrentViewItemId] =useResourceManagerStore((s) => [s.mode,@@ -105,6 +114,11 @@ const ResourceManager = memo<ResourceManagerProps>(({ content }) => {const handleBack = () => {setMode('explorer');setCurrentViewItemId(undefined);+ // An item opened by path (`/resource/{file,page}/:id`) goes back to the Docs home.+ if (OPENED_ITEM_PATH.test(location.pathname)) {+ navigate(RESOURCE_HOME_PATH);+ return;+ }// Remove the file query parameter from URLsetSearchParams((prev) => {prev.delete('file');@@ -132,7 +146,7 @@ const ResourceManager = memo<ResourceManagerProps>(({ content }) => {<Flexbox className={styles.container} height={'100%'} style={cssVariables}>{/* Explorer stays mounted to preserve its state, unless the callerswaps in its own base content (resource home dashboard) */}- {content ?? <Explorer />}+ {content ?? <Explorer hero={explorerHero} />}{/* Editor overlay */}{mode === 'editor' && (diff --git a/src/features/ResourceManager/store/action.ts b/src/features/ResourceManager/store/action.tsindex c8232e7900d..7157673fd54 100644--- a/src/features/ResourceManager/store/action.ts+++ b/src/features/ResourceManager/store/action.ts@@ -84,12 +84,13 @@ const fetchExplorerSearchPage = async (const response = await resourceService.queryResources({category: params.category,+ filesOnly: !params.libraryId,includeContentPreview: params.includeContentPreview,libraryId: params.libraryId,limit: pageSize,offset: (cursor ?? 0) * pageSize,q: params.q,- showFilesInKnowledgeBase: false,+ showFilesInKnowledgeBase: !params.libraryId,sourceFilter: params.sourceFilter,visibility: params.visibility,});diff --git a/src/features/WorkGallery/WorksTypeTabs.tsx b/src/features/WorkGallery/WorksTypeTabs.tsxnew file mode 100644index 00000000000..360564fba50--- /dev/null+++ b/src/features/WorkGallery/WorksTypeTabs.tsx@@ -0,0 +1,66 @@+'use client';++import { Segmented } from '@lobehub/ui';+import { memo, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { useBusinessResourceCategories } from '@/business/client/features/ResourceCategories';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';++/** Works types every deployment has; business types append after them. */+const WORK_TYPES = [+ { key: 'all', titleKey: 'docs.works.all', url: '/resource/works' },+ { key: 'task', titleKey: 'docs.works.task', url: '/resource/works?works=task' },+ { key: 'document', titleKey: 'docs.works.document', url: '/resource/works?works=document' },+] as const;++interface WorksTypeTabsProps {+ /** A `?works=` key (`all` / `task` / `document`) or a business category key. */+ activeKey: string;+}++/**+ * One Works section, many output types: the switch keeps Agent output in a+ * single place while each type keeps its own view and route.+ */+const WorksTypeTabs = memo<WorksTypeTabsProps>(({ activeKey }) => {+ const { t } = useTranslation('file');+ const navigate = useWorkspaceAwareNavigate();+ const businessCategories = useBusinessResourceCategories();++ const options = useMemo(+ () => [+ ...WORK_TYPES.map((type) => ({+ label: t(type.titleKey),+ url: type.url,+ value: type.key as string,+ })),+ ...businessCategories.map((category) => ({+ // Business categories carry a `file` key typed as a plain string.+ label: t(category.titleKey as never) as string,+ url: category.url,+ value: category.key,+ })),+ ],+ [businessCategories, t],+ );++ // Narrower provider keys (linear / github) have no tab; they read as "All".+ const value = options.some((option) => option.value === activeKey) ? activeKey : 'all';++ return (+ <Segmented+ options={options.map(({ label, value }) => ({ label, value }))}+ size={'small'}+ value={value}+ onChange={(next) => {+ const target = options.find((option) => option.value === next);+ if (target) navigate(target.url, { replace: true });+ }}+ />+ );+});++WorksTypeTabs.displayName = 'WorksTypeTabs';++export default WorksTypeTabs;diff --git a/src/features/WorkGallery/index.tsx b/src/features/WorkGallery/index.tsxindex e13402ab0fc..983f177d60c 100644--- a/src/features/WorkGallery/index.tsx+++ b/src/features/WorkGallery/index.tsx@@ -24,6 +24,7 @@ import { useWorkspaceWorksInfinite } from './hooks';import WorkGallerySkeleton, { WorkGalleryCardsSkeleton } from './Skeleton';import { useOpenWork } from './useOpenWork';import WorkPreviewCard from './WorkPreviewCard';+import WorksTypeTabs from './WorksTypeTabs';const styles = createStaticStyles(({ css }) => ({agentFilter: css`@@ -124,6 +125,11 @@ const styles = createStaticStyles(({ css }) => ({color: ${cssVar.colorText};}`,+ typeBar: css`+ flex: none;+ padding-block: 12px 0;+ padding-inline: 24px;+ `,scroll: css`overflow: hidden auto;flex: 1;@@ -314,10 +320,20 @@ const WorkGallery = memo<WorkGalleryProps>(({ galleryKey }) => {);};+ const typeTabs = (+ <Flexbox className={styles.typeBar}>+ <WorksTypeTabs activeKey={galleryKey} />+ </Flexbox>+ );+return isLoadingInitial && items.length === 0 ? (- <WorkGallerySkeleton />+ <Flexbox className={styles.container}>+ {typeTabs}+ <WorkGallerySkeleton />+ </Flexbox>) : (<Flexbox className={styles.container}>+ {typeTabs}{agentIds.length > 0 && (<Flexbox horizontal align={'center'} className={styles.filterBar} gap={4}><Buttondiff --git a/src/routes/(main)/page/[id]/index.tsx b/src/routes/(main)/page/[id]/index.tsxdeleted file mode 100644index 1de42296760..00000000000--- a/src/routes/(main)/page/[id]/index.tsx+++ /dev/null@@ -1,35 +0,0 @@-'use client';--import { useUnmount } from 'ahooks';-import { memo, Suspense } from 'react';-import { useParams } from 'react-router';-import { createStoreUpdater } from 'zustand-utils';--import { delayed } from '@/components/Skeleton/Delayed';-import SurfaceSkeleton from '@/components/Skeleton/Surface';-import PageExplorer from '@/features/PageExplorer';-import { usePageStore } from '@/store/page';-import { getIdFromIdentifier } from '@/utils/identifier';--const PagesPage = memo(() => {- const storeUpdater = createStoreUpdater(usePageStore);- const params = useParams<{ id: string }>();-- const pageId = getIdFromIdentifier(params.id ?? '', 'docs');-- useUnmount(() => {- usePageStore.setState({ selectedPageId: undefined });- });-- storeUpdater('selectedPageId', pageId);-- return (- <Suspense fallback={delayed(<SurfaceSkeleton variant={'editor'} />)}>- <PageExplorer pageId={pageId} />- </Suspense>- );-});--PagesPage.displayName = 'PagesPage';--export default PagesPage;diff --git a/src/routes/(main)/page/index.tsx b/src/routes/(main)/page/index.tsxdeleted file mode 100644index c6f9f8c4fd8..00000000000--- a/src/routes/(main)/page/index.tsx+++ /dev/null@@ -1,17 +0,0 @@-'use client';--import { Suspense } from 'react';--import { delayed } from '@/components/Skeleton/Delayed';-import SurfaceSkeleton from '@/components/Skeleton/Surface';-import PageExplorerPlaceholder from '@/features/PageExplorer/PageExplorerPlaceholder';--const PagesPage = () => {- return (- <Suspense fallback={delayed(<SurfaceSkeleton variant={'editor'} />)}>- <PageExplorerPlaceholder />- </Suspense>- );-};--export default PagesPage;diff --git a/src/routes/(main)/page/redirect.tsx b/src/routes/(main)/page/redirect.tsxnew file mode 100644index 00000000000..257d0a091f6--- /dev/null+++ b/src/routes/(main)/page/redirect.tsx@@ -0,0 +1 @@+export { default } from '@/features/Pages/PagesToDocsRedirect';diff --git a/src/routes/(main)/resource/(home)/library/index.tsx b/src/routes/(main)/resource/(home)/library/index.tsxnew file mode 100644index 00000000000..026fda3c02d--- /dev/null+++ b/src/routes/(main)/resource/(home)/library/index.tsx@@ -0,0 +1 @@+export { default } from '@/features/LibraryGallery';diff --git a/src/routes/(main)/resource/(home)/worksLoader.test.ts b/src/routes/(main)/resource/(home)/worksLoader.test.tsindex 7c7bc1a44db..145378d1a5f 100644--- a/src/routes/(main)/resource/(home)/worksLoader.test.ts+++ b/src/routes/(main)/resource/(home)/worksLoader.test.ts@@ -40,8 +40,9 @@ beforeEach(() => {describe('galleryKeyOfUrl', () => {it.each([- ['https://app.test/resource', 'all'],- ['https://app.test/acme/resource/', 'all'],+ ['https://app.test/resource', null],+ ['https://app.test/acme/resource/', null],+ ['https://app.test/resource/drive', null],['https://app.test/resource/works', 'all'],['https://app.test/resource/works?works=task', 'task'],['https://app.test/resource/works?works=bogus', 'all'],@@ -66,13 +67,13 @@ describe('worksLoader', () => {it('uses the persisted Private / Workspace mode of the active workspace', async () => {mocks.workspaceId = 'ws_private';- await load('https://app.test/resource');+ await load('https://app.test/resource/works');expect(mocks.preHydrateWorkspaceWorks).toHaveBeenLastCalledWith(expect.objectContaining({ visibility: 'private', workspaceId: 'ws_private' }),);mocks.workspaceId = 'ws_other';- await load('https://app.test/resource');+ await load('https://app.test/resource/works');expect(mocks.preHydrateWorkspaceWorks).toHaveBeenLastCalledWith(expect.objectContaining({ visibility: 'public', workspaceId: 'ws_other' }),);@@ -96,7 +97,7 @@ describe('worksLoader', () => {mocks.workspaceId = 'ws_other';mocks.workspaceSlug = 'acme';- await load('https://app.test/acme/resource', { workspaceSlug: 'acme' });+ await load('https://app.test/acme/resource/works', { workspaceSlug: 'acme' });expect(mocks.preHydrateWorkspaceWorks).toHaveBeenCalledWith(expect.objectContaining({ workspaceId: 'ws_other' }),@@ -104,11 +105,16 @@ describe('worksLoader', () => {});it.each([- ['another workspace', 'https://app.test/beta/resource', { workspaceSlug: 'beta' }, 'acme'],- ['the personal space', 'https://app.test/resource', {}, 'acme'],+ [+ 'another workspace',+ 'https://app.test/beta/resource/works',+ { workspaceSlug: 'beta' },+ 'acme',+ ],+ ['the personal space', 'https://app.test/resource/works', {}, 'acme'],['a workspace from the personal space',- 'https://app.test/acme/resource',+ 'https://app.test/acme/resource/works',{ workspaceSlug: 'acme' },null,],diff --git a/src/routes/(main)/resource/(home)/worksLoader.ts b/src/routes/(main)/resource/(home)/worksLoader.tsindex e66c19f2116..986aa7adf73 100644--- a/src/routes/(main)/resource/(home)/worksLoader.ts+++ b/src/routes/(main)/resource/(home)/worksLoader.ts@@ -9,15 +9,13 @@ import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaintimport { workActions } from '@/store/work';/**- * The Work gallery filter a resource URL paints: the dashboard's recent works- * (`/resource`) and the gallery (`/resource/works?works=<key>`). Other- * categories show no Works.+ * The Work gallery filter a resource URL paints: the gallery+ * (`/resource/works?works=<key>`). Other Docs routes show no Works.*/export const galleryKeyOfUrl = (url: URL): WorkGalleryKey | null => {const segment = url.pathname.match(/\/resource(?:\/([^/]+))?\/?$/);- if (!segment) return null;- if (!segment[1]) return 'all';- if (segment[1] !== 'works') return null;+ // Only the Works gallery shows Works; the Docs home lists pages and files.+ if (segment?.[1] !== 'works') return null;return parseWorkGalleryKey(url.searchParams.get('works')) ?? 'all';};diff --git a/src/services/document/index.ts b/src/services/document/index.tsindex a58dc1fae63..83730ad80fc 100644--- a/src/services/document/index.ts+++ b/src/services/document/index.ts@@ -165,10 +165,12 @@ export class DocumentService {}async queryDocuments(params?: {+ creator?: 'others' | 'self';current?: number;fileTypes?: string[];pageSize?: number;sourceTypes?: string[];+ standaloneOnly?: boolean;}): Promise<{ items: DocumentItem[]; total: number }> {return lambdaClient.document.queryDocuments.query(params);}diff --git a/src/services/file/index.ts b/src/services/file/index.tsindex fecd472756e..7e69f6cfa67 100644--- a/src/services/file/index.ts+++ b/src/services/file/index.ts@@ -159,6 +159,11 @@ export class FileService {return lambdaClient.file.updateFile.mutate({ id, ...data });};+ /** The Docs home list: pages and files mixed, newest update first. */+ getDocsHomeItems = async (tab: 'mine' | 'recent' | 'shared', limit?: number) => {+ return lambdaClient.file.homeItems.query({ limit, tab });+ };+getRecentFiles = async (limit?: number, visibility?: QueryFileListParams['visibility']) => {return lambdaClient.file.recentFiles.query({ limit, visibility });};diff --git a/src/services/resource/index.ts b/src/services/resource/index.tsindex de2c769ceec..6a7276abfb2 100644--- a/src/services/resource/index.ts+++ b/src/services/resource/index.ts@@ -43,6 +43,8 @@ const mapToResourceItem = (item: FileListItem): ResourceItem => {id: item.id,+ knowledgeBaseIds: item.knowledgeBaseIds,+// Metadatametadata: item.metadata || undefined,diff --git a/src/spa/router/desktopRouter.meta.desktop.test.ts b/src/spa/router/desktopRouter.meta.desktop.test.tsindex 2aa092ad924..62b3369ab00 100644--- a/src/spa/router/desktopRouter.meta.desktop.test.ts+++ b/src/spa/router/desktopRouter.meta.desktop.test.ts@@ -27,7 +27,7 @@ describe('mainAreaMetaRoutes (Electron adapter)', () => {});it('uses the active resource category for the tab title and icon', () => {- const { static: staticMeta } = matchRouteMeta(mainAreaMetaRoutes, '/resource/images');+ const { static: staticMeta } = matchRouteMeta(mainAreaMetaRoutes, '/resource/drive/images');expect(staticMeta.titleKey).toBe('navigation.resourceImages');expect(staticMeta.icon).toBe(ImageIcon);diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsxindex 645b557a6b4..1682d358881 100644--- a/src/spa/router/desktopRouter.shared.tsx+++ b/src/spa/router/desktopRouter.shared.tsx@@ -3,19 +3,11 @@import {BrainCircuit,Download,- FilePenIcon,- FilesIcon,- FileText,HomeIcon,Image,- ImageIcon,- LayoutPanelTopIcon,- LibraryBigIcon,- Mic2,Scale,Settings,ShapesIcon,- SquarePlay,Video,} from 'lucide-react';import { createElement, type ReactElement } from 'react';@@ -24,7 +16,6 @@ import type { RouteObject } from 'react-router';import {BusinessDesktopRoutesWithMainLayout,BusinessDesktopRoutesWithoutMainLayout,- BusinessResourceRoutes,} from '@/business/client/BusinessDesktopRoutes';import AppsSkeleton from '@/components/Skeleton/Apps';import CommunityHomeSkeleton from '@/components/Skeleton/CommunityHome';@@ -35,7 +26,6 @@ import ConversationSegmentSkeleton from '@/components/Skeleton/Conversation/Segmimport { delayed } from '@/components/Skeleton/Delayed';import GenerationSkeleton from '@/components/Skeleton/Generation';import MemorySkeleton from '@/components/Skeleton/Memory';-import ResourceHomeSkeleton from '@/components/Skeleton/ResourceHome';import ProviderSettingsSkeleton, {ProviderDetailSkeleton,} from '@/components/Skeleton/Settings/Provider';@@ -75,16 +65,15 @@ import { agentDocumentListLoader } from '@/spa/router/agentDocumentListLoader';import { channelDataLoader } from '@/spa/router/channelDataLoader';import { contextListLoader } from '@/spa/router/contextListLoader';import { identitiesListLoader } from '@/spa/router/identitiesListLoader';-import { libraryTreeLoader } from '@/spa/router/libraryTreeLoader';import { pageListLoader } from '@/spa/router/pageListLoader';import { preferenceListLoader } from '@/spa/router/preferenceListLoader';import { projectWorkspaceRoute } from '@/spa/router/projectWorkspaceRoutes';import { agentAccessLoader, agentGroupAccessLoader } from '@/spa/router/resourceAccessLoader';+import { resourceRoute } from '@/spa/router/resourceRoutes';import { NoRouteSkeleton, routeMeta } from '@/spa/router/routeMeta';import { scheduledTaskListLoader } from '@/spa/router/scheduledTaskListLoader';import { taskWorkspaceChildren } from '@/spa/router/taskWorkspaceRoutes';import { withSegmentFallback } from '@/spa/router/withSegmentFallback';-import { worksLoader } from '@/spa/router/worksLoader';import { workspaceSettingsContentRoute } from '@/spa/router/workspaceSettingsRoutes';import { SettingsTabs } from '@/store/global/initialState';import { dynamicElement, dynamicLayout, ErrorBoundary, redirectElement } from '@/utils/router';@@ -103,23 +92,6 @@ const groupChatElement = dynamicElement({ fallback: delayed(<ConversationLayoutSkeleton />), preloadId: 'group' },);-const resourceCategoryRoutes: RouteObject[] = [- { icon: LayoutPanelTopIcon, path: 'all', titleKey: 'navigation.resourceAll' },- { icon: FileText, path: 'documents', titleKey: 'navigation.resourceDocuments' },- { icon: ImageIcon, path: 'images', titleKey: 'navigation.resourceImages' },- { icon: SquarePlay, path: 'videos', titleKey: 'navigation.resourceVideos' },- { icon: Mic2, path: 'audios', titleKey: 'navigation.resourceAudios' },- { icon: FilesIcon, path: 'files', titleKey: 'navigation.resourceFiles' },-].map(({ icon, path, titleKey }) => ({- element: dynamicElement(- () => import('@/routes/(main)/resource/(home)'),- `Desktop > Resource > Home > ${path}`,- { preloadId: 'resource' },- ),- handle: { meta: routeMeta({ icon, titleKey }) },- path,-}));-export interface MainAreaRouteOptions {/** Electron renders Home inside each tab router; Web renders it beside the router outlet. */createHomeElement?: () => ReactElement;@@ -639,120 +611,7 @@ export const sharedMainAreaChildren: RouteObject[] = [path: 'community',},- // Resource routes- {- children: [- // Home routes (resource list)- {- children: [- {- element: dynamicElement(- () => import('@/routes/(main)/resource/(home)'),- 'Desktop > Resource > Home',- { preloadId: 'resource' },- ),- handle: {- meta: routeMeta({- icon: LibraryBigIcon,- Skeleton: ResourceHomeSkeleton,- titleKey: 'navigation.resources',- }),- },- index: true,- loader: worksLoader,- },- ...BusinessResourceRoutes,- ...resourceCategoryRoutes,- // /resource/page needs a static segment: the dynamic `:category`- // ties with the workspace mirror `/:workspaceSlug/page` on route- // score, and the workspace tree would swallow it into a slug 404.- {- element: dynamicElement(- () => import('@/routes/(main)/resource/(home)'),- 'Desktop > Resource > Home > Pages',- { preloadId: 'resource' },- ),- handle: {- meta: routeMeta({ icon: FilePenIcon, titleKey: 'navigation.resourcePages' }),- },- path: 'page',- },- // Category views share the home page: /resource/documents, /resource/images, …- {- element: dynamicElement(- () => import('@/routes/(main)/resource/(home)'),- 'Desktop > Resource > Home > Category',- { preloadId: 'resource' },- ),- handle: {- meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.resources' }),- },- loader: worksLoader,- path: ':category',- },- ],- element: dynamicElement(- () => import('@/routes/(main)/resource/(home)/_layout'),- 'Desktop > Resource > Home > Layout',- { preloadId: 'resource' },- ),- handle: { meta: routeMeta({ Skeleton: ResourceCategorySkeleton }) },- },- // Library routes (knowledge base detail)- {- children: [- {- element: dynamicElement(- () => import('@/routes/(main)/resource/library'),- 'Desktop > Resource > Library',- ),- handle: {- meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.knowledgeBase' }),- },- index: true,- },- {- element: dynamicElement(- () => import('@/routes/(main)/resource/library/permission'),- 'Desktop > Resource > Library > Permission',- ),- handle: {- meta: routeMeta({- icon: LibraryBigIcon,- Skeleton: createSurfaceSkeleton('form'),- titleKey: 'navigation.knowledgeBase',- }),- },- path: 'permission',- },- {- element: dynamicElement(- () => import('@/routes/(main)/resource/library/[slug]'),- 'Desktop > Resource > Library > Slug',- ),- handle: {- meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.knowledgeBase' }),- },- path: ':slug',- },- ],- element: dynamicElement(- () => import('@/routes/(main)/resource/library/_layout'),- 'Desktop > Resource > Library > Layout',- ),- loader: libraryTreeLoader,- path: 'library/:id',- },- ],- element: dynamicElement(- () => import('@/routes/(main)/resource/_layout'),- 'Desktop > Resource > Layout',- { preloadId: 'resource' },- ),- errorElement: <ErrorBoundary />,- handle: { meta: routeMeta({ Skeleton: createSurfaceSkeleton('list') }) },- path: 'resource',- },+ resourceRoute,// Memory routes{@@ -1070,30 +929,18 @@ export const sharedMainAreaChildren: RouteObject[] = [),},- // Pages routes+ // Pages live in Docs: /page → /resource, /page/:id → /resource/page/:id.+ ...(['page', 'page/:id'] as const).map((path) => ({+ element: dynamicElement(+ () => import('@/routes/(main)/page/redirect'),+ `Desktop > Page > Redirect (${path})`,+ ),+ handle: { meta: pageRouteMeta },+ path,+ })),+ // The page permission screen keeps the Pages layout.{children: [- {- element: dynamicElement(() => import('@/routes/(main)/page'), 'Desktop > Page', {- preloadId: 'page',- }),- handle: {- meta: routeMeta({- icon: FilePenIcon,- Skeleton: createSurfaceSkeleton('list'),- titleKey: 'navigation.pages',- }),- },- index: true,- },- {- element: dynamicElement(- () => import('@/routes/(main)/page/[id]'),- 'Desktop > Page > Detail',- ),- handle: { meta: pageRouteMeta },- path: ':id',- },{element: dynamicElement(() => import('@/routes/(main)/page/[id]/permission'),diff --git a/src/spa/router/desktopRouter.sync.test.tsx b/src/spa/router/desktopRouter.sync.test.tsxindex 8975661c268..a44a3e2dc59 100644--- a/src/spa/router/desktopRouter.sync.test.tsx+++ b/src/spa/router/desktopRouter.sync.test.tsx@@ -82,6 +82,7 @@ async function readRouterSources() {'projectWorkspaceRoutes.tsx','taskWorkspaceRoutes.tsx','workspaceSettingsRoutes.tsx',+ 'resourceRoutes.tsx',].map((filename) => readFile(path.join(process.cwd(), 'src/spa/router', filename), 'utf8')),);}@@ -516,9 +517,11 @@ describe('desktop router shared definition', () => {['/apps', AppsSkeleton],['/memory', MemorySkeleton],['/resource', ResourceHomeSkeleton],- ['/resource/files', ResourceCategorySkeleton],- ['/resource/images', ResourceCategorySkeleton],+ ['/resource/drive', ResourceCategorySkeleton],+ ['/resource/drive/files', ResourceCategorySkeleton],+ ['/resource/drive/images', ResourceCategorySkeleton],['/resource/works', ResourceCategorySkeleton],+ ['/resource/library', ResourceCategorySkeleton],] as const) {const matches = matchRoutes(getRoutes(pathname), pathname);expect(@@ -571,13 +574,13 @@ describe('desktop router shared definition', () => {])('%s paints the resource skeleton on its first render, without a chunk wait',(_, getRoutes) => {- const matches = matchRoutes(getRoutes('/resource/files'), '/resource/files');+ const matches = matchRoutes(getRoutes('/resource/drive/files'), '/resource/drive/files');const Skeleton = resolveRouteSkeleton(matches?.map(({ route }) => ({ handle: route.handle })) ?? [],);const html = renderToString(- <MemoryRouter initialEntries={['/resource/files']}>+ <MemoryRouter initialEntries={['/resource/drive/files']}>{Skeleton && <Skeleton />}</MemoryRouter>,);@@ -733,9 +736,10 @@ describe('desktop router shared definition', () => {});it('keeps business resource and task routes in the shared definition', async () => {- const [sharedSource] = await readRouterSources();+ const [sharedSource, , , , , , resourceSource] = await readRouterSources();- expect(sharedSource).toContain('...BusinessResourceRoutes');+ expect(sharedSource).toContain('resourceRoute,');+ expect(resourceSource).toContain('...BusinessResourceRoutes');expect(sharedSource).toContain("import('@/routes/(main)/(task-workspace)/_layout')");expect(sharedSource).toContain("import('@/routes/(main)/agent/task/[taskId]')");expect(sharedSource).not.toContain("import('@/routes/(main)/task-workspace/_layout')");diff --git a/src/spa/router/resourceRoutes.tsx b/src/spa/router/resourceRoutes.tsxnew file mode 100644index 00000000000..192c82a792f--- /dev/null+++ b/src/spa/router/resourceRoutes.tsx@@ -0,0 +1,202 @@+'use client';++import {+ ClipboardListIcon,+ FilePenIcon,+ FilesIcon,+ FileText,+ HardDriveIcon,+ ImageIcon,+ LibraryBigIcon,+ Mic2,+ SquarePlay,+} from 'lucide-react';+import type { RouteObject } from 'react-router';++import { BusinessResourceRoutes } from '@/business/client/BusinessDesktopRoutes';+import ResourceHomeSkeleton from '@/components/Skeleton/ResourceHome';+import { createSurfaceSkeleton } from '@/components/Skeleton/Surface';+import ResourceCategorySkeleton from '@/features/ResourceHome/Skeleton';+import { libraryTreeLoader } from '@/spa/router/libraryTreeLoader';+import { routeMeta } from '@/spa/router/routeMeta';+import { worksLoader } from '@/spa/router/worksLoader';+import { dynamicElement, ErrorBoundary } from '@/utils/router';++// Drive views share the Docs home page: /resource/drive, /resource/drive/images, …+const resourceDriveRoutes: RouteObject[] = [+ { icon: HardDriveIcon, path: 'drive', titleKey: 'navigation.resourceDrive' },+ { icon: FileText, path: 'drive/documents', titleKey: 'navigation.resourceDocuments' },+ { icon: ImageIcon, path: 'drive/images', titleKey: 'navigation.resourceImages' },+ { icon: SquarePlay, path: 'drive/videos', titleKey: 'navigation.resourceVideos' },+ { icon: Mic2, path: 'drive/audios', titleKey: 'navigation.resourceAudios' },+ { icon: FilesIcon, path: 'drive/files', titleKey: 'navigation.resourceFiles' },+ { icon: HardDriveIcon, path: 'drive/:category', titleKey: 'navigation.resourceDrive' },+].map(({ icon, path, titleKey }) => ({+ element: dynamicElement(+ () => import('@/routes/(main)/resource/(home)'),+ `Desktop > Resource > Home > ${path}`,+ { preloadId: 'resource' },+ ),+ handle: { meta: routeMeta({ icon, titleKey }) },+ path,+}));++/**+ * Docs (`/resource`): the home dashboard, the drive, the library gallery and+ * Works share one layout and sidebar; a library opens under `library/:id` with+ * its own sidebar. Shared by the root and the workspace route trees.+ */+export const resourceRoute: RouteObject = {+ children: [+ // Home routes (resource list)+ {+ children: [+ {+ element: dynamicElement(+ () => import('@/routes/(main)/resource/(home)'),+ 'Desktop > Resource > Home',+ { preloadId: 'resource' },+ ),+ handle: {+ meta: routeMeta({+ icon: LibraryBigIcon,+ Skeleton: ResourceHomeSkeleton,+ titleKey: 'navigation.resources',+ }),+ },+ index: true,+ },+ ...BusinessResourceRoutes,+ ...resourceDriveRoutes,+ {+ element: dynamicElement(+ () => import('@/routes/(main)/resource/(home)'),+ 'Desktop > Resource > Home > Works',+ { preloadId: 'resource' },+ ),+ handle: {+ meta: routeMeta({ icon: ClipboardListIcon, titleKey: 'navigation.resourceWorks' }),+ },+ loader: worksLoader,+ path: 'works',+ },+ // Library gallery: every library as a cover card; a library itself+ // opens under `library/:id` with its own sidebar.+ {+ element: dynamicElement(+ () => import('@/routes/(main)/resource/(home)/library'),+ 'Desktop > Resource > Library Gallery',+ { preloadId: 'resource' },+ ),+ handle: {+ meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.knowledgeBase' }),+ },+ path: 'library',+ },+ // Legacy /resource/page (pages left the drive): a static segment, since+ // the dynamic `:category` ties with the workspace mirror+ // `/:workspaceSlug/page` on route score and would be swallowed into a+ // slug 404. The page redirects to the Docs home.+ {+ element: dynamicElement(+ () => import('@/routes/(main)/resource/(home)'),+ 'Desktop > Resource > Home > Pages',+ { preloadId: 'resource' },+ ),+ handle: {+ meta: routeMeta({ icon: FilePenIcon, titleKey: 'navigation.resourcePages' }),+ },+ path: 'page',+ },+ // A page or file opened inside Docs, over the home dashboard.+ ...(+ [+ { icon: FilePenIcon, path: 'page/:id', titleKey: 'navigation.resourcePages' },+ { icon: FilesIcon, path: 'file/:id', titleKey: 'navigation.resourceFiles' },+ ] as const+ ).map(({ icon, path, titleKey }) => ({+ element: dynamicElement(+ () => import('@/routes/(main)/resource/(home)'),+ `Desktop > Resource > Home > ${path}`,+ { preloadId: 'resource' },+ ),+ handle: { meta: routeMeta({ icon, titleKey }) },+ path,+ })),+ // Legacy category paths (/resource/documents, /resource/all, …)+ // redirect into the drive.+ {+ element: dynamicElement(+ () => import('@/routes/(main)/resource/(home)'),+ 'Desktop > Resource > Home > Category',+ { preloadId: 'resource' },+ ),+ handle: {+ meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.resources' }),+ },+ loader: worksLoader,+ path: ':category',+ },+ ],+ element: dynamicElement(+ () => import('@/routes/(main)/resource/(home)/_layout'),+ 'Desktop > Resource > Home > Layout',+ { preloadId: 'resource' },+ ),+ handle: { meta: routeMeta({ Skeleton: ResourceCategorySkeleton }) },+ },+ // Library routes (knowledge base detail)+ {+ children: [+ {+ element: dynamicElement(+ () => import('@/routes/(main)/resource/library'),+ 'Desktop > Resource > Library',+ ),+ handle: {+ meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.knowledgeBase' }),+ },+ index: true,+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/resource/library/permission'),+ 'Desktop > Resource > Library > Permission',+ ),+ handle: {+ meta: routeMeta({+ icon: LibraryBigIcon,+ Skeleton: createSurfaceSkeleton('form'),+ titleKey: 'navigation.knowledgeBase',+ }),+ },+ path: 'permission',+ },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/resource/library/[slug]'),+ 'Desktop > Resource > Library > Slug',+ ),+ handle: {+ meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.knowledgeBase' }),+ },+ path: ':slug',+ },+ ],+ element: dynamicElement(+ () => import('@/routes/(main)/resource/library/_layout'),+ 'Desktop > Resource > Library > Layout',+ ),+ loader: libraryTreeLoader,+ path: 'library/:id',+ },+ ],+ element: dynamicElement(+ () => import('@/routes/(main)/resource/_layout'),+ 'Desktop > Resource > Layout',+ { preloadId: 'resource' },+ ),+ errorElement: <ErrorBoundary />,+ handle: { meta: routeMeta({ Skeleton: createSurfaceSkeleton('list') }) },+ path: 'resource',+};diff --git a/src/store/file/slices/resource/projection.ts b/src/store/file/slices/resource/projection.tsindex 9b58cd56c0c..8184cec98c8 100644--- a/src/store/file/slices/resource/projection.ts+++ b/src/store/file/slices/resource/projection.ts@@ -18,6 +18,8 @@ export const DEFAULT_RESOURCE_PAGE_SIZE = 50;*/export interface ResourceListParams {category?: FilesTabs;+ /** Drive listing: uploaded files only, no pages or folders. */+ filesOnly?: boolean;includeContentPreview?: boolean;libraryId?: string;/**@@ -57,6 +59,7 @@ export const normalizeResourceListParams = (return {category: input.category,+ filesOnly: input.filesOnly || undefined,includeContentPreview: input.includeContentPreview || undefined,libraryId: input.libraryId,pageSize: input.limit ?? DEFAULT_RESOURCE_PAGE_SIZE,@@ -92,6 +95,7 @@ export const resourceListResource = definePagedReplica<},query: ({category,+ filesOnly,includeContentPreview,libraryId,pageSize,@@ -104,6 +108,7 @@ export const resourceListResource = definePagedReplica<visibility,}) => ({category,+ filesOnly,includeContentPreview,libraryId,pageSize,diff --git a/src/store/file/slices/resource/utils.test.ts b/src/store/file/slices/resource/utils.test.tsindex 4549d3f431b..b6b2624a731 100644--- a/src/store/file/slices/resource/utils.test.ts+++ b/src/store/file/slices/resource/utils.test.ts@@ -1,6 +1,12 @@import { describe, expect, it } from 'vitest';-import { getResourceQueryKey, isOptimisticRowInRequestedPool } from './utils';+import type { ResourceItem } from '@/types/resource';++import {+ getResourceQueryKey,+ isOptimisticRowInRequestedPool,+ listsMovedRowUnfiltered,+} from './utils';describe('getResourceQueryKey', () => {it('returns one stable default key when no query is given', () => {@@ -45,3 +51,22 @@ describe('isOptimisticRowInRequestedPool', () => {expect(isOptimisticRowInRequestedPool(undefined, { parentId: 'folder-a' })).toBe(false);});});++describe('listsMovedRowUnfiltered', () => {+ it('keeps a folder in the drive listing but keeps a page out of it', () => {+ const drive = { filesOnly: true, parentId: null } as const;++ expect(+ listsMovedRowUnfiltered(drive, {+ fileType: 'custom/folder',+ sourceType: 'document',+ } as unknown as ResourceItem),+ ).toBe(true);+ expect(+ listsMovedRowUnfiltered(drive, {+ fileType: 'custom/document',+ sourceType: 'document',+ } as unknown as ResourceItem),+ ).toBe(false);+ });+});diff --git a/src/store/file/slices/resource/utils.ts b/src/store/file/slices/resource/utils.tsindex 63b19d3fb64..50360a92c68 100644--- a/src/store/file/slices/resource/utils.ts+++ b/src/store/file/slices/resource/utils.ts@@ -1,3 +1,5 @@+import { CUSTOM_FOLDER_FILE_TYPE } from '@lobechat/const';+import { type ResourceItem, type ResourceQueryParams } from '@/types/resource';import { type ResourceListParams, type ResourceListValue } from './projection';@@ -121,6 +123,16 @@ export const listsMovedRowUnfiltered = (if (!params.libraryId && !params.showFilesInKnowledgeBase && resource.knowledgeBaseId) {return false;}+ // The drive lists uploaded files and the folders that hold them; a page row is+ // never part of it.+ if (+ params.filesOnly &&+ resource.sourceType === 'document' &&+ resource.fileType !== CUSTOM_FOLDER_FILE_TYPE+ ) {+ return false;+ }+return true;};diff --git a/src/store/home/slices/recent/action.test.ts b/src/store/home/slices/recent/action.test.tsindex af608761085..480ea032646 100644--- a/src/store/home/slices/recent/action.test.ts+++ b/src/store/home/slices/recent/action.test.ts@@ -20,11 +20,7 @@ import { recentService } from '@/services/recent';import { taskService } from '@/services/task';import { useHomeStore } from '@/store/home';import { createRecentQueryKey, initialRecentState } from '@/store/home/slices/recent/initialState';-import {- recentFileListResource,- recentListResource,- recentPageListResource,-} from '@/store/home/slices/recent/projection';+import { docsHomeListResource, recentListResource } from '@/store/home/slices/recent/projection';import { homeRecentSelectors } from '@/store/home/slices/recent/selectors';const item = (id: string, title: string, type: RecentItem['type'] = 'task'): RecentItem => ({@@ -97,8 +93,7 @@ const load = async (sidebar: RecentItem[], drawer?: RecentItem[]) => {beforeEach(() => {useScope(`recent-user-${randomUUID()}:personal`);act(() => useHomeStore.setState({ ...initialRecentState }));- vi.spyOn(fileService, 'getRecentFiles').mockImplementation(() => new Promise(() => {}));- vi.spyOn(fileService, 'getRecentPages').mockImplementation(() => new Promise(() => {}));+ vi.spyOn(fileService, 'getDocsHomeItems').mockImplementation(() => new Promise(() => {}));});afterEach(() => {@@ -224,148 +219,131 @@ describe('recents replica', () => {});});-type RecentFileRow = Awaited<ReturnType<typeof fileService.getRecentFiles>>[number];-type RecentPageRow = Awaited<ReturnType<typeof fileService.getRecentPages>>[number];+type DocsHomeItem = Awaited<ReturnType<typeof fileService.getDocsHomeItems>>[number];-const fileRow = (id: string, url: string): RecentFileRow =>+const homeItem = (id: string, sourceType: 'document' | 'file' = 'document'): DocsHomeItem =>({- chunkCount: 3,createdAt: new Date(0),- fileType: 'image/png',+ fileType: sourceType === 'document' ? 'custom/document' : 'image/png',id,- name: `${id}.png`,- url,- }) as unknown as RecentFileRow;--const pageRow = (id: string): RecentPageRow =>- ({- content: 'the whole page body',- editorData: { root: {} },- id,- metadata: { emoji: '📄' },+ knowledgeBaseIds: ['kb-1'],+ metadata: { emoji: '📄', heavy: 'x'.repeat(10) },name: id,+ sourceType,updatedAt: new Date(0),- }) as unknown as RecentPageRow;+ uploader: { avatar: null, fullName: 'Ada', id: 'user-1', username: 'ada' },+ userId: 'user-1',+ }) as unknown as DocsHomeItem;const storedRow = <T>(resource: { storage?: { get: (key: { queryKey: string; scope: string }) => Promise<T> } },queryKey: string,) => resource.storage!.get({ queryKey, scope });-describe('resource home recents replica', () => {- it('paints the persisted file and page cards before the network answers', async () => {- await recentFileListResource.storage!.set(- { queryKey: 'private', scope },+describe('docs home list replica', () => {+ it('paints the persisted rows before the network answers', async () => {+ await docsHomeListResource.storage!.set(+ { queryKey: 'recent', scope },{- data: [{ createdAt: new Date(0), fileType: 'image/png', id: 'f1', name: 'Cached file' }],+ data: [+ {+ createdAt: new Date(0),+ fileType: 'custom/document',+ id: 'p1',+ knowledgeBaseIds: [],+ kind: 'page',+ name: 'Cached page',+ updatedAt: new Date(0),+ },+ ],updatedAt: 1,},);- await recentPageListResource.storage!.set(- { queryKey: 'private', scope },- { data: [{ id: 'p1', name: 'Cached page', updatedAt: new Date(0) }], updatedAt: 1 },- );- const { result } = renderHook(- () => ({- files: useHomeStore((s) => s.useFetchResourceRecentFiles)({ visibility: 'private' }),- pages: useHomeStore((s) => s.useFetchResourceRecentPages)({ visibility: 'private' }),- }),- { wrapper },- );+ const { result } = renderHook(() => useHomeStore((s) => s.useFetchDocsHome)('recent'), {+ wrapper,+ });- await waitFor(() => {- const state = useHomeStore.getState();- expect(homeRecentSelectors.resourceFiles({ visibility: 'private' })(state)?.[0].name).toBe(- 'Cached file',- );- expect(homeRecentSelectors.resourcePages({ visibility: 'private' })(state)?.[0].name).toBe(+ await waitFor(() =>+ expect(homeRecentSelectors.docsHome('recent')(useHomeStore.getState())?.[0].name).toBe('Cached page',- );- });- expect(result.current.files.isValidating).toBe(true);- expect(result.current.pages.isValidating).toBe(true);+ ),+ );+ expect(result.current.isValidating).toBe(true);});- it('keeps each visibility in its own entry', async () => {- vi.mocked(fileService.getRecentPages).mockImplementation(async (_limit, visibility) => [- pageRow(`page-${visibility}`),+ it('keeps each tab in its own entry', async () => {+ vi.mocked(fileService.getDocsHomeItems).mockImplementation(async (tab) => [+ homeItem(`row-${tab}`),]);renderHook(() => {- useHomeStore((s) => s.useFetchResourceRecentPages)({ visibility: 'private' });- useHomeStore((s) => s.useFetchResourceRecentPages)({ visibility: 'public' });+ useHomeStore((s) => s.useFetchDocsHome)('mine');+ useHomeStore((s) => s.useFetchDocsHome)('shared');},{ wrapper },);await waitFor(() => {const state = useHomeStore.getState();- expect(homeRecentSelectors.resourcePages({ visibility: 'private' })(state)?.[0].id).toBe(- 'page-private',- );- expect(homeRecentSelectors.resourcePages({ visibility: 'public' })(state)?.[0].id).toBe(- 'page-public',- );+ expect(homeRecentSelectors.docsHome('mine')(state)?.[0].id).toBe('row-mine');+ expect(homeRecentSelectors.docsHome('shared')(state)?.[0].id).toBe('row-shared');});});- it('persists slim page cards, never the page body', async () => {- vi.mocked(fileService.getRecentPages).mockResolvedValue([pageRow('p1')]);-- renderHook(() => useHomeStore((s) => s.useFetchResourceRecentPages)({}), { wrapper });-- await waitFor(async () =>- expect((await storedRow(recentPageListResource, 'all'))?.data).toEqual([- { emoji: '📄', id: 'p1', name: 'p1', updatedAt: new Date(0) },- ]),- );- });-- it('drops credential-bearing file URLs from the persisted copy only', async () => {- vi.mocked(fileService.getRecentFiles).mockResolvedValue([- fileRow('signed', 'https://s3.example.com/a.png?X-Amz-Signature=secret'),- fileRow('proxy', 'https://app.example.com/f/proxy'),+ it('persists slim rows with kind, location and owner', async () => {+ vi.mocked(fileService.getDocsHomeItems).mockResolvedValue([+ homeItem('p1'),+ homeItem('f1', 'file'),]);- renderHook(() => useHomeStore((s) => s.useFetchResourceRecentFiles)({}), { wrapper });+ renderHook(() => useHomeStore((s) => s.useFetchDocsHome)('recent'), { wrapper });await waitFor(async () =>- expect((await storedRow(recentFileListResource, 'all'))?.data).toBeDefined(),+ expect((await storedRow(docsHomeListResource, 'recent'))?.data).toEqual([+ {+ createdAt: new Date(0),+ emoji: '📄',+ fileType: 'custom/document',+ id: 'p1',+ knowledgeBaseIds: ['kb-1'],+ kind: 'page',+ name: 'p1',+ owner: { avatar: null, id: 'user-1', name: 'Ada' },+ updatedAt: new Date(0),+ userId: 'user-1',+ },+ expect.objectContaining({ id: 'f1', kind: 'file' }),+ ]),);- const persisted = (await storedRow(recentFileListResource, 'all'))!.data;- expect(persisted.map((card) => card.url)).toEqual([- undefined,- 'https://app.example.com/f/proxy',- ]);- expect(persisted[0]).not.toHaveProperty('chunkCount');- expect(JSON.stringify(localStorage)).not.toContain('X-Amz-Signature');- // The session still shows the thumbnail it was handed.- expect(- homeRecentSelectors- .resourceFiles({})(useHomeStore.getState())- ?.map((card) => card.url),- ).toEqual([- 'https://s3.example.com/a.png?X-Amz-Signature=secret',- 'https://app.example.com/f/proxy',- ]);+ expect(JSON.stringify(localStorage)).not.toContain('heavy');});- it("never paints another workspace's cards", async () => {- await recentFileListResource.storage!.set(- { queryKey: 'all', scope: `${scope}-other-workspace` },+ it("never paints another workspace's rows", async () => {+ await docsHomeListResource.storage!.set(+ { queryKey: 'recent', scope: `${scope}-other-workspace` },{- data: [{ createdAt: new Date(0), fileType: 'image/png', id: 'x', name: 'Theirs' }],+ data: [+ {+ createdAt: new Date(0),+ fileType: 'image/png',+ id: 'x',+ knowledgeBaseIds: [],+ kind: 'file',+ name: 'Theirs',+ updatedAt: new Date(0),+ },+ ],updatedAt: 1,},);- const { result } = renderHook(() => useHomeStore((s) => s.useFetchResourceRecentFiles)({}), {+ const { result } = renderHook(() => useHomeStore((s) => s.useFetchDocsHome)('recent'), {wrapper,});await waitFor(() => expect(result.current.isHydrated).toBe(true));- expect(homeRecentSelectors.resourceFiles({})(useHomeStore.getState())).toBeUndefined();+ expect(homeRecentSelectors.docsHome('recent')(useHomeStore.getState())).toBeUndefined();});});diff --git a/src/store/home/slices/recent/action.ts b/src/store/home/slices/recent/action.tsindex 38611fa37a7..7c45fdec4b5 100644--- a/src/store/home/slices/recent/action.ts+++ b/src/store/home/slices/recent/action.ts@@ -18,25 +18,18 @@ import { setNamespace } from '@/utils/storeDebug';import { type RecentEntityRef, toRecentEntityRef } from './initialState';import {- type RecentFileCard,- recentFileListResource,+ DOCS_HOME_LIMIT,+ docsHomeListResource,+ type DocsHomeRow,+ type DocsHomeTab,recentListResource,- type RecentPageCard,- recentPageListResource,- type ResourceRecentParams,- toPersistedRecentFiles,- toRecentFileCard,- toRecentPageCard,+ toDocsHomeRow,} from './projection';const n = setNamespace('recent');/** Rows in the "all recents" drawer. */export const ALL_RECENTS_LIMIT = 50;-/** Cards in the resource home "Recent files" grid. */-export const RESOURCE_RECENT_FILES_LIMIT = 8;-/** Cards in the resource home "Recent pages" grid. */-export const RESOURCE_RECENT_PAGES_LIMIT = 6;interface RenameRecentParams {id: string;@@ -78,8 +71,7 @@ export class RecentActionImpl {readonly #renameQueues = new Map<RecentEntityRef, Promise<unknown>>();readonly #recentList;readonly #recents;- readonly #resourceRecentFiles;- readonly #resourceRecentPages;+ readonly #docsHome;constructor(set: Setter, get: () => HomeStore, _api?: unknown) {void _api;@@ -94,28 +86,14 @@ export class RecentActionImpl {view: recordLens<HomeStore, RecentItem[]>('recentListMap'),});this.#recents = linkReplicaEntity<RecentItem>([this.#recentList]);- this.#resourceRecentFiles = createReplicaSlice(recentFileListResource, {- actionPrefix: n('resourceRecentFiles'),- fetcher: async ({ visibility }) =>- (await fileService.getRecentFiles(RESOURCE_RECENT_FILES_LIMIT, visibility)).map(- toRecentFileCard,- ),+ this.#docsHome = createReplicaSlice(docsHomeListResource, {+ actionPrefix: n('docsHome'),+ fetcher: async ({ tab }) =>+ (await fileService.getDocsHomeItems(tab, DOCS_HOME_LIMIT)).map(toDocsHomeRow),get,set,- stateKey: 'resourceRecentFilesReplica',- toPersisted: toPersistedRecentFiles,- view: recordLens<HomeStore, RecentFileCard[]>('resourceRecentFilesMap'),- });- this.#resourceRecentPages = createReplicaSlice(recentPageListResource, {- actionPrefix: n('resourceRecentPages'),- fetcher: async ({ visibility }) =>- (await fileService.getRecentPages(RESOURCE_RECENT_PAGES_LIMIT, visibility)).map(- toRecentPageCard,- ),- get,- set,- stateKey: 'resourceRecentPagesReplica',- view: recordLens<HomeStore, RecentPageCard[]>('resourceRecentPagesMap'),+ stateKey: 'docsHomeReplica',+ view: recordLens<HomeStore, DocsHomeRow[]>('docsHomeMap'),});}@@ -174,13 +152,14 @@ export class RecentActionImpl {useFetchAllRecents = (open: boolean): ReplicaSyncResult =>this.#recentList.useSync({ limit: ALL_RECENTS_LIMIT }, { enabled: open });- /** Resource home "Recent files". Read them with `homeRecentSelectors.resourceFiles`. */- useFetchResourceRecentFiles = (params: ResourceRecentParams): ReplicaSyncResult =>- this.#resourceRecentFiles.useSync(params);+ /** Refetch every loaded Docs home tab, e.g. after a page or file was added. */+ refreshDocsHome = async (): Promise<void> => {+ await this.#docsHome.revalidate();+ };- /** Resource home "Recent pages". Read them with `homeRecentSelectors.resourcePages`. */- useFetchResourceRecentPages = (params: ResourceRecentParams): ReplicaSyncResult =>- this.#resourceRecentPages.useSync(params);+ /** The Docs home list for one tab. Read it with `homeRecentSelectors.docsHome`. */+ useFetchDocsHome = (tab: DocsHomeTab, enabled: boolean = true): ReplicaSyncResult =>+ this.#docsHome.useSync({ tab }, { enabled });/*** Sidebar recents. Asks for `limit + 1` rows to know whether "view all" isdiff --git a/src/store/home/slices/recent/initialState.ts b/src/store/home/slices/recent/initialState.tsindex 4363a22fe3f..805512ed96f 100644--- a/src/store/home/slices/recent/initialState.ts+++ b/src/store/home/slices/recent/initialState.ts@@ -2,7 +2,7 @@ import type { RecentItem } from '@lobechat/types';import { createReplicaState, type ReplicaState } from '@/libs/replica';-import type { RecentFileCard, RecentPageCard } from './projection';+import type { DocsHomeRow } from './projection';export { createRecentQueryKey } from './projection';@@ -14,24 +14,19 @@ export const toRecentEntityRef = (item: Pick<RecentItem, 'id' | 'type'>): Recentexport interface RecentState {allRecentsDrawerOpen: boolean;+ /** Docs home list per tab, the view of the `docsHomeList` replica. */+ docsHomeMap: Record<string, DocsHomeRow[]>;+ docsHomeReplica: ReplicaState<DocsHomeRow[]>;/** Recents per query (`limit:N`), the view of the `recentList` replica. */recentListMap: Record<string, RecentItem[]>;/** Replica bookkeeping for `recentListMap`. */recentListReplica: ReplicaState<RecentItem[]>;- /** Resource home "Recent files" per visibility, the view of the `resourceRecentFiles` replica. */- resourceRecentFilesMap: Record<string, RecentFileCard[]>;- resourceRecentFilesReplica: ReplicaState<RecentFileCard[]>;- /** Resource home "Recent pages" per visibility, the view of the `resourceRecentPages` replica. */- resourceRecentPagesMap: Record<string, RecentPageCard[]>;- resourceRecentPagesReplica: ReplicaState<RecentPageCard[]>;}export const initialRecentState: RecentState = {allRecentsDrawerOpen: false,+ docsHomeMap: {},+ docsHomeReplica: createReplicaState(),recentListMap: {},recentListReplica: createReplicaState(),- resourceRecentFilesMap: {},- resourceRecentFilesReplica: createReplicaState(),- resourceRecentPagesMap: {},- resourceRecentPagesReplica: createReplicaState(),};diff --git a/src/store/home/slices/recent/projection.ts b/src/store/home/slices/recent/projection.tsindex b2f39652979..bf70abc8bf9 100644--- a/src/store/home/slices/recent/projection.ts+++ b/src/store/home/slices/recent/projection.ts@@ -1,6 +1,7 @@import type { RecentItem } from '@lobechat/types';import { defineReplica } from '@/libs/replica';+import type { fileService } from '@/services/file';export interface RecentListParams {limit: number;@@ -21,86 +22,63 @@ export const recentListResource = defineReplica<RecentListParams, RecentItem[]>(version: 1,});-export interface ResourceRecentParams {- /** Workspace visibility filter; personal mode sends none. */- visibility?: 'private' | 'public';+export type DocsHomeTab = 'mine' | 'recent' | 'shared';++export interface DocsHomeParams {+ tab: DocsHomeTab;}-/** One resource-home recents query per visibility; the cache scope already carries the workspace. */-export const resourceRecentKey = ({ visibility }: ResourceRecentParams): string =>- visibility ?? 'all';+/** Rows the Docs home list shows; it fetches one head page per tab. */+export const DOCS_HOME_LIMIT = 50;-/** What a resource-home "Recent files" card renders. */-export interface RecentFileCard {+/** One row of the Docs home list: a page or an uploaded file. */+export interface DocsHomeRow {createdAt: Date | string;- fileType?: string;- id: string;- name: string;- url?: string;-}--/** What a resource-home "Recent pages" card renders. */-export interface RecentPageCard {emoji?: string;+ fileType: string;id: string;+ kind: 'file' | 'page';+ /** Knowledge bases the row is filed into; empty for standalone rows. */+ knowledgeBaseIds: string[];name: string;+ owner?: { avatar?: string | null; id: string; name: string } | null;updatedAt: Date | string;+ userId?: string | null;}-export const toRecentFileCard = ({- createdAt,- fileType,- id,- name,- url,-}: RecentFileCard): RecentFileCard => ({ createdAt, fileType, id, name, url });+type DocsHomeItem = Awaited<ReturnType<typeof fileService.getDocsHomeItems>>[number];-export const toRecentPageCard = ({- id,- metadata,- name,- updatedAt,-}: {- id: string;- metadata?: Record<string, any> | null;- name: string;- updatedAt: Date | string;-}): RecentPageCard => {- const emoji = (metadata as { emoji?: unknown } | null | undefined)?.emoji;- return { emoji: typeof emoji === 'string' ? emoji : undefined, id, name, updatedAt };+/** Server row → list row. Slim on purpose: the list persists to localStorage. */+export const toDocsHomeRow = (item: DocsHomeItem): DocsHomeRow => {+ const emoji = (item.metadata as { emoji?: unknown } | null | undefined)?.emoji;+ const uploader = item.uploader;+ return {+ createdAt: item.createdAt,+ emoji: typeof emoji === 'string' ? emoji : undefined,+ fileType: item.fileType,+ id: item.id,+ knowledgeBaseIds: item.knowledgeBaseIds ?? [],+ kind: item.sourceType === 'document' ? 'page' : 'file',+ name: item.name,+ owner: uploader+ ? {+ avatar: uploader.avatar,+ id: uploader.id,+ name: uploader.fullName || uploader.username || uploader.id.slice(0, 8),+ }+ : null,+ updatedAt: item.updatedAt,+ userId: item.userId,+ };};/**- * A URL that carries a query string (a presigned storage URL in local dev) is a- * short-lived credential; the stable `/f/:id` proxy URL production returns has none.+ * The Docs home list, one entry per tab. localStorage keeps the first frame+ * instant; the cache scope already carries the workspace.*/-const isCredentialUrl = (url: string): boolean => {- try {- return new URL(url, 'http://localhost').search !== '';- } catch {- return true;- }-};--/** Persist file cards without credential-bearing URLs; the card falls back to its icon. */-export const toPersistedRecentFiles = (cards: RecentFileCard[]): RecentFileCard[] =>- cards.map((card) => (card.url && isCredentialUrl(card.url) ? { ...card, url: undefined } : card));--/**- * Resource home "Recent files". Slim cards only (no chunk / embedding status),- * localStorage so the section paints the last rows on the first frame.- */-export const recentFileListResource = defineReplica<ResourceRecentParams, RecentFileCard[]>({- key: resourceRecentKey,- name: 'resourceRecentFiles',- storage: 'localStorage',- version: 1,-});--/** Resource home "Recent pages": slim cards, never the page body. */-export const recentPageListResource = defineReplica<ResourceRecentParams, RecentPageCard[]>({- key: resourceRecentKey,- name: 'resourceRecentPages',+export const docsHomeListResource = defineReplica<DocsHomeParams, DocsHomeRow[]>({+ key: ({ tab }) => tab,+ name: 'docsHomeList',storage: 'localStorage',version: 1,});diff --git a/src/store/home/slices/recent/selectors.ts b/src/store/home/slices/recent/selectors.tsindex 33efab78943..f887948a566 100644--- a/src/store/home/slices/recent/selectors.ts+++ b/src/store/home/slices/recent/selectors.ts@@ -1,7 +1,7 @@import { type HomeStore } from '@/store/home/store';import { type RecentEntityRef, toRecentEntityRef } from './initialState';-import { resourceRecentKey, type ResourceRecentParams } from './projection';+import type { DocsHomeTab } from './projection';/** Items of one recents query; `undefined` until it is hydrated or fetched. */const query = (queryKey: string) => (s: HomeStore) => s.recentListMap[queryKey];@@ -9,17 +9,11 @@ const query = (queryKey: string) => (s: HomeStore) => s.recentListMap[queryKey];const item = (queryKey: string, ref: RecentEntityRef) => (s: HomeStore) =>s.recentListMap[queryKey]?.find((recent) => toRecentEntityRef(recent) === ref);-/** Resource home recent files; `undefined` until hydrated or fetched. */-const resourceFiles = (params: ResourceRecentParams) => (s: HomeStore) =>- s.resourceRecentFilesMap[resourceRecentKey(params)];--/** Resource home recent pages; `undefined` until hydrated or fetched. */-const resourcePages = (params: ResourceRecentParams) => (s: HomeStore) =>- s.resourceRecentPagesMap[resourceRecentKey(params)];+/** One Docs home tab; `undefined` until hydrated or fetched. */+const docsHome = (tab: DocsHomeTab) => (s: HomeStore) => s.docsHomeMap[tab];export const homeRecentSelectors = {+ docsHome,item,query,- resourceFiles,- resourcePages,};diff --git a/src/store/library/slices/crud/action.test.ts b/src/store/library/slices/crud/action.test.tsindex 6d1c0136ca0..7ec04ecb18b 100644--- a/src/store/library/slices/crud/action.test.ts+++ b/src/store/library/slices/crud/action.test.ts@@ -304,6 +304,30 @@ describe('knowledgeBase crud replicas', () => {expect(useKnowledgeBaseStore.getState().knowledgeBaseLoadingIds).not.toContain('p1');});+ it('sets a cover inside settings optimistically and sends only the cover', async () => {+ await seedList();+ let resolve!: (value: unknown) => void;+ vi.mocked(knowledgeBaseService.updateKnowledgeBaseList).mockImplementation(+ () => new Promise((res) => (resolve = res)) as any,+ );++ const operation = useKnowledgeBaseStore+ .getState()+ .updateKnowledgeBaseCover('p1', 'preset:dusk');++ expect(list('private')?.find((kb) => kb.id === 'p1')?.settings).toMatchObject({+ cover: 'preset:dusk',+ });+ expect(knowledgeBaseService.updateKnowledgeBaseList).toHaveBeenCalledWith('p1', {+ cover: 'preset:dusk',+ });++ await act(async () => {+ resolve(undefined);+ await operation;+ });+ });+it('creates a KB and reconciles the list from the server', async () => {await seedList();vi.mocked(knowledgeBaseService.createKnowledgeBase).mockResolvedValue('kb-new' as any);diff --git a/src/store/library/slices/crud/action.ts b/src/store/library/slices/crud/action.tsindex 8643f28708e..e2107f93730 100644--- a/src/store/library/slices/crud/action.ts+++ b/src/store/library/slices/crud/action.ts@@ -195,6 +195,23 @@ export class KnowledgeBaseCrudActionImpl {this.#get().internal_toggleKnowledgeBaseLoading(id, false);}};++ /**+ * Set (or with `null`, clear back to the generated default) a library's+ * cover. The cover lives in `settings`, which the server merges into.+ */+ updateKnowledgeBaseCover = async (id: string, cover: string | null): Promise<void> => {+ await this.#kbEntity.optimistic(+ id,+ (kb) => {+ const { cover: _previous, ...settings } = (kb.settings ?? {}) as Record<string, unknown>;+ return { ...kb, settings: cover ? { ...settings, cover } : settings };+ },+ () => knowledgeBaseService.updateKnowledgeBaseList(id, { cover }),+ );++ await this.#get().refreshKnowledgeBaseList();+ };}export type KnowledgeBaseCrudAction = Pick<diff --git a/src/store/page/action.firstScreen.test.ts b/src/store/page/action.firstScreen.test.tsnew file mode 100644index 00000000000..b88328d835a--- /dev/null+++ b/src/store/page/action.firstScreen.test.ts@@ -0,0 +1,54 @@+import { readdirSync, readFileSync } from 'node:fs';+import path from 'node:path';++import { describe, expect, it, vi } from 'vitest';++import { pageActions } from './action';+import { usePageStore } from './store';++const refreshDocsHome = vi.fn();++vi.mock('@/store/home', () => ({+ useHomeStore: { getState: () => ({ refreshDocsHome }) },+}));++vi.mock('@/libs/swr', () => ({+ mutate: vi.fn(),+ useClientDataSWR: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),+}));++vi.mock('@/services/document', () => ({+ documentService: { deleteDocument: vi.fn().mockResolvedValue(undefined) },+}));++const STORE_DIR = __dirname;++/** Every non-test module of the page store, recursively. */+const storeSources = (dir: string): string[] =>+ readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) return storeSources(full);+ return /\.tsx?$/.test(entry.name) && !/\.test\.tsx?$/.test(entry.name) ? [full] : [];+ });++describe('page store — first-screen imports', () => {+ // The page store is on the first screen. A static import of the home store+ // drags the chat store and the model bank into the entry chunk (+700 KB+ // gzip on the size gate), so those stores may only be loaded on demand.+ it.each(['@/store/home', '@/store/chat'])('does not statically import %s', (specifier) => {+ const staticImport = new RegExp(`^import(?!\\s+type)[^;]*from '${specifier}['/]`, 'm');+ const offenders = storeSources(STORE_DIR).filter((file) =>+ staticImport.test(readFileSync(file, 'utf8')),+ );++ expect(offenders.map((file) => path.relative(STORE_DIR, file))).toEqual([]);+ });++ it('still refreshes the Docs home after a page is removed', async () => {+ usePageStore.setState({ selectedPageId: null });++ await pageActions.removePage('docs_a');++ await vi.waitFor(() => expect(refreshDocsHome).toHaveBeenCalled());+ });+});diff --git a/src/store/page/action.ts b/src/store/page/action.tsindex cdb32af106e..618a96ec299 100644--- a/src/store/page/action.ts+++ b/src/store/page/action.ts@@ -12,12 +12,31 @@ import { setNamespace } from '@/utils/storeDebug';import { initialState, type PageState } from './initialState';import { currentPageSize, PagePrivateAction } from './privateAction';-import { documentItemToLobeDocument, PAGE_LIST_KEY, TEMP_PAGE_ID_PREFIX } from './projection';+import {+ documentItemToLobeDocument,+ PAGE_LIST_KEY,+ type PageSectionScope,+ TEMP_PAGE_ID_PREFIX,+} from './projection';import { listSelectors } from './slices/list/selectors';import { usePageStore } from './store';const n = setNamespace('page');+/**+ * The Docs home tabs live in the home store, on their own replica — a page+ * mutation refreshes the sidebar sections through the shared entity, but not+ * those tabs. The dashboard stays mounted underneath the editor overlay, so+ * without this a rename or delete leaves the old row on it until an unrelated+ * refetch.+ */+const syncDocsHome = (): void => {+ // Loaded on demand: the page store is on the first screen, and a static+ // import would pull the home store — and through it the chat store and the+ // whole model bank — into the entry chunk.+ void import('@/store/home').then(({ useHomeStore }) => useHomeStore.getState().refreshDocsHome());+};+export interface PageUpdateParams {emoji?: string;title?: string;@@ -49,6 +68,10 @@ export class PageActionImpl {return this.#private.list.useSync({ pageSize });};+ /** The Docs sidebar's My docs / Shared sections; rows via `pageSelectors.pageSection`. */+ useFetchPageSection = (scope: PageSectionScope, limit: number): ReplicaSyncResult =>+ this.#private.section.useSync({ limit, scope });+useFetchPageDetail = (pageId?: string | null): ReplicaSyncResult =>this.#private.detail.useSync(pageId || null);@@ -60,6 +83,7 @@ export class PageActionImpl {refreshDocuments = async (): Promise<void> => {await this.#private.revalidateList();+ syncDocsHome();};publishPageToWorkspace = async (pageId: string): Promise<{ documentIds: string[] }> => {@@ -233,6 +257,7 @@ export class PageActionImpl {});this.#private.insertListRow(documentItemToLobeDocument(newPage));+ syncDocsHome();return newPage;};@@ -251,6 +276,7 @@ export class PageActionImpl {await this.#private.entity.optimistic(pageId, 'remove', () =>documentService.deleteDocument(pageId),);+ syncDocsHome();} catch (error) {console.error('Failed to delete page:', error);if (selectedPageId === pageId) {@@ -272,6 +298,7 @@ export class PageActionImpl {renamePage = async (pageId: string, title: string, emoji?: string): Promise<void> => {try {await this.updatePageOptimistically(pageId, { emoji, title });+ syncDocsHome();} catch (error) {console.error('Failed to rename page:', error);} finally {diff --git a/src/store/page/privateAction.ts b/src/store/page/privateAction.tsindex 35b37e213b1..3029faceb92 100644--- a/src/store/page/privateAction.ts+++ b/src/store/page/privateAction.ts@@ -1,4 +1,10 @@-import { createReplicaSlice, linkReplicaEntity, recordLens, singleEntity } from '@/libs/replica';+import {+ arrayEntity,+ createReplicaSlice,+ linkReplicaEntity,+ recordLens,+ singleEntity,+} from '@/libs/replica';import { getCacheScope } from '@/libs/swr/useCacheScope';import { documentService } from '@/services/document';import { useGlobalStore } from '@/store/global';@@ -13,6 +19,8 @@ import {pageDetailResource,pageListResource,type PageListValue,+ pageSectionResource,+ type PageSectionScope,} from './projection';const DEFAULT_PAGE_SIZE = 20;@@ -27,6 +35,7 @@ export class PagePrivateAction {readonly detail;readonly entity;readonly list;+ readonly section;constructor(set: Setter, get: () => PageState) {this.#get = get;@@ -55,7 +64,16 @@ export class PagePrivateAction {stateKey: 'pageDetailReplica',view: recordLens<PageState, LobeDocument>('pageDetailMap'),});- this.entity = linkReplicaEntity<LobeDocument>([this.list, this.detail]);+ this.section = createReplicaSlice(pageSectionResource, {+ actionPrefix: 'pageSection',+ entity: arrayEntity<LobeDocument>((doc) => doc.id),+ get,+ set,+ stateKey: 'pageSectionReplica',+ view: recordLens<PageState, LobeDocument[]>('pageSectionMap'),+ });+ // A rename or delete in the editor reaches the sidebar sections' rows too.+ this.entity = linkReplicaEntity<LobeDocument>([this.list, this.detail, this.section]);}insertListRow = (doc: LobeDocument): void => {@@ -86,7 +104,13 @@ export class PagePrivateAction {);};- revalidateList = (): Promise<unknown> => this.list.revalidate(PAGE_LIST_KEY);+ revalidateList = (): Promise<unknown> =>+ Promise.all([+ this.list.revalidate(PAGE_LIST_KEY),+ ...(['mine', 'shared'] satisfies PageSectionScope[]).map((scope) =>+ this.section.revalidate(scope),+ ),+ ]);preHydrateList = (): Promise<boolean> => {const scope = getCacheScope();diff --git a/src/store/page/projection.ts b/src/store/page/projection.tsindex 6294bdeeba6..cab597c1205 100644--- a/src/store/page/projection.ts+++ b/src/store/page/projection.ts@@ -135,3 +135,36 @@ export const pageDetailResource = defineReplica<string, LobeDocument, LobeDocumestorage: 'indexedDB',version: 1,});++/**+ * The Docs sidebar's page sections: `mine` lists the caller's own pages outside+ * every library, `shared` the workspace pages other members created and shared+ * (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 interface PageSectionParams {+ /** Rows shown; one more is fetched so the section knows whether to offer "View all". */+ limit: number;+ scope: PageSectionScope;+}++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_DOCUMENT_SOURCE_TYPES,+ standaloneOnly: true,+ });++ return result.items.filter(isAllowedPageDocument).map(documentItemToLobeDocument);+ },+ key: ({ scope }) => scope,+ name: 'pageSection',+ storage: 'localStorage',+ version: 1,+});diff --git a/src/store/page/selectors.ts b/src/store/page/selectors.tsindex 4c377f499a5..d19573f9185 100644--- a/src/store/page/selectors.ts+++ b/src/store/page/selectors.ts@@ -1,5 +1,11 @@+import type { PageState } from './initialState';+import type { PageSectionScope } from './projection';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];+export const pageSelectors = {...listSelectors,+ pageSection,};diff --git a/src/store/page/slices/list/initialState.ts b/src/store/page/slices/list/initialState.tsindex 939f256a8e0..8929ec991a0 100644--- a/src/store/page/slices/list/initialState.ts+++ b/src/store/page/slices/list/initialState.ts@@ -19,6 +19,10 @@ export interface PageListSliceState {pageListMap: Record<string, PageListValue>;/** Local-first bookkeeping for `pageListMap`. */pageListReplica: ReplicaState<PageListValue>;+ /** The Docs sidebar's page sections (`pageSectionMap[mine|shared]`). */+ pageSectionMap: Record<string, LobeDocument[]>;+ /** Local-first bookkeeping for `pageSectionMap`. */+ pageSectionReplica: ReplicaState<LobeDocument[]>;}export const initialPageListState: PageListSliceState = {@@ -26,4 +30,6 @@ export const initialPageListState: PageListSliceState = {pageDetailReplica: createReplicaState(),pageListMap: {},pageListReplica: createReplicaState(),+ pageSectionMap: {},+ pageSectionReplica: createReplicaState(),};diff --git a/src/store/page/slices/list/selectors.test.ts b/src/store/page/slices/list/selectors.test.tsindex f8c0bad5894..65df283c255 100644--- a/src/store/page/slices/list/selectors.test.ts+++ b/src/store/page/slices/list/selectors.test.ts@@ -123,4 +123,30 @@ describe('listSelectors — replica-backed reads', () => {expect(listSelectors.getDocumentById('same-page')(state)?.title).toBe('From list');});++ it('resolves a page that only a Docs sidebar section has loaded', () => {+ // Fresh Docs load: the section rendered the row, the flat list has not.+ const state = createState([], {+ pageSectionMap: {+ mine: [doc('section-only', 'private', { title: 'Section only' })],+ },+ });++ expect(listSelectors.getDocumentById('section-only')(state)?.title).toBe('Section only');+ });++ it('prefers the list and by-id copies over a section row', () => {+ const state = createState([doc('everywhere', 'private', { title: 'From list' })], {+ pageDetailMap: { 'deep-link': doc('deep-link', 'private', { title: 'From detail' }) },+ pageSectionMap: {+ mine: [+ doc('everywhere', 'private', { title: 'From section' }),+ doc('deep-link', 'private', { title: 'From section' }),+ ],+ },+ });++ expect(listSelectors.getDocumentById('everywhere')(state)?.title).toBe('From list');+ expect(listSelectors.getDocumentById('deep-link')(state)?.title).toBe('From detail');+ });});diff --git a/src/store/page/slices/list/selectors.ts b/src/store/page/slices/list/selectors.tsindex ae727d5bc79..5667fc5e408 100644--- a/src/store/page/slices/list/selectors.ts+++ b/src/store/page/slices/list/selectors.ts@@ -63,12 +63,28 @@ 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). Returns the stored object, so a component subscribing to- * this selector keeps a stable reference until the page actually changes.+ * the list fetches), and finally to a Docs sidebar section.+ *+ * 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,+ * duplicate and delete all resolve the row through this selector, so leaving+ * the sections out made those actions a silent no-op on exactly those rows.+ *+ * Returns the stored object, so a component subscribing to this selector keeps+ * a stable reference until the page actually changes.*/const getDocumentById = (docId: string | undefined) => (s: PageState) => {if (!docId) return undefined;- return pageList(s)?.items.find((doc) => doc.id === docId) ?? s.pageDetailMap[docId];++ const listRow = pageList(s)?.items.find((doc) => doc.id === docId);+ if (listRow) return listRow;++ const detailRow = s.pageDetailMap[docId];+ if (detailRow) return detailRow;++ return Object.values(s.pageSectionMap)+ .flat()+ .find((doc) => doc.id === docId);};const hasMoreDocuments = (s: PageState): boolean => Boolean(pageList(s)?.hasMore);diff --git a/src/store/user/slices/preference/selectors/preference.ts b/src/store/user/slices/preference/selectors/preference.tsindex e72cfd225b7..07637aff1ca 100644--- a/src/store/user/slices/preference/selectors/preference.ts+++ b/src/store/user/slices/preference/selectors/preference.ts@@ -16,6 +16,9 @@ const hideSyncAlert = (s: UserStore) => s.preference.hideSyncAlert;const hideSettingsMoveGuide = (s: UserStore) => s.preference.guide?.moveSettingsToAvatar;+/** Whether the "Pages and Resources are now Docs" notice was acknowledged. */+const docsMergedNoticeSeen = (s: UserStore) => !!s.preference.guide?.docsMerged;+const showUploadFileInKnowledgeBaseTip = (s: UserStore) =>s.preference.guide?.uploadFileInKnowledgeBase;@@ -30,6 +33,7 @@ const terminalFontFamily = (s: UserStore): string | undefined =>export const preferenceSelectors = {defaultOpenInApp,+ docsMergedNoticeSeen,fontFamily,hideSettingsMoveGuide,hideSyncAlert,diff --git a/src/types/resource.ts b/src/types/resource.tsindex fa7c66dde36..21886ab2432 100644--- a/src/types/resource.ts+++ b/src/types/resource.ts@@ -41,6 +41,8 @@ export interface ResourceItem {// Identityid: string;knowledgeBaseId?: string;+ /** Knowledge bases the row is filed into; the drive tags rows with them. */+ knowledgeBaseIds?: string[];// Metadatametadata?: Record<string, any>;// Real ID or temp-resource-{timestamp}-{random}@@ -74,6 +76,8 @@ export interface ResourceItem {*/export interface ResourceQueryParams {category?: FilesTabs;+ /** Drive listing: uploaded files and the folders that hold them, no pages. */+ filesOnly?: boolean;includeContentPreview?: boolean;libraryId?: string;limit?: number;