Skip to content

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

✨ feat(library): add an Agents tab listing each agent's knowledge base (#22599)

Arvin Xu717312666c0b
diff --git a/apps/server/src/routers/lambda/__tests__/knowledgeBase.test.ts b/apps/server/src/routers/lambda/__tests__/knowledgeBase.test.ts
index 2e94714a0f2..d33062fa354 100644
--- a/apps/server/src/routers/lambda/__tests__/knowledgeBase.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/knowledgeBase.test.ts
@@ -15,6 +15,7 @@ const routerMocks = vi.hoisted(() => ({
assertKnowledgeBaseBrowsable: vi.fn(),
assertCanPerformResourceAction: vi.fn(),
businessFileTransferStorageCheck: vi.fn(),
+ filterRestrictedKnowledgeBases: vi.fn(async (_ctx: unknown, items: unknown) => items),
hasWorkspaceScopedPermission: vi.fn(),
}));
@@ -31,6 +32,18 @@ const mockKnowledgeBaseModelUpdate = vi.fn();
const mockDocumentModelFindByIds = vi.fn();
const mockFileModelFindByIds = vi.fn();
+const agentSpaceMocks = vi.hoisted(() => ({ flags: vi.fn(), list: vi.fn() }));
+
+vi.mock('@/server/featureFlags', () => ({
+ getServerFeatureFlagsStateFromRuntimeConfig: agentSpaceMocks.flags,
+}));
+
+vi.mock('@/database/repositories/agentSpace', () => ({
+ AgentSpaceRepository: class {
+ list = agentSpaceMocks.list;
+ },
+}));
+
vi.mock('@/business/server/lambda-routers/file', () => ({
businessFileTransferStorageCheck: routerMocks.businessFileTransferStorageCheck,
}));
@@ -47,7 +60,7 @@ vi.mock('@/server/routers/lambda/_helpers/knowledgeBaseAccess', () => ({
assertContentsNotInRestrictedKnowledgeBase:
routerMocks.assertContentsNotInRestrictedKnowledgeBase,
assertKnowledgeBaseBrowsable: routerMocks.assertKnowledgeBaseBrowsable,
- filterRestrictedKnowledgeBases: vi.fn(async (_ctx, items) => items),
+ filterRestrictedKnowledgeBases: routerMocks.filterRestrictedKnowledgeBases,
getUseLevelKnowledgeBaseIds: vi.fn().mockResolvedValue([]),
}));
@@ -250,6 +263,32 @@ describe('knowledgeBaseRouter', () => {
});
});
+ describe('getAgentSpaces', () => {
+ it('stays empty while the rollout flag is off', async () => {
+ agentSpaceMocks.flags.mockResolvedValue({ enableAgentKnowledgeSpace: false });
+
+ await expect(caller.getAgentSpaces()).resolves.toEqual([]);
+ expect(agentSpaceMocks.list).not.toHaveBeenCalled();
+ });
+
+ it('lists agent spaces once the flag is on', async () => {
+ agentSpaceMocks.flags.mockResolvedValue({ enableAgentKnowledgeSpace: true });
+ agentSpaceMocks.list.mockResolvedValue([{ id: 'kb-agent' }]);
+
+ await expect(caller.getAgentSpaces()).resolves.toEqual([{ id: 'kb-agent' }]);
+ });
+
+ it('drops spaces the caller is restricted from browsing', async () => {
+ agentSpaceMocks.flags.mockResolvedValue({ enableAgentKnowledgeSpace: true });
+ agentSpaceMocks.list.mockResolvedValue([{ id: 'kb-agent' }, { id: 'kb-restricted' }]);
+ routerMocks.filterRestrictedKnowledgeBases.mockImplementationOnce(async (_ctx, items) =>
+ (items as { id: string }[]).filter((item) => item.id !== 'kb-restricted'),
+ );
+
+ await expect(caller.getAgentSpaces()).resolves.toEqual([{ id: 'kb-agent' }]);
+ });
+ });
+
describe('removeKnowledgeBase', () => {
it("lets a member delete another creator's visible library", async () => {
mockKnowledgeBaseModelFindById.mockResolvedValue(publicMemberKnowledgeBase());
diff --git a/apps/server/src/routers/lambda/knowledgeBase.ts b/apps/server/src/routers/lambda/knowledgeBase.ts
index ecf0030ce29..f5e30108633 100644
--- a/apps/server/src/routers/lambda/knowledgeBase.ts
+++ b/apps/server/src/routers/lambda/knowledgeBase.ts
@@ -9,9 +9,11 @@ import { DocumentModel } from '@/database/models/document';
import { FileModel } from '@/database/models/file';
import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';
import { ResourcePermissionModel } from '@/database/models/resourcePermission';
+import { AgentSpaceRepository } from '@/database/repositories/agentSpace';
import { DEDICATED_KNOWLEDGE_BASE_TYPES, DEFAULT_RESOURCE_ACCESS_LEVELS } from '@/database/schemas';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';
import { FileService } from '@/server/services/file';
import {
getWorkspaceScopedPermissionMatches,
@@ -389,6 +391,22 @@ export const knowledgeBaseRouter = router({
return ctx.knowledgeBaseModel.removeFilesFromKnowledgeBase(input.knowledgeBaseId, input.ids);
}),
+ getAgentSpaces: knowledgeBaseProcedure.query(async ({ ctx }) => {
+ const { enableAgentKnowledgeSpace } = await getServerFeatureFlagsStateFromRuntimeConfig(
+ ctx.userId,
+ );
+ if (!enableAgentKnowledgeSpace) return [];
+
+ const spaces = await new AgentSpaceRepository(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ ).list();
+
+ // Same rule as the library list: a card must open for whoever can see it.
+ return filterRestrictedKnowledgeBases(ctx, spaces);
+ }),
+
removeKnowledgeBase: knowledgeBaseProcedure
.use(withScopedPermission('knowledge_base:delete'))
.input(z.object({ id: z.string() }))
diff --git a/apps/server/src/services/toolExecution/constants.ts b/apps/server/src/services/toolExecution/constants.ts
index 635b1e5b8e0..b6b882d5533 100644
--- a/apps/server/src/services/toolExecution/constants.ts
+++ b/apps/server/src/services/toolExecution/constants.ts
@@ -1 +1 @@
-export const TOOL_RESULTS_DIR_NAME = '.tool-results';
+export { AGENT_TOOL_RESULTS_DIR_NAME as TOOL_RESULTS_DIR_NAME } from '@lobechat/const';
diff --git a/locales/en-US/file.json b/locales/en-US/file.json
index 77f8693b2c1..b96277a4382 100644
--- a/locales/en-US/file.json
+++ b/locales/en-US/file.json
@@ -56,9 +56,14 @@
"docs.home.tabs.mine": "Created by me",
"docs.home.tabs.recent": "Recently updated",
"docs.home.tabs.shared": "Shared with me",
+ "docs.library.agentSpaces.emptyDesc": "An Agent's documents appear here once you open that Agent",
+ "docs.library.agentSpaces.emptyTitle": "No Agent knowledge bases yet",
+ "docs.library.agentSpaces.untitled": "Untitled Agent",
"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.tabs.agents": "Agents",
+ "docs.library.tabs.mine": "My knowledge bases",
"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.",
diff --git a/locales/zh-CN/file.json b/locales/zh-CN/file.json
index 009b2f8981f..6b81b93eff7 100644
--- a/locales/zh-CN/file.json
+++ b/locales/zh-CN/file.json
@@ -56,9 +56,14 @@
"docs.home.tabs.mine": "我创建的",
"docs.home.tabs.recent": "最近更新",
"docs.home.tabs.shared": "与我共享",
+ "docs.library.agentSpaces.emptyDesc": "打开助理后,它的文档会显示在这里",
+ "docs.library.agentSpaces.emptyTitle": "还没有助理知识库",
+ "docs.library.agentSpaces.untitled": "未命名助理",
"docs.library.emptyDesc": "把相关的文件和文稿收进知识库,供团队和助理一起使用",
"docs.library.emptyTitle": "还没有知识库",
"docs.library.noDescription": "暂无简介",
+ "docs.library.tabs.agents": "助理",
+ "docs.library.tabs.mine": "我的知识库",
"docs.library.updatedAt": "更新于 {{time}}",
"docs.mergeNotice.confirm": "知道了",
"docs.mergeNotice.drive.desc": "所有上传过的文件按类型归在这里,已放进知识库的文件也能看到。",
diff --git a/packages/const/src/agentDocument.ts b/packages/const/src/agentDocument.ts
index fd26775afcd..bbe38bddb10 100644
--- a/packages/const/src/agentDocument.ts
+++ b/packages/const/src/agentDocument.ts
@@ -34,6 +34,9 @@ export const EDITOR_DOCUMENT_SOURCE_TYPES = [
* page/resource listings exclude these by default so agent working artifacts
* (tool outputs, skill bundles) don't flood the library.
*/
+/** Folder holding an agent's archived tool results; runtime data, never browsable content. */
+export const AGENT_TOOL_RESULTS_DIR_NAME = '.tool-results';
+
export const AGENT_ARTIFACT_SOURCE_TYPES = ['agent', 'agent-signal'] as const;
/**
diff --git a/packages/database/src/repositories/agentSpace/__tests__/index.test.ts b/packages/database/src/repositories/agentSpace/__tests__/index.test.ts
index 5ca1ae09150..54fc8dd421d 100644
--- a/packages/database/src/repositories/agentSpace/__tests__/index.test.ts
+++ b/packages/database/src/repositories/agentSpace/__tests__/index.test.ts
@@ -14,6 +14,7 @@ import {
SKILL_MANAGEMENT_SOURCE,
SKILL_MANAGEMENT_SOURCE_TYPE,
users,
+ workspaces,
} from '../../../schemas';
import type { LobeChatDatabase } from '../../../type';
import { AgentSpaceRepository } from '../index';
@@ -115,6 +116,63 @@ describe('AgentSpaceRepository', () => {
});
});
+ describe('list', () => {
+ it('returns only the spaces of agents the caller can see, with agent identity', async () => {
+ const spaceId = await repository.ensure(agentId);
+ await db.insert(knowledgeBases).values({ id: 'kb-plain', name: 'Plain', userId });
+ await db
+ .insert(agentsKnowledgeBases)
+ .values({ agentId, knowledgeBaseId: 'kb-plain', userId });
+
+ await expect(repository.list()).resolves.toMatchObject([
+ { agentId, id: spaceId, title: 'Writer' },
+ ]);
+ await expect(new AgentSpaceRepository(db, otherUserId).list()).resolves.toEqual([]);
+ });
+ });
+
+ describe('list in a workspace', () => {
+ it('hides a public agent whose space is still private to its creator', async () => {
+ const workspaceId = 'ws-agent-space';
+ await db.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Team',
+ primaryOwnerId: userId,
+ slug: 'agent-space-team',
+ });
+ await db.insert(agents).values({
+ id: 'agt_space_ws',
+ title: 'Team agent',
+ userId,
+ visibility: 'public',
+ workspaceId,
+ });
+ await db.insert(knowledgeBases).values({
+ id: 'kb-private-space',
+ name: 'Team agent',
+ settings: { owner: { id: 'agt_space_ws', type: 'agent' } },
+ type: 'agent',
+ userId,
+ visibility: 'private',
+ workspaceId,
+ });
+ await db.insert(agentsKnowledgeBases).values({
+ agentId: 'agt_space_ws',
+ enabled: false,
+ knowledgeBaseId: 'kb-private-space',
+ userId,
+ workspaceId,
+ });
+
+ await expect(new AgentSpaceRepository(db, userId, workspaceId).list()).resolves.toHaveLength(
+ 1,
+ );
+ await expect(new AgentSpaceRepository(db, otherUserId, workspaceId).list()).resolves.toEqual(
+ [],
+ );
+ });
+ });
+
describe('migrateBatch', () => {
it('moves dedicated documents, including soft-deleted bindings, and keeps updatedAt', async () => {
await insertDocument('doc-a');
diff --git a/packages/database/src/repositories/agentSpace/index.ts b/packages/database/src/repositories/agentSpace/index.ts
index e411a78ed9b..112909f0ba5 100644
--- a/packages/database/src/repositories/agentSpace/index.ts
+++ b/packages/database/src/repositories/agentSpace/index.ts
@@ -1,4 +1,5 @@
-import { and, asc, eq, inArray, isNull, sql } from 'drizzle-orm';
+import type { AgentKnowledgeSpaceItem } from '@lobechat/types';
+import { and, asc, desc, eq, inArray, isNull, sql } from 'drizzle-orm';
import {
agentDocuments,
@@ -65,6 +66,37 @@ export class AgentSpaceRepository {
return space?.id;
}
+ /**
+ * Lists the spaces of every agent visible to the caller, most recently edited agent first.
+ */
+ async list(): Promise<AgentKnowledgeSpaceItem[]> {
+ return this.db
+ .select({
+ agentId: agents.id,
+ avatar: agents.avatar,
+ backgroundColor: agents.backgroundColor,
+ description: agents.description,
+ id: knowledgeBases.id,
+ title: agents.title,
+ })
+ .from(agentsKnowledgeBases)
+ .innerJoin(knowledgeBases, eq(knowledgeBases.id, agentsKnowledgeBases.knowledgeBaseId))
+ .innerJoin(agents, eq(agents.id, agentsKnowledgeBases.agentId))
+ .where(
+ and(
+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, agents),
+ // A space keeps its own visibility, so listing it needs access to both.
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ knowledgeBases,
+ ),
+ eq(knowledgeBases.type, AGENT_SPACE_TYPE),
+ sql`${knowledgeBases.settings} -> 'owner' ->> 'id' = ${agents.id}`,
+ ),
+ )
+ .orderBy(desc(agents.updatedAt));
+ }
+
/**
* Returns the agent's space, creating it on first use.
*
diff --git a/packages/database/src/repositories/knowledge/__tests__/documentChildren.test.ts b/packages/database/src/repositories/knowledge/__tests__/documentChildren.test.ts
index 55e9d777a0b..e9178e25108 100644
--- a/packages/database/src/repositories/knowledge/__tests__/documentChildren.test.ts
+++ b/packages/database/src/repositories/knowledge/__tests__/documentChildren.test.ts
@@ -101,3 +101,27 @@ describe('KnowledgeRepo.query — documents with children', () => {
expect(fileChildren[0].hasChildren).toBe(false);
});
});
+
+describe('agent space listing', () => {
+ it('shows agent documents but not the tool-result archive', async () => {
+ await serverDB
+ .insert(documents)
+ .values([
+ page('agent-note', { sourceType: 'agent' }),
+ page('.tool-results', { fileType: 'custom/folder', sourceType: 'agent' }),
+ ]);
+
+ const ids = (await knowledgeRepo.query({ knowledgeBaseId: kbId })).map(({ id }) => id);
+
+ expect(ids).toContain('agent-note');
+ expect(ids).not.toContain('.tool-results');
+ });
+
+ it("keeps a user's own folder that happens to share the archive name", async () => {
+ await serverDB.insert(documents).values(page('.tool-results', { fileType: 'custom/folder' }));
+
+ const ids = (await knowledgeRepo.query({ knowledgeBaseId: kbId })).map(({ id }) => id);
+
+ expect(ids).toContain('.tool-results');
+ });
+});
diff --git a/packages/database/src/repositories/knowledge/index.ts b/packages/database/src/repositories/knowledge/index.ts
index 6f41293546f..267ad08aba6 100644
--- a/packages/database/src/repositories/knowledge/index.ts
+++ b/packages/database/src/repositories/knowledge/index.ts
@@ -1,5 +1,6 @@
import {
AGENT_ARTIFACT_SOURCE_TYPES,
+ AGENT_TOOL_RESULTS_DIR_NAME,
CUSTOM_DOCUMENT_FILE_TYPE,
CUSTOM_FOLDER_FILE_TYPE,
HTML_DOCUMENT_FILE_TYPE,
@@ -587,6 +588,11 @@ export class KnowledgeRepo {
// already come back through the file arm.
knowledgeBaseId ? isNull(d.fileId) : undefined,
knowledgeBaseId ? eq(d.knowledgeBaseId, knowledgeBaseId) : undefined,
+ // An agent's space holds its archive folder too, which is runtime data.
+ // Matching provenance keeps a user's own folder of the same name visible.
+ knowledgeBaseId
+ ? sql`NOT (${d.filename} IS NOT DISTINCT FROM ${AGENT_TOOL_RESULTS_DIR_NAME} AND ${inArray(d.sourceType, [...AGENT_ARTIFACT_SOURCE_TYPES])})`
+ : undefined,
!knowledgeBaseId && excludeKnowledgeBaseIds?.length
? or(isNull(d.knowledgeBaseId), notInArray(d.knowledgeBaseId, excludeKnowledgeBaseIds))
: undefined,
diff --git a/packages/locales/src/default/file.ts b/packages/locales/src/default/file.ts
index f2df2a4b011..e5f025645bb 100644
--- a/packages/locales/src/default/file.ts
+++ b/packages/locales/src/default/file.ts
@@ -60,6 +60,11 @@ export default {
'docs.home.tabs.mine': 'Created by me',
'docs.home.tabs.recent': 'Recently updated',
'docs.home.tabs.shared': 'Shared with me',
+ 'docs.library.agentSpaces.emptyDesc': "An Agent's documents appear here once you open that Agent",
+ 'docs.library.agentSpaces.emptyTitle': 'No Agent knowledge bases yet',
+ 'docs.library.agentSpaces.untitled': 'Untitled Agent',
+ 'docs.library.tabs.agents': 'Agents',
+ 'docs.library.tabs.mine': 'My knowledge bases',
'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',
diff --git a/packages/types/src/knowledgeBase/index.ts b/packages/types/src/knowledgeBase/index.ts
index 672bbf5432f..40acdbfb6d4 100644
--- a/packages/types/src/knowledgeBase/index.ts
+++ b/packages/types/src/knowledgeBase/index.ts
@@ -29,6 +29,17 @@ export interface KnowledgeBaseItem {
visibility?: 'private' | 'public';
}
+/** An agent's dedicated knowledge base, identified to the user by its agent. */
+export interface AgentKnowledgeSpaceItem {
+ agentId: string;
+ avatar: string | null;
+ backgroundColor: string | null;
+ description: string | null;
+ /** The knowledge base id. */
+ id: string;
+ title: string | null;
+}
+
export interface CreateKnowledgeBaseParams {
avatar?: string;
/** Cover image: a preset key (`preset:<id>`) or an uploaded image URL. */
diff --git a/src/features/LibraryGallery/AgentSpaceGallery.tsx b/src/features/LibraryGallery/AgentSpaceGallery.tsx
new file mode 100644
index 00000000000..696b5939476
--- /dev/null
+++ b/src/features/LibraryGallery/AgentSpaceGallery.tsx
@@ -0,0 +1,77 @@
+'use client';
+
+import { Empty, Flexbox } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+import { BotIcon } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import AgentAvatar from '@/components/AgentAvatar';
+import AsyncBoundary from '@/components/AsyncBoundary';
+import {
+ RESOURCE_HOME_SECTIONS,
+ ResourceSectionSkeleton,
+} from '@/components/Skeleton/ResourceHome';
+import { knowledgeBaseSelectors, useKnowledgeBaseStore } from '@/store/library';
+
+import { libraryCardStyles } from './LibraryCard';
+
+interface AgentSpaceGalleryProps {
+ onOpen: (id: string) => void;
+}
+
+/** Every agent's dedicated library, identified by the agent rather than a cover. */
+const AgentSpaceGallery = ({ onOpen }: AgentSpaceGalleryProps) => {
+ const { t } = useTranslation('file');
+ const useFetchAgentSpaceList = useKnowledgeBaseStore((s) => s.useFetchAgentSpaceList);
+ const { error, isHydrated, revalidate } = useFetchAgentSpaceList(true);
+ const data = useKnowledgeBaseStore(knowledgeBaseSelectors.agentSpaceList);
+
+ return (
+ <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.agentSpaces.emptyDesc')}
+ icon={BotIcon}
+ title={t('docs.library.agentSpaces.emptyTitle')}
+ />
+ }
+ onRetry={() => revalidate()}
+ >
+ <div {...stylex.props(libraryCardStyles.grid)}>
+ {data?.map((space) => {
+ const name = space.title || t('docs.library.agentSpaces.untitled');
+
+ return (
+ <button
+ key={space.id}
+ type={'button'}
+ {...stylex.props(libraryCardStyles.card)}
+ onClick={() => onOpen(space.id)}
+ >
+ <Flexbox gap={10} padding={14} width={'100%'}>
+ <AgentAvatar
+ agentId={space.agentId}
+ avatar={space.avatar}
+ background={space.backgroundColor ?? undefined}
+ name={name}
+ size={40}
+ />
+ <span {...stylex.props(libraryCardStyles.name)}>{name}</span>
+ <div {...stylex.props(libraryCardStyles.description)}>
+ {space.description || t('docs.library.noDescription')}
+ </div>
+ </Flexbox>
+ </button>
+ );
+ })}
+ </div>
+ </AsyncBoundary>
+ );
+};
+
+export default AgentSpaceGallery;
diff --git a/src/features/LibraryGallery/index.tsx b/src/features/LibraryGallery/index.tsx
index 496b582ae01..8b39698b651 100644
--- a/src/features/LibraryGallery/index.tsx
+++ b/src/features/LibraryGallery/index.tsx
@@ -1,10 +1,11 @@
'use client';
-import { Button, cssVar, Empty, Flexbox } from '@lobehub/ui';
+import { Button, cssVar, Empty, Flexbox, Tabs } 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 { useSearchParams } from 'react-router';
import AsyncBoundary from '@/components/AsyncBoundary';
import {
@@ -17,9 +18,15 @@ import { useResourceManagerStore } from '@/features/ResourceManager/store';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { usePermission } from '@/hooks/usePermission';
import { knowledgeBaseSelectors, useKnowledgeBaseStore } from '@/store/library';
+import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
+import AgentSpaceGallery from './AgentSpaceGallery';
import { CreateLibraryCard, LibraryCard, libraryCardStyles } from './LibraryCard';
+const TAB_PARAM = 'tab';
+const AGENTS_TAB = 'agents';
+const MINE_TAB = 'mine';
+
const styles = stylex.create({
content: {
width: '100%',
@@ -45,6 +52,10 @@ const LibraryGallery = memo(() => {
const navigate = useWorkspaceAwareNavigate();
const { allowed: canCreate, reason } = usePermission('create_content');
const { open: openCreateLibrary } = useCreateNewModal();
+ const showAgentSpaces = useServerConfigStore(serverConfigSelectors.enableAgentKnowledgeSpace);
+ // In the URL so coming back from an agent's library lands on the same tab.
+ const [searchParams, setSearchParams] = useSearchParams();
+ const showingAgents = showAgentSpaces && searchParams.get(TAB_PARAM) === AGENTS_TAB;
const setLibraryId = useResourceManagerStore((s) => s.setLibraryId);
// Coming back from a library, its id must not keep scoping uploads and lists.
useLayoutEffect(() => {
@@ -71,55 +82,80 @@ const LibraryGallery = memo(() => {
return (
<Flexbox height={'100%'}>
<NavHeader
- left={<Flexbox style={{ marginLeft: 8 }}>{t('docs.section.library')}</Flexbox>}
style={{ borderBottom: `1px solid ${cssVar.colorBorderSecondary}` }}
+ left={
+ <Flexbox horizontal align={'center'} gap={12} style={{ marginLeft: 8 }}>
+ <span style={{ whiteSpace: 'nowrap' }}>{t('docs.section.library')}</span>
+ {showAgentSpaces && (
+ <Tabs
+ activeKey={showingAgents ? AGENTS_TAB : MINE_TAB}
+ size={'small'}
+ variant={'rounded'}
+ items={[
+ { key: MINE_TAB, label: t('docs.library.tabs.mine') },
+ { key: AGENTS_TAB, label: t('docs.library.tabs.agents') },
+ ]}
+ onChange={(key) =>
+ setSearchParams(key === AGENTS_TAB ? { [TAB_PARAM]: AGENTS_TAB } : {}, {
+ replace: true,
+ })
+ }
+ />
+ )}
+ </Flexbox>
+ }
right={
- <Button
- disabled={!canCreate}
- icon={PlusIcon}
- title={canCreate ? undefined : reason}
- type={'primary'}
- onClick={handleCreate}
- >
- {t('library.new')}
- </Button>
+ showingAgents ? undefined : (
+ <Button
+ disabled={!canCreate}
+ icon={PlusIcon}
+ title={canCreate ? undefined : reason}
+ type={'primary'}
+ 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>
+ {showingAgents ? (
+ <AgentSpaceGallery onOpen={openLibrary} />
+ ) : (
+ <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'}
+ 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>
diff --git a/src/services/knowledgeBase.ts b/src/services/knowledgeBase.ts
index 72211564311..01e09b1745c 100644
--- a/src/services/knowledgeBase.ts
+++ b/src/services/knowledgeBase.ts
@@ -12,6 +12,10 @@ class KnowledgeBaseService {
);
};
+ getAgentSpaces = async () => {
+ return lambdaClient.knowledgeBase.getAgentSpaces.query();
+ };
+
getKnowledgeBaseById = async (id: string) => {
return lambdaClient.knowledgeBase.getKnowledgeBaseById.query({ id });
};
diff --git a/src/store/library/slices/crud/action.ts b/src/store/library/slices/crud/action.ts
index e2107f93730..2765a8b6f30 100644
--- a/src/store/library/slices/crud/action.ts
+++ b/src/store/library/slices/crud/action.ts
@@ -9,9 +9,15 @@ import {
import { knowledgeBaseService } from '@/services/knowledgeBase';
import type { KnowledgeBaseStore } from '@/store/library/store';
import type { StoreSetter } from '@/store/types';
-import type { CreateKnowledgeBaseParams, KnowledgeBaseItem } from '@/types/knowledgeBase';
+import type {
+ AgentKnowledgeSpaceItem,
+ CreateKnowledgeBaseParams,
+ KnowledgeBaseItem,
+} from '@/types/knowledgeBase';
import {
+ AGENT_SPACE_LIST_KEY,
+ agentSpaceListResource,
KNOWLEDGE_BASE_LIST_ALL_KEY,
knowledgeBaseItemResource,
knowledgeBaseListResource,
@@ -38,6 +44,7 @@ export const createCrudSlice = (set: Setter, get: () => KnowledgeBaseStore, _api
* `useFetch*` hooks only orchestrate fetching and return flags.
*/
export class KnowledgeBaseCrudActionImpl {
+ readonly #agentSpaceList;
readonly #get: () => KnowledgeBaseStore;
readonly #kbEntity;
readonly #kbItem;
@@ -76,6 +83,13 @@ export class KnowledgeBaseCrudActionImpl {
stateKey: 'knowledgeBaseDetailReplica',
view: recordLens<KnowledgeBaseStore, KnowledgeBaseItem>('knowledgeBaseDetailMap'),
});
+ this.#agentSpaceList = createReplicaSlice(agentSpaceListResource, {
+ actionPrefix: 'agentSpaceList',
+ get,
+ set,
+ stateKey: 'agentSpaceListReplica',
+ view: recordLens<KnowledgeBaseStore, AgentKnowledgeSpaceItem[]>('agentSpaceListMap'),
+ });
// The same KB lives in the list surfaces and in the by-id projection.
this.#kbEntity = linkReplicaEntity<KnowledgeBaseItem>([this.#kbList, this.#kbItem]);
}
@@ -112,6 +126,10 @@ export class KnowledgeBaseCrudActionImpl {
useFetchKnowledgeBaseList = (visibility?: KnowledgeBaseVisibility): ReplicaSyncResult =>
this.#kbList.useSync({ visibility });
+ /** Syncs agents' dedicated libraries; pass `false` until that surface is shown. */
+ useFetchAgentSpaceList = (enabled: boolean): ReplicaSyncResult =>
+ this.#agentSpaceList.useSync(enabled ? AGENT_SPACE_LIST_KEY : null);
+
// ---- writes ------------------------------------------------------------
createNewKnowledgeBase = async (params: CreateKnowledgeBaseParams): Promise<string> => {
diff --git a/src/store/library/slices/crud/initialState.ts b/src/store/library/slices/crud/initialState.ts
index ea88c19762c..acc2e9b4c34 100644
--- a/src/store/library/slices/crud/initialState.ts
+++ b/src/store/library/slices/crud/initialState.ts
@@ -1,8 +1,12 @@
import { createReplicaState, type ReplicaState } from '@/libs/replica';
-import { type KnowledgeBaseItem } from '@/types/knowledgeBase';
+import { type AgentKnowledgeSpaceItem, type KnowledgeBaseItem } from '@/types/knowledgeBase';
export interface KnowledgeBaseState {
activeKnowledgeBaseId: string | null;
+ /** Agents' dedicated libraries (`agentSpaceListMap.all`). */
+ agentSpaceListMap: Record<string, AgentKnowledgeSpaceItem[]>;
+ /** Local-first bookkeeping for `agentSpaceListMap`. */
+ agentSpaceListReplica: ReplicaState<AgentKnowledgeSpaceItem[]>;
/** By-id KB projection (`knowledgeBaseDetailMap[id]`). */
knowledgeBaseDetailMap: Record<string, KnowledgeBaseItem>;
/** Local-first bookkeeping for `knowledgeBaseDetailMap`. */
@@ -19,6 +23,8 @@ export interface KnowledgeBaseState {
export const initialKnowledgeBaseState: KnowledgeBaseState = {
activeKnowledgeBaseId: null,
+ agentSpaceListMap: {},
+ agentSpaceListReplica: createReplicaState(),
knowledgeBaseDetailMap: {},
knowledgeBaseDetailReplica: createReplicaState(),
knowledgeBaseListMap: {},
diff --git a/src/store/library/slices/crud/projection.ts b/src/store/library/slices/crud/projection.ts
index 2d888d3d59b..0523f654aeb 100644
--- a/src/store/library/slices/crud/projection.ts
+++ b/src/store/library/slices/crud/projection.ts
@@ -1,6 +1,6 @@
import { defineReplica } from '@/libs/replica';
import { knowledgeBaseService } from '@/services/knowledgeBase';
-import type { KnowledgeBaseItem } from '@/types/knowledgeBase';
+import type { AgentKnowledgeSpaceItem, KnowledgeBaseItem } from '@/types/knowledgeBase';
/**
* Workspace-scoped visibility of a KB. `private` rows are visible to their
@@ -56,3 +56,19 @@ export const knowledgeBaseItemResource = defineReplica<
storage: 'indexedDB',
version: 1,
});
+
+/** The only entry of the agent space list: the replica scope already isolates workspaces. */
+export const AGENT_SPACE_LIST_KEY = 'all';
+
+/** Agents' dedicated libraries, a surface of their own next to the user's libraries. */
+export const agentSpaceListResource = defineReplica<
+ typeof AGENT_SPACE_LIST_KEY,
+ AgentKnowledgeSpaceItem[],
+ AgentKnowledgeSpaceItem[]
+>({
+ fetcher: () => knowledgeBaseService.getAgentSpaces(),
+ key: (key) => key,
+ name: 'agentSpaceList',
+ storage: 'indexedDB',
+ version: 1,
+});
diff --git a/src/store/library/slices/crud/selectors.ts b/src/store/library/slices/crud/selectors.ts
index 12d0932faed..7acca7d328d 100644
--- a/src/store/library/slices/crud/selectors.ts
+++ b/src/store/library/slices/crud/selectors.ts
@@ -1,6 +1,10 @@
import { type KnowledgeBaseStoreState } from '@/store/library/initialState';
-import { knowledgeBaseListKey, type KnowledgeBaseVisibility } from './projection';
+import {
+ AGENT_SPACE_LIST_KEY,
+ knowledgeBaseListKey,
+ type KnowledgeBaseVisibility,
+} from './projection';
const activeKnowledgeBaseId = (s: KnowledgeBaseStoreState) => s.activeKnowledgeBaseId;
@@ -21,8 +25,12 @@ const isKnowledgeBaseListInit =
(visibility?: KnowledgeBaseVisibility) => (s: KnowledgeBaseStoreState) =>
s.knowledgeBaseListMap[knowledgeBaseListKey(visibility)] !== undefined;
+/** Agents' dedicated libraries; `undefined` until first read. */
+const agentSpaceList = (s: KnowledgeBaseStoreState) => s.agentSpaceListMap[AGENT_SPACE_LIST_KEY];
+
export const knowledgeBaseSelectors = {
activeKnowledgeBaseId,
+ agentSpaceList,
getKnowledgeBaseById,
getKnowledgeBaseList,
getKnowledgeBaseNameById,