Skip to content

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

🐛 fix(chat-input): keep the library picker reachable when nothing is attached (#18144)

Arvin Xuf0036bf8f543
diff --git a/apps/server/src/routers/lambda/__tests__/agent.test.ts b/apps/server/src/routers/lambda/__tests__/agent.test.ts
index 11aaf450fb9..51a05da2fd8 100644
--- a/apps/server/src/routers/lambda/__tests__/agent.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/agent.test.ts
@@ -346,6 +346,41 @@ describe('agentRouter', () => {
},
]);
});
+
+ // Regression: `visibility` is workspace-scoped — buildWorkspaceWhere ignores
+ // the column in personal mode while it still defaults to 'public', so
+ // forcing the public scope there filtered personal rows by a value that
+ // carries no meaning.
+ it('sends no visibility scope in personal mode, even for a public agent', async () => {
+ agentModelMock.getAgentVisibility.mockResolvedValue('public');
+ fileModelMock.query.mockResolvedValue([]);
+ knowledgeBaseModelMock.query.mockResolvedValue([]);
+ agentModelMock.getAgentAssignedKnowledge.mockResolvedValue({ files: [], knowledgeBases: [] });
+
+ const caller = agentRouter.createCaller(mockCtx);
+ await caller.getKnowledgeBasesAndFiles({ agentId: 'agent1', visibility: 'private' });
+
+ expect(fileModelMock.query).toHaveBeenCalledWith(
+ expect.objectContaining({ visibility: undefined }),
+ );
+ expect(knowledgeBaseModelMock.query).toHaveBeenCalledWith(
+ expect.objectContaining({ visibility: undefined }),
+ );
+ });
+
+ it('forces the workspace scope for a public agent inside a workspace', async () => {
+ agentModelMock.getAgentVisibility.mockResolvedValue('public');
+ fileModelMock.query.mockResolvedValue([]);
+ knowledgeBaseModelMock.query.mockResolvedValue([]);
+ agentModelMock.getAgentAssignedKnowledge.mockResolvedValue({ files: [], knowledgeBases: [] });
+
+ const caller = agentRouter.createCaller({ ...mockCtx, workspaceId: 'ws-1' });
+ await caller.getKnowledgeBasesAndFiles({ agentId: 'agent1', visibility: 'private' });
+
+ expect(fileModelMock.query).toHaveBeenCalledWith(
+ expect.objectContaining({ visibility: 'public' }),
+ );
+ });
});
describe('createAgentFiles', () => {
diff --git a/apps/server/src/routers/lambda/agent.ts b/apps/server/src/routers/lambda/agent.ts
index 6c08fa53d64..0e56719e197 100644
--- a/apps/server/src/routers/lambda/agent.ts
+++ b/apps/server/src/routers/lambda/agent.ts
@@ -626,8 +626,17 @@ export const agentRouter = router({
// in the model layer, and (b) hard-force `visibility='public'` when
// the agent is public — the client tab is a UX aid, not a gate.
const agentVisibility = await ctx.agentModel.getAgentVisibility(input.agentId);
- const effectiveVisibility =
- agentVisibility === 'public' ? ('public' as const) : input.visibility;
+
+ // `visibility` is workspace-scoped. In personal mode buildWorkspaceWhere
+ // ignores the column entirely (every row is implicitly private to its
+ // owner) while the column still defaults to 'public', so forcing a scope
+ // here would filter personal rows by a value that carries no meaning.
+ // Only workspace agents get a visibility scope.
+ const effectiveVisibility = ctx.workspaceId
+ ? agentVisibility === 'public'
+ ? ('public' as const)
+ : input.visibility
+ : undefined;
const knowledgeBases = await ctx.knowledgeBaseModel.query({
callerAgentVisibility: agentVisibility,
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index e4ba1568b8f..a55876eafaf 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -776,6 +776,7 @@
"knowledgeBase.library.action.detail": "Details",
"knowledgeBase.library.action.remove": "Remove",
"knowledgeBase.library.title": "Files / Libraries",
+ "knowledgeBase.related.browse": "Choose Files / Libraries",
"knowledgeBase.related.empty": "No related files or libraries",
"knowledgeBase.relativeFilesOrLibraries": "Related Files/Libraries",
"knowledgeBase.title": "Library",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index a7fc7855f93..377f3c135bd 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -776,6 +776,7 @@
"knowledgeBase.library.action.detail": "详情",
"knowledgeBase.library.action.remove": "移除",
"knowledgeBase.library.title": "文件 / 资源库",
+ "knowledgeBase.related.browse": "选择文件 / 资源库",
"knowledgeBase.related.empty": "暂无关联文件或资源库",
"knowledgeBase.relativeFilesOrLibraries": "关联文件 / 资源库",
"knowledgeBase.title": "资源库",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 190ee97cb56..51aa469c72c 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -613,6 +613,7 @@ export default {
'knowledgeBase.library.title': 'Files / Libraries',
'knowledgeBase.files': 'Files',
'knowledgeBase.libraries': 'Libraries',
+ 'knowledgeBase.related.browse': 'Choose Files / Libraries',
'knowledgeBase.related.empty': 'No related files or libraries',
'knowledgeBase.relativeFilesOrLibraries': 'Related Files/Libraries',
'knowledgeBase.title': 'Library',
diff --git a/src/features/ChatInput/ActionBar/Knowledge/useControls.test.ts b/src/features/ChatInput/ActionBar/Knowledge/useControls.test.ts
new file mode 100644
index 00000000000..6dc04291913
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Knowledge/useControls.test.ts
@@ -0,0 +1,65 @@
+import { fireEvent, render, renderHook, screen } from '@testing-library/react';
+import type { ReactElement } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useControls } from './useControls';
+
+const mockFiles = vi.hoisted(() => ({
+ current: [] as { enabled: boolean; id: string; name: string; type: string }[],
+}));
+const mockKnowledgeBases = vi.hoisted(() => ({
+ current: [] as { enabled: boolean; id: string; name: string }[],
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (state: unknown) => unknown) =>
+ selector({ toggleFile: vi.fn(), toggleKnowledgeBase: vi.fn() }),
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: {
+ getAgentFilesById: () => () => mockFiles.current,
+ getAgentKnowledgeBasesById: () => () => mockKnowledgeBases.current,
+ },
+}));
+
+vi.mock('../../hooks/useAgentId', () => ({ useAgentId: () => 'agent-1' }));
+
+describe('useControls', () => {
+ beforeEach(() => {
+ mockFiles.current = [];
+ mockKnowledgeBases.current = [];
+ });
+
+ // Regression: the footer was only built once something was already attached, so a
+ // fresh agent showed "No related files or libraries" with no way in — the first
+ // library or file could never be attached from the composer.
+ it('keeps the picker reachable when nothing is attached yet', () => {
+ const openAttachKnowledgeModal = vi.fn();
+
+ const { result } = renderHook(() => useControls({ openAttachKnowledgeModal }));
+
+ expect(result.current.items).toHaveLength(0);
+ expect(result.current.footer).not.toBeNull();
+
+ render(result.current.footer as ReactElement);
+ fireEvent.click(screen.getByRole('button', { name: 'knowledgeBase.related.browse' }));
+
+ expect(openAttachKnowledgeModal).toHaveBeenCalledTimes(1);
+ });
+
+ it('switches the footer to "view more" once libraries or files are attached', () => {
+ mockKnowledgeBases.current = [{ enabled: true, id: 'kb-1', name: 'Handbook' }];
+ const openAttachKnowledgeModal = vi.fn();
+
+ const { result } = renderHook(() => useControls({ openAttachKnowledgeModal }));
+
+ expect(result.current.items).toHaveLength(1);
+ expect(result.current.enabledCount).toBe(1);
+
+ render(result.current.footer as ReactElement);
+ fireEvent.click(screen.getByRole('button', { name: 'knowledgeBase.viewMore' }));
+
+ expect(openAttachKnowledgeModal).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/features/ChatInput/ActionBar/Knowledge/useControls.tsx b/src/features/ChatInput/ActionBar/Knowledge/useControls.tsx
index 57076165a3b..884fb44271a 100644
--- a/src/features/ChatInput/ActionBar/Knowledge/useControls.tsx
+++ b/src/features/ChatInput/ActionBar/Knowledge/useControls.tsx
@@ -127,20 +127,24 @@ export const useControls = ({
...fileItems,
];
- const footer =
- relatedGroups.length > 0 ? (
- <button
- className={cx(styles.viewMore)}
- type="button"
- onClick={(event) => {
- event.stopPropagation();
- openAttachKnowledgeModal();
- }}
- >
- <Icon color={cssVar.colorTextSecondary} icon={LibraryBig} size={14} />
- <span className={cx(styles.viewMoreLabel)}>{t('knowledgeBase.viewMore')}</span>
- </button>
- ) : null;
+ // The footer is the only entry into the full library / file picker, so it stays
+ // rendered when nothing is attached yet — otherwise the submenu shows "no related
+ // files or libraries" with no way to attach the first one.
+ const footer = (
+ <button
+ className={cx(styles.viewMore)}
+ type="button"
+ onClick={(event) => {
+ event.stopPropagation();
+ openAttachKnowledgeModal();
+ }}
+ >
+ <Icon color={cssVar.colorTextSecondary} icon={LibraryBig} size={14} />
+ <span className={cx(styles.viewMoreLabel)}>
+ {relatedGroups.length > 0 ? t('knowledgeBase.viewMore') : t('knowledgeBase.related.browse')}
+ </span>
+ </button>
+ );
return { enabledCount, footer, items: relatedGroups } satisfies KnowledgeControls;
};
diff --git a/src/features/ChatInput/ActionBar/Upload/index.tsx b/src/features/ChatInput/ActionBar/Upload/index.tsx
index 70def7093ff..1c91491c6f5 100644
--- a/src/features/ChatInput/ActionBar/Upload/index.tsx
+++ b/src/features/ChatInput/ActionBar/Upload/index.tsx
@@ -1,22 +1,15 @@
import { validateVideoFileSize } from '@lobechat/utils/client';
-import { type ItemType } from '@lobehub/ui';
import { Icon, Tooltip } from '@lobehub/ui';
import { toast } from '@lobehub/ui/base-ui';
import { Upload } from 'antd';
import { css, cx } from 'antd-style';
-import isEqual from 'fast-deep-equal';
-import { ArrowRight, FileUp, FolderUp, ImageUp, LibraryBig, Paperclip } from 'lucide-react';
+import { FileUp, FolderUp, ImageUp, Paperclip } from 'lucide-react';
import { memo, Suspense, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import FileIcon from '@/components/FileIcon';
-import RepoIcon from '@/components/LibIcon';
import TipGuide from '@/components/TipGuide';
-import { openAttachKnowledgeModal } from '@/features/LibraryModal';
import { useMediaUploadAbility } from '@/hooks/useMediaUploadAbility';
import { usePermission } from '@/hooks/usePermission';
-import { useAgentStore } from '@/store/agent';
-import { agentByIdSelectors } from '@/store/agent/selectors';
import { useFileStore } from '@/store/file';
import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
import { useUserStore } from '@/store/user';
@@ -27,7 +20,7 @@ import { useEffectiveModel } from '../../hooks/useEffectiveModel';
import { useChatInputStore } from '../../store';
import { type ActionDropdownMenuItems } from '../components/ActionDropdown';
import { ChatInputAction } from '../components/ChatInputAction';
-import CheckboxItem from '../components/CheckboxWithLoading';
+import { MENU_ICON_SIZE, useKnowledgeMenuItems } from './useKnowledgeMenuItems';
const hotArea = css`
&::before {
@@ -38,11 +31,6 @@ const hotArea = css`
}
`;
-// Keep every row's leading icon the same width. The menu's icon slot sizes to its
-// content, so a larger file-type icon next to a smaller line icon would widen that
-// slot and push its label out of alignment with the upload / "view more" rows.
-const MENU_ICON_SIZE = 20;
-
const FileUpload = memo(() => {
const { t } = useTranslation('chat');
@@ -69,16 +57,7 @@ const FileUpload = memo(() => {
const [dropdownOpen, setDropdownOpen] = useState(false);
const [updating, setUpdating] = useState(false);
- const files = useAgentStore((s) => agentByIdSelectors.getAgentFilesById(agentId)(s), isEqual);
- const knowledgeBases = useAgentStore(
- (s) => agentByIdSelectors.getAgentKnowledgeBasesById(agentId)(s),
- isEqual,
- );
-
- const [toggleFile, toggleKnowledgeBase] = useAgentStore((s) => [
- s.toggleFile,
- s.toggleKnowledgeBase,
- ]);
+ const knowledgeItems = useKnowledgeMenuItems({ onUpdatingChange: setUpdating });
// Viewer doesn't have `file:upload` permission — backend would 403.
// Render the disabled paperclip with a tooltip so the entry stays visible
@@ -209,81 +188,7 @@ const FileUpload = memo(() => {
},
];
- const knowledgeItems: ItemType[] = [];
-
- // Only add knowledge base items if there are files or knowledge bases
- if (files.length > 0 || knowledgeBases.length > 0) {
- knowledgeItems.push({
- children: [
- // first the files
- ...files.map((item) => ({
- icon: <FileIcon fileName={item.name} fileType={item.type} size={MENU_ICON_SIZE} />,
- key: item.id,
- label: (
- <CheckboxItem
- checked={item.enabled}
- id={item.id}
- label={item.name}
- onUpdate={async (id, enabled) => {
- setUpdating(true);
- await toggleFile(id, enabled);
- setUpdating(false);
- }}
- />
- ),
- })),
-
- // then the knowledge bases
- ...knowledgeBases.map((item) => ({
- icon: <RepoIcon size={MENU_ICON_SIZE} />,
- key: item.id,
- label: (
- <CheckboxItem
- checked={item.enabled}
- id={item.id}
- label={item.name}
- onUpdate={async (id, enabled) => {
- setUpdating(true);
- await toggleKnowledgeBase(id, enabled);
- setUpdating(false);
- }}
- />
- ),
- })),
- ],
- key: 'relativeFilesOrLibraries',
- label: t('knowledgeBase.relativeFilesOrLibraries'),
- type: 'group',
- });
- }
-
- if (knowledgeItems.length > 0) {
- knowledgeItems.push(
- {
- type: 'divider',
- },
- {
- extra: <Icon icon={ArrowRight} />,
- icon: <Icon icon={LibraryBig} size={MENU_ICON_SIZE} />,
- key: 'knowledge-base-store',
- label: t('knowledgeBase.viewMore'),
- onClick: () => {
- openAttachKnowledgeModal();
- },
- },
- );
- } else {
- knowledgeItems.push({
- disabled: true,
- key: 'knowledge-empty',
- label: t('knowledgeBase.related.empty'),
- });
- }
-
- const items: ActionDropdownMenuItems = [
- ...uploadItems,
- ...(knowledgeItems.length > 0 ? knowledgeItems : []),
- ];
+ const items: ActionDropdownMenuItems = [...uploadItems, ...knowledgeItems];
const content = (
<ChatInputAction
diff --git a/src/features/ChatInput/ActionBar/Upload/useKnowledgeMenuItems.test.ts b/src/features/ChatInput/ActionBar/Upload/useKnowledgeMenuItems.test.ts
new file mode 100644
index 00000000000..29b746ea1a3
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Upload/useKnowledgeMenuItems.test.ts
@@ -0,0 +1,67 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useKnowledgeMenuItems } from './useKnowledgeMenuItems';
+
+const mockFiles = vi.hoisted(() => ({
+ current: [] as { enabled: boolean; id: string; name: string; type: string }[],
+}));
+const mockKnowledgeBases = vi.hoisted(() => ({
+ current: [] as { enabled: boolean; id: string; name: string }[],
+}));
+const mockCanConfigureResource = vi.hoisted(() => ({ current: true }));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (state: unknown) => unknown) =>
+ selector({ toggleFile: vi.fn(), toggleKnowledgeBase: vi.fn() }),
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: {
+ getAgentFilesById: () => () => mockFiles.current,
+ getAgentKnowledgeBasesById: () => () => mockKnowledgeBases.current,
+ },
+}));
+
+vi.mock('../../hooks/useAgentId', () => ({ useAgentId: () => 'agent-1' }));
+vi.mock('../../hooks/useChatInputResourceAccess', () => ({
+ useChatInputResourceAccess: () => ({ canConfigureResource: mockCanConfigureResource.current }),
+}));
+
+const keysOf = (items: unknown[]) =>
+ items.map((item) => (item as { key?: string }).key).filter(Boolean);
+
+describe('useKnowledgeMenuItems', () => {
+ beforeEach(() => {
+ mockFiles.current = [];
+ mockKnowledgeBases.current = [];
+ mockCanConfigureResource.current = true;
+ });
+
+ // Regression: the picker entry is now unconditional, but `fileUpload` stays in
+ // CHAT_ONLY_ACTIONS, so a group member who can chat/upload without edit access
+ // still reaches this menu. Its getKnowledgeBasesAndFiles query asserts edit
+ // access server-side, so offering the picker would open a modal that 403s.
+ it('offers no knowledge entries when the member cannot configure the resource', () => {
+ mockCanConfigureResource.current = false;
+ mockKnowledgeBases.current = [{ enabled: true, id: 'kb-1', name: 'Handbook' }];
+
+ const { result } = renderHook(() => useKnowledgeMenuItems({ onUpdatingChange: vi.fn() }));
+
+ expect(result.current).toEqual([]);
+ });
+
+ it('offers the picker entry alongside the empty hint when nothing is attached', () => {
+ const { result } = renderHook(() => useKnowledgeMenuItems({ onUpdatingChange: vi.fn() }));
+
+ expect(keysOf(result.current)).toEqual(['knowledge-empty', 'knowledge-base-store']);
+ });
+
+ it('lists related files and libraries above the picker entry', () => {
+ mockKnowledgeBases.current = [{ enabled: true, id: 'kb-1', name: 'Handbook' }];
+
+ const { result } = renderHook(() => useKnowledgeMenuItems({ onUpdatingChange: vi.fn() }));
+
+ expect(keysOf(result.current)).toEqual(['relativeFilesOrLibraries', 'knowledge-base-store']);
+ });
+});
diff --git a/src/features/ChatInput/ActionBar/Upload/useKnowledgeMenuItems.tsx b/src/features/ChatInput/ActionBar/Upload/useKnowledgeMenuItems.tsx
new file mode 100644
index 00000000000..a1e998780a5
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Upload/useKnowledgeMenuItems.tsx
@@ -0,0 +1,127 @@
+import { type ItemType } from '@lobehub/ui';
+import { Icon } from '@lobehub/ui';
+import isEqual from 'fast-deep-equal';
+import { ArrowRight, LibraryBig } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import FileIcon from '@/components/FileIcon';
+import RepoIcon from '@/components/LibIcon';
+import { openAttachKnowledgeModal } from '@/features/LibraryModal';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+
+import { useAgentId } from '../../hooks/useAgentId';
+import { useChatInputResourceAccess } from '../../hooks/useChatInputResourceAccess';
+import CheckboxItem from '../components/CheckboxWithLoading';
+
+// Keep every row's leading icon the same width. The menu's icon slot sizes to its
+// content, so a larger file-type icon next to a smaller line icon would widen that
+// slot and push its label out of alignment with the upload / "view more" rows.
+export const MENU_ICON_SIZE = 20;
+
+/**
+ * Builds the knowledge half of the paperclip menu: the related files/libraries
+ * group plus the entry into the full picker.
+ *
+ * Returns nothing for members who cannot configure the resource. `fileUpload`
+ * stays in CHAT_ONLY_ACTIONS so chat-only members keep the paperclip, but
+ * attaching knowledge mutates the agent config and the picker's own
+ * `getKnowledgeBasesAndFiles` query asserts edit access server-side — offering
+ * it here would open a modal that immediately fails. Same gate the Plus menu
+ * applies to its Attachments submenu.
+ */
+export const useKnowledgeMenuItems = ({
+ onUpdatingChange,
+}: {
+ onUpdatingChange: (updating: boolean) => void;
+}): ItemType[] => {
+ const { t } = useTranslation('chat');
+ const agentId = useAgentId();
+ const { canConfigureResource } = useChatInputResourceAccess();
+
+ const files = useAgentStore((s) => agentByIdSelectors.getAgentFilesById(agentId)(s), isEqual);
+ const knowledgeBases = useAgentStore(
+ (s) => agentByIdSelectors.getAgentKnowledgeBasesById(agentId)(s),
+ isEqual,
+ );
+
+ const [toggleFile, toggleKnowledgeBase] = useAgentStore((s) => [
+ s.toggleFile,
+ s.toggleKnowledgeBase,
+ ]);
+
+ if (!canConfigureResource) return [];
+
+ const items: ItemType[] = [];
+
+ if (files.length > 0 || knowledgeBases.length > 0) {
+ items.push({
+ children: [
+ // first the files
+ ...files.map((item) => ({
+ icon: <FileIcon fileName={item.name} fileType={item.type} size={MENU_ICON_SIZE} />,
+ key: item.id,
+ label: (
+ <CheckboxItem
+ checked={item.enabled}
+ id={item.id}
+ label={item.name}
+ onUpdate={async (id, enabled) => {
+ onUpdatingChange(true);
+ await toggleFile(id, enabled);
+ onUpdatingChange(false);
+ }}
+ />
+ ),
+ })),
+
+ // then the knowledge bases
+ ...knowledgeBases.map((item) => ({
+ icon: <RepoIcon size={MENU_ICON_SIZE} />,
+ key: item.id,
+ label: (
+ <CheckboxItem
+ checked={item.enabled}
+ id={item.id}
+ label={item.name}
+ onUpdate={async (id, enabled) => {
+ onUpdatingChange(true);
+ await toggleKnowledgeBase(id, enabled);
+ onUpdatingChange(false);
+ }}
+ />
+ ),
+ })),
+ ],
+ key: 'relativeFilesOrLibraries',
+ label: t('knowledgeBase.relativeFilesOrLibraries'),
+ type: 'group',
+ });
+ }
+
+ const hasRelated = items.length > 0;
+
+ if (hasRelated) {
+ items.push({ type: 'divider' });
+ } else {
+ items.push({
+ disabled: true,
+ key: 'knowledge-empty',
+ label: t('knowledgeBase.related.empty'),
+ });
+ }
+
+ // The picker entry is the only way to attach the first library or file, so it has to
+ // stay reachable while nothing is attached yet — otherwise the empty hint is a dead end.
+ items.push({
+ extra: <Icon icon={ArrowRight} />,
+ icon: <Icon icon={LibraryBig} size={MENU_ICON_SIZE} />,
+ key: 'knowledge-base-store',
+ label: hasRelated ? t('knowledgeBase.viewMore') : t('knowledgeBase.related.browse'),
+ onClick: () => {
+ openAttachKnowledgeModal();
+ },
+ });
+
+ return items;
+};
diff --git a/src/features/LibraryModal/AssignKnowledgeBase/List.tsx b/src/features/LibraryModal/AssignKnowledgeBase/List.tsx
index 8038cc2a723..8c8c7aa9fdc 100644
--- a/src/features/LibraryModal/AssignKnowledgeBase/List.tsx
+++ b/src/features/LibraryModal/AssignKnowledgeBase/List.tsx
@@ -12,6 +12,7 @@ import Item from './Item';
import MasonryItemWrapper from './Item/MasonryItemWrapper';
import Loading from './Loading';
import MasonrySkeleton from './MasonrySkeleton';
+import { resolvePickerScope } from './resolvePickerScope';
import { type ViewMode } from './ViewSwitcher';
import ViewSwitcher from './ViewSwitcher';
import VisibilityTabs, { type PickerVisibility } from './VisibilityTabs';
@@ -19,22 +20,25 @@ import VisibilityTabs, { type PickerVisibility } from './VisibilityTabs';
export const List = memo(() => {
const { t } = useTranslation(['file', 'chat']);
- const [useFetchFilesAndKnowledgeBases, activeAgentId, agentVisibility] = useAgentStore((s) => [
- s.useFetchFilesAndKnowledgeBases,
- s.activeAgentId,
- s.activeAgentId ? s.agentMap[s.activeAgentId]?.visibility : undefined,
- ]);
-
- // Public agents can only reference workspace resources. The backend
- // enforces this hard (see agent.getKnowledgeBasesAndFiles) — this flag
- // just drives the UX: hide the tab, show an explainer, and force the
- // fetch to workspace scope so the client can't ask for private items.
- const isPublicAgent = agentVisibility === 'public';
+ 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,
+ ]);
const [mode, setMode] = useState<PickerVisibility>('public');
- const effectiveMode: PickerVisibility = isPublicAgent ? 'public' : mode;
-
- const { isLoading, error, data } = useFetchFilesAndKnowledgeBases(activeAgentId, effectiveMode);
+ const { effectiveVisibility, showPublicAgentHint, showVisibilityTabs } = resolvePickerScope({
+ agentVisibility,
+ agentWorkspaceId,
+ mode,
+ });
+
+ const { isLoading, error, data } = useFetchFilesAndKnowledgeBases(
+ activeAgentId,
+ effectiveVisibility,
+ );
const [columnCount, setColumnCount] = useState(2);
const [isTransitioning, setIsTransitioning] = useState(false);
@@ -95,10 +99,10 @@ export const List = memo(() => {
*/}
<Flexbox gap={8} style={{ paddingBlockEnd: 12 }}>
<Flexbox horizontal align={'center'} justify={'space-between'}>
- {isPublicAgent ? <span /> : <VisibilityTabs value={mode} onChange={setMode} />}
+ {showVisibilityTabs ? <VisibilityTabs value={mode} onChange={setMode} /> : <span />}
<ViewSwitcher view={viewMode} onViewChange={setViewMode} />
</Flexbox>
- {isPublicAgent && (
+ {showPublicAgentHint && (
<Alert
showIcon
message={t('resources.knowledgePicker.publicAgentHint', { ns: 'chat' })}
diff --git a/src/features/LibraryModal/AssignKnowledgeBase/resolvePickerScope.test.ts b/src/features/LibraryModal/AssignKnowledgeBase/resolvePickerScope.test.ts
new file mode 100644
index 00000000000..d1f52074591
--- /dev/null
+++ b/src/features/LibraryModal/AssignKnowledgeBase/resolvePickerScope.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolvePickerScope } from './resolvePickerScope';
+
+describe('resolvePickerScope', () => {
+ // Regression: `agents.visibility` defaults to 'public' and carries no meaning
+ // in personal mode, so keying the public-agent branch off it alone showed the
+ // "publish to workspace" hint to users who have no workspace at all, and
+ // narrowed the fetch to rows that merely held the default value.
+ describe('personal mode (no owning workspace)', () => {
+ it('shows no workspace hint and sends no visibility filter', () => {
+ expect(
+ resolvePickerScope({ agentVisibility: 'public', agentWorkspaceId: null, mode: 'public' }),
+ ).toEqual({
+ effectiveVisibility: undefined,
+ showPublicAgentHint: false,
+ showVisibilityTabs: false,
+ });
+ });
+
+ it('hides the visibility tabs — personal rows have no private/workspace split', () => {
+ const scope = resolvePickerScope({
+ agentVisibility: 'private',
+ agentWorkspaceId: undefined,
+ mode: 'private',
+ });
+
+ expect(scope.showVisibilityTabs).toBe(false);
+ expect(scope.effectiveVisibility).toBeUndefined();
+ });
+ });
+
+ describe('workspace agent', () => {
+ it('forces the workspace scope and explains why for a public agent', () => {
+ expect(
+ resolvePickerScope({
+ agentVisibility: 'public',
+ agentWorkspaceId: 'ws-1',
+ mode: 'private',
+ }),
+ ).toEqual({
+ effectiveVisibility: 'public',
+ showPublicAgentHint: true,
+ showVisibilityTabs: false,
+ });
+ });
+
+ it('follows the picked tab for a private agent', () => {
+ expect(
+ resolvePickerScope({
+ agentVisibility: 'private',
+ agentWorkspaceId: 'ws-1',
+ mode: 'private',
+ }),
+ ).toEqual({
+ effectiveVisibility: 'private',
+ showPublicAgentHint: false,
+ showVisibilityTabs: true,
+ });
+ });
+ });
+});
diff --git a/src/features/LibraryModal/AssignKnowledgeBase/resolvePickerScope.ts b/src/features/LibraryModal/AssignKnowledgeBase/resolvePickerScope.ts
new file mode 100644
index 00000000000..0dd3fb4c242
--- /dev/null
+++ b/src/features/LibraryModal/AssignKnowledgeBase/resolvePickerScope.ts
@@ -0,0 +1,61 @@
+import { type PickerVisibility } from './VisibilityTabs';
+
+export interface PickerScope {
+ /**
+ * Visibility filter to send with the fetch. `undefined` in personal mode —
+ * see below.
+ */
+ effectiveVisibility?: PickerVisibility;
+ /** Explain that a workspace-public agent can only reach workspace resources. */
+ showPublicAgentHint: boolean;
+ /** Let the member switch between their private drawer and the workspace share. */
+ showVisibilityTabs: boolean;
+}
+
+/**
+ * Decides what the knowledge picker may reach for the active agent.
+ *
+ * `visibility` is workspace-scoped: `buildWorkspaceWhere` ignores the column in
+ * personal mode (`workspace_id IS NULL`), where every row is implicitly private
+ * to its owner, and the column defaults to `'public'`. Keying off `visibility`
+ * alone therefore reads *every* personal agent as a public workspace agent —
+ * showing a hint that asks the user to "publish to workspace" when no workspace
+ * exists, and narrowing the fetch to rows that merely happen to carry the
+ * default value. Pair it with `workspaceId`, the same predicate
+ * `isPublicWorkspaceAgent` uses in `@lobechat/types`.
+ */
+export const resolvePickerScope = ({
+ agentVisibility,
+ agentWorkspaceId,
+ mode,
+}: {
+ agentVisibility?: 'private' | 'public';
+ agentWorkspaceId?: string | null;
+ /** The tab the member picked; only meaningful for a workspace agent. */
+ mode: PickerVisibility;
+}): PickerScope => {
+ // Personal mode: no private/workspace split exists, so no tabs, no hint, and
+ // no visibility filter — otherwise a row stored as 'private' would be
+ // unreachable with no tab to switch to.
+ if (!agentWorkspaceId)
+ return {
+ effectiveVisibility: undefined,
+ showPublicAgentHint: false,
+ showVisibilityTabs: false,
+ };
+
+ // Public agents can only reference workspace resources. The backend enforces
+ // this hard (see agent.getKnowledgeBasesAndFiles) — this just drives the UX.
+ if (agentVisibility === 'public')
+ return {
+ effectiveVisibility: 'public',
+ showPublicAgentHint: true,
+ showVisibilityTabs: false,
+ };
+
+ return {
+ effectiveVisibility: mode,
+ showPublicAgentHint: false,
+ showVisibilityTabs: true,
+ };
+};