🤯 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(knowledge-base): reserve dedicated library types and hide them from lists (#22586)
Arvin Xu9d4998a732dd
diff --git a/packages/database/src/models/__tests__/knowledgeBase.type.test.ts b/packages/database/src/models/__tests__/knowledgeBase.type.test.tsnew file mode 100644index 00000000000..7a848d7a272--- /dev/null+++ b/packages/database/src/models/__tests__/knowledgeBase.type.test.ts@@ -0,0 +1,110 @@+// @vitest-environment node+import type { KnowledgeBaseItem } from '@lobechat/types';+import { eq } from 'drizzle-orm';+import { beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import {+ agents,+ agentsKnowledgeBases,+ knowledgeBases,+ projectKnowledgeBases,+ projects,+ users,+} from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { AgentModel } from '../agent';+import { KnowledgeBaseModel } from '../knowledgeBase';+import { ProjectModel } from '../project';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'kb-type-test-user';+const otherUserId = 'kb-type-test-other-user';+const agentId = 'kb-type-test-agent';+const projectId = 'kb-type-test-project';++const knowledgeBaseModel = new KnowledgeBaseModel(serverDB, userId);++beforeEach(async () => {+ await serverDB.delete(users).where(eq(users.id, userId));+ await serverDB.delete(users).where(eq(users.id, otherUserId));+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);++ await serverDB.insert(knowledgeBases).values([+ { id: 'kb-user', name: 'User library', userId },+ { id: 'kb-custom', name: 'Other typed library', type: 'custom', userId },+ { id: 'kb-agent', name: 'Agent space', type: 'agent', userId },+ { id: 'kb-project', name: 'Project space', type: 'project', userId },+ { id: 'kb-other-user', name: 'Not mine', userId: otherUserId },+ ]);+});++describe('dedicated knowledge bases', () => {+ it('leaves agent and project spaces out of library lists, keeping NULL and other types', async () => {+ const ids = (await knowledgeBaseModel.query()).map(({ id }) => id).sort();++ expect(ids).toEqual(['kb-custom', 'kb-user']);+ });++ it('still applies the visibility filter', async () => {+ await serverDB+ .update(knowledgeBases)+ .set({ visibility: 'private' })+ .where(eq(knowledgeBases.id, 'kb-user'));++ const ids = (await knowledgeBaseModel.query({ visibility: 'private' })).map(({ id }) => id);++ expect(ids).toEqual(['kb-user']);+ });++ it('keeps a dedicated space reachable by id for its owner flows', async () => {+ await expect(knowledgeBaseModel.findById('kb-agent')).resolves.toMatchObject({ type: 'agent' });+ });++ it('never lets the generic update change a library type', async () => {+ await knowledgeBaseModel.update('kb-user', {+ name: 'Renamed',+ type: 'agent',+ } as Partial<KnowledgeBaseItem>);++ await expect(knowledgeBaseModel.findById('kb-user')).resolves.toMatchObject({+ name: 'Renamed',+ type: null,+ });+ });++ it('hides a dedicated mount from agent knowledge but keeps unavailable mounts', async () => {+ await serverDB.insert(agents).values({ id: agentId, userId });+ await serverDB.insert(agentsKnowledgeBases).values([+ { agentId, knowledgeBaseId: 'kb-user', userId },+ { agentId, knowledgeBaseId: 'kb-agent', enabled: false, userId },+ // Another user's library fails the join guard: the mount survives as a placeholder.+ { agentId, knowledgeBaseId: 'kb-other-user', userId },+ ]);++ const { knowledgeBases: mounted } = await new AgentModel(+ serverDB,+ userId,+ ).getAgentAssignedKnowledge(agentId);++ expect(mounted).toHaveLength(2);+ expect(mounted.map(({ id }) => id)).toContain('kb-user');+ expect(mounted.map(({ id }) => id)).not.toContain('kb-agent');+ expect(mounted.some(({ id }) => id === null || id === undefined)).toBe(true);+ });++ it('hides a dedicated mount from project knowledge and retrieval', async () => {+ await serverDB.insert(projects).values({ id: projectId, name: 'Project', userId });+ await serverDB.insert(projectKnowledgeBases).values([+ { knowledgeBaseId: 'kb-user', projectId },+ { knowledgeBaseId: 'kb-project', projectId },+ ]);+ const projectModel = new ProjectModel(serverDB, userId);++ const listed = await projectModel.listKnowledgeBases(projectId);++ expect(listed?.map(({ knowledgeBase }) => knowledgeBase.id)).toEqual(['kb-user']);+ await expect(projectModel.getEnabledKnowledgeBaseIds(projectId)).resolves.toEqual(['kb-user']);+ });+});diff --git a/packages/database/src/models/agent/knowledge.ts b/packages/database/src/models/agent/knowledge.tsindex 8f07f6e52d8..c79398bf848 100644--- a/packages/database/src/models/agent/knowledge.ts+++ b/packages/database/src/models/agent/knowledge.ts@@ -1,6 +1,7 @@-import { and, desc, eq, inArray } from 'drizzle-orm';+import { and, desc, eq, inArray, isNull, or } from 'drizzle-orm';import { agentsFiles, agentsKnowledgeBases, files, knowledgeBases } from '../../schemas';+import { isUserKnowledgeBase } from '../../utils/knowledgeBaseType';import { buildWorkspacePayload, buildWorkspaceWhere } from '../../utils/workspace';import { type AgentModelContext } from './context';@@ -22,7 +23,14 @@ export const getAgentAssignedKnowledge = async (ctx: AgentModelContext, id: strictx.db.select({ enabled: agentsKnowledgeBases.enabled, knowledgeBases }).from(agentsKnowledgeBases)- .where(and(eq(agentsKnowledgeBases.agentId, id), ctx.agentsKnowledgeBasesOwnership()))+ .where(+ and(+ eq(agentsKnowledgeBases.agentId, id),+ ctx.agentsKnowledgeBasesOwnership(),+ // Keep "unavailable" mounts (left join missed); only an owned space is hidden.+ or(isNull(knowledgeBases.id), isUserKnowledgeBase()),+ ),+ ).orderBy(desc(agentsKnowledgeBases.createdAt)).leftJoin(knowledgeBases,diff --git a/packages/database/src/models/knowledgeBase.ts b/packages/database/src/models/knowledgeBase.tsindex 7635f24a94e..459003ea817 100644--- a/packages/database/src/models/knowledgeBase.ts+++ b/packages/database/src/models/knowledgeBase.ts@@ -4,6 +4,7 @@ import { and, count, desc, eq, inArray, ne, or, sum } from 'drizzle-orm';import type { NewDocument, NewFile, NewKnowledgeBase } from '../schemas';import { documents, files, knowledgeBaseFiles, knowledgeBases } from '../schemas';import type { LobeChatDatabase } from '../type';+import { isUserKnowledgeBase } from '../utils/knowledgeBaseType';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';import { FileModel } from './file';@@ -204,9 +205,11 @@ export class KnowledgeBaseModel {visibility?: 'private' | 'public';}) => {const ownershipWhere = this.ownership(options?.callerAgentVisibility);- const conditions = options?.visibility- ? and(ownershipWhere, eq(knowledgeBases.visibility, options.visibility))- : ownershipWhere;+ const conditions = and(+ ownershipWhere,+ isUserKnowledgeBase(),+ options?.visibility ? eq(knowledgeBases.visibility, options.visibility) : undefined,+ );const data = await this.db.select({@@ -267,6 +270,7 @@ export class KnowledgeBaseModel {// carry it into the spread at runtime, so widen the type to strip it by name.const {id: _id,+ type: _type,userId: _userId,visibility: _visibility,workspaceId: _workspaceId,diff --git a/packages/database/src/models/project.ts b/packages/database/src/models/project.tsindex e2444e6f007..db60fdc763b 100644--- a/packages/database/src/models/project.ts+++ b/packages/database/src/models/project.ts@@ -21,6 +21,7 @@ import { tasks } from '../schemas/task';import { topics } from '../schemas/topic';import { works } from '../schemas/work';import type { LobeChatDatabase } from '../type';+import { isUserKnowledgeBase } from '../utils/knowledgeBaseType';import { joinTopicAgentsToProjects } from '../utils/projectTopicAgents';import { topicRunStartedAtColumn } from '../utils/topicRunStartedAt';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';@@ -720,6 +721,7 @@ export class ProjectModel {.where(and(eq(projectKnowledgeBases.projectId, projectId),+ isUserKnowledgeBase(),buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId },knowledgeBases,@@ -915,6 +917,7 @@ export class ProjectModel {and(eq(projectKnowledgeBases.projectId, projectId),eq(projectKnowledgeBases.enabled, true),+ isUserKnowledgeBase(),buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId },knowledgeBases,diff --git a/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.ts b/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.tsindex 925aac6bf9f..c28123bbe2e 100644--- a/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.ts+++ b/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.ts@@ -30,6 +30,7 @@ import type { LobeChatDatabase } from '../../../type';import { notAgentShareDocument } from '../../../utils/documentVisibility';import { libraryVisibleFile, notAgentShareFileReference } from '../../../utils/fileVisibility';import { normalizeInboxAgentMeta, normalizeInboxAgentTitle } from '../../../utils/inboxAgent';+import { isUserKnowledgeBase } from '../../../utils/knowledgeBaseType';import { visibleMemoryState } from '../../../utils/memoryVisibility';import { searchableMessage } from '../../../utils/searchableMessage';import { notShareVisitorMessage, notShareVisitorTopic } from '../../../utils/shareVisitor';@@ -759,6 +760,7 @@ export const hydrateKnowledgeBases = async (hits.map(({ id }) => id),),buildWorkspaceWhere(scope, knowledgeBases),+ isUserKnowledgeBase(),excludeKnowledgeBaseIds.length > 0? notInArray(knowledgeBases.id, excludeKnowledgeBaseIds): undefined,diff --git a/packages/database/src/repositories/ftsSearch/pgLike/candidates.ts b/packages/database/src/repositories/ftsSearch/pgLike/candidates.tsindex ff8f4ac3de5..8d467c8149c 100644--- a/packages/database/src/repositories/ftsSearch/pgLike/candidates.ts+++ b/packages/database/src/repositories/ftsSearch/pgLike/candidates.ts@@ -34,6 +34,7 @@ import {userMemoriesPreferences,userPersonaDocuments,} from '../../../schemas';+import { isUserKnowledgeBase } from '../../../utils/knowledgeBaseType';import { searchableMessage } from '../../../utils/searchableMessage';import { buildWorkspaceWhere } from '../../../utils/workspace';import type { PostgresFtsSearchContext } from '../postgres/context';@@ -357,6 +358,7 @@ const CANDIDATE_TARGETS: Record<FtsSearchBackendEntity, CandidateTarget | undefitable: knowledgeBases,where: (scope, filters) => [buildWorkspaceWhere(scope, knowledgeBases),+ isUserKnowledgeBase(),filters.excludeKnowledgeBaseIds?.length? notInArray(knowledgeBases.id, filters.excludeKnowledgeBaseIds): undefined,diff --git a/packages/database/src/repositories/ftsSearch/postgres/command-menu.ts b/packages/database/src/repositories/ftsSearch/postgres/command-menu.tsindex 4f84c31ec71..6d00b534d44 100644--- a/packages/database/src/repositories/ftsSearch/postgres/command-menu.ts+++ b/packages/database/src/repositories/ftsSearch/postgres/command-menu.ts@@ -16,6 +16,7 @@ import {notAgentShareFileReference,} from '../../../utils/fileVisibility';import { normalizeInboxAgentMeta, normalizeInboxAgentTitle } from '../../../utils/inboxAgent';+import { isUserKnowledgeBase } from '../../../utils/knowledgeBaseType';import { searchableMessageText } from '../../../utils/searchableMessage';import { notShareVisitorMessage, notShareVisitorTopic } from '../../../utils/shareVisitor';import { notChannelTopic, notChannelTopicRef } from '../../../utils/topicVisibility';@@ -557,6 +558,7 @@ export async function searchKnowledgeBases(.where(and(context.scanScopeWhere(knowledgeBases),+ isUserKnowledgeBase(),context.liftsExclusionFilter ? undefined : excludeIdsWhere(knowledgeBases.id),dialect.match(KNOWLEDGE_BASE_FIELDS, preparedQuery),),diff --git a/packages/database/src/schemas/file.ts b/packages/database/src/schemas/file.tsindex bf5c7481bd9..c721c38b453 100644--- a/packages/database/src/schemas/file.ts+++ b/packages/database/src/schemas/file.ts@@ -318,6 +318,14 @@ export type FileUploadItem = typeof fileUploads.$inferSelect;/** Knowledge-base visibility — shared by column def and insert schema. */export const KNOWLEDGE_BASE_VISIBILITY = ['private', 'public'] as const;+/**+ * `knowledge_bases.type` values marking a library dedicated to one owner (an+ * agent's or project's own space). A NULL type is an ordinary user library.+ * Owned libraries are reached through their owner, never through library lists.+ */+export const DEDICATED_KNOWLEDGE_BASE_TYPES = ['agent', 'project'] as const;+export type DedicatedKnowledgeBaseType = (typeof DEDICATED_KNOWLEDGE_BASE_TYPES)[number];+export const knowledgeBases = pgTable('knowledge_bases',{diff --git a/packages/database/src/utils/knowledgeBaseType.ts b/packages/database/src/utils/knowledgeBaseType.tsnew file mode 100644index 00000000000..085780292c3--- /dev/null+++ b/packages/database/src/utils/knowledgeBaseType.ts@@ -0,0 +1,19 @@+import { isNull, notInArray, or } from 'drizzle-orm';++import { DEDICATED_KNOWLEDGE_BASE_TYPES, knowledgeBases } from '../schemas';++/**+ * Keeps user-curated libraries and drops the ones dedicated to an agent or project.+ *+ * Use when:+ * - A query lists libraries for a user to browse, pick from, search or mount.+ *+ * Returns:+ * - A predicate on `knowledge_bases`; NULL `type` must be matched explicitly because+ * `NOT IN` alone would discard every ordinary library.+ */+export const isUserKnowledgeBase = () =>+ or(+ isNull(knowledgeBases.type),+ notInArray(knowledgeBases.type, [...DEDICATED_KNOWLEDGE_BASE_TYPES]),+ );