🤯 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
🐛 fix(page-editor): keep page title renames when the version moved or the page switched (#23123)
Rdmclin209de4308592b
diff --git a/src/features/PageEditor/StoreUpdater.test.tsx b/src/features/PageEditor/StoreUpdater.test.tsxnew file mode 100644index 00000000000..12d970864c2--- /dev/null+++ b/src/features/PageEditor/StoreUpdater.test.tsx@@ -0,0 +1,75 @@+import { act, render } from '@testing-library/react';+import { useEffect } from 'react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { createStore, Provider, usePageEditorStore } from './store';+import StoreUpdater from './StoreUpdater';++const performSaveMock = vi.fn();++vi.mock('@/store/document', () => ({+ useDocumentStore: { getState: () => ({ performSave: performSaveMock }) },+}));+vi.mock('@/store/page', () => ({+ pageSelectors: { getDocumentById: () => () => undefined },+ usePageStore: (selector: (s: unknown) => unknown) => selector({}),+}));+vi.mock('./useDocumentLock', () => ({ useDocumentLock: () => {} }));+vi.mock('./useResourceEvents', () => ({ useResourceEvents: () => {} }));+vi.mock('./usePageDraft', () => ({ usePageDraft: () => {} }));+vi.mock('./useReleaseAgentEdit', () => ({ useReleaseAgentEdit: () => {} }));++let typeTitle: ((title: string) => void) | undefined;+const TitleInput = () => {+ const setTitle = usePageEditorStore((s) => s.setTitle);+ useEffect(() => {+ typeTitle = setTitle;+ }, [setTitle]);+ return null;+};++const renderEditor = (pageId: string, title: string) => (+ <Provider createStore={() => createStore({ documentId: 'page-a', title: 'M11W1 本周事项' })}>+ <StoreUpdater pageId={pageId} title={title} />+ <TitleInput />+ </Provider>+);++describe('StoreUpdater - switching pages on a mounted editor (T-14156)', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ performSaveMock.mockReset().mockResolvedValue(undefined);+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ it('saves a rename still waiting in the debounce into the page it was typed on', async () => {+ const view = render(renderEditor('page-a', 'M11W1 本周事项'));++ act(() => typeTitle!('待办事项'));+ // Switch before the meta debounce fires.+ view.rerender(renderEditor('page-b', 'Other page'));+ await act(async () => {+ await vi.runAllTimersAsync();+ });++ expect(performSaveMock).toHaveBeenCalledTimes(1);+ expect(performSaveMock).toHaveBeenCalledWith(+ 'page-a',+ expect.objectContaining({ title: '待办事项' }),+ expect.objectContaining({ metadataOnly: true }),+ );+ });++ it('does not save anything when switching without a pending rename', async () => {+ const view = render(renderEditor('page-a', 'M11W1 本周事项'));++ view.rerender(renderEditor('page-b', 'Other page'));+ await act(async () => {+ await vi.runAllTimersAsync();+ });++ expect(performSaveMock).not.toHaveBeenCalled();+ });+});diff --git a/src/features/PageEditor/StoreUpdater.tsx b/src/features/PageEditor/StoreUpdater.tsxindex ae4cfdb1acf..1e70fc51f4f 100644--- a/src/features/PageEditor/StoreUpdater.tsx+++ b/src/features/PageEditor/StoreUpdater.tsx@@ -43,6 +43,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(const initMeta = usePageEditorStore((s) => s.initMeta);const setDocumentId = usePageEditorStore((s) => s.setDocumentId);+ const flushMetaSave = usePageEditorStore((s) => s.flushMetaSave);const syncMeta = usePageEditorStore((s) => s.syncMeta);// Workspace pages are view-first; resolve once here so the lock + gating read// a single source of truth. Private-visibility pages are creator-only —@@ -77,8 +78,14 @@ const StoreUpdater = memo<StoreUpdaterProps>(// action instead, so a panel left open on the previous document doesn't// carry over to this one (see setDocumentId).useEffect(() => {- if (typeof pageId !== 'undefined') setDocumentId(pageId);- }, [pageId, setDocumentId]);+ if (typeof pageId === 'undefined') return;+ // A title typed on the previous page may still sit in the meta debounce.+ // Flush it while the store still points at that page: once `documentId`+ // and `initMeta` move to this one, the pending save would find a clean+ // store for the wrong document and the rename would be dropped.+ if (storeApi.getState().documentId !== pageId) flushMetaSave();+ setDocumentId(pageId);+ }, [pageId, setDocumentId, flushMetaSave, storeApi]);useStoreUpdater('isWorkspacePage', isWorkspacePage);useStoreUpdater('isWorkspaceScopedPage', isWorkspaceScopedPage);useStoreUpdater('knowledgeBaseId', knowledgeBaseId);diff --git a/src/store/document/slices/editor/action.metadataConflict.test.ts b/src/store/document/slices/editor/action.metadataConflict.test.tsnew file mode 100644index 00000000000..805f8428b06--- /dev/null+++ b/src/store/document/slices/editor/action.metadataConflict.test.ts@@ -0,0 +1,175 @@+import { act } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { documentService } from '@/services/document';++import { useDocumentStore } from '../../store';++vi.mock('@/services/document', () => ({+ documentService: {+ acquireDocumentLock: vi.fn().mockResolvedValue({ holderId: null, lockedByOther: false }),+ getDocumentById: vi.fn(),+ releaseDocumentLock: vi.fn().mockResolvedValue(undefined),+ updateDocument: vi.fn(),+ },+}));++const loadedAt = new Date('2026-01-01T00:00:00.000Z');+// The room projected body edits since the page loaded: the row moved on while+// the editor still holds the load-time version.+const projectedAt = new Date('2026-01-01T00:05:00.000Z');++const versionConflict = () =>+ Object.assign(new Error('Document has been updated by another session'), {+ data: { code: 'CONFLICT' },+ });++const editor = { getDocument: vi.fn(() => null), setDocument: vi.fn() };++const seedRoomPage = () => {+ act(() => {+ useDocumentStore.getState().initDocumentWithEditor({+ content: '# Body',+ documentId: 'doc-1',+ editor: editor as any,+ sourceType: 'page',+ updatedAt: loadedAt,+ });+ useDocumentStore.getState().internal_dispatchDocument({+ id: 'doc-1',+ type: 'updateDocument',+ // A workspace room page holding its own edit lease.+ value: { collab: true as any, lockOwnerId: 'owner-1' },+ });+ useDocumentStore.setState({+ documentDetailMap: {+ 'doc-1': {+ document: {+ content: '# Body',+ id: 'doc-1',+ metadata: { emoji: '⭐' },+ title: 'M11W1 本周事项',+ updatedAt: loadedAt,+ },+ } as any,+ },+ });+ });+};++const saveTitle = (title: string) =>+ useDocumentStore+ .getState()+ .performSave('doc-1', { emoji: '⭐', title }, { metadataOnly: true, saveSource: 'autosave' });++describe('DocumentStore - title / emoji save after the version moved (T-14156)', () => {+ beforeEach(() => {+ vi.mocked(documentService.updateDocument).mockReset();+ vi.mocked(documentService.getDocumentById).mockReset();+ vi.mocked(documentService.acquireDocumentLock).mockClear();+ act(() => {+ Object.keys(useDocumentStore.getState().documents).forEach((id) =>+ useDocumentStore.getState().closeDocument(id),+ );+ useDocumentStore.setState({ documentDetailMap: {}, editor: undefined });+ });+ });++ it('replays a rename against the latest version when only the body moved', async () => {+ seedRoomPage();+ vi.mocked(documentService.getDocumentById).mockResolvedValue({+ content: '# Body edited in the room',+ id: 'doc-1',+ metadata: { emoji: '⭐' },+ title: 'M11W1 本周事项',+ updatedAt: projectedAt,+ } as any);+ vi.mocked(documentService.updateDocument)+ .mockRejectedValueOnce(versionConflict())+ .mockResolvedValueOnce({+ historyAppended: false,+ id: 'doc-1',+ updatedAt: '2026-01-01T00:05:01.000Z',+ } as any);++ await act(async () => {+ await saveTitle('待办事项');+ });++ expect(documentService.updateDocument).toHaveBeenCalledTimes(2);+ expect(documentService.updateDocument).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({ expectedUpdatedAt: projectedAt, title: '待办事项' }),+ );+ // A title never needs the body lease, so the replay must not reclaim it.+ expect(documentService.acquireDocumentLock).not.toHaveBeenCalled();+ expect(useDocumentStore.getState().documents['doc-1'].saveStatus).toBe('saved');+ expect(useDocumentStore.getState().documentDetailMap['doc-1']?.document?.title).toBe(+ '待办事项',+ );+ });++ it('does not overwrite a title a collaborator changed meanwhile, and reports the failure', async () => {+ seedRoomPage();+ vi.mocked(documentService.getDocumentById).mockResolvedValue({+ content: '# Body',+ id: 'doc-1',+ metadata: { emoji: '⭐' },+ title: 'Renamed by a teammate',+ updatedAt: projectedAt,+ } as any);+ const conflict = versionConflict();+ vi.mocked(documentService.updateDocument).mockRejectedValueOnce(conflict);++ await act(async () => {+ await expect(saveTitle('待办事项')).rejects.toBe(conflict);+ });++ expect(documentService.updateDocument).toHaveBeenCalledTimes(1);+ // Not "Latest version loaded": the rename never reached the server.+ expect(useDocumentStore.getState().documents['doc-1'].saveStatus).toBe('failed');+ expect(useDocumentStore.getState().documents['doc-1'].saveBlockedByLock).toBeFalsy();+ });++ it('does not overwrite an emoji a collaborator changed meanwhile', async () => {+ seedRoomPage();+ vi.mocked(documentService.getDocumentById).mockResolvedValue({+ content: '# Body',+ id: 'doc-1',+ metadata: { emoji: '🔥' },+ title: 'M11W1 本周事项',+ updatedAt: projectedAt,+ } as any);+ const conflict = versionConflict();+ vi.mocked(documentService.updateDocument).mockRejectedValueOnce(conflict);++ await act(async () => {+ await expect(saveTitle('待办事项')).rejects.toBe(conflict);+ });++ expect(documentService.updateDocument).toHaveBeenCalledTimes(1);+ });++ it('keeps the conflict when no cached row can vouch for the meta', async () => {+ seedRoomPage();+ act(() => {+ useDocumentStore.setState({ documentDetailMap: {} });+ });+ vi.mocked(documentService.getDocumentById).mockResolvedValue({+ content: '# Body',+ id: 'doc-1',+ metadata: { emoji: '⭐' },+ title: 'M11W1 本周事项',+ updatedAt: projectedAt,+ } as any);+ const conflict = versionConflict();+ vi.mocked(documentService.updateDocument).mockRejectedValueOnce(conflict);++ await act(async () => {+ await expect(saveTitle('待办事项')).rejects.toBe(conflict);+ });++ expect(documentService.updateDocument).toHaveBeenCalledTimes(1);+ expect(useDocumentStore.getState().documents['doc-1'].saveStatus).toBe('failed');+ });+});diff --git a/src/store/document/slices/editor/action.ts b/src/store/document/slices/editor/action.tsindex a7909c7e615..c0d830c1290 100644--- a/src/store/document/slices/editor/action.ts+++ b/src/store/document/slices/editor/action.ts@@ -52,6 +52,19 @@ export interface RemoteDocumentRow extends DocumentFormatFields {export type ReconcileResult = 'unchanged' | 'rebased' | 'adopted';+/**+ * How a save may recover from a version CONFLICT once the store has reconciled+ * the latest row: `body` replays a content save over an unchanged body base;+ * `metadata` replays a title / emoji-only save when nobody else touched the+ * meta it was built from (`base`, the cached row; without one it never replays).+ */+type ConflictRetry =+ | { kind: 'body' }+ | {+ base?: { metadata?: unknown; title?: string | null };+ kind: 'metadata';+ };+type Setter = StoreSetter<DocumentStore>;export const createEditorSlice = (set: Setter, get: () => DocumentStore, _api?: unknown) =>new EditorActionImpl(set, get, _api);@@ -665,12 +678,27 @@ export class EditorActionImpl {title: metadata?.title,});+ // A title / emoji-only save sends no body, so a version moved by a body+ // write (another session, or this page's own room projection) cannot be+ // clobbered by replaying it — only a concurrent meta change could.+ const cachedMeta = this.#get().documentDetailMap[id]?.document;+ let conflictRetry: ConflictRetry | undefined;+ if (!options?.restoreFromHistoryId) {+ if (!hasMetadataChanges) conflictRetry = { kind: 'body' };+ else if (metadataOnly)+ conflictRetry = {+ base: cachedMeta+ ? { metadata: cachedMeta.metadata, title: cachedMeta.title }+ : undefined,+ kind: 'metadata',+ };+ }+let result: Awaited<ReturnType<typeof requestSave>>;try {result = await requestSave(doc.lastUpdatedTime ?? undefined);} catch (error) {- const canRetry = !hasMetadataChanges && !options?.restoreFromHistoryId;- result = await this.retrySaveAfterReconcile(id, doc, error, requestSave, canRetry);+ result = await this.retrySaveAfterReconcile(id, doc, error, requestSave, conflictRetry);}// Old servers omit updatedAt. Keep the known token; conflict reconciliation@@ -772,10 +800,15 @@ export class EditorActionImpl {internal_dispatchDocument({id,type: 'updateDocument',- value: {- saveBlockedByLock: lockBlocked || undefined,- saveStatus: adoptedRemote ? 'saved' : 'idle',- },+ // A refused title / emoji has no autosave to re-arm, and the body lock+ // never gates it: `idle` would read as "Latest version loaded" over a+ // rename that never reached the server.+ value: metadataOnly+ ? { saveStatus: 'failed' }+ : {+ saveBlockedByLock: lockBlocked || undefined,+ saveStatus: adoptedRemote ? 'saved' : 'idle',+ },});if (conflicted && !lockBlocked && live?.isDirty && live.autoSave !== false) {this.#get().triggerDebouncedSave(id);@@ -793,7 +826,7 @@ export class EditorActionImpl {},error: unknown,requestSave: (expectedUpdatedAt?: Date) => Promise<T>,- canRetry: boolean,+ retry: ConflictRetry | undefined,): Promise<T> => {const errorCode = (error as { data?: { code?: string } })?.data?.code;if (errorCode !== 'CONFLICT') throw error;@@ -820,7 +853,26 @@ export class EditorActionImpl {// reconciles against it instead of re-adopting a stale server read.this.#get().internal_adoptDocumentDetail(id, latest, scope);}- if (outcome === 'adopted' || !canRetry) throw error;+ if (!retry) throw error;++ if (retry.kind === 'metadata') {+ // The request carries no body, so whatever moved the version (a body+ // write — for a room page, its own projection) is not overwritten, and+ // the body lock does not gate it. Only a concurrent title / emoji change+ // would be: replay just when the meta still matches the base it was built+ // from (`savedMetadata` replaces the whole object). Without a cached+ // base there is nothing to compare, so a collaborator's change cannot be+ // ruled out: keep the conflict.+ const { base } = retry;+ const metaUnchanged =+ !!base &&+ (latest.title ?? null) === (base.title ?? null) &&+ isEqual(latest.metadata ?? null, base.metadata ?? null);+ if (!metaUnchanged) throw error;+ return await requestSave(latest.updatedAt);+ }++ if (outcome === 'adopted') throw error;// `baseDoc` is the store snapshot this request was built from; an// overlapping newer save from this tab may have moved the live base since,