Skip to content

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

πŸ› fix: isolate document hydration and metadata saves (#21182)

AmAzing-23755f074207
diff --git a/src/features/EditorCanvas/DocumentIdMode.test.tsx b/src/features/EditorCanvas/DocumentIdMode.test.tsx
index 7e9b9f10826..70b2bd59ee9 100644
--- a/src/features/EditorCanvas/DocumentIdMode.test.tsx
+++ b/src/features/EditorCanvas/DocumentIdMode.test.tsx
@@ -121,7 +121,7 @@ describe('DocumentIdMode', () => {
render(<DocumentIdMode documentId="doc-1" editor={editor} onInit={onInit} />);
await waitFor(() => {
- expect(onEditorInit).toHaveBeenCalledWith(editor);
+ expect(onEditorInit).toHaveBeenCalledWith(editor, 'doc-1');
expect(onInit).toHaveBeenCalledWith(editor);
});
});
diff --git a/src/features/EditorCanvas/DocumentIdMode.tsx b/src/features/EditorCanvas/DocumentIdMode.tsx
index 2277b15b39f..219d3092aa2 100644
--- a/src/features/EditorCanvas/DocumentIdMode.tsx
+++ b/src/features/EditorCanvas/DocumentIdMode.tsx
@@ -136,7 +136,7 @@ const DocumentIdMode = memo<DocumentIdModeProps>(
initializedDocIdRef.current = documentId;
hydratedVersionRef.current = remoteDocumentVersion;
- void onEditorInit(editorInstance).finally(() => {
+ void onEditorInit(editorInstance, documentId).finally(() => {
onInit?.(editorInstance);
});
},
@@ -160,7 +160,7 @@ const DocumentIdMode = memo<DocumentIdModeProps>(
// Lock content-change callback while hydrating document content into editor.
contentChangeLockRef.current = true;
- void onEditorInit(editor).finally(() => {
+ void onEditorInit(editor, documentId).finally(() => {
onInit?.(editor);
queueMicrotask(() => {
if (initRunIdRef.current === runId) {
@@ -198,7 +198,7 @@ const DocumentIdMode = memo<DocumentIdModeProps>(
const runId = ++initRunIdRef.current;
contentChangeLockRef.current = true;
- void onEditorInit(editor).finally(() => {
+ void onEditorInit(editor, documentId).finally(() => {
onInit?.(editor);
queueMicrotask(() => {
if (initRunIdRef.current === runId) {
diff --git a/src/features/PageEditor/store/action.ts b/src/features/PageEditor/store/action.ts
index 50716307fea..45920de7508 100644
--- a/src/features/PageEditor/store/action.ts
+++ b/src/features/PageEditor/store/action.ts
@@ -182,7 +182,7 @@ export const store: (initState?: Partial<State>) => StateCreator<Store> =
emoji,
title,
},
- { saveSource: 'autosave' },
+ { metadataOnly: true, saveSource: 'autosave' },
);
// Notify parent after successful save. The callbacks were captured
diff --git a/src/features/PageEditor/store/metaSync.test.ts b/src/features/PageEditor/store/metaSync.test.ts
index 2513998ae1f..d0f85473220 100644
--- a/src/features/PageEditor/store/metaSync.test.ts
+++ b/src/features/PageEditor/store/metaSync.test.ts
@@ -49,7 +49,7 @@ describe('PageEditorStore - meta save vs in-flight typing', () => {
expect(performSaveMock).toHaveBeenLastCalledWith(
'docs_1',
{ emoji: undefined, title: 'abcdef' },
- { saveSource: 'autosave' },
+ { metadataOnly: true, saveSource: 'autosave' },
);
expect(store.getState().isMetaDirty).toBe(false);
expect(store.getState().lastSavedTitle).toBe('abcdef');
diff --git a/src/features/PageExplorer/index.tsx b/src/features/PageExplorer/index.tsx
index 3500e936f2d..2d7638a0e6e 100644
--- a/src/features/PageExplorer/index.tsx
+++ b/src/features/PageExplorer/index.tsx
@@ -3,7 +3,8 @@
import { memo, type ReactNode, useCallback } from 'react';
import { PageEditor } from '@/features/PageEditor';
-import { pageActions, pageSelectors, usePageStore } from '@/store/page';
+import { invalidateDocumentMutation } from '@/services/document/invalidation';
+import { pageSelectors, usePageStore } from '@/store/page';
interface PageExplorerProps {
/** Forwarded to PageEditor. */
@@ -29,20 +30,11 @@ const PageExplorer = memo<PageExplorerProps>(({ pageId, header, fullWidthHeader,
const title = document?.title;
const emoji = document?.metadata?.emoji as string | undefined;
- // Optimistic update handlers for title and emoji
- const handleTitleChange = useCallback(
- (newTitle: string) => {
- pageActions.updatePageOptimistically(pageId, { title: newTitle });
- },
- [pageId],
- );
-
- const handleEmojiChange = useCallback(
- (newEmoji: string | undefined) => {
- pageActions.updatePageOptimistically(pageId, { emoji: newEmoji });
- },
- [pageId],
- );
+ // PageEditor has already persisted the metadata. Only refresh its readers:
+ // a second rename would advance the server version behind the editor's back.
+ const handleMetadataSaved = useCallback(() => {
+ void invalidateDocumentMutation({ documentId: pageId, refreshDocumentEditor: false });
+ }, [pageId]);
return (
<PageEditor
@@ -53,8 +45,8 @@ const PageExplorer = memo<PageExplorerProps>(({ pageId, header, fullWidthHeader,
pageId={pageId}
rightPanel={rightPanel}
title={title}
- onEmojiChange={handleEmojiChange}
- onTitleChange={handleTitleChange}
+ onEmojiChange={handleMetadataSaved}
+ onTitleChange={handleMetadataSaved}
/>
);
});
diff --git a/src/features/ResourceManager/index.tsx b/src/features/ResourceManager/index.tsx
index f9bfbc78da3..aaed7b176a2 100644
--- a/src/features/ResourceManager/index.tsx
+++ b/src/features/ResourceManager/index.tsx
@@ -9,6 +9,7 @@ import { PageEditor } from '@/features/PageEditor';
import { useResourceManagerStore } from '@/features/ResourceManager/store';
import { usePermission } from '@/hooks/usePermission';
import dynamic from '@/libs/next/dynamic';
+import { invalidateDocumentMutation } from '@/services/document/invalidation';
import { useFileStore } from '@/store/file';
import { documentSelectors } from '@/store/file/slices/document/selectors';
@@ -75,7 +76,6 @@ 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();
@@ -112,26 +112,15 @@ const ResourceManager = memo<ResourceManagerProps>(({ content }) => {
});
};
- // Optimistic update handlers for page title and emoji
- const handleTitleChange = useCallback(
- (newTitle: string) => {
- if (currentViewItemId) {
- updateDocumentOptimistically(currentViewItemId, { title: newTitle });
- }
- },
- [currentViewItemId, updateDocumentOptimistically],
- );
-
- const handleEmojiChange = useCallback(
- (newEmoji: string | undefined) => {
- if (currentViewItemId) {
- updateDocumentOptimistically(currentViewItemId, {
- metadata: { ...currentDocument?.metadata, emoji: newEmoji },
- });
- }
- },
- [currentViewItemId, currentDocument?.metadata, updateDocumentOptimistically],
- );
+ // The editor owns the write; refreshing readers must not issue another rename.
+ const handleMetadataSaved = useCallback(() => {
+ if (!currentViewItemId) return;
+ void invalidateDocumentMutation({
+ documentId: currentViewItemId,
+ refreshDocumentEditor: false,
+ refreshResources: true,
+ });
+ }, [currentViewItemId]);
return (
<>
@@ -161,8 +150,8 @@ const ResourceManager = memo<ResourceManagerProps>(({ content }) => {
pageId={currentViewItemId}
title={currentDocument?.title}
onBack={handleBack}
- onEmojiChange={handleEmojiChange}
- onTitleChange={handleTitleChange}
+ onEmojiChange={handleMetadataSaved}
+ onTitleChange={handleMetadataSaved}
/>
</Flexbox>
)}
diff --git a/src/services/document/invalidation.test.ts b/src/services/document/invalidation.test.ts
index b465913c250..e7c5ee8fd8d 100644
--- a/src/services/document/invalidation.test.ts
+++ b/src/services/document/invalidation.test.ts
@@ -3,7 +3,9 @@ import { act, renderHook, waitFor } from '@testing-library/react';
import useSWR from 'swr';
import { describe, expect, it, vi } from 'vitest';
+import { documentService } from '@/services/document';
import { documentDetailResource } from '@/store/document/slices/document/projection';
+import { fileDocumentResource } from '@/store/file/slices/document/projection';
import { invalidateDocumentMutation } from './invalidation';
@@ -40,4 +42,41 @@ describe('invalidateDocumentMutation', () => {
expect(result.current.document.data).toEqual(row);
expect(otherFetcher).toHaveBeenCalledTimes(otherCalls);
});
+ it('refreshes saved resource metadata without rewriting it or rehydrating a dirty editor', async () => {
+ const id = 'metadata-only-document';
+ const mutation = vi.spyOn(documentService, 'updateDocument');
+ let row = { title: 'Before' };
+ const fileFetcher = vi.fn(async () => row);
+ const editorFetcher = vi.fn(async () => ({ content: 'Saved body' }));
+ const { result } = renderHook(() => ({
+ document: useSWR(
+ replicaKeys.sync(
+ fileDocumentResource.name,
+ fileDocumentResource.version,
+ fileDocumentResource.scope.get(),
+ id,
+ id,
+ ),
+ fileFetcher,
+ ),
+ editor: useSWR(documentDetailSyncKey(id), editorFetcher),
+ }));
+ await waitFor(() => expect(result.current.document.data?.title).toBe('Before'));
+ await waitFor(() => expect(result.current.editor.data?.content).toBe('Saved body'));
+ const editorCalls = editorFetcher.mock.calls.length;
+ row = { title: 'Already saved' };
+
+ await act(async () => {
+ await invalidateDocumentMutation({
+ documentId: id,
+ refreshDocumentEditor: false,
+ refreshResources: true,
+ });
+ });
+
+ expect(result.current.document.data?.title).toBe('Already saved');
+ expect(editorFetcher).toHaveBeenCalledTimes(editorCalls);
+ expect(mutation).not.toHaveBeenCalled();
+ mutation.mockRestore();
+ });
});
diff --git a/src/services/document/invalidation.ts b/src/services/document/invalidation.ts
index d76e077ec5b..fb01d0b4f7a 100644
--- a/src/services/document/invalidation.ts
+++ b/src/services/document/invalidation.ts
@@ -5,6 +5,8 @@ import {
agentDocumentReaderResource,
} from '@/store/agentDocument/projection';
import { documentDetailResource } from '@/store/document/slices/document/projection';
+import { fileDocumentResource } from '@/store/file/slices/document/projection';
+import { resourceListResource } from '@/store/file/slices/resource/projection';
import { notebookDocumentsResource } from '@/store/notebook/projection';
import { pageDetailResource, pageListResource } from '@/store/page/projection';
import { agentDocumentSkillsResource } from '@/store/tool/slices/agentDocumentSkills/projection';
@@ -18,13 +20,21 @@ export interface InvalidateDocumentMutationParams {
documentId?: string;
refreshDocumentEditor?: boolean;
refreshPageDocuments?: boolean;
+ refreshResources?: boolean;
topicId?: string;
}
export const invalidateDocumentMutation = async (
params: InvalidateDocumentMutationParams,
): Promise<void> => {
- const { agentId, documentId, refreshDocumentEditor, refreshPageDocuments, topicId } = params;
+ const {
+ agentId,
+ documentId,
+ refreshDocumentEditor,
+ refreshPageDocuments,
+ refreshResources,
+ topicId,
+ } = params;
const revalidations: Promise<unknown>[] = [];
if (documentId) {
@@ -44,6 +54,11 @@ export const invalidateDocumentMutation = async (
revalidations.push(revalidateReplica(pageListResource));
}
+ if (refreshResources) {
+ if (documentId) revalidations.push(revalidateReplica(fileDocumentResource, documentId));
+ revalidations.push(revalidateReplica(resourceListResource));
+ }
+
if (topicId) {
// The topic's document list is a replica, so its sync lives outside the
// legacy `notebook:documents` SWR entry. Refresh the affected topic only: a
diff --git a/src/store/document/slices/editor/action.identity.test.ts b/src/store/document/slices/editor/action.identity.test.ts
new file mode 100644
index 00000000000..25b938c6373
--- /dev/null
+++ b/src/store/document/slices/editor/action.identity.test.ts
@@ -0,0 +1,147 @@
+import type { IEditor } from '@lobehub/editor';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { documentService } from '@/services/document';
+
+import { useDocumentStore } from '../../store';
+
+vi.mock('@/services/document', () => ({
+ documentService: {
+ updateDocument: vi.fn(),
+ },
+}));
+vi.mock('@/services/notebook', () => ({ notebookService: {} }));
+
+const body = (text: string) => ({
+ root: { children: [{ children: [{ text, type: 'text' }], type: 'paragraph' }], type: 'root' },
+});
+const makeEditor = (text: string) => {
+ const editor = {
+ getDocument: vi.fn((format: string) => (format === 'json' ? body(text) : text)),
+ setDocument: vi.fn(),
+ };
+ return { editor: editor as unknown as IEditor, spy: editor };
+};
+const seed = (id: string, text: string, editor: IEditor) => {
+ useDocumentStore.getState().initDocumentWithEditor({
+ autoSave: false,
+ content: text,
+ documentId: id,
+ editor,
+ editorData: body(text),
+ sourceType: 'page',
+ updatedAt: new Date('2026-10-18T00:00:00Z'),
+ });
+};
+
+beforeEach(() => {
+ useDocumentStore.setState({
+ activeDocumentId: undefined,
+ documents: {},
+ documentDetailMap: {},
+ editor: undefined,
+ });
+ vi.mocked(documentService.updateDocument).mockReset().mockResolvedValue({
+ historyAppended: false,
+ id: 'B',
+ updatedAt: '2026-10-18T00:00:01Z',
+ });
+});
+
+describe('document identity and metadata-only saves', () => {
+ it('hydrates the requested cached document while the global active document still points elsewhere', async () => {
+ const { editor, spy } = makeEditor('A body');
+ seed('B', 'B body', editor);
+ seed('A', 'A body', editor);
+
+ await useDocumentStore.getState().onEditorInit(editor, 'B');
+
+ expect(spy.setDocument).toHaveBeenCalledWith('json', JSON.stringify(body('B body')), {
+ keepId: true,
+ });
+ expect(useDocumentStore.getState().documents.A.content).toBe('A body');
+ });
+
+ it('does not fall back to the active document when the requested document has not loaded', async () => {
+ const { editor, spy } = makeEditor('A body');
+ seed('A', 'A body', editor);
+ await useDocumentStore.getState().onEditorInit(editor, 'missing');
+ expect(spy.setDocument).not.toHaveBeenCalled();
+ });
+
+ it('renames B without reading or persisting an editor still showing A', async () => {
+ const { editor, spy } = makeEditor('A body');
+ seed('B', 'B body', editor);
+ const before = useDocumentStore.getState().documents.B;
+
+ await useDocumentStore.getState().performSave(
+ 'B',
+ { title: 'B renamed' },
+ {
+ metadataOnly: true,
+ saveSource: 'autosave',
+ },
+ );
+
+ const request = vi.mocked(documentService.updateDocument).mock.calls[0][0];
+ expect(request).toMatchObject({ id: 'B', title: 'B renamed' });
+ expect(request).not.toHaveProperty('content');
+ expect(request).not.toHaveProperty('editorData');
+ expect(spy.getDocument).not.toHaveBeenCalled();
+ expect(useDocumentStore.getState().documents.B).toMatchObject({
+ content: before.content,
+ editorData: before.editorData,
+ isDirty: false,
+ lastSavedContent: before.lastSavedContent,
+ lastSavedEditorData: before.lastSavedEditorData,
+ });
+ });
+
+ it('preserves an unsaved body and its saved baseline when metadata finishes saving', async () => {
+ const { editor } = makeEditor('B draft');
+ seed('B', 'B saved', editor);
+ useDocumentStore.getState().handleContentChange();
+ const before = useDocumentStore.getState().documents.B;
+
+ await useDocumentStore
+ .getState()
+ .performSave('B', { title: 'B renamed' }, { metadataOnly: true });
+
+ expect(useDocumentStore.getState().documents.B).toMatchObject({
+ content: 'B draft',
+ editorData: before.editorData,
+ isDirty: true,
+ lastSavedContent: 'B saved',
+ lastSavedEditorData: before.lastSavedEditorData,
+ });
+ await useDocumentStore.getState().performSave('B', undefined, { saveSource: 'manual' });
+ expect(documentService.updateDocument).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ content: 'B draft',
+ expectedUpdatedAt: new Date('2026-10-18T00:00:01Z'),
+ id: 'B',
+ }),
+ );
+ expect(useDocumentStore.getState().documents.B.isDirty).toBe(false);
+ });
+ it('removes an explicitly cleared emoji while preserving unrelated saved metadata', async () => {
+ const { editor } = makeEditor('B body');
+ seed('B', 'B body', editor);
+ useDocumentStore.setState({
+ documentDetailMap: {
+ B: { document: { id: 'B', metadata: { createdAt: 123, emoji: 'πŸ“˜' } } as any },
+ },
+ });
+
+ await useDocumentStore
+ .getState()
+ .performSave('B', { emoji: undefined }, { metadataOnly: true });
+
+ expect(documentService.updateDocument).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'B', metadata: { createdAt: 123 } }),
+ );
+ expect(useDocumentStore.getState().documentDetailMap.B.document?.metadata).toEqual({
+ createdAt: 123,
+ });
+ });
+});
diff --git a/src/store/document/slices/editor/action.persistentId.test.ts b/src/store/document/slices/editor/action.persistentId.test.ts
index 11bec3dbd76..6829759d1f6 100644
--- a/src/store/document/slices/editor/action.persistentId.test.ts
+++ b/src/store/document/slices/editor/action.persistentId.test.ts
@@ -79,7 +79,7 @@ describe('DocumentStore - persisted node ids', () => {
});
});
- await act(() => result.current.onEditorInit(editor));
+ await act(() => result.current.onEditorInit(editor, 'doc-persisted-ids'));
expect(topLevelIds(editor)).toEqual(['6w5t9drdmo', '7oxxhtqflo']);
},
diff --git a/src/store/document/slices/editor/action.test.ts b/src/store/document/slices/editor/action.test.ts
index a9a98f17184..b5072a187fa 100644
--- a/src/store/document/slices/editor/action.test.ts
+++ b/src/store/document/slices/editor/action.test.ts
@@ -217,7 +217,7 @@ describe('DocumentStore - Editor Actions', () => {
// Then call onEditorInit
act(() => {
- result.current.onEditorInit(mockEditor);
+ result.current.onEditorInit(mockEditor, 'doc-1');
});
expect(mockEditor.setDocument).toHaveBeenCalledWith('markdown', '# Hello World');
@@ -245,7 +245,7 @@ name: youtube-comment-retrieval-workflow
});
act(() => {
- result.current.onEditorInit(mockEditor);
+ result.current.onEditorInit(mockEditor, 'doc-1');
});
expect(mockEditor.setDocument).toHaveBeenCalledWith(
@@ -293,7 +293,7 @@ name: skill-name
});
act(() => {
- result.current.onEditorInit(mockEditor);
+ result.current.onEditorInit(mockEditor, 'doc-1');
});
expect(mockEditor.setDocument).toHaveBeenCalledTimes(1);
@@ -334,7 +334,7 @@ name: skill-name
});
act(() => {
- result.current.onEditorInit(mockEditor);
+ result.current.onEditorInit(mockEditor, 'doc-1');
});
expect(consoleWarn).toHaveBeenCalledWith(
@@ -368,7 +368,7 @@ name: skill-name
});
act(() => {
- result.current.onEditorInit(mockEditor);
+ result.current.onEditorInit(mockEditor, 'doc-1');
});
expect(mockEditor.setDocument).toHaveBeenCalledWith('json', JSON.stringify(editorData), {
@@ -390,7 +390,7 @@ name: skill-name
});
act(() => {
- result.current.onEditorInit(mockEditor);
+ result.current.onEditorInit(mockEditor, 'doc-previous');
});
act(() => {
@@ -402,7 +402,7 @@ name: skill-name
});
act(() => {
- result.current.onEditorInit(mockEditor);
+ result.current.onEditorInit(mockEditor, 'doc-1');
});
expect(mockEditor.setDocument).toHaveBeenLastCalledWith(
@@ -437,7 +437,7 @@ name: skill-name
});
await act(async () => {
- await result.current.onEditorInit(mockEditor);
+ await result.current.onEditorInit(mockEditor, 'doc-1');
});
expect(consoleError).toHaveBeenCalledWith(
diff --git a/src/store/document/slices/editor/action.ts b/src/store/document/slices/editor/action.ts
index 779e60384bd..b05690119af 100644
--- a/src/store/document/slices/editor/action.ts
+++ b/src/store/document/slices/editor/action.ts
@@ -29,6 +29,8 @@ export interface SaveMetadata {
}
export interface SaveExecutionOptions {
+ /** Persist title/emoji without reading, writing or acknowledging the editor body. */
+ metadataOnly?: boolean;
restoreFromHistoryId?: string;
saveSource?: 'autosave' | 'manual' | 'restore' | 'system' | 'llm_call';
}
@@ -242,11 +244,16 @@ export class EditorActionImpl {
return 'adopted';
};
- onEditorInit = async (editor: IEditor): Promise<void> => {
- const { activeDocumentId, documents } = this.#get();
- if (!editor || !activeDocumentId) return;
+ /**
+ * Hydrate the document owned by this canvas. A child's initialization effect can
+ * run before the parent's activeDocumentId update, so the global selection is
+ * not a reliable identity for the body being mounted.
+ */
+ onEditorInit = async (editor: IEditor, documentId: string): Promise<void> => {
+ const { documents } = this.#get();
+ if (!editor) return;
- const doc = documents[activeDocumentId];
+ const doc = documents[documentId];
if (!doc) return;
@@ -327,7 +334,7 @@ export class EditorActionImpl {
const id = documentId || this.#get().activeDocumentId;
if (!id) return;
- this.syncEditorContent(id, { triggerAutoSave: false });
+ if (!options?.metadataOnly) this.syncEditorContent(id, { triggerAutoSave: false });
const previous = this.#inflightSaves.get(id) ?? Promise.resolve();
const run = previous.catch(() => {}).then(() => this.#runSave(id, metadata, options));
this.#inflightSaves.set(id, run);
@@ -350,7 +357,18 @@ export class EditorActionImpl {
const doc = documents[id];
if (!doc) return;
- const hasMetadataChanges = metadata?.emoji !== undefined || metadata?.title !== undefined;
+ const hasEmojiChange = metadata !== undefined && 'emoji' in metadata;
+ const hasMetadataChanges = hasEmojiChange || metadata?.title !== undefined;
+ const savedMetadata = hasEmojiChange
+ ? Object.fromEntries(
+ Object.entries({
+ ...this.#get().documentDetailMap[id]?.document?.metadata,
+ emoji: metadata?.emoji,
+ }).filter(([, value]) => value !== undefined),
+ )
+ : undefined;
+ const metadataOnly = options?.metadataOnly === true;
+ if (metadataOnly && !hasMetadataChanges) return;
// Skip save if neither document content nor metadata changed
if (!doc.isDirty && !hasMetadataChanges) return;
@@ -362,7 +380,7 @@ export class EditorActionImpl {
const currentContent = doc.content ?? '';
const currentEditorData = doc.editorData;
- if (!isValidEditorData(currentEditorData)) {
+ if (!metadataOnly && !isValidEditorData(currentEditorData)) {
console.warn('[DocumentStore] Refusing to save invalid editorData:', currentEditorData);
internal_dispatchDocument({ id, type: 'updateDocument', value: { saveStatus: 'idle' } });
return;
@@ -373,12 +391,13 @@ export class EditorActionImpl {
// in DiffAllToolbar, which mutates editor state before calling performSave.
const requestSave = (expectedUpdatedAt?: Date) =>
documentService.updateDocument({
- content: currentContent,
- editorData: JSON.stringify(currentEditorData),
+ ...(!metadataOnly
+ ? { content: currentContent, editorData: JSON.stringify(currentEditorData) }
+ : {}),
...(expectedUpdatedAt ? { expectedUpdatedAt } : {}),
id,
lockOwnerId: doc.lockOwnerId,
- metadata: metadata?.emoji ? { emoji: metadata.emoji } : undefined,
+ metadata: savedMetadata,
restoreFromHistoryId: options?.restoreFromHistoryId,
saveSource: options?.saveSource,
title: metadata?.title,
@@ -405,10 +424,16 @@ export class EditorActionImpl {
id,
type: 'updateDocument',
value: {
- isDirty:
- current?.content !== currentContent || !isEqual(current?.editorData, currentEditorData),
- lastSavedContent: currentContent,
- lastSavedEditorData: structuredClone(currentEditorData),
+ // A metadata response cannot acknowledge body edits that it never sent.
+ ...(!metadataOnly
+ ? {
+ isDirty:
+ current?.content !== currentContent ||
+ !isEqual(current?.editorData, currentEditorData),
+ lastSavedContent: currentContent,
+ lastSavedEditorData: structuredClone(currentEditorData),
+ }
+ : {}),
...(savedAt ? { lastUpdatedTime: savedAt } : {}),
saveBlockedByLock: false,
saveStatus: 'saved',
@@ -425,8 +450,7 @@ export class EditorActionImpl {
id,
{
...cachedDetail,
- content: currentContent,
- editorData: currentEditorData,
+ ...(!metadataOnly ? { 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
@@ -434,14 +458,14 @@ export class EditorActionImpl {
...(metadata?.title !== undefined
? { filename: metadata.title, title: metadata.title }
: {}),
- ...(metadata?.emoji ? { metadata: { emoji: metadata.emoji } } : {}),
+ ...(savedMetadata ? { metadata: savedMetadata } : {}),
updatedAt: savedAt ?? cachedDetail.updatedAt,
},
scope,
);
}
- if (this.#get().documents[id]?.isDirty && doc.autoSave !== false) {
+ if (!metadataOnly && this.#get().documents[id]?.isDirty && doc.autoSave !== false) {
this.#get().triggerDebouncedSave(id);
}
} catch (error) {
diff --git a/src/store/document/slices/editor/onEditorInit.emptyParseShell.test.ts b/src/store/document/slices/editor/onEditorInit.emptyParseShell.test.ts
index ab27a1b28bb..b61d9b5c3a8 100644
--- a/src/store/document/slices/editor/onEditorInit.emptyParseShell.test.ts
+++ b/src/store/document/slices/editor/onEditorInit.emptyParseShell.test.ts
@@ -41,7 +41,7 @@ describe('onEditorInit empty-parse shell tolerance (Lexical error #38)', () => {
});
act(() => {
- result.current.onEditorInit(mockEditor);
+ result.current.onEditorInit(mockEditor, 'doc-1');
});
// The empty-parse shell must not reach setDocument('json') β€” it would
@@ -70,7 +70,7 @@ describe('onEditorInit empty-parse shell tolerance (Lexical error #38)', () => {
});
act(() => {
- result.current.onEditorInit(mockEditor);
+ result.current.onEditorInit(mockEditor, 'doc-legacy');
});
expect(mockEditor.setDocument).toHaveBeenCalledWith('json', JSON.stringify(legacy), {