π€― 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(editor-runtime): add mutation handlers for post-save synchronization (#14469)
Innei6b010c8380af
diff --git a/packages/editor-runtime/src/EditorRuntime.ts b/packages/editor-runtime/src/EditorRuntime.tsindex 94d02368035..7049265d73e 100644--- a/packages/editor-runtime/src/EditorRuntime.ts+++ b/packages/editor-runtime/src/EditorRuntime.ts@@ -27,9 +27,23 @@ interface InspectableEditor {pluginsInstances?: unknown[];}+interface LiteXMLNodeMatch {+ attributes: string;+ content: string;+ id: string;+ tagName: string;+}++export type EditorMutationApiName = 'editTitle' | 'initPage' | 'modifyNodes' | 'replaceText';++export interface EditorMutationContext {+ apiName: EditorMutationApiName;+}+export interface EditorRuntimeDebugSnapshot {currentDocId?: string;dataSourceTypes: string[];+ hasAfterMutateHandler: boolean;hasBeforeMutateHandler: boolean;hasEditor: boolean;hasLexicalEditor: boolean;@@ -50,6 +64,9 @@ const getDataSourceTypes = (editor: InspectableEditor): string[] => {return Object.keys(dataTypeMap).sort();};+const hasDataSource = (editor: InspectableEditor, type: string) =>+ getDataSourceTypes(editor).includes(type);+/*** Editor Execution Runtime* Handles the execution logic for editor operations including:@@ -64,7 +81,9 @@ export class EditorRuntime {private titleSetter: ((title: string) => void) | null = null;private titleGetter: (() => string) | null = null;private currentDocId: string | undefined = undefined;- private beforeMutateHandler: (() => void | Promise<void>) | null = null;+ private afterMutateHandler: (() => void | Promise<void>) | null = null;+ private beforeMutateHandler: ((context: EditorMutationContext) => void | Promise<void>) | null =+ null;/*** Set the current editor instance@@ -94,11 +113,22 @@ export class EditorRuntime {* Set a handler to be called before any mutating operation.* This can be used to save history or perform other pre-mutation tasks.*/- setBeforeMutateHandler(handler: (() => void | Promise<void>) | null) {+ setBeforeMutateHandler(+ handler: ((context: EditorMutationContext) => void | Promise<void>) | null,+ ) {this.beforeMutateHandler = handler;log('[EditorRuntime] setBeforeMutateHandler', this.getDebugSnapshot());}+ /**+ * Set a handler to be called after any successful mutating operation.+ * This can be used to synchronize editor changes into the host persistence layer.+ */+ setAfterMutateHandler(handler: (() => void | Promise<void>) | null) {+ this.afterMutateHandler = handler;+ log('[EditorRuntime] setAfterMutateHandler', this.getDebugSnapshot());+ }+/*** Set the title setter and getter functions*/@@ -125,6 +155,7 @@ export class EditorRuntime {return {currentDocId: this.currentDocId,dataSourceTypes: inspectableEditor ? getDataSourceTypes(inspectableEditor) : [],+ hasAfterMutateHandler: !!this.afterMutateHandler,hasBeforeMutateHandler: !!this.beforeMutateHandler,hasEditor: !!this.editor,hasLexicalEditor,@@ -166,6 +197,22 @@ export class EditorRuntime {return { getter: this.titleGetter, setter: this.titleSetter };}+ private async runBeforeMutate(apiName: EditorMutationApiName) {+ try {+ await this.beforeMutateHandler?.({ apiName });+ } catch {+ /* ignore pre-mutation errors */+ }+ }++ private async runAfterMutate() {+ try {+ await this.afterMutateHandler?.();+ } catch {+ /* ignore post-mutation errors */+ }+ }+// ==================== Initialize ====================/**@@ -175,14 +222,15 @@ export class EditorRuntime {async initPage(args: InitDocumentArgs): Promise<InitPageRuntimeResult> {log('[EditorRuntime] initPage:start', {markdownLength: args.markdown.length,+snapshot: this.getDebugSnapshot(),});- try {- await this.beforeMutateHandler?.();- } catch {- /* ignore pre-mutation errors */+ if (!args.markdown || args.markdown.trim().length === 0) {+ throw new Error('initPage failed: markdown content is empty.');}++ await this.runBeforeMutate('initPage');const editor = this.getEditor();let markdown = args.markdown;@@ -196,6 +244,11 @@ export class EditorRuntime {// Remove the title line from markdownmarkdown = markdown.slice(titleLine.length).trimStart();+ log('[EditorRuntime] initPage:titleExtracted', {+ extractedTitle,+ remainingMarkdownLength: markdown.length,+ });+// Set the title separately if title handlers are availableif (this.titleSetter) {this.titleSetter(extractedTitle);@@ -203,11 +256,31 @@ export class EditorRuntime {}// Set markdown content directly - the editor will convert it internally+editor.setDocument('markdown', markdown, { keepId: true });// Get the resulting document to count nodes+ // Lexical getDocument('json') returns { root: { children: [...] } }+ // where 'root' wraps the top-level block elementsconst jsonState = editor.getDocument('json') as any;- const nodeCount = jsonState?.children?.length || 0;+ const root = jsonState?.root ?? jsonState;+ const nodeCount = root?.children?.length || 0;++ log('[EditorRuntime] initPage:afterSetDocument', {+ nodeCount,+ jsonStateKeys: jsonState ? Object.keys(jsonState) : null,+ rootKeys: root ? Object.keys(root) : null,+ });++ if (nodeCount === 0) {+ throw new Error(+ `initPage failed: setDocument produced 0 nodes. ` ++ `Input markdown length: ${args.markdown.length}, ` ++ `after title-stripping: ${markdown.length}. ` ++ `jsonState keys: ${jsonState ? JSON.stringify(Object.keys(jsonState)) : 'null'}, ` ++ `root keys: ${root ? JSON.stringify(Object.keys(root)) : 'null'}.`,+ );+ }const result = { extractedTitle, nodeCount };log('[EditorRuntime] initPage:success', {@@ -216,6 +289,8 @@ export class EditorRuntime {titleExtracted: !!extractedTitle,});+ await this.runAfterMutate();+return result;}@@ -231,11 +306,7 @@ export class EditorRuntime {titleLength: args.title.length,});- try {- await this.beforeMutateHandler?.();- } catch {- /* ignore pre-mutation errors */- }+ await this.runBeforeMutate('editTitle');const { setter, getter } = this.getTitleHandlers();const previousTitle = getter();@@ -248,6 +319,8 @@ export class EditorRuntime {titleLength: args.title.length,});+ await this.runAfterMutate();+return result;}@@ -326,11 +399,7 @@ export class EditorRuntime {snapshot: this.getDebugSnapshot(),});- try {- await this.beforeMutateHandler?.();- } catch {- /* ignore pre-mutation errors */- }+ await this.runBeforeMutate('modifyNodes');const editor = this.getEditor();let { operations } = args;@@ -373,6 +442,10 @@ export class EditorRuntime {afterId: op.afterId,litexml: op.litexml,});+ } else {+ throw new Error(+ `Insert operation requires either 'beforeId' or 'afterId'. Got: ${JSON.stringify(Object.keys(op))}.`,+ );}results.push({ action: 'insert', success: true });break;@@ -403,10 +476,14 @@ export class EditorRuntime {}}- // Dispatch all operations at once+ if (!hasDataSource(editor as InspectableEditor, 'litexml')) {+ throw new Error('modifyNodes failed: LiteXML data source is not ready.');+ }++ // Dispatch all operations at once. The LiteXML command handler returns false+ // even after handling the command, so the return value is not a failure signal.log('Dispatching LITEXML_MODIFY_COMMAND with payload:', commandPayload);- const success = editor.dispatchCommand(LITEXML_MODIFY_COMMAND, commandPayload);- log('Command dispatched, success:', success);+ editor.dispatchCommand(LITEXML_MODIFY_COMMAND, commandPayload);const successCount = results.filter((r) => r.success).length;const totalCount = results.length;@@ -418,6 +495,8 @@ export class EditorRuntime {totalCount,});+ await this.runAfterMutate();+return result;}@@ -425,23 +504,21 @@ export class EditorRuntime {/*** Extract all element nodes with their IDs and content from LiteXML- * Returns an array of { id, tagName, fullMatch, content } objects+ * Returns an array of { id, tagName, attributes, content } objects*/- private extractNodesFromLiteXML(- litexml: string,- ): Array<{ content: string; fullMatch: string; id: string; tagName: string }> {- const nodes: Array<{ content: string; fullMatch: string; id: string; tagName: string }> = [];+ private extractNodesFromLiteXML(litexml: string): LiteXMLNodeMatch[] {+ const nodes: LiteXMLNodeMatch[] = [];// Match elements with id attributes and their content// Pattern: <tagName id="nodeId" ...>content</tagName>- const elementRegex = /<(\w+)\s[^>]*id="([^"]+)"[^>]*>([\s\S]*?)<\/\1>/g;+ const elementRegex = /<(\w+)(\s[^>]*id="([^"]+)"[^>]*)>([\s\S]*?)<\/\1>/g;let match;while ((match = elementRegex.exec(litexml)) !== null) {nodes.push({- content: match[3],- fullMatch: match[0],- id: match[2],+ attributes: match[2].trim(),+ content: match[4],+ id: match[3],tagName: match[1],});}@@ -593,11 +670,7 @@ export class EditorRuntime {* @returns Raw result with modifiedNodeIds and replacementCount*/async replaceText(args: ReplaceTextArgs): Promise<ReplaceTextRuntimeResult> {- try {- await this.beforeMutateHandler?.();- } catch {- /* ignore pre-mutation errors */- }+ await this.runBeforeMutate('replaceText');const editor = this.getEditor();const { searchText, newText, useRegex = false, replaceAll = true, nodeIds } = args;@@ -613,6 +686,7 @@ export class EditorRuntime {const pageXML = editor.getDocument('litexml') as unknown as string;if (!pageXML) {+ console.error('[EditorRuntime] replaceText:failed β pageXML is empty');throw new Error('Document is empty or not initialized');}@@ -630,6 +704,8 @@ export class EditorRuntime {// Extract nodes from LiteXMLconst nodes = this.extractNodesFromLiteXML(pageXML);+ const allNodeIds = nodes.map((n) => n.id);+log('Found nodes:', nodes.length);// Filter nodes if nodeIds is specified and non-empty@@ -638,12 +714,7 @@ export class EditorRuntime {const targetNodes = hasNodeFilter ? nodes.filter((node) => nodeIds.includes(node.id)) : nodes;if (hasNodeFilter && targetNodes.length === 0) {- log(- '[replaceText] Node IDs requested:',- nodeIds,- 'Available IDs:',- nodes.map((n) => n.id),- );+ log('[replaceText] Node IDs requested:', nodeIds, 'Available IDs:', allNodeIds);throw new Error(`None of the specified nodes were found: ${nodeIds.join(', ')}`);}@@ -660,7 +731,9 @@ export class EditorRuntime {? node.content.includes(searchPattern): searchPattern.test(node.content);- if (!hasMatch) continue;+ if (!hasMatch) {+ continue;+ }// Reset regex lastIndex if using regexif (searchPattern instanceof RegExp) {@@ -680,12 +753,7 @@ export class EditorRuntime {modifiedNodeIds.push(node.id);// Build the updated LiteXML for this node- // Extract attributes from the original fullMatch- const firstSpace = node.fullMatch.indexOf(' ');- const attributes =- firstSpace > 0 ? node.fullMatch.slice(firstSpace + 1, -1) : `id="${node.id}"`;-- const updatedLitexml = `<${node.tagName} ${attributes}>${newContent}</${node.tagName}>`;+ const updatedLitexml = `<${node.tagName} ${node.attributes}>${newContent}</${node.tagName}>`;litexmlUpdates.push(updatedLitexml);log('Updated node:', node.id, 'count:', count);@@ -698,14 +766,24 @@ export class EditorRuntime {}// Apply updates if any replacements were made+if (litexmlUpdates.length > 0) {log('Applying updates:', litexmlUpdates.length);- const success = editor.dispatchCommand(LITEXML_APPLY_COMMAND, {+ if (!hasDataSource(editor as InspectableEditor, 'litexml')) {+ throw new Error('replaceText failed: LiteXML data source is not ready.');+ }++ const dispatchSuccess = editor.dispatchCommand(LITEXML_APPLY_COMMAND, {litexml: litexmlUpdates,});- log('Command dispatched, success:', success);++ log('Command dispatched, success:', dispatchSuccess);}- return { modifiedNodeIds, replacementCount: totalReplacementCount };+ const result = { modifiedNodeIds, replacementCount: totalReplacementCount };++ await this.runAfterMutate();++ return result;}}diff --git a/packages/editor-runtime/src/__tests__/EditorRuntime.test.ts b/packages/editor-runtime/src/__tests__/EditorRuntime.test.tsindex e3312800210..4f55c18c73e 100644--- a/packages/editor-runtime/src/__tests__/EditorRuntime.test.ts+++ b/packages/editor-runtime/src/__tests__/EditorRuntime.test.ts@@ -531,7 +531,7 @@ describe('EditorRuntime', () => {await runtime.initPage({ markdown: 'Test content' });await moment();- expect(handler).toHaveBeenCalledTimes(1);+ expect(handler).toHaveBeenCalledWith({ apiName: 'initPage' });});it('should call beforeMutateHandler before editTitle', async () => {@@ -540,7 +540,7 @@ describe('EditorRuntime', () => {await runtime.editTitle({ title: 'New Title' });- expect(handler).toHaveBeenCalledTimes(1);+ expect(handler).toHaveBeenCalledWith({ apiName: 'editTitle' });});it('should call beforeMutateHandler before modifyNodes', async () => {@@ -551,7 +551,7 @@ describe('EditorRuntime', () => {operations: [{ action: 'insert', afterId: 'root', litexml: '<p>Test</p>' }],});- expect(handler).toHaveBeenCalledTimes(1);+ expect(handler).toHaveBeenCalledWith({ apiName: 'modifyNodes' });});it('should call beforeMutateHandler before replaceText', async () => {@@ -560,7 +560,7 @@ describe('EditorRuntime', () => {await runtime.replaceText({ searchText: 'old', newText: 'new' });- expect(handler).toHaveBeenCalledTimes(1);+ expect(handler).toHaveBeenCalledWith({ apiName: 'replaceText' });});it('should still proceed when beforeMutateHandler is not set', async () => {@@ -583,6 +583,40 @@ describe('EditorRuntime', () => {});});+ describe('afterMutateHandler', () => {+ it('should call afterMutateHandler after initPage succeeds', async () => {+ const handler = vi.fn().mockResolvedValue(undefined);+ runtime.setAfterMutateHandler(handler);++ await runtime.initPage({ markdown: 'Test content' });+ await moment();++ expect(handler).toHaveBeenCalledTimes(1);+ });++ it('should not call afterMutateHandler when initPage fails before mutation', async () => {+ const handler = vi.fn().mockResolvedValue(undefined);+ runtime.setAfterMutateHandler(handler);++ await expect(runtime.initPage({ markdown: '' })).rejects.toThrow(+ 'initPage failed: markdown content is empty.',+ );++ expect(handler).not.toHaveBeenCalled();+ });++ it('should still proceed when afterMutateHandler throws', async () => {+ const handler = vi.fn().mockRejectedValue(new Error('Handler failed'));+ runtime.setAfterMutateHandler(handler);++ const result = await runtime.initPage({ markdown: 'Test content' });+ await moment();++ expect(handler).toHaveBeenCalledTimes(1);+ expect(result.nodeCount).toBeGreaterThanOrEqual(0);+ });+ });+describe('getPageContentContext', () => {beforeEach(async () => {await runtime.initPage({ markdown: 'Test content for context' });diff --git a/src/features/AgentMockDevtools/index.tsx b/src/features/AgentMockDevtools/index.tsxindex 9249172ac77..6efca28ff6a 100644--- a/src/features/AgentMockDevtools/index.tsx+++ b/src/features/AgentMockDevtools/index.tsx@@ -1,4 +1,5 @@import { memo, useEffect, useState } from 'react';+import { useMatches } from 'react-router-dom';import { Fab } from './Fab';import { Modal } from './Modal';@@ -26,9 +27,17 @@ const useDevtoolsEnabled = (): boolean => {return enabled;};+const useIsAgentTopicRoute = (): boolean => {+ const matches = useMatches();+ // Check if any resolved route segment has a topicId param+ // This correctly distinguishes /agent/:topicId from /agent/page, /agent/profile, etc.+ return matches.some((m) => 'topicId' in m.params);+};+const AgentMockDevtools = memo(() => {const enabled = useDevtoolsEnabled();- if (!isDevEnv || !enabled) return null;+ const isAgentTopicRoute = useIsAgentTopicRoute();+ if (!isDevEnv || !enabled || !isAgentTopicRoute) return null;return (<><Fab />diff --git a/src/features/PageEditor/StoreUpdater.tsx b/src/features/PageEditor/StoreUpdater.tsxindex 56dc50732dd..bc9c7885c40 100644--- a/src/features/PageEditor/StoreUpdater.tsx+++ b/src/features/PageEditor/StoreUpdater.tsx@@ -3,7 +3,9 @@import { memo, useEffect } from 'react';import { createStoreUpdater } from 'zustand-utils';+import { hasMeaningfulEditorContent } from '@/libs/editor/hasMeaningfulEditorContent';import { documentHistoryQueueService } from '@/services/documentHistoryQueue';+import { useDocumentStore } from '@/store/document';import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-page-agent';import { type PublicState } from './store';@@ -77,14 +79,27 @@ const StoreUpdater = memo<StoreUpdaterProps>(pageAgentRuntime.setCurrentDocId(pageId);pageAgentRuntime.setTitleHandlers(storeApi.getState().setTitle, titleGetter);pageAgentRuntime.setBeforeMutateHandler(() => {+ const editor = storeApi.getState().editor;+ const editorData = editor?.getDocument('json');++ if (!hasMeaningfulEditorContent(editorData)) {+ return;+ }+documentHistoryQueueService.enqueueEditorSnapshot({documentId: pageId,- editor: storeApi.getState().editor,+ editor,});});+ pageAgentRuntime.setAfterMutateHandler(async () => {+ if (!pageId) return;++ await useDocumentStore.getState().commitEditorMutation(pageId, { saveSource: 'llm_call' });+ });return () => {pageAgentRuntime.setCurrentDocId(undefined);+ pageAgentRuntime.setAfterMutateHandler(null);pageAgentRuntime.setTitleHandlers(null, null);pageAgentRuntime.setBeforeMutateHandler(null);void documentHistoryQueueService.flush();diff --git a/src/features/TopicCanvas/index.test.tsx b/src/features/TopicCanvas/index.test.tsxindex 500180b3682..e77b3e79c94 100644--- a/src/features/TopicCanvas/index.test.tsx+++ b/src/features/TopicCanvas/index.test.tsx@@ -14,11 +14,12 @@ const mockEditor = {['markdown', {}],]),focus: vi.fn(),- getDocument: vi.fn(() => ({ root: true })),+ getDocument: vi.fn((): unknown => ({ root: true })),getLexicalEditor: vi.fn(() => ({})),} as const;const runtimeSpies = vi.hoisted(() => ({+ setAfterMutateHandler: vi.fn(),setBeforeMutateHandler: vi.fn(),setCurrentDocId: vi.fn(),setEditor: vi.fn(),@@ -26,6 +27,9 @@ const runtimeSpies = vi.hoisted(() => ({}));const useEditorMock = vi.hoisted(() => vi.fn(() => mockEditor));+const documentStoreMock = vi.hoisted(() => ({+ commitEditorMutation: vi.fn(),+}));vi.mock('@lobehub/editor/react', () => ({EditorProvider: ({ children }: { children: ReactNode }) => <>{children}</>,@@ -106,6 +110,12 @@ vi.mock('@/services/documentHistoryQueue', () => ({},}));+vi.mock('@/store/document', () => ({+ useDocumentStore: {+ getState: () => documentStoreMock,+ },+}));+vi.mock('@/store/tool/slices/builtin/executors/lobe-page-agent', () => ({pageAgentRuntime: runtimeSpies,}));@@ -129,23 +139,61 @@ describe('TopicCanvas', () => {expect(runtimeSpies.setCurrentDocId).toHaveBeenCalledWith('doc-1');expect(runtimeSpies.setTitleHandlers).toHaveBeenCalledTimes(1);expect(runtimeSpies.setBeforeMutateHandler).toHaveBeenCalledWith(expect.any(Function));+ expect(runtimeSpies.setAfterMutateHandler).toHaveBeenCalledWith(expect.any(Function));});const beforeMutateHandler = runtimeSpies.setBeforeMutateHandler.mock.calls.find(([handler]) => typeof handler === 'function',- )?.[0] as (() => void) | undefined;- beforeMutateHandler?.();+ )?.[0] as ((context: { apiName: 'modifyNodes' }) => void) | undefined;+ beforeMutateHandler?.({ apiName: 'modifyNodes' });expect(documentHistoryQueueService.enqueueEditorSnapshot).toHaveBeenCalledWith({documentId: 'doc-1',editor: mockEditor,});+ const afterMutateHandler = runtimeSpies.setAfterMutateHandler.mock.calls.find(+ ([handler]) => typeof handler === 'function',+ )?.[0] as (() => Promise<void>) | undefined;+ await afterMutateHandler?.();++ expect(documentStoreMock.commitEditorMutation).toHaveBeenCalledWith('doc-1', {+ saveSource: 'llm_call',+ });+unmount();expect(runtimeSpies.setCurrentDocId).toHaveBeenLastCalledWith(undefined);+ expect(runtimeSpies.setAfterMutateHandler).toHaveBeenLastCalledWith(null);expect(runtimeSpies.setTitleHandlers).toHaveBeenLastCalledWith(null, null);expect(runtimeSpies.setBeforeMutateHandler).toHaveBeenLastCalledWith(null);expect(runtimeSpies.setEditor).toHaveBeenLastCalledWith(null);});++ it('does not save a history snapshot for an empty editor state', async () => {+ const { unmount } = render(+ <TopicCanvas documentId="doc-1" title="Topic Title" onTitleChange={vi.fn()} />,+ );++ await waitFor(() => {+ expect(runtimeSpies.setBeforeMutateHandler).toHaveBeenCalledWith(expect.any(Function));+ });++ const beforeMutateHandler = runtimeSpies.setBeforeMutateHandler.mock.calls.find(+ ([handler]) => typeof handler === 'function',+ )?.[0] as ((context: { apiName: 'modifyNodes' }) => void) | undefined;++ mockEditor.getDocument.mockReturnValueOnce({+ root: {+ children: [{ children: [], type: 'paragraph' }],+ type: 'root',+ },+ });++ beforeMutateHandler?.({ apiName: 'modifyNodes' });++ expect(documentHistoryQueueService.enqueueEditorSnapshot).not.toHaveBeenCalled();++ unmount();+ });});diff --git a/src/features/TopicCanvas/index.tsx b/src/features/TopicCanvas/index.tsxindex 00cb1bc5740..9ddee11b427 100644--- a/src/features/TopicCanvas/index.tsx+++ b/src/features/TopicCanvas/index.tsx@@ -11,7 +11,9 @@ import { memo, useCallback, useEffect, useRef, useState } from 'react';import { DiffAllToolbar, EditorCanvas as SharedEditorCanvas } from '@/features/EditorCanvas';import WideScreenContainer from '@/features/WideScreenContainer';import { useRegisterFilesHotkeys } from '@/hooks/useHotkeys';+import { hasMeaningfulEditorContent } from '@/libs/editor/hasMeaningfulEditorContent';import { documentHistoryQueueService } from '@/services/documentHistoryQueue';+import { useDocumentStore } from '@/store/document';import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-page-agent';import { StyleSheet } from '@/utils/styles';@@ -139,18 +141,35 @@ const TopicCanvasPageAgentBridge = memo<},() => titleRef.current,);- pageAgentRuntime.setBeforeMutateHandler(() => {+ pageAgentRuntime.setBeforeMutateHandler(({ apiName }) => {+ const editorData = editor?.getDocument('json');+ const hasHistorySnapshot = hasMeaningfulEditorContent(editorData);+log('[TopicCanvas/PageAgentBridge] beforeMutate', {+ apiName,dataSourceTypes: getPageAgentEditorSnapshot(editor).dataSourceTypes,documentId,hasEditor: !!editor,+ hasHistorySnapshot,});+ if (!hasHistorySnapshot) {+ return;+ }+documentHistoryQueueService.enqueueEditorSnapshot({ documentId, editor });});+ pageAgentRuntime.setAfterMutateHandler(async () => {+ if (!documentId) return;++ await useDocumentStore+ .getState()+ .commitEditorMutation(documentId, { saveSource: 'llm_call' });+ });return () => {log('[TopicCanvas/PageAgentBridge] clearDocumentContext', { documentId });pageAgentRuntime.setCurrentDocId(undefined);+ pageAgentRuntime.setAfterMutateHandler(null);pageAgentRuntime.setTitleHandlers(null, null);pageAgentRuntime.setBeforeMutateHandler(null);void documentHistoryQueueService.flush();diff --git a/src/libs/editor/hasMeaningfulEditorContent.test.ts b/src/libs/editor/hasMeaningfulEditorContent.test.tsnew file mode 100644index 00000000000..e81d57e89ce--- /dev/null+++ b/src/libs/editor/hasMeaningfulEditorContent.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from 'vitest';++import { hasMeaningfulEditorContent } from './hasMeaningfulEditorContent';++describe('hasMeaningfulEditorContent', () => {+ it('should reject an empty paragraph editor state', () => {+ expect(+ hasMeaningfulEditorContent({+ root: {+ children: [+ {+ children: [],+ type: 'paragraph',+ },+ ],+ type: 'root',+ },+ }),+ ).toBe(false);+ });++ it('should accept text content', () => {+ expect(+ hasMeaningfulEditorContent({+ root: {+ children: [+ {+ children: [{ text: 'content', type: 'text' }],+ type: 'paragraph',+ },+ ],+ type: 'root',+ },+ }),+ ).toBe(true);+ });++ it('should accept non-text structural content', () => {+ expect(+ hasMeaningfulEditorContent({+ root: {+ children: [{ type: 'horizontalrule' }],+ type: 'root',+ },+ }),+ ).toBe(true);+ });+});diff --git a/src/libs/editor/hasMeaningfulEditorContent.ts b/src/libs/editor/hasMeaningfulEditorContent.tsnew file mode 100644index 00000000000..9c2434912ad--- /dev/null+++ b/src/libs/editor/hasMeaningfulEditorContent.ts@@ -0,0 +1,30 @@+const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null;++export const hasMeaningfulEditorContent = (editorData: unknown): boolean => {+ if (!isRecord(editorData)) return false;++ const root = editorData.root;++ // Unknown shapes are treated as meaningful so callers do not drop data they+ // cannot safely classify.+ if (!isRecord(root) || !Array.isArray(root.children)) return true;++ const walk = (node: unknown): boolean => {+ if (!isRecord(node)) return false;++ if (typeof node.text === 'string' && node.text.trim().length > 0) return true;++ const type = node.type;+ if (typeof type === 'string' && !['paragraph', 'root', 'text'].includes(type)) {+ return true;+ }++ const children = node.children;+ if (!Array.isArray(children)) return false;++ return children.some(walk);+ };++ return root.children.some(walk);+};diff --git a/src/store/document/slices/editor/action.test.ts b/src/store/document/slices/editor/action.test.tsindex df9d47380e6..2f2628e077d 100644--- a/src/store/document/slices/editor/action.test.ts+++ b/src/store/document/slices/editor/action.test.ts@@ -367,6 +367,55 @@ describe('DocumentStore - Editor Actions', () => {});});+ describe('commitEditorMutation', () => {+ it('syncs current editor content and immediately saves through the document manager', async () => {+ const { result } = renderHook(() => useDocumentStore());+ const editorData = {+ root: { children: [{ children: [], type: 'paragraph' }], type: 'root' },+ };+ const mockEditor = {+ getDocument: vi.fn((type: string) => {+ if (type === 'markdown') return '# Updated';+ if (type === 'json') return editorData;+ return null;+ }),+ setDocument: vi.fn(),+ } as any;++ act(() => {+ result.current.initDocumentWithEditor({+ content: '# Initial',+ documentId: 'doc-1',+ editor: mockEditor,+ editorData: {+ root: { children: [{ children: [], type: 'paragraph' }], type: 'root' },+ },+ sourceType: 'page',+ });+ });++ await act(async () => {+ await result.current.commitEditorMutation('doc-1', { saveSource: 'llm_call' });+ });++ expect(documentService.updateDocument).toHaveBeenCalledWith(+ expect.objectContaining({+ content: '# Updated',+ editorData: JSON.stringify(editorData),+ id: 'doc-1',+ saveSource: 'llm_call',+ }),+ );+ expect(result.current.documents['doc-1']).toMatchObject({+ content: '# Updated',+ editorData,+ isDirty: false,+ lastSavedContent: '# Updated',+ lastSavedEditorData: editorData,+ });+ });+ });+describe('setEditorState', () => {it('should set editor state', () => {const { result } = renderHook(() => useDocumentStore());diff --git a/src/store/document/slices/editor/action.ts b/src/store/document/slices/editor/action.tsindex e51011e062f..656f47020c1 100644--- a/src/store/document/slices/editor/action.ts+++ b/src/store/document/slices/editor/action.ts@@ -57,13 +57,17 @@ export class EditorActionImpl {}};- handleContentChange = (): void => {+ private syncEditorContent = (+ documentId?: string,+ options: { triggerAutoSave?: boolean } = {},+ ): boolean => {const { editor, activeDocumentId, documents, internal_dispatchDocument } = this.#get();+ const id = documentId || activeDocumentId;- if (!editor || !activeDocumentId) return;+ if (!editor || !id) return false;- const doc = documents[activeDocumentId];- if (!doc) return;+ const doc = documents[id];+ if (!doc) return false;try {const markdown = (editor.getDocument('markdown') as unknown as string) || '';@@ -75,7 +79,7 @@ export class EditorActionImpl {internal_dispatchDocument({- id: activeDocumentId,+ id,type: 'updateDocument',value: { content: markdown, editorData, isDirty: contentChanged },},@@ -83,14 +87,32 @@ export class EditorActionImpl {);// Only trigger auto-save if content actually changed AND autoSave is enabled- if (contentChanged && doc.autoSave !== false) {- this.#get().triggerDebouncedSave(activeDocumentId);+ if (options.triggerAutoSave !== false && contentChanged && doc.autoSave !== false) {+ this.#get().triggerDebouncedSave(id);}++ return contentChanged;} catch (error) {console.error('[DocumentStore] Failed to update content:', error);+ return false;}};+ commitEditorMutation = async (+ documentId?: string,+ options?: SaveExecutionOptions,+ ): Promise<void> => {+ const id = documentId || this.#get().activeDocumentId;+ if (!id) return;++ this.syncEditorContent(id, { triggerAutoSave: false });+ await this.performSave(id, undefined, options);+ };++ handleContentChange = (): void => {+ this.syncEditorContent(undefined, { triggerAutoSave: true });+ };+internal_dispatchDocument = (payload: DocumentDispatch, action?: string): void => {const { documents } = this.#get();const nextDocuments = documentReducer(documents, payload);diff --git a/src/store/file/slices/document/action.test.ts b/src/store/file/slices/document/action.test.tsindex dca6f7015d8..eebd58179f3 100644--- a/src/store/file/slices/document/action.test.ts+++ b/src/store/file/slices/document/action.test.ts@@ -233,6 +233,65 @@ describe('DocumentAction', () => {expect(useStore.getState().resourceMap.get('doc-1')?._optimistic).toBeUndefined();});+ it('does not send content or editorData when Page Agent editTitle follows initPage', async () => {+ const { result } = renderHook(() => useStore());+ const initializedEditorData = {+ root: {+ children: [{ children: [], type: 'paragraph', version: 1 }],+ type: 'root',+ version: 1,+ },+ };++ vi.mocked(documentService.updateDocument).mockResolvedValue({+ historyAppended: false,+ id: 'doc-1',+ });++ act(() => {+ useStore.setState(+ {+ documents: [+ createDocumentFixture({+ content: '',+ editorData: {},+ }),+ ],+ },+ false,+ );+ });++ await act(async () => {+ await result.current.updateDocumentOptimistically('doc-1', {+ content: 'Body written by page agent.',+ editorData: initializedEditorData,+ });+ });++ await act(async () => {+ await result.current.updateDocumentOptimistically('doc-1', {+ metadata: { emoji: 'page' },+ title: 'Final title',+ });+ });++ expect(documentService.updateDocument).toHaveBeenNthCalledWith(1, {+ content: 'Body written by page agent.',+ editorData: JSON.stringify(initializedEditorData),+ id: 'doc-1',+ metadata: {},+ parentId: undefined,+ title: 'Old title',+ });+ expect(documentService.updateDocument).toHaveBeenNthCalledWith(2, {+ id: 'doc-1',+ metadata: { emoji: 'page' },+ parentId: undefined,+ title: 'Final title',+ });+ });+it('reverts optimistic resource updates when the sync fails', async () => {const { result } = renderHook(() => useStore());const existingDocument = createDocumentFixture();diff --git a/src/store/file/slices/document/action.ts b/src/store/file/slices/document/action.tsindex b81585f9ca9..ca51459fbe2 100644--- a/src/store/file/slices/document/action.ts+++ b/src/store/file/slices/document/action.ts@@ -683,15 +683,19 @@ export class DocumentActionImpl {// Queue background sync to DBtry {await documentService.updateDocument({- content: updatedPage.content || '',- editorData:- typeof updatedPage.editorData === 'string'- ? updatedPage.editorData- : JSON.stringify(updatedPage.editorData || {}),id: documentId,metadata: updatedPage.metadata || {},parentId: updatedPage.parentId !== undefined ? updatedPage.parentId : undefined,title: updatedPage.title || updatedPage.filename,+ ...(updates.content === undefined ? {} : { content: updatedPage.content ?? '' }),+ ...(updates.editorData === undefined+ ? {}+ : {+ editorData:+ typeof updatedPage.editorData === 'string'+ ? updatedPage.editorData+ : JSON.stringify(updatedPage.editorData || {}),+ }),});if (existingResource) {this.#syncResourceItem(this.#createResourceItem(updatedPage, existingResource));diff --git a/src/store/page/slices/crud/action.ts b/src/store/page/slices/crud/action.tsindex ce095dd59c9..49890781160 100644--- a/src/store/page/slices/crud/action.ts+++ b/src/store/page/slices/crud/action.ts@@ -326,11 +326,6 @@ export class CrudActionImpl {// Queue background sync to DBtry {await documentService.updateDocument({- content: updatedPage.content || '',- editorData:- typeof updatedPage.editorData === 'string'- ? updatedPage.editorData- : JSON.stringify(updatedPage.editorData || {}),id: pageId,metadata: updatedPage.metadata || {},parentId: updatedPage.parentId || undefined,diff --git a/vite.config.ts b/vite.config.tsindex eb83f70663f..8259f2bf15e 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -109,7 +109,7 @@ export default defineConfig({},define: sharedRendererDefine({ isMobile, isElectron: false }),experimental: {- bundledDev: true,+ bundledDev: false,},resolve: {tsconfigPaths: true,