🤯 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(document): migrate the document detail to @lobechat/replica (#20589)
Arvin Xu743ae9c87ce5
diff --git a/packages/replica/src/zustand/createReplicaSlice.test.ts b/packages/replica/src/zustand/createReplicaSlice.test.tsindex 7adbb0d6465..3e578fd1dc6 100644--- a/packages/replica/src/zustand/createReplicaSlice.test.ts+++ b/packages/replica/src/zustand/createReplicaSlice.test.ts@@ -506,6 +506,107 @@ describe('createReplicaSlice', () => {expect(contexts[0]).toEqual({ key: 'a', scope: 'user-1:personal' });});+ it('evicts the persisted row when a response has nothing to persist', async () => {+ // Two bindings share one storage, so the second one reads what the first+ // one left behind — a reload of the same resource.+ const storage = createMemoryStorage();+ const bind = () => {+ const resource = defineReplica<{ id: string }, string[]>({+ key: ({ id }) => id,+ name: 'evictingList',+ scope,+ storage: storage.storage,+ version: 1,+ });+ const store = createStore<TestState>()(() => ({+ lists: {},+ listsReplica: createReplicaState(),+ }));+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {+ driver,+ get: store.getState,+ set: (partial) => store.setState(partial),+ stateKey: 'listsReplica',+ // `['gone']` is a page state that must never be persisted.+ toPersisted: (data) => (data[0] === 'gone' ? null : data),+ view: recordLens('lists'),+ });+ return { slice, store };+ };++ const first = bind();+ act(() => {+ first.slice.replace({ id: 'a' }, ['cached']);+ });+ await waitFor(() => expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['cached']));++ act(() => {+ first.slice.replace({ id: 'a' }, ['gone']);+ });+ // The value stays in memory…+ expect(first.store.getState().lists.a).toEqual(['gone']);+ // …while the row persisted for it earlier is removed.+ await waitFor(() => expect(storage.rows.has('user-1:personal|a')).toBe(false));++ // A reload hydrates nothing instead of resurrecting the evicted value.+ const reloaded = bind();+ await act(async () => {+ await reloaded.slice.hydrate({ id: 'a' });+ });+ expect(reloaded.store.getState().lists.a).toBeUndefined();+ });++ it('clears a reloaded key from the persisted index when the response has nothing to persist', async () => {+ const storage = createMemoryStorage();+ const indexKey = { queryKey: REPLICA_INDEX_KEY, scope: 'user-1:personal' };+ const bind = () => {+ const resource = defineReplica<{ id: string }, string[]>({+ key: ({ id }) => id,+ name: 'indexedList',+ scope,+ storage: storage.storage,+ version: 1,+ });+ const store = createStore<TestState>()(() => ({+ lists: {},+ listsReplica: createReplicaState(),+ }));+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {+ driver,+ get: store.getState,+ set: (partial) => store.setState(partial),+ stateKey: 'listsReplica',+ toPersisted: (data) => (data[0] === 'gone' ? null : data),+ view: recordLens('lists'),+ });+ return { slice, store };+ };++ const first = bind();+ act(() => {+ first.slice.replace({ id: 'a' }, ['cached']);+ });+ await waitFor(() => expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['cached']));+ await waitFor(async () => expect((await storage.storage.get(indexKey))?.data).toEqual(['a']));++ // A reload: a fresh engine whose in-memory index bookkeeping is empty, so+ // only the persisted index knows the key is there.+ const reloaded = bind();+ await act(async () => {+ await reloaded.slice.hydrate({ id: 'a' });+ });+ expect(reloaded.store.getState().lists.a).toEqual(['cached']);++ act(() => {+ reloaded.slice.replace({ id: 'a' }, ['gone']);+ });+ // The row goes…+ await waitFor(() => expect(storage.rows.has('user-1:personal|a')).toBe(false));+ // …and so does its index entry, so later entity scans do not chase a+ // missing row.+ await waitFor(async () => expect((await storage.storage.get(indexKey))?.data).toEqual([]));+ });+it('a version bump ignores rows written by the previous version', async () => {// One backing map shared by every version, keyed by the namespace the// factory receives — like IndexedDB rows of two app releases.diff --git a/packages/replica/src/zustand/driver.ts b/packages/replica/src/zustand/driver.tsindex 74b31998b82..96d2a2bb49b 100644--- a/packages/replica/src/zustand/driver.ts+++ b/packages/replica/src/zustand/driver.ts@@ -5,6 +5,8 @@export interface ReplicaSyncSchedule {/** Collapse identical requests within this window (ms). */dedupingInterval?: number;+ /** Skip focus revalidation while the last one is younger than this (ms). */+ focusThrottleInterval?: number;/** Poll every N ms while mounted (0 = off); a function decides per tick from the latest data. */refreshInterval?: number | ((latest: any) => number);/** Keep polling while the page is hidden. */diff --git a/src/features/PageEditor/useDocumentLock.ts b/src/features/PageEditor/useDocumentLock.tsindex 9d356195576..49a53f16bfb 100644--- a/src/features/PageEditor/useDocumentLock.ts+++ b/src/features/PageEditor/useDocumentLock.ts@@ -5,10 +5,10 @@ import { useEffect, useMemo, useRef } from 'react';import { type EditLockClient, useEditLock } from '@/features/EditLock';import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';import { usePermission } from '@/hooks/usePermission';-import { mutate } from '@/libs/swr';+import { revalidateReplica } from '@/libs/replica';import { documentService } from '@/services/document';-import { documentSWRKeys } from '@/services/document/swrKeys';import { useDocumentStore } from '@/store/document';+import { documentDetailResource } from '@/store/document/slices/document/projection';import { editorSelectors } from '@/store/document/slices/editor';import { usePageEditorStore } from './store';@@ -133,7 +133,7 @@ export const useDocumentLock = () => {const recovered = prevHealthRef.current === 'lost' && lock.health === 'healthy';prevHealthRef.current = lock.health;if (recovered && documentId) {- void mutate(documentSWRKeys.editor(documentId));+ void revalidateReplica(documentDetailResource, documentId);}}, [lock.health, documentId]);@@ -150,7 +150,7 @@ export const useDocumentLock = () => {const tookOver = wasLockedByOtherRef.current && !isLockedByOther;wasLockedByOtherRef.current = Boolean(isLockedByOther);if (isLockedByOther || tookOver || saveBlockedByLock) {- void mutate(documentSWRKeys.editor(documentId));+ void revalidateReplica(documentDetailResource, documentId);}}, [workspacePage, documentId, isLockedByOther, saveBlockedByLock]);diff --git a/src/features/PageEditor/useResourceEvents.ts b/src/features/PageEditor/useResourceEvents.tsindex d780a1c5b3d..b257d1ed785 100644--- a/src/features/PageEditor/useResourceEvents.ts+++ b/src/features/PageEditor/useResourceEvents.ts@@ -3,10 +3,11 @@import { fetchEventSource } from '@lobechat/utils/client';import { useEffect } from 'react';+import { revalidateReplica } from '@/libs/replica';import { mutate } from '@/libs/swr';import { documentLikeKeys, isDocumentCommentKeyForEvent } from '@/libs/swr/keys';import { documentService } from '@/services/document';-import { documentSWRKeys } from '@/services/document/swrKeys';+import { documentDetailResource } from '@/store/document/slices/document/projection';import { pageSelectors, usePageStore } from '@/store/page';import { useUserStore } from '@/store/user';import { userProfileSelectors } from '@/store/user/slices/auth/selectors';@@ -88,7 +89,7 @@ export const useResourceEvents = () => {if (parsed.type === 'doc.updated') {// Re-fetch; DocumentIdMode re-hydrates the editor on the new// version when the local editor isn't dirty.- void mutate(documentSWRKeys.editor(documentId));+ void revalidateReplica(documentDetailResource, documentId);} else if (parsed.type === 'document.commentsChanged' && workspaceId) {void mutate((key) =>isDocumentCommentKeyForEvent(key, {diff --git a/src/hooks/usePrefetchPage.ts b/src/hooks/usePrefetchPage.tsindex 57a417c5e8f..83e566b31ef 100644--- a/src/hooks/usePrefetchPage.ts+++ b/src/hooks/usePrefetchPage.ts@@ -1,24 +1,21 @@import { useCallback } from 'react';-import { mutate } from '@/libs/swr';-import { documentService } from '@/services/document';-import { documentSWRKeys } from '@/services/document/swrKeys';+import { useDocumentStore } from '@/store/document';/**- * Returns a callback to prefetch page/document data into the SWR cache.- * Call the returned function on mouseEnter to warm the cache before navigation.+ * Returns a callback to prefetch the document detail before navigation.+ * Call the returned function on mouseEnter to warm the replica so the editor+ * paints from the projection instead of a skeleton.** The Pages sidebar list is no longer an SWR cache entry — it is a* `@lobechat/replica` resource that hydrates from IndexedDB on mount — so only- * the editor's document content is warmed here.+ * the document detail is warmed here.*/export const usePrefetchPage = () => {return useCallback((documentId: string) => {if (!documentId) return;- // Prefetch individual document content (for the editor)- mutate(documentSWRKeys.editor(documentId), documentService.getDocumentById(documentId), {- revalidate: false,- });+ // Prefetch the document detail into its replica (for the editor)+ void useDocumentStore.getState().prefetchDocument(documentId);}, []);};diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 2bf5f796581..dbfc67a8fcc 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -20,7 +20,7 @@*/import { type ConversationContext } from '@lobechat/types';-import { agentDocumentSWRKeys, documentSWRKeys } from '@/services/document/swrKeys';+import { agentDocumentSWRKeys } from '@/services/document/swrKeys';type KeyFactory<A extends unknown[]> = ((...args: A) => readonly unknown[]) & { root: string };@@ -1167,7 +1167,6 @@ export const swrKeys = {cron: cronKeys,device: deviceKeys,discover: discoverKeys,- document: documentSWRKeys,electron: electronKeys,eval: evalKeys,expertise: expertiseKeys,diff --git a/src/services/document/invalidation.ts b/src/services/document/invalidation.tsindex cb08cae0fd2..6dc9d43555a 100644--- a/src/services/document/invalidation.ts+++ b/src/services/document/invalidation.ts@@ -1,11 +1,12 @@import { revalidateReplica } from '@/libs/replica';import { mutate } from '@/libs/swr';import { portalKeys } from '@/libs/swr/keys';+import { documentDetailResource } from '@/store/document/slices/document/projection';import { notebookDocumentsResource } from '@/store/notebook/projection';import { pageDetailResource, pageListResource } from '@/store/page/projection';import { agentDocumentSkillsResource } from '@/store/tool/slices/agentDocumentSkills/projection';-import { agentDocumentSWRKeys, documentSWRKeys } from './swrKeys';+import { agentDocumentSWRKeys } from './swrKeys';export type DocumentMutationCause ='agent-document' | 'document-service' | 'notebook' | 'page-title';@@ -35,7 +36,9 @@ export const invalidateDocumentMutation = async (if (documentId) {if (refreshDocumentEditor !== false) {- revalidations.push(mutate(documentSWRKeys.editor(documentId)));+ // The document detail is a replica; its sync lives outside the SWR cache+ // keyed by `document:editor`, so revalidate the replica instead.+ revalidations.push(revalidateReplica(documentDetailResource, documentId));}// The page domain is a `@lobechat/replica` domain, so its by-id copy and// its list sync through `replica:sync` keys rather than the SWR cache:diff --git a/src/services/document/swrKeys.ts b/src/services/document/swrKeys.tsindex 831ff5c4b2e..5d0830b96af 100644--- a/src/services/document/swrKeys.ts+++ b/src/services/document/swrKeys.ts@@ -13,7 +13,3 @@ export const agentDocumentSWRKeys = {['agent:documentReader', agentId, documentId] as const,readDocument: (agentId: string, id: string) => ['agent:documentEditor', agentId, id] as const,};--export const documentSWRKeys = {- editor: (documentId: string) => ['document:editor', documentId] as const,-};diff --git a/src/store/document/index.ts b/src/store/document/index.tsindex 23b899127a1..911ac11b690 100644--- a/src/store/document/index.ts+++ b/src/store/document/index.ts@@ -8,9 +8,13 @@ export { getDocumentStoreState, useDocumentStore } from './store';// Re-export document slice typesexport type {DocumentAction,+ DocumentDetail,+ DocumentDetailSliceState,InitDocumentParams,UseFetchDocumentOptions,+ UseFetchDocumentResult,} from './slices/document';+export { documentDetailResource } from './slices/document';// Re-export editor slice typesexport type {diff --git a/src/store/document/slices/document/action.test.ts b/src/store/document/slices/document/action.test.tsindex 1c32058783c..cff9b0115fb 100644--- a/src/store/document/slices/document/action.test.ts+++ b/src/store/document/slices/document/action.test.ts@@ -1,242 +1,676 @@-import { act, renderHook } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';+/**+ * @vitest-environment happy-dom+ *+ * The document detail is a replica: one row per document id, persisted per+ * identity scope, so the editor's first frame comes 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 type * as SwrModule from '@/libs/swr';-import { useClientDataSWRWithSync } from '@/libs/swr';+import { act, render, 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, replicaSWRDriver } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';import { documentService } from '@/services/document';-import { pageActions } from '@/store/page';+import { initialEditorState } from '@/store/document/slices/editor';import { useDocumentStore } from '../../store';+import { initialDocumentDetailSliceState } from './initialState';+import { documentDetailResource } from './projection';++const mocks = vi.hoisted(() => ({+ activeWorkspaceId: null as string | null,+ upsertDocument: vi.fn(),+}));++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ getActiveWorkspaceId: () => mocks.activeWorkspaceId,+ useActiveWorkspaceId: () => mocks.activeWorkspaceId,+}));vi.mock('@/services/document', () => ({documentService: {getDocumentById: vi.fn(),- updateDocument: vi.fn().mockResolvedValue({- historyAppended: false,- id: 'doc-1',- updatedAt: '2026-01-01T00:00:00.000Z',- }),+ updateDocument: vi.fn(),},}));-vi.mock('@/libs/swr', async (importOriginal) => {- const actual = await importOriginal<typeof SwrModule>();- return {- ...actual,- mutate: vi.fn().mockResolvedValue(undefined),- useClientDataSWRWithSync: vi.fn(() => ({ data: undefined, isValidating: false })),- };-});-vi.mock('@/store/page', () => ({- pageActions: { upsertDocument: vi.fn() },+ pageActions: { upsertDocument: mocks.upsertDocument },}));+const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};++const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => new Map() } },+ createElement(MutateBridge),+ children,+ );++const baseEditorData = {+ root: { children: [{ children: [], type: 'paragraph' }], type: 'root' },+};++/** A document row as the server returns it. */+const documentRow = (overrides: Record<string, unknown> = {}) =>+ ({+ content: '# Server',+ editorData: baseEditorData,+ id: 'doc-1',+ updatedAt: new Date('2026-01-02T00:00:00.000Z'),+ ...overrides,+ }) as any;++/** Never-resolving fetch: the first frame can only come from storage. */+const pending = () => new Promise<never>(() => {});+const createEditor = () => ({getDocument: vi.fn((type: string) => {if (type === 'markdown') return '# Draft';- if (type === 'json') {- return { root: { children: [{ children: [], type: 'paragraph' }], type: 'root' } };- }+ if (type === 'json') return baseEditorData;return null;}),getLexicalEditor: vi.fn(),setDocument: vi.fn(),});-const baseEditorData = {- root: { children: [{ children: [], type: 'paragraph' }], type: 'root' },-};--const captureOnData = (+const renderDocument = (documentId: string,- editor: any,- options: { sourceType?: 'notebook' | 'page'; topicId?: string } = {},-) => {- renderHook(() =>- useDocumentStore.getState().useFetchDocument(documentId, { editor, ...options }),+ editor: ReturnType<typeof createEditor>,+ options: Record<string, unknown> = {},+) =>+ renderHook(+ () => useDocumentStore.getState().useFetchDocument(documentId, { editor, ...options }),+ { wrapper },);- const swrCall = vi.mocked(useClientDataSWRWithSync).mock.calls.at(-1);- return swrCall?.[2]?.onData as (data: unknown) => void;-};-describe('useFetchDocument onData', () => {+const storedRow = (documentId: string, scope: string) =>+ documentDetailResource.storage!.get({ queryKey: documentId, scope });++const detailSliceState = () => ({ ...initialEditorState, ...initialDocumentDetailSliceState });++describe('document detail replica', () => {+ const scopes = new Set<string>();+ let scope = '';++ const useScope = (next: string) => {+ scope = next;+ scopes.add(next);+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ };+beforeEach(() => {- vi.mocked(useClientDataSWRWithSync).mockClear();- const state = useDocumentStore.getState();- Object.keys(state.documents).forEach((id) => state.closeDocument(id));- useDocumentStore.setState({- activeDocumentId: undefined,- editor: undefined,- lastActiveTopicDocumentIdByTopicId: {},- });+ mocks.activeWorkspaceId = null;+ mocks.upsertDocument.mockClear();+ useScope(`document-user-${randomUUID()}:personal`);+ act(() => useDocumentStore.setState(detailSliceState()));+ vi.mocked(documentService.getDocumentById).mockReset();+ vi.mocked(documentService.updateDocument).mockReset();});- it('initializes a document the store has not loaded yet', () => {- const editor = createEditor();- const onData = captureOnData('doc-1', editor, { sourceType: 'notebook', topicId: 'topic-1' });+ afterEach(async () => {+ await Promise.all(+ [...scopes].map((value) =>+ Promise.all(+ ['doc-1', 'doc-2'].map((id) =>+ documentDetailResource.storage!.remove({ queryKey: id, scope: value }),+ ),+ ),+ ),+ );+ scopes.clear();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });- act(() => {- onData({- content: '# Server',- editorData: baseEditorData,- id: 'doc-1',- updatedAt: new Date('2026-01-01T00:00:00.000Z'),- });- });+ it('paints the persisted document into the editor before the network answers', async () => {+ const cached = documentRow({ content: '# Cached' });+ await documentDetailResource.storage!.set(+ { queryKey: 'doc-1', scope },+ { data: { document: cached }, updatedAt: 1 },+ );+ vi.mocked(documentService.getDocumentById).mockImplementation(pending as any);- expect(useDocumentStore.getState().documents['doc-1']).toMatchObject({- content: '# Server',- isDirty: false,- lastUpdatedTime: new Date('2026-01-01T00:00:00.000Z'),- });- expect(useDocumentStore.getState().lastActiveTopicDocumentIdByTopicId).toEqual({- 'topic-1': 'doc-1',- });+ const editor = createEditor();+ const { result } = renderDocument('doc-1', editor);++ await waitFor(() =>+ expect(useDocumentStore.getState().documents['doc-1']?.content).toBe('# Cached'),+ );+ expect(useDocumentStore.getState().documentDetailMap['doc-1']).toEqual({ document: cached });+ expect(result.current.data?.content).toBe('# 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);+ expect(editor.setDocument).not.toHaveBeenCalled();});- it('adopts a newer server body over a dirty draft', () => {+ it('adopts a newer server body over a dirty draft when the sync revalidates', async () => {+ vi.mocked(documentService.getDocumentById).mockResolvedValue(documentRow() as any);const editor = createEditor();- const onData = captureOnData('doc-1', editor, { sourceType: 'notebook', topicId: 'topic-1' });-- act(() => {- useDocumentStore.getState().initDocumentWithEditor({- content: '# Old',- documentId: 'doc-1',- editor: editor as any,- editorData: baseEditorData,- sourceType: 'notebook',- updatedAt: new Date('2026-01-01T00:00:00.000Z'),- });- useDocumentStore.getState().handleContentChange();+ const { result } = renderDocument('doc-1', editor, {+ sourceType: 'notebook',+ topicId: 'topic-1',});++ await waitFor(() => expect(useDocumentStore.getState().documents['doc-1']).toBeDefined());+ act(() => useDocumentStore.getState().handleContentChange());expect(useDocumentStore.getState().documents['doc-1'].isDirty).toBe(true);- useDocumentStore.setState({ lastActiveTopicDocumentIdByTopicId: {} });+ expect(useDocumentStore.getState().lastActiveTopicDocumentIdByTopicId).toEqual({+ 'topic-1': 'doc-1',+ });- act(() => {- onData({+ vi.mocked(documentService.getDocumentById).mockResolvedValue(+ documentRow({content: '# Agent write',- editorData: baseEditorData,- id: 'doc-1',- updatedAt: new Date('2026-01-02T00:00:00.000Z'),- });+ updatedAt: new Date('2026-01-03T00:00:00.000Z'),+ }) as any,+ );+ await act(async () => {+ await result.current.mutate();});expect(useDocumentStore.getState().documents['doc-1']).toMatchObject({content: '# Agent write',isDirty: false,lastSavedContent: '# Agent write',- lastUpdatedTime: new Date('2026-01-02T00:00:00.000Z'),+ lastUpdatedTime: new Date('2026-01-03T00:00:00.000Z'),saveStatus: 'saved',});- expect(useDocumentStore.getState().lastActiveTopicDocumentIdByTopicId).toEqual({- 'topic-1': 'doc-1',- });});- it('keeps the dirty draft when only the server version moved', () => {+ it('keeps the dirty draft when only the server version moved', async () => {+ vi.mocked(documentService.getDocumentById).mockResolvedValue(documentRow() as any);const editor = createEditor();- const onData = captureOnData('doc-1', editor, { sourceType: 'notebook' });+ const { result } = renderDocument('doc-1', editor);- act(() => {- useDocumentStore.getState().initDocumentWithEditor({- content: '# Old',- documentId: 'doc-1',- editor: editor as any,- editorData: baseEditorData,- sourceType: 'notebook',- updatedAt: new Date('2026-01-01T00:00:00.000Z'),- });- useDocumentStore.getState().handleContentChange();- });+ await waitFor(() => expect(useDocumentStore.getState().documents['doc-1']).toBeDefined());+ act(() => useDocumentStore.getState().handleContentChange());- act(() => {- onData({- content: '# Old',- editorData: structuredClone(baseEditorData),- id: 'doc-1',- updatedAt: new Date('2026-01-02T00:00:00.000Z'),- });+ vi.mocked(documentService.getDocumentById).mockResolvedValue(+ documentRow({ updatedAt: new Date('2026-01-05T00:00:00.000Z') }) as any,+ );+ await act(async () => {+ await result.current.mutate();});expect(useDocumentStore.getState().documents['doc-1']).toMatchObject({content: '# Draft',isDirty: true,- lastSavedContent: '# Old',- lastUpdatedTime: new Date('2026-01-02T00:00:00.000Z'),+ lastSavedContent: '# Server',+ lastUpdatedTime: new Date('2026-01-05T00:00:00.000Z'),});});- it('ignores a replayed cached row that is older than the version saved since', async () => {- const editor = createEditor();- const onData = captureOnData('doc-1', editor, { sourceType: 'notebook' });- vi.mocked(documentService.updateDocument).mockResolvedValueOnce({+ it('ignores a replayed row older than the version saved since', async () => {+ vi.mocked(documentService.getDocumentById).mockResolvedValue(documentRow() as any);+ vi.mocked(documentService.updateDocument).mockResolvedValue({historyAppended: false,id: 'doc-1',- updatedAt: '2026-01-02T00:00:00.000Z',- });+ updatedAt: '2026-01-06T00:00:00.000Z',+ } as any);+ const editor = createEditor();+ const { result } = renderDocument('doc-1', editor);- act(() => {- useDocumentStore.getState().initDocumentWithEditor({- content: '# Old',- documentId: 'doc-1',- editor: editor as any,- editorData: baseEditorData,- sourceType: 'notebook',- updatedAt: new Date('2026-01-01T00:00:00.000Z'),- });- useDocumentStore.getState().handleContentChange();- });+ await waitFor(() => expect(useDocumentStore.getState().documents['doc-1']).toBeDefined());+ act(() => useDocumentStore.getState().handleContentChange());await act(async () => {await useDocumentStore.getState().performSave('doc-1');});expect(useDocumentStore.getState().documents['doc-1']).toMatchObject({content: '# Draft',isDirty: false,- lastUpdatedTime: new Date('2026-01-02T00:00:00.000Z'),+ lastUpdatedTime: new Date('2026-01-06T00:00:00.000Z'),});- act(() => {- onData({- content: '# Old',- editorData: baseEditorData,- id: 'doc-1',- updatedAt: new Date('2026-01-01T00:00:00.000Z'),- });+ vi.mocked(documentService.getDocumentById).mockResolvedValue(+ documentRow({ content: '# Server', updatedAt: new Date('2026-01-01T00:00:00.000Z') }) as any,+ );+ await act(async () => {+ await result.current.mutate();});expect(useDocumentStore.getState().documents['doc-1']).toMatchObject({content: '# Draft',isDirty: false,lastSavedContent: '# Draft',- lastUpdatedTime: new Date('2026-01-02T00:00:00.000Z'),+ lastUpdatedTime: new Date('2026-01-06T00:00:00.000Z'),});});- it('mirrors page metadata into the page store on the reconcile path', () => {- const upsertDocument = vi.mocked(pageActions.upsertDocument);+ it('mirrors page metadata into the page store on the reconcile path', async () => {+ const first = documentRow();+ vi.mocked(documentService.getDocumentById).mockResolvedValue(first as any);const editor = createEditor();- const onData = captureOnData('doc-1', editor, { sourceType: 'page' });- const row = {- content: '# Old',- id: 'doc-1',- updatedAt: new Date('2026-01-02T00:00:00.000Z'),+ const { result } = renderDocument('doc-1', editor, { sourceType: 'page' });++ await waitFor(() => expect(mocks.upsertDocument).toHaveBeenCalledWith(first));++ const newer = documentRow({ updatedAt: new Date('2026-01-07T00:00:00.000Z') });+ vi.mocked(documentService.getDocumentById).mockResolvedValue(newer as any);+ await act(async () => {+ await result.current.mutate();+ });++ expect(mocks.upsertDocument).toHaveBeenCalledWith(newer);+ });++ it('resolves a missing document to not found and never persists the marker', async () => {+ vi.mocked(documentService.getDocumentById).mockResolvedValue(undefined as any);+ const editor = createEditor();+ const { result } = renderDocument('doc-1', editor);++ await waitFor(() =>+ expect(useDocumentStore.getState().documentDetailMap['doc-1']).toEqual({ document: null }),+ );+ expect(result.current.data).toBeNull();+ // No editor entry is created for a document that does not exist.+ expect(useDocumentStore.getState().documents['doc-1']).toBeUndefined();+ expect(await storedRow('doc-1', scope)).toBeUndefined();+ });++ it('initializes the editor in the same commit that the projection lands in', async () => {+ const cached = documentRow({ content: '# Cached' });+ await documentDetailResource.storage!.set(+ { queryKey: 'doc-1', scope },+ { data: { document: cached }, updatedAt: 1 },+ );+ vi.mocked(documentService.getDocumentById).mockImplementation(pending as any);++ const editor = createEditor();+ const commits: Array<{ editorReady: boolean; view: boolean }> = [];+ const Probe = () => {+ const view = useDocumentStore((s) => Boolean(s.documentDetailMap['doc-1']));+ const editorReady = useDocumentStore((s) => Boolean(s.documents['doc-1']));+ commits.push({ editorReady, view });+ useDocumentStore((s) => s.useFetchDocument)('doc-1', { editor, sourceType: 'page' });+ return null;};+ render(createElement(Probe), { wrapper });+ await waitFor(() => expect(useDocumentStore.getState().documents['doc-1']).toBeDefined());++ // No committed render may show the projection holding the document while the+ // editor state is still missing: that frame is the skeleton flash a repeat+ // visit is supposed to be free of.+ expect(commits.filter((c) => c.view && !c.editorReady)).toEqual([]);+ expect(useDocumentStore.getState().documents['doc-1']?.content).toBe('# Cached');+ });++ it('drops the previous identity’s document, projection and editor state included', async () => {+ vi.mocked(documentService.getDocumentById).mockResolvedValue(documentRow() as any);+ const editor = createEditor();+ const sync = renderDocument('doc-1', editor);+ await waitFor(() =>+ expect(useDocumentStore.getState().documentDetailMap['doc-1']).toBeDefined(),+ );+ expect(useDocumentStore.getState().documents['doc-1']).toBeDefined();++ vi.mocked(documentService.getDocumentById).mockImplementation(pending as any);+ useScope(`document-user-${randomUUID()}:personal`);+ sync.rerender();++ await waitFor(() =>+ expect(useDocumentStore.getState().documentDetailMap['doc-1']).toBeUndefined(),+ );+ // The editor bucket derived from the previous identity goes with the+ // projection. `DocumentIdMode` gates "loaded" on `documents[id]`, so leaving+ // it behind keeps rendering the previous scope's body.+ expect(useDocumentStore.getState().documents['doc-1']).toBeUndefined();+ });++ it('drops every previous-identity editor entry on a scope reset, not only the mounted one', async () => {+ vi.mocked(documentService.getDocumentById).mockImplementation(+ async (id: string) => documentRow({ id }) as any,+ );+ const first = renderDocument('doc-1', createEditor());+ await waitFor(() => expect(useDocumentStore.getState().documents['doc-1']).toBeDefined());+ // Leave doc-1 without closing it: its editor entry stays behind, inactive.+ first.unmount();+ act(() => useDocumentStore.setState({ activeDocumentId: undefined }));++ const second = renderDocument('doc-2', createEditor());+ await waitFor(() => expect(useDocumentStore.getState().documents['doc-2']).toBeDefined());+ expect(useDocumentStore.getState().documents['doc-1']).toBeDefined();++ vi.mocked(documentService.getDocumentById).mockImplementation(pending as any);+ useScope(`document-user-${randomUUID()}:personal`);+ second.rerender();++ await waitFor(() => expect(useDocumentStore.getState().documentDetailMap).toEqual({}));+ // The inactive doc-1 entry is not watched by any mounted hook, yet it was+ // derived from the reset scope: revisiting it must not paint the old body.+ expect(useDocumentStore.getState().documents['doc-1']).toBeUndefined();+ expect(useDocumentStore.getState().documents['doc-2']).toBeUndefined();+ });++ it('keeps no previous-identity editor state when the new scope’s fetch fails', async () => {+ vi.mocked(documentService.getDocumentById).mockResolvedValue(documentRow() as any);+ const editor = createEditor();+ const sync = renderDocument('doc-1', editor);+ await waitFor(() => expect(useDocumentStore.getState().documents['doc-1']).toBeDefined());++ // The new identity's read fails: nothing may fall back to the old body.+ vi.mocked(documentService.getDocumentById).mockRejectedValue(new Error('offline') as any);+ useScope(`document-user-${randomUUID()}:personal`);+ sync.rerender();++ await waitFor(() => expect(sync.result.current.error).toBeDefined());+ expect(useDocumentStore.getState().documentDetailMap['doc-1']).toBeUndefined();+ expect(useDocumentStore.getState().documents['doc-1']).toBeUndefined();+ });++ it('warms the replica for a hover prefetch so the next visit paints from storage', async () => {+ const prefetched = documentRow({ id: 'doc-2', content: '# Prefetched' });+ vi.mocked(documentService.getDocumentById).mockResolvedValue(prefetched as any);++ await act(async () => {+ await useDocumentStore.getState().prefetchDocument('doc-2');+ });++ expect(useDocumentStore.getState().documentDetailMap['doc-2']).toEqual({+ document: prefetched,+ });+ expect((await storedRow('doc-2', scope))?.data).toEqual({ document: prefetched });+ });++ it('does not leak a prefetch fetched under another identity into the new scope', async () => {+ const previousScope = scope;+ const prefetched = documentRow({ id: 'doc-2', content: '# Old identity' });+ let resolveFetch!: (value: unknown) => void;+ vi.mocked(documentService.getDocumentById).mockImplementation(+ () => new Promise((resolve) => (resolveFetch = resolve)) as any,+ );++ const inflight = useDocumentStore.getState().prefetchDocument('doc-2');+ // The identity switches while the request is in flight.+ useScope(`document-user-${randomUUID()}:personal`);+ resolveFetch(prefetched);+ await act(async () => {+ await inflight;+ });++ // The response was fetched under the previous identity, so it may not land+ // in the new identity's memory…+ expect(useDocumentStore.getState().documentDetailMap['doc-2']).toBeUndefined();+ expect(await storedRow('doc-2', scope)).toBeUndefined();+ // …nor in the previous identity's persisted partition.+ expect(await storedRow('doc-2', previousScope)).toBeUndefined();+ });++ it('evicts a previously persisted document when the server no longer has it', async () => {+ // Cached before the document was deleted / became inaccessible.+ const stale = documentRow({ content: '# Revoked' });+ await documentDetailResource.storage!.set(+ { queryKey: 'doc-1', scope },+ { data: { document: stale }, updatedAt: 1 },+ );+ vi.mocked(documentService.getDocumentById).mockResolvedValue(undefined as any);++ const editor = createEditor();+ const { result } = renderDocument('doc-1', editor);++ await waitFor(() =>+ expect(useDocumentStore.getState().documentDetailMap['doc-1']).toEqual({ document: null }),+ );+ expect(result.current.data).toBeNull();+ // The in-memory "not found" marker is kept, but the stale row is gone.+ await waitFor(async () => expect(await storedRow('doc-1', scope)).toBeUndefined());+ });++ it('a reload cannot resurrect a document the server has dropped', async () => {+ const stale = documentRow({ content: '# Revoked' });+ await documentDetailResource.storage!.set(+ { queryKey: 'doc-1', scope },+ { data: { document: stale }, updatedAt: 1 },+ );+ vi.mocked(documentService.getDocumentById).mockResolvedValue(undefined as any);+ const first = renderDocument('doc-1', createEditor());+ await waitFor(async () => expect(await storedRow('doc-1', scope)).toBeUndefined());+ first.unmount();++ // Reload: memory is gone, so only the persisted projection could paint a+ // first frame — and the read that follows fails.+ act(() => useDocumentStore.setState(detailSliceState()));+ vi.mocked(documentService.getDocumentById).mockRejectedValue(new Error('offline') as any);+ const editor = createEditor();+ const second = renderDocument('doc-1', editor);+ await waitFor(() => expect(second.result.current.error).toBeDefined());++ expect(useDocumentStore.getState().documentDetailMap['doc-1']).toBeUndefined();+ expect(useDocumentStore.getState().documents['doc-1']).toBeUndefined();+ expect(editor.setDocument).not.toHaveBeenCalled();+ });++ it('revalidates on focus with a ~20s throttle', async () => {+ const spy = vi.spyOn(replicaSWRDriver, 'useQuery');+ vi.mocked(documentService.getDocumentById).mockResolvedValue(documentRow() as any);+ renderDocument('doc-1', createEditor());++ await waitFor(() => expect(useDocumentStore.getState().documents['doc-1']).toBeDefined());++ // The app-wide default focus throttle is five minutes; without the explicit+ // option another writer's edit would stay stale for minutes on a personal /+ // notebook document (no workspace-page SSE stream to close the gap).+ const syncCall = spy.mock.calls.find(+ ([, , options]) => (options as { revalidateOnFocus?: boolean })?.revalidateOnFocus,+ );+ expect(syncCall?.[2]).toMatchObject({+ focusThrottleInterval: 20_000,+ revalidateOnFocus: true,+ });+ });++ it('refreshes the persisted detail after a successful save', async () => {+ vi.mocked(documentService.getDocumentById).mockResolvedValue(documentRow() as any);+ vi.mocked(documentService.updateDocument).mockResolvedValue({+ historyAppended: false,+ id: 'doc-1',+ updatedAt: '2026-01-08T00:00:00.000Z',+ } as any);++ renderDocument('doc-1', createEditor());+ await waitFor(() => expect(useDocumentStore.getState().documents['doc-1']).toBeDefined());+ // Only the body the server returned on load is persisted so far.+ expect((await storedRow('doc-1', scope))?.data).toEqual({ document: documentRow() });++ act(() => useDocumentStore.getState().handleContentChange());+ await act(async () => {+ await useDocumentStore.getState().performSave('doc-1');+ });++ // The save is server-confirmed: the replica — and its IndexedDB row — now+ // hold the edited body, so a reload cannot paint the pre-edit one.+ const persisted = await storedRow('doc-1', scope);+ expect(persisted?.data).toEqual({+ document: expect.objectContaining({+ content: '# Draft',+ editorData: baseEditorData,+ updatedAt: new Date('2026-01-08T00:00:00.000Z'),+ }),+ });+ });++ it('mirrors a saved title and emoji into the persisted detail', async () => {+ vi.mocked(documentService.getDocumentById).mockResolvedValue(+ documentRow({ filename: 'Old', metadata: { emoji: '📄' }, title: 'Old' }) as any,+ );+ vi.mocked(documentService.updateDocument).mockResolvedValue({+ historyAppended: false,+ id: 'doc-1',+ updatedAt: '2026-01-08T00:00:00.000Z',+ } as any);++ renderDocument('doc-1', createEditor());+ await waitFor(() => expect(useDocumentStore.getState().documents['doc-1']).toBeDefined());++ await act(async () => {+ await useDocumentStore.getState().performSave('doc-1', { emoji: '🚀', title: 'New' });+ });++ const saved = expect.objectContaining({+ filename: 'New',+ metadata: { emoji: '🚀' },+ title: 'New',+ });+ expect(useDocumentStore.getState().documentDetailMap['doc-1']).toEqual({ document: saved });+ await waitFor(async () =>+ expect((await storedRow('doc-1', scope))?.data).toEqual({ document: saved }),+ );+ });++ it('does not let a sync that started before a save revert the saved detail', async () => {+ vi.mocked(documentService.getDocumentById).mockResolvedValue(documentRow() as any);+ vi.mocked(documentService.updateDocument).mockResolvedValue({+ historyAppended: false,+ id: 'doc-1',+ updatedAt: '2026-01-08T00:00:00.000Z',+ } as any);++ const { result } = renderDocument('doc-1', createEditor());+ await waitFor(() => expect(useDocumentStore.getState().documents['doc-1']).toBeDefined());++ // A focus / SSE revalidation starts and reads the pre-save row…+ let resolveFetch!: (value: unknown) => void;+ vi.mocked(documentService.getDocumentById).mockImplementation(+ () => new Promise((resolve) => (resolveFetch = resolve)) as any,+ );+ let revalidation!: Promise<unknown>;act(() => {- useDocumentStore.getState().initDocumentWithEditor({- content: '# Old',- documentId: 'doc-1',- editor: editor as any,- sourceType: 'page',- updatedAt: new Date('2026-01-01T00:00:00.000Z'),- });+ revalidation = result.current.mutate();+ });+ await waitFor(() => expect(resolveFetch).toBeDefined());++ // …the save lands while it is in flight…+ act(() => useDocumentStore.getState().handleContentChange());+ await act(async () => {+ await useDocumentStore.getState().performSave('doc-1');});++ // …and the late response carries the older row.+ await act(async () => {+ resolveFetch(documentRow());+ await revalidation;+ });++ const saved = expect.objectContaining({+ content: '# Draft',+ updatedAt: new Date('2026-01-08T00:00:00.000Z'),+ });+ expect(useDocumentStore.getState().documentDetailMap['doc-1']).toEqual({ document: saved });+ await waitFor(async () =>+ expect((await storedRow('doc-1', scope))?.data).toEqual({ document: saved }),+ );+ });++ it('does not let a sync that started before an unversioned save revert it', async () => {+ vi.mocked(documentService.getDocumentById).mockResolvedValue(documentRow() as any);+ // An older server: the save result carries no `updatedAt`.+ vi.mocked(documentService.updateDocument).mockResolvedValue({+ historyAppended: false,+ id: 'doc-1',+ } as any);++ const { result } = renderDocument('doc-1', createEditor());+ await waitFor(() => expect(useDocumentStore.getState().documents['doc-1']).toBeDefined());++ let resolveFetch!: (value: unknown) => void;+ vi.mocked(documentService.getDocumentById).mockImplementation(+ () => new Promise((resolve) => (resolveFetch = resolve)) as any,+ );+ let revalidation!: Promise<unknown>;act(() => {- onData(row);+ revalidation = result.current.mutate();+ });+ await waitFor(() => expect(resolveFetch).toBeDefined());++ act(() => useDocumentStore.getState().handleContentChange());+ await act(async () => {+ await useDocumentStore.getState().performSave('doc-1');+ });++ // The late read carries the pre-save body with the very same timestamp.+ await act(async () => {+ resolveFetch(documentRow());+ await revalidation;+ });++ const saved = expect.objectContaining({ content: '# Draft' });+ expect(useDocumentStore.getState().documentDetailMap['doc-1']).toEqual({ document: saved });+ await waitFor(async () =>+ expect((await storedRow('doc-1', scope))?.data).toEqual({ document: saved }),+ );+ });++ it('refreshes an entry already in memory with a newer prefetched row', async () => {+ act(() =>+ useDocumentStore+ .getState()+ .internal_adoptDocumentDetail('doc-2', documentRow({ content: '# Old', id: 'doc-2' })),+ );+ const newer = documentRow({+ content: '# Newer',+ id: 'doc-2',+ updatedAt: new Date('2026-01-09T00:00:00.000Z'),+ });+ vi.mocked(documentService.getDocumentById).mockResolvedValue(newer as any);++ await act(() => useDocumentStore.getState().prefetchDocument('doc-2'));++ expect(useDocumentStore.getState().documentDetailMap['doc-2']).toEqual({ document: newer });+ });++ it('keeps a newer in-memory entry over an older prefetched row', async () => {+ const current = documentRow({+ content: '# Current',+ id: 'doc-2',+ updatedAt: new Date('2026-01-09T00:00:00.000Z'),+ });+ act(() => useDocumentStore.getState().internal_adoptDocumentDetail('doc-2', current));+ vi.mocked(documentService.getDocumentById).mockResolvedValue(+ documentRow({ content: '# Older', id: 'doc-2' }) as any,+ );++ await act(() => useDocumentStore.getState().prefetchDocument('doc-2'));++ expect(useDocumentStore.getState().documentDetailMap['doc-2']).toEqual({ document: current });+ });++ it('does not let a late prefetch overwrite the entry a sync already settled', async () => {+ const stale = documentRow({ id: 'doc-2', content: '# Stale prefetch' });+ let resolvePrefetch!: (value: unknown) => void;+ vi.mocked(documentService.getDocumentById)+ .mockImplementationOnce(() => new Promise((resolve) => (resolvePrefetch = resolve)) as any)+ .mockResolvedValue(undefined as any);++ const inflight = useDocumentStore.getState().prefetchDocument('doc-2');++ // Navigation starts the real sync, which settles the document as not-found.+ renderDocument('doc-2', createEditor());+ await waitFor(() =>+ expect(useDocumentStore.getState().documentDetailMap['doc-2']).toEqual({ document: null }),+ );++ // The prefetch resolves late and must not resurrect the dropped document.+ resolvePrefetch(stale);+ await act(async () => {+ await inflight;});- expect(upsertDocument).toHaveBeenCalledWith(row);- expect(documentService.getDocumentById).not.toHaveBeenCalled();+ expect(useDocumentStore.getState().documentDetailMap['doc-2']).toEqual({ document: null });+ expect(await storedRow('doc-2', scope)).toBeUndefined();});});diff --git a/src/store/document/slices/document/action.ts b/src/store/document/slices/document/action.tsindex b21c24ec745..3dc22ecba02 100644--- a/src/store/document/slices/document/action.ts+++ b/src/store/document/slices/document/action.ts@@ -4,18 +4,20 @@ import { EDITOR_DEBOUNCE_TIME, EDITOR_MAX_WAIT } from '@lobechat/const';import type { DocumentItem } from '@lobechat/database/schemas';import type { IEditor } from '@lobehub/editor';import { debounce } from 'es-toolkit/compat';-import type { SWRResponse } from 'swr';+import { useLayoutEffect } from 'react';-import { useClientDataSWRWithSync } from '@/libs/swr';+import { createReplicaSlice, recordLens } from '@/libs/replica';import { documentService } from '@/services/document';-import { documentSWRKeys } from '@/services/document/swrKeys';import { pageActions } from '@/store/page';import type { StoreSetter } from '@/store/types';import { isSkillMarkdownDocument, parseSkillMarkdownFrontmatter } from '@/utils/skillMarkdown';import { setNamespace } from '@/utils/storeDebug';import type { DocumentStore } from '../../store';+import { useDocumentStore } from '../../store';import type { DocumentContentFormat, DocumentSourceType } from '../editor/initialState';+import type { DocumentDetail } from './projection';+import { documentDetailResource } from './projection';const n = setNamespace('document/document');@@ -60,6 +62,26 @@ export interface UseFetchDocumentOptions {topicId?: string | null;}+/**+ * Result of `useFetchDocument`.+ *+ * `data` is the replica view (`undefined` = nothing loaded for this id yet,+ * `null` = the server answered "not found"). It is read from the store, not+ * returned by the hook, so it paints from the persisted projection on the first+ * frame and the network only confirms it.+ */+export interface UseFetchDocumentResult {+ data: DocumentItem | 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>;+}++const detailLens = recordLens<DocumentStore, DocumentDetail>('documentDetailMap');+type Setter = StoreSetter<DocumentStore>;export const createDocumentSlice = (set: Setter, get: () => DocumentStore, _api?: unknown) =>new DocumentActionImpl(set, get, _api);@@ -68,13 +90,83 @@ export class DocumentActionImpl {readonly #get: () => DocumentStore;readonly #set: Setter;readonly #debouncedSaves = new Map<string, ReturnType<typeof debounce>>();+ /**+ * Per-document count of server rows adopted outside a read (saves, CONFLICT+ * reconciles). A read that saw the count change while in flight started+ * before that row was written, so it must not replace it.+ */+ readonly #adoptions = new Map<string, number>();+ readonly #detail;constructor(set: Setter, get: () => DocumentStore, _api?: unknown) {void _api;this.#set = set;this.#get = get;+ this.#detail = createReplicaSlice(documentDetailResource, {+ actionPrefix: n('documentDetail'),+ fetcher: async (id) => {+ const adoptedBefore = this.#adoptions.get(id) ?? 0;+ const document = (await documentService.getDocumentById(id)) ?? null;+ // A save (or CONFLICT reconcile) adopted a server row while this read was+ // in flight: that row is newer than anything this read saw, even when an+ // older server returned no `updatedAt` to compare. Keep it.+ const current = this.#get().documentDetailMap[id];+ if ((this.#adoptions.get(id) ?? 0) !== adoptedBefore && current) return current;+ return this.#keepNewerDetail(id, { document });+ },+ get,+ set,+ stateKey: 'documentDetailReplica',+ // A "not found" answer is a page state, not a document: never persist it,+ // and evict the row persisted for this document earlier (the engine+ // removes it) so a reload cannot resurrect a deleted / revoked document.+ toPersisted: (data) => (data.document ? data : null),+ view: { ...detailLens, clear: this.#clearDetailView },+ });}+ /**+ * Scope reset (account / workspace switch): drop the projection together with+ * every editor entry derived from it, in the same commit.+ *+ * `useFetchDocument` only watches the document it is mounted for, so editor+ * entries of documents opened earlier in the session would otherwise survive+ * the reset: revisiting one under the new identity would treat the previous+ * identity's body as loaded (and keep showing it if the new fetch fails).+ * Their queued autosaves belong to the previous identity and are cancelled,+ * never flushed under the new one.+ */+ #clearDetailView = (state: DocumentStore): Partial<DocumentStore> => {+ const derivedIds = Object.keys(state.documentDetailMap).filter((id) => state.documents[id]);+ if (derivedIds.length === 0) return detailLens.clear(state);++ const documents = { ...state.documents };+ for (const id of derivedIds) {+ this.#cleanupDebouncedSave(id);+ delete documents[id];+ }+ return { ...detailLens.clear(state), documents };+ };++ /**+ * Order a fetched detail against the entry it is about to replace.+ *+ * A focus / SSE revalidation that started before a save but answers after it+ * carries the pre-save row. The save already adopted the newer revision into+ * the replica, so landing the late response would regress the projection and+ * its IndexedDB row — and a later offline reload would hydrate the pre-save+ * body. Keep the entry when the response is strictly older; a not-found answer+ * and any equal-or-newer revision still win.+ */+ #keepNewerDetail = (documentId: string, fetched: DocumentDetail): DocumentDetail => {+ const current = this.#get().documentDetailMap[documentId]?.document;+ const next = fetched.document;+ if (!current?.updatedAt || !next?.updatedAt) return fetched;+ return new Date(next.updatedAt).getTime() < new Date(current.updatedAt).getTime()+ ? { document: current }+ : fetched;+ };+cancelDebouncedSave = (documentId: string): void => {this.#debouncedSaves.get(documentId)?.cancel();};@@ -217,75 +309,206 @@ export class DocumentActionImpl {};/**- * SWR hook to fetch document and initialize in DocumentStore+ * Clear the editor state derived from a replica entry that has left the view.+ *+ * The only way a loaded entry disappears while this route stays mounted is a+ * replica scope reset (account / workspace switch), which drops every entry+ * of the previous identity. The editor state derived from that entry has to+ * go with it: `DocumentIdMode` treats a present `documents[id]` as "loaded",+ * so leaving it behind renders the previous identity's body — and, once the+ * new scope's request fails, keeps rendering it behind an inline error.+ *+ * A queued autosave is cancelled rather than flushed: it belongs to the+ * previous identity and must not be sent under the new one.+ */+ #clearDerivedDocument = (documentId: string): void => {+ if (!this.#get().documents[documentId]) return;+ this.cancelDebouncedSave(documentId);+ this.#get().internal_dispatchDocument(+ { id: documentId, type: 'deleteDocument' },+ n('clearDerivedDocument'),+ );+ };++ /**+ * Fold one server row into the editor's derived state.+ *+ * Called both when the replica view changes (the persisted projection paints+ * before the network answers) and when a fresh response lands, so the editor+ * adopts a document in either path. Idempotent: an existing entry is only+ * reconciled against, never re-initialized.+ */+ #adoptDocument = (+ documentId: string,+ document: DocumentItem | null,+ options: {+ autoSave?: boolean;+ editor?: IEditor;+ sourceType: DocumentSourceType;+ topicId?: string | null;+ },+ ): void => {+ const { autoSave, editor, sourceType, topicId } = options;+ // `null` = the server answered "not found"; nothing to adopt.+ if (!document || !editor) return;++ // Check if this response is still for the current active document.+ // This prevents race conditions when quickly switching between documents.+ const currentActiveId = this.#get().activeDocumentId;+ if (currentActiveId && currentActiveId !== documentId) return;++ if (this.#get().documents[documentId]) {+ this.#get().reconcileRemote(documentId, document);+ if (sourceType === 'notebook' && topicId) {+ this.#rememberTopicDocument(topicId, documentId);+ }+ if (sourceType === 'page') {+ pageActions.upsertDocument(document);+ }+ return;+ }++ this.#get().initDocumentWithEditor({+ autoSave,+ content: document.content,+ contentFormat: isSkillMarkdownDocument(document) ? 'skillMarkdown' : 'markdown',+ documentId,+ editor,+ editorData: document.editorData,+ sourceType,+ topicId: topicId ?? undefined,+ updatedAt: document.updatedAt,+ });++ // Mirror page metadata (title/emoji) into pageStore so PageExplorer+ // selectors resolve correctly when the page is opened from a context+ // that didn't pre-load the documents list (e.g. task workspace modal).+ if (sourceType === 'page') {+ pageActions.upsertDocument(document);+ }+ };++ /**+ * Fetch a document through its replica and initialize it in the DocumentStore.*/useFetchDocument = (documentId: string | undefined,options: UseFetchDocumentOptions = {},- ): SWRResponse<DocumentItem | null> => {+ ): UseFetchDocumentResult => {const { autoSave = true, editor, sourceType = 'page', topicId } = options;- const swrKey = documentId && editor ? documentSWRKeys.editor(documentId) : null;-- return useClientDataSWRWithSync<DocumentItem | null>(- swrKey,- async () => {- // documentId is guaranteed to be defined when swrKey is not null- const document = await documentService.getDocumentById(documentId!);- if (!document) {- console.warn(`[useFetchDocument] Document not found: ${documentId}`);- return null;- }+ const enabled = Boolean(documentId && editor);- return document;- },- {- focusThrottleInterval: 20_000,- onData: (document) => {- // Both documentId and editor are guaranteed to be defined when this callback is called- if (!document || !documentId || !editor) return;-- // Check if this response is still for the current active document- // This prevents race conditions when quickly switching between documents- const currentActiveId = this.#get().activeDocumentId;-- if (currentActiveId && currentActiveId !== documentId) {- // User has already switched to another document, discard this stale response- return;- }+ // The view is the source of truth: read it from the store so a reload paints+ // the persisted projection on the first frame, before the network answers.+ const entry = useDocumentStore((s) =>+ documentId ? s.documentDetailMap[documentId] : undefined,+ );+ const document = entry?.document;++ const sync = this.#detail.useSync(enabled ? documentId : undefined, {+ // Keep a long-open editor in step with other writers. Personal and+ // notebook documents have no workspace-page SSE stream, so the app-wide+ // five-minute focus throttle would leave another writer's edit stale for+ // minutes after returning to the tab — ~20s is the window this was tuned+ // to before the migration.+ focusThrottleInterval: 20_000,+ revalidateOnFocus: true,+ });- if (this.#get().documents[documentId]) {- this.#get().reconcileRemote(documentId, document);- if (sourceType === 'notebook' && topicId) {- this.#rememberTopicDocument(topicId, documentId);- }- if (sourceType === 'page') {- pageActions.upsertDocument(document);- }- return;- }+ useLayoutEffect(() => {+ if (!enabled || !documentId) return;++ // Adopt *synchronously with the store write that produced the entry*, so+ // the editor state lands in the same commit as the hydrated view. Waiting+ // for a passive effect — or for `isHydrated`, which only flips in a later+ // commit — leaves a painted frame where the projection already holds the+ // document but `documents[id]` is still missing, and that frame is exactly+ // the skeleton flash a repeat visit is supposed to avoid.+ const adopt = (state: DocumentStore, previous?: DocumentStore) => {+ const next = state.documentDetailMap[documentId];+ if (!next) {+ // The entry left the view: a scope reset dropped the previous+ // identity's entries. Its derived editor state must not outlive it —+ // see `#clearDerivedDocument`.+ if (previous?.documentDetailMap[documentId]) this.#clearDerivedDocument(documentId);+ return;+ }+ // Only react to *this* entry changing; every other store write (typing+ // in the editor included) is none of our business.+ if (previous && previous.documentDetailMap[documentId] === next) return;+ // Entries are scope-owned by the engine; never adopt one that belongs to+ // another identity (this hook can stay mounted across an identity switch).+ const scope = state.documentDetailReplica?.scope;+ if (scope !== undefined && scope !== documentDetailResource.scope.get()) return;+ this.#adoptDocument(documentId, next.document, { autoSave, editor, sourceType, topicId });+ };++ // An entry already in memory (repeat visit in this session) never writes+ // again, so adopt it now; hydration and every response go through the+ // subscription.+ adopt(useDocumentStore.getState());+ return useDocumentStore.subscribe(adopt);+ }, [autoSave, documentId, editor, enabled, sourceType, topicId]);++ return {+ data: document,+ error: sync.error,+ isLoading: enabled && document === undefined && sync.error == null,+ isValidating: sync.isValidating,+ mutate: sync.revalidate,+ };+ };- this.#get().initDocumentWithEditor({- autoSave,- content: document.content,- contentFormat: isSkillMarkdownDocument(document) ? 'skillMarkdown' : 'markdown',- documentId,- editor,- editorData: document.editorData,- sourceType,- topicId: topicId ?? undefined,- updatedAt: document.updatedAt,- });-- // Mirror page metadata (title/emoji) into pageStore so PageExplorer- // selectors resolve correctly when the page is opened from a context- // that didn't pre-load the documents list (e.g. task workspace modal).- if (sourceType === 'page') {- pageActions.upsertDocument(document);- }- },- revalidateOnFocus: true,- },- );+ /**+ * Warm the replica for a document the user is about to open (hover prefetch),+ * so navigation paints the editor from the projection instead of a skeleton.+ */+ prefetchDocument = async (documentId: string): Promise<void> => {+ // Capture the identity BEFORE the request. An account / workspace switch+ // while it is in flight would otherwise make `replace` fall back to the new+ // scope and write the old identity's document into its memory and IndexedDB+ // partition. The regular `useSync` path captures the scope the same way; the+ // engine drops an action whose scope is no longer active.+ const scope = documentDetailResource.scope.get();+ try {+ const before = this.#get().documentDetailMap[documentId];+ const document = await documentService.getDocumentById(documentId);+ // A sync or save that wrote the entry while this was in flight owns it+ // now: it may hold a newer revision, or a confirmed absence. Never let a+ // late prefetch regress it — e.g. resurrect the body of a document the+ // sync has just settled as not-found.+ if (this.#get().documentDetailMap[documentId] !== before) return;+ // Otherwise the response refreshes the entry (a retained one may be stale+ // from an earlier visit), unless it is strictly older than it.+ this.#detail.replace(+ documentId,+ this.#keepNewerDetail(documentId, { document: document ?? null }),+ scope,+ );+ } catch (error) {+ console.error('[DocumentStore] Failed to prefetch document:', error);+ }+ };++ /**+ * Adopt a server row the caller already holds (e.g. the save pipeline+ * reconciling a CONFLICT) so the replica — not a stale fetch — is what the+ * editor hydrates from next.+ *+ * `scope` is the identity the row was fetched under, captured *before* the+ * request. Pass it whenever the caller awaited something in between: an+ * account / workspace switch would otherwise make `replace` fall back to the+ * new scope and write the previous identity's document into its memory and+ * IndexedDB partition. The engine drops an action whose scope is no longer+ * active.+ */+ internal_adoptDocumentDetail = (+ documentId: string,+ document: DocumentItem | null,+ scope?: string,+ ): void => {+ this.#adoptions.set(documentId, (this.#adoptions.get(documentId) ?? 0) + 1);+ this.#detail.replace(documentId, { document }, scope);};}diff --git a/src/store/document/slices/document/index.ts b/src/store/document/slices/document/index.tsindex 01d713cccf9..9acdf228c6b 100644--- a/src/store/document/slices/document/index.ts+++ b/src/store/document/slices/document/index.ts@@ -3,4 +3,7 @@ export {type DocumentAction,type InitDocumentParams,type UseFetchDocumentOptions,+ type UseFetchDocumentResult,} from './action';+export { type DocumentDetailSliceState, initialDocumentDetailSliceState } from './initialState';+export { type DocumentDetail, documentDetailResource } from './projection';diff --git a/src/store/document/slices/document/initialState.ts b/src/store/document/slices/document/initialState.tsnew file mode 100644index 00000000000..36d52761c4e--- /dev/null+++ b/src/store/document/slices/document/initialState.ts@@ -0,0 +1,15 @@+import { createReplicaState, type ReplicaState } from '@/libs/replica';++import type { DocumentDetail } from './projection';++export interface DocumentDetailSliceState {+ /** Server rows of the documents opened this session, keyed by document id. */+ documentDetailMap: Record<string, DocumentDetail>;+ /** Replica bookkeeping of `documentDetailMap` (its view). */+ documentDetailReplica: ReplicaState<DocumentDetail>;+}++export const initialDocumentDetailSliceState: DocumentDetailSliceState = {+ documentDetailMap: {},+ documentDetailReplica: createReplicaState(),+};diff --git a/src/store/document/slices/document/projection.ts b/src/store/document/slices/document/projection.tsnew file mode 100644index 00000000000..2e21c4a3743--- /dev/null+++ b/src/store/document/slices/document/projection.ts@@ -0,0 +1,29 @@+import type { DocumentItem } from '@lobechat/database/schemas';++import { defineReplica } from '@/libs/replica';++/**+ * The value of one document-detail 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 editor page must+ * tell "the server answered not found" (`document: null`, so it can settle on+ * its 404) apart from "nothing loaded yet" (no entry at all).+ */+export interface DocumentDetail {+ /** The server row, or `null` when the server has no such document. */+ document: DocumentItem | null;+}++/**+ * One document detail per entry, keyed by the document id it was opened with.+ * Persisted to IndexedDB: on a reload the editor's first frame comes from the+ * projection and the network only confirms it. The "not found" marker is never+ * persisted — it is a page state, not a document.+ */+export const documentDetailResource = defineReplica<string, DocumentDetail>({+ key: (id) => id,+ name: 'documentDetail',+ storage: 'indexedDB',+ version: 1,+});diff --git a/src/store/document/slices/editor/action.reconcile.test.ts b/src/store/document/slices/editor/action.reconcile.test.tsindex 437fa55ee1a..64ad603382e 100644--- a/src/store/document/slices/editor/action.reconcile.test.ts+++ b/src/store/document/slices/editor/action.reconcile.test.ts@@ -1,9 +1,11 @@-import { act, renderHook } from '@testing-library/react';+import { act, renderHook, waitFor } from '@testing-library/react';import { describe, expect, it, vi } from 'vitest';+import { cacheScope } from '@/libs/replica';import { documentService } from '@/services/document';import { useDocumentStore } from '../../store';+import { documentDetailResource } from '../document/projection';// Mock servicesvi.mock('@/services/document', () => ({@@ -654,5 +656,83 @@ describe('DocumentStore - Editor Actions (reconcile)', () => {});vi.useRealTimers();});++ it('drops a CONFLICT reconciliation whose read lands after the identity moved on', async () => {+ const previousScope = 'user_previous:personal';+ const nextScope = 'user_next:personal';+ const scopeSpy = vi.spyOn(cacheScope, 'get').mockReturnValue(previousScope);+ const persistSpy = vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);++ try {+ const { result } = renderHook(() => useDocumentStore());+ const conflict = Object.assign(new Error('conflict'), { data: { code: 'CONFLICT' } });+ vi.mocked(documentService.updateDocument).mockRejectedValue(conflict);++ let resolveFetch!: (value: unknown) => void;+ vi.mocked(documentService.getDocumentById).mockImplementation(+ () => new Promise((resolve) => (resolveFetch = resolve)) as any,+ );++ // The editor holds an unsaved local draft the mock reports back verbatim.+ const savedEditorData = { root: { children: [], type: 'root' } };+ const draftEditorData = {+ root: { children: [{ children: [], type: 'paragraph' }], type: 'root' },+ };+ const editor = {+ ...createValidMockEditor(),+ getDocument: vi.fn((type: string) => {+ if (type === 'markdown') return '# Local draft';+ if (type === 'json') return draftEditorData;+ return null;+ }),+ };++ act(() => {+ result.current.initDocumentWithEditor({+ content: '# Saved',+ documentId: 'doc-1',+ editor: editor as any,+ editorData: savedEditorData,+ sourceType: 'page',+ updatedAt: new Date('2025-12-31T00:00:00.000Z'),+ });+ result.current.markDirty('doc-1');+ });++ let save!: Promise<unknown>;+ await act(async () => {+ save = result.current+ .performSave('doc-1', undefined, { saveSource: 'manual' })+ .catch(() => undefined);+ });++ // The account / workspace switches while the reconciliation read is in flight.+ scopeSpy.mockReturnValue(nextScope);+ await act(async () => {+ resolveFetch({+ content: '# Remote from the previous identity',+ id: 'doc-1',+ updatedAt: new Date('2026-01-05T00:00:00.000Z'),+ });+ await save;+ });++ // The previous identity's row must not reach the new identity's editor state…+ expect(result.current.documents['doc-1']).toMatchObject({+ content: '# Local draft',+ isDirty: true,+ });+ // …nor its replica memory or persisted partition.+ expect(useDocumentStore.getState().documentDetailMap['doc-1']).toBeUndefined();+ await waitFor(async () => {+ expect(+ await documentDetailResource.storage!.get({ queryKey: 'doc-1', scope: nextScope }),+ ).toBeUndefined();+ });+ } finally {+ scopeSpy.mockRestore();+ persistSpy.mockRestore();+ }+ });});});diff --git a/src/store/document/slices/editor/action.ts b/src/store/document/slices/editor/action.tsindex 14968fea8b4..b6175b904b6 100644--- a/src/store/document/slices/editor/action.ts+++ b/src/store/document/slices/editor/action.ts@@ -8,14 +8,13 @@ import { t } from 'i18next';import { EMPTY_EDITOR_STATE } from '@/libs/editor/constants';import { isValidEditorData } from '@/libs/editor/isValidEditorData';-import { mutate } from '@/libs/swr';import { documentService } from '@/services/document';-import { documentSWRKeys } from '@/services/document/swrKeys';import type { StoreSetter } from '@/store/types';import { composeSkillMarkdown, parseSkillMarkdownFrontmatter } from '@/utils/skillMarkdown';import { setNamespace } from '@/utils/storeDebug';import type { DocumentStore } from '../../store';+import { documentDetailResource } from '../document/projection';import type { DocumentDispatch } from './reducer';import { documentReducer } from './reducer';@@ -333,6 +332,9 @@ export class EditorActionImpl {metadata?: SaveMetadata,options?: SaveExecutionOptions,): Promise<void> => {+ // Capture the identity before the request: the detail replica must not be+ // refreshed under a new account / workspace if one switches mid-save.+ const scope = documentDetailResource.scope.get();const { documents, internal_dispatchDocument } = this.#get();const doc = documents[id];if (!doc) return;@@ -402,6 +404,32 @@ export class EditorActionImpl {},});+ // The server now holds this body. Mirror it into the detail replica: its+ // IndexedDB row is what a reload paints before the network answers, so+ // leaving the pre-edit body there would render stale content — and keep+ // rendering it when the confirming read is slow or fails.+ const cachedDetail = this.#get().documentDetailMap[id]?.document;+ if (cachedDetail) {+ this.#get().internal_adoptDocumentDetail(+ id,+ {+ ...cachedDetail,+ content: currentContent,+ editorData: currentEditorData,+ // Mirror the metadata this save wrote, exactly as the server applies+ // it (`title` also renames `filename`; `metadata` is replaced). A+ // stale title / emoji here would be republished by the next body+ // save and painted by a reload whose confirming read fails.+ ...(metadata?.title !== undefined+ ? { filename: metadata.title, title: metadata.title }+ : {}),+ ...(metadata?.emoji ? { metadata: { emoji: metadata.emoji } } : {}),+ updatedAt: savedAt ?? cachedDetail.updatedAt,+ },+ scope,+ );+ }+if (this.#get().documents[id]?.isDirty && doc.autoSave !== false) {this.#get().triggerDebouncedSave(id);}@@ -446,6 +474,12 @@ export class EditorActionImpl {const errorCode = (error as { data?: { code?: string } })?.data?.code;if (errorCode !== 'CONFLICT') throw error;+ // Capture the identity BEFORE the request, like the sync and prefetch paths.+ // An account / workspace switch while the read is in flight must not+ // reconcile the previous identity's row into the new identity's editor+ // state, nor persist it into the new scope's replica partition.+ const scope = documentDetailResource.scope.get();+let latest: Awaited<ReturnType<typeof documentService.getDocumentById>>;try {latest = await documentService.getDocumentById(id);@@ -453,10 +487,14 @@ export class EditorActionImpl {throw error;}if (!latest?.updatedAt) throw error;+ // The identity moved on while we were fetching: this reconciliation is stale.+ if (scope !== documentDetailResource.scope.get()) throw error;const outcome = this.reconcileRemote(id, latest);if (outcome === 'adopted') {- void mutate(documentSWRKeys.editor(id), latest, { revalidate: false });+ // Feed the adopted row back into the detail replica so the next sync+ // reconciles against it instead of re-adopting a stale server read.+ this.#get().internal_adoptDocumentDetail(id, latest, scope);}if (outcome === 'adopted' || !canRetry) throw error;diff --git a/src/store/document/store.ts b/src/store/document/store.tsindex 15543ce45c0..dccd9acc1df 100644--- a/src/store/document/store.ts+++ b/src/store/document/store.ts@@ -6,13 +6,17 @@ import { createDevtools } from '../middleware/createDevtools';import { expose } from '../middleware/expose';import { flattenActions } from '../utils/flattenActions';import { type ResetableStore, ResetableStoreAction } from '../utils/resetableStore';-import { type DocumentAction } from './slices/document';+import {+ type DocumentAction,+ type DocumentDetailSliceState,+ initialDocumentDetailSliceState,+} from './slices/document';import { createDocumentSlice } from './slices/document';import { type EditorAction, type EditorState } from './slices/editor';import { createEditorSlice, initialEditorState } from './slices/editor';// State type-export type DocumentState = EditorState;+export type DocumentState = EditorState & DocumentDetailSliceState;// Action typeexport type DocumentStoreAction = DocumentAction & EditorAction & ResetableStore;@@ -23,6 +27,7 @@ export type DocumentStore = DocumentState & DocumentStoreAction;// Initial stateconst initialState: DocumentState = {...initialEditorState,+ ...initialDocumentDetailSliceState,};class DocumentStoreResetAction extends ResetableStoreAction<DocumentStore> {