Skip to content

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

πŸ› fix(resource): scope workspace lists and knowledge base permissions (#18406)

Rdmclin2676a732d134b
diff --git a/apps/server/src/routers/lambda/__tests__/knowledgeBase.test.ts b/apps/server/src/routers/lambda/__tests__/knowledgeBase.test.ts
index 51ee8b97b6a..7a328531f0a 100644
--- a/apps/server/src/routers/lambda/__tests__/knowledgeBase.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/knowledgeBase.test.ts
@@ -4,6 +4,7 @@ import { knowledgeBaseRouter } from '@/server/routers/lambda/knowledgeBase';
import { TransferErrorCode } from '@/types/transferError';
const routerMocks = vi.hoisted(() => ({
+ assertCanPerformResourceAction: vi.fn(),
businessFileTransferStorageCheck: vi.fn(),
hasWorkspaceScopedPermission: vi.fn(),
}));
@@ -13,6 +14,7 @@ const mockKnowledgeBaseModelCopyToWorkspace = vi.fn();
const mockKnowledgeBaseModelFindById = vi.fn();
const mockKnowledgeBaseModelTransferTo = vi.fn();
const mockKnowledgeBaseModelHasForeignLinkedRows = vi.fn().mockResolvedValue(false);
+const mockKnowledgeBaseModelUpdate = vi.fn();
vi.mock('@/business/server/lambda-routers/file', () => ({
businessFileTransferStorageCheck: routerMocks.businessFileTransferStorageCheck,
@@ -22,6 +24,10 @@ vi.mock('@/server/services/workspacePermission', () => ({
hasWorkspaceScopedPermission: routerMocks.hasWorkspaceScopedPermission,
}));
+vi.mock('@/server/services/resourcePermission', () => ({
+ assertCanPerformResourceAction: routerMocks.assertCanPerformResourceAction,
+}));
+
const mockPermissionRemoveAll = vi.fn();
const mockPermissionSetAccessLevel = vi.fn();
vi.mock('@/database/models/resourcePermission', () => ({
@@ -38,6 +44,7 @@ vi.mock('@/database/models/knowledgeBase', () => ({
findById: mockKnowledgeBaseModelFindById,
hasForeignLinkedRows: mockKnowledgeBaseModelHasForeignLinkedRows,
transferTo: mockKnowledgeBaseModelTransferTo,
+ update: mockKnowledgeBaseModelUpdate,
})),
}));
@@ -53,12 +60,77 @@ describe('knowledgeBaseRouter', () => {
beforeEach(() => {
vi.clearAllMocks();
+ routerMocks.assertCanPerformResourceAction.mockResolvedValue(undefined);
routerMocks.businessFileTransferStorageCheck.mockResolvedValue(undefined);
routerMocks.hasWorkspaceScopedPermission.mockResolvedValue(true);
mockKnowledgeBaseModelCopyToWorkspace.mockResolvedValue({ id: 'kb-copy' });
mockKnowledgeBaseModelCountFileUsage.mockResolvedValue(4096);
mockKnowledgeBaseModelFindById.mockResolvedValue({ id: 'kb-1', userId: 'test-user' });
mockKnowledgeBaseModelTransferTo.mockResolvedValue({ id: 'kb-1' });
+ mockKnowledgeBaseModelUpdate.mockResolvedValue({ id: 'kb-1' });
+ });
+
+ describe('updateKnowledgeBase', () => {
+ it("uses the resource edit policy for another member's shared library", async () => {
+ mockKnowledgeBaseModelFindById.mockResolvedValue({
+ id: 'kb-1',
+ userId: 'another-member',
+ visibility: 'public',
+ workspaceId: 'workspace-active',
+ });
+
+ await caller.updateKnowledgeBase({ id: 'kb-1', value: { name: 'Updated library' } });
+
+ expect(routerMocks.assertCanPerformResourceAction).toHaveBeenCalledWith(
+ expect.objectContaining({
+ action: 'edit',
+ resourceId: 'kb-1',
+ resourceType: 'knowledgeBase',
+ }),
+ );
+ expect(mockKnowledgeBaseModelUpdate).toHaveBeenCalledWith('kb-1', {
+ name: 'Updated library',
+ });
+ });
+
+ // Regression: the input used to be `insertKnowledgeBasesSchema.partial()`,
+ // so a member with collaborative `edit` access could reassign the row, move
+ // it to another workspace, or take it private through the rename endpoint.
+ it('drops identity and scope fields from the update payload', async () => {
+ mockKnowledgeBaseModelFindById.mockResolvedValue({
+ id: 'kb-1',
+ userId: 'another-member',
+ visibility: 'public',
+ workspaceId: 'workspace-active',
+ });
+
+ await caller.updateKnowledgeBase({
+ id: 'kb-1',
+ value: {
+ description: 'New description',
+ id: 'hijacked-id',
+ name: 'Updated library',
+ userId: 'test-user',
+ visibility: 'private',
+ workspaceId: 'other-workspace',
+ },
+ } as Parameters<typeof caller.updateKnowledgeBase>[0]);
+
+ expect(mockKnowledgeBaseModelUpdate).toHaveBeenCalledWith('kb-1', {
+ description: 'New description',
+ name: 'Updated library',
+ });
+ });
+
+ it('does not update the library when resource edit access is denied', async () => {
+ routerMocks.assertCanPerformResourceAction.mockRejectedValue(new Error('denied'));
+
+ await expect(
+ caller.updateKnowledgeBase({ id: 'kb-1', value: { name: 'Updated library' } }),
+ ).rejects.toThrow('denied');
+
+ expect(mockKnowledgeBaseModelUpdate).not.toHaveBeenCalled();
+ });
});
describe('transferKnowledgeBase', () => {
diff --git a/apps/server/src/routers/lambda/file.ts b/apps/server/src/routers/lambda/file.ts
index a0d3d4bcd42..ce72b0844b6 100644
--- a/apps/server/src/routers/lambda/file.ts
+++ b/apps/server/src/routers/lambda/file.ts
@@ -591,12 +591,19 @@ export const fileRouter = router({
}),
recentFiles: fileProcedure
- .input(z.object({ limit: z.number().max(50).optional() }).optional())
+ .input(
+ z
+ .object({
+ limit: z.number().max(50).optional(),
+ visibility: z.enum(['private', 'public']).optional(),
+ })
+ .optional(),
+ )
.query(async ({ ctx, input }) => {
const limit = input?.limit ?? 12;
// Files only (pages are excluded in SQL, so `limit` can't be eaten by
// page rows that are then filtered out).
- const fileItems = await ctx.knowledgeRepo.queryRecent(limit, 'file');
+ const fileItems = await ctx.knowledgeRepo.queryRecent(limit, 'file', input?.visibility);
if (fileItems.length === 0) return [];
@@ -649,12 +656,19 @@ export const fileRouter = router({
}),
recentPages: fileProcedure
- .input(z.object({ limit: z.number().max(50).optional() }).optional())
+ .input(
+ z
+ .object({
+ limit: z.number().max(50).optional(),
+ visibility: z.enum(['private', 'public']).optional(),
+ })
+ .optional(),
+ )
.query(async ({ ctx, input }) => {
const limit = input?.limit ?? 12;
// Pages only (folders and files are excluded in SQL, so `limit` can't be
// eaten by rows that are then filtered out).
- return ctx.knowledgeRepo.queryRecent(limit, 'page');
+ return ctx.knowledgeRepo.queryRecent(limit, 'page', input?.visibility);
}),
removeFile: fileProcedure
diff --git a/apps/server/src/routers/lambda/knowledgeBase.ts b/apps/server/src/routers/lambda/knowledgeBase.ts
index 7362f0e0651..37a98e958b6 100644
--- a/apps/server/src/routers/lambda/knowledgeBase.ts
+++ b/apps/server/src/routers/lambda/knowledgeBase.ts
@@ -7,10 +7,11 @@ import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceA
import { serverDBEnv } from '@/config/db';
import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';
import { ResourcePermissionModel } from '@/database/models/resourcePermission';
-import { DEFAULT_RESOURCE_ACCESS_LEVELS, insertKnowledgeBasesSchema } from '@/database/schemas';
+import { DEFAULT_RESOURCE_ACCESS_LEVELS } from '@/database/schemas';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { FileService } from '@/server/services/file';
+import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';
import {
getWorkspaceScopedPermissionMatches,
hasWorkspaceScopedPermission,
@@ -28,6 +29,22 @@ import {
getUseLevelKnowledgeBaseIds,
} from './_helpers/knowledgeBaseAccess';
+/**
+ * Presentation metadata only. Deliberately NOT `insertKnowledgeBasesSchema.partial()`:
+ * that carries `id`, `userId`, `workspaceId` and `visibility`, and a shared
+ * knowledge base is now editable by any member holding `edit` access rather than
+ * only by its creator. Without this narrowing such a member could reassign the
+ * row, move it to another workspace, or take it private β€” bypassing the
+ * creator-only transfer and publish/make-private procedures and putting the
+ * library out of its own creator's reach. Mirrors the OpenAPI
+ * `UpdateKnowledgeBaseSchema` surface.
+ */
+const updatableKnowledgeBaseFields = z.object({
+ avatar: z.string().nullish(),
+ description: z.string().nullish(),
+ name: z.string().optional(),
+});
+
const knowledgeBaseProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
const wsId = ctx.workspaceId ?? undefined;
@@ -409,13 +426,29 @@ export const knowledgeBaseRouter = router({
.input(
z.object({
id: z.string(),
- value: insertKnowledgeBasesSchema.partial(),
+ value: updatableKnowledgeBaseFields,
}),
)
.mutation(async ({ input, ctx }) => {
const existing = await ctx.knowledgeBaseModel.findById(input.id);
if (!existing) return;
- assertWorkspaceRowManageable(ctx, existing.userId, 'knowledge base');
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'edit',
+ db: ctx.serverDB,
+ grantedPermissions: (ctx as { workspacePermissionCodes?: string[] })
+ .workspacePermissionCodes,
+ meta: {
+ userId: existing.userId,
+ visibility: existing.visibility ?? null,
+ workspaceId: existing.workspaceId ?? null,
+ },
+ resourceId: input.id,
+ resourceType: 'knowledgeBase',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
return ctx.knowledgeBaseModel.update(input.id, input.value);
}),
diff --git a/apps/server/src/routers/lambda/work.ts b/apps/server/src/routers/lambda/work.ts
index ba88fcf8029..d823958b076 100644
--- a/apps/server/src/routers/lambda/work.ts
+++ b/apps/server/src/routers/lambda/work.ts
@@ -126,6 +126,7 @@ export const workRouter = router({
originAgentId: z.string().nullable().optional(),
provider: z.enum(WORK_SKILL_PROVIDERS).optional(),
type: z.enum(['task', 'document', 'external', 'file']).nullable().optional(),
+ visibility: z.enum(['private', 'public']).optional(),
}),
)
.query(async ({ ctx, input }) => ctx.workModel.listByWorkspace(input)),
diff --git a/apps/server/src/services/resourcePermission/index.test.ts b/apps/server/src/services/resourcePermission/index.test.ts
index eb68fe85a7d..0d086b101ac 100644
--- a/apps/server/src/services/resourcePermission/index.test.ts
+++ b/apps/server/src/services/resourcePermission/index.test.ts
@@ -686,6 +686,40 @@ describe('canPerformResourceAction', () => {
).resolves.toBe(true);
});
+ it('lets a member edit a KB at the default edit level', async () => {
+ permissionMatchesMock.mockImplementation(memberMatches as any);
+ effectiveAccessMock.mockResolvedValue('edit');
+
+ await expect(
+ canPerformResourceAction({
+ action: 'edit',
+ db,
+ meta: kbMeta,
+ resourceId: 'kb-1',
+ resourceType: 'knowledgeBase',
+ userId: 'member',
+ workspaceId: 'ws-1',
+ }),
+ ).resolves.toBe(true);
+ });
+
+ it('blocks a member from editing a use-level KB', async () => {
+ permissionMatchesMock.mockImplementation(memberMatches as any);
+ effectiveAccessMock.mockResolvedValue('use');
+
+ await expect(
+ canPerformResourceAction({
+ action: 'edit',
+ db,
+ meta: kbMeta,
+ resourceId: 'kb-1',
+ resourceType: 'knowledgeBase',
+ userId: 'member',
+ workspaceId: 'ws-1',
+ }),
+ ).resolves.toBe(false);
+ });
+
it('blocks a member from browsing a use-level KB while keeping it usable', async () => {
permissionMatchesMock.mockImplementation(memberMatches as any);
effectiveAccessMock.mockResolvedValue('use');
diff --git a/packages/database/src/models/__tests__/knowledgeBase.test.ts b/packages/database/src/models/__tests__/knowledgeBase.test.ts
index 03b2fb75012..ca08bf1bb7c 100644
--- a/packages/database/src/models/__tests__/knowledgeBase.test.ts
+++ b/packages/database/src/models/__tests__/knowledgeBase.test.ts
@@ -1,4 +1,5 @@
// @vitest-environment node
+import type { KnowledgeBaseItem } from '@lobechat/types';
import { and, eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -134,6 +135,33 @@ describe('KnowledgeBaseModel', () => {
userId,
});
});
+
+ // Regression: a shared knowledge base is editable by any member holding
+ // `edit` access, so the generic update must not be a back door into the
+ // identity and scope columns that transfer / publish own.
+ it('ignores identity and scope columns', async () => {
+ const { id } = await knowledgeBaseModel.create({ name: 'Test Group' });
+
+ await knowledgeBaseModel.update(id, {
+ id: 'hijacked-id',
+ name: 'Renamed',
+ userId: 'user2',
+ visibility: 'private',
+ // Not on `KnowledgeBaseItem`, but a JSON payload can carry it in.
+ workspaceId: 'some-other-workspace',
+ } as Partial<KnowledgeBaseItem>);
+
+ const updated = await serverDB.query.knowledgeBases.findFirst({
+ where: eq(knowledgeBases.id, id),
+ });
+ expect(updated).toMatchObject({
+ id,
+ name: 'Renamed',
+ userId,
+ visibility: 'public',
+ workspaceId: null,
+ });
+ });
});
const fileList = [
diff --git a/packages/database/src/models/knowledgeBase.ts b/packages/database/src/models/knowledgeBase.ts
index c604636a7b4..04f59be682d 100644
--- a/packages/database/src/models/knowledgeBase.ts
+++ b/packages/database/src/models/knowledgeBase.ts
@@ -254,11 +254,30 @@ export class KnowledgeBaseModel {
};
// update
- update = async (id: string, value: Partial<KnowledgeBaseItem>) =>
- this.db
+ update = async (id: string, value: Partial<KnowledgeBaseItem>) => {
+ // Identity and scope columns never travel through the generic update. The
+ // ownership predicate spans every knowledge base visible in the workspace,
+ // and shared libraries are editable by any member holding `edit` access, so
+ // without stripping these a member could reassign another member's library,
+ // move it to a different workspace, or take it private. Ignored rather than
+ // rejected so a client that sends an extra field still gets its real edit
+ // applied. Transfer and publish/make-private have their own guarded paths
+ // and write these columns directly.
+ // `workspaceId` is not on `KnowledgeBaseItem`, but a JSON payload can still
+ // carry it into the spread at runtime, so widen the type to strip it by name.
+ const {
+ id: _id,
+ userId: _userId,
+ visibility: _visibility,
+ workspaceId: _workspaceId,
+ ...safe
+ } = value as Partial<KnowledgeBaseItem> & { workspaceId?: string | null };
+
+ return this.db
.update(knowledgeBases)
- .set({ ...value, updatedAt: new Date() })
+ .set({ ...safe, updatedAt: new Date() })
.where(and(eq(knowledgeBases.id, id), this.ownership()));
+ };
/**
* Publish a private knowledge base into the workspace. Thin wrapper around
diff --git a/packages/database/src/models/work/__tests__/workspace.test.ts b/packages/database/src/models/work/__tests__/workspace.test.ts
index 78f1cd3b7a4..7bd6e036156 100644
--- a/packages/database/src/models/work/__tests__/workspace.test.ts
+++ b/packages/database/src/models/work/__tests__/workspace.test.ts
@@ -230,6 +230,57 @@ describe('WorkModel Β· listByWorkspace', () => {
expect((await memberWorks.listByWorkspace({})).items).toHaveLength(0);
});
+ it('separates private and public Works for the Resources mode switch', async () => {
+ const workspaceId = 'work-test-gallery-visibility-workspace';
+ await serverDB.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Gallery Visibility Test Workspace',
+ primaryOwnerId: userId,
+ slug: workspaceId,
+ });
+
+ const taskModel = new TaskModel(serverDB, userId, workspaceId);
+ const workModel = new WorkModel(serverDB, userId, workspaceId);
+ const privateTask = await taskModel.create({
+ instruction: 'Private gallery task',
+ name: 'Private gallery task',
+ visibility: 'private',
+ });
+ const publicTask = await taskModel.create({
+ instruction: 'Public gallery task',
+ name: 'Public gallery task',
+ visibility: 'public',
+ });
+ const privateWork = await workModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-gallery-private',
+ taskId: privateTask.id,
+ toolCallId: 'tool-call-gallery-private',
+ toolIdentifier: 'lobe-task',
+ toolName: 'createTask',
+ topicId,
+ });
+ const publicWork = await workModel.registerTask({
+ changeType: 'created',
+ rootOperationId: 'op-gallery-public',
+ taskId: publicTask.id,
+ toolCallId: 'tool-call-gallery-public',
+ toolIdentifier: 'lobe-task',
+ toolName: 'createTask',
+ topicId,
+ });
+
+ const combined = await workModel.listByWorkspace({});
+ const privateOnly = await workModel.listByWorkspace({ visibility: 'private' });
+ const publicOnly = await workModel.listByWorkspace({ visibility: 'public' });
+
+ expect(combined.items.map((item) => item.id).sort()).toEqual(
+ [privateWork!.id, publicWork!.id].sort(),
+ );
+ expect(privateOnly.items.map((item) => item.id)).toEqual([privateWork!.id]);
+ expect(publicOnly.items.map((item) => item.id)).toEqual([publicWork!.id]);
+ });
+
it('flags an orphaned task work whose task was deleted without the tool', async () => {
const taskModel = new TaskModel(serverDB, userId);
const workModel = new WorkModel(serverDB, userId);
diff --git a/packages/database/src/models/work/queries.ts b/packages/database/src/models/work/queries.ts
index 4d4c6e411c9..ae8e0fd2183 100644
--- a/packages/database/src/models/work/queries.ts
+++ b/packages/database/src/models/work/queries.ts
@@ -9,6 +9,7 @@ import {
type WorkVersionEventItem,
type WorkVersionEventMap,
type WorkVersionItem,
+ type WorkVisibility,
} from '@lobechat/types';
import type { SQL } from 'drizzle-orm';
import { and, desc, eq, inArray, isNull, lt, or } from 'drizzle-orm';
@@ -265,6 +266,8 @@ export interface ListByWorkspaceParams {
/** Narrow the `external` type to a single skill provider's resource types. */
provider?: WorkSkillProvider | null;
type?: WorkType | null;
+ /** Narrow the Resources gallery to Private or Workspace rows. */
+ visibility?: WorkVisibility;
}
// Not exported: only used as this module's own return-type annotation. The
@@ -319,6 +322,7 @@ export const listByWorkspace = async (
];
if (params.type) filters.push(eq(works.type, params.type));
if (params.originAgentId) filters.push(eq(works.originAgentId, params.originAgentId));
+ if (ctx.workspaceId && params.visibility) filters.push(eq(works.visibility, params.visibility));
// User-visible gallery tabs stay per-provider (Linear / GitHub) but filter by
// provider β€” its resource types β€” over the unified `external` Work type.
if (params.provider) {
diff --git a/packages/database/src/repositories/knowledge/index.test.ts b/packages/database/src/repositories/knowledge/index.test.ts
index b3bae592f60..78c8b7e15a2 100644
--- a/packages/database/src/repositories/knowledge/index.test.ts
+++ b/packages/database/src/repositories/knowledge/index.test.ts
@@ -424,6 +424,50 @@ describe('KnowledgeRepo', () => {
expect(names).toContain('public-doc.pdf');
expect(names).not.toContain('other-private-doc.pdf');
});
+
+ it('should separate recent pages and files by the Resources visibility mode', async () => {
+ await serverDB.insert(files).values([
+ {
+ fileType: 'text/plain',
+ name: 'public-file.txt',
+ size: 100,
+ url: 'public-file-url',
+ userId,
+ visibility: 'public',
+ workspaceId,
+ },
+ {
+ fileType: 'text/plain',
+ name: 'caller-private-file.txt',
+ size: 100,
+ url: 'caller-private-file-url',
+ userId,
+ visibility: 'private',
+ workspaceId,
+ },
+ {
+ fileType: 'text/plain',
+ name: 'other-private-file.txt',
+ size: 100,
+ url: 'other-private-file-url',
+ userId: otherUserId,
+ visibility: 'private',
+ workspaceId,
+ },
+ ]);
+
+ const repo = new KnowledgeRepo(serverDB, userId, workspaceId);
+
+ const privatePages = await repo.queryRecent(10, 'page', 'private');
+ const publicPages = await repo.queryRecent(10, 'page', 'public');
+ const privateFiles = await repo.queryRecent(10, 'file', 'private');
+ const publicFiles = await repo.queryRecent(10, 'file', 'public');
+
+ expect(privatePages.map((item) => item.name)).toEqual(['caller-private-doc.pdf']);
+ expect(publicPages.map((item) => item.name)).toEqual(['public-doc.pdf']);
+ expect(privateFiles.map((item) => item.name)).toEqual(['caller-private-file.txt']);
+ expect(publicFiles.map((item) => item.name)).toEqual(['public-file.txt']);
+ });
});
describe('query - search filtering', () => {
@@ -721,6 +765,14 @@ describe('KnowledgeRepo', () => {
expect(otherUserItem).toBeUndefined();
});
+ it('should ignore Resources visibility narrowing in personal mode', async () => {
+ const privateMode = await knowledgeRepo.queryRecent(10, 'file', 'private');
+ const publicMode = await knowledgeRepo.queryRecent(10, 'file', 'public');
+
+ expect(privateMode.map((item) => item.name)).toEqual(['recent-1.pdf', 'recent-2.pdf']);
+ expect(publicMode.map((item) => item.name)).toEqual(['recent-1.pdf', 'recent-2.pdf']);
+ });
+
it('should still return pages when newer files would fill the limit', async () => {
// The page kind has to be filtered in SQL: filtering a truncated
// recent-everything list dropped every page as soon as the newest rows
diff --git a/packages/database/src/repositories/knowledge/index.ts b/packages/database/src/repositories/knowledge/index.ts
index 5fe856207c6..6172748aaf4 100644
--- a/packages/database/src/repositories/knowledge/index.ts
+++ b/packages/database/src/repositories/knowledge/index.ts
@@ -278,6 +278,21 @@ export class KnowledgeRepo {
private documentScope = () => buildWorkspaceWhere(this.scope(), d);
+ /**
+ * Narrow a workspace-scoped list to one Resources mode. Personal rows are
+ * already owner-scoped and deliberately ignore the mode filter.
+ */
+ private visibilityFilter = (
+ visibility: QueryFileListParams['visibility'],
+ column: AnyPgColumn,
+ ): SQL | undefined => {
+ if (!this.workspaceId || !visibility) return undefined;
+
+ return visibility === 'private'
+ ? eq(column, 'private')
+ : (or(eq(column, 'public'), isNull(column)) as SQL);
+ };
+
/**
* Filters shared by both arms. `visibility` narrows the ownership-scoped pool;
* rows predating the column count as public.
@@ -298,10 +313,7 @@ export class KnowledgeRepo {
? isNull(cols.parentId)
: eq(cols.parentId, parentId),
q ? or(...cols.names.map((name) => ilike(name, `%${q}%`))) : undefined,
- visibility === 'private' ? eq(cols.visibility, 'private') : undefined,
- visibility === 'public'
- ? or(eq(cols.visibility, 'public'), isNull(cols.visibility))
- : undefined,
+ this.visibilityFilter(visibility, cols.visibility),
];
private fileArm = (
@@ -429,9 +441,14 @@ export class KnowledgeRepo {
* `LIMIT` truncate away every row of the wanted kind β€” a burst of uploads
* left the resource home with an empty "recent pages" section.
*/
- async queryRecent(limit: number = 12, kind?: RecentItemKind): Promise<KnowledgeItem[]> {
+ async queryRecent(
+ limit: number = 12,
+ kind?: RecentItemKind,
+ visibility?: QueryFileListParams['visibility'],
+ ): Promise<KnowledgeItem[]> {
const fileArm = this.fileArm([
this.notInAnyKnowledgeBase(),
+ this.visibilityFilter(visibility, f.visibility),
// Derived pages live in the documents table; their backing file row is not
// a file the user uploaded, so it never belongs to the file list.
kind === 'file' ? ne(f.fileType, CUSTOM_DOCUMENT_FILE_TYPE) : undefined,
@@ -439,6 +456,7 @@ export class KnowledgeRepo {
const documentArm = this.documentArm([
isNull(d.knowledgeBaseId),
+ this.visibilityFilter(visibility, d.visibility),
// Folders are containers, not pages.
kind === 'page' ? ne(d.fileType, CUSTOM_FOLDER_FILE_TYPE) : undefined,
]);
diff --git a/src/business/client/hooks/useKnowledgeBaseTransferMenuItem.ts b/src/business/client/hooks/useKnowledgeBaseTransferMenuItem.ts
index 1b3c515369d..a28bb3fe955 100644
--- a/src/business/client/hooks/useKnowledgeBaseTransferMenuItem.ts
+++ b/src/business/client/hooks/useKnowledgeBaseTransferMenuItem.ts
@@ -1,10 +1,3 @@
import { type ItemType } from 'antd/es/menu/interface';
-export interface KnowledgeBaseTransferMenuItemOptions {
- disabled?: boolean;
-}
-
-export const useKnowledgeBaseTransferMenuItem = (
- _id?: string,
- _options?: KnowledgeBaseTransferMenuItemOptions,
-): ItemType[] | null => null;
+export const useKnowledgeBaseTransferMenuItem = (_id?: string): ItemType[] | null => null;
diff --git a/src/features/LibraryModal/CreateNew/CreateForm.tsx b/src/features/LibraryModal/CreateNew/CreateForm.tsx
index c2dc211a998..f7f8885ff45 100644
--- a/src/features/LibraryModal/CreateNew/CreateForm.tsx
+++ b/src/features/LibraryModal/CreateNew/CreateForm.tsx
@@ -36,16 +36,23 @@ const CreateForm = memo<CreateFormProps>(({ id, initialValues, onClose, onSucces
const values = {
description: description.trim(),
name: name.trim(),
- visibility: listVisibility === 'private' ? ('private' as const) : ('public' as const),
};
try {
if (isEditMode) {
+ // Edit only touches the metadata the form shows. `listVisibility`
+ // describes the sidebar mode the user happens to be browsing in, not
+ // this library's visibility β€” sending it would silently take a shared
+ // library private just because its description was edited from the
+ // Private tab. Publish / make-private have their own guarded entries.
await updateKnowledgeBase(id, values);
setLoading(false);
onClose?.();
} else {
- const newId = await createNewKnowledgeBase(values);
+ const newId = await createNewKnowledgeBase({
+ ...values,
+ visibility: listVisibility === 'private' ? ('private' as const) : ('public' as const),
+ });
setLoading(false);
if (onSuccess) {
diff --git a/src/features/ResourceHome/Home/RecentFiles.tsx b/src/features/ResourceHome/Home/RecentFiles.tsx
index 605032dc772..8b8e0ef755e 100644
--- a/src/features/ResourceHome/Home/RecentFiles.tsx
+++ b/src/features/ResourceHome/Home/RecentFiles.tsx
@@ -7,9 +7,14 @@ 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 { useResourceManagerStore } from '@/features/ResourceManager/store';
+import { getResourceQueryVisibility } from '@/features/ResourceManager/store/selectors';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useClientDataSWR } from '@/libs/swr';
+import { resourceKeys } from '@/libs/swr/keys';
import { fileService } from '@/services/file';
import { FilesTabs } from '@/types/files';
@@ -80,17 +85,25 @@ const formatTime = (date: Date | string) =>
const RecentFiles = memo(() => {
const { t } = useTranslation('file');
const navigate = useWorkspaceAwareNavigate();
-
- const { data, isLoading } = useClientDataSWR('resource-home-recent-files', () =>
- fileService.getRecentFiles(8),
+ const workspaceId = useActiveWorkspaceId();
+ const listVisibility = useResourceManagerStore((s) => s.listVisibility);
+ const visibility = workspaceId
+ ? getResourceQueryVisibility(undefined, listVisibility)
+ : undefined;
+
+ const { data, error, isLoading, mutate } = useClientDataSWR(
+ resourceKeys.recentFiles(workspaceId ?? null, visibility),
+ () => fileService.getRecentFiles(8, visibility),
);
- if (!isLoading && !data?.length) return null;
+ if (!isLoading && !error && !data?.length) return null;
return (
<Flexbox gap={12}>
<SectionTitle title={t('home.recentFiles')} viewAllUrl={`/resource/${FilesTabs.All}`} />
- {isLoading ? (
+ {error && !data?.length ? (
+ <AsyncError error={error} variant={'inline'} onRetry={() => void mutate()} />
+ ) : isLoading ? (
<div className={styles.grid}>
{Array.from({ length: 4 }, (_, index) => (
<Skeleton.Node active key={index} style={{ height: 160, width: '100%' }} />
@@ -98,7 +111,7 @@ const RecentFiles = memo(() => {
</div>
) : (
<div className={styles.grid}>
- {data!.map((item) => {
+ {data?.map((item) => {
const isImage = item.fileType?.startsWith('image');
return (
<button
diff --git a/src/features/ResourceHome/Home/RecentPages.tsx b/src/features/ResourceHome/Home/RecentPages.tsx
index ae720817ba8..5dad171231e 100644
--- a/src/features/ResourceHome/Home/RecentPages.tsx
+++ b/src/features/ResourceHome/Home/RecentPages.tsx
@@ -8,8 +8,13 @@ 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 { useResourceManagerStore } from '@/features/ResourceManager/store';
+import { getResourceQueryVisibility } from '@/features/ResourceManager/store/selectors';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useClientDataSWR } from '@/libs/swr';
+import { resourceKeys } from '@/libs/swr/keys';
import { fileService } from '@/services/file';
import SectionTitle from './SectionTitle';
@@ -68,17 +73,25 @@ const formatTime = (date: Date | string) =>
const RecentPages = memo(() => {
const { t } = useTranslation('file');
const navigate = useWorkspaceAwareNavigate();
-
- const { data, isLoading } = useClientDataSWR('resource-home-recent-pages', () =>
- fileService.getRecentPages(6),
+ const workspaceId = useActiveWorkspaceId();
+ const listVisibility = useResourceManagerStore((s) => s.listVisibility);
+ const visibility = workspaceId
+ ? getResourceQueryVisibility(undefined, listVisibility)
+ : undefined;
+
+ const { data, error, isLoading, mutate } = useClientDataSWR(
+ resourceKeys.recentPages(workspaceId ?? null, visibility),
+ () => fileService.getRecentPages(6, visibility),
);
- if (!isLoading && !data?.length) return null;
+ if (!isLoading && !error && !data?.length) return null;
return (
<Flexbox gap={12}>
<SectionTitle title={t('home.recentPages')} viewAllUrl={'/resource/page'} />
- {isLoading ? (
+ {error && !data?.length ? (
+ <AsyncError error={error} variant={'inline'} onRetry={() => void mutate()} />
+ ) : isLoading ? (
<div className={styles.grid}>
{Array.from({ length: 3 }, (_, index) => (
<Skeleton.Node active key={index} style={{ height: 64, width: '100%' }} />
@@ -86,7 +99,7 @@ const RecentPages = memo(() => {
</div>
) : (
<div className={styles.grid}>
- {data!.map((item) => {
+ {data?.map((item) => {
const emoji = (item.metadata as { emoji?: string } | null)?.emoji;
return (
<button
diff --git a/src/features/ResourceHome/Home/RecentWorks.tsx b/src/features/ResourceHome/Home/RecentWorks.tsx
index 2bd257c48cc..a50261dee4b 100644
--- a/src/features/ResourceHome/Home/RecentWorks.tsx
+++ b/src/features/ResourceHome/Home/RecentWorks.tsx
@@ -6,6 +6,7 @@ import { createStaticStyles } from 'antd-style';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncError from '@/components/AsyncError';
import { useWorkspaceWorksInfinite } from '@/features/WorkGallery/hooks';
import { useOpenWork } from '@/features/WorkGallery/useOpenWork';
import WorkPreviewCard from '@/features/WorkGallery/WorkPreviewCard';
@@ -27,15 +28,17 @@ const RecentWorks = memo(() => {
const { t } = useTranslation('file');
const openWork = useOpenWork();
- const { items, isLoadingInitial } = useWorkspaceWorksInfinite('all');
+ const { error, items, isLoadingInitial, reload } = useWorkspaceWorksInfinite('all');
const recent = items.slice(0, MAX_RECENT_WORKS);
- if (!isLoadingInitial && recent.length === 0) return null;
+ if (!isLoadingInitial && !error && recent.length === 0) return null;
return (
<Flexbox gap={12}>
<SectionTitle title={t('work.group')} viewAllUrl={'/resource/works'} />
- {isLoadingInitial ? (
+ {error && recent.length === 0 ? (
+ <AsyncError error={error} variant={'inline'} onRetry={reload} />
+ ) : isLoadingInitial ? (
<div className={styles.grid}>
{Array.from({ length: 3 }, (_, index) => (
<Skeleton.Node active key={index} style={{ height: 220, width: '100%' }} />
diff --git a/src/features/ResourceHome/Layout/Body/LibraryList/Item/useDropdownMenu.test.ts b/src/features/ResourceHome/Layout/Body/LibraryList/Item/useDropdownMenu.test.ts
new file mode 100644
index 00000000000..4769b34330b
--- /dev/null
+++ b/src/features/ResourceHome/Layout/Body/LibraryList/Item/useDropdownMenu.test.ts
@@ -0,0 +1,211 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useDropdownMenu } from './useDropdownMenu';
+
+const mocks = vi.hoisted(() => ({
+ activeWorkspaceId: 'workspace-1' as string | undefined,
+ canEdit: true,
+ canManage: false,
+ currentUserId: 'user-current',
+ openEditor: vi.fn(),
+ transferItems: [
+ { key: 'transfer-knowledge-base', label: 'Move to…' },
+ { key: 'copy-knowledge-base', label: 'Copy to…' },
+ ],
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ Icon: () => null,
+}));
+
+vi.mock('@lobehub/ui/base-ui', () => ({
+ confirmModal: vi.fn(),
+ toast: { error: vi.fn(), success: vi.fn() },
+}));
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ useActiveWorkspaceId: () => mocks.activeWorkspaceId,
+}));
+
+vi.mock('@/business/client/hooks/useKnowledgeBaseTransferMenuItem', () => ({
+ useKnowledgeBaseTransferMenuItem: () => mocks.transferItems,
+}));
+
+vi.mock('@/features/LibraryModal', () => ({
+ useCreateNewModal: () => ({ open: mocks.openEditor }),
+}));
+
+vi.mock('@/features/VisibilityConfirmContent', () => ({
+ default: () => null,
+}));
+
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => vi.fn(),
+}));
+
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: () => ({ allowed: mocks.canEdit }),
+}));
+
+vi.mock('@/hooks/useResourceManageable', () => ({
+ useResourceManageable: () => mocks.canManage,
+}));
+
+vi.mock('@/store/library', () => ({
+ useKnowledgeBaseStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({
+ publishKnowledgeBaseToWorkspace: vi.fn(),
+ removeKnowledgeBase: vi.fn(),
+ setKnowledgeBaseVisibility: vi.fn(),
+ }),
+}));
+
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({ user: { id: mocks.currentUserId } }),
+}));
+
+vi.mock('@/store/user/selectors', () => ({
+ userProfileSelectors: {
+ userId: (state: { user?: { id?: string } }) => state.user?.id,
+ },
+}));
+
+interface MenuItem {
+ disabled?: boolean;
+ key?: string;
+ type?: 'divider';
+}
+
+const getItems = (permissionManageable = false) => {
+ const { result } = renderHook(() =>
+ useDropdownMenu({
+ id: 'kb-1',
+ name: 'Shared library',
+ permissionManageable,
+ toggleEditing: vi.fn(),
+ userId: 'user-creator',
+ visibility: 'public',
+ }),
+ );
+
+ return result.current() as MenuItem[];
+};
+
+const getKeys = (items: MenuItem[]) => items.flatMap((item) => (item.key ? [item.key] : []));
+const getMenuStructure = (items: MenuItem[]) =>
+ items.flatMap((item) => item.key ?? item.type ?? []);
+
+describe('Knowledge base list item dropdown menu', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.activeWorkspaceId = 'workspace-1';
+ mocks.canEdit = true;
+ mocks.canManage = false;
+ mocks.currentUserId = 'user-current';
+ });
+
+ it('lets workspace members rename and edit a shared knowledge base', () => {
+ const items = getItems();
+
+ expect(getKeys(items)).toEqual(['rename', 'editDescription']);
+ expect(items.filter((item) => item.key).every((item) => item.disabled !== true)).toBe(true);
+ });
+
+ it('omits unavailable ownership actions instead of disabling them', () => {
+ const items = getItems(true);
+
+ expect(getKeys(items)).toEqual(['rename', 'editDescription', 'member-permissions']);
+ expect(getMenuStructure(items)).toEqual([
+ 'rename',
+ 'editDescription',
+ 'divider',
+ 'member-permissions',
+ ]);
+ expect(getKeys(items)).not.toEqual(
+ expect.arrayContaining(['transfer-knowledge-base', 'copy-knowledge-base', 'delete']),
+ );
+ });
+
+ it('keeps ownership actions available to the creator or workspace owner', () => {
+ mocks.canManage = true;
+
+ const items = getItems(true);
+
+ expect(getKeys(items)).toEqual([
+ 'rename',
+ 'editDescription',
+ 'member-permissions',
+ 'transfer-knowledge-base',
+ 'copy-knowledge-base',
+ 'delete',
+ ]);
+ expect(getMenuStructure(items)).toEqual([
+ 'rename',
+ 'editDescription',
+ 'divider',
+ 'member-permissions',
+ 'divider',
+ 'transfer-knowledge-base',
+ 'copy-knowledge-base',
+ 'divider',
+ 'delete',
+ ]);
+ expect(items.filter((item) => item.key).every((item) => item.disabled !== true)).toBe(true);
+ });
+
+ it('groups visibility and member permission actions together', () => {
+ mocks.canManage = true;
+ mocks.currentUserId = 'user-creator';
+
+ expect(getMenuStructure(getItems(true))).toEqual([
+ 'rename',
+ 'editDescription',
+ 'divider',
+ 'makePrivate',
+ 'member-permissions',
+ 'divider',
+ 'transfer-knowledge-base',
+ 'copy-knowledge-base',
+ 'divider',
+ 'delete',
+ ]);
+ });
+
+ it('still separates move/copy when there is no member permission entry', () => {
+ mocks.canManage = true;
+
+ expect(getMenuStructure(getItems())).toEqual([
+ 'rename',
+ 'editDescription',
+ 'divider',
+ 'transfer-knowledge-base',
+ 'copy-knowledge-base',
+ 'divider',
+ 'delete',
+ ]);
+ });
+
+ it('never opens or closes the menu with a divider', () => {
+ mocks.canEdit = false;
+ mocks.canManage = true;
+
+ const items = getItems(true);
+
+ expect(getMenuStructure(items)).toEqual(['member-permissions']);
+ });
+
+ it('omits rename and edit when the workspace role cannot edit content', () => {
+ mocks.canEdit = false;
+
+ expect(getKeys(getItems())).toEqual([]);
+ });
+});
diff --git a/src/features/ResourceHome/Layout/Body/LibraryList/Item/useDropdownMenu.tsx b/src/features/ResourceHome/Layout/Body/LibraryList/Item/useDropdownMenu.tsx
index 0c0b9c02a8b..8b108ff91b4 100644
--- a/src/features/ResourceHome/Layout/Body/LibraryList/Item/useDropdownMenu.tsx
+++ b/src/features/ResourceHome/Layout/Body/LibraryList/Item/useDropdownMenu.tsx
@@ -1,5 +1,5 @@
-import { type MenuProps } from '@lobehub/ui';
-import { Icon, Tooltip } from '@lobehub/ui';
+import type { MenuProps } from '@lobehub/ui';
+import { Icon } from '@lobehub/ui';
import { confirmModal, toast } from '@lobehub/ui/base-ui';
import { EyeOffIcon, FileText, GlobeIcon, PencilLine, Trash, UsersIcon } from 'lucide-react';
import { useCallback, useMemo } from 'react';
@@ -47,11 +47,10 @@ export const useDropdownMenu = ({
const { open } = useCreateNewModal();
const { allowed: canEdit } = usePermission('edit_own_content');
// Cross-workspace move/copy follows the same creator-or-owner rule as the
- // other row management actions. Keep the entries visible but disabled so a
- // member understands that the capability exists without being offered an
- // action the server will reject.
+ // other ownership actions. Unavailable row actions are omitted from the
+ // compact menu instead of leaving members with disabled dead ends.
const canManage = useResourceManageable(userId);
- const transferMenuItems = useKnowledgeBaseTransferMenuItem(id, { disabled: !canManage });
+ const transferMenuItems = useKnowledgeBaseTransferMenuItem(id);
const currentUserId = useUserStore(userProfileSelectors.userId);
// Only the creator of a still-private KB sees the "Publish to workspace" entry.
// Mirrors the file / agent / task one-way publish pattern.
@@ -85,10 +84,6 @@ export const useDropdownMenu = ({
[activeWorkspaceId, permissionManageable, id, t, wsNavigate],
);
- // Row-level ownership: only the creator or a workspace owner may edit or
- // delete a shared knowledge base β€” mirrors the server-side enforcement.
- const manageTooltip = canManage ? undefined : t('manageOnlyCreator', { ns: 'common' });
-
const handleDelete = useCallback(() => {
if (!canEdit || !canManage) return;
if (!id) return;
@@ -114,12 +109,12 @@ export const useDropdownMenu = ({
}, [canEdit, canManage, id, removeKnowledgeBase, t]);
const handleEditDescription = useCallback(() => {
- if (!canEdit || !canManage) return;
+ if (!canEdit) return;
open({
id,
initialValues: { description: description || '', name },
});
- }, [canEdit, canManage, description, id, name, open]);
+ }, [canEdit, description, id, name, open]);
const handlePublish = useCallback(() => {
if (!isOwnPrivateKb) return;
@@ -160,103 +155,98 @@ export const useDropdownMenu = ({
});
}, [isOwnPublicKb, id, setKnowledgeBaseVisibility, t]);
- return useCallback(
- () =>
- [
- {
- disabled: !canEdit || !canManage,
- icon: <Icon icon={PencilLine} />,
- key: 'rename',
- label: manageTooltip ? (
- <Tooltip title={manageTooltip}>
- <span>{t('rename', { ns: 'common' })}</span>
- </Tooltip>
- ) : (
- t('rename', { ns: 'common' })
- ),
- onClick: (info: any) => {
- info.domEvent?.stopPropagation();
- if (!canEdit || !canManage) return;
- // Defer to next frame so the DropdownMenu fully finishes its
- // close animation and event handlers before the Popover opens.
- // Otherwise the tail-end mouseup/click bubbles to document and
- // Popover's outside-click detection fires `onOpenChange(false)`
- // one tick after we set it to true, causing the input to flash
- // open and immediately snap shut.
- requestAnimationFrame(() => toggleEditing(true));
- },
- },
- {
- disabled: !canEdit || !canManage,
- icon: <Icon icon={FileText} />,
- key: 'editDescription',
- label: manageTooltip ? (
- <Tooltip title={manageTooltip}>
- <span>{t('edit', { ns: 'common' })}</span>
- </Tooltip>
- ) : (
- t('edit', { ns: 'common' })
- ),
- onClick: (info: any) => {
- info.domEvent?.stopPropagation();
- handleEditDescription();
- },
- },
- canEdit &&
- isOwnPrivateKb && {
- icon: <Icon icon={GlobeIcon} />,
- key: 'publishToWorkspace',
- label: t('library.publish'),
- onClick: (info: any) => {
- info.domEvent?.stopPropagation();
- handlePublish();
+ return useCallback(() => {
+ // Assemble the menu as ordered groups and let the dividers fall out of which
+ // groups survived. Hand-wiring a divider next to each entry silently drops
+ // or duplicates separators as soon as one capability combination changes.
+ const groups: NonNullable<MenuProps['items']>[] = [
+ // Content edits: gated by the workspace role only. Row ownership no longer
+ // gates them β€” the server accepts any member holding an `edit` grant.
+ canEdit
+ ? [
+ {
+ icon: <Icon icon={PencilLine} />,
+ key: 'rename',
+ label: t('rename', { ns: 'common' }),
+ onClick: (info: any) => {
+ info.domEvent?.stopPropagation();
+ if (!canEdit) return;
+ // Defer to next frame so the DropdownMenu fully finishes its
+ // close animation and event handlers before the Popover opens.
+ // Otherwise the tail-end mouseup/click bubbles to document and
+ // Popover's outside-click detection fires `onOpenChange(false)`
+ // one tick after we set it to true, causing the input to flash
+ // open and immediately snap shut.
+ requestAnimationFrame(() => toggleEditing(true));
+ },
},
- },
- canEdit && isOwnPrivateKb && { type: 'divider' },
- canEdit &&
- isOwnPublicKb && {
- icon: <Icon icon={EyeOffIcon} />,
- key: 'makePrivate',
- label: t('makePrivate', { ns: 'common' }),
- onClick: (info: any) => {
- info.domEvent?.stopPropagation();
- handleMakePrivate();
+ {
+ icon: <Icon icon={FileText} />,
+ key: 'editDescription',
+ label: t('edit', { ns: 'common' }),
+ onClick: (info: any) => {
+ info.domEvent?.stopPropagation();
+ handleEditDescription();
+ },
},
- },
- canEdit && isOwnPublicKb && { type: 'divider' },
+ ]
+ : [],
+ // Sharing: visibility switches plus the member-permission page.
+ [
+ canEdit && isOwnPrivateKb
+ ? {
+ icon: <Icon icon={GlobeIcon} />,
+ key: 'publishToWorkspace',
+ label: t('library.publish'),
+ onClick: (info: any) => {
+ info.domEvent?.stopPropagation();
+ handlePublish();
+ },
+ }
+ : null,
+ canEdit && isOwnPublicKb
+ ? {
+ icon: <Icon icon={EyeOffIcon} />,
+ key: 'makePrivate',
+ label: t('makePrivate', { ns: 'common' }),
+ onClick: (info: any) => {
+ info.domEvent?.stopPropagation();
+ handleMakePrivate();
+ },
+ }
+ : null,
memberPermissionMenuItem,
- memberPermissionMenuItem && { type: 'divider' },
- ...(canEdit ? (transferMenuItems ?? []) : []),
- { type: 'divider' },
- {
- danger: true,
- disabled: !canEdit || !canManage,
- icon: <Icon icon={Trash} />,
- key: 'delete',
- label: manageTooltip ? (
- <Tooltip title={manageTooltip}>
- <span>{t('delete', { ns: 'common' })}</span>
- </Tooltip>
- ) : (
- t('delete', { ns: 'common' })
- ),
- onClick: handleDelete,
- },
- ].filter(Boolean) as MenuProps['items'],
- [
- canEdit,
- canManage,
- manageTooltip,
- t,
- toggleEditing,
- handleDelete,
- handleEditDescription,
- handlePublish,
- handleMakePrivate,
- isOwnPrivateKb,
- isOwnPublicKb,
- memberPermissionMenuItem,
- transferMenuItems,
- ],
- );
+ ].filter(Boolean) as NonNullable<MenuProps['items']>,
+ // Cross-workspace move / copy: creator-or-owner only.
+ canEdit && canManage ? (transferMenuItems ?? []) : [],
+ canEdit && canManage
+ ? [
+ {
+ danger: true,
+ icon: <Icon icon={Trash} />,
+ key: 'delete',
+ label: t('delete', { ns: 'common' }),
+ onClick: handleDelete,
+ },
+ ]
+ : [],
+ ];
+
+ return groups
+ .filter((group) => group.length > 0)
+ .flatMap((group, index) => (index === 0 ? group : [{ type: 'divider' as const }, ...group]));
+ }, [
+ canEdit,
+ canManage,
+ t,
+ toggleEditing,
+ handleDelete,
+ handleEditDescription,
+ handlePublish,
+ handleMakePrivate,
+ isOwnPrivateKb,
+ isOwnPublicKb,
+ memberPermissionMenuItem,
+ transferMenuItems,
+ ]);
};
diff --git a/src/features/ResourceManager/components/Explorer/Header/KnowledgeBasePermissionAction.tsx b/src/features/ResourceManager/components/Explorer/Header/KnowledgeBasePermissionAction.tsx
deleted file mode 100644
index 95c4770bc9d..00000000000
--- a/src/features/ResourceManager/components/Explorer/Header/KnowledgeBasePermissionAction.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-'use client';
-
-import { ActionIcon } from '@lobehub/ui';
-import { LockIcon } from 'lucide-react';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { useHasActiveWorkspace } from '@/business/client/hooks/useHasActiveWorkspace';
-import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
-import { useAccessLevelOptions } from '@/features/ResourcePermission/useAccessLevelOptions';
-import { useResourcePermission } from '@/features/ResourcePermission/useResourcePermission';
-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
-
-interface KnowledgeBasePermissionActionProps {
- knowledgeBaseId: string;
-}
-
-const KnowledgeBasePermissionAction = memo<KnowledgeBasePermissionActionProps>(
- ({ knowledgeBaseId }) => {
- const { t } = useTranslation('setting');
- const hasActiveWorkspace = useHasActiveWorkspace();
- const navigate = useWorkspaceAwareNavigate();
- const { data } = useResourcePermission(
- 'knowledgeBase',
- hasActiveWorkspace ? knowledgeBaseId : undefined,
- );
- const accessOptions = useAccessLevelOptions({
- accessLevel: data?.accessLevel,
- isPrivate: data?.visibility === 'private',
- resourceType: 'knowledgeBase',
- });
- const activeOption = accessOptions.find(({ value }) => value === data?.accessLevel);
-
- if (!data?.canManage || !activeOption) return null;
-
- const title = t('permission.generalAccess.trigger', { level: activeOption.label });
-
- return (
- <ActionIcon
- aria-label={title}
- icon={LockIcon}
- size={DESKTOP_HEADER_ICON_SMALL_SIZE}
- title={title}
- onClick={() => navigate(`/resource/library/${knowledgeBaseId}/permission`)}
- />
- );
- },
-);
-
-KnowledgeBasePermissionAction.displayName = 'KnowledgeBasePermissionAction';
-
-export default KnowledgeBasePermissionAction;
diff --git a/src/features/ResourceManager/components/Explorer/Header/index.tsx b/src/features/ResourceManager/components/Explorer/Header/index.tsx
index 17ddd6c6ca7..d200784b39a 100644
--- a/src/features/ResourceManager/components/Explorer/Header/index.tsx
+++ b/src/features/ResourceManager/components/Explorer/Header/index.tsx
@@ -24,7 +24,6 @@ import SortDropdown from '../ToolBar/SortDropdown';
import SourceFilter from '../ToolBar/SourceFilter';
import ViewSwitcher from '../ToolBar/ViewSwitcher';
import Breadcrumb from './Breadcrumb';
-import KnowledgeBasePermissionAction from './KnowledgeBasePermissionAction';
import SearchInput from './SearchInput';
/**
@@ -186,7 +185,6 @@ const Header = memo(() => {
) : (
<Flexbox horizontal align={'center'} gap={4} style={{ marginLeft: 8 }}>
<Breadcrumb category={category} knowledgeBaseId={libraryId} />
- <KnowledgeBasePermissionAction knowledgeBaseId={libraryId} />
</Flexbox>
);
diff --git a/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsx b/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsx
index 259f4bc6e4e..bd0c8da2533 100644
--- a/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsx
+++ b/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsx
@@ -69,18 +69,21 @@ const SearchResultsOverlay = memo(() => {
mutate,
} = useClientDataSWR(
isActive
- ? resourceKeys.search({
- category: libraryId ? undefined : category,
- libraryId,
- q: searchQuery,
- // Search narrows the list the user is looking at, so it has to honour
- // the source they picked. Omitting it left the chip visibly selected
- // while results came back from every non-hidden source β€” and made
- // `Acceptance` search unusable, since that source is hidden unless
- // explicitly asked for.
- sourceFilter,
- visibility,
- })
+ ? resourceKeys.search(
+ {
+ category: libraryId ? undefined : category,
+ libraryId,
+ q: searchQuery,
+ // Search narrows the list the user is looking at, so it has to honour
+ // the source they picked. Omitting it left the chip visibly selected
+ // while results came back from every non-hidden source β€” and made
+ // `Acceptance` search unusable, since that source is hidden unless
+ // explicitly asked for.
+ sourceFilter,
+ visibility,
+ },
+ activeWorkspaceId ?? null,
+ )
: null,
async ([, params]: [
string,
diff --git a/src/features/WorkGallery/hooks.ts b/src/features/WorkGallery/hooks.ts
index 4db44fe9baa..ff1740328d2 100644
--- a/src/features/WorkGallery/hooks.ts
+++ b/src/features/WorkGallery/hooks.ts
@@ -2,6 +2,8 @@ import { useCallback, useEffect } from 'react';
import useSWRInfinite from 'swr/infinite';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { useResourceManagerStore } from '@/features/ResourceManager/store';
+import { getResourceQueryVisibility } from '@/features/ResourceManager/store/selectors';
import { workKeys } from '@/libs/swr/keys';
import type { WorkSummaryPage } from '@/services/work';
import { workService } from '@/services/work';
@@ -18,25 +20,45 @@ const WORK_GALLERY_PAGE_SIZE = 30;
*/
export const useWorkspaceWorksInfinite = (galleryKey: WorkGalleryKey) => {
const workspaceId = useActiveWorkspaceId();
+ const listVisibility = useResourceManagerStore((s) => s.listVisibility);
const filter = workFilterFromKey(galleryKey);
+ // Personal Works have no workspace mode switch, so keep the historical
+ // unfiltered query there. Inside a workspace, mirror every other Resources
+ // surface: Private means caller-owned private rows; Workspace means public
+ // rows shared with the team.
+ const visibility = workspaceId
+ ? getResourceQueryVisibility(undefined, listVisibility)
+ : undefined;
const getKey = useCallback(
(_index: number, previous: WorkSummaryPage | null) => {
// Stop paging once the previous page reported no further cursor.
if (previous && previous.nextCursor === null) return null;
- return workKeys.workspace(workspaceId, galleryKey, previous?.nextCursor ?? undefined);
+ return workKeys.workspace(
+ workspaceId,
+ galleryKey,
+ previous?.nextCursor ?? undefined,
+ visibility,
+ );
},
- [galleryKey, workspaceId],
+ [galleryKey, visibility, workspaceId],
);
const { data, error, isLoading, isValidating, mutate, setSize, size } = useSWRInfinite(
getKey,
- ([, , , cursor]: readonly [string, string | null, string, string | null]) =>
+ ([, , , cursor, keyVisibility]: readonly [
+ string,
+ string | null,
+ string,
+ string | null,
+ 'private' | 'public' | null,
+ ]) =>
workService.listByWorkspace({
cursor: cursor || undefined,
limit: WORK_GALLERY_PAGE_SIZE,
provider: filter.provider,
type: filter.type ?? null,
+ visibility: keyVisibility ?? undefined,
}),
{ revalidateFirstPage: false },
);
@@ -45,7 +67,7 @@ export const useWorkspaceWorksInfinite = (galleryKey: WorkGalleryKey) => {
// don't cascade-fetch as many pages as the previous filter had loaded.
useEffect(() => {
setSize(1);
- }, [galleryKey, setSize]);
+ }, [galleryKey, setSize, visibility]);
const loadMore = useCallback(() => {
void setSize((s) => s + 1);
diff --git a/src/libs/swr/keys.test.ts b/src/libs/swr/keys.test.ts
index 41f7b5308bd..5c2935811c9 100644
--- a/src/libs/swr/keys.test.ts
+++ b/src/libs/swr/keys.test.ts
@@ -1,7 +1,7 @@
import { unstable_serialize } from 'swr';
import { describe, expect, it } from 'vitest';
-import { agentBuilderKeys, recentKeys, taskKeys } from './keys';
+import { agentBuilderKeys, recentKeys, resourceKeys, taskKeys, workKeys } from './keys';
import { CACHE_TIERS } from './localStorageProvider';
describe('recentKeys', () => {
@@ -54,6 +54,52 @@ describe('recentKeys', () => {
});
});
+describe('workKeys', () => {
+ it('keeps the Resources Private and Workspace galleries in separate cache entries', () => {
+ expect(workKeys.workspace('workspace-1', 'all', null, 'private')).not.toEqual(
+ workKeys.workspace('workspace-1', 'all', null, 'public'),
+ );
+ });
+
+ it('keeps non-Resources callers on the unfiltered cache entry', () => {
+ expect(workKeys.workspace('workspace-1', 'project:project-1')).toEqual([
+ 'work:workspace',
+ 'workspace-1',
+ 'project:project-1',
+ null,
+ null,
+ ]);
+ });
+});
+
+describe('resourceKeys', () => {
+ it('keeps Private and Workspace recent sections in separate cache entries', () => {
+ expect(resourceKeys.recentPages('workspace-1', 'private')).not.toEqual(
+ resourceKeys.recentPages('workspace-1', 'public'),
+ );
+ expect(resourceKeys.recentFiles('workspace-1', 'private')).not.toEqual(
+ resourceKeys.recentFiles('workspace-1', 'public'),
+ );
+ });
+
+ // Regression: without the workspace in the key, switching workspaces served
+ // the previous workspace's rows out of cache before revalidation landed.
+ it('keeps every Resources cache entry scoped to its workspace', () => {
+ expect(resourceKeys.recentFiles('workspace-1', 'public')).not.toEqual(
+ resourceKeys.recentFiles('workspace-2', 'public'),
+ );
+ expect(resourceKeys.recentPages('workspace-1', 'public')).not.toEqual(
+ resourceKeys.recentPages('workspace-2', 'public'),
+ );
+ expect(resourceKeys.recentFiles(null, undefined)).not.toEqual(
+ resourceKeys.recentFiles('workspace-1', undefined),
+ );
+ expect(resourceKeys.search({ q: 'report' }, 'workspace-1')).not.toEqual(
+ resourceKeys.search({ q: 'report' }, 'workspace-2'),
+ );
+ });
+});
+
describe('agentBuilderKeys', () => {
// Regression: builder suggestion chips were memory-only (no CACHE_TIERS entry),
// so every page load showed a skeleton and paid a fresh LLM generation. The key
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 9f562e8d8b7..6a35d4ac650 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -357,17 +357,18 @@ export const workKeys = {
versions: def('work:versions', (workId: string) => ['work:versions', workId]),
// Cross-topic Work gallery on the resource page: keyed by owner scope + the
// gallery filter key (type OR provider tab, e.g. `all` / `task` / `linear`) +
- // keyset cursor (one entry per infinite-scroll page). The filter key (not the
- // Work type) is the discriminator so the per-provider linear/github tabs,
- // which share the `external` Work type, get distinct cache entries.
+ // keyset cursor (one entry per infinite-scroll page) + the Resources
+ // Private/Workspace visibility. The filter key (not the Work type) is the
+ // discriminator so the per-provider linear/github tabs, which share the
+ // `external` Work type, get distinct cache entries.
workspace: def(
'work:workspace',
- (workspaceId: string | null | undefined, filterKey: string, cursor?: string | null) => [
- 'work:workspace',
- workspaceId ?? null,
- filterKey,
- cursor ?? null,
- ],
+ (
+ workspaceId: string | null | undefined,
+ filterKey: string,
+ cursor?: string | null,
+ visibility?: 'private' | 'public' | null,
+ ) => ['work:workspace', workspaceId ?? null, filterKey, cursor ?? null, visibility ?? null],
),
};
@@ -1170,7 +1171,30 @@ export const resourceKeys = {
params,
workspaceId,
]),
- search: def('resource:search', (params: unknown) => ['resource:search', params]),
+ // Every Resources cache entry is workspace-scoped: the same visibility means
+ // different rows in each workspace, so leaving `workspaceId` out of the key
+ // makes a workspace switch serve the previous workspace's rows from cache.
+ recentFiles: def(
+ 'resource:recentFiles',
+ (workspaceId: string | null, visibility?: 'private' | 'public') => [
+ 'resource:recentFiles',
+ workspaceId,
+ visibility ?? null,
+ ],
+ ),
+ recentPages: def(
+ 'resource:recentPages',
+ (workspaceId: string | null, visibility?: 'private' | 'public') => [
+ 'resource:recentPages',
+ workspaceId,
+ visibility ?? null,
+ ],
+ ),
+ search: def('resource:search', (params: unknown, workspaceId: string | null) => [
+ 'resource:search',
+ params,
+ workspaceId,
+ ]),
};
export const providerKeys = {
clientConfig: def('provider:clientConfig', (id: string) => ['provider:clientConfig', id]),
diff --git a/src/services/file/index.ts b/src/services/file/index.ts
index 29c606be014..e20431321a4 100644
--- a/src/services/file/index.ts
+++ b/src/services/file/index.ts
@@ -151,12 +151,12 @@ export class FileService {
return lambdaClient.file.updateFile.mutate({ id, ...data });
};
- getRecentFiles = async (limit?: number) => {
- return lambdaClient.file.recentFiles.query({ limit });
+ getRecentFiles = async (limit?: number, visibility?: QueryFileListParams['visibility']) => {
+ return lambdaClient.file.recentFiles.query({ limit, visibility });
};
- getRecentPages = async (limit?: number) => {
- return lambdaClient.file.recentPages.query({ limit });
+ getRecentPages = async (limit?: number, visibility?: QueryFileListParams['visibility']) => {
+ return lambdaClient.file.recentPages.query({ limit, visibility });
};
transferEntity = async (
diff --git a/src/services/work.ts b/src/services/work.ts
index 82ce424fce1..b5bb0f7ff20 100644
--- a/src/services/work.ts
+++ b/src/services/work.ts
@@ -11,6 +11,7 @@ import type {
WorkVersionEventItem,
WorkVersionEventMap,
WorkVersionItem,
+ WorkVisibility,
} from '@lobechat/types';
import { mutate } from '@/libs/swr';
@@ -74,6 +75,7 @@ class WorkService {
originAgentId?: string | null;
provider?: WorkSkillProvider;
type?: WorkType | null;
+ visibility?: WorkVisibility;
}): Promise<WorkSummaryPage> =>
lambdaClient.work.listByWorkspace.query({ ...params, includeFileWorks: true });