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(agent): split the knowledge picker into libraries and files (#23433)

Arvin Xu2cd33f8569ca
diff --git a/apps/server/src/routers/lambda/agent/knowledge.ts b/apps/server/src/routers/lambda/agent/knowledge.ts
index fad5f05bf1d..d83d6abae4f 100644
--- a/apps/server/src/routers/lambda/agent/knowledge.ts
+++ b/apps/server/src/routers/lambda/agent/knowledge.ts
@@ -174,16 +174,20 @@ export const knowledgeRouter = router({
// Filter out all images
.filter((file) => !file.fileType.startsWith('image'))
.map((file) => ({
+ createdAt: file.createdAt,
enabled: knowledge.files.some((item) => item.id === file.id),
fileType: file.fileType,
id: file.id,
name: file.name,
ownerUserId: file.userId,
+ size: file.size,
type: KnowledgeType.File,
+ updatedAt: file.updatedAt,
visibility: file.visibility as 'private' | 'public',
})),
...visibleKnowledgeBases.map((knowledgeBase) => ({
avatar: knowledgeBase.avatar,
+ createdAt: knowledgeBase.createdAt,
description: knowledgeBase.description,
enabled: knowledge.knowledgeBases.some((item) => item.id === knowledgeBase.id),
id: knowledgeBase.id,
@@ -191,6 +195,7 @@ export const knowledgeRouter = router({
name: knowledgeBase.name,
ownerUserId: knowledgeBase.userId,
type: KnowledgeType.KnowledgeBase,
+ updatedAt: knowledgeBase.updatedAt,
visibility: knowledgeBase.visibility,
})),
];
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 95724248e49..6323c195fe9 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1802,9 +1802,23 @@
"knowledgeBase.files": "Files",
"knowledgeBase.libraries": "Libraries",
"knowledgeBase.library.action.add": "Add",
+ "knowledgeBase.library.action.added": "Added",
"knowledgeBase.library.action.detail": "Details",
"knowledgeBase.library.action.remove": "Remove",
"knowledgeBase.library.title": "Files / Libraries",
+ "knowledgeBase.picker.createLibrary": "Create library",
+ "knowledgeBase.picker.fileEmpty": "No documents to attach yet. Upload them in Resources first; images, audio and video can’t be searched.",
+ "knowledgeBase.picker.libraryEmpty": "No libraries yet. Create one, then add documents to it in Resources.",
+ "knowledgeBase.picker.noMatch": "Nothing matches your search",
+ "knowledgeBase.picker.searchFile": "Search files",
+ "knowledgeBase.picker.searchLibrary": "Search libraries",
+ "knowledgeBase.picker.sort.createdAt": "Recently created",
+ "knowledgeBase.picker.sort.name": "Name A–Z",
+ "knowledgeBase.picker.sort.nameDesc": "Name Z–A",
+ "knowledgeBase.picker.sort.updatedAt": "Recently updated",
+ "knowledgeBase.picker.tabs.file": "Files",
+ "knowledgeBase.picker.tabs.library": "Libraries",
+ "knowledgeBase.picker.title": "Attach Knowledge",
"knowledgeBase.related.browse": "Choose Files / Libraries",
"knowledgeBase.related.empty": "No related files or libraries",
"knowledgeBase.relativeFilesOrLibraries": "Related Files/Libraries",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 0799f613e58..84c4e05fc81 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1802,9 +1802,23 @@
"knowledgeBase.files": "文件",
"knowledgeBase.libraries": "资源库",
"knowledgeBase.library.action.add": "添加",
+ "knowledgeBase.library.action.added": "已添加",
"knowledgeBase.library.action.detail": "详情",
"knowledgeBase.library.action.remove": "移除",
"knowledgeBase.library.title": "文件 / 资源库",
+ "knowledgeBase.picker.createLibrary": "新建知识库",
+ "knowledgeBase.picker.fileEmpty": "还没有可关联的文档。先在「资源」里上传;图片、音频和视频无法被检索。",
+ "knowledgeBase.picker.libraryEmpty": "还没有知识库。新建一个,再到「资源」里往里放文档。",
+ "knowledgeBase.picker.noMatch": "没有匹配的结果",
+ "knowledgeBase.picker.searchFile": "搜索文件",
+ "knowledgeBase.picker.searchLibrary": "搜索知识库",
+ "knowledgeBase.picker.sort.createdAt": "最近创建",
+ "knowledgeBase.picker.sort.name": "名称 A–Z",
+ "knowledgeBase.picker.sort.nameDesc": "名称 Z–A",
+ "knowledgeBase.picker.sort.updatedAt": "最近更新",
+ "knowledgeBase.picker.tabs.file": "文件",
+ "knowledgeBase.picker.tabs.library": "知识库",
+ "knowledgeBase.picker.title": "关联知识",
"knowledgeBase.related.browse": "选择文件 / 资源库",
"knowledgeBase.related.empty": "暂无关联文件或资源库",
"knowledgeBase.relativeFilesOrLibraries": "关联文件 / 资源库",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 29438cce308..0eb97162945 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1104,11 +1104,27 @@ export default {
'knowledgeBase.disabled':
'Library chat isn’t available in this deployment. Switch to a server-side database, or use {{cloud}}.',
'knowledgeBase.library.action.add': 'Add',
+ 'knowledgeBase.library.action.added': 'Added',
'knowledgeBase.library.action.detail': 'Details',
'knowledgeBase.library.action.remove': 'Remove',
'knowledgeBase.library.title': 'Files / Libraries',
'knowledgeBase.files': 'Files',
'knowledgeBase.libraries': 'Libraries',
+ 'knowledgeBase.picker.title': 'Attach Knowledge',
+ 'knowledgeBase.picker.tabs.library': 'Libraries',
+ 'knowledgeBase.picker.tabs.file': 'Files',
+ 'knowledgeBase.picker.searchLibrary': 'Search libraries',
+ 'knowledgeBase.picker.searchFile': 'Search files',
+ 'knowledgeBase.picker.sort.updatedAt': 'Recently updated',
+ 'knowledgeBase.picker.sort.createdAt': 'Recently created',
+ 'knowledgeBase.picker.sort.name': 'Name A–Z',
+ 'knowledgeBase.picker.sort.nameDesc': 'Name Z–A',
+ 'knowledgeBase.picker.noMatch': 'Nothing matches your search',
+ 'knowledgeBase.picker.libraryEmpty':
+ 'No libraries yet. Create one, then add documents to it in Resources.',
+ 'knowledgeBase.picker.createLibrary': 'Create library',
+ 'knowledgeBase.picker.fileEmpty':
+ 'No documents to attach yet. Upload them in Resources first; images, audio and video can’t be searched.',
'knowledgeBase.related.browse': 'Choose Files / Libraries',
'knowledgeBase.related.empty': 'No related files or libraries',
'knowledgeBase.relativeFilesOrLibraries': 'Related Files/Libraries',
diff --git a/packages/types/src/knowledgeBase/index.ts b/packages/types/src/knowledgeBase/index.ts
index 40acdbfb6d4..156b0a04600 100644
--- a/packages/types/src/knowledgeBase/index.ts
+++ b/packages/types/src/knowledgeBase/index.ts
@@ -58,6 +58,8 @@ export enum KnowledgeType {
export interface KnowledgeItem {
avatar?: string | null;
content?: string;
+ /** Creation time: one of the picker's sort orders. */
+ createdAt?: Date | string;
description?: string | null;
enabled?: boolean;
fileType?: string;
@@ -71,7 +73,11 @@ export interface KnowledgeItem {
name: string;
/** Creator's user id — used by the picker to gate creator-only actions and identify ownership. */
ownerUserId?: string;
+ /** File only: bytes, so the picker can tell two similar documents apart. */
+ size?: number;
type: KnowledgeType;
+ /** Last change: sorts the picker, and is shown next to a file's size. */
+ updatedAt?: Date | string;
/** Workspace-scoped visibility of the underlying resource (file or KB). */
visibility?: 'private' | 'public';
}
diff --git a/scripts/stylexMigration/legacyFiles.json b/scripts/stylexMigration/legacyFiles.json
index d213826a12e..b1e08f2b7e4 100644
--- a/scripts/stylexMigration/legacyFiles.json
+++ b/scripts/stylexMigration/legacyFiles.json
@@ -378,7 +378,6 @@
"src/features/Integrations/Overview.tsx",
"src/features/LibraryModal/AssignKnowledgeBase/Item/MasonryItem.tsx",
"src/features/LibraryModal/AssignKnowledgeBase/Item/index.tsx",
- "src/features/LibraryModal/AssignKnowledgeBase/MasonrySkeleton.tsx",
"src/features/LibraryModal/AssignKnowledgeBase/ViewSwitcher.tsx",
"src/features/LibraryModal/AssignKnowledgeBase/VisibilityTabs.tsx",
"src/features/LibraryModal/FilePicker/index.tsx",
diff --git a/src/features/LibraryModal/AssignKnowledgeBase/Item/Action.tsx b/src/features/LibraryModal/AssignKnowledgeBase/Item/Action.tsx
index 0338fb6756f..b4f66ad465d 100644
--- a/src/features/LibraryModal/AssignKnowledgeBase/Item/Action.tsx
+++ b/src/features/LibraryModal/AssignKnowledgeBase/Item/Action.tsx
@@ -1,12 +1,11 @@
-import { ActionIcon, Button, DropdownMenu, Flexbox, Icon } from '@lobehub/ui';
-import { InfoIcon, MoreVerticalIcon, Trash2 } from 'lucide-react';
+import { ActionIcon, DropdownMenu, Flexbox, Icon, Text } from '@lobehub/ui';
+import { CheckIcon, ExternalLinkIcon, MoreHorizontalIcon, PlusIcon, Trash2 } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { buildFilePath, buildLibraryPath } from '@/features/ResourceManager/utils/resourcePath';
import { useAgentStore } from '@/store/agent';
-import { useServerConfigStore } from '@/store/serverConfig';
import { KnowledgeType } from '@/types/knowledgeBase';
interface ActionsProps {
@@ -15,10 +14,13 @@ interface ActionsProps {
type: KnowledgeType;
}
+/**
+ * A row's add / attached control. Adding is a single round "+"; an attached row says so in words and
+ * keeps removal one step away behind "…", so a stray click on the state never detaches it.
+ */
const Actions = memo<ActionsProps>(({ id, type, enabled }) => {
const { t } = useTranslation('chat');
- const mobile = useServerConfigStore((s) => s.isMobile);
const activeWorkspaceSlug = useActiveWorkspaceSlug();
const [
addFilesToAgent,
@@ -33,66 +35,70 @@ const Actions = memo<ActionsProps>(({ id, type, enabled }) => {
]);
const [loading, setLoading] = useState(false);
+ const isLibrary = type === KnowledgeType.KnowledgeBase;
- const assignKnowledge = async () => {
+ const run = async (task: () => Promise<void>) => {
setLoading(true);
- if (type === KnowledgeType.KnowledgeBase) {
- await addKnowledgeBasesToAgent(id);
- } else {
- await addFilesToAgent([id], true);
+ try {
+ await task();
+ } finally {
+ setLoading(false);
}
- setLoading(false);
};
- const removeKnowledge = async () => {
- setLoading(true);
- if (type === KnowledgeType.KnowledgeBase) {
- await removeKnowledgeBasesFromAgent(id);
- } else {
- await removeFilesFromAgent(id);
- }
- setLoading(false);
- };
+ const assignKnowledge = () =>
+ run(() => (isLibrary ? addKnowledgeBasesToAgent(id) : addFilesToAgent([id], true)));
+
+ const removeKnowledge = () =>
+ run(() => (isLibrary ? removeKnowledgeBasesFromAgent(id) : removeFilesFromAgent(id)));
+
+ if (!enabled)
+ return (
+ <ActionIcon
+ icon={PlusIcon}
+ loading={loading}
+ size={'small'}
+ style={{ borderRadius: '50%' }}
+ title={t('knowledgeBase.library.action.add')}
+ variant={'filled'}
+ onClick={assignKnowledge}
+ />
+ );
return (
- <Flexbox horizontal align={'center'}>
- {enabled ? (
- <DropdownMenu
- placement="bottomRight"
- items={[
- {
- icon: <Icon icon={InfoIcon} />,
- key: 'detail',
- label: t('knowledgeBase.library.action.detail'),
- onClick: () => {
- window.open(
- type === KnowledgeType.KnowledgeBase
- ? buildLibraryPath(id, activeWorkspaceSlug)
- : buildFilePath(id, activeWorkspaceSlug),
- );
- },
- },
- {
- danger: true,
- icon: <Icon icon={Trash2} />,
- key: 'remove',
- label: t('knowledgeBase.library.action.remove'),
- onClick: removeKnowledge,
+ <Flexbox horizontal align={'center'} gap={4}>
+ <Flexbox horizontal align={'center'} gap={4}>
+ <Icon icon={CheckIcon} size={14} />
+ <Text fontSize={12} type={'secondary'}>
+ {t('knowledgeBase.library.action.added')}
+ </Text>
+ </Flexbox>
+ <DropdownMenu
+ placement={'bottomRight'}
+ items={[
+ {
+ icon: <Icon icon={ExternalLinkIcon} />,
+ key: 'detail',
+ label: t('knowledgeBase.library.action.detail'),
+ onClick: () => {
+ window.open(
+ isLibrary
+ ? buildLibraryPath(id, activeWorkspaceSlug)
+ : buildFilePath(id, activeWorkspaceSlug),
+ );
},
- ]}
- >
- <ActionIcon icon={MoreVerticalIcon} loading={loading} />
- </DropdownMenu>
- ) : (
- <Button
- loading={loading}
- size={mobile ? 'small' : undefined}
- type={'primary'}
- onClick={assignKnowledge}
- >
- {t('knowledgeBase.library.action.add')}
- </Button>
- )}
+ },
+ {
+ danger: true,
+ icon: <Icon icon={Trash2} />,
+ key: 'remove',
+ label: t('knowledgeBase.library.action.remove'),
+ onClick: removeKnowledge,
+ },
+ ]}
+ >
+ <ActionIcon icon={MoreHorizontalIcon} loading={loading} size={'small'} />
+ </DropdownMenu>
</Flexbox>
);
});
diff --git a/src/features/LibraryModal/AssignKnowledgeBase/Item/MasonryItemWrapper.tsx b/src/features/LibraryModal/AssignKnowledgeBase/Item/MasonryItemWrapper.tsx
deleted file mode 100644
index 44231649127..00000000000
--- a/src/features/LibraryModal/AssignKnowledgeBase/Item/MasonryItemWrapper.tsx
+++ /dev/null
@@ -1,27 +0,0 @@
-import { memo } from 'react';
-
-import { type KnowledgeItem } from '@/types/knowledgeBase';
-
-import MasonryItem from './MasonryItem';
-
-interface MasonryItemWrapperProps {
- data: KnowledgeItem;
- index: number;
-}
-
-const MasonryItemWrapper = memo<MasonryItemWrapperProps>(({ data: item }) => {
- // Safety check: return null if item is undefined
- if (!item || !item.id) {
- return null;
- }
-
- return (
- <div style={{ padding: '8px 4px' }}>
- <MasonryItem {...item} />
- </div>
- );
-});
-
-MasonryItemWrapper.displayName = 'MasonryItemWrapper';
-
-export default MasonryItemWrapper;
diff --git a/src/features/LibraryModal/AssignKnowledgeBase/Item/index.tsx b/src/features/LibraryModal/AssignKnowledgeBase/Item/index.tsx
index 5c663498de0..79436c2b838 100644
--- a/src/features/LibraryModal/AssignKnowledgeBase/Item/index.tsx
+++ b/src/features/LibraryModal/AssignKnowledgeBase/Item/index.tsx
@@ -1,9 +1,13 @@
+import { formatSize } from '@lobechat/utils/format';
import { createStaticStyles, cssVar, Flexbox, Icon, Text } from '@lobehub/ui';
+import dayjs from 'dayjs';
import { LockIcon } from 'lucide-react';
import { memo, type ReactNode } from 'react';
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import KnowledgeIcon from '@/components/KnowledgeIcon';
-import { type KnowledgeItem } from '@/types/knowledgeBase';
+import { buildFilePath, buildLibraryPath } from '@/features/ResourceManager/utils/resourcePath';
+import { type KnowledgeItem, KnowledgeType } from '@/types/knowledgeBase';
import Actions from './Action';
@@ -17,6 +21,11 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
link: css`
overflow: hidden;
color: ${cssVar.colorText};
+
+ &:hover {
+ color: ${cssVar.colorPrimary};
+ text-decoration: underline;
+ }
`,
title: css`
margin: 0 !important;
@@ -30,7 +39,35 @@ interface PluginItemProps extends KnowledgeItem {
}
const PluginItem = memo<PluginItemProps>(
- ({ action, id, fileType, name, type, description, enabled, memberRestricted, visibility }) => {
+ ({
+ action,
+ id,
+ fileType,
+ name,
+ type,
+ description,
+ enabled,
+ memberRestricted,
+ size,
+ updatedAt,
+ visibility,
+ }) => {
+ const activeWorkspaceSlug = useActiveWorkspaceSlug();
+ const isLibrary = type === KnowledgeType.KnowledgeBase;
+ // The name is the way into the library or file, so it opens it in a new tab.
+ const detailPath = isLibrary
+ ? buildLibraryPath(id, activeWorkspaceSlug)
+ : buildFilePath(id, activeWorkspaceSlug);
+ // Files carry no description; their size and last change tell similar documents apart.
+ const meta = isLibrary
+ ? description
+ : [
+ size ? formatSize(size) : undefined,
+ updatedAt ? dayjs(updatedAt).format('YYYY-MM-DD') : undefined,
+ ]
+ .filter(Boolean)
+ .join(' · ');
+
return (
<Flexbox
horizontal
@@ -60,13 +97,21 @@ const PluginItem = memo<PluginItemProps>(
{visibility === 'private' && (
<Icon color={cssVar.colorTextDescription} icon={LockIcon} size={12} />
)}
- <Text ellipsis className={styles.title}>
- {name}
- </Text>
+ <a
+ className={styles.link}
+ href={detailPath}
+ rel={'noreferrer'}
+ target={'_blank'}
+ title={name}
+ >
+ <Text ellipsis className={styles.title}>
+ {name}
+ </Text>
+ </a>
</Flexbox>
- {description && (
+ {meta && (
<Text ellipsis className={styles.desc}>
- {description}
+ {meta}
</Text>
)}
</Flexbox>
diff --git a/src/features/LibraryModal/AssignKnowledgeBase/List.tsx b/src/features/LibraryModal/AssignKnowledgeBase/List.tsx
index ae22e5ce87b..d94e6bf7d80 100644
--- a/src/features/LibraryModal/AssignKnowledgeBase/List.tsx
+++ b/src/features/LibraryModal/AssignKnowledgeBase/List.tsx
@@ -1,39 +1,62 @@
import { type KnowledgeItem } from '@lobechat/types';
-import { Alert, Center, Empty, Flexbox, Icon } from '@lobehub/ui';
-import { VirtuosoMasonry } from '@virtuoso.dev/masonry';
-import { BookOpen, ServerCrash } from 'lucide-react';
-import React, { memo, useMemo, useState } from 'react';
+import {
+ Alert,
+ Button,
+ Center,
+ Empty,
+ Flexbox,
+ Icon,
+ SearchBar,
+ Segmented,
+ Select,
+} from '@lobehub/ui';
+import { BookOpen, FileText, PlusIcon, SearchX, ServerCrash } from 'lucide-react';
+import { memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Virtuoso } from 'react-virtuoso';
import { useAgentStore } from '@/store/agent';
import { agentKnowledgeSelectors } from '@/store/agent/selectors';
-import { useGlobalStore } from '@/store/global';
+import { useCreateNewModal } from '../CreateNew';
+import {
+ filterPickerItems,
+ itemsOfKind,
+ type PickerKind,
+ type PickerSort,
+} from './filterPickerItems';
import Item from './Item';
-import MasonryItemWrapper from './Item/MasonryItemWrapper';
import Loading from './Loading';
-import MasonrySkeleton from './MasonrySkeleton';
import { resolvePickerScope } from './resolvePickerScope';
-import { useViewTransition } from './useViewTransition';
-import ViewSwitcher from './ViewSwitcher';
-import { type ViewMode } from './ViewSwitcher';
import VisibilityTabs, { type PickerVisibility } from './VisibilityTabs';
/** Stable empty list so an un-loaded surface never hands Virtuoso a new array each render. */
const EMPTY_KNOWLEDGE: KnowledgeItem[] = [];
-export const List = memo(() => {
- const { t } = useTranslation(['file', 'chat']);
+interface ListProps {
+ defaultKind: PickerKind;
+}
- const [useFetchFilesAndKnowledgeBases, activeAgentId, agentVisibility, agentWorkspaceId] =
- useAgentStore((s) => [
- s.useFetchFilesAndKnowledgeBases,
- s.activeAgentId,
- s.activeAgentId ? s.agentMap[s.activeAgentId]?.visibility : undefined,
- s.activeAgentId ? s.agentMap[s.activeAgentId]?.workspaceId : undefined,
- ]);
+export const List = memo<ListProps>(({ defaultKind }) => {
+ const { t } = useTranslation(['chat', 'file']);
+ const [
+ useFetchFilesAndKnowledgeBases,
+ activeAgentId,
+ agentVisibility,
+ agentWorkspaceId,
+ addKnowledgeBaseToAgent,
+ ] = useAgentStore((s) => [
+ s.useFetchFilesAndKnowledgeBases,
+ s.activeAgentId,
+ s.activeAgentId ? s.agentMap[s.activeAgentId]?.visibility : undefined,
+ s.activeAgentId ? s.agentMap[s.activeAgentId]?.workspaceId : undefined,
+ s.addKnowledgeBaseToAgent,
+ ]);
+
+ const [kind, setKind] = useState<PickerKind>(defaultKind);
+ const [keyword, setKeyword] = useState('');
+ const [sort, setSort] = useState<PickerSort>('updatedAt');
const [mode, setMode] = useState<PickerVisibility>('public');
const { effectiveVisibility, showPublicAgentHint, showVisibilityTabs } = resolvePickerScope({
agentVisibility,
@@ -50,113 +73,121 @@ export const List = memo(() => {
),
);
const items = data ?? EMPTY_KNOWLEDGE;
-
- const [columnCount, setColumnCount] = useState(2);
-
- const viewMode = useGlobalStore((s) => s.status.knowledgeBaseModalViewMode || 'list') as ViewMode;
- const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
- const { isTransitioning, startTransition } = useViewTransition(viewMode);
- const setViewMode = (mode: ViewMode) => {
- startTransition();
- updateSystemStatus({ knowledgeBaseModalViewMode: mode });
+ const visibleItems = useMemo(
+ () => filterPickerItems({ items, keyword, kind, sort }),
+ [items, keyword, kind, sort],
+ );
+ const libraryCount = useMemo(() => itemsOfKind(items, 'library').length, [items]);
+ const fileCount = useMemo(() => itemsOfKind(items, 'file').length, [items]);
+
+ // A new library is created for this agent, so it is attached as soon as it exists.
+ const { open: openCreateLibrary } = useCreateNewModal();
+ const createLibrary = () =>
+ // Created in the tab's scope, so a library made from the Private tab stays private and
+ // remains in this list once attached.
+ openCreateLibrary({
+ onSuccess: (id) => void addKnowledgeBaseToAgent(id),
+ visibility: effectiveVisibility,
+ });
+
+ const kindEmpty = (kind === 'library' ? libraryCount : fileCount) === 0;
+
+ const renderEmpty = () => {
+ if (error)
+ return (
+ <>
+ <Icon icon={ServerCrash} size={64} />
+ {t('networkError', { ns: 'file' })}
+ </>
+ );
+
+ if (!kindEmpty) return <Empty description={t('knowledgeBase.picker.noMatch')} icon={SearchX} />;
+
+ return kind === 'library' ? (
+ <Empty
+ description={t('knowledgeBase.picker.libraryEmpty')}
+ icon={BookOpen}
+ action={
+ <Button icon={<Icon icon={PlusIcon} />} type={'primary'} onClick={createLibrary}>
+ {t('knowledgeBase.picker.createLibrary')}
+ </Button>
+ }
+ />
+ ) : (
+ <Empty description={t('knowledgeBase.picker.fileEmpty')} icon={FileText} />
+ );
};
- // Update column count based on window size (max 2 columns for modal)
- const updateColumnCount = React.useCallback(() => {
- const width = window.innerWidth;
- if (width < 480) {
- setColumnCount(1);
- } else {
- setColumnCount(2);
- }
- }, []);
-
- // Initialize column count on mount
- React.useEffect(() => {
- updateColumnCount();
- }, [updateColumnCount]);
-
- // Set up resize listener when in masonry mode
- React.useEffect(() => {
- if (viewMode === 'masonry') {
- window.addEventListener('resize', updateColumnCount);
- return () => window.removeEventListener('resize', updateColumnCount);
- }
- }, [viewMode, updateColumnCount]);
-
- const isEmpty = items.length === 0;
-
- const masonryContext = useMemo(() => ({}), []);
-
return (
<Flexbox height={500}>
{/*
* Toolbar sits flush with the list items below: Virtuoso uses
* `marginInline: -16` to pull rows back to the outer edge and each
- * Item re-applies `paddingInline={16}`. Match that here so the tab
- * group and view switcher line up with the item icons / add buttons.
+ * Item re-applies `paddingInline={16}`.
*/}
- <Flexbox gap={8} style={{ paddingBlockEnd: 12 }}>
- <Flexbox horizontal align={'center'} justify={'space-between'}>
- {showVisibilityTabs ? <VisibilityTabs value={mode} onChange={setMode} /> : <span />}
- <ViewSwitcher view={viewMode} onViewChange={setViewMode} />
+ <Flexbox gap={12} style={{ paddingBlockEnd: 8 }}>
+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>
+ <Segmented
+ value={kind}
+ options={[
+ {
+ label: `${t('knowledgeBase.picker.tabs.library')} ${libraryCount || ''}`.trim(),
+ value: 'library',
+ },
+ {
+ label: `${t('knowledgeBase.picker.tabs.file')} ${fileCount || ''}`.trim(),
+ value: 'file',
+ },
+ ]}
+ onChange={(value) => setKind(value as PickerKind)}
+ />
+ {showVisibilityTabs && <VisibilityTabs value={mode} onChange={setMode} />}
</Flexbox>
- {showPublicAgentHint && (
- <Alert
- showIcon
- message={t('resources.knowledgePicker.publicAgentHint', { ns: 'chat' })}
- type={'info'}
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Flexbox flex={1}>
+ <SearchBar
+ allowClear
+ value={keyword}
+ variant={'outlined'}
+ placeholder={
+ kind === 'library'
+ ? t('knowledgeBase.picker.searchLibrary')
+ : t('knowledgeBase.picker.searchFile')
+ }
+ onInputChange={setKeyword}
+ />
+ </Flexbox>
+ <Select
+ style={{ flex: 'none', width: 136 }}
+ value={sort}
+ variant={'filled'}
+ options={[
+ { label: t('knowledgeBase.picker.sort.updatedAt'), value: 'updatedAt' },
+ { label: t('knowledgeBase.picker.sort.createdAt'), value: 'createdAt' },
+ { label: t('knowledgeBase.picker.sort.name'), value: 'name' },
+ { label: t('knowledgeBase.picker.sort.nameDesc'), value: 'nameDesc' },
+ ]}
+ onChange={(value) => setSort(value as PickerSort)}
/>
+ </Flexbox>
+ {showPublicAgentHint && (
+ <Alert showIcon message={t('resources.knowledgePicker.publicAgentHint')} type={'info'} />
)}
</Flexbox>
- {isLoading || isTransitioning ? (
- viewMode === 'masonry' ? (
- <MasonrySkeleton columnCount={columnCount} />
- ) : (
- <Loading />
- )
- ) : isEmpty ? (
- <Center gap={12} padding={40}>
- {error ? (
- <>
- <Icon icon={ServerCrash} size={80} />
- {t('networkError')}
- </>
- ) : (
- <Empty
- description={t('empty')}
- descriptionProps={{ fontSize: 14 }}
- icon={BookOpen}
- style={{ maxWidth: 400 }}
- />
- )}
+ {isLoading ? (
+ <Loading />
+ ) : visibleItems.length === 0 ? (
+ <Center flex={1} gap={12} padding={40}>
+ {renderEmpty()}
</Center>
- ) : viewMode === 'list' ? (
+ ) : (
<Virtuoso
+ data={visibleItems}
increaseViewportBy={typeof window !== 'undefined' ? window.innerHeight : 0}
+ itemContent={(_, item) => <Item key={item.id} {...item} />}
overscan={24}
style={{ flex: 1, marginInline: -16 }}
- totalCount={items.length}
- itemContent={(index) => {
- const item = items[index];
- return <Item key={item.id} {...item} />;
- }}
/>
- ) : (
- <div style={{ height: '100%', position: 'relative' }}>
- <div style={{ inset: 0, position: 'absolute' }}>
- <VirtuosoMasonry
- ItemContent={MasonryItemWrapper}
- columnCount={columnCount}
- context={masonryContext}
- data={items}
- style={{
- gap: '16px',
- height: '100%',
- }}
- />
- </div>
- </div>
)}
</Flexbox>
);
diff --git a/src/features/LibraryModal/AssignKnowledgeBase/MasonrySkeleton.tsx b/src/features/LibraryModal/AssignKnowledgeBase/MasonrySkeleton.tsx
deleted file mode 100644
index 1fcce11aa0e..00000000000
--- a/src/features/LibraryModal/AssignKnowledgeBase/MasonrySkeleton.tsx
+++ /dev/null
@@ -1,53 +0,0 @@
-import { createStaticStyles, Flexbox, Skeleton } from '@lobehub/ui';
-import { memo } from 'react';
-
-const styles = createStaticStyles(({ css, cssVar }) => ({
- card: css`
- padding: 12px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: ${cssVar.borderRadiusLG};
- background: ${cssVar.colorBgContainer};
- `,
- grid: css`
- display: grid;
- gap: 16px;
- padding-block: 12px;
- `,
-}));
-
-interface MasonrySkeletonProps {
- columnCount: number;
-}
-
-const MasonrySkeleton = memo<MasonrySkeletonProps>(({ columnCount }) => {
- // Generate varying heights for more natural masonry look
- const heights = [160, 180, 170, 160, 190, 170, 160, 180];
-
- // Calculate number of items based on column count (max 2 columns for modal)
- const itemCount = Math.min(columnCount * 3, 8);
-
- return (
- <div
- className={styles.grid}
- style={{
- gridTemplateColumns: `repeat(${columnCount}, 1fr)`,
- }}
- >
- {Array.from({ length: itemCount }).map((_, index) => (
- <div className={styles.card} key={index}>
- <Flexbox horizontal align={'flex-start'} gap={16} width={'100%'}>
- <Skeleton.Avatar size={48} />
- <Flexbox gap={16} style={{ height: heights[index % heights.length] }} width={'100%'}>
- <Skeleton.Text width={'80%'} />
- <Skeleton.Text rows={3} width={['100%', '90%', '70%']} />
- </Flexbox>
- </Flexbox>
- </div>
- ))}
- </div>
- );
-});
-
-MasonrySkeleton.displayName = 'MasonrySkeleton';
-
-export default MasonrySkeleton;
diff --git a/src/features/LibraryModal/AssignKnowledgeBase/filterPickerItems.test.ts b/src/features/LibraryModal/AssignKnowledgeBase/filterPickerItems.test.ts
new file mode 100644
index 00000000000..fac1f72c6cd
--- /dev/null
+++ b/src/features/LibraryModal/AssignKnowledgeBase/filterPickerItems.test.ts
@@ -0,0 +1,109 @@
+import { describe, expect, it } from 'vitest';
+
+import { type KnowledgeItem, KnowledgeType } from '@/types/knowledgeBase';
+
+import { filterPickerItems, itemsOfKind, type PickerSort } from './filterPickerItems';
+
+const file = (id: string, fileType: string, extra?: Partial<KnowledgeItem>): KnowledgeItem => ({
+ fileType,
+ id,
+ name: id,
+ type: KnowledgeType.File,
+ ...extra,
+});
+const library = (id: string, extra?: Partial<KnowledgeItem>): KnowledgeItem => ({
+ id,
+ name: id,
+ type: KnowledgeType.KnowledgeBase,
+ ...extra,
+});
+
+// The server returns every file first and libraries last, so a member with many uploads opened
+// "Add library" and saw only video files.
+const items = [
+ file('line-plan-it-r1-4k.mp4', 'video/mp4'),
+ file('podcast.mp3', 'audio/mpeg'),
+ file('handbook.pdf', 'application/pdf'),
+ file('notes.md', 'text/markdown', { enabled: true }),
+ library('Product docs'),
+ library('Support FAQ', { enabled: true }),
+];
+
+const files = [
+ file('b-old.pdf', 'application/pdf', { createdAt: '2025-06-01', updatedAt: '2026-01-01' }),
+ file('a-new.pdf', 'application/pdf', { createdAt: '2025-01-01', updatedAt: '2026-03-01' }),
+ file('c-mid.pdf', 'application/pdf', { createdAt: '2025-12-01', updatedAt: '2026-02-01' }),
+];
+
+const ids = (sort: PickerSort, list = files) =>
+ filterPickerItems({ items: list, kind: 'file', sort }).map((item) => item.id);
+
+describe('filterPickerItems', () => {
+ it('shows only libraries in the library tab', () => {
+ expect(filterPickerItems({ items, kind: 'library' }).map((item) => item.id)).toEqual([
+ 'Support FAQ',
+ 'Product docs',
+ ]);
+ });
+
+ it('shows only searchable files in the file tab, attached first', () => {
+ expect(filterPickerItems({ items, kind: 'file' }).map((item) => item.id)).toEqual([
+ 'notes.md',
+ 'handbook.pdf',
+ ]);
+ });
+
+ it('matches the keyword case-insensitively within the tab', () => {
+ expect(filterPickerItems({ items, keyword: ' PRODUCT ', kind: 'library' })).toEqual([
+ library('Product docs'),
+ ]);
+ expect(filterPickerItems({ items, keyword: 'product', kind: 'file' })).toEqual([]);
+ });
+});
+
+describe('filterPickerItems sort', () => {
+ it('lists the most recently updated first by default', () => {
+ expect(filterPickerItems({ items: files, kind: 'file' }).map((item) => item.id)).toEqual([
+ 'a-new.pdf',
+ 'c-mid.pdf',
+ 'b-old.pdf',
+ ]);
+ });
+
+ it('lists the most recently created first', () => {
+ expect(ids('createdAt')).toEqual(['c-mid.pdf', 'b-old.pdf', 'a-new.pdf']);
+ });
+
+ it('lists by name A–Z and Z–A', () => {
+ expect(ids('name')).toEqual(['a-new.pdf', 'b-old.pdf', 'c-mid.pdf']);
+ expect(ids('nameDesc')).toEqual(['c-mid.pdf', 'b-old.pdf', 'a-new.pdf']);
+ });
+
+ // Reviewers read "A–Z" by first letter: 产品 (chanpin) belongs between API and release.
+ it('files Chinese names under their pinyin initial', () => {
+ const mixed = [
+ file('release-notes.md', 'text/markdown'),
+ file('产品需求文档.pdf', 'application/pdf'),
+ file('API 接口说明.pdf', 'application/pdf'),
+ ];
+ expect(ids('name', mixed)).toEqual([
+ 'API 接口说明.pdf',
+ '产品需求文档.pdf',
+ 'release-notes.md',
+ ]);
+ });
+});
+
+describe('itemsOfKind', () => {
+ it('keeps an already attached media file so it can still be removed', () => {
+ const attachedVideo = file('demo.mp4', 'video/mp4', { enabled: true });
+ expect(itemsOfKind([...items, attachedVideo], 'file').map((item) => item.id)).toContain(
+ 'demo.mp4',
+ );
+ });
+
+ it('counts what each tab can offer', () => {
+ expect(itemsOfKind(items, 'library')).toHaveLength(2);
+ expect(itemsOfKind(items, 'file')).toHaveLength(2);
+ });
+});
diff --git a/src/features/LibraryModal/AssignKnowledgeBase/filterPickerItems.ts b/src/features/LibraryModal/AssignKnowledgeBase/filterPickerItems.ts
new file mode 100644
index 00000000000..25ef4567c4b
--- /dev/null
+++ b/src/features/LibraryModal/AssignKnowledgeBase/filterPickerItems.ts
@@ -0,0 +1,89 @@
+import { pinyin } from 'pinyin-pro';
+
+import { type KnowledgeItem, KnowledgeType } from '@/types/knowledgeBase';
+
+/** Which half of the picker is open: libraries or standalone files. */
+export type PickerKind = 'file' | 'library';
+
+/** How a tab orders its rows: by name either way, or newest change / creation first. */
+export type PickerSort = 'createdAt' | 'name' | 'nameDesc' | 'updatedAt';
+
+/**
+ * Files an agent cannot read when it answers: media has no text to chunk and search. The server
+ * already drops images; audio and video still come through and used to bury the libraries.
+ */
+const UNSEARCHABLE_FILE_PREFIXES = ['image/', 'video/', 'audio/'];
+
+export const isSearchableFile = (item: KnowledgeItem) =>
+ !UNSEARCHABLE_FILE_PREFIXES.some((prefix) => item.fileType?.startsWith(prefix));
+
+const kindType = (kind: PickerKind) =>
+ kind === 'library' ? KnowledgeType.KnowledgeBase : KnowledgeType.File;
+
+/**
+ * Rows of one kind that the agent could actually search. A media file attached before this filter
+ * existed stays listed, so it can still be removed from here.
+ */
+export const itemsOfKind = (items: KnowledgeItem[], kind: PickerKind) =>
+ items.filter(
+ (item) =>
+ item.type === kindType(kind) &&
+ (item.type !== KnowledgeType.File || item.enabled || isSearchableFile(item)),
+ );
+
+const timeOf = (value?: Date | string) => (value ? new Date(value).getTime() : 0);
+
+/**
+ * Names compare by their first letters, so a Chinese name files under its pinyin (产品 → C)
+ * between Latin names instead of collecting before or after all of them.
+ */
+const nameKey = (name: string) =>
+ /\p{Script=Han}/u.test(name)
+ ? pinyin(name, { nonZh: 'consecutive', toneType: 'none', type: 'array' }).join('')
+ : name;
+
+const compareNames = (a: KnowledgeItem, b: KnowledgeItem) =>
+ nameKey(a.name).localeCompare(nameKey(b.name), 'en', { numeric: true, sensitivity: 'base' });
+
+const compareBy =
+ (sort: PickerSort) =>
+ (a: KnowledgeItem, b: KnowledgeItem): number => {
+ switch (sort) {
+ case 'name': {
+ return compareNames(a, b);
+ }
+ case 'nameDesc': {
+ return compareNames(b, a);
+ }
+ case 'createdAt': {
+ return timeOf(b.createdAt) - timeOf(a.createdAt);
+ }
+ default: {
+ return timeOf(b.updatedAt) - timeOf(a.updatedAt);
+ }
+ }
+ };
+
+/**
+ * What the picker shows for a tab and a search: only that kind, matched by name, ordered by the
+ * chosen sort, with the ones already attached first so the member sees what the agent has before
+ * what it could have.
+ */
+export const filterPickerItems = ({
+ items,
+ keyword,
+ kind,
+ sort = 'updatedAt',
+}: {
+ items: KnowledgeItem[];
+ keyword?: string;
+ kind: PickerKind;
+ sort?: PickerSort;
+}): KnowledgeItem[] => {
+ const query = keyword?.trim().toLowerCase();
+ const matched = itemsOfKind(items, kind)
+ .filter((item) => !query || item.name.toLowerCase().includes(query))
+ .sort(compareBy(sort));
+
+ return [...matched.filter((item) => item.enabled), ...matched.filter((item) => !item.enabled)];
+};
diff --git a/src/features/LibraryModal/AssignKnowledgeBase/index.tsx b/src/features/LibraryModal/AssignKnowledgeBase/index.tsx
index ea41fa2c94b..1f0463890d1 100644
--- a/src/features/LibraryModal/AssignKnowledgeBase/index.tsx
+++ b/src/features/LibraryModal/AssignKnowledgeBase/index.tsx
@@ -4,9 +4,12 @@ import { memo } from 'react';
import { useServerConfigStore } from '@/store/serverConfig';
+import { type PickerKind } from './filterPickerItems';
import List from './List';
-const Content = memo(() => {
+export type { PickerKind } from './filterPickerItems';
+
+const Content = memo<{ kind: PickerKind }>(({ kind }) => {
const mobile = useServerConfigStore((s) => s.isMobile);
return (
@@ -15,16 +18,23 @@ const Content = memo(() => {
style={{ maxHeight: mobile ? '-webkit-fill-available' : 'inherit' }}
width={'100%'}
>
- <List />
+ <List defaultKind={kind} />
</Flexbox>
);
});
-export const openAttachKnowledgeModal = (): ModalInstance =>
+interface AttachKnowledgeModalOptions {
+ /** The tab to open on; "Add file" lands on files, everything else on libraries. */
+ kind?: PickerKind;
+}
+
+export const openAttachKnowledgeModal = ({
+ kind = 'library',
+}: AttachKnowledgeModalOptions = {}): ModalInstance =>
createModal({
- content: <Content />,
+ content: <Content kind={kind} />,
footer: false,
styles: { content: { overflow: 'hidden' } },
- title: t('knowledgeBase.library.title', { ns: 'chat' }),
+ title: t('knowledgeBase.picker.title', { ns: 'chat' }),
width: 600,
});
diff --git a/src/features/LibraryModal/AssignKnowledgeBase/useViewTransition.test.ts b/src/features/LibraryModal/AssignKnowledgeBase/useViewTransition.test.ts
deleted file mode 100644
index 5f48ffdf5e1..00000000000
--- a/src/features/LibraryModal/AssignKnowledgeBase/useViewTransition.test.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * @vitest-environment happy-dom
- */
-import { act, renderHook } from '@testing-library/react';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { useViewTransition } from './useViewTransition';
-
-describe('useViewTransition', () => {
- beforeEach(() => {
- vi.useFakeTimers();
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- // Regression: completion used to wait for list rows, so after a failed first
- // fetch (no rows ever) a view switch left a permanent skeleton over the
- // network error.
- it('settles a view switch without waiting for list rows', async () => {
- const { result, rerender } = renderHook(({ viewMode }) => useViewTransition(viewMode), {
- initialProps: { viewMode: 'list' },
- });
-
- act(() => result.current.startTransition());
- rerender({ viewMode: 'masonry' });
- expect(result.current.isTransitioning).toBe(true);
-
- await act(async () => {
- await vi.advanceTimersByTimeAsync(500);
- });
-
- expect(result.current.isTransitioning).toBe(false);
- });
-});
diff --git a/src/features/LibraryModal/AssignKnowledgeBase/useViewTransition.ts b/src/features/LibraryModal/AssignKnowledgeBase/useViewTransition.ts
deleted file mode 100644
index 8ea26a64a04..00000000000
--- a/src/features/LibraryModal/AssignKnowledgeBase/useViewTransition.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { useCallback, useEffect, useState } from 'react';
-
-/** How long the skeleton stays up after a view-mode switch (ms). */
-export const VIEW_TRANSITION_MS = 100;
-
-/**
- * Brief skeleton between list / masonry view switches.
- *
- * Completion depends only on time, never on the list having rows: a surface
- * whose first fetch failed has none, and gating on them would leave the
- * skeleton up instead of the network error until the modal remounts. A list
- * that is still loading keeps its own skeleton through `isLoading`.
- */
-export const useViewTransition = (viewMode: string) => {
- const [isTransitioning, setIsTransitioning] = useState(false);
-
- useEffect(() => {
- if (!isTransitioning) return;
- let timer: ReturnType<typeof setTimeout> | undefined;
- const frame = requestAnimationFrame(() => {
- timer = setTimeout(() => setIsTransitioning(false), VIEW_TRANSITION_MS);
- });
- return () => {
- cancelAnimationFrame(frame);
- if (timer) clearTimeout(timer);
- };
- }, [isTransitioning, viewMode]);
-
- const startTransition = useCallback(() => setIsTransitioning(true), []);
-
- return { isTransitioning, startTransition };
-};
diff --git a/src/features/LibraryModal/CreateNew/CreateForm.tsx b/src/features/LibraryModal/CreateNew/CreateForm.tsx
index 88ab5cbbee3..56a3c73436b 100644
--- a/src/features/LibraryModal/CreateNew/CreateForm.tsx
+++ b/src/features/LibraryModal/CreateNew/CreateForm.tsx
@@ -9,105 +9,114 @@ import { useResourceManagerStore } from '@/features/ResourceManager/store';
import { buildLibraryPath } from '@/features/ResourceManager/utils/resourcePath';
import { useKnowledgeBaseStore } from '@/store/library';
+import { resolveNewLibraryVisibility } from './resolveNewLibraryVisibility';
+
interface CreateFormProps {
id?: string;
initialValues?: { cover?: string; description?: string; name?: string };
onClose?: () => void;
onSuccess?: (id: string) => void;
+ /**
+ * Visibility for a new library when the caller knows its scope, such as the knowledge picker's
+ * Private tab. Without it, creation follows the Resources sidebar mode.
+ */
+ visibility?: 'private' | 'public';
}
-const CreateForm = memo<CreateFormProps>(({ id, initialValues, onClose, onSuccess }) => {
- const { t } = useTranslation('knowledgeBase');
- const [loading, setLoading] = useState(false);
- const [name, setName] = useState(initialValues?.name || '');
- const [description, setDescription] = useState(initialValues?.description || '');
- // A new library has no id yet; a per-form seed keeps the previewed default
- // cover identical to the one it is created with.
- const [draftSeed] = useState(() => id ?? `draft-${Math.random().toString(36).slice(2)}`);
- const [cover, setCover] = useState<string | null>(initialValues?.cover ?? null);
- const updateKnowledgeBaseCover = useKnowledgeBaseStore((s) => s.updateKnowledgeBaseCover);
- const createNewKnowledgeBase = useKnowledgeBaseStore((s) => s.createNewKnowledgeBase);
- const updateKnowledgeBase = useKnowledgeBaseStore((s) => s.updateKnowledgeBase);
- // Derive KB visibility from the current sidebar mode: "private space" →
- // private KB, "workspace space" → public KB. Personal-mode users have the
- // toggle hidden and `listVisibility` stays at its default 'workspace', so
- // personal-mode create still resolves to 'public' — matching the pre-column
- // default and giving `buildWorkspaceWhere` nothing to filter on.
- const listVisibility = useResourceManagerStore((s) => s.listVisibility);
- const activeWorkspaceSlug = useActiveWorkspaceSlug();
-
- const isEditMode = !!id;
+const CreateForm = memo<CreateFormProps>(
+ ({ id, initialValues, onClose, onSuccess, visibility }) => {
+ const { t } = useTranslation('knowledgeBase');
+ const [loading, setLoading] = useState(false);
+ const [name, setName] = useState(initialValues?.name || '');
+ const [description, setDescription] = useState(initialValues?.description || '');
+ // A new library has no id yet; a per-form seed keeps the previewed default
+ // cover identical to the one it is created with.
+ const [draftSeed] = useState(() => id ?? `draft-${Math.random().toString(36).slice(2)}`);
+ const [cover, setCover] = useState<string | null>(initialValues?.cover ?? null);
+ const updateKnowledgeBaseCover = useKnowledgeBaseStore((s) => s.updateKnowledgeBaseCover);
+ const createNewKnowledgeBase = useKnowledgeBaseStore((s) => s.createNewKnowledgeBase);
+ const updateKnowledgeBase = useKnowledgeBaseStore((s) => s.updateKnowledgeBase);
+ // Derive KB visibility from the current sidebar mode: "private space" →
+ // private KB, "workspace space" → public KB. Personal-mode users have the
+ // toggle hidden and `listVisibility` stays at its default 'workspace', so
+ // personal-mode create still resolves to 'public' — matching the pre-column
+ // default and giving `buildWorkspaceWhere` nothing to filter on.
+ const listVisibility = useResourceManagerStore((s) => s.listVisibility);
+ const activeWorkspaceSlug = useActiveWorkspaceSlug();
- const handleSubmit = async () => {
- if (!name.trim()) return;
+ const isEditMode = !!id;
- setLoading(true);
- const values = {
- description: description.trim(),
- name: name.trim(),
- };
+ const handleSubmit = async () => {
+ if (!name.trim()) return;
- 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);
- if (cover !== (initialValues?.cover ?? null)) await updateKnowledgeBaseCover(id, cover);
- setLoading(false);
- onClose?.();
- } else {
- const newId = await createNewKnowledgeBase({
- ...values,
- cover: cover ?? presetCoverValue(defaultCoverPreset(draftSeed).id),
- visibility: listVisibility === 'private' ? ('private' as const) : ('public' as const),
- });
- setLoading(false);
+ setLoading(true);
+ const values = {
+ description: description.trim(),
+ name: name.trim(),
+ };
- if (onSuccess) {
- onSuccess(newId);
+ 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);
+ if (cover !== (initialValues?.cover ?? null)) await updateKnowledgeBaseCover(id, cover);
+ setLoading(false);
onClose?.();
} else {
- // Workspace routes are mounted under `/:workspaceSlug`, so the hard
- // navigation must carry the active slug or it lands in the personal
- // scope where the new library does not resolve.
- window.location.href = buildLibraryPath(newId, activeWorkspaceSlug);
+ const newId = await createNewKnowledgeBase({
+ ...values,
+ cover: cover ?? presetCoverValue(defaultCoverPreset(draftSeed).id),
+ visibility: resolveNewLibraryVisibility(visibility, listVisibility),
+ });
+ setLoading(false);
+
+ if (onSuccess) {
+ onSuccess(newId);
+ onClose?.();
+ } else {
+ // Workspace routes are mounted under `/:workspaceSlug`, so the hard
+ // navigation must carry the active slug or it lands in the personal
+ // scope where the new library does not resolve.
+ window.location.href = buildLibraryPath(newId, activeWorkspaceSlug);
+ }
}
+ } catch (e) {
+ console.error(e);
+ setLoading(false);
}
- } catch (e) {
- console.error(e);
- setLoading(false);
- }
- };
+ };
- return (
- <Flexbox gap={16}>
- <Input
- autoFocus
- placeholder={t('createNew.name.placeholder')}
- value={name}
- onChange={(e) => setName(e.target.value)}
- />
- <Flexbox gap={8}>
- <label style={{ fontSize: 14 }}>{t('createNew.description.label')}</label>
- <TextArea
- placeholder={t('createNew.description.placeholder')}
- style={{ minHeight: 120 }}
- value={description}
- onChange={(e) => setDescription(e.target.value)}
+ return (
+ <Flexbox gap={16}>
+ <Input
+ autoFocus
+ placeholder={t('createNew.name.placeholder')}
+ value={name}
+ onChange={(e) => setName(e.target.value)}
/>
+ <Flexbox gap={8}>
+ <label style={{ fontSize: 14 }}>{t('createNew.description.label')}</label>
+ <TextArea
+ placeholder={t('createNew.description.placeholder')}
+ style={{ minHeight: 120 }}
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ />
+ </Flexbox>
+ <Flexbox gap={8}>
+ <label style={{ fontSize: 14 }}>{t('createNew.cover.label')}</label>
+ <CoverPicker seed={draftSeed} value={cover} onChange={setCover} />
+ </Flexbox>
+ <Button block loading={loading} type={'primary'} onClick={handleSubmit}>
+ {isEditMode ? t('createNew.edit.confirm') : t('createNew.confirm')}
+ </Button>
</Flexbox>
- <Flexbox gap={8}>
- <label style={{ fontSize: 14 }}>{t('createNew.cover.label')}</label>
- <CoverPicker seed={draftSeed} value={cover} onChange={setCover} />
- </Flexbox>
- <Button block loading={loading} type={'primary'} onClick={handleSubmit}>
- {isEditMode ? t('createNew.edit.confirm') : t('createNew.confirm')}
- </Button>
- </Flexbox>
- );
-});
+ );
+ },
+);
export default CreateForm;
diff --git a/src/features/LibraryModal/CreateNew/index.tsx b/src/features/LibraryModal/CreateNew/index.tsx
index d65cdf98595..95080dc0abf 100644
--- a/src/features/LibraryModal/CreateNew/index.tsx
+++ b/src/features/LibraryModal/CreateNew/index.tsx
@@ -8,12 +8,21 @@ interface ModalContentProps {
id?: string;
initialValues?: { cover?: string; description?: string; name?: string };
onSuccess?: (id: string) => void;
+ visibility?: 'private' | 'public';
}
-const ModalContent = memo<ModalContentProps>(({ id, initialValues, onSuccess }) => {
+const ModalContent = memo<ModalContentProps>(({ id, initialValues, onSuccess, visibility }) => {
const { close } = useModalContext();
- return <CreateForm id={id} initialValues={initialValues} onClose={close} onSuccess={onSuccess} />;
+ return (
+ <CreateForm
+ id={id}
+ initialValues={initialValues}
+ visibility={visibility}
+ onClose={close}
+ onSuccess={onSuccess}
+ />
+ );
});
ModalContent.displayName = 'KnowledgeBaseCreateModalContent';
@@ -22,6 +31,8 @@ interface OpenParams {
id?: string;
initialValues?: { cover?: string; description?: string; name?: string };
onSuccess?: (id: string) => void;
+ /** Scope for a new library; defaults to the Resources sidebar mode. */
+ visibility?: 'private' | 'public';
}
export const useCreateNewModal = () => {
@@ -37,6 +48,7 @@ export const useCreateNewModal = () => {
<ModalContent
id={props?.id}
initialValues={props?.initialValues}
+ visibility={props?.visibility}
onSuccess={props?.onSuccess}
/>
</Suspense>
diff --git a/src/features/LibraryModal/CreateNew/resolveNewLibraryVisibility.test.ts b/src/features/LibraryModal/CreateNew/resolveNewLibraryVisibility.test.ts
new file mode 100644
index 00000000000..d5bb026c9b3
--- /dev/null
+++ b/src/features/LibraryModal/CreateNew/resolveNewLibraryVisibility.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveNewLibraryVisibility } from './resolveNewLibraryVisibility';
+
+describe('resolveNewLibraryVisibility', () => {
+ // The picker's Private tab creates a private library even though the Resources sidebar,
+ // which the member is not looking at, still sits on its default workspace mode.
+ it('keeps the scope the caller asked for', () => {
+ expect(resolveNewLibraryVisibility('private', 'workspace')).toBe('private');
+ expect(resolveNewLibraryVisibility('public', 'private')).toBe('public');
+ });
+
+ it('falls back to the Resources sidebar mode', () => {
+ expect(resolveNewLibraryVisibility(undefined, 'private')).toBe('private');
+ expect(resolveNewLibraryVisibility(undefined, 'workspace')).toBe('public');
+ });
+});
diff --git a/src/features/LibraryModal/CreateNew/resolveNewLibraryVisibility.ts b/src/features/LibraryModal/CreateNew/resolveNewLibraryVisibility.ts
new file mode 100644
index 00000000000..4460697bcbe
--- /dev/null
+++ b/src/features/LibraryModal/CreateNew/resolveNewLibraryVisibility.ts
@@ -0,0 +1,9 @@
+/**
+ * Visibility of a library about to be created. A caller that knows its scope (the knowledge
+ * picker's Private / Workspace tab) wins; otherwise the Resources sidebar mode decides, where
+ * "private space" means private and anything else means workspace.
+ */
+export const resolveNewLibraryVisibility = (
+ requested: 'private' | 'public' | undefined,
+ listVisibility: string | undefined,
+): 'private' | 'public' => requested ?? (listVisibility === 'private' ? 'private' : 'public');
diff --git a/src/routes/(main)/agent/profile/features/KnowledgeEditor/index.tsx b/src/routes/(main)/agent/profile/features/KnowledgeEditor/index.tsx
index 5f09754e603..bd147c85ce6 100644
--- a/src/routes/(main)/agent/profile/features/KnowledgeEditor/index.tsx
+++ b/src/routes/(main)/agent/profile/features/KnowledgeEditor/index.tsx
@@ -8,7 +8,7 @@ import { useTranslation } from 'react-i18next';
import FileIcon from '@/components/FileIcon';
import RepoIcon from '@/components/LibIcon';
-import { openAttachKnowledgeModal } from '@/features/LibraryModal';
+import { openAttachKnowledgeModal, type PickerKind } from '@/features/LibraryModal';
import ItemRow from '@/features/ProfileEditor/ItemRow';
import ToolListGroup from '@/features/ProfileEditor/ToolListGroup';
import { usePermission } from '@/hooks/usePermission';
@@ -67,13 +67,13 @@ const KnowledgeEditor = memo(() => {
s.removeFileFromAgent,
]);
- const addControl = (label: string) => (
+ const addControl = (label: string, kind: PickerKind) => (
<Button
disabled={!canEdit}
icon={<Icon icon={PlusIcon} />}
size={'small'}
type={'text'}
- onClick={() => openAttachKnowledgeModal()}
+ onClick={() => openAttachKnowledgeModal({ kind })}
>
{label}
</Button>
@@ -107,7 +107,7 @@ const KnowledgeEditor = memo(() => {
<Flexbox gap={16}>
<ToolListGroup
- addControl={addControl(t('settingAgent.knowledgePage.addLibrary'))}
+ addControl={addControl(t('settingAgent.knowledgePage.addLibrary'), 'library')}
desc={t('settingAgent.knowledgePage.libraries.desc')}
emptyText={t('settingAgent.knowledgePage.libraries.empty')}
title={t('settingAgent.knowledgePage.libraries.title')}
@@ -127,7 +127,7 @@ const KnowledgeEditor = memo(() => {
))}
/>
<ToolListGroup
- addControl={addControl(t('settingAgent.knowledgePage.addFile'))}
+ addControl={addControl(t('settingAgent.knowledgePage.addFile'), 'file')}
desc={t('settingAgent.knowledgePage.files.desc')}
emptyText={t('settingAgent.knowledgePage.files.empty')}
title={t('settingAgent.knowledgePage.files.title')}