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(file): move the file document detail onto @lobechat/replica (#20597)

Arvin Xuf1a0a9f27e95
diff --git a/src/features/ResourceManager/index.tsx b/src/features/ResourceManager/index.tsx
index 61d5b9138a2..df853aa3afd 100644
--- a/src/features/ResourceManager/index.tsx
+++ b/src/features/ResourceManager/index.tsx
@@ -2,7 +2,7 @@
import { Flexbox } from '@lobehub/ui';
import { createStaticStyles, useTheme } from 'antd-style';
-import { memo, type ReactNode, useCallback, useEffect, useMemo } from 'react';
+import { memo, type ReactNode, useCallback, useMemo } from 'react';
import { useSearchParams } from 'react-router';
import DragUploadZone from '@/components/DragUploadZone';
@@ -10,7 +10,6 @@ import { PageEditor } from '@/features/PageEditor';
import { useResourceManagerStore } from '@/features/ResourceManager/store';
import { usePermission } from '@/hooks/usePermission';
import dynamic from '@/libs/next/dynamic';
-import { documentService } from '@/services/document';
import { useFileStore } from '@/store/file';
import { documentSelectors } from '@/store/file/slices/document/selectors';
@@ -78,6 +77,7 @@ const ResourceManager = memo<ResourceManagerProps>(({ content }) => {
const currentDocument = useFileStore(documentSelectors.getDocumentById(currentViewItemId));
const updateDocumentOptimistically = useFileStore((s) => s.updateDocumentOptimistically);
+ const useFetchDocumentDetail = useFileStore((s) => s.useFetchDocumentDetail);
const { allowed: canUpload } = usePermission('create_content');
const uploadTopLevel = useTopLevelFileUpload();
@@ -96,20 +96,12 @@ const ResourceManager = memo<ResourceManagerProps>(({ content }) => {
[theme.colorBgContainerSecondary],
);
- // Fetch specific document when switching to page mode if not already loaded
- useEffect(() => {
- if (mode === 'page' && currentViewItemId && !currentDocument) {
- // Document not in store, fetch it individually
- documentService.getDocumentById(currentViewItemId).then((doc) => {
- if (doc) {
- // Add the document to the store's documents array
- useFileStore.setState((state) => ({
- documents: [...state.documents, doc as any],
- }));
- }
- });
- }
- }, [mode, currentViewItemId, currentDocument]);
+ // Keep the open item's document row in the replica. Deliberately not gated on
+ // `mode`: on a cold `?file=` deep link the page/file decision itself needs the
+ // row, so gating on it would wait for the very network the projection exists
+ // to avoid. The view is read from the store, so a reload paints from the
+ // persisted projection on the first frame and the network only confirms it.
+ useFetchDocumentDetail(currentViewItemId);
const handleBack = () => {
setMode('explorer');
diff --git a/src/store/file/initialState.ts b/src/store/file/initialState.ts
index 06a8c25af29..ef360b21ce0 100644
--- a/src/store/file/initialState.ts
+++ b/src/store/file/initialState.ts
@@ -2,11 +2,11 @@ import { type ImageFileState } from './slices/chat';
import { initialImageFileState } from './slices/chat';
import { type FileChunkState } from './slices/chunk';
import { initialFileChunkState } from './slices/chunk';
-import { type DocumentState } from './slices/document';
-import { initialDocumentState } from './slices/document';
-// Leaf module on purpose: the slice barrel also pulls in `action.ts`, which
+// Leaf modules on purpose: the slice barrel also pulls in `action.ts`, which
// imports this store back — reaching it from here would close the cycle before
// the store is initialized.
+import { type DocumentState } from './slices/document/initialState';
+import { initialDocumentState } from './slices/document/initialState';
import { type FileManagerState } from './slices/fileManager/initialState';
import { initialFileManagerState } from './slices/fileManager/initialState';
import { type ResourceState } from './slices/resource/initialState';
diff --git a/src/store/file/selectors.ts b/src/store/file/selectors.ts
index 02a09c14e10..469357f6ead 100644
--- a/src/store/file/selectors.ts
+++ b/src/store/file/selectors.ts
@@ -5,5 +5,8 @@ export const filesSelectors = {
};
export { fileChatSelectors } from './slices/chat/selectors';
-export { documentSelectors } from './slices/document';
+// Leaf module on purpose: the slice barrel also pulls in `action.ts`, which
+// imports this store back — reaching it from the store entry would close the
+// cycle before the store is initialized.
+export { documentSelectors } from './slices/document/selectors';
export * from './slices/fileManager/selectors';
diff --git a/src/store/file/slices/document/action.test.ts b/src/store/file/slices/document/action.test.ts
index 2a1afa24690..b09c35eeeb9 100644
--- a/src/store/file/slices/document/action.test.ts
+++ b/src/store/file/slices/document/action.test.ts
@@ -1,29 +1,88 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * `file/slices/document` is a by-id replica of the `documents` table: one entry
+ * per document id, persisted per identity scope, so the resource manager paints
+ * the open page from the projection and the network only confirms it. This suite
+ * drives the real sync path (SWR provider + the app's scoped mutate) instead of
+ * poking the store.
+ */
+import { randomUUID } from 'node:crypto';
+
import {
CUSTOM_DOCUMENT_FILE_TYPE,
CUSTOM_FOLDER_FILE_TYPE,
DERIVED_DOCUMENT_SOURCE_TYPE,
} from '@lobechat/const';
-import { act, renderHook } from '@testing-library/react';
+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 { cacheScope } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
import { documentService } from '@/services/document';
import { DocumentSourceType, type LobeDocument } from '@/types/document';
import { type ResourceItem } from '@/types/resource';
-import { useFileStore as useStore } from '../../store';
+import { useFileStore } from '../../store';
import { getResourceQueryKey } from '../resource/utils';
+import { initialDocumentState } from './initialState';
+import { fileDocumentResource } from './projection';
+
+const mocks = vi.hoisted(() => ({ activeWorkspaceId: null as string | null }));
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ getActiveWorkspaceId: () => mocks.activeWorkspaceId,
+ useActiveWorkspaceId: () => mocks.activeWorkspaceId,
+}));
vi.mock('@/services/document', () => ({
documentService: {
createDocument: vi.fn(),
deleteDocument: vi.fn(),
getDocumentById: vi.fn(),
- queryDocuments: vi.fn(),
updateDocument: vi.fn(),
},
}));
-const createDocumentFixture = (overrides: Partial<LobeDocument> = {}): LobeDocument => ({
+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,
+ );
+
+/** A `documents` row as the server returns it. */
+const serverRow = (overrides: Record<string, unknown> = {}) =>
+ ({
+ content: 'Body',
+ createdAt: new Date('2024-01-01T00:00:00.000Z'),
+ editorData: '{}',
+ fileType: CUSTOM_DOCUMENT_FILE_TYPE,
+ filename: 'Old title',
+ id: 'doc-1',
+ metadata: {},
+ parentId: null,
+ slug: null,
+ source: 'document',
+ sourceType: DocumentSourceType.EDITOR,
+ title: 'Old title',
+ totalCharCount: 4,
+ updatedAt: new Date('2024-01-01T00:00:00.000Z'),
+ ...overrides,
+ }) as any;
+
+/** The normalized store shape the replica holds. */
+const lobeDocument = (overrides: Partial<LobeDocument> = {}): LobeDocument => ({
content: 'Body',
createdAt: new Date('2024-01-01T00:00:00.000Z'),
editorData: {},
@@ -35,7 +94,7 @@ const createDocumentFixture = (overrides: Partial<LobeDocument> = {}): LobeDocum
sourceType: DocumentSourceType.EDITOR,
title: 'Old title',
totalCharCount: 4,
- totalLineCount: 1,
+ totalLineCount: 0,
updatedAt: new Date('2024-01-01T00:00:00.000Z'),
...overrides,
});
@@ -58,355 +117,496 @@ const createResourceFixture = (overrides: Partial<ResourceItem> = {}): ResourceI
...overrides,
});
-beforeEach(() => {
- vi.clearAllMocks();
-
- useStore.setState(
- {
- documents: [],
- localDocumentMap: new Map(),
- queryParams: undefined,
- resourceList: [],
- resourceMap: new Map(),
- },
- false,
- );
-});
+/** Never-resolving fetch: the first frame can only come from storage. */
+const pending = <T>() => new Promise<T>(() => {});
-afterEach(() => {
- vi.restoreAllMocks();
-});
+const storedRow = (documentId: string, scope: string) =>
+ fileDocumentResource.storage!.get({ queryKey: documentId, scope });
+
+describe('file document replica', () => {
+ const scopes = new Set<string>();
+ let scope = '';
-describe('DocumentAction', () => {
- it('creates a folder in the current resource list without full revalidation', async () => {
- const { result } = renderHook(() => useStore());
-
- vi.mocked(documentService.createDocument).mockResolvedValue({
- content: '',
- createdAt: new Date('2024-01-01T00:00:00.000Z'),
- editorData: '{}',
- fileType: CUSTOM_FOLDER_FILE_TYPE,
- id: 'folder-1',
- metadata: {},
- parentId: null,
- slug: 'new-folder',
- source: 'document',
- title: 'New Folder',
- totalCharCount: 0,
- updatedAt: new Date('2024-01-01T00:00:00.000Z'),
- } as any);
-
- act(() => {
- useStore.setState(
+ 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);
+ };
+
+ /** Render `useFetchDocumentDetail` the way the resource manager calls it. */
+ const renderDetail = (documentId: string | undefined) =>
+ renderHook(
+ () => {
+ const useFetchDocumentDetail = useFileStore((s) => s.useFetchDocumentDetail);
+
+ return useFetchDocumentDetail(documentId);
+ },
+ { wrapper },
+ );
+
+ beforeEach(() => {
+ mocks.activeWorkspaceId = null;
+ useScope(`file-user-${randomUUID()}:personal`);
+ act(() =>
+ useFileStore.setState(
{
- queryParams: {
- libraryId: 'kb-1',
- parentId: null,
- },
+ ...initialDocumentState,
+ queryParams: undefined,
+ resourceList: [],
+ resourceMap: new Map(),
},
false,
- );
- });
-
- await act(async () => {
- await result.current.createFolder('New Folder', undefined, 'kb-1');
- });
+ ),
+ );
+ vi.mocked(documentService.createDocument).mockReset();
+ vi.mocked(documentService.deleteDocument).mockReset();
+ vi.mocked(documentService.getDocumentById).mockReset();
+ vi.mocked(documentService.updateDocument).mockReset();
+ });
- expect(useStore.getState().resourceList.map((item) => item.id)).toEqual(['folder-1']);
- expect(useStore.getState().resourceMap.get('folder-1')).toMatchObject({
- fileType: CUSTOM_FOLDER_FILE_TYPE,
- id: 'folder-1',
- knowledgeBaseId: 'kb-1',
- name: 'New Folder',
- parentId: null,
- slug: 'new-folder',
- sourceType: DERIVED_DOCUMENT_SOURCE_TYPE,
- title: 'New Folder',
- });
+ afterEach(async () => {
+ await Promise.all(
+ [...scopes].map((value) =>
+ Promise.all(
+ ['doc-1', 'doc-2', 'folder-1'].map((id) =>
+ fileDocumentResource.storage!.remove({ queryKey: id, scope: value }),
+ ),
+ ),
+ ),
+ );
+ scopes.clear();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
});
- it('updates the local document and visible resource after a successful save', async () => {
- const { result } = renderHook(() => useStore());
- const existingDocument = createDocumentFixture();
- const existingResource = createResourceFixture();
+ describe('by-id detail', () => {
+ it('paints the persisted row on the first frame, before the network answers', async () => {
+ const cached = lobeDocument({ content: '# Cached', title: 'Cached' });
+ await fileDocumentResource.storage!.set(
+ { queryKey: 'doc-1', scope },
+ { data: { document: cached }, updatedAt: 1 },
+ );
+ vi.mocked(documentService.getDocumentById).mockImplementation(() => pending());
- vi.mocked(documentService.updateDocument).mockResolvedValue({
- historyAppended: false,
- id: 'doc-1',
- updatedAt: '2026-01-01T00:00:00.000Z',
- });
+ const { result } = renderDetail('doc-1');
- act(() => {
- useStore.setState(
- {
- documents: [existingDocument],
- queryParams: {
- libraryId: 'kb-1',
- parentId: null,
- },
- resourceList: [existingResource],
- resourceMap: new Map([[existingResource.id, existingResource]]),
- },
- false,
+ await waitFor(() =>
+ expect(useFileStore.getState().documentMap['doc-1']).toEqual({ document: cached }),
);
+ expect(result.current.data).toEqual(cached);
+ expect(result.current.isLoading).toBe(false);
+ // The network request is still in flight; the frame did not wait for it.
+ expect(result.current.isValidating).toBe(true);
});
- await act(async () => {
- await result.current.updateDocument('doc-1', {
- metadata: { emoji: 'page' },
- title: 'Renamed title',
+ it('adopts the server row and persists the projection', async () => {
+ vi.mocked(documentService.getDocumentById).mockResolvedValue(
+ serverRow({ content: '# Server', title: 'Server title' }) as any,
+ );
+
+ const { result } = renderDetail('doc-1');
+
+ await waitFor(() =>
+ expect(useFileStore.getState().documentMap['doc-1']?.document?.content).toBe('# Server'),
+ );
+ expect(result.current.data?.title).toBe('Server title');
+ await waitFor(async () => {
+ const stored = await storedRow('doc-1', scope);
+ expect(stored?.data.document?.content).toBe('# Server');
});
});
- expect(documentService.updateDocument).toHaveBeenCalledWith({
- content: undefined,
- editorData: undefined,
- id: 'doc-1',
- metadata: { emoji: 'page' },
- parentId: undefined,
- title: 'Renamed title',
- });
- expect(useStore.getState().localDocumentMap.get('doc-1')).toMatchObject({
- metadata: { emoji: 'page' },
- title: 'Renamed title',
- });
- expect(useStore.getState().resourceMap.get('doc-1')).toMatchObject({
- metadata: { emoji: 'page' },
- name: 'Renamed title',
- title: 'Renamed title',
- });
- });
+ it('resolves a missing document to not found and never persists the marker', async () => {
+ vi.mocked(documentService.getDocumentById).mockResolvedValue(undefined as any);
- it('updates the resource optimistically and clears the marker after sync', async () => {
- const { result } = renderHook(() => useStore());
- const existingDocument = createDocumentFixture();
- const existingResource = createResourceFixture();
-
- let resolveUpdate:
- | ((value: {
- historyAppended: boolean;
- id: string;
- savedAt?: string;
- updatedAt: string;
- }) => void)
- | undefined;
- vi.mocked(documentService.updateDocument).mockImplementation(
- () =>
- new Promise((resolve) => {
- resolveUpdate = resolve;
- }),
- );
+ const { result } = renderDetail('doc-1');
- act(() => {
- useStore.setState(
- {
- documents: [existingDocument],
- queryParams: {
- libraryId: 'kb-1',
- parentId: null,
- },
- resourceList: [existingResource],
- resourceMap: new Map([[existingResource.id, existingResource]]),
- },
- false,
+ await waitFor(() =>
+ expect(useFileStore.getState().documentMap['doc-1']).toEqual({ document: null }),
);
+ expect(result.current.data).toBeNull();
+ expect(await storedRow('doc-1', scope)).toBeUndefined();
});
- let pendingUpdate!: Promise<void>;
- act(() => {
- pendingUpdate = result.current.updateDocumentOptimistically('doc-1', {
- title: 'Optimistic title',
+ it('drops the persisted row when a previously cached document turns out to be gone', async () => {
+ const cached = lobeDocument({ content: '# Cached', title: 'Cached' });
+ await fileDocumentResource.storage!.set(
+ { queryKey: 'doc-1', scope },
+ { data: { document: cached }, updatedAt: 1 },
+ );
+ // The document was deleted / access revoked on another device: the server
+ // now answers not found for it.
+ vi.mocked(documentService.getDocumentById).mockResolvedValue(undefined as any);
+
+ const { result } = renderDetail('doc-1');
+
+ await waitFor(() =>
+ expect(useFileStore.getState().documentMap['doc-1']).toEqual({ document: null }),
+ );
+ expect(result.current.data).toBeNull();
+ // The stale projection must be gone, so a later reload cannot hydrate and
+ // briefly paint a document the server no longer has.
+ await waitFor(async () => {
+ expect(await storedRow('doc-1', scope)).toBeUndefined();
});
});
- expect(useStore.getState().resourceMap.get('doc-1')).toMatchObject({
- _optimistic: {
- isPending: true,
- queryKey: getResourceQueryKey(useStore.getState().queryParams),
- retryCount: 0,
- },
- name: 'Optimistic title',
- title: 'Optimistic title',
- });
+ it('drops the previous identity’s rows before the next one paints', async () => {
+ vi.mocked(documentService.getDocumentById).mockResolvedValue(serverRow() as any);
- resolveUpdate?.({ historyAppended: false, id: 'doc-1', updatedAt: '2026-01-01T00:00:00.000Z' });
+ const sync = renderDetail('doc-1');
+ await waitFor(() => expect(useFileStore.getState().documentMap['doc-1']).toBeDefined());
- await act(async () => {
- await pendingUpdate;
+ vi.mocked(documentService.getDocumentById).mockImplementation(() => pending());
+ useScope(`file-user-${randomUUID()}:personal`);
+ sync.rerender();
+
+ await waitFor(() => expect(useFileStore.getState().documentMap['doc-1']).toBeUndefined());
});
- expect(useStore.getState().resourceMap.get('doc-1')).toMatchObject({
- name: 'Optimistic title',
- title: 'Optimistic title',
+ it('warms the replica for a prefetch so the next visit paints from storage', async () => {
+ const prefetched = serverRow({ id: 'doc-2', content: '# Prefetched', title: 'Prefetched' });
+ vi.mocked(documentService.getDocumentById).mockResolvedValue(prefetched as any);
+
+ const { result } = renderHook(() => useFileStore(), { wrapper });
+
+ await act(async () => {
+ await result.current.prefetchDocument('doc-2');
+ });
+
+ expect(useFileStore.getState().documentMap['doc-2']?.document?.content).toBe('# Prefetched');
+ await waitFor(async () => {
+ const stored = await storedRow('doc-2', scope);
+ expect(stored?.data.document?.content).toBe('# Prefetched');
+ });
});
- expect(useStore.getState().resourceMap.get('doc-1')?._optimistic).toBeUndefined();
});
- it('does not send content or editorData when Page Agent editTitle follows initPage', async () => {
- const { result } = renderHook(() => useStore());
- const initializedEditorData = {
- root: {
- children: [{ children: [], type: 'paragraph', version: 1 }],
- type: 'root',
- version: 1,
- },
- };
+ describe('writes', () => {
+ it('keeps the created folder in the replica and in the current resource list', async () => {
+ vi.mocked(documentService.createDocument).mockResolvedValue(
+ serverRow({
+ content: '',
+ fileType: CUSTOM_FOLDER_FILE_TYPE,
+ id: 'folder-1',
+ parentId: null,
+ slug: 'new-folder',
+ title: 'New Folder',
+ totalCharCount: 0,
+ }) as any,
+ );
+
+ const { result } = renderHook(() => useFileStore(), { wrapper });
+
+ act(() => {
+ useFileStore.setState({ queryParams: { libraryId: 'kb-1', parentId: null } }, false);
+ });
+
+ await act(async () => {
+ await result.current.createFolder('New Folder', undefined, 'kb-1');
+ });
- vi.mocked(documentService.updateDocument).mockResolvedValue({
- historyAppended: false,
- id: 'doc-1',
- updatedAt: '2026-01-01T00:00:00.000Z',
+ expect(useFileStore.getState().resourceList.map((item) => item.id)).toEqual(['folder-1']);
+ expect(useFileStore.getState().resourceMap.get('folder-1')).toMatchObject({
+ fileType: CUSTOM_FOLDER_FILE_TYPE,
+ id: 'folder-1',
+ knowledgeBaseId: 'kb-1',
+ name: 'New Folder',
+ parentId: null,
+ slug: 'new-folder',
+ sourceType: DERIVED_DOCUMENT_SOURCE_TYPE,
+ title: 'New Folder',
+ });
+ // The new row is openable without another round trip.
+ expect(useFileStore.getState().documentMap['folder-1']?.document).toMatchObject({
+ id: 'folder-1',
+ title: 'New Folder',
+ });
});
- act(() => {
- useStore.setState(
- {
- documents: [
- createDocumentFixture({
- content: '',
- editorData: {},
- }),
- ],
- },
- false,
+ it('puts a created page into the replica so it resolves by id immediately', async () => {
+ vi.mocked(documentService.createDocument).mockResolvedValue(
+ serverRow({ content: 'Hello', id: 'doc-2', title: 'Fresh page' }) as any,
);
- });
- await act(async () => {
- await result.current.updateDocumentOptimistically('doc-1', {
- content: 'Body written by page agent.',
- editorData: initializedEditorData,
+ const { result } = renderHook(() => useFileStore(), { wrapper });
+
+ await act(async () => {
+ await result.current.createDocument({ content: 'Hello', title: 'Fresh page' });
+ });
+
+ expect(useFileStore.getState().documentMap['doc-2']?.document).toMatchObject({
+ content: 'Hello',
+ id: 'doc-2',
+ title: 'Fresh page',
});
});
- await act(async () => {
- await result.current.updateDocumentOptimistically('doc-1', {
+ it('updates the replica and the visible resource after a successful save', async () => {
+ const existingResource = createResourceFixture();
+ vi.mocked(documentService.updateDocument).mockResolvedValue({
+ historyAppended: false,
+ id: 'doc-1',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ } as any);
+
+ const { result } = renderHook(() => useFileStore(), { wrapper });
+
+ act(() => {
+ useFileStore.setState(
+ {
+ documentMap: { 'doc-1': { document: lobeDocument() } },
+ queryParams: { libraryId: 'kb-1', parentId: null },
+ resourceList: [existingResource],
+ resourceMap: new Map([[existingResource.id, existingResource]]),
+ },
+ false,
+ );
+ });
+
+ await act(async () => {
+ await result.current.updateDocument('doc-1', {
+ metadata: { emoji: 'page' },
+ title: 'Renamed title',
+ });
+ });
+
+ expect(documentService.updateDocument).toHaveBeenCalledWith({
+ content: undefined,
+ editorData: undefined,
+ id: 'doc-1',
metadata: { emoji: 'page' },
- title: 'Final title',
+ parentId: undefined,
+ title: 'Renamed title',
+ });
+ expect(useFileStore.getState().documentMap['doc-1']?.document).toMatchObject({
+ metadata: { emoji: 'page' },
+ title: 'Renamed title',
+ });
+ expect(useFileStore.getState().resourceMap.get('doc-1')).toMatchObject({
+ metadata: { emoji: 'page' },
+ name: 'Renamed title',
+ title: 'Renamed title',
});
});
- expect(documentService.updateDocument).toHaveBeenNthCalledWith(1, {
- content: 'Body written by page agent.',
- editorData: JSON.stringify(initializedEditorData),
- id: 'doc-1',
- metadata: {},
- parentId: undefined,
- title: 'Old title',
- });
- expect(documentService.updateDocument).toHaveBeenNthCalledWith(2, {
- id: 'doc-1',
- metadata: { emoji: 'page' },
- parentId: undefined,
- title: 'Final title',
- });
- });
+ it('shows a rename optimistically and clears the resource marker after sync', async () => {
+ const existingResource = createResourceFixture();
+ let resolveUpdate!: (value: unknown) => void;
+ vi.mocked(documentService.updateDocument).mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveUpdate = resolve;
+ }) as any,
+ );
- it('keeps a list row whose library/parent are unknown when its title is saved', async () => {
- const { result } = renderHook(() => useStore());
- const existingDocument = createDocumentFixture();
- // `file.getKnowledgeItems` rows carry neither `knowledgeBaseId` nor `parentId`,
- // so the merged resource must not be judged "outside the current query".
- const existingResource = createResourceFixture();
- delete existingResource.knowledgeBaseId;
- delete existingResource.parentId;
-
- vi.mocked(documentService.updateDocument).mockResolvedValue({
- historyAppended: false,
- id: 'doc-1',
- updatedAt: '2026-01-01T00:00:00.000Z',
- });
+ const { result } = renderHook(() => useFileStore(), { wrapper });
- act(() => {
- useStore.setState(
- {
- documents: [existingDocument],
- queryParams: { libraryId: 'kb-1', parentId: null },
- resourceList: [existingResource],
- resourceMap: new Map([[existingResource.id, existingResource]]),
+ act(() => {
+ useFileStore.setState(
+ {
+ documentMap: { 'doc-1': { document: lobeDocument() } },
+ queryParams: { libraryId: 'kb-1', parentId: null },
+ resourceList: [existingResource],
+ resourceMap: new Map([[existingResource.id, existingResource]]),
+ },
+ false,
+ );
+ });
+
+ let pendingUpdate!: Promise<void>;
+ act(() => {
+ pendingUpdate = result.current.updateDocumentOptimistically('doc-1', {
+ title: 'Optimistic title',
+ });
+ });
+
+ expect(useFileStore.getState().documentMap['doc-1']?.document?.title).toBe(
+ 'Optimistic title',
+ );
+ expect(useFileStore.getState().resourceMap.get('doc-1')).toMatchObject({
+ _optimistic: {
+ isPending: true,
+ queryKey: getResourceQueryKey(useFileStore.getState().queryParams),
+ retryCount: 0,
},
- false,
+ name: 'Optimistic title',
+ title: 'Optimistic title',
+ });
+
+ resolveUpdate({ historyAppended: false, id: 'doc-1', updatedAt: '2026-01-01T00:00:00.000Z' });
+
+ await act(async () => {
+ await pendingUpdate;
+ });
+
+ expect(useFileStore.getState().documentMap['doc-1']?.document?.title).toBe(
+ 'Optimistic title',
);
+ expect(useFileStore.getState().resourceMap.get('doc-1')).toMatchObject({
+ name: 'Optimistic title',
+ title: 'Optimistic title',
+ });
+ expect(useFileStore.getState().resourceMap.get('doc-1')?._optimistic).toBeUndefined();
});
- await act(async () => {
- await result.current.updateDocumentOptimistically('doc-1', { title: 'Typed title' });
- });
+ it('reverts the replica and the resource when the sync fails', async () => {
+ const existingResource = createResourceFixture();
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.mocked(documentService.updateDocument).mockRejectedValue(new Error('sync failed'));
- expect(useStore.getState().resourceList.map((item) => item.id)).toEqual(['doc-1']);
- expect(useStore.getState().resourceMap.get('doc-1')).toMatchObject({ name: 'Typed title' });
- });
+ const { result } = renderHook(() => useFileStore(), { wrapper });
- it('keeps a folder list row with unknown parentId when its title is saved', async () => {
- const { result } = renderHook(() => useStore());
- const existingDocument = createDocumentFixture();
- const existingResource = createResourceFixture();
- delete existingResource.knowledgeBaseId;
- delete existingResource.parentId;
-
- vi.mocked(documentService.updateDocument).mockResolvedValue({
- historyAppended: false,
- id: 'doc-1',
- updatedAt: '2026-01-01T00:00:00.000Z',
+ act(() => {
+ useFileStore.setState(
+ {
+ documentMap: { 'doc-1': { document: lobeDocument() } },
+ queryParams: { libraryId: 'kb-1', parentId: null },
+ resourceList: [existingResource],
+ resourceMap: new Map([[existingResource.id, existingResource]]),
+ },
+ false,
+ );
+ });
+
+ await act(async () => {
+ await result.current.updateDocumentOptimistically('doc-1', { title: 'Broken title' });
+ });
+
+ expect(consoleErrorSpy).toHaveBeenCalled();
+ expect(useFileStore.getState().documentMap['doc-1']?.document?.title).toBe('Old title');
+ expect(useFileStore.getState().resourceMap.get('doc-1')).toMatchObject({
+ name: 'Old title',
+ title: 'Old title',
+ });
+ expect(useFileStore.getState().resourceMap.get('doc-1')?._optimistic).toBeUndefined();
});
- act(() => {
- useStore.setState(
- {
- documents: [existingDocument],
- queryParams: { libraryId: 'kb-1', parentId: 'weekly-reports' },
- resourceList: [existingResource],
- resourceMap: new Map([[existingResource.id, existingResource]]),
+ it('does not send content or editorData when only the title changes', async () => {
+ const initializedEditorData = {
+ root: {
+ children: [{ children: [], type: 'paragraph', version: 1 }],
+ root: { type: 'root', version: 1 },
},
- false,
- );
- });
+ } as any;
- await act(async () => {
- await result.current.updateDocumentOptimistically('doc-1', { title: 'Typed title' });
- });
+ vi.mocked(documentService.updateDocument).mockResolvedValue({
+ historyAppended: false,
+ id: 'doc-1',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ } as any);
- expect(useStore.getState().resourceList.map((item) => item.id)).toEqual(['doc-1']);
- expect(useStore.getState().resourceMap.get('doc-1')).toMatchObject({ name: 'Typed title' });
- });
+ const { result } = renderHook(() => useFileStore(), { wrapper });
- it('reverts optimistic resource updates when the sync fails', async () => {
- const { result } = renderHook(() => useStore());
- const existingDocument = createDocumentFixture();
- const existingResource = createResourceFixture();
- const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ act(() => {
+ useFileStore.setState(
+ { documentMap: { 'doc-1': { document: lobeDocument({ content: '', editorData: {} }) } } },
+ false,
+ );
+ });
- vi.mocked(documentService.updateDocument).mockRejectedValue(new Error('sync failed'));
+ await act(async () => {
+ await result.current.updateDocumentOptimistically('doc-1', {
+ content: 'Body written by page agent.',
+ editorData: initializedEditorData,
+ });
+ });
- act(() => {
- useStore.setState(
- {
- documents: [existingDocument],
- queryParams: {
- libraryId: 'kb-1',
- parentId: null,
- },
- resourceList: [existingResource],
- resourceMap: new Map([[existingResource.id, existingResource]]),
- },
- false,
- );
+ await act(async () => {
+ await result.current.updateDocumentOptimistically('doc-1', {
+ metadata: { emoji: 'page' },
+ title: 'Final title',
+ });
+ });
+
+ expect(documentService.updateDocument).toHaveBeenNthCalledWith(1, {
+ content: 'Body written by page agent.',
+ editorData: JSON.stringify(initializedEditorData),
+ id: 'doc-1',
+ metadata: {},
+ parentId: undefined,
+ title: 'Old title',
+ });
+ expect(documentService.updateDocument).toHaveBeenNthCalledWith(2, {
+ id: 'doc-1',
+ metadata: { emoji: 'page' },
+ parentId: undefined,
+ title: 'Final title',
+ });
});
- await act(async () => {
- await result.current.updateDocumentOptimistically('doc-1', {
- title: 'Broken title',
+ it('keeps a list row whose library/parent are unknown when its title is saved', async () => {
+ const existingResource = createResourceFixture();
+ delete existingResource.knowledgeBaseId;
+ delete existingResource.parentId;
+
+ vi.mocked(documentService.updateDocument).mockResolvedValue({
+ historyAppended: false,
+ id: 'doc-1',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ } as any);
+
+ const { result } = renderHook(() => useFileStore(), { wrapper });
+
+ act(() => {
+ useFileStore.setState(
+ {
+ documentMap: { 'doc-1': { document: lobeDocument() } },
+ queryParams: { libraryId: 'kb-1', parentId: null },
+ resourceList: [existingResource],
+ resourceMap: new Map([[existingResource.id, existingResource]]),
+ },
+ false,
+ );
+ });
+
+ await act(async () => {
+ await result.current.updateDocumentOptimistically('doc-1', { title: 'Typed title' });
+ });
+
+ expect(useFileStore.getState().resourceList.map((item) => item.id)).toEqual(['doc-1']);
+ expect(useFileStore.getState().resourceMap.get('doc-1')).toMatchObject({
+ name: 'Typed title',
});
});
- expect(consoleErrorSpy).toHaveBeenCalled();
- expect(useStore.getState().localDocumentMap.get('doc-1')).toMatchObject({
- title: 'Old title',
+ it('drops the row on delete and restores it when the server rejects', async () => {
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.mocked(documentService.deleteDocument).mockRejectedValue(new Error('delete failed'));
+
+ const { result } = renderHook(() => useFileStore(), { wrapper });
+
+ act(() => {
+ useFileStore.setState({ documentMap: { 'doc-1': { document: lobeDocument() } } }, false);
+ });
+
+ await act(async () => {
+ await expect(result.current.removeDocument('doc-1')).rejects.toThrow('delete failed');
+ });
+
+ expect(consoleErrorSpy).toHaveBeenCalled();
+ expect(useFileStore.getState().documentMap['doc-1']?.document).toMatchObject({
+ id: 'doc-1',
+ title: 'Old title',
+ });
});
- expect(useStore.getState().resourceMap.get('doc-1')).toMatchObject({
- name: 'Old title',
- title: 'Old title',
+
+ it('drops the row once the delete succeeds', async () => {
+ vi.mocked(documentService.deleteDocument).mockResolvedValue(undefined);
+
+ const { result } = renderHook(() => useFileStore(), { wrapper });
+
+ act(() => {
+ useFileStore.setState({ documentMap: { 'doc-1': { document: lobeDocument() } } }, false);
+ });
+
+ await act(async () => {
+ await result.current.removeDocument('doc-1');
+ });
+
+ expect(useFileStore.getState().documentMap['doc-1']).toBeUndefined();
});
- expect(useStore.getState().resourceMap.get('doc-1')?._optimistic).toBeUndefined();
});
});
diff --git a/src/store/file/slices/document/action.ts b/src/store/file/slices/document/action.ts
index ce8ffcbbb95..b46f5ebf928 100644
--- a/src/store/file/slices/document/action.ts
+++ b/src/store/file/slices/document/action.ts
@@ -2,35 +2,50 @@ import {
CUSTOM_DOCUMENT_FILE_TYPE,
CUSTOM_FOLDER_FILE_TYPE,
DERIVED_DOCUMENT_SOURCE_TYPE,
- PAGE_DOCUMENT_FILE_TYPES,
- PAGE_DOCUMENT_SOURCE_TYPES,
} from '@lobechat/const';
+import { type DocumentItem } from '@lobechat/database/schemas';
import { createNanoId } from '@lobechat/utils';
-import { type SWRResponse } from 'swr';
+import isEqual from 'fast-deep-equal';
-import { useClientDataSWRWithSync } from '@/libs/swr';
+import { createReplicaSlice, recordLens } from '@/libs/replica';
import { documentService } from '@/services/document';
-import { useGlobalStore } from '@/store/global';
import { type StoreSetter } from '@/store/types';
import { type LobeDocument } from '@/types/document';
import { DocumentSourceType } from '@/types/document';
import { type ResourceItem } from '@/types/resource';
import { setNamespace } from '@/utils/storeDebug';
-import type { FileStore } from '../../store';
+import { type FileStore, useFileStore } from '../../store';
import { getResourceQueryKey } from '../resource/utils';
-import { type DocumentQueryFilter } from './initialState';
+import { type FileDocumentDetail, fileDocumentResource } from './projection';
const n = setNamespace('document');
-// EDITOR is a client-only stamp on in-memory drafts; DB rows never carry it.
-const ALLOWED_DOCUMENT_SOURCE_TYPES = new Set([
- DocumentSourceType.EDITOR as string,
- ...PAGE_DOCUMENT_SOURCE_TYPES,
-]);
-const ALLOWED_DOCUMENT_FILE_TYPES = new Set(PAGE_DOCUMENT_FILE_TYPES);
-const EDITOR_DOCUMENT_FILE_TYPE = CUSTOM_DOCUMENT_FILE_TYPE;
+type Setter = StoreSetter<FileStore>;
+
+/**
+ * Result of {@link DocumentActionImpl.useFetchDocumentDetail}.
+ *
+ * `data` is the replica view, read from the store (not from the hook's return)
+ * so the first frame paints from the persisted projection and the network only
+ * confirms it: `undefined` = nothing loaded for this id yet, `null` = the
+ * server answered "not found".
+ */
+export interface UseFetchDocumentDetailResult {
+ data: LobeDocument | null | undefined;
+ error: unknown;
+ /** SWR's `isLoading` semantics: no value yet and no error. */
+ isLoading: boolean;
+ isValidating: boolean;
+ /** Re-run the network sync for this document. */
+ mutate: () => Promise<unknown>;
+}
+/**
+ * Shape the resource explorer merges onto its list rows. Kept separate from
+ * `LobeDocument`: a list row also needs the library it belongs to, which the
+ * document row itself does not carry.
+ */
interface ResourceDocumentSnapshot {
content?: string | null;
createdAt?: Date | string;
@@ -47,35 +62,85 @@ interface ResourceDocumentSnapshot {
updatedAt?: Date | string;
}
-/**
- * Check if a page should be displayed in the page list
- */
-const isAllowedDocument = (page: { fileType: string; sourceType: string }) => {
- return (
- ALLOWED_DOCUMENT_SOURCE_TYPES.has(page.sourceType) &&
- ALLOWED_DOCUMENT_FILE_TYPES.has(page.fileType)
- );
-};
-
-type Setter = StoreSetter<FileStore>;
export const createDocumentSlice = (set: Setter, get: () => FileStore, _api?: unknown) =>
new DocumentActionImpl(set, get, _api);
export class DocumentActionImpl {
readonly #get: () => FileStore;
- readonly #set: Setter;
+ /**
+ * One document row per id. The replica owns every transition of `documentMap`
+ * (hydrate → first frame, server replace, optimistic rename, delete).
+ */
+ readonly #documents;
constructor(set: Setter, get: () => FileStore, _api?: unknown) {
void _api;
- this.#set = set;
this.#get = get;
- }
+ this.#documents = createReplicaSlice(fileDocumentResource, {
+ actionPrefix: n('fileDocument'),
+ fetcher: async (id) => {
+ const row = await documentService.getDocumentById(id);
- #findExistingDocument = (documentId: string): LobeDocument | undefined => {
- const { documents, localDocumentMap } = this.#get();
+ return { document: row ? this.#toLobeDocument(row) : null };
+ },
+ get,
+ set,
+ stateKey: 'fileDocumentReplica',
+ // The server response is authoritative for a resumed / refocused sync.
+ // Ordering comes from the replica's mutation ordering — a local write
+ // still in flight is preserved by the optimistic overlay and rebased onto
+ // this value — never from comparing a client-clock `updatedAt` against a
+ // server-clock one.
+ merge: (incoming, confirmed) => (isEqual(incoming, confirmed) ? undefined : incoming),
+ // A "not found" answer is a page state, not a document: never persist it,
+ // and `null` (not `undefined`) tells the engine to drop any previously
+ // persisted projection, so a later hydrate cannot paint a document the
+ // server no longer has.
+ toPersisted: (data) => (data.document ? data : null),
+ view: recordLens<FileStore, FileDocumentDetail>('documentMap'),
+ });
+ }
- return localDocumentMap.get(documentId) ?? documents.find((doc) => doc.id === documentId);
- };
+ /**
+ * Normalize a server row into the store's document shape. Kept in one place so
+ * the sync path and the create/duplicate paths produce the same entry.
+ */
+ #toLobeDocument = (row: DocumentItem): LobeDocument => ({
+ content: row.content || null,
+ createdAt: row.createdAt ? new Date(row.createdAt) : new Date(),
+ editorData:
+ typeof row.editorData === 'string' ? JSON.parse(row.editorData) : (row.editorData ?? null),
+ fileType: row.fileType,
+ filename: row.title || row.filename || 'Untitled',
+ id: row.id,
+ metadata: row.metadata || {},
+ source: 'document',
+ sourceType: DocumentSourceType.EDITOR,
+ title: row.title || '',
+ totalCharCount: row.content?.length || 0,
+ totalLineCount: 0,
+ updatedAt: row.updatedAt ? new Date(row.updatedAt) : new Date(),
+ });
+
+ /** The resource-explorer snapshot of a server row (carries its library). */
+ #toResourceSnapshot = (
+ row: DocumentItem,
+ knowledgeBaseId?: string,
+ ): ResourceDocumentSnapshot => ({
+ content: row.content,
+ createdAt: row.createdAt,
+ editorData: row.editorData,
+ fileType: row.fileType,
+ id: row.id,
+ knowledgeBaseId,
+ metadata: row.metadata,
+ parentId: row.parentId,
+ slug: row.slug,
+ source: row.source,
+ title: row.title,
+ totalCharCount: row.totalCharCount,
+ updatedAt: row.updatedAt,
+ });
#normalizeDate = (value: Date | string | undefined, fallback: Date) => {
return value ? new Date(value) : fallback;
@@ -91,9 +156,15 @@ export class DocumentActionImpl {
return typeof editorData === 'string' ? JSON.parse(editorData) : editorData;
};
+ /**
+ * Build the next document row. `updatedAt` is the authoritative write time
+ * the update endpoint returned; only when the caller has none (an optimistic
+ * value built before the request) does it fall back to the local clock.
+ */
#createUpdatedDocument = (
existingDocument: LobeDocument,
updates: Partial<LobeDocument>,
+ updatedAt?: Date | string,
): LobeDocument => {
const mergedMetadata =
updates.metadata !== undefined
@@ -109,17 +180,10 @@ export class DocumentActionImpl {
...updates,
metadata: cleanedMetadata,
title: updates.title || existingDocument.title,
- updatedAt: new Date(),
+ updatedAt: this.#normalizeDate(updatedAt, new Date()),
};
};
- #setLocalDocument = (documentId: string, document: LobeDocument, actionName: string) => {
- const { localDocumentMap } = this.#get();
- const newMap = new Map(localDocumentMap);
- newMap.set(documentId, document);
- this.#set({ localDocumentMap: newMap }, false, actionName);
- };
-
/**
* Whether `resource` belongs in the explorer's current list.
*
@@ -186,7 +250,7 @@ export class DocumentActionImpl {
content: document.content !== undefined ? document.content : (fallback?.content ?? null),
createdAt: this.#normalizeDate(document.createdAt, fallback?.createdAt ?? now),
editorData: this.#parseEditorData(document.editorData, fallback?.editorData),
- fileType: document.fileType ?? fallback?.fileType ?? EDITOR_DOCUMENT_FILE_TYPE,
+ fileType: document.fileType ?? fallback?.fileType ?? CUSTOM_DOCUMENT_FILE_TYPE,
id: document.id,
knowledgeBaseId: document.knowledgeBaseId ?? fallback?.knowledgeBaseId,
metadata: document.metadata ?? fallback?.metadata,
@@ -251,7 +315,7 @@ export class DocumentActionImpl {
const newPage = await documentService.createDocument({
content,
editorData: '{}', // Empty JSON object instead of empty string
- fileType: EDITOR_DOCUMENT_FILE_TYPE,
+ fileType: CUSTOM_DOCUMENT_FILE_TYPE,
knowledgeBaseId,
metadata: {
createdAt: now,
@@ -260,24 +324,12 @@ export class DocumentActionImpl {
title,
});
+ // Hold the row in the replica so the page can be opened (and re-opened from
+ // a reload) without another round trip; the explorer list is fed from the
+ // resource slice.
+ this.#documents.replace(newPage.id, { document: this.#toLobeDocument(newPage) });
this.#syncResourceItem(
- this.#createResourceItem(
- {
- content: newPage.content,
- createdAt: newPage.createdAt,
- editorData: newPage.editorData,
- fileType: newPage.fileType,
- id: newPage.id,
- knowledgeBaseId,
- metadata: newPage.metadata,
- parentId: newPage.parentId,
- source: newPage.source,
- title: newPage.title,
- totalCharCount: newPage.totalCharCount,
- updatedAt: newPage.updatedAt,
- },
- undefined,
- ),
+ this.#createResourceItem(this.#toResourceSnapshot(newPage, knowledgeBaseId)),
);
return newPage;
@@ -307,61 +359,14 @@ export class DocumentActionImpl {
title: name,
});
+ this.#documents.replace(folder.id, { document: this.#toLobeDocument(folder) });
this.#syncResourceItem(
- this.#createResourceItem(
- {
- content: folder.content,
- createdAt: folder.createdAt,
- editorData: folder.editorData,
- fileType: folder.fileType,
- id: folder.id,
- knowledgeBaseId,
- metadata: folder.metadata,
- parentId: folder.parentId,
- slug: folder.slug,
- source: folder.source,
- title: folder.title,
- totalCharCount: folder.totalCharCount,
- updatedAt: folder.updatedAt,
- },
- undefined,
- ),
+ this.#createResourceItem(this.#toResourceSnapshot(folder, knowledgeBaseId)),
);
return folder.id;
};
- createOptimisticDocument = (title: string = 'Untitled'): string => {
- const { localDocumentMap } = this.#get();
-
- // Generate temporary ID with prefix to identify optimistic pages
- const tempId = `temp-document-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
- const now = new Date();
-
- const newPage: LobeDocument = {
- content: null,
- createdAt: now,
- editorData: null,
- fileType: EDITOR_DOCUMENT_FILE_TYPE,
- filename: title,
- id: tempId,
- metadata: {},
- source: 'document',
- sourceType: DocumentSourceType.EDITOR,
- title,
- totalCharCount: 0,
- totalLineCount: 0,
- updatedAt: now,
- };
-
- // Add to local map
- const newMap = new Map(localDocumentMap);
- newMap.set(tempId, newPage);
- this.#set({ localDocumentMap: newMap }, false, n('createOptimisticDocument'));
-
- return tempId;
- };
-
duplicateDocument = async (documentId: string): Promise<{ [key: string]: any; id: string }> => {
// Fetch the source page
const sourcePage = await documentService.getDocumentById(documentId);
@@ -387,258 +392,19 @@ export class DocumentActionImpl {
title: `${sourcePage.title} (Copy)`,
});
- // Add the new page to local map immediately for instant UI update
- const { localDocumentMap } = this.#get();
- const newMap = new Map(localDocumentMap);
- const editorPage: LobeDocument = {
- content: newPage.content || null,
- createdAt: newPage.createdAt ? new Date(newPage.createdAt) : new Date(),
- editorData:
- typeof newPage.editorData === 'string'
- ? JSON.parse(newPage.editorData)
- : newPage.editorData || null,
- fileType: newPage.fileType,
- filename: newPage.title || newPage.filename || '',
- id: newPage.id,
- metadata: newPage.metadata || {},
- source: 'document',
- sourceType: DocumentSourceType.EDITOR,
- title: newPage.title || '',
- totalCharCount: newPage.content?.length || 0,
- totalLineCount: 0,
- updatedAt: newPage.updatedAt ? new Date(newPage.updatedAt) : new Date(),
- };
- newMap.set(newPage.id, editorPage);
- this.#set({ localDocumentMap: newMap }, false, n('duplicateDocument'));
-
- // Don't refresh pages here - we've already added it to the local map
- // This prevents the loading skeleton from appearing
+ // Make the copy openable immediately: the replica entry is what
+ // `getDocumentById` resolves, so the editor does not wait on a refetch.
+ this.#documents.replace(newPage.id, { document: this.#toLobeDocument(newPage) });
return newPage;
};
- fetchDocumentDetail = async (documentId: string): Promise<void> => {
- try {
- const document = await documentService.getDocumentById(documentId);
-
- if (!document) {
- console.warn(`[fetchDocumentDetail] Document not found: ${documentId}`);
- return;
- }
-
- // Update local map with full document details including editorData
- const { localDocumentMap } = this.#get();
- const newMap = new Map(localDocumentMap);
-
- const fullDocument: LobeDocument = {
- content: document.content || null,
- createdAt: document.createdAt ? new Date(document.createdAt) : new Date(),
- editorData:
- typeof document.editorData === 'string'
- ? JSON.parse(document.editorData)
- : document.editorData || null,
- fileType: document.fileType,
- filename: document.title || document.filename || 'Untitled',
- id: document.id,
- metadata: document.metadata || {},
- source: 'document',
- sourceType: DocumentSourceType.EDITOR,
- title: document.title || '',
- totalCharCount: document.content?.length || 0,
- totalLineCount: 0,
- updatedAt: document.updatedAt ? new Date(document.updatedAt) : new Date(),
- };
-
- newMap.set(documentId, fullDocument);
- this.#set({ localDocumentMap: newMap }, false, n('fetchDocumentDetail'));
- } catch (error) {
- console.error('[fetchDocumentDetail] Failed to fetch document:', error);
- }
- };
-
- fetchDocuments = async ({ pageOnly = false }: { pageOnly?: boolean }): Promise<void> => {
- this.#set({ isDocumentListLoading: true }, false, n('fetchDocuments/start'));
-
- try {
- const pageSize = useGlobalStore.getState().status.pagePageSize || 20;
- const queryFilters: DocumentQueryFilter | undefined = pageOnly
- ? {
- fileTypes: PAGE_DOCUMENT_FILE_TYPES,
- sourceTypes: PAGE_DOCUMENT_SOURCE_TYPES,
- }
- : undefined;
-
- const queryParams = queryFilters
- ? { current: 0, pageSize, ...queryFilters }
- : { current: 0, pageSize };
-
- const result = await documentService.queryDocuments(queryParams);
-
- const pages = result.items.filter(isAllowedDocument).map((doc) => ({
- ...doc,
- filename: doc.filename ?? doc.title ?? 'Untitled',
- })) as LobeDocument[];
-
- const hasMore = result.items.length >= pageSize;
-
- this.#set(
- {
- currentPage: 0,
- documentQueryFilter: queryFilters,
- documents: pages,
- documentsTotal: result.total,
- hasMoreDocuments: hasMore,
- isDocumentListLoading: false,
- },
- false,
- n('fetchDocuments/success'),
- );
-
- // Sync with local map: remove temp pages that now exist on server
- const { localDocumentMap } = this.#get();
- const newMap = new Map(localDocumentMap);
-
- for (const [id] of localDocumentMap.entries()) {
- if (id.startsWith('temp-document-')) {
- newMap.delete(id);
- }
- }
-
- this.#set({ localDocumentMap: newMap }, false, n('fetchDocuments/syncLocalMap'));
- } catch (error) {
- console.error('Failed to fetch pages:', error);
- this.#set({ isDocumentListLoading: false }, false, n('fetchDocuments/error'));
- throw error;
- }
- };
-
- getOptimisticDocuments = (): LobeDocument[] => {
- const { localDocumentMap, documents } = this.#get();
-
- // Track which pages we've added
- const addedIds = new Set<string>();
-
- // Create result array - start with server pages
- const result: LobeDocument[] = documents.map((page) => {
- addedIds.add(page.id);
- // Check if we have a local optimistic update for this page
- const localUpdate = localDocumentMap.get(page.id);
- // If local update exists and is newer, use it; otherwise use server version
- if (localUpdate && new Date(localUpdate.updatedAt) >= new Date(page.updatedAt)) {
- return localUpdate;
- }
- return page;
- });
-
- // Add any optimistic pages that aren't in server list yet (e.g., newly created temp pages)
- for (const [id, page] of localDocumentMap.entries()) {
- if (!addedIds.has(id)) {
- result.unshift(page); // Add new pages to the beginning
- }
- }
-
- return result;
- };
-
- loadMoreDocuments = async (): Promise<void> => {
- const { currentPage, isLoadingMoreDocuments, hasMoreDocuments, documentQueryFilter } =
- this.#get();
-
- if (isLoadingMoreDocuments || !hasMoreDocuments) return;
-
- const nextPage = currentPage + 1;
-
- this.#set({ isLoadingMoreDocuments: true }, false, n('loadMoreDocuments/start'));
-
- try {
- const pageSize = useGlobalStore.getState().status.pagePageSize || 20;
- const queryParams = documentQueryFilter
- ? { current: nextPage, pageSize, ...documentQueryFilter }
- : { current: nextPage, pageSize };
-
- const result = await documentService.queryDocuments(queryParams);
-
- const newPages = result.items.filter(isAllowedDocument).map((doc) => ({
- ...doc,
- filename: doc.filename ?? doc.title ?? 'Untitled',
- })) as LobeDocument[];
-
- const hasMore = result.items.length >= pageSize;
-
- this.#set(
- {
- currentPage: nextPage,
- documents: [...this.#get().documents, ...newPages],
- documentsTotal: result.total,
- hasMoreDocuments: hasMore,
- isLoadingMoreDocuments: false,
- },
- false,
- n('loadMoreDocuments/success'),
- );
- } catch (error) {
- console.error('Failed to load more pages:', error);
- this.#set({ isLoadingMoreDocuments: false }, false, n('loadMoreDocuments/error'));
- }
- };
-
- removeDocument = async (documentId: string): Promise<void> => {
- // Remove from local optimistic map first (optimistic update)
- const { localDocumentMap, documents } = this.#get();
- const newMap = new Map(localDocumentMap);
- newMap.delete(documentId);
-
- // Also remove from documents array to update the list immediately
- const newDocuments = documents.filter((doc) => doc.id !== documentId);
-
- this.#set(
- { documents: newDocuments, localDocumentMap: newMap },
- false,
- n('removeDocument/optimistic'),
- );
-
- try {
- // Delete from documents table
- await documentService.deleteDocument(documentId);
- // No need to call fetchDocuments() - optimistic update is enough
- } catch (error) {
- console.error('Failed to delete document:', error);
- // Restore the document in local map and documents array on error
- const restoredMap = new Map(localDocumentMap);
- this.#set(
- {
- documents,
- localDocumentMap: restoredMap,
- },
- false,
- n('removeDocument/restore'),
- );
- throw error;
- }
- };
-
- removeTempDocument = (tempId: string): void => {
- const { localDocumentMap } = this.#get();
- const newMap = new Map(localDocumentMap);
- newMap.delete(tempId);
- this.#set({ localDocumentMap: newMap }, false, n('removeTempDocument'));
- };
-
- replaceTempDocumentWithReal = (tempId: string, realPage: LobeDocument): void => {
- const { localDocumentMap } = this.#get();
- const newMap = new Map(localDocumentMap);
-
- // Remove temp page
- newMap.delete(tempId);
-
- // Add real page with same position
- newMap.set(realPage.id, realPage);
-
- this.#set({ localDocumentMap: newMap }, false, n('replaceTempDocumentWithReal'));
- };
-
+ /**
+ * Keep the client's document row in step with the server, without a list
+ * refetch: the replica entry is the single cache the resource manager reads.
+ */
updateDocument = async (id: string, updates: Partial<LobeDocument>): Promise<void> => {
- await documentService.updateDocument({
+ const result = await documentService.updateDocument({
content: updates.content ?? undefined,
editorData: updates.editorData
? typeof updates.editorData === 'string'
@@ -651,11 +417,18 @@ export class DocumentActionImpl {
title: updates.title,
});
- const existingDocument = this.#findExistingDocument(id);
+ const existingDocument = this.#get().documentMap[id]?.document;
if (existingDocument) {
- const updatedDocument = this.#createUpdatedDocument(existingDocument, updates);
- this.#setLocalDocument(id, updatedDocument, n('updateDocument'));
+ // Order the projection by the write time the server stamped, not by the
+ // browser clock: a change a collaborator made around this window must not
+ // be judged older just because the local clock runs ahead.
+ const updatedDocument = this.#createUpdatedDocument(
+ existingDocument,
+ updates,
+ result?.updatedAt,
+ );
+ this.#documents.replace(id, { document: updatedDocument });
this.#syncResourceItem(
this.#createResourceItem(updatedDocument, this.#get().resourceMap.get(id)),
);
@@ -682,65 +455,68 @@ export class DocumentActionImpl {
);
};
+ /**
+ * Rename / re-emoji a document: show it at once, write through, and put the
+ * previous value back if the write fails. Also mirrors the change onto the
+ * explorer row, which is what the user is actually looking at.
+ */
updateDocumentOptimistically = async (
documentId: string,
updates: Partial<LobeDocument>,
): Promise<void> => {
- const { localDocumentMap, documents } = this.#get();
+ const existingDocument = this.#get().documentMap[documentId]?.document;
- // Find the page either in local map or documents state
- let existingPage = localDocumentMap.get(documentId);
- if (!existingPage) {
- existingPage = documents.find((doc) => doc.id === documentId);
- }
-
- if (!existingPage) {
- console.warn('[updateDocumentOptimistically] Page not found:', documentId);
+ if (!existingDocument) {
+ console.warn('[updateDocumentOptimistically] Document not found:', documentId);
return;
}
const existingResource = this.#get().resourceMap.get(documentId);
- const updatedPage = this.#createUpdatedDocument(existingPage, updates);
+ const updatedDocument = this.#createUpdatedDocument(existingDocument, updates);
- // Update local map immediately for optimistic UI
- this.#setLocalDocument(documentId, updatedPage, n('updateDocumentOptimistically'));
+ // Optimistic overlay: the view shows the new value until the DB confirms it.
+ const token = this.#documents.beginOptimistic(documentId, () => ({
+ document: updatedDocument,
+ }));
if (existingResource) {
this.#syncResourceItem(
- this.#createResourceItem(updatedPage, existingResource, { optimistic: true }),
+ this.#createResourceItem(updatedDocument, existingResource, { optimistic: true }),
);
}
- // Queue background sync to DB
try {
- await documentService.updateDocument({
+ const result = await documentService.updateDocument({
id: documentId,
- metadata: updatedPage.metadata || {},
- parentId: updatedPage.parentId !== undefined ? updatedPage.parentId : undefined,
- title: updatedPage.title || updatedPage.filename,
- ...(updates.content === undefined ? {} : { content: updatedPage.content ?? '' }),
+ metadata: updatedDocument.metadata || {},
+ parentId: updatedDocument.parentId !== undefined ? updatedDocument.parentId : undefined,
+ title: updatedDocument.title || updatedDocument.filename,
+ ...(updates.content === undefined ? {} : { content: updatedDocument.content ?? '' }),
...(updates.editorData === undefined
? {}
: {
editorData:
- typeof updatedPage.editorData === 'string'
- ? updatedPage.editorData
- : JSON.stringify(updatedPage.editorData || {}),
+ typeof updatedDocument.editorData === 'string'
+ ? updatedDocument.editorData
+ : JSON.stringify(updatedDocument.editorData || {}),
}),
});
+
+ // Confirm with the authoritative write time the server returned, so the
+ // persisted / confirmed row is ordered by the server clock rather than the
+ // optimistic local one (which may run ahead).
+ const confirmedDocument = result?.updatedAt
+ ? { ...updatedDocument, updatedAt: new Date(result.updatedAt) }
+ : updatedDocument;
+ token.commit(() => ({ document: confirmedDocument }));
+
if (existingResource) {
- this.#syncResourceItem(this.#createResourceItem(updatedPage, existingResource));
+ this.#syncResourceItem(this.#createResourceItem(confirmedDocument, existingResource));
}
} catch (error) {
console.error('[updateDocumentOptimistically] Failed to sync to DB:', error);
- // On error, revert the optimistic update
- const revertMap = new Map(localDocumentMap);
- if (existingPage) {
- revertMap.set(documentId, existingPage);
- } else {
- revertMap.delete(documentId);
- }
- this.#set({ localDocumentMap: revertMap }, false, n('revertOptimisticUpdate'));
+ // Put the previous row back; the explorer row follows the same value.
+ token.rollback();
if (existingResource) {
this.#syncResourceItem(existingResource);
@@ -748,56 +524,56 @@ export class DocumentActionImpl {
}
};
- useFetchDocumentDetail = (documentId: string | undefined): SWRResponse<LobeDocument | null> => {
- const swrKey = documentId ? ['documentDetail', documentId] : null;
-
- return useClientDataSWRWithSync<LobeDocument | null>(
- swrKey,
- async () => {
- if (!documentId) return null;
-
- const document = await documentService.getDocumentById(documentId);
- if (!document) {
- console.warn(`[useFetchDocumentDetail] Document not found: ${documentId}`);
- return null;
- }
-
- // Transform API response to LobeDocument format
- const fullDocument: LobeDocument = {
- content: document.content || null,
- createdAt: document.createdAt ? new Date(document.createdAt) : new Date(),
- editorData:
- typeof document.editorData === 'string'
- ? JSON.parse(document.editorData)
- : document.editorData || null,
- fileType: document.fileType,
- filename: document.title || document.filename || 'Untitled',
- id: document.id,
- metadata: document.metadata || {},
- source: 'document',
- sourceType: DocumentSourceType.EDITOR,
- title: document.title || '',
- totalCharCount: document.content?.length || 0,
- totalLineCount: 0,
- updatedAt: document.updatedAt ? new Date(document.updatedAt) : new Date(),
- };
-
- return fullDocument;
- },
- {
- focusThrottleInterval: 5000,
- onData: (document) => {
- if (!document) return;
-
- // Auto-sync to localDocumentMap
- const { localDocumentMap } = this.#get();
- const newMap = new Map(localDocumentMap);
- newMap.set(documentId!, document);
- this.#set({ localDocumentMap: newMap }, false, n('useFetchDocumentDetail/onData'));
- },
- revalidateOnFocus: true, // 5 seconds
- },
- );
+ removeDocument = async (documentId: string): Promise<void> => {
+ // Drop the row optimistically; restore it if the server rejects the delete.
+ const snapshot = this.#get().documentMap[documentId];
+ this.#documents.remove(documentId);
+
+ try {
+ await documentService.deleteDocument(documentId);
+ } catch (error) {
+ console.error('Failed to delete document:', error);
+ if (snapshot) this.#documents.replace(documentId, snapshot);
+ throw error;
+ }
+ };
+
+ /**
+ * Warm the replica for a document the user is about to open, so the resource
+ * manager paints from the projection (and a later reload hydrates it) instead
+ * of waiting on the network.
+ */
+ prefetchDocument = async (documentId: string): Promise<void> => {
+ try {
+ const row = await documentService.getDocumentById(documentId);
+ this.#documents.replace(documentId, {
+ document: row ? this.#toLobeDocument(row) : null,
+ });
+ } catch (error) {
+ console.error('[FileStore] Failed to prefetch document:', error);
+ }
+ };
+
+ /**
+ * Sync one document through its replica. The view is the source of truth, so
+ * a reload or a return to the route paints from the persisted projection on
+ * the first frame and the network only confirms it.
+ */
+ useFetchDocumentDetail = (documentId: string | undefined): UseFetchDocumentDetailResult => {
+ const entry = useFileStore((s) => (documentId ? s.documentMap[documentId] : undefined));
+
+ const sync = this.#documents.useSync(documentId, {
+ // Keep an open page in step with other writers.
+ revalidateOnFocus: true,
+ });
+
+ return {
+ data: entry?.document,
+ error: sync.error,
+ isLoading: Boolean(documentId) && entry === undefined && sync.error == null,
+ isValidating: sync.isValidating,
+ mutate: sync.revalidate,
+ };
};
}
diff --git a/src/store/file/slices/document/index.ts b/src/store/file/slices/document/index.ts
index 6bdd1f4b2ef..2f9449bdb81 100644
--- a/src/store/file/slices/document/index.ts
+++ b/src/store/file/slices/document/index.ts
@@ -1,3 +1,4 @@
export * from './action';
export * from './initialState';
+export * from './projection';
export * from './selectors';
diff --git a/src/store/file/slices/document/initialState.ts b/src/store/file/slices/document/initialState.ts
index cfac42bdf44..fd374e94d53 100644
--- a/src/store/file/slices/document/initialState.ts
+++ b/src/store/file/slices/document/initialState.ts
@@ -1,52 +1,21 @@
-import { type LobeDocument } from '@/types/document';
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
-export interface DocumentQueryFilter {
- fileTypes?: string[];
- sourceTypes?: string[];
-}
+import { type FileDocumentDetail } from './projection';
export interface DocumentState {
/**
- * current page number (0-based)
- */
- currentPage: number;
- /**
- * Filters used in the last document query
- */
- documentQueryFilter?: DocumentQueryFilter;
- /**
- * Server documents fetched from document service
- */
- documents: LobeDocument[];
- /**
- * total count of documents
- */
- documentsTotal: number;
- /**
- * whether there are more documents to load
- */
- hasMoreDocuments: boolean;
- /**
- * Loading state for document fetching
- */
- isDocumentListLoading: boolean;
- /**
- * loading more documents state
+ * The file store's document rows, keyed by document id — the replica view.
+ * Selectors read this location; the replica slice is its only writer.
*/
- isLoadingMoreDocuments: boolean;
+ documentMap: Record<string, FileDocumentDetail>;
/**
- * Local optimistic document map for immediate UI updates
+ * Replica bookkeeping of `documentMap` (hydration, optimistic overlays,
+ * scope and persistence state).
*/
- localDocumentMap: Map<string, LobeDocument>;
+ fileDocumentReplica: ReplicaState<FileDocumentDetail>;
}
export const initialDocumentState: DocumentState = {
- currentPage: 0,
- documentQueryFilter: undefined,
- documents: [],
- documentsTotal: 0,
- hasMoreDocuments: false,
- isDocumentListLoading: false,
- isLoadingMoreDocuments: false,
- localDocumentMap: new Map(),
+ documentMap: {},
+ fileDocumentReplica: createReplicaState(),
};
diff --git a/src/store/file/slices/document/projection.ts b/src/store/file/slices/document/projection.ts
new file mode 100644
index 00000000000..958a381c7f2
--- /dev/null
+++ b/src/store/file/slices/document/projection.ts
@@ -0,0 +1,33 @@
+import { defineReplica } from '@/libs/replica';
+import { type LobeDocument } from '@/types/document';
+
+/**
+ * The value of one file-store document entry.
+ *
+ * Wrapped in an object on purpose: a replica value can never be `null` (the
+ * engine reads `null` as "keep the current value"), but the resource manager
+ * must tell "the server answered not found" (`document: null`) apart from
+ * "nothing loaded yet" (no entry at all).
+ */
+export interface FileDocumentDetail {
+ /** The document row, or `null` when the server has no such document. */
+ document: LobeDocument | null;
+}
+
+/**
+ * The file store's document rows, one entry per document id.
+ *
+ * The slice is a by-id detail cache: the resource manager resolves the item it
+ * has open through it (page detection, title / emoji editing) and the create
+ * flows insert the row they just made. Persisted to IndexedDB, so returning to
+ * the resources route — or reloading a `?file=` deep link — paints from the
+ * projection while the network only confirms it.
+ *
+ * The "not found" marker is never persisted: it is a page state, not a document.
+ */
+export const fileDocumentResource = defineReplica<string, FileDocumentDetail>({
+ key: (id) => id,
+ name: 'fileDocument',
+ storage: 'indexedDB',
+ version: 1,
+});
diff --git a/src/store/file/slices/document/selectors.ts b/src/store/file/slices/document/selectors.ts
index f46c32eb8cd..4f05e6e4027 100644
--- a/src/store/file/slices/document/selectors.ts
+++ b/src/store/file/slices/document/selectors.ts
@@ -1,66 +1,17 @@
-import { type LobeDocument } from '@/types/document';
-
import { type FilesStoreState } from '../../initialState';
-const getDocumentById = (documentId: string | undefined) => (s: FilesStoreState) => {
- if (!documentId) return undefined;
-
- // First check local optimistic map
- const localDocument = s.localDocumentMap.get(documentId);
-
- // Then check server documents
- const serverDocument = s.documents.find((doc) => doc.id === documentId);
-
- // If both exist, prefer the local update if it's newer
- if (localDocument && serverDocument) {
- return new Date(localDocument.updatedAt) >= new Date(serverDocument.updatedAt)
- ? localDocument
- : serverDocument;
- }
-
- // Return whichever exists, or undefined if neither exists
- return localDocument || serverDocument;
-};
-
/**
- * Get all documents merged from local optimistic map and server data
+ * Resolve the document row an item id refers to, if this client holds it.
+ *
+ * Reads the replica view: a persisted row paints on the first frame, and a
+ * locally written row (created or optimistically renamed) is the same entry.
*/
-const getOptimisticDocuments = (s: FilesStoreState): LobeDocument[] => {
- // Track which documents we've added
- const addedIds = new Set<string>();
-
- // Create result array - start with server documents
- const result: LobeDocument[] = s.documents.map((doc) => {
- addedIds.add(doc.id);
- // Check if we have a local optimistic update for this document
- const localUpdate = s.localDocumentMap.get(doc.id);
- // If local update exists and is newer, use it; otherwise use server version
- if (localUpdate && new Date(localUpdate.updatedAt) >= new Date(doc.updatedAt)) {
- return localUpdate;
- }
- return doc;
- });
-
- // Add any optimistic documents that aren't in server list yet (e.g., newly created temp documents)
- for (const [id, doc] of s.localDocumentMap.entries()) {
- if (!addedIds.has(id)) {
- result.unshift(doc); // Add new documents to the beginning
- }
- }
+const getDocumentById = (documentId: string | undefined) => (s: FilesStoreState) => {
+ if (!documentId) return undefined;
- return result;
+ return s.documentMap[documentId]?.document ?? undefined;
};
-const hasMoreDocuments = (s: FilesStoreState): boolean => s.hasMoreDocuments;
-
-const isLoadingMoreDocuments = (s: FilesStoreState): boolean => s.isLoadingMoreDocuments;
-
-const documentsTotal = (s: FilesStoreState): number => s.documentsTotal;
-
export const documentSelectors = {
- documentsTotal,
getDocumentById,
- getOptimisticDocuments,
- hasMoreDocuments,
- isLoadingMoreDocuments,
};