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.

♻️ refactor(knowledge): move the agent knowledge list onto @lobechat/replica (#20669)

Arvin Xucfa464da3b96
diff --git a/src/features/LibraryModal/AssignKnowledgeBase/List.tsx b/src/features/LibraryModal/AssignKnowledgeBase/List.tsx
index ad4295a82a1..2ce02f75db3 100644
--- a/src/features/LibraryModal/AssignKnowledgeBase/List.tsx
+++ b/src/features/LibraryModal/AssignKnowledgeBase/List.tsx
@@ -1,3 +1,4 @@
+import { type KnowledgeItem } from '@lobechat/types';
import { Center, Empty, Flexbox, Icon } from '@lobehub/ui';
import { Alert } from '@lobehub/ui/base-ui';
import { VirtuosoMasonry } from '@virtuoso.dev/masonry';
@@ -7,6 +8,7 @@ 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 Item from './Item';
@@ -14,10 +16,14 @@ import MasonryItemWrapper from './Item/MasonryItemWrapper';
import Loading from './Loading';
import MasonrySkeleton from './MasonrySkeleton';
import { resolvePickerScope } from './resolvePickerScope';
+import { useViewTransition } from './useViewTransition';
import { type ViewMode } from './ViewSwitcher';
import ViewSwitcher 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']);
@@ -36,18 +42,23 @@ export const List = memo(() => {
mode,
});
- const { isLoading, error, data } = useFetchFilesAndKnowledgeBases(
- activeAgentId,
- effectiveVisibility,
+ const { isLoading, error } = useFetchFilesAndKnowledgeBases(activeAgentId, effectiveVisibility);
+ // The rows land in the knowledge replica; read them through the selector so a
+ // fetched / hydrated list re-renders the picker.
+ const data = useAgentStore(
+ agentKnowledgeSelectors.getAgentKnowledgeList(
+ activeAgentId ? { agentId: activeAgentId, visibility: effectiveVisibility } : undefined,
+ ),
);
+ const items = data ?? EMPTY_KNOWLEDGE;
const [columnCount, setColumnCount] = useState(2);
- const [isTransitioning, setIsTransitioning] = useState(false);
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) => {
- setIsTransitioning(true);
+ startTransition();
updateSystemStatus({ knowledgeBaseModalViewMode: mode });
};
@@ -74,19 +85,7 @@ export const List = memo(() => {
}
}, [viewMode, updateColumnCount]);
- // Handle view transition with a brief delay to show skeleton
- React.useEffect(() => {
- if (isTransitioning && data) {
- requestAnimationFrame(() => {
- const timer = setTimeout(() => {
- setIsTransitioning(false);
- }, 100);
- return () => clearTimeout(timer);
- });
- }
- }, [isTransitioning, viewMode, data]);
-
- const isEmpty = data && data.length === 0;
+ const isEmpty = items.length === 0;
const masonryContext = useMemo(() => ({}), []);
@@ -138,9 +137,9 @@ export const List = memo(() => {
increaseViewportBy={typeof window !== 'undefined' ? window.innerHeight : 0}
overscan={24}
style={{ flex: 1, marginInline: -16 }}
- totalCount={data!.length}
+ totalCount={items.length}
itemContent={(index) => {
- const item = data![index];
+ const item = items[index];
return <Item key={item.id} {...item} />;
}}
/>
@@ -151,7 +150,7 @@ export const List = memo(() => {
ItemContent={MasonryItemWrapper}
columnCount={columnCount}
context={masonryContext}
- data={data || []}
+ data={items}
style={{
gap: '16px',
height: '100%',
diff --git a/src/features/LibraryModal/AssignKnowledgeBase/useViewTransition.test.ts b/src/features/LibraryModal/AssignKnowledgeBase/useViewTransition.test.ts
new file mode 100644
index 00000000000..5f48ffdf5e1
--- /dev/null
+++ b/src/features/LibraryModal/AssignKnowledgeBase/useViewTransition.test.ts
@@ -0,0 +1,36 @@
+/**
+ * @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
new file mode 100644
index 00000000000..8ea26a64a04
--- /dev/null
+++ b/src/features/LibraryModal/AssignKnowledgeBase/useViewTransition.ts
@@ -0,0 +1,32 @@
+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/libs/swr/keys.ts b/src/libs/swr/keys.ts
index da71d194170..2bf5f796581 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -444,8 +444,8 @@ export const serverConfigKeys = {
};
// ---- discover (marketplace) ---------------------------------------------
-// NOTE: discover/eval/ragEval/knowledgeBase/device/userMemory/agentKnowledge/
-// file prefixes are deliberately kept OUT of `CACHE_TIERS`
+// NOTE: discover/eval/ragEval/knowledgeBase/device/userMemory/file prefixes
+// are deliberately kept OUT of `CACHE_TIERS`
// (see localStorageProvider.ts) so this key-convergence introduces no new
// persistence — they stay memory-only exactly as before.
export const discoverKeys = {
@@ -672,17 +672,6 @@ export const globalKeys = {
systemStatus: def('global:systemStatus', () => ['global:systemStatus']),
};
-// ---- agent knowledge (kept off the `agent:` idb tier on purpose) --------
-export const agentKnowledgeKeys = {
- list: def(
- 'agentKnowledge:list',
- (agentId: string | undefined, visibility?: 'private' | 'public') => {
- const base = ['agentKnowledge:list', agentId] as const;
- return visibility ? [...base, visibility] : base;
- },
- ),
-};
-
// ---- file ---------------------------------------------------------------
export const fileKeys = {
ttsFile: def('file:ttsFile', (messageId: string) => ['file:ttsFile', messageId]),
@@ -1169,7 +1158,6 @@ export const swrKeys = {
agentBuilder: agentBuilderKeys,
agentDocument: agentDocumentSWRKeys,
agentHome: agentHomeKeys,
- agentKnowledge: agentKnowledgeKeys,
agentProfile: agentProfileKeys,
agentSignal: agentSignalKeys,
aiModel: aiModelKeys,
diff --git a/src/store/agent/initialState.ts b/src/store/agent/initialState.ts
index 70907603f4e..20368b37947 100644
--- a/src/store/agent/initialState.ts
+++ b/src/store/agent/initialState.ts
@@ -5,15 +5,18 @@ import { type BotSliceState } from './slices/bot';
import { initialBotSliceState } from './slices/bot';
import { type BuiltinAgentSliceState } from './slices/builtin';
import { initialBuiltinAgentSliceState } from './slices/builtin';
+import { initialKnowledgeSliceState, type KnowledgeSliceState } from './slices/knowledge';
export type AgentStoreState = AgentArtworkSliceState &
AgentSliceState &
BotSliceState &
- BuiltinAgentSliceState;
+ BuiltinAgentSliceState &
+ KnowledgeSliceState;
export const initialState: AgentStoreState = {
...initialAgentArtworkSliceState,
...initialAgentSliceState,
...initialBotSliceState,
...initialBuiltinAgentSliceState,
+ ...initialKnowledgeSliceState,
};
diff --git a/src/store/agent/selectors/index.ts b/src/store/agent/selectors/index.ts
index d01f3142ea2..b2f0d7d67aa 100644
--- a/src/store/agent/selectors/index.ts
+++ b/src/store/agent/selectors/index.ts
@@ -1,4 +1,5 @@
export { agentArtworkSelectors } from '../slices/artwork/selectors';
+export { agentKnowledgeSelectors } from '../slices/knowledge/selectors';
export * from './agentByIdSelectors';
export * from './builtinAgentSelectors';
export * from './chatConfigByIdSelectors';
diff --git a/src/store/agent/slices/knowledge/action.test.ts b/src/store/agent/slices/knowledge/action.test.ts
index f6e10c208b0..d1094988c54 100644
--- a/src/store/agent/slices/knowledge/action.test.ts
+++ b/src/store/agent/slices/knowledge/action.test.ts
@@ -1,13 +1,32 @@
-import { act, renderHook, waitFor } from '@testing-library/react';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
+/**
+ * @vitest-environment happy-dom
+ *
+ * Imperative knowledge behaviour: the add / remove / toggle actions keep their
+ * `activeAgentId` guards and service parameters, and a knowledge mutation fans
+ * out to every loaded visibility surface through `internal_refreshAgentKnowledge`.
+ * The local-first wiring (hydration, cold start, scope switch) is covered by
+ * `replica.test.ts`.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { mutate } from '@/libs/swr';
import { agentService } from '@/services/agent';
-import { KnowledgeType } from '@/types/knowledgeBase';
-import { withSWR } from '~test-utils';
+import { initialState } from '../../initialState';
import { useAgentStore } from '../../store';
+import { agentKnowledgeListKey } from './projection';
+
+vi.mock('@/libs/swr', async () => {
+ const actual = await vi.importActual<Record<string, unknown>>('@/libs/swr');
+ return { ...actual, mutate: vi.fn() };
+});
+
+vi.mock('@/libs/swr/useCacheScope', () => ({
+ getCacheScope: () => 'u1:personal',
+ isScopeTrusted: () => true,
+ useCacheScope: () => 'u1:personal',
+}));
-// Mock agentService
vi.mock('@/services/agent', () => ({
AVAILABLE_AGENTS_CONTEXT_QUERY_LIMIT: 12,
agentService: {
@@ -21,289 +40,144 @@ vi.mock('@/services/agent', () => ({
},
}));
-// Mock SWR mutate
-vi.mock('swr', async () => {
- const actual = await vi.importActual('swr');
- return {
- ...actual,
- mutate: vi.fn(),
- };
-});
-
-beforeEach(() => {
- vi.clearAllMocks();
- useAgentStore.setState({
- activeAgentId: undefined,
- agentMap: {},
- builtinAgentIdMap: {},
- updateAgentConfigSignal: undefined,
- updateAgentMetaSignal: undefined,
+const AGENT_ID = 'agent-1';
+const KNOWLEDGE_KEY = agentKnowledgeListKey({ agentId: AGENT_ID, visibility: 'private' });
+const SYNC_KEY = [
+ 'replica:sync',
+ 'agentKnowledgeList',
+ 1,
+ 'u1:personal',
+ KNOWLEDGE_KEY,
+ { agentId: AGENT_ID, visibility: 'private' },
+];
+
+const reset = (activeAgentId?: string) => {
+ useAgentStore.setState({ ...initialState, activeAgentId });
+};
+
+/** Predicates the store handed to the scoped `mutate` (replica revalidations). */
+const revalidatePredicates = () =>
+ vi.mocked(mutate).mock.calls.map(([key]) => key as (k: unknown) => boolean);
+
+const expectKnowledgeRevalidated = () =>
+ expect(revalidatePredicates().some((predicate) => predicate(SYNC_KEY))).toBe(true);
+
+describe('KnowledgeSlice actions', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(mutate).mockResolvedValue(undefined as never);
+ vi.mocked(agentService.createAgentFiles).mockResolvedValue(undefined as never);
+ vi.mocked(agentService.createAgentKnowledgeBase).mockResolvedValue(undefined as never);
+ vi.mocked(agentService.deleteAgentFile).mockResolvedValue(undefined as never);
+ vi.mocked(agentService.deleteAgentKnowledgeBase).mockResolvedValue(undefined as never);
+ vi.mocked(agentService.toggleFile).mockResolvedValue(undefined as never);
+ vi.mocked(agentService.toggleKnowledgeBase).mockResolvedValue(undefined as never);
+ reset(AGENT_ID);
});
-});
-afterEach(() => {
- vi.restoreAllMocks();
-});
-
-describe('KnowledgeSlice Actions', () => {
describe('addFilesToAgent', () => {
it('should not call service if no activeAgentId', async () => {
- const { result } = renderHook(() => useAgentStore());
-
- await act(async () => {
- await result.current.addFilesToAgent(['file-1', 'file-2']);
- });
-
+ reset(undefined);
+ await useAgentStore.getState().addFilesToAgent(['file-1', 'file-2']);
expect(agentService.createAgentFiles).not.toHaveBeenCalled();
});
it('should not call service if fileIds is empty', async () => {
- const { result } = renderHook(() => useAgentStore());
-
- act(() => {
- useAgentStore.setState({ activeAgentId: 'agent-1' });
- });
-
- await act(async () => {
- await result.current.addFilesToAgent([]);
- });
-
+ await useAgentStore.getState().addFilesToAgent([]);
expect(agentService.createAgentFiles).not.toHaveBeenCalled();
});
- it('should call createAgentFiles with correct params', async () => {
- const { result } = renderHook(() => useAgentStore());
-
- vi.mocked(agentService.createAgentFiles).mockResolvedValue(undefined as any);
-
- act(() => {
- useAgentStore.setState({ activeAgentId: 'agent-1' });
- });
-
- await act(async () => {
- await result.current.addFilesToAgent(['file-1', 'file-2'], true);
- });
+ it('should call createAgentFiles with correct params and revalidate knowledge', async () => {
+ await useAgentStore.getState().addFilesToAgent(['file-1', 'file-2'], true);
expect(agentService.createAgentFiles).toHaveBeenCalledWith(
- 'agent-1',
+ AGENT_ID,
['file-1', 'file-2'],
true,
);
+ expectKnowledgeRevalidated();
});
});
describe('addKnowledgeBaseToAgent', () => {
it('should not call service if no activeAgentId', async () => {
- const { result } = renderHook(() => useAgentStore());
-
- await act(async () => {
- await result.current.addKnowledgeBaseToAgent('kb-1');
- });
-
+ reset(undefined);
+ await useAgentStore.getState().addKnowledgeBaseToAgent('kb-1');
expect(agentService.createAgentKnowledgeBase).not.toHaveBeenCalled();
});
it('should call createAgentKnowledgeBase with enabled=true', async () => {
- const { result } = renderHook(() => useAgentStore());
-
- vi.mocked(agentService.createAgentKnowledgeBase).mockResolvedValue(undefined as any);
-
- act(() => {
- useAgentStore.setState({ activeAgentId: 'agent-1' });
- });
-
- await act(async () => {
- await result.current.addKnowledgeBaseToAgent('kb-1');
- });
-
- expect(agentService.createAgentKnowledgeBase).toHaveBeenCalledWith('agent-1', 'kb-1', true);
+ await useAgentStore.getState().addKnowledgeBaseToAgent('kb-1');
+ expect(agentService.createAgentKnowledgeBase).toHaveBeenCalledWith(AGENT_ID, 'kb-1', true);
});
});
describe('removeFileFromAgent', () => {
it('should not call service if no activeAgentId', async () => {
- const { result } = renderHook(() => useAgentStore());
-
- await act(async () => {
- await result.current.removeFileFromAgent('file-1');
- });
-
+ reset(undefined);
+ await useAgentStore.getState().removeFileFromAgent('file-1');
expect(agentService.deleteAgentFile).not.toHaveBeenCalled();
});
it('should call deleteAgentFile with correct params', async () => {
- const { result } = renderHook(() => useAgentStore());
-
- vi.mocked(agentService.deleteAgentFile).mockResolvedValue(undefined as any);
-
- act(() => {
- useAgentStore.setState({ activeAgentId: 'agent-1' });
- });
-
- await act(async () => {
- await result.current.removeFileFromAgent('file-1');
- });
-
- expect(agentService.deleteAgentFile).toHaveBeenCalledWith('agent-1', 'file-1');
+ await useAgentStore.getState().removeFileFromAgent('file-1');
+ expect(agentService.deleteAgentFile).toHaveBeenCalledWith(AGENT_ID, 'file-1');
});
});
describe('removeKnowledgeBaseFromAgent', () => {
it('should not call service if no activeAgentId', async () => {
- const { result } = renderHook(() => useAgentStore());
-
- await act(async () => {
- await result.current.removeKnowledgeBaseFromAgent('kb-1');
- });
-
+ reset(undefined);
+ await useAgentStore.getState().removeKnowledgeBaseFromAgent('kb-1');
expect(agentService.deleteAgentKnowledgeBase).not.toHaveBeenCalled();
});
it('should call deleteAgentKnowledgeBase with correct params', async () => {
- const { result } = renderHook(() => useAgentStore());
-
- vi.mocked(agentService.deleteAgentKnowledgeBase).mockResolvedValue(undefined as any);
-
- act(() => {
- useAgentStore.setState({ activeAgentId: 'agent-1' });
- });
-
- await act(async () => {
- await result.current.removeKnowledgeBaseFromAgent('kb-1');
- });
-
- expect(agentService.deleteAgentKnowledgeBase).toHaveBeenCalledWith('agent-1', 'kb-1');
+ await useAgentStore.getState().removeKnowledgeBaseFromAgent('kb-1');
+ expect(agentService.deleteAgentKnowledgeBase).toHaveBeenCalledWith(AGENT_ID, 'kb-1');
});
});
describe('toggleFile', () => {
it('should not call service if no activeAgentId', async () => {
- const { result } = renderHook(() => useAgentStore());
-
- await act(async () => {
- await result.current.toggleFile('file-1', true);
- });
-
+ reset(undefined);
+ await useAgentStore.getState().toggleFile('file-1', true);
expect(agentService.toggleFile).not.toHaveBeenCalled();
});
it('should call toggleFile with correct params', async () => {
- const { result } = renderHook(() => useAgentStore());
-
- vi.mocked(agentService.toggleFile).mockResolvedValue(undefined as any);
-
- act(() => {
- useAgentStore.setState({ activeAgentId: 'agent-1' });
- });
-
- await act(async () => {
- await result.current.toggleFile('file-1', true);
- });
-
- expect(agentService.toggleFile).toHaveBeenCalledWith('agent-1', 'file-1', true);
+ await useAgentStore.getState().toggleFile('file-1', true);
+ expect(agentService.toggleFile).toHaveBeenCalledWith(AGENT_ID, 'file-1', true);
});
it('should call toggleFile with open=false', async () => {
- const { result } = renderHook(() => useAgentStore());
-
- vi.mocked(agentService.toggleFile).mockResolvedValue(undefined as any);
-
- act(() => {
- useAgentStore.setState({ activeAgentId: 'agent-1' });
- });
-
- await act(async () => {
- await result.current.toggleFile('file-1', false);
- });
-
- expect(agentService.toggleFile).toHaveBeenCalledWith('agent-1', 'file-1', false);
+ await useAgentStore.getState().toggleFile('file-1', false);
+ expect(agentService.toggleFile).toHaveBeenCalledWith(AGENT_ID, 'file-1', false);
});
});
describe('toggleKnowledgeBase', () => {
it('should not call service if no activeAgentId', async () => {
- const { result } = renderHook(() => useAgentStore());
-
- await act(async () => {
- await result.current.toggleKnowledgeBase('kb-1', true);
- });
-
+ reset(undefined);
+ await useAgentStore.getState().toggleKnowledgeBase('kb-1', true);
expect(agentService.toggleKnowledgeBase).not.toHaveBeenCalled();
});
it('should call toggleKnowledgeBase with correct params', async () => {
- const { result } = renderHook(() => useAgentStore());
-
- vi.mocked(agentService.toggleKnowledgeBase).mockResolvedValue(undefined as any);
-
- act(() => {
- useAgentStore.setState({ activeAgentId: 'agent-1' });
- });
-
- await act(async () => {
- await result.current.toggleKnowledgeBase('kb-1', true);
- });
-
- expect(agentService.toggleKnowledgeBase).toHaveBeenCalledWith('agent-1', 'kb-1', true);
+ await useAgentStore.getState().toggleKnowledgeBase('kb-1', true);
+ expect(agentService.toggleKnowledgeBase).toHaveBeenCalledWith(AGENT_ID, 'kb-1', true);
});
it('should call toggleKnowledgeBase with open=false', async () => {
- const { result } = renderHook(() => useAgentStore());
-
- vi.mocked(agentService.toggleKnowledgeBase).mockResolvedValue(undefined as any);
-
- act(() => {
- useAgentStore.setState({ activeAgentId: 'agent-1' });
- });
-
- await act(async () => {
- await result.current.toggleKnowledgeBase('kb-1', false);
- });
-
- expect(agentService.toggleKnowledgeBase).toHaveBeenCalledWith('agent-1', 'kb-1', false);
+ await useAgentStore.getState().toggleKnowledgeBase('kb-1', false);
+ expect(agentService.toggleKnowledgeBase).toHaveBeenCalledWith(AGENT_ID, 'kb-1', false);
});
});
- describe('useFetchFilesAndKnowledgeBases', () => {
- it('should fetch files and knowledge bases for active agent', async () => {
- const mockData = [
- { enabled: true, id: 'file-1', name: 'file1.txt', type: KnowledgeType.File },
- { enabled: true, id: 'kb-1', name: 'KB 1', type: KnowledgeType.KnowledgeBase },
- ];
-
- vi.mocked(agentService.getFilesAndKnowledgeBases).mockResolvedValueOnce(mockData);
-
- act(() => {
- useAgentStore.setState({ activeAgentId: 'agent-1' });
- });
-
- const { result } = renderHook(
- () => useAgentStore().useFetchFilesAndKnowledgeBases('agent-1'),
- {
- wrapper: withSWR,
- },
- );
-
- await waitFor(() => expect(result.current.data).toEqual(mockData));
-
- expect(agentService.getFilesAndKnowledgeBases).toHaveBeenCalledWith('agent-1', undefined);
- });
-
- it('should return empty array as fallback', async () => {
- vi.mocked(agentService.getFilesAndKnowledgeBases).mockResolvedValueOnce([]);
-
- act(() => {
- useAgentStore.setState({ activeAgentId: 'agent-1' });
- });
-
- const { result } = renderHook(
- () => useAgentStore().useFetchFilesAndKnowledgeBases('agent-1'),
- {
- wrapper: withSWR,
- },
- );
-
- await waitFor(() => expect(result.current.data).toEqual([]));
+ describe('internal_refreshAgentKnowledge', () => {
+ it('revalidates the knowledge replica of the active scope', async () => {
+ await useAgentStore.getState().internal_refreshAgentKnowledge();
+ expectKnowledgeRevalidated();
});
});
});
diff --git a/src/store/agent/slices/knowledge/action.ts b/src/store/agent/slices/knowledge/action.ts
index 18a949ac805..688e4a67f69 100644
--- a/src/store/agent/slices/knowledge/action.ts
+++ b/src/store/agent/slices/knowledge/action.ts
@@ -1,29 +1,62 @@
import { type KnowledgeItem } from '@lobechat/types';
-import { type SWRResponse } from 'swr';
-
-import { mutate, useClientDataSWR } from '@/libs/swr';
-import { agentKnowledgeKeys } from '@/libs/swr/keys';
+import isEqual from 'fast-deep-equal';
+
+import {
+ arrayEntity,
+ createReplicaSlice,
+ recordLens,
+ type ReplicaSyncResult,
+} from '@/libs/replica';
import { agentService } from '@/services/agent';
import { type StoreSetter } from '@/store/types';
import { type AgentStore } from '../../store';
+import {
+ agentKnowledgeListKey,
+ type AgentKnowledgeListParams,
+ agentKnowledgeListResource,
+} from './projection';
/**
* Knowledge Slice Actions
- * Handles knowledge base and file operations
+ * Handles knowledge base and file operations via the `agentKnowledgeList`
+ * replica (read through `agentKnowledgeSelectors`).
*/
type Setter = StoreSetter<AgentStore>;
+
+/** `useFetchFilesAndKnowledgeBases` result: replica flags plus the SWR-era aliases. */
+export interface AgentKnowledgeSyncResult extends ReplicaSyncResult {
+ /** A request is in flight and the surface has no rows to show yet. */
+ isLoading: boolean;
+ /** Alias of `revalidate`. */
+ mutate: () => Promise<unknown>;
+ /** Entry key the caller's rows live under (`agentKnowledgeMap[queryKey]`). */
+ queryKey?: string;
+}
+
export const createKnowledgeSlice = (set: Setter, get: () => AgentStore, _api?: unknown) =>
new KnowledgeSliceActionImpl(set, get, _api);
export class KnowledgeSliceActionImpl {
readonly #get: () => AgentStore;
+ readonly #knowledgeList;
constructor(set: Setter, get: () => AgentStore, _api?: unknown) {
void _api;
- void set;
this.#get = get;
+ this.#knowledgeList = createReplicaSlice(agentKnowledgeListResource, {
+ actionPrefix: 'agentKnowledge',
+ entity: arrayEntity<KnowledgeItem>((item) => item.id),
+ fetcher: ({ agentId, visibility }) =>
+ agentService.getFilesAndKnowledgeBases(agentId, visibility),
+ get,
+ // An unchanged response must not re-render the picker.
+ merge: (incoming, confirmed) => (isEqual(incoming, confirmed) ? undefined : incoming),
+ set,
+ stateKey: 'agentKnowledgeListReplica',
+ view: recordLens<AgentStore, KnowledgeItem[]>('agentKnowledgeMap'),
+ });
}
addFilesToAgent = async (fileIds: string[], enabled?: boolean): Promise<void> => {
@@ -48,15 +81,11 @@ export class KnowledgeSliceActionImpl {
};
internal_refreshAgentKnowledge = async (): Promise<void> => {
- const agentId = this.#get().activeAgentId;
- // The picker keys its cache per visibility (unscoped/private/workspace)
- // so a mutation needs to invalidate all three surfaces at once, otherwise
- // switching tab after add/remove still shows the stale list.
- await Promise.all([
- mutate(agentKnowledgeKeys.list(agentId)),
- mutate(agentKnowledgeKeys.list(agentId, 'private')),
- mutate(agentKnowledgeKeys.list(agentId, 'public')),
- ]);
+ // The picker keys its cache per visibility (unscoped/private/workspace), so
+ // a mutation has to invalidate all three surfaces at once, otherwise
+ // switching tab after add/remove still shows the stale list. A keyless
+ // revalidate covers every loaded surface of the active scope.
+ await this.#knowledgeList.revalidate();
};
removeFileFromAgent = async (fileId: string): Promise<void> => {
@@ -95,17 +124,32 @@ export class KnowledgeSliceActionImpl {
await internal_refreshAgentConfig(activeAgentId);
};
+ /**
+ * Fetch orchestration for the knowledge picker. The rows land in
+ * `agentKnowledgeMap[queryKey]` — read them through
+ * `agentKnowledgeSelectors.getAgentKnowledgeList`.
+ */
useFetchFilesAndKnowledgeBases = (
agentId?: string,
- visibility?: 'private' | 'public',
- ): SWRResponse<KnowledgeItem[]> => {
- return useClientDataSWR<KnowledgeItem[]>(
- agentId ? agentKnowledgeKeys.list(agentId, visibility) : null,
- () => agentService.getFilesAndKnowledgeBases(agentId!, visibility),
- {
- fallbackData: [],
- },
- );
+ visibility?: AgentKnowledgeListParams['visibility'],
+ ): AgentKnowledgeSyncResult => {
+ const params: AgentKnowledgeListParams | undefined = agentId
+ ? { agentId, visibility }
+ : undefined;
+ const queryKey = params ? agentKnowledgeListKey(params) : undefined;
+ const sync = this.#knowledgeList.useSync(params, { enabled: !!agentId });
+
+ return {
+ ...sync,
+ // Loading only until the surface has rows to show: a revalidation over an
+ // already-painted surface must not flash a skeleton.
+ isLoading:
+ !!queryKey &&
+ !this.#get().agentKnowledgeMap[queryKey] &&
+ (sync.isValidating || !sync.isHydrated),
+ mutate: sync.revalidate,
+ queryKey,
+ };
};
}
diff --git a/src/store/agent/slices/knowledge/index.ts b/src/store/agent/slices/knowledge/index.ts
index 3428811492a..b906cec9fa6 100644
--- a/src/store/agent/slices/knowledge/index.ts
+++ b/src/store/agent/slices/knowledge/index.ts
@@ -1 +1,13 @@
-export { createKnowledgeSlice, type KnowledgeSliceAction } from './action';
+export {
+ type AgentKnowledgeSyncResult,
+ createKnowledgeSlice,
+ type KnowledgeSliceAction,
+} from './action';
+export { initialKnowledgeSliceState, type KnowledgeSliceState } from './initialState';
+export {
+ agentKnowledgeListKey,
+ type AgentKnowledgeListParams,
+ agentKnowledgeListResource,
+ type AgentKnowledgeVisibility,
+} from './projection';
+export { agentKnowledgeSelectors } from './selectors';
diff --git a/src/store/agent/slices/knowledge/initialState.ts b/src/store/agent/slices/knowledge/initialState.ts
new file mode 100644
index 00000000000..f1489284bc3
--- /dev/null
+++ b/src/store/agent/slices/knowledge/initialState.ts
@@ -0,0 +1,15 @@
+import { type KnowledgeItem } from '@lobechat/types';
+
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+
+export interface KnowledgeSliceState {
+ /** Local-first bookkeeping for `agentKnowledgeMap`. */
+ agentKnowledgeListReplica: ReplicaState<KnowledgeItem[]>;
+ /** Files + knowledge bases per visibility surface (`agentKnowledgeMap[<agentId>[:<visibility>]]`). */
+ agentKnowledgeMap: Record<string, KnowledgeItem[]>;
+}
+
+export const initialKnowledgeSliceState: KnowledgeSliceState = {
+ agentKnowledgeMap: {},
+ agentKnowledgeListReplica: createReplicaState(),
+};
diff --git a/src/store/agent/slices/knowledge/projection.ts b/src/store/agent/slices/knowledge/projection.ts
new file mode 100644
index 00000000000..eb1457e65ab
--- /dev/null
+++ b/src/store/agent/slices/knowledge/projection.ts
@@ -0,0 +1,43 @@
+import { type KnowledgeItem } from '@lobechat/types';
+
+import { defineReplica } from '@/libs/replica';
+
+/**
+ * Visibility surface of the agent-knowledge picker. `undefined` is the
+ * unfiltered surface used in personal scope (see `resolvePickerScope`).
+ */
+export type AgentKnowledgeVisibility = 'private' | 'public';
+
+export interface AgentKnowledgeListParams {
+ agentId: string;
+ visibility?: AgentKnowledgeVisibility;
+}
+
+/**
+ * Entry identity of one knowledge surface: `<agentId>` (unfiltered) or
+ * `<agentId>:<visibility>`. Agent ids never contain a colon, so the two never
+ * collide. The picker keys its cache per visibility so switching tab after a
+ * mutation never shows the other tab's stale rows.
+ */
+export const agentKnowledgeListKey = ({ agentId, visibility }: AgentKnowledgeListParams): string =>
+ visibility ? `${agentId}:${visibility}` : agentId;
+
+/**
+ * Files + knowledge bases attached to one agent, one local-first entry per
+ * visibility surface (`agentKnowledgeMap[<agentId>[:<visibility>]]`).
+ *
+ * Hydrates from IndexedDB, revalidates over the network, and is the only writer
+ * of the view: read it through `agentKnowledgeSelectors`, the sync hook only
+ * orchestrates fetching. `entity` lets a toggle/removal fan out to every loaded
+ * surface of the same item.
+ */
+export const agentKnowledgeListResource = defineReplica<
+ AgentKnowledgeListParams,
+ KnowledgeItem[],
+ KnowledgeItem[]
+>({
+ key: agentKnowledgeListKey,
+ name: 'agentKnowledgeList',
+ storage: 'indexedDB',
+ version: 1,
+});
diff --git a/src/store/agent/slices/knowledge/replica.test.ts b/src/store/agent/slices/knowledge/replica.test.ts
new file mode 100644
index 00000000000..bc3db68305d
--- /dev/null
+++ b/src/store/agent/slices/knowledge/replica.test.ts
@@ -0,0 +1,147 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The agent-knowledge list is a `@lobechat/replica` resource whose view is the
+ * agent store's `agentKnowledgeMap`: the persisted projection paints while the
+ * network confirms it, an unchanged response keeps the array reference, a
+ * refresh after a knowledge mutation repaints the surface, and a cache-scope
+ * switch drops the previous identity's rows before paint.
+ */
+import { randomUUID } from 'node:crypto';
+
+import { type KnowledgeItem } from '@lobechat/types';
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import { type PropsWithChildren } from 'react';
+import { createElement, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { agentService } from '@/services/agent';
+import { useAgentStore } from '@/store/agent';
+import { agentKnowledgeSelectors } from '@/store/agent/selectors';
+import { KnowledgeType } from '@/types/knowledgeBase';
+
+import { initialState } from '../../initialState';
+import { type AgentKnowledgeListParams, agentKnowledgeListResource } from './projection';
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map() } },
+ createElement(MutateBridge),
+ children,
+ );
+
+const PARAMS: AgentKnowledgeListParams = { agentId: 'agent-1', visibility: 'private' };
+
+const item = (id: string, overrides: Partial<KnowledgeItem> = {}): KnowledgeItem => ({
+ enabled: true,
+ id,
+ name: id,
+ type: KnowledgeType.File,
+ ...overrides,
+});
+
+/** Never-resolving fetch: what the store holds can only have come from storage. */
+const pending = () => new Promise<never>(() => {});
+
+const STORAGE_KEY = agentKnowledgeListResource.storageKey(PARAMS);
+
+/** The loaded rows of the surface under test, as the picker reads them. */
+const rows = () => agentKnowledgeSelectors.getAgentKnowledgeList(PARAMS)(useAgentStore.getState());
+
+const renderSync = () =>
+ renderHook(
+ () => useAgentStore((s) => s.useFetchFilesAndKnowledgeBases)(PARAMS.agentId, PARAMS.visibility),
+ { wrapper },
+ );
+
+describe('agent knowledge list replica', () => {
+ const scopes = new Set<string>();
+ let scope = '';
+
+ const useScope = (next: string) => {
+ scope = next;
+ scopes.add(next);
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ };
+
+ beforeEach(() => {
+ useScope(`knowledge-user-${randomUUID()}:personal`);
+ useAgentStore.setState({ ...initialState });
+ });
+
+ afterEach(async () => {
+ cleanup();
+ await Promise.all(
+ [...scopes].map((value) =>
+ agentKnowledgeListResource.storage!.remove({ queryKey: STORAGE_KEY, scope: value }),
+ ),
+ );
+ scopes.clear();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ it('paints the persisted list before the network answers', async () => {
+ await agentKnowledgeListResource.storage!.set(
+ { queryKey: STORAGE_KEY, scope },
+ { data: [item('f1', { name: 'Cached' })], updatedAt: 1 },
+ );
+ vi.spyOn(agentService, 'getFilesAndKnowledgeBases').mockImplementation(pending);
+
+ renderSync();
+
+ await waitFor(() => expect(rows()).toHaveLength(1));
+ expect(rows()![0].name).toBe('Cached');
+ });
+
+ it('keeps the list reference when the server returns an unchanged list', async () => {
+ const get = vi.spyOn(agentService, 'getFilesAndKnowledgeBases').mockResolvedValue([item('f1')]);
+ renderSync();
+ await waitFor(() => expect(rows()).toHaveLength(1));
+ const before = rows();
+
+ get.mockResolvedValue([item('f1')]);
+ await act(() => useAgentStore.getState().internal_refreshAgentKnowledge());
+
+ expect(rows()).toBe(before);
+ });
+
+ it('repaints the surface after a knowledge mutation refreshes it', async () => {
+ const get = vi.spyOn(agentService, 'getFilesAndKnowledgeBases').mockResolvedValue([item('f1')]);
+ renderSync();
+ await waitFor(() => expect(rows()).toHaveLength(1));
+
+ get.mockResolvedValue([
+ item('f1'),
+ item('kb-1', { name: 'Fresh', type: KnowledgeType.KnowledgeBase }),
+ ]);
+ await act(() => useAgentStore.getState().internal_refreshAgentKnowledge());
+
+ await waitFor(() => expect(rows()).toHaveLength(2));
+ expect(rows()!.map((row) => row.id)).toEqual(['f1', 'kb-1']);
+ });
+
+ it('drops the previous scope’s rows on a cache-scope switch', async () => {
+ const get = vi.spyOn(agentService, 'getFilesAndKnowledgeBases').mockResolvedValue([item('f1')]);
+ const { rerender } = renderSync();
+ await waitFor(() => expect(rows()).toHaveLength(1));
+
+ // Switch identity: the new scope's rows are still in flight.
+ useScope(`${scope.split(':')[0]}:ws-1`);
+ get.mockImplementation(pending);
+ rerender();
+
+ expect(rows()).toBeUndefined();
+ });
+});
diff --git a/src/store/agent/slices/knowledge/selectors.ts b/src/store/agent/slices/knowledge/selectors.ts
new file mode 100644
index 00000000000..1f41980baf6
--- /dev/null
+++ b/src/store/agent/slices/knowledge/selectors.ts
@@ -0,0 +1,26 @@
+import { type KnowledgeItem } from '@lobechat/types';
+
+import { type AgentStore } from '../../store';
+import { agentKnowledgeListKey, type AgentKnowledgeListParams } from './projection';
+
+/**
+ * The loaded rows of one knowledge surface, or `undefined` before its first
+ * paint. Read by the knowledge picker; the knowledge slice is the only writer.
+ */
+const getAgentKnowledgeList =
+ (params?: AgentKnowledgeListParams) =>
+ (s: AgentStore): KnowledgeItem[] | undefined =>
+ params ? s.agentKnowledgeMap[agentKnowledgeListKey(params)] : undefined;
+
+/** The surface is loaded and empty (not merely un-fetched). */
+const isAgentKnowledgeListEmpty =
+ (params?: AgentKnowledgeListParams) =>
+ (s: AgentStore): boolean => {
+ const list = getAgentKnowledgeList(params)(s);
+ return !!list && list.length === 0;
+ };
+
+export const agentKnowledgeSelectors = {
+ getAgentKnowledgeList,
+ isAgentKnowledgeListEmpty,
+};