🤯 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
⚡️ perf(page-editor): keep document switches responsive on long pages (#22962)
Innei0d14e4961913
diff --git a/src/features/EditorCanvas/DocumentIdMode.test.tsx b/src/features/EditorCanvas/DocumentIdMode.test.tsxindex c97c6bd2c3b..a30d3b6944e 100644--- a/src/features/EditorCanvas/DocumentIdMode.test.tsx+++ b/src/features/EditorCanvas/DocumentIdMode.test.tsx@@ -1,6 +1,7 @@/*** @vitest-environment happy-dom*/+import type { IEditor } from '@lobehub/editor';import { act, render, screen, waitFor } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -67,6 +68,7 @@ vi.mock('@/store/document', () => ({vi.mock('@/store/document/slices/editor', () => ({editorSelectors: {+ content: vi.fn(() => () => ''),isDirty: vi.fn(() => () => false),isDocumentLoading: vi.fn(() => () => false),},@@ -89,6 +91,7 @@ describe('DocumentIdMode', () => {onEditorInit.mockClear();useFetchDocument.mockClear();vi.mocked(editorSelectors.isDocumentLoading).mockReturnValue(() => false);+ vi.mocked(editorSelectors.content).mockImplementation(() => () => '');saveHotkeyHandler = undefined;});@@ -300,4 +303,54 @@ describe('DocumentIdMode', () => {expect(screen.queryByTestId('pending-body')).not.toBeInTheDocument();expect(screen.getByTestId('internal-editor')).toBeVisible();});++ describe('long bodies', () => {+ const LONG_BODY = 'x'.repeat(50_000);+ // Only readiness is read on these paths.+ const editor = { getLexicalEditor: vi.fn(() => ({})) } as unknown as IEditor;+ const sleep = (ms: number) => {+ const { promise, resolve } = Promise.withResolvers<void>();+ setTimeout(resolve, ms);+ return promise;+ };++ beforeEach(() => {+ vi.mocked(editorSelectors.content).mockImplementation(+ (id) => () => (id === 'doc-long' ? LONG_BODY : ''),+ );+ });++ it('loads a long body after the switch paints, behind a skeleton', async () => {+ render(<DocumentIdMode documentId="doc-long" editor={editor} />);++ // The switch commits without building the body; the previous one stays hidden.+ expect(onEditorInit).not.toHaveBeenCalled();+ expect(screen.getByTestId('internal-editor')).not.toBeVisible();++ await waitFor(() => expect(onEditorInit).toHaveBeenCalledWith(editor, 'doc-long'));+ await waitFor(() => expect(screen.getByTestId('internal-editor')).toBeVisible());+ });++ it('keeps the atomic swap for a short body', () => {+ render(<DocumentIdMode documentId="doc-short" editor={editor} />);++ expect(onEditorInit).toHaveBeenCalledWith(editor, 'doc-short');+ expect(screen.getByTestId('internal-editor')).toBeVisible();+ });++ it('drops a long body left before it loaded, and loads it on return', async () => {+ const { rerender } = render(<DocumentIdMode documentId="doc-long" editor={editor} />);+ rerender(<DocumentIdMode documentId="doc-short" editor={editor} />);++ // Wait past the frame the long body was scheduled for.+ await act(() => sleep(50));+ expect(onEditorInit).toHaveBeenCalledTimes(1);+ expect(onEditorInit).toHaveBeenLastCalledWith(editor, 'doc-short');++ rerender(<DocumentIdMode documentId="doc-long" editor={editor} />);++ await waitFor(() => expect(onEditorInit).toHaveBeenLastCalledWith(editor, 'doc-long'));+ expect(onEditorInit).toHaveBeenCalledTimes(2);+ });+ });});diff --git a/src/features/EditorCanvas/DocumentIdMode.tsx b/src/features/EditorCanvas/DocumentIdMode.tsxindex 66849a60238..3965bbb9237 100644--- a/src/features/EditorCanvas/DocumentIdMode.tsx+++ b/src/features/EditorCanvas/DocumentIdMode.tsx@@ -2,7 +2,7 @@import { type IEditor } from '@lobehub/editor';import isEqual from 'fast-deep-equal';-import { memo, useCallback, useEffect, useRef } from 'react';+import { memo, useCallback, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { createStoreUpdater } from 'zustand-utils';@@ -27,6 +27,14 @@ const EditorSkeleton = () => (</div>);+/**+ * Stored markdown length from which a body loads after the switch has painted+ * instead of inside it. Building a long, deeply nested body blocks the main thread+ * for hundreds of milliseconds; inside the click it freezes the previous page until+ * it is done. Shorter bodies keep the atomic swap, so they never flash a skeleton.+ */+const AFTER_PAINT_HYDRATION_MIN_LENGTH = 50_000;+export interface DocumentIdModeProps extends EditorCanvasProps {documentId: string;editor: IEditor | undefined;@@ -129,6 +137,70 @@ const DocumentIdMode = memo<DocumentIdModeProps>(// Track which documentId has already had onEditorInit calledconst initializedDocIdRef = useRef<string | null>(null);const hydratedVersionRef = useRef<string | undefined>(undefined);+ // Cancels a load still waiting for the switch to paint.+ const cancelPendingHydrationRef = useRef<(() => void) | undefined>(undefined);++ // The document whose body the editor holds. Until a long body is this one's,+ // the editor (still holding the previous body) hides behind a skeleton.+ const [bodyDocumentId, setBodyDocumentId] = useState<string>();+ const isLongBody = useDocumentStore(+ (s) => editorSelectors.content(documentId)(s).length >= AFTER_PAINT_HYDRATION_MIN_LENGTH,+ );+ const isAwaitingBody = !collab && isLongBody && bodyDocumentId !== documentId;++ // Every load of the stored body runs with the content-change callback locked:+ // the load's own update is not an edit, and reporting it would serialize the+ // whole body again inside the route switch.+ const hydrate = useCallback(+ (editorInstance: IEditor, afterPaint = false) => {+ cancelPendingHydrationRef.current?.();+ cancelPendingHydrationRef.current = undefined;++ const run = () => {+ cancelPendingHydrationRef.current = undefined;+ const runId = ++initRunIdRef.current;+ contentChangeLockRef.current = true;++ void onEditorInit(editorInstance, documentId).finally(() => {+ onInit?.(editorInstance);+ queueMicrotask(() => {+ if (initRunIdRef.current === runId) {+ contentChangeLockRef.current = false;+ }+ });+ });+ setBodyDocumentId(documentId);+ };++ if (!afterPaint) {+ run();+ return;+ }++ // A frame callback runs before that frame paints; a task it queues runs after.+ let timer: number | undefined;+ const frame = window.requestAnimationFrame(() => {+ timer = window.setTimeout(run, 0);+ });+ cancelPendingHydrationRef.current = () => {+ window.cancelAnimationFrame(frame);+ window.clearTimeout(timer);+ };+ },+ [documentId, onEditorInit, onInit],+ );++ // A load waiting for its paint belongs to the document it was scheduled for.+ // Leaving that document first drops it, and a return has to load it again.+ useEffect(+ () => () => {+ if (!cancelPendingHydrationRef.current) return;+ cancelPendingHydrationRef.current();+ cancelPendingHydrationRef.current = undefined;+ if (initializedDocIdRef.current === documentId) initializedDocIdRef.current = null;+ },+ [documentId],+ );const handleEditorInit = useCallback((editorInstance: IEditor) => {@@ -145,11 +217,9 @@ const DocumentIdMode = memo<DocumentIdModeProps>(initializedDocIdRef.current = documentId;hydratedVersionRef.current = remoteDocumentVersion;- void onEditorInit(editorInstance, documentId).finally(() => {- onInit?.(editorInstance);- });+ hydrate(editorInstance, isAwaitingBody);},- [collab, documentId, onEditorInit, onInit, remoteDocumentVersion],+ [collab, documentId, hydrate, isAwaitingBody, onInit, remoteDocumentVersion],);// Critical fix: if the editor is already initialized, we need to manually call onEditorInit@@ -163,30 +233,19 @@ const DocumentIdMode = memo<DocumentIdModeProps>(!isLoading &&initializedDocIdRef.current !== documentId) {- const runId = ++initRunIdRef.current;initializedDocIdRef.current = documentId;hydratedVersionRef.current = remoteDocumentVersion;- // Lock content-change callback while hydrating document content into editor.- contentChangeLockRef.current = true;-- void onEditorInit(editor, documentId).finally(() => {- onInit?.(editor);- queueMicrotask(() => {- if (initRunIdRef.current === runId) {- contentChangeLockRef.current = false;- }- });- });+ hydrate(editor, isAwaitingBody);}}, [collab,documentId,editor,+ hydrate,+ isAwaitingBody,isEditorInitialized,isLoading,- onEditorInit,- onInit,remoteDocumentVersion,]);@@ -207,26 +266,15 @@ const DocumentIdMode = memo<DocumentIdModeProps>(const doc = useDocumentStore.getState().documents[documentId];if (doc && isEqual(editor.getDocument('json'), doc.editorData)) return;- const runId = ++initRunIdRef.current;- contentChangeLockRef.current = true;-- void onEditorInit(editor, documentId).finally(() => {- onInit?.(editor);- queueMicrotask(() => {- if (initRunIdRef.current === runId) {- contentChangeLockRef.current = false;- }- });- });+ hydrate(editor);}, [collab,documentId,editor,+ hydrate,isDirty,isEditorInitialized,isLoading,- onEditorInit,- onInit,remoteDocumentVersion,]);@@ -285,8 +333,10 @@ const DocumentIdMode = memo<DocumentIdModeProps>(/>)}{pendingBody}- {/* A room binds to the mounted editor, so it stays mounted behind the pending body. */}- <div style={{ display: pendingBody ? 'none' : 'contents' }}>+ {isAwaitingBody && <EditorSkeleton />}+ {/* A room binds to the mounted editor, so it stays mounted behind the pending body;+ a long body loads into the hidden editor after the switch paints. */}+ <div style={{ display: pendingBody || isAwaitingBody ? 'none' : 'contents' }}><InternalEditorcontentChangeLockRef={contentChangeLockRef}editor={editor}diff --git a/src/store/document/slices/editor/action.identity.test.ts b/src/store/document/slices/editor/action.identity.test.tsindex e5f872d5d45..9a0e018f8c6 100644--- a/src/store/document/slices/editor/action.identity.test.ts+++ b/src/store/document/slices/editor/action.identity.test.ts@@ -56,7 +56,7 @@ describe('document identity and metadata-only saves', () => {await useDocumentStore.getState().onEditorInit(editor, 'B');- expect(spy.setDocument).toHaveBeenCalledWith('json', JSON.stringify(body('B body')), {+ expect(spy.setDocument).toHaveBeenCalledWith('json', body('B body'), {keepId: true,});expect(useDocumentStore.getState().documents.A.content).toBe('A body');diff --git a/src/store/document/slices/editor/action.test.ts b/src/store/document/slices/editor/action.test.tsindex 58e3f071df4..fd8392d9bbc 100644--- a/src/store/document/slices/editor/action.test.ts+++ b/src/store/document/slices/editor/action.test.ts@@ -316,7 +316,7 @@ name: skill-name});expect(mockEditor.setDocument).toHaveBeenCalledTimes(1);- expect(mockEditor.setDocument).toHaveBeenCalledWith('json', JSON.stringify(editorData), {+ expect(mockEditor.setDocument).toHaveBeenCalledWith('json', editorData, {keepId: true,});});@@ -359,14 +359,9 @@ name: skill-nameexpect(consoleWarn).toHaveBeenCalledWith('[DocumentStore] Failed to load SKILL.md editorData, falling back to markdown',);- expect(mockEditor.setDocument).toHaveBeenNthCalledWith(- 1,- 'json',- JSON.stringify(editorData),- {- keepId: true,- },- );+ expect(mockEditor.setDocument).toHaveBeenNthCalledWith(1, 'json', editorData, {+ keepId: true,+ });expect(mockEditor.setDocument).toHaveBeenNthCalledWith(2, 'markdown', '# Body');consoleWarn.mockRestore();@@ -390,7 +385,7 @@ name: skill-nameresult.current.onEditorInit(mockEditor, 'doc-1');});- expect(mockEditor.setDocument).toHaveBeenCalledWith('json', JSON.stringify(editorData), {+ expect(mockEditor.setDocument).toHaveBeenCalledWith('json', editorData, {keepId: true,});});diff --git a/src/store/document/slices/editor/action.ts b/src/store/document/slices/editor/action.tsindex b4c7b38fb39..a7909c7e615 100644--- a/src/store/document/slices/editor/action.ts+++ b/src/store/document/slices/editor/action.ts@@ -141,9 +141,11 @@ export class EditorActionImpl {const markdownChanged = markdown !== doc.lastSavedContent;const editorDataChanged = !isEqual(editorData, doc.lastSavedEditorData);+ // The editor state determines its markdown, so an unchanged tree under the+ // same frontmatter is the loaded body without comparing markdown text.const isLoadedBody =!!doc.loadedBody &&- markdown === doc.loadedBody.content &&+ doc.loadedBody.skillFrontmatter === doc.skillFrontmatter &&isEqual(editorData, doc.loadedBody.editorData);const contentChanged = !isLoadedBody && (markdownChanged || editorDataChanged);@@ -478,30 +480,32 @@ export class EditorActionImpl {* reads as an edit — opening the page marks it dirty, autosaves it and holds* navigation behind a "Saving…" toast although the user changed nothing.*+ * Only the tree is recorded. Its markdown export costs more than the load+ * itself on a long, deeply nested page and would run inside the route switch;+ * `content` keeps the stored markdown, which is this body.+ ** `lastSaved*` keeps the server's body: conflict reconciliation compares* remote rows against it, and a normalized copy there would make a remote* title-only change look like a body change and discard local edits.*/#adoptLoadedBody = (editor: IEditor, documentId: string): void => {try {- const markdown = this.getPersistedMarkdown(- documentId,- (editor.getDocument('markdown') as unknown as string) || '',- );const editorData = editor.getDocument('json');if (!isValidEditorData(editorData)) return;- // The load's own change event already queued an autosave of this body.+ // An unlocked load's own change event may have queued an autosave of this body.this.#get().cancelDebouncedSave(documentId);this.#get().internal_dispatchDocument({id: documentId,type: 'updateDocument',value: {- content: markdown,editorData,isDirty: false,- loadedBody: { content: markdown, editorData },+ loadedBody: {+ editorData,+ skillFrontmatter: this.#get().documents[documentId]?.skillFrontmatter,+ },},},'adoptLoadedBody',@@ -535,7 +539,7 @@ export class EditorActionImpl {if (doc.contentFormat === 'skillMarkdown') {if (hasValidEditorData) {try {- editor.setDocument('json', JSON.stringify(doc.editorData), { keepId: true });+ editor.setDocument('json', doc.editorData, { keepId: true });return;} catch {console.warn(@@ -557,7 +561,7 @@ export class EditorActionImpl {// Set content from document stateif (hasValidEditorData) {try {- editor.setDocument('json', JSON.stringify(doc.editorData), { keepId: true });+ editor.setDocument('json', doc.editorData, { keepId: true });return;} catch {// Fallback to markdown if JSON failsdiff --git a/src/store/document/slices/editor/initialState.ts b/src/store/document/slices/editor/initialState.tsindex f58172d1042..8f3bb6ad3bf 100644--- a/src/store/document/slices/editor/initialState.ts+++ b/src/store/document/slices/editor/initialState.ts@@ -74,13 +74,14 @@ export interface EditorContentState {*/lastUpdatedTime: Date | null;/**- * The body as the editor serialized it right after loading it. Loading is not- * byte-stable (fresh node ids, the editor's own markdown export), so a body- * equal to this is unedited even when it differs from `lastSaved*`. Only the- * dirty check reads it; `lastSaved*` stays the server's body, which conflict- * reconciliation compares remote rows against. Cleared once a save lands.- */- loadedBody?: { content: string; editorData: unknown };+ * The tree the editor built right after loading the body, with the SKILL.md+ * frontmatter it was loaded under. Loading is not byte-stable (fresh node ids,+ * the editor's own markdown export), so a tree equal to this is unedited even+ * when it differs from `lastSaved*`. Only the dirty check reads it;+ * `lastSaved*` stays the server's body, which conflict reconciliation compares+ * remote rows against. Cleared once a save lands.+ */+ loadedBody?: { editorData: unknown; skillFrontmatter?: string };/*** Edit-session id that currently owns this document's collaborative lock.* Used by workspace page saves to prove the client still holds the lease.diff --git a/src/store/document/slices/editor/onEditorInit.emptyParseShell.test.ts b/src/store/document/slices/editor/onEditorInit.emptyParseShell.test.tsindex b61d9b5c3a8..a958cc8e814 100644--- a/src/store/document/slices/editor/onEditorInit.emptyParseShell.test.ts+++ b/src/store/document/slices/editor/onEditorInit.emptyParseShell.test.ts@@ -48,7 +48,7 @@ describe('onEditorInit empty-parse shell tolerance (Lexical error #38)', () => {// throw Lexical error #38 on hydration — so the markdown fallback runs.expect(mockEditor.setDocument).not.toHaveBeenCalledWith('json',- JSON.stringify({ root: { children: [], type: 'root' } }),+ { root: { children: [], type: 'root' } },{ keepId: true },);expect(mockEditor.setDocument).toHaveBeenCalledWith('markdown', '# Body');@@ -73,7 +73,7 @@ describe('onEditorInit empty-parse shell tolerance (Lexical error #38)', () => {result.current.onEditorInit(mockEditor, 'doc-legacy');});- expect(mockEditor.setDocument).toHaveBeenCalledWith('json', JSON.stringify(legacy), {+ expect(mockEditor.setDocument).toHaveBeenCalledWith('json', legacy, {keepId: true,});});diff --git a/src/store/document/slices/editor/onEditorInit.loadedBaseline.test.ts b/src/store/document/slices/editor/onEditorInit.loadedBaseline.test.tsindex 07b4cd07ef1..07f53fad6cd 100644--- a/src/store/document/slices/editor/onEditorInit.loadedBaseline.test.ts+++ b/src/store/document/slices/editor/onEditorInit.loadedBaseline.test.ts@@ -1,3 +1,4 @@+import type { IEditor } from '@lobehub/editor';import { act, renderHook } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -178,4 +179,66 @@ describe('onEditorInit — the loaded body is the clean baseline', () => {expect(doc.isDirty).toBe(true);expect(doc.content).toBe('# Title\n\nLocal edit\n');});++ it('loads a page without exporting its body as markdown', async () => {+ const { result } = renderHook(() => useDocumentStore());+ // The canvas locks its change callback while loading, so the load reports nothing.+ const editor = createLoadingEditor(() => {});++ act(() => {+ result.current.initDocumentWithEditor({+ content: '# Title',+ documentId: 'doc-1',+ editor: editor as unknown as IEditor,+ editorData: null,+ sourceType: 'page',+ });+ useDocumentStore.setState({+ activeDocumentId: 'doc-1',+ editor: editor as unknown as IEditor,+ });+ });++ await act(async () => {+ await result.current.onEditorInit(editor as unknown as IEditor, 'doc-1');+ });++ // A long page's markdown export costs more than loading it.+ expect(editor.getDocument).not.toHaveBeenCalledWith('markdown');+ expect(useDocumentStore.getState().documents['doc-1'].isDirty).toBe(false);+ });++ it('keeps a SKILL.md frontmatter edit made after loading as an edit', async () => {+ const { result } = renderHook(() => useDocumentStore());+ const editor = createLoadingEditor(() => {});++ act(() => {+ result.current.initDocumentWithEditor({+ content: '---\nname: old-skill\n---\n\n# Title',+ contentFormat: 'skillMarkdown',+ documentId: 'doc-1',+ editor: editor as unknown as IEditor,+ editorData: null,+ sourceType: 'page',+ });+ useDocumentStore.setState({+ activeDocumentId: 'doc-1',+ editor: editor as unknown as IEditor,+ });+ });++ await act(async () => {+ await result.current.onEditorInit(editor as unknown as IEditor, 'doc-1');+ });++ act(() => {+ result.current.updateSkillFrontmatter('doc-1', 'name: new-skill');+ });+ // The body tree is still the loaded one; only the frontmatter moved.+ act(() => {+ useDocumentStore.getState().handleContentChange();+ });++ expect(useDocumentStore.getState().documents['doc-1'].isDirty).toBe(true);+ });});diff --git a/src/store/document/slices/editor/reducer.ts b/src/store/document/slices/editor/reducer.tsindex fd5f4aabb78..1db6cbe2e75 100644--- a/src/store/document/slices/editor/reducer.ts+++ b/src/store/document/slices/editor/reducer.ts@@ -1,8 +1,14 @@-import { produce } from 'immer';+import { Immer } from 'immer';import { type EditorContentState } from './initialState';import { createInitialEditorContentState } from './initialState';+// A long page's body is a multi-megabyte tree. Auto-freeze walks every body+// assigned here to freeze it, which costs tens of milliseconds per update on such+// a page, inside the document switch and on every edit. Stored bodies are never+// mutated: the editor clones whatever it loads.+const { produce } = new Immer({ autoFreeze: false });+// ============ Action Types ============type AddDocumentAction = {