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(document): keep edits typed during an in-flight save on tab refocus (#21241)

Lobehub Coderf98c1237e3f7
diff --git a/src/store/document/slices/document/action.test.ts b/src/store/document/slices/document/action.test.ts
index b8295b02ad5..36006c5d62a 100644
--- a/src/store/document/slices/document/action.test.ts
+++ b/src/store/document/slices/document/action.test.ts
@@ -200,6 +200,88 @@ describe('document detail replica', () => {
});
});
+ it('keeps edits typed during an in-flight save when a focus revalidation lands', async () => {
+ vi.mocked(documentService.getDocumentById).mockResolvedValue(documentRow() as any);
+ let settleSave!: () => void;
+ vi.mocked(documentService.updateDocument).mockReturnValue(
+ new Promise((resolve) => {
+ settleSave = () =>
+ resolve({ historyAppended: false, id: 'doc-1', updatedAt: '2026-01-03T00:00:00.000Z' });
+ }) as any,
+ );
+ const editor = createEditor();
+ const { result } = renderDocument('doc-1', editor);
+
+ await waitFor(() => expect(useDocumentStore.getState().documents['doc-1']).toBeDefined());
+ act(() => useDocumentStore.getState().handleContentChange());
+ const save = useDocumentStore.getState().performSave('doc-1');
+ await waitFor(() => expect(documentService.updateDocument).toHaveBeenCalled());
+
+ // The server already committed the save, but its response has not arrived:
+ // the read returns that row, which lacks what was typed since.
+ vi.mocked(documentService.getDocumentById).mockResolvedValue(
+ documentRow({
+ content: '# Draft without the latest edits',
+ 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: '# Draft',
+ isDirty: true,
+ });
+
+ await act(async () => {
+ settleSave();
+ await save;
+ });
+ });
+
+ it('adopts a newer writer read during an in-flight save once the save settles', async () => {
+ vi.mocked(documentService.getDocumentById).mockResolvedValue(documentRow() as any);
+ let settleSave!: () => void;
+ vi.mocked(documentService.updateDocument).mockReturnValue(
+ new Promise((resolve) => {
+ settleSave = () =>
+ resolve({ historyAppended: false, id: 'doc-1', updatedAt: '2026-01-03T00:00:00.000Z' });
+ }) as any,
+ );
+ const editor = createEditor();
+ const { result } = renderDocument('doc-1', editor);
+
+ await waitFor(() => expect(useDocumentStore.getState().documents['doc-1']).toBeDefined());
+ act(() => useDocumentStore.getState().handleContentChange());
+ const save = useDocumentStore.getState().performSave('doc-1');
+ await waitFor(() => expect(documentService.updateDocument).toHaveBeenCalled());
+
+ // Another writer committed after this save; its row arrives first.
+ const newer = new Date('2026-01-04T00:00:00.000Z');
+ vi.mocked(documentService.getDocumentById).mockResolvedValue(
+ documentRow({ content: '# Other writer', updatedAt: newer }) as any,
+ );
+ await act(async () => {
+ await result.current.mutate();
+ });
+ expect(useDocumentStore.getState().documents['doc-1'].content).toBe('# Draft');
+
+ await act(async () => {
+ settleSave();
+ await save;
+ });
+
+ expect(useDocumentStore.getState().documents['doc-1']).toMatchObject({
+ content: '# Other writer',
+ lastUpdatedTime: newer,
+ });
+ expect(useDocumentStore.getState().documentDetailMap['doc-1']?.document).toMatchObject({
+ content: '# Other writer',
+ updatedAt: newer,
+ });
+ });
+
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({
diff --git a/src/store/document/slices/document/action.ts b/src/store/document/slices/document/action.ts
index 0baaa525515..fa114fb14c4 100644
--- a/src/store/document/slices/document/action.ts
+++ b/src/store/document/slices/document/action.ts
@@ -392,7 +392,7 @@ export class DocumentActionImpl {
if (currentActiveId && currentActiveId !== documentId) return;
if (this.#get().documents[documentId]) {
- this.#get().reconcileRemote(documentId, document);
+ this.#reconcileWhenSettled(documentId, document);
if (sourceType === 'notebook' && topicId) {
this.#rememberTopicDocument(topicId, documentId);
}
@@ -422,6 +422,30 @@ export class DocumentActionImpl {
}
};
+ /**
+ * Reconcile a read once no save of this document is in flight.
+ *
+ * A read that lands mid-save (e.g. a focus revalidation after a tab switch)
+ * may carry the row that save is writing, without the edits typed since:
+ * adopting it then would wipe them from the editor. It may also carry a newer
+ * writer's revision, so it is deferred rather than dropped: once the save
+ * settles, the newest row in the view is reconciled, and `reconcileRemote`
+ * ignores it unless it is newer than what the save confirmed.
+ */
+ #reconcileWhenSettled = (documentId: string, row: DocumentItem): void => {
+ const pending = this.#get().getPendingSave(documentId);
+ if (!pending) {
+ this.#get().reconcileRemote(documentId, row);
+ return;
+ }
+
+ const retry = () => {
+ const latest = this.#get().documentDetailMap[documentId]?.document;
+ if (latest) this.#reconcileWhenSettled(documentId, latest);
+ };
+ void pending.then(retry, retry);
+ };
+
/**
* Fetch a document through its replica and initialize it in the DocumentStore.
*/
diff --git a/src/store/document/slices/editor/action.ts b/src/store/document/slices/editor/action.ts
index a85d0146240..f5c6f1cfaaa 100644
--- a/src/store/document/slices/editor/action.ts
+++ b/src/store/document/slices/editor/action.ts
@@ -464,7 +464,13 @@ export class EditorActionImpl {
// 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) {
+ // A read that landed while this save was in flight may already hold a
+ // newer writer's revision; mirroring this save over it would regress it.
+ const cachedIsNewer =
+ !!savedAt &&
+ !!cachedDetail?.updatedAt &&
+ new Date(cachedDetail.updatedAt).getTime() > savedAt.getTime();
+ if (cachedDetail && !cachedIsNewer) {
this.#get().internal_adoptDocumentDetail(
id,
{