🤯 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): show the stored page while its room syncs instead of an empty editor (#21924)
Inneid3b85ed7deb2
diff --git a/src/features/EditorCanvas/DocumentIdMode.test.tsx b/src/features/EditorCanvas/DocumentIdMode.test.tsxindex c4312880adc..c97c6bd2c3b 100644--- a/src/features/EditorCanvas/DocumentIdMode.test.tsx+++ b/src/features/EditorCanvas/DocumentIdMode.test.tsx@@ -281,4 +281,23 @@ describe('DocumentIdMode', () => {expect(screen.getByTestId('not-found')).toBeInTheDocument();expect(screen.queryByTestId('internal-editor')).not.toBeInTheDocument();});+ it('shows the pending body over the mounted editor until the room body arrives', () => {+ const editor = { getLexicalEditor: vi.fn(() => ({})) } as any;+ const { rerender } = render(+ <DocumentIdMode+ collab+ documentId="doc-1"+ editor={editor}+ pendingBody={<div data-testid="pending-body" />}+ />,+ );++ expect(screen.getByTestId('pending-body')).toBeInTheDocument();+ expect(screen.getByTestId('internal-editor')).not.toBeVisible();++ rerender(<DocumentIdMode collab documentId="doc-1" editor={editor} />);++ expect(screen.queryByTestId('pending-body')).not.toBeInTheDocument();+ expect(screen.getByTestId('internal-editor')).toBeVisible();+ });});diff --git a/src/features/EditorCanvas/DocumentIdMode.tsx b/src/features/EditorCanvas/DocumentIdMode.tsxindex 4b3a9eeff4e..66849a60238 100644--- a/src/features/EditorCanvas/DocumentIdMode.tsx+++ b/src/features/EditorCanvas/DocumentIdMode.tsx@@ -41,6 +41,7 @@ const DocumentIdMode = memo<DocumentIdModeProps>(documentId,autoSave = true,collab = false,+ pendingBody,sourceType = 'page',topicId,onContentChange,@@ -283,15 +284,19 @@ const DocumentIdMode = memo<DocumentIdModeProps>(}}/>)}- <InternalEditor- contentChangeLockRef={contentChangeLockRef}- editor={editor}- placeholder={editorProps.placeholder || t('pageEditor.editorPlaceholder')}- style={style}- onContentChange={handleChange}- onInit={handleEditorInit}- {...editorProps}- />+ {pendingBody}+ {/* A room binds to the mounted editor, so it stays mounted behind the pending body. */}+ <div style={{ display: pendingBody ? 'none' : 'contents' }}>+ <InternalEditor+ contentChangeLockRef={contentChangeLockRef}+ editor={editor}+ placeholder={editorProps.placeholder || t('pageEditor.editorPlaceholder')}+ style={style}+ onContentChange={handleChange}+ onInit={handleEditorInit}+ {...editorProps}+ />+ </div></>);},diff --git a/src/features/EditorCanvas/EditorCanvas.tsx b/src/features/EditorCanvas/EditorCanvas.tsxindex e6b56446cf6..999b5b9e083 100644--- a/src/features/EditorCanvas/EditorCanvas.tsx+++ b/src/features/EditorCanvas/EditorCanvas.tsx@@ -2,7 +2,7 @@import { type IEditor, type SlashOptions } from '@lobehub/editor';import type { ChatInputActionsProps, Editor, EditorProps } from '@lobehub/editor/react';-import { type CSSProperties } from 'react';+import { type CSSProperties, type ReactNode } from 'react';import { memo } from 'react';import SafeBoundary from '@/components/ErrorBoundary';@@ -148,6 +148,12 @@ export interface EditorCanvasProps {*/onPressEnter?: (props: { editor: IEditor; event: KeyboardEvent }) => boolean | void;+ /**+ * Shown in place of the editor while the body is not in it yet (a room still+ * syncing); the editor stays mounted behind it (documentId mode only).+ */+ pendingBody?: ReactNode;+/*** Placeholder text for empty editor*/diff --git a/src/features/PageEditor/EditorCanvas/RoomBodyPreview.test.tsx b/src/features/PageEditor/EditorCanvas/RoomBodyPreview.test.tsxnew file mode 100644index 00000000000..14134a0c31b--- /dev/null+++ b/src/features/PageEditor/EditorCanvas/RoomBodyPreview.test.tsx@@ -0,0 +1,39 @@+/**+ * @vitest-environment happy-dom+ */+import { render } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { EditorCanvas } from '@/features/EditorCanvas';++import RoomBodyPreview from './RoomBodyPreview';++const previewEditor = { id: 'preview-editor' };+const storedEditorData = { root: { children: [{ type: 'paragraph' }] } };++vi.mock('@lobehub/editor/react', () => ({ useEditor: () => previewEditor }));++vi.mock('@/features/EditorCanvas', () => ({+ EditorCanvas: vi.fn(() => null),+}));++vi.mock('@/store/document', () => ({+ useDocumentStore: (selector: (state: unknown) => unknown) =>+ selector({+ documents: { 'doc-1': { content: 'stored body', editorData: storedEditorData } },+ }),+}));++describe('RoomBodyPreview', () => {+ it('renders the stored body read-only on its own editor', () => {+ render(<RoomBodyPreview documentId="doc-1" placeholder="Type" />);++ expect(vi.mocked(EditorCanvas).mock.lastCall?.[0]).toMatchObject({+ editable: false,+ editor: previewEditor,+ editorData: { content: 'stored body', editorData: storedEditorData },+ entityId: 'doc-1',+ placeholder: 'Type',+ });+ });+});diff --git a/src/features/PageEditor/EditorCanvas/RoomBodyPreview.tsx b/src/features/PageEditor/EditorCanvas/RoomBodyPreview.tsxnew file mode 100644index 00000000000..44ce58ca463--- /dev/null+++ b/src/features/PageEditor/EditorCanvas/RoomBodyPreview.tsx@@ -0,0 +1,39 @@+'use client';++import { useEditor } from '@lobehub/editor/react';+import { type ComponentProps, memo, useMemo } from 'react';++import { EditorCanvas as SharedEditorCanvas } from '@/features/EditorCanvas';+import { useDocumentStore } from '@/store/document';++type RoomBodyPreviewProps = Pick<+ ComponentProps<typeof SharedEditorCanvas>,+ 'allowContentBleed' | 'className' | 'enableInlineMath' | 'extraPlugins' | 'placeholder' | 'style'+> & { documentId: string };++// The stored body, read-only, while the room syncs. It runs on its own editor:+// writing the row into the room's editor would add a second copy of the page.+const RoomBodyPreview = memo<RoomBodyPreviewProps>(({ documentId, ...canvasProps }) => {+ const editor = useEditor();+ const content = useDocumentStore((s) => s.documents[documentId]?.content);+ const storedEditorData = useDocumentStore((s) => s.documents[documentId]?.editorData);+ const editorData = useMemo(+ () => ({ content: content ?? '', editorData: storedEditorData }),+ [content, storedEditorData],+ );++ return (+ <SharedEditorCanvas+ editable={false}+ editor={editor}+ editorData={editorData}+ entityId={documentId}+ floatingToolbar={false}+ {...canvasProps}+ />+ );+});++RoomBodyPreview.displayName = 'RoomBodyPreview';++export default RoomBodyPreview;diff --git a/src/features/PageEditor/EditorCanvas/index.tsx b/src/features/PageEditor/EditorCanvas/index.tsxindex 62be08b4b67..05951d14bfe 100644--- a/src/features/PageEditor/EditorCanvas/index.tsx+++ b/src/features/PageEditor/EditorCanvas/index.tsx@@ -13,6 +13,7 @@ import { EditorCanvas as SharedEditorCanvas } from '@/features/EditorCanvas';import { usePageCollab } from '../collab/usePageCollab';import { usePageEditorStore } from '../store';import { usePageEditable } from '../usePageEditable';+import RoomBodyPreview from './RoomBodyPreview';import { useAddCommentItem } from './useAddCommentItem';import { useAskCopilotItem } from './useAskCopilotItem';import { useDocumentMentionOption } from './useDocumentMentionOption';@@ -32,6 +33,9 @@ const EditorCanvas = memo<EditorCanvasProps>(({ askCopilotTarget, placeholder, sconst documentId = usePageEditorStore((s) => s.documentId);const onCollabReset = usePageEditorStore((s) => s.onCollabReset);const collabPlugin = usePageCollab(documentId, onCollabReset);+ const collabBodyShown = usePageEditorStore(+ (s) => !!s.collab?.bodyReady || s.collab?.status === 'error',+ );const slashItems = useSlashItems();const askCopilotItem = useAskCopilotItem(editor, askCopilotTarget);@@ -42,13 +46,30 @@ const EditorCanvas = memo<EditorCanvasProps>(({ askCopilotTarget, placeholder, s[addCommentItem, askCopilotItem],);+ const basePlugins = useMemo(+ () => [Editor.withProps(ReactBlockPlugin, { anchorPadding: 0 }), ReactCollapsiblePlugin],+ [],+ );const extraPlugins = useMemo(- () => [- Editor.withProps(ReactBlockPlugin, { anchorPadding: 0 }),- ReactCollapsiblePlugin,- ...(collabPlugin ? [collabPlugin] : []),- ],- [collabPlugin],+ () => (collabPlugin ? [...basePlugins, collabPlugin] : basePlugins),+ [basePlugins, collabPlugin],+ );+ const resolvedPlaceholder = placeholder || t('pageEditor.editorPlaceholder');+ const showStoredBody = !!collabPlugin && !collabBodyShown && !!documentId;+ const pendingBody = useMemo(+ () =>+ showStoredBody ? (+ <RoomBodyPreview+ allowContentBleed+ className={mentionPlainClassName}+ documentId={documentId!}+ enableInlineMath={false}+ extraPlugins={basePlugins}+ placeholder={resolvedPlaceholder}+ style={style}+ />+ ) : undefined,+ [basePlugins, documentId, resolvedPlaceholder, showStoredBody, style],);return (@@ -62,7 +83,8 @@ const EditorCanvas = memo<EditorCanvasProps>(({ askCopilotTarget, placeholder, senableInlineMath={false}extraPlugins={extraPlugins}mentionOption={mentionOption}- placeholder={placeholder || t('pageEditor.editorPlaceholder')}+ pendingBody={pendingBody}+ placeholder={resolvedPlaceholder}// Commenting on a selection is a read action: it must survive the page// being locked by another collaborator or opened view-only, when the// formatting toolbar (and Ask Copilot with it) is withheld.diff --git a/src/features/PageEditor/collab/provider.test.ts b/src/features/PageEditor/collab/provider.test.tsindex 80aa2882b89..ed79a6e9b44 100644--- a/src/features/PageEditor/collab/provider.test.ts+++ b/src/features/PageEditor/collab/provider.test.ts@@ -65,6 +65,23 @@ describe('PageCollabProvider', () => {expect(onSync).toHaveBeenCalledWith(true);});+ it('holds its awareness until the room answered the subscribe', () => {+ const { deliver, mux, ready, sent } = createMux();+ const provider = new PageCollabProvider('doc_1', new Y.Doc(), mux as any);++ provider.connect();+ ready();+ provider.awareness.setLocalState({ user: { name: 'A' } });++ expect(sent.filter((m) => m.type === 'doc_awareness')).toEqual([]);++ deliver(synced());++ expect(sent.filter((m) => m.type === 'doc_awareness')).toMatchObject([+ { state: { user: { name: 'A' } }, type: 'doc_awareness' },+ ]);+ });+it('asks the editor to bootstrap when it holds the claim', async () => {const { deliver, mux, ready } = createMux();const onBootstrap = vi.fn();diff --git a/src/features/PageEditor/collab/provider.ts b/src/features/PageEditor/collab/provider.tsindex 2788b71bfc2..41f2f1b6de0 100644--- a/src/features/PageEditor/collab/provider.ts+++ b/src/features/PageEditor/collab/provider.ts@@ -118,6 +118,9 @@ export class PageCollabProvider extends Emitter {private bootstrapping = false;private conflicted = false;private synced = false;+ // The hub refuses anything for the document until its subscribe settles, and a+ // refusal before the first sync fails the join.+ private subscribed = false;private failed = false;private subscribedAt = 0;private syncTimer: ReturnType<typeof setTimeout> | undefined;@@ -129,9 +132,10 @@ export class PageCollabProvider extends Emitter {private readonly events: PageCollabProviderEvents = {},) {super();- this.awareness = new PageCollabAwareness(doc.clientID, (state) =>- this.channel?.send({ clientID: doc.clientID, documentId, state, type: 'doc_awareness' }),- );+ this.awareness = new PageCollabAwareness(doc.clientID, (state) => {+ if (!this.subscribed) return;+ this.channel?.send({ clientID: doc.clientID, documentId, state, type: 'doc_awareness' });+ });doc.on('update', this.handleLocalUpdate);}@@ -190,6 +194,7 @@ export class PageCollabProvider extends Emitter {private subscribe = () => {this.synced = false;+ this.subscribed = false;this.subscribedAt = Date.now();clearTimeout(this.syncTimer);this.syncTimer = setTimeout(() => {@@ -206,6 +211,7 @@ export class PageCollabProvider extends Emitter {private handleStatus = (status: GatewayMuxStatus) => {if (status !== 'connected') {this.synced = false;+ this.subscribed = false;this.emit('status', { status: status === 'connecting' ? 'reconnecting' : status });this.events.onStatus?.('offline');}@@ -261,6 +267,7 @@ export class PageCollabProvider extends Emitter {this.events.onReset?.('epoch');return;}+ this.subscribed = true;this.bootstrapping = false;this.epoch = message.epoch;this.events.onAccess?.(message.access);diff --git a/src/features/PageEditor/collab/usePageCollab.ts b/src/features/PageEditor/collab/usePageCollab.tsindex a04c19c9a94..4e21dc39baf 100644--- a/src/features/PageEditor/collab/usePageCollab.ts+++ b/src/features/PageEditor/collab/usePageCollab.ts@@ -16,6 +16,7 @@ import { userProfileSelectors } from '@/store/user/selectors';import { usePageEditorStore, useStoreApi } from '../store';import { PageCollabProvider } from './provider';+import { whenBodyFilled } from './whenBodyFilled';const PAGE_META_KEY = 'meta';@@ -25,6 +26,8 @@ const offlineSnapshots = new Map<string, unknown>();// ponytail: fixed delay, push the projected title over resource events if it lags.const PAGE_LIST_REFRESH_DELAY_MS = 3000;+const BODY_FILL_TIMEOUT_MS = 500;+// Deployment-static config, read once like the gateway transport does. Rooms// exist only where the server enables page collaboration (LobeHub Cloud).const readGatewayUrl = () => {@@ -61,6 +64,7 @@ export const usePageCollab = (documentId: string | undefined, onReset?: () => voif (!enabled || !gatewayUrl) return undefined;const doc = new Y.Doc();+ let stopBodyWait: (() => void) | undefined;const setCollab = (next: Partial<NonNullable<ReturnType<typeof storeApi.getState>['collab']>>,) =>@@ -101,16 +105,25 @@ export const usePageCollab = (documentId: string | undefined, onReset?: () => vo) {setCollab({ status });}+ if (status === 'synced' && !stopBodyWait) {+ stopBodyWait = whenBodyFilled(+ storeApi.getState().editor?.getLexicalEditor(),+ BODY_FILL_TIMEOUT_MS,+ () => setCollab({ bodyReady: true }),+ );+ }},});- setCollab({ retry: () => provider.retry(), status: 'connecting' });+ // The previous page's session state is still in the store at this point.+ setCollab({ bodyReady: false, retry: () => provider.retry(), status: 'connecting' });- return { doc, provider };+ return { doc, provider, stopBodyWait: () => stopBodyWait?.() };}, [enabled, gatewayUrl, documentId, storeApi, onReset]);useEffect(() => {if (!session) return;return () => {+ session.stopBodyWait();session.provider.destroy();storeApi.setState({ collab: undefined });};diff --git a/src/features/PageEditor/collab/whenBodyFilled.test.ts b/src/features/PageEditor/collab/whenBodyFilled.test.tsnew file mode 100644index 00000000000..c3f0b401bee--- /dev/null+++ b/src/features/PageEditor/collab/whenBodyFilled.test.ts@@ -0,0 +1,79 @@+import {+ $createParagraphNode,+ $createTextNode,+ $getRoot,+ createEditor,+ type LexicalEditor,+} from 'lexical';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { whenBodyFilled } from './whenBodyFilled';++const commit = (editor: LexicalEditor, fn: () => void) =>+ new Promise<void>((resolve) => {+ editor.update(fn, { onUpdate: resolve });+ });++const emptyEditor = async () => {+ const editor = createEditor({ onError: (error) => Promise.reject(error) });+ await commit(editor, () => $getRoot().append($createParagraphNode()));+ return editor;+};++const fill = (editor: LexicalEditor) =>+ commit(editor, () => {+ $getRoot()+ .clear()+ .append($createParagraphNode().append($createTextNode('room body')));+ });++describe('whenBodyFilled', () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ it('waits for the update that writes the body', async () => {+ const editor = await emptyEditor();+ const onFilled = vi.fn();++ whenBodyFilled(editor, 1000, onFilled);+ await commit(editor, () => $getRoot().getFirstChild());+ expect(onFilled).not.toHaveBeenCalled();++ await fill(editor);+ expect(onFilled).toHaveBeenCalledTimes(1);+ });++ it('answers at once for a filled editor', async () => {+ const editor = await emptyEditor();+ await fill(editor);+ const onFilled = vi.fn();++ whenBodyFilled(editor, 1000, onFilled);++ expect(onFilled).toHaveBeenCalledTimes(1);+ });++ it('gives up on a page that stays empty', async () => {+ vi.useFakeTimers();+ const editor = createEditor({ onError: (error) => Promise.reject(error) });+ const onFilled = vi.fn();++ whenBodyFilled(editor, 500, onFilled);+ vi.advanceTimersByTime(499);+ expect(onFilled).not.toHaveBeenCalled();++ vi.advanceTimersByTime(1);+ expect(onFilled).toHaveBeenCalledTimes(1);+ });++ it('stays silent once cancelled', async () => {+ const editor = await emptyEditor();+ const onFilled = vi.fn();++ whenBodyFilled(editor, 1000, onFilled)();+ await fill(editor);++ expect(onFilled).not.toHaveBeenCalled();+ });+});diff --git a/src/features/PageEditor/collab/whenBodyFilled.ts b/src/features/PageEditor/collab/whenBodyFilled.tsnew file mode 100644index 00000000000..793e9fbfff3--- /dev/null+++ b/src/features/PageEditor/collab/whenBodyFilled.ts@@ -0,0 +1,41 @@+import { $getRoot, $isElementNode, type LexicalEditor } from 'lexical';++const isBodyEmpty = (editor: LexicalEditor) =>+ editor.getEditorState().read(() => {+ const root = $getRoot();+ if (root.getChildrenSize() > 1) return false;+ const first = root.getFirstChild();+ return !first || ($isElementNode(first) && first.getChildrenSize() === 0);+ });++// A room reports `synced` before the binding's write of its body commits to the+// editor, so revealing the editor on `synced` can show an empty page. A page+// that really is empty never fills, hence the timeout.+export const whenBodyFilled = (+ editor: LexicalEditor | null | undefined,+ timeoutMs: number,+ onFilled: () => void,+): (() => void) => {+ if (!editor || !isBodyEmpty(editor)) {+ onFilled();+ return () => {};+ }++ let settled = false;+ const stop = () => {+ settled = true;+ clearTimeout(timer);+ unregister();+ };+ const finish = () => {+ if (settled) return;+ stop();+ onFilled();+ };+ const unregister = editor.registerUpdateListener(() => {+ if (!isBodyEmpty(editor)) finish();+ });+ const timer = setTimeout(finish, timeoutMs);++ return stop;+};diff --git a/src/features/PageEditor/store/initialState.ts b/src/features/PageEditor/store/initialState.tsindex bdfd3a1dc36..3c10da8b68f 100644--- a/src/features/PageEditor/store/initialState.ts+++ b/src/features/PageEditor/store/initialState.ts@@ -37,6 +37,8 @@ export interface PublicState {export interface PageCollabState {access: 'edit' | 'view';+ /** The room's body reached the editor; until then the page shows the stored copy. */+ bodyReady?: boolean;pending: number;/** Joins the room again after it failed to sync. */retry?: () => void;