🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor(library): move the knowledge-base list and CRUD onto @lobechat/replica (#20602)
Arvin Xu9abb2cef4105
diff --git a/src/features/ResourceHome/Home/Libraries.tsx b/src/features/ResourceHome/Home/Libraries.tsxindex 2432f4f3bd5..d105b70a45b 100644--- a/src/features/ResourceHome/Home/Libraries.tsx+++ b/src/features/ResourceHome/Home/Libraries.tsx@@ -16,7 +16,7 @@ import { useCreateNewModal } from '@/features/LibraryModal';import { useResourceManagerStore } from '@/features/ResourceManager/store';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { usePermission } from '@/hooks/usePermission';-import { useKnowledgeBaseStore } from '@/store/library';+import { knowledgeBaseSelectors, useKnowledgeBaseStore } from '@/store/library';import { getLibraryListAsyncState } from '../Layout/Body/LibraryList/state';import SectionTitle from './SectionTitle';@@ -111,12 +111,14 @@ const Libraries = memo(() => {const visibility = listVisibility === 'private' ? ('private' as const) : ('public' as const);const useFetchKnowledgeBaseList = useKnowledgeBaseStore((s) => s.useFetchKnowledgeBaseList);- const { data, error, isLoading, isValidating, mutate } = useFetchKnowledgeBaseList(visibility);- // The hook uses fallbackData: []; for a new workspace/visibility key SWR therefore- // reports isLoading=false while the request is still validating.+ const { error, isHydrated, isValidating, revalidate } = useFetchKnowledgeBaseList(visibility);+ // The rows are read from the replica view; the hook only orchestrates fetching.+ const data = useKnowledgeBaseStore(knowledgeBaseSelectors.getKnowledgeBaseList(visibility));+ // A fresh scope has no persisted row yet, so `!isHydrated` keeps the skeleton+ // up until the first local read completes and the network sync lands.const { isLoading: showSkeleton } = getLibraryListAsyncState({data,- isLoading,+ isLoading: !isHydrated,isValidating,});@@ -136,7 +138,7 @@ const Libraries = memo(() => {<Flexbox gap={12}><SectionTitle title={t('home.libraries')} />{error && !data?.length ? (- <AsyncError error={error} variant={'inline'} onRetry={() => void mutate()} />+ <AsyncError error={error} variant={'inline'} onRetry={() => void revalidate()} />) : showSkeleton ? (<ResourceSectionSkeleton {...RESOURCE_HOME_SECTIONS.libraries} />) : (diff --git a/src/features/ResourceHome/Layout/Body/LibraryList/index.tsx b/src/features/ResourceHome/Layout/Body/LibraryList/index.tsxindex db50542ec89..72e42fe7c11 100644--- a/src/features/ResourceHome/Layout/Body/LibraryList/index.tsx+++ b/src/features/ResourceHome/Layout/Body/LibraryList/index.tsx@@ -11,7 +11,7 @@ import SkeletonList from '@/features/NavPanel/components/SkeletonList';import { useResourceManagerStore } from '@/features/ResourceManager/store';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { usePermission } from '@/hooks/usePermission';-import { useKnowledgeBaseStore } from '@/store/library';+import { knowledgeBaseSelectors, useKnowledgeBaseStore } from '@/store/library';import Item from './Item';import { getLibraryListAsyncState } from './state';@@ -29,15 +29,14 @@ const LibraryList = memo(() => {const visibility = listVisibility === 'private' ? ('private' as const) : ('public' as const);const useFetchKnowledgeBaseList = useKnowledgeBaseStore((s) => s.useFetchKnowledgeBaseList);- // `isValidating` catches the first fetch after switching mode — SWR's key- // has no cache yet, and because `useFetchKnowledgeBaseList` sets- // `fallbackData: []`, `isLoading` collapses to false immediately. Without- // this, the sidebar flashes the empty state for the network round-trip- // before the real list arrives.- // `fallbackData: []` keeps `data` an array even on failure, so a failed KB-list- // fetch used to render the "create your first library" empty (Read §1.1- // failure-as-empty). Read `error` / `mutate` and branch the failure before empty.- const { data, isLoading, isValidating, error, mutate } = useFetchKnowledgeBaseList(visibility);+ // The rows are read from the local-first replica view, the hook only reports+ // the sync flags. `!isHydrated` covers the window before the persisted row is+ // read and `isValidating` the first network round-trip, so the sidebar shows+ // the skeleton instead of flashing the empty state for the round-trip.+ // A failed KB-list fetch must branch to the error state before empty (Read+ // §1.1 failure-as-empty): read `error` / `revalidate` and branch first.+ const { error, isHydrated, isValidating, revalidate } = useFetchKnowledgeBaseList(visibility);+ const data = useKnowledgeBaseStore(knowledgeBaseSelectors.getKnowledgeBaseList(visibility));const navigate = useWorkspaceAwareNavigate();@@ -57,7 +56,7 @@ const LibraryList = memo(() => {boundaryData,isEmpty,isLoading: showSkeleton,- } = getLibraryListAsyncState({ data, isLoading, isValidating });+ } = getLibraryListAsyncState({ data, isLoading: !isHydrated, isValidating });return (<AsyncBoundary@@ -76,7 +75,7 @@ const LibraryList = memo(() => {onClick={handleCreate}/>}- onRetry={() => mutate()}+ onRetry={() => revalidate()}><Flexbox gap={1} paddingInline={4}>{data?.map((item) => (@@ -86,9 +85,9 @@ const LibraryList = memo(() => {key={item.id}memberRestricted={(item as { memberRestricted?: boolean }).memberRestricted}name={item.name}+ permissionManageable={(item as { permissionManageable?: boolean }).permissionManageable}userId={item.userId}visibility={item.visibility}- permissionManageable={(item as { permissionManageable?: boolean }).permissionManageable}/>))}</Flexbox>diff --git a/src/features/ResourceLibrary/Layout/Header/LibraryHead.tsx b/src/features/ResourceLibrary/Layout/Header/LibraryHead.tsxindex e9fc7aabc54..49436b9b65e 100644--- a/src/features/ResourceLibrary/Layout/Header/LibraryHead.tsx+++ b/src/features/ResourceLibrary/Layout/Header/LibraryHead.tsx@@ -47,7 +47,9 @@ const Head = memo<{ id: string }>(({ id }) => {const [isDropZoneActive, setIsDropZoneActive] = useState(false);const useFetchKnowledgeBaseList = useKnowledgeBaseStore((s) => s.useFetchKnowledgeBaseList);- const { data: libraries } = useFetchKnowledgeBaseList();+ // Fetch orchestration only; the rows are read from the replica view below.+ useFetchKnowledgeBaseList();+ const libraries = useKnowledgeBaseStore(knowledgeBaseSelectors.getKnowledgeBaseList());const activeLibrary = libraries?.find((library) => library.id === id) as(NonNullable<typeof libraries>[number] & { memberRestricted?: boolean }) | undefined;diff --git a/src/features/ResourceManager/components/KnowledgeBaseListProvider.tsx b/src/features/ResourceManager/components/KnowledgeBaseListProvider.tsxindex ce606712144..57b24ed341d 100644--- a/src/features/ResourceManager/components/KnowledgeBaseListProvider.tsx+++ b/src/features/ResourceManager/components/KnowledgeBaseListProvider.tsx@@ -3,16 +3,18 @@import type { PropsWithChildren } from 'react';import { createContext, memo, use, useMemo } from 'react';-import { useKnowledgeBaseStore } from '@/store/library';+import { knowledgeBaseSelectors, useKnowledgeBaseStore } from '@/store/library';import type { KnowledgeBaseItem } from '@/types/knowledgeBase';const KnowledgeBaseListContext = createContext<KnowledgeBaseItem[] | null>(null);export const KnowledgeBaseListProvider = memo<PropsWithChildren>(({ children }) => {const useFetchKnowledgeBaseList = useKnowledgeBaseStore((s) => s.useFetchKnowledgeBaseList);- const { data } = useFetchKnowledgeBaseList();+ // Fetch orchestration only; the rows are read from the replica view below.+ useFetchKnowledgeBaseList();- const knowledgeBases = useMemo(() => data ?? [], [data]);+ const list = useKnowledgeBaseStore(knowledgeBaseSelectors.getKnowledgeBaseList());+ const knowledgeBases = useMemo(() => list ?? [], [list]);return <KnowledgeBaseListContext value={knowledgeBases}>{children}</KnowledgeBaseListContext>;});diff --git a/src/features/ResourceManager/hooks/useKnowledgeItem.ts b/src/features/ResourceManager/hooks/useKnowledgeItem.tsindex 18429fbb5db..ec6ca3453b9 100644--- a/src/features/ResourceManager/hooks/useKnowledgeItem.ts+++ b/src/features/ResourceManager/hooks/useKnowledgeItem.ts@@ -1,7 +1,29 @@-import { useKnowledgeBaseStore } from '@/store/library';+import { knowledgeBaseSelectors, useKnowledgeBaseStore } from '@/store/library';+import type { KnowledgeBaseItem } from '@/types/knowledgeBase';-export const useKnowledgeBaseItem = (id: string) => {+export interface KnowledgeBaseItemState {+ data: KnowledgeBaseItem | undefined;+ error: unknown;+ isLoading: boolean;+ mutate: () => Promise<unknown>;+}++/**+ * Resolve one KB by id for the route layout / permission page. The value is+ * read from the `knowledgeBaseItem` replica view (never from the fetch result);+ * the hook only starts the hydrate + network sync and reports its flags.+ *+ * `isLoading` stays true until the first sync settles, so the route keeps its+ * loading skeleton instead of flashing a "not found" before the fetch lands.+ */+export const useKnowledgeBaseItem = (id: string): KnowledgeBaseItemState => {const useFetchKnowledgeBaseItem = useKnowledgeBaseStore((s) => s.useFetchKnowledgeBaseItem);+ const sync = useFetchKnowledgeBaseItem(id);+ const data = useKnowledgeBaseStore(knowledgeBaseSelectors.getKnowledgeBaseById(id));++ const active = !!id;+ const isLoading =+ active && data === undefined && (sync.error ? false : !sync.isHydrated || sync.isValidating);- return useFetchKnowledgeBaseItem(id);+ return { data, error: sync.error, isLoading, mutate: sync.revalidate };};diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex bde6f9bd2e7..7e7fa4ad3d8 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -721,18 +721,6 @@ export const ragEvalKeys = {]),};-// ---- knowledge base ------------------------------------------------------export const knowledgeBaseKeys = {- item: def('knowledgeBase:item', (id: string) => ['knowledgeBase:item', id]),- list: def(- 'knowledgeBase:list',- (workspaceId?: string | null, visibility?: 'private' | 'public') => {- const base = workspaceId ? ['knowledgeBase:list', workspaceId] : ['knowledgeBase:list'];- return visibility ? [...base, visibility] : base;- },- ),-};-// ---- device -------------------------------------------------------------export const trashKeys = {countByType: def('trash:countByType', () => ['trash:countByType']),@@ -1475,7 +1463,6 @@ export const swrKeys = {image: imageKeys,imessage: imessageKeys,inbox: inboxKeys,- knowledgeBase: knowledgeBaseKeys,localFile: localFileKeys,message: messageKeys,messenger: messengerKeys,diff --git a/src/store/library/slices/crud/action.test.ts b/src/store/library/slices/crud/action.test.tsindex 34435a1429e..6992adcd9b7 100644--- a/src/store/library/slices/crud/action.test.ts+++ b/src/store/library/slices/crud/action.test.ts@@ -1,506 +1,331 @@+/**+ * @vitest-environment happy-dom+ *+ * The knowledge-base list and the by-id projection are replicas: they paint+ * from the persisted copy on the first frame, the network only confirms, and a+ * rename or delete reaches every loaded copy at once.+ */+import { randomUUID } from 'node:crypto';+import { act, 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 { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';-import { mutate } from '@/libs/swr';-import { knowledgeBaseKeys } from '@/libs/swr/keys';+import { cacheScope } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';import { knowledgeBaseService } from '@/services/knowledgeBase';-import type { CreateKnowledgeBaseParams, KnowledgeBaseItem } from '@/types/knowledgeBase';-import { withSWR } from '~test-utils';+import type { KnowledgeBaseItem } from '@/types/knowledgeBase';import { useKnowledgeBaseStore } from '../../store';+import { initialKnowledgeBaseState } from './initialState';+import { knowledgeBaseItemResource, knowledgeBaseListResource } from './projection';+import { knowledgeBaseSelectors } from './selectors';-const mocks = vi.hoisted(() => ({- activeWorkspaceId: null as string | null,-}));+const mocks = vi.hoisted(() => ({ activeWorkspaceId: null as string | null }));vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({- getActiveWorkspaceId: vi.fn(() => mocks.activeWorkspaceId),- useActiveWorkspaceId: vi.fn(() => mocks.activeWorkspaceId),+ getActiveWorkspaceId: () => mocks.activeWorkspaceId,+ useActiveWorkspaceId: () => mocks.activeWorkspaceId,}));-vi.mock('@/libs/swr', async (importOriginal) => {- const modules = await importOriginal();- return {- ...(modules as any),- mutate: vi.fn(),- };-});--vi.mock('swr', async (importOriginal) => {- const modules = await importOriginal();- return {- ...(modules as any),- mutate: vi.fn(),- };-});+vi.mock('@/services/knowledgeBase', () => ({+ knowledgeBaseService: {+ createKnowledgeBase: vi.fn(),+ deleteKnowledgeBase: vi.fn(),+ getKnowledgeBaseById: vi.fn(),+ getKnowledgeBaseList: vi.fn(),+ publishKnowledgeBaseToWorkspace: vi.fn(),+ setKnowledgeBaseVisibility: vi.fn(),+ updateKnowledgeBaseList: vi.fn(),+ },+}));-beforeEach(() => {- vi.clearAllMocks();- mocks.activeWorkspaceId = null;-- useKnowledgeBaseStore.setState(- {- activeKnowledgeBaseId: null,- activeKnowledgeBaseItems: {},- initKnowledgeBaseList: false,- knowledgeBaseLoadingIds: [],- knowledgeBaseRenamingId: null,- },- false,+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,);-});--afterEach(() => {- vi.restoreAllMocks();-});--describe('KnowledgeBaseCrudAction', () => {- describe('createNewKnowledgeBase', () => {- it('should create knowledge base and refresh list', async () => {- const params: CreateKnowledgeBaseParams = {- name: 'Test KB',- description: 'Test Description',- };-- vi.spyOn(knowledgeBaseService, 'createKnowledgeBase').mockResolvedValue('new-kb-id');- const { result } = renderHook(() => useKnowledgeBaseStore());- const refreshSpy = vi.spyOn(result.current, 'refreshKnowledgeBaseList').mockResolvedValue();-- const id = await act(async () => {- return await result.current.createNewKnowledgeBase(params);- });+const item = (id: string, name = id): KnowledgeBaseItem =>+ ({+ avatar: null,+ createdAt: new Date(0),+ id,+ isPublic: null,+ name,+ settings: {},+ type: 'file',+ updatedAt: new Date(0),+ }) as KnowledgeBaseItem;++/** Never-resolving fetch: the first frame can only come from storage. */+const pending = () => new Promise<never>(() => {});++const list = (visibility?: 'private' | 'public') =>+ useKnowledgeBaseStore.getState().knowledgeBaseListMap[visibility ?? 'all'];++const detail = (id: string) =>+ knowledgeBaseSelectors.getKnowledgeBaseById(id)(useKnowledgeBaseStore.getState());++const LIST_ALL_STORAGE_KEY = knowledgeBaseListResource.storageKey({ visibility: undefined });+const LIST_PRIVATE_STORAGE_KEY = knowledgeBaseListResource.storageKey({ visibility: 'private' });+const listStorageKeys = [LIST_ALL_STORAGE_KEY, LIST_PRIVATE_STORAGE_KEY, 'public'];+const itemStorageKeys = ['kb-1', 'kb-9', 'p1', 'kb-gone'];++describe('knowledgeBase crud replicas', () => {+ 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);+ };- expect(knowledgeBaseService.createKnowledgeBase).toHaveBeenCalledWith(params);- expect(refreshSpy).toHaveBeenCalled();- expect(id).toBe('new-kb-id');- });+ beforeEach(() => {+ mocks.activeWorkspaceId = null;+ useScope(`kb-user-${randomUUID()}:personal`);+ act(() => useKnowledgeBaseStore.setState(initialKnowledgeBaseState));+ });- it('should handle errors during creation', async () => {- const params: CreateKnowledgeBaseParams = {- name: 'Test KB',- };+ afterEach(async () => {+ await Promise.all(+ [...scopes].flatMap((scope) => [+ ...listStorageKeys.map((queryKey) =>+ knowledgeBaseListResource.storage!.remove({ queryKey, scope }),+ ),+ ...itemStorageKeys.map((queryKey) =>+ knowledgeBaseItemResource.storage!.remove({ queryKey, scope }),+ ),+ ]),+ );+ scopes.clear();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });- const error = new Error('Creation failed');- vi.spyOn(knowledgeBaseService, 'createKnowledgeBase').mockRejectedValue(error);+ describe('reads', () => {+ it('paints the persisted list before the network answers', async () => {+ await knowledgeBaseListResource.storage!.set(+ { queryKey: LIST_PRIVATE_STORAGE_KEY, scope },+ { data: [item('kb-1', 'Cached')], updatedAt: 1 },+ );+ vi.mocked(knowledgeBaseService.getKnowledgeBaseList).mockImplementation(pending);- const { result } = renderHook(() => useKnowledgeBaseStore());+ const sync = renderHook(+ () => useKnowledgeBaseStore((s) => s.useFetchKnowledgeBaseList)('private'),+ { wrapper },+ );+ const view = renderHook(() =>+ useKnowledgeBaseStore(knowledgeBaseSelectors.getKnowledgeBaseList('private')),+ );- await expect(- act(async () => {- await result.current.createNewKnowledgeBase(params);- }),- ).rejects.toThrow('Creation failed');+ await waitFor(() => expect(view.result.current?.map((kb) => kb.name)).toEqual(['Cached']));+ expect(sync.result.current.isHydrated).toBe(true);+ expect(sync.result.current.isValidating).toBe(true);});- });- describe('internal_toggleKnowledgeBaseLoading', () => {- it('should add id to loading state when loading is true', () => {- const { result } = renderHook(() => useKnowledgeBaseStore());+ it('replaces the list with the server response and persists it', async () => {+ vi.mocked(knowledgeBaseService.getKnowledgeBaseList).mockResolvedValue([+ item('kb-1', 'Server'),+ ] as any);- act(() => {- result.current.internal_toggleKnowledgeBaseLoading('kb-1', true);+ renderHook(() => useKnowledgeBaseStore((s) => s.useFetchKnowledgeBaseList)('private'), {+ wrapper,});- expect(result.current.knowledgeBaseLoadingIds).toContain('kb-1');- });-- it('should remove id from loading state when loading is false', () => {- act(() => {- useKnowledgeBaseStore.setState({- knowledgeBaseLoadingIds: ['kb-1', 'kb-2'],+ await waitFor(() => expect(list('private')?.[0]?.name).toBe('Server'));+ await waitFor(async () => {+ const cached = await knowledgeBaseListResource.storage!.get({+ queryKey: LIST_PRIVATE_STORAGE_KEY,+ scope,});+ expect(cached?.data.map((kb) => kb.id)).toEqual(['kb-1']);});-- const { result } = renderHook(() => useKnowledgeBaseStore());-- act(() => {- result.current.internal_toggleKnowledgeBaseLoading('kb-1', false);- });-- expect(result.current.knowledgeBaseLoadingIds).not.toContain('kb-1');- expect(result.current.knowledgeBaseLoadingIds).toContain('kb-2');});- it('should handle multiple toggle operations', () => {- const { result } = renderHook(() => useKnowledgeBaseStore());+ it('keeps the private and workspace surfaces apart', async () => {+ vi.mocked(knowledgeBaseService.getKnowledgeBaseList).mockImplementation(+ async (visibility?: 'private' | 'public') =>+ (visibility === 'private' ? [item('p1', 'Private')] : [item('w1', 'Workspace')]) as any,+ );- act(() => {- result.current.internal_toggleKnowledgeBaseLoading('kb-1', true);- result.current.internal_toggleKnowledgeBaseLoading('kb-2', true);- result.current.internal_toggleKnowledgeBaseLoading('kb-3', true);+ renderHook(() => useKnowledgeBaseStore((s) => s.useFetchKnowledgeBaseList)('private'), {+ wrapper,});-- expect(result.current.knowledgeBaseLoadingIds).toEqual(['kb-1', 'kb-2', 'kb-3']);-- act(() => {- result.current.internal_toggleKnowledgeBaseLoading('kb-2', false);+ renderHook(() => useKnowledgeBaseStore((s) => s.useFetchKnowledgeBaseList)('public'), {+ wrapper,});- expect(result.current.knowledgeBaseLoadingIds).toEqual(['kb-1', 'kb-3']);- });- });-- describe('refreshKnowledgeBaseList', () => {- it('should execute refresh without errors', async () => {- const { result } = renderHook(() => useKnowledgeBaseStore());-- await expect(- act(async () => {- await result.current.refreshKnowledgeBaseList();- }),- ).resolves.not.toThrow();-- expect(mutate).toHaveBeenCalledWith(knowledgeBaseKeys.list());+ await waitFor(() => expect(list('private')).toHaveLength(1));+ await waitFor(() => expect(list('public')).toHaveLength(1));+ expect(list('private')![0].name).toBe('Private');+ expect(list('public')![0].name).toBe('Workspace');});- it('should refresh the active workspace-scoped cache key', async () => {- mocks.activeWorkspaceId = 'workspace-1';- const { result } = renderHook(() => useKnowledgeBaseStore());+ it('lands a KB fetched by id in the by-id projection', async () => {+ vi.mocked(knowledgeBaseService.getKnowledgeBaseById).mockResolvedValue(+ item('kb-9', 'Detail') as any,+ );- await act(async () => {- await result.current.refreshKnowledgeBaseList();+ renderHook(() => useKnowledgeBaseStore((s) => s.useFetchKnowledgeBaseItem)('kb-9'), {+ wrapper,});- expect(mutate).toHaveBeenCalledWith(knowledgeBaseKeys.list('workspace-1'));- expect(getActiveWorkspaceId).toHaveBeenCalled();+ await waitFor(() => expect(detail('kb-9')?.name).toBe('Detail'));+ expect(+ knowledgeBaseSelectors.getKnowledgeBaseNameById('kb-9')(useKnowledgeBaseStore.getState()),+ ).toBe('Detail');+ expect(useKnowledgeBaseStore.getState().activeKnowledgeBaseId).toBe('kb-9');});- });- describe('removeKnowledgeBase', () => {- it('should delete knowledge base and refresh list', async () => {- vi.spyOn(knowledgeBaseService, 'deleteKnowledgeBase').mockResolvedValue(undefined as any);+ it('drops the cached by-id detail when the server reports it missing', async () => {+ // A detail persisted by an earlier session (or another tab).+ await knowledgeBaseItemResource.storage!.set(+ { queryKey: 'kb-gone', scope },+ { data: item('kb-gone', 'Cached') as any, updatedAt: 1 },+ );- const { result } = renderHook(() => useKnowledgeBaseStore());- const refreshSpy = vi.spyOn(result.current, 'refreshKnowledgeBaseList').mockResolvedValue();+ // The record was deleted elsewhere: the by-id fetch confirms the miss.+ vi.mocked(knowledgeBaseService.getKnowledgeBaseById).mockResolvedValue(undefined as any);- await act(async () => {- await result.current.removeKnowledgeBase('kb-to-delete');+ renderHook(() => useKnowledgeBaseStore((s) => s.useFetchKnowledgeBaseItem)('kb-gone'), {+ wrapper,});- expect(knowledgeBaseService.deleteKnowledgeBase).toHaveBeenCalledWith('kb-to-delete');- expect(refreshSpy).toHaveBeenCalled();- });-- it('should handle errors during deletion', async () => {- const error = new Error('Deletion failed');- vi.spyOn(knowledgeBaseService, 'deleteKnowledgeBase').mockRejectedValue(error);-- const { result } = renderHook(() => useKnowledgeBaseStore());-- await expect(- act(async () => {- await result.current.removeKnowledgeBase('kb-id');- }),- ).rejects.toThrow('Deletion failed');+ // The stale cached row must not keep the route on a resolved detail.+ await waitFor(() => expect(detail('kb-gone')).toBeUndefined());+ expect(knowledgeBaseService.getKnowledgeBaseById).toHaveBeenCalledWith('kb-gone');});});- describe('updateKnowledgeBase', () => {- it('should update knowledge base with loading states', async () => {- const updateParams: CreateKnowledgeBaseParams = {- name: 'Updated KB',- description: 'Updated Description',- };-- vi.spyOn(knowledgeBaseService, 'updateKnowledgeBaseList').mockResolvedValue(undefined as any);-- const { result } = renderHook(() => useKnowledgeBaseStore());- const toggleLoadingSpy = vi.spyOn(result.current, 'internal_toggleKnowledgeBaseLoading');- const refreshSpy = vi.spyOn(result.current, 'refreshKnowledgeBaseList').mockResolvedValue();-- await act(async () => {- await result.current.updateKnowledgeBase('kb-1', updateParams);+ describe('mutations', () => {+ /** Load `private` (and `all`) with two rows so the write paths have a target. */+ const seedList = async (items: KnowledgeBaseItem[] = [item('p1', 'Original'), item('p2')]) => {+ vi.mocked(knowledgeBaseService.getKnowledgeBaseList).mockResolvedValue(items as any);+ renderHook(() => useKnowledgeBaseStore((s) => s.useFetchKnowledgeBaseList)('private'), {+ wrapper,});+ await waitFor(() => expect(list('private')).toHaveLength(items.length));+ };- expect(toggleLoadingSpy).toHaveBeenCalledWith('kb-1', true);- expect(knowledgeBaseService.updateKnowledgeBaseList).toHaveBeenCalledWith(- 'kb-1',- updateParams,- );- expect(refreshSpy).toHaveBeenCalled();- expect(toggleLoadingSpy).toHaveBeenCalledWith('kb-1', false);- });+ it('removes a KB optimistically and rolls the row back when the delete fails', async () => {+ await seedList();- it('should toggle loading off even if update fails', async () => {- const error = new Error('Update failed');- vi.spyOn(knowledgeBaseService, 'updateKnowledgeBaseList').mockRejectedValue(error);-- const { result } = renderHook(() => useKnowledgeBaseStore());- const toggleLoadingSpy = vi.spyOn(result.current, 'internal_toggleKnowledgeBaseLoading');-- await expect(- act(async () => {- await result.current.updateKnowledgeBase('kb-1', { name: 'Test' });- }),- ).rejects.toThrow('Update failed');-- expect(toggleLoadingSpy).toHaveBeenCalledWith('kb-1', true);- // The false toggle won't be called because the error interrupts the flow- });- });-- describe('useFetchKnowledgeBaseItem', () => {- it('should fetch knowledge base item by id', async () => {- const mockItem: KnowledgeBaseItem = {- id: 'kb-1',- name: 'Test KB',- description: 'Test Description',- avatar: 'avatar-url',- type: 'file',- enabled: true,- isPublic: false,- settings: {},- createdAt: new Date(),- updatedAt: new Date(),- };-- vi.spyOn(knowledgeBaseService, 'getKnowledgeBaseById').mockResolvedValue(mockItem);-- const { result } = renderHook(- () => useKnowledgeBaseStore().useFetchKnowledgeBaseItem('kb-1'),- {- wrapper: withSWR,- },+ let reject!: (error: unknown) => void;+ vi.mocked(knowledgeBaseService.deleteKnowledgeBase).mockImplementation(+ () => new Promise((_resolve, rej) => (reject = rej)) as any,);- await waitFor(() => {- expect(result.current.data).toEqual(mockItem);- });-- expect(knowledgeBaseService.getKnowledgeBaseById).toHaveBeenCalledWith('kb-1');- });+ const operation = useKnowledgeBaseStore.getState().removeKnowledgeBase('p1');- it('should update store state on successful fetch', async () => {- const mockItem: KnowledgeBaseItem = {- id: 'kb-2',- name: 'Another KB',- description: 'Another Description',- avatar: 'avatar-url-2',- type: 'file',- enabled: true,- isPublic: false,- settings: {},- createdAt: new Date(),- updatedAt: new Date(),- };-- vi.spyOn(knowledgeBaseService, 'getKnowledgeBaseById').mockResolvedValue(mockItem);-- const { result } = renderHook(- () => useKnowledgeBaseStore().useFetchKnowledgeBaseItem('kb-2'),- {- wrapper: withSWR,- },- );+ await waitFor(() => expect(list('private')?.map((kb) => kb.id)).toEqual(['p2']));- await waitFor(() => {- expect(result.current.data).toEqual(mockItem);- });+ reject(new Error('boom'));+ await expect(operation).rejects.toThrow('boom');- const state = useKnowledgeBaseStore.getState();- expect(state.activeKnowledgeBaseId).toBe('kb-2');- expect(state.activeKnowledgeBaseItems['kb-2']).toEqual(mockItem);+ expect(list('private')?.map((kb) => kb.id)).toEqual(['p1', 'p2']);});- it('should not update store when item is undefined', async () => {- vi.spyOn(knowledgeBaseService, 'getKnowledgeBaseById').mockResolvedValue(undefined);-- act(() => {- useKnowledgeBaseStore.setState({- activeKnowledgeBaseId: 'original-id',- activeKnowledgeBaseItems: {},- });+ it('renames across the list and the by-id copy optimistically, then reconciles', async () => {+ await seedList();+ vi.mocked(knowledgeBaseService.getKnowledgeBaseById).mockResolvedValue(item('p1') as any);+ renderHook(() => useKnowledgeBaseStore((s) => s.useFetchKnowledgeBaseItem)('p1'), {+ wrapper,});+ await waitFor(() => expect(detail('p1')).toBeDefined());- const { result } = renderHook(- () => useKnowledgeBaseStore().useFetchKnowledgeBaseItem('kb-3'),- {- wrapper: withSWR,- },+ let resolve!: (value: unknown) => void;+ vi.mocked(knowledgeBaseService.updateKnowledgeBaseList).mockImplementation(+ () => new Promise((res) => (resolve = res)) as any,);- await waitFor(() => {- expect(result.current.data).toBeUndefined();+ const operation = useKnowledgeBaseStore.getState().updateKnowledgeBase('p1', {+ name: 'Renamed',});- const state = useKnowledgeBaseStore.getState();- expect(state.activeKnowledgeBaseId).toBe('original-id');- expect(state.activeKnowledgeBaseItems).toEqual({});- });+ // Both loaded copies show the new name before the server answers.+ expect(list('private')?.find((kb) => kb.id === 'p1')?.name).toBe('Renamed');+ expect(detail('p1')?.name).toBe('Renamed');+ expect(useKnowledgeBaseStore.getState().knowledgeBaseLoadingIds).toContain('p1');- it('should preserve existing items when updating', async () => {- const existingItem: KnowledgeBaseItem = {- id: 'kb-existing',- name: 'Existing KB',- description: 'Existing',- avatar: 'avatar-existing',- type: 'file',- enabled: true,- isPublic: false,- settings: {},- createdAt: new Date(),- updatedAt: new Date(),- };-- const newItem: KnowledgeBaseItem = {- id: 'kb-new',- name: 'New KB',- description: 'New',- avatar: 'avatar-new',- type: 'file',- enabled: true,- isPublic: false,- settings: {},- createdAt: new Date(),- updatedAt: new Date(),- };-- act(() => {- useKnowledgeBaseStore.setState({- activeKnowledgeBaseItems: {- 'kb-existing': existingItem,- },- });- });-- vi.spyOn(knowledgeBaseService, 'getKnowledgeBaseById').mockResolvedValue(newItem);-- const { result } = renderHook(- () => useKnowledgeBaseStore().useFetchKnowledgeBaseItem('kb-new'),- {- wrapper: withSWR,- },- );-- await waitFor(() => {- expect(result.current.data).toEqual(newItem);+ // The refresh that follows the write sees the server's new state.+ vi.mocked(knowledgeBaseService.getKnowledgeBaseList).mockResolvedValue([+ item('p1', 'Renamed'),+ item('p2'),+ ] as any);+ await act(async () => {+ resolve(undefined);+ await operation;});- const state = useKnowledgeBaseStore.getState();- expect(state.activeKnowledgeBaseItems['kb-existing']).toEqual(existingItem);- expect(state.activeKnowledgeBaseItems['kb-new']).toEqual(newItem);+ expect(list('private')?.find((kb) => kb.id === 'p1')?.name).toBe('Renamed');+ expect(useKnowledgeBaseStore.getState().knowledgeBaseLoadingIds).not.toContain('p1');});- });- describe('useFetchKnowledgeBaseList', () => {- it('should fetch knowledge base list with default config', async () => {- const mockList: KnowledgeBaseItem[] = [- {- id: 'kb-1',- name: 'KB 1',- description: 'Description 1',- avatar: 'avatar-1',- type: 'file',- enabled: true,- isPublic: false,- settings: {},- createdAt: new Date(),- updatedAt: new Date(),- },- {- id: 'kb-2',- name: 'KB 2',- description: 'Description 2',- avatar: 'avatar-2',- type: 'file',- enabled: false,- isPublic: false,- settings: {},- createdAt: new Date(),- updatedAt: new Date(),- },- ];-- vi.spyOn(knowledgeBaseService, 'getKnowledgeBaseList').mockResolvedValue(mockList);-- const { result } = renderHook(() => useKnowledgeBaseStore().useFetchKnowledgeBaseList(), {- wrapper: withSWR,- });+ it('rolls the rename back and clears the loading flag when the write fails', async () => {+ await seedList();+ vi.mocked(knowledgeBaseService.updateKnowledgeBaseList).mockRejectedValue(new Error('boom'));- await waitFor(() => {- expect(result.current.data).toEqual(mockList);- });+ await expect(+ useKnowledgeBaseStore.getState().updateKnowledgeBase('p1', { name: 'Renamed' }),+ ).rejects.toThrow('boom');- expect(knowledgeBaseService.getKnowledgeBaseList).toHaveBeenCalled();+ expect(list('private')?.find((kb) => kb.id === 'p1')?.name).toBe('Original');+ expect(useKnowledgeBaseStore.getState().knowledgeBaseLoadingIds).not.toContain('p1');});- it('should use fallback data when service returns empty', async () => {- vi.spyOn(knowledgeBaseService, 'getKnowledgeBaseList').mockResolvedValue([]);-- const { result } = renderHook(() => useKnowledgeBaseStore().useFetchKnowledgeBaseList(), {- wrapper: withSWR,- });+ it('creates a KB and reconciles the list from the server', async () => {+ await seedList();+ vi.mocked(knowledgeBaseService.createKnowledgeBase).mockResolvedValue('kb-new' as any);+ vi.mocked(knowledgeBaseService.getKnowledgeBaseList).mockResolvedValue([+ item('kb-new', 'Fresh'),+ item('p1', 'Original'),+ item('p2'),+ ] as any);++ const id = await act(() =>+ useKnowledgeBaseStore.getState().createNewKnowledgeBase({ name: 'Fresh' }),+ );- // Wait for the SWR hook to settle- await waitFor(() => {- expect(result.current.data).toEqual([]);- });+ expect(id).toBe('kb-new');+ expect(knowledgeBaseService.createKnowledgeBase).toHaveBeenCalledWith({ name: 'Fresh' });+ await waitFor(() => expect(list('private')?.[0]?.id).toBe('kb-new'));});- it('should initialize knowledge base list on first success', async () => {- const mockList: KnowledgeBaseItem[] = [- {- id: 'kb-1',- name: 'KB 1',- description: 'Description 1',- avatar: 'avatar-1',- type: 'file',- enabled: true,- isPublic: false,- settings: {},- createdAt: new Date(),- updatedAt: new Date(),- },- ];-- // Ensure initKnowledgeBaseList is false initially- act(() => {- useKnowledgeBaseStore.setState({- initKnowledgeBaseList: false,- });- });-- vi.spyOn(knowledgeBaseService, 'getKnowledgeBaseList').mockResolvedValue(mockList);-- const { result } = renderHook(() => useKnowledgeBaseStore().useFetchKnowledgeBaseList(), {- wrapper: withSWR,- });+ it('publishes and flips visibility through the server, then refreshes', async () => {+ await seedList();+ vi.mocked(knowledgeBaseService.publishKnowledgeBaseToWorkspace).mockResolvedValue(+ undefined as any,+ );+ vi.mocked(knowledgeBaseService.setKnowledgeBaseVisibility).mockResolvedValue(+ undefined as any,+ );- // Wait for the SWR hook to settle and onSuccess to be called- await waitFor(() => {- expect(result.current.data).toEqual(mockList);- });+ await act(() => useKnowledgeBaseStore.getState().publishKnowledgeBaseToWorkspace('p1'));+ await act(() => useKnowledgeBaseStore.getState().setKnowledgeBaseVisibility('p1', 'private'));- // Verify initKnowledgeBaseList is set to true after onSuccess- await waitFor(() => {- const state = useKnowledgeBaseStore.getState();- expect(state.initKnowledgeBaseList).toBe(true);- });+ expect(knowledgeBaseService.publishKnowledgeBaseToWorkspace).toHaveBeenCalledWith('p1');+ expect(knowledgeBaseService.setKnowledgeBaseVisibility).toHaveBeenCalledWith('p1', 'private');});- it('should not re-initialize if already initialized', async () => {- const mockList: KnowledgeBaseItem[] = [];-- act(() => {- useKnowledgeBaseStore.setState({- initKnowledgeBaseList: true,- });- });-- vi.spyOn(knowledgeBaseService, 'getKnowledgeBaseList').mockResolvedValue(mockList);-- const { result } = renderHook(() => useKnowledgeBaseStore().useFetchKnowledgeBaseList(), {- wrapper: withSWR,- });-- await waitFor(() => {- expect(result.current.data).toEqual(mockList);- });+ it('toggles the row loading flag', () => {+ act(() => useKnowledgeBaseStore.getState().internal_toggleKnowledgeBaseLoading('p1', true));+ expect(useKnowledgeBaseStore.getState().knowledgeBaseLoadingIds).toContain('p1');- const state = useKnowledgeBaseStore.getState();- expect(state.initKnowledgeBaseList).toBe(true);+ act(() => useKnowledgeBaseStore.getState().internal_toggleKnowledgeBaseLoading('p1', false));+ expect(useKnowledgeBaseStore.getState().knowledgeBaseLoadingIds).not.toContain('p1');});});});diff --git a/src/store/library/slices/crud/action.ts b/src/store/library/slices/crud/action.tsindex c67af8494ed..0d2962a94ef 100644--- a/src/store/library/slices/crud/action.ts+++ b/src/store/library/slices/crud/action.ts@@ -1,27 +1,119 @@-import type { SWRResponse } from 'swr';--import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';-import { mutate, useClientDataSWR } from '@/libs/swr';-import { knowledgeBaseKeys } from '@/libs/swr/keys';+import {+ arrayEntity,+ createReplicaSlice,+ linkReplicaEntity,+ recordLens,+ type ReplicaSyncResult,+ singleEntity,+} from '@/libs/replica';import { knowledgeBaseService } from '@/services/knowledgeBase';import type { KnowledgeBaseStore } from '@/store/library/store';import type { StoreSetter } from '@/store/types';import type { CreateKnowledgeBaseParams, KnowledgeBaseItem } from '@/types/knowledgeBase';+import {+ KNOWLEDGE_BASE_LIST_ALL_KEY,+ knowledgeBaseItemResource,+ knowledgeBaseListResource,+ type KnowledgeBaseVisibility,+} from './projection';+type Setter = StoreSetter<KnowledgeBaseStore>;export const createCrudSlice = (set: Setter, get: () => KnowledgeBaseStore, _api?: unknown) =>new KnowledgeBaseCrudActionImpl(set, get, _api);+/**+ * The knowledge-base domain's read + write slice, on top of two local-first+ * replicas:+ *+ * - `knowledgeBaseList` is the one list per visibility surface+ * (`knowledgeBaseListMap[all|private|public]`). It hydrates from IndexedDB,+ * revalidates over the network and is the only writer of the view.+ * - `knowledgeBaseItem` is the by-id projection (`knowledgeBaseDetailMap[id]`)+ * for a KB that is not in the loaded list (route layout, permission page).+ *+ * Both hold copies of the same KB, so they are linked: a rename or a delete+ * fans out to every loaded copy (and to the persisted rows of entries that are+ * not loaded). Read the values through `knowledgeBaseSelectors`; the two+ * `useFetch*` hooks only orchestrate fetching and return flags.+ */export class KnowledgeBaseCrudActionImpl {readonly #get: () => KnowledgeBaseStore;+ readonly #kbEntity;+ readonly #kbItem;+ readonly #kbList;readonly #set: Setter;constructor(set: Setter, get: () => KnowledgeBaseStore, _api?: unknown) {void _api;this.#set = set;this.#get = get;++ this.#kbList = createReplicaSlice(knowledgeBaseListResource, {+ actionPrefix: 'knowledgeBaseList',+ entity: arrayEntity<KnowledgeBaseItem>((kb) => kb.id),+ get,+ set,+ stateKey: 'knowledgeBaseListReplica',+ view: recordLens<KnowledgeBaseStore, KnowledgeBaseItem[]>('knowledgeBaseListMap'),+ });+ this.#kbItem = createReplicaSlice(knowledgeBaseItemResource, {+ actionPrefix: 'knowledgeBaseItem',+ // The value IS the KB, so entity-level writes (rename, delete) find and+ // map it through this adapter.+ entity: singleEntity<KnowledgeBaseItem>((kb) => kb.id),+ fetcher: async (id) => {+ const item = await knowledgeBaseService.getKnowledgeBaseById(id);+ return item ?? undefined;+ },+ get,+ // A defined response replaces the cached detail. A miss (`undefined`)+ // keeps the cached row here and is cleared in `useFetchKnowledgeBaseItem`+ // once it is known to be authoritative, so a KB deleted on another device+ // does not stay painted on a resolved detail route.+ merge: (incoming) => incoming,+ set,+ stateKey: 'knowledgeBaseDetailReplica',+ view: recordLens<KnowledgeBaseStore, KnowledgeBaseItem>('knowledgeBaseDetailMap'),+ });+ // The same KB lives in the list surfaces and in the by-id projection.+ this.#kbEntity = linkReplicaEntity<KnowledgeBaseItem>([this.#kbList, this.#kbItem]);}+ // ---- reads -------------------------------------------------------------++ /**+ * Fetch orchestration for one KB by id. Hydrates the persisted projection,+ * then revalidates; the row lands in `knowledgeBaseDetailMap[id]` and is read+ * through `knowledgeBaseSelectors.getKnowledgeBaseById`.+ */+ useFetchKnowledgeBaseItem = (id: string): ReplicaSyncResult =>+ this.#kbItem.useSync(id || null, {+ onSuccess: (item) => {+ if (!item) {+ // An authoritative miss: the fetch succeeded but the server no longer+ // has this KB. Drop the persisted detail so `useKnowledgeBaseItem`+ // stops returning the stale row and the route resolves to+ // `<NotFound />` instead of a resolved-but-gone KB.+ if (id) this.#kbItem.remove(id);++ return;+ }++ this.#set({ activeKnowledgeBaseId: id }, false, 'knowledgeBase/itemActive');+ },+ });++ /**+ * Fetch orchestration for one KB list surface. The rows land in+ * `knowledgeBaseListMap[visibility ?? 'all']` — read them through+ * `knowledgeBaseSelectors.getKnowledgeBaseList`.+ */+ useFetchKnowledgeBaseList = (visibility?: KnowledgeBaseVisibility): ReplicaSyncResult =>+ this.#kbList.useSync({ visibility });++ // ---- writes ------------------------------------------------------------+createNewKnowledgeBase = async (params: CreateKnowledgeBaseParams): Promise<string> => {const id = await knowledgeBaseService.createKnowledgeBase(params);@@ -42,25 +134,34 @@ export class KnowledgeBaseCrudActionImpl {);};+ /**+ * Revalidate every list surface (unfiltered / private / workspace) so a+ * mutation is reflected wherever the KB is currently rendered. The sidebar+ * shows one visibility at a time while the switcher and the quick-access row+ * read the unfiltered list, so all three may be on screen.+ */refreshKnowledgeBaseList = async (): Promise<void> => {- const workspaceId = getActiveWorkspaceId();- // The KB list is keyed by (workspaceId, visibility?), so we invalidate the- // three surfaces that can be currently rendered — unscoped, private-only,- // workspace-only — to keep both modes in sync after a mutation.await Promise.all([- mutate(knowledgeBaseKeys.list(workspaceId)),- mutate(knowledgeBaseKeys.list(workspaceId, 'private')),- mutate(knowledgeBaseKeys.list(workspaceId, 'public')),+ this.#kbList.revalidate(KNOWLEDGE_BASE_LIST_ALL_KEY),+ this.#kbList.revalidate('private'),+ this.#kbList.revalidate('public'),]);};removeKnowledgeBase = async (id: string): Promise<void> => {- await knowledgeBaseService.deleteKnowledgeBase(id);+ // One optimistic removal across every loaded list surface; a failed delete+ // rolls them all back together.+ await this.#kbEntity.optimistic(id, 'remove', () =>+ knowledgeBaseService.deleteKnowledgeBase(id),+ );+await this.#get().refreshKnowledgeBaseList();};publishKnowledgeBaseToWorkspace = async (id: string): Promise<void> => {await knowledgeBaseService.publishKnowledgeBaseToWorkspace(id);++ // The row hops from the private surface into the workspace one.await this.#get().refreshKnowledgeBaseList();};@@ -69,52 +170,25 @@ export class KnowledgeBaseCrudActionImpl {visibility: 'private' | 'public',): Promise<void> => {await knowledgeBaseService.setKnowledgeBaseVisibility(id, visibility);+await this.#get().refreshKnowledgeBaseList();};updateKnowledgeBase = async (id: string, value: CreateKnowledgeBaseParams): Promise<void> => {this.#get().internal_toggleKnowledgeBaseLoading(id, true);- await knowledgeBaseService.updateKnowledgeBaseList(id, value);- await this.#get().refreshKnowledgeBaseList();-- this.#get().internal_toggleKnowledgeBaseLoading(id, false);- };-- useFetchKnowledgeBaseItem = (id: string): SWRResponse<KnowledgeBaseItem | undefined> => {- return useClientDataSWR<KnowledgeBaseItem | undefined>(- knowledgeBaseKeys.item(id),- () => knowledgeBaseService.getKnowledgeBaseById(id),- {- onSuccess: (item) => {- if (!item) return;-- this.#set({- activeKnowledgeBaseId: id,- activeKnowledgeBaseItems: {- ...this.#get().activeKnowledgeBaseItems,- [id]: item,- },- });- },- },- );- };-- useFetchKnowledgeBaseList = (- visibility?: 'private' | 'public',- ): SWRResponse<KnowledgeBaseItem[]> => {- const workspaceId = getActiveWorkspaceId();- return useClientDataSWR<KnowledgeBaseItem[]>(- knowledgeBaseKeys.list(workspaceId, visibility),- () => knowledgeBaseService.getKnowledgeBaseList(visibility),- {- fallbackData: [],- onSuccess: () => {- if (!this.#get().initKnowledgeBaseList)- this.#set({ initKnowledgeBaseList: true }, false, 'useFetchKnowledgeBaseList/init');- },- },- );+ try {+ // Show the new name / description in every loaded copy at once, then+ // persist; a failed sync rolls every copy back to the KB it had before.+ await this.#kbEntity.optimistic(+ id,+ (kb) => ({ ...kb, ...value }),+ () => knowledgeBaseService.updateKnowledgeBaseList(id, value),+ );++ await this.#get().refreshKnowledgeBaseList();+ } finally {+ this.#get().internal_toggleKnowledgeBaseLoading(id, false);+ }};}diff --git a/src/store/library/slices/crud/index.ts b/src/store/library/slices/crud/index.tsindex 6bdd1f4b2ef..2f9449bdb81 100644--- a/src/store/library/slices/crud/index.ts+++ b/src/store/library/slices/crud/index.ts@@ -1,3 +1,4 @@export * from './action';export * from './initialState';+export * from './projection';export * from './selectors';diff --git a/src/store/library/slices/crud/initialState.ts b/src/store/library/slices/crud/initialState.tsindex 738c57d8861..ea88c19762c 100644--- a/src/store/library/slices/crud/initialState.ts+++ b/src/store/library/slices/crud/initialState.ts@@ -1,19 +1,28 @@+import { createReplicaState, type ReplicaState } from '@/libs/replica';import { type KnowledgeBaseItem } from '@/types/knowledgeBase';export interface KnowledgeBaseState {activeKnowledgeBaseId: string | null;- activeKnowledgeBaseItems: Record<string, KnowledgeBaseItem>;- initKnowledgeBaseList: boolean;+ /** By-id KB projection (`knowledgeBaseDetailMap[id]`). */+ knowledgeBaseDetailMap: Record<string, KnowledgeBaseItem>;+ /** Local-first bookkeeping for `knowledgeBaseDetailMap`. */+ knowledgeBaseDetailReplica: ReplicaState<KnowledgeBaseItem>;+ /** The KB list per visibility surface (`knowledgeBaseListMap[all|private|public]`). */+ knowledgeBaseListMap: Record<string, KnowledgeBaseItem[]>;+ /** Local-first bookkeeping for `knowledgeBaseListMap`. */+ knowledgeBaseListReplica: ReplicaState<KnowledgeBaseItem[]>;+ /** Ids whose update round-trip is in flight (drives the sidebar row spinner). */knowledgeBaseLoadingIds: string[];+ /** The row currently being renamed inline. */knowledgeBaseRenamingId?: string | null;- knowledgeBaseUpdatingId: string | null;}export const initialKnowledgeBaseState: KnowledgeBaseState = {activeKnowledgeBaseId: null,- activeKnowledgeBaseItems: {},- initKnowledgeBaseList: false,+ knowledgeBaseDetailMap: {},+ knowledgeBaseDetailReplica: createReplicaState(),+ knowledgeBaseListMap: {},+ knowledgeBaseListReplica: createReplicaState(),knowledgeBaseLoadingIds: [],knowledgeBaseRenamingId: null,- knowledgeBaseUpdatingId: null,};diff --git a/src/store/library/slices/crud/projection.ts b/src/store/library/slices/crud/projection.tsnew file mode 100644index 00000000000..2d888d3d59b--- /dev/null+++ b/src/store/library/slices/crud/projection.ts@@ -0,0 +1,58 @@+import { defineReplica } from '@/libs/replica';+import { knowledgeBaseService } from '@/services/knowledgeBase';+import type { KnowledgeBaseItem } from '@/types/knowledgeBase';++/**+ * Workspace-scoped visibility of a KB. `private` rows are visible to their+ * creator only, `public` rows to the whole workspace.+ */+export type KnowledgeBaseVisibility = 'private' | 'public';++/**+ * Entry key of the unfiltered KB list. The sidebar renders exactly one of the+ * `private` / `public` surfaces at a time, while the home quick-access and the+ * library switcher read the unfiltered list — each surface is its own entry so+ * switching the sidebar mode never overwrites the other surface's rows.+ */+export const KNOWLEDGE_BASE_LIST_ALL_KEY = 'all';++export interface KnowledgeBaseListParams {+ visibility?: KnowledgeBaseVisibility;+}++/** Entry identity of one list surface (`all` / `private` / `public`). */+export const knowledgeBaseListKey = (visibility?: KnowledgeBaseVisibility) =>+ visibility ?? KNOWLEDGE_BASE_LIST_ALL_KEY;++/**+ * The KB list. The address is `knowledgeBaseListMap[all|private|public]`; every+ * selector reads it from there and the crud slice is the only writer.+ */+export const knowledgeBaseListResource = defineReplica<+ KnowledgeBaseListParams,+ KnowledgeBaseItem[],+ KnowledgeBaseItem[]+>({+ fetcher: ({ visibility }) => knowledgeBaseService.getKnowledgeBaseList(visibility),+ key: ({ visibility }) => knowledgeBaseListKey(visibility),+ name: 'knowledgeBaseList',+ storage: 'indexedDB',+ version: 1,+});++/**+ * One KB by id (`knowledgeBaseDetailMap[id]`), for a KB that is not in the+ * loaded list (deep link, permission page, route layout). The fetcher answers+ * `undefined` for a KB the server no longer has; the crud slice then drops the+ * cached projection, so the route resolves to `<NotFound />`.+ */+export const knowledgeBaseItemResource = defineReplica<+ string,+ KnowledgeBaseItem,+ KnowledgeBaseItem | undefined+>({+ key: (id) => id,+ name: 'knowledgeBaseItem',+ storage: 'indexedDB',+ version: 1,+});diff --git a/src/store/library/slices/crud/selectors.ts b/src/store/library/slices/crud/selectors.tsindex c6c1686f775..12d0932faed 100644--- a/src/store/library/slices/crud/selectors.ts+++ b/src/store/library/slices/crud/selectors.ts@@ -1,14 +1,30 @@import { type KnowledgeBaseStoreState } from '@/store/library/initialState';+import { knowledgeBaseListKey, type KnowledgeBaseVisibility } from './projection';+const activeKnowledgeBaseId = (s: KnowledgeBaseStoreState) => s.activeKnowledgeBaseId;+/** One KB by id — backed by the `knowledgeBaseItem` replica. */const getKnowledgeBaseById = (id: string) => (s: KnowledgeBaseStoreState) =>- s.activeKnowledgeBaseItems[id];+ s.knowledgeBaseDetailMap[id];const getKnowledgeBaseNameById = (id: string) => (s: KnowledgeBaseStoreState) =>getKnowledgeBaseById(id)(s)?.name;+/** One KB list surface (`all` / `private` / `public`) — backed by the `knowledgeBaseList` replica. */+const getKnowledgeBaseList =+ (visibility?: KnowledgeBaseVisibility) => (s: KnowledgeBaseStoreState) =>+ s.knowledgeBaseListMap[knowledgeBaseListKey(visibility)];++/** Whether a list surface has been read (hydrated or fetched) at least once. */+const isKnowledgeBaseListInit =+ (visibility?: KnowledgeBaseVisibility) => (s: KnowledgeBaseStoreState) =>+ s.knowledgeBaseListMap[knowledgeBaseListKey(visibility)] !== undefined;+export const knowledgeBaseSelectors = {activeKnowledgeBaseId,+ getKnowledgeBaseById,+ getKnowledgeBaseList,getKnowledgeBaseNameById,+ isKnowledgeBaseListInit,};diff --git a/src/store/trash/action.ts b/src/store/trash/action.tsindex f76e5833aea..c0dd02a1534 100644--- a/src/store/trash/action.ts+++ b/src/store/trash/action.ts@@ -27,7 +27,6 @@ const RESTORE_AFFECTED_KEY_PREFIXES = ['group:','home:','image:',- 'knowledgeBase:',// Replicas (topic list, …) sync through `replica:sync` keys (`@lobechat/replica`).'replica:',// conversation transcripts — a restored message must reappear in its thread