🤯 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(chat-input): stop serializing a composer that is being torn down (#19425)
Inneid2f17fe2bf91
diff --git a/package.json b/package.jsonindex ccca056ed1b..1719b340754 100644--- a/package.json+++ b/package.json@@ -311,7 +311,7 @@"@lobehub/analytics": "^1.6.4","@lobehub/charts": "^5.4.0","@lobehub/desktop-ipc-typings": "workspace:*",- "@lobehub/editor": "^4.27.0",+ "@lobehub/editor": "^4.27.3","@lobehub/icons": "^5.18.0","@lobehub/market-sdk": "0.41.0","@lobehub/tts": "^5.1.2",diff --git a/src/features/ChatInput/editorDocument.ts b/src/features/ChatInput/editorDocument.tsnew file mode 100644index 00000000000..4dd013edc0c--- /dev/null+++ b/src/features/ChatInput/editorDocument.ts@@ -0,0 +1,30 @@+import type { IEditor } from '@lobehub/editor';++// A kernel registers its data sources when its root mounts and drops them again+// on destroy, so a debounced handler landing mid route switch can reach one that+// can no longer serialize. Callers must skip their work instead of reading the+// failure as an empty composer — persisting that emptiness deletes the draft.+export const canSerialize = (editor?: IEditor) => !!editor?.getLexicalEditor();++export const readDocument = (editor: IEditor | undefined, type: string): unknown => {+ if (!canSerialize(editor)) return undefined;+ try {+ return editor!.getDocument(type);+ } catch {+ return undefined;+ }+};++export const writeDocument = (+ editor: IEditor | undefined,+ type: string,+ content: any,+ options?: Record<string, unknown>,+) => {+ if (!canSerialize(editor)) return;+ try {+ editor!.setDocument(type, content, options);+ } catch {+ /* the composer this content belongs to went away mid write */+ }+};diff --git a/src/features/ChatInput/hooks/useChatInputDraft.test.tsx b/src/features/ChatInput/hooks/useChatInputDraft.test.tsxindex d0f2f6d0743..3c4720cf029 100644--- a/src/features/ChatInput/hooks/useChatInputDraft.test.tsx+++ b/src/features/ChatInput/hooks/useChatInputDraft.test.tsx@@ -15,6 +15,7 @@ const createFakeEditor = () => {json = undefined;}),focus: vi.fn(),+ getLexicalEditor: () => ({}),getDocument: vi.fn((type: string) =>type === 'markdown' ? ((json?.text as string) ?? '') : json,),@@ -38,9 +39,38 @@ describe('useChatInputDraft', () => {vi.restoreAllMocks();});+ it('keeps a saved draft when the composer can no longer serialize', () => {+ const draftJson = { root: { children: [{ text: 'typed before the switch' }] } };+ saveDraft('main_agt_a_tpc_1', draftJson);+ // the kernel lost its data sources with the composer it belonged to+ const tornDown = {+ cleanDocument: () => {+ throw new Error('DataSource for type "text" is not registered.');+ },+ focus: vi.fn(),+ getDocument: () => {+ throw new Error('DataSource for type "markdown" is not registered.');+ },+ getLexicalEditor: () => null,+ } as unknown as IEditor;+ const store = createStore({ draftKey: 'main_agt_a_tpc_1', editor: tornDown });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <Provider createStore={() => store}>{children}</Provider>+ );++ renderHook(() => useChatInputDraft(), { wrapper });++ act(() => {+ store.setState({ draftKey: 'main_agt_b_tpc_2' });+ });++ expect(getDraft('main_agt_a_tpc_1')).toEqual(draftJson);+ });+it('flushes the pending debounced draft save on unmount', () => {const draftJson = { root: { children: [{ text: 'latest edit' }] } };const editor = {+ getLexicalEditor: () => ({}),getDocument: vi.fn((type: string) => (type === 'markdown' ? 'latest edit' : draftJson)),} as unknown as IEditor;const store = createStore({ draftKey: 'main_agent_topic', editor });@@ -170,6 +200,7 @@ describe('useChatInputDraft', () => {const draftJson = { root: { children: [{ text: 'draft' }] } };const setDocument = vi.fn();const editor = {+ getLexicalEditor: () => ({}),getDocument: vi.fn(),isEmpty: true,setDocument,@@ -186,7 +217,7 @@ describe('useChatInputDraft', () => {result.current.restoreDraft(editor);});- expect(setDocument).toHaveBeenCalledWith('json', draftJson);+ expect(setDocument).toHaveBeenCalledWith('json', draftJson, undefined);});it('saves the old draft, clears the editor and restores the new draft on draftKey change', () => {@@ -200,6 +231,7 @@ describe('useChatInputDraft', () => {empty = true;}),focus: vi.fn(),+ getLexicalEditor: () => ({}),getDocument: vi.fn((type: string) => (type === 'markdown' ? markdown : oldJson)),get isEmpty() {return empty;@@ -221,7 +253,7 @@ describe('useChatInputDraft', () => {expect(getDraft('main_agt_a_tpc_1')).toEqual(oldJson);expect(editor.cleanDocument).toHaveBeenCalledTimes(1);- expect(editor.setDocument).toHaveBeenCalledWith('json', newJson);+ expect(editor.setDocument).toHaveBeenCalledWith('json', newJson, undefined);act(() => {vi.runAllTimers();@@ -236,6 +268,7 @@ describe('useChatInputDraft', () => {const editor = {cleanDocument: vi.fn(),focus,+ getLexicalEditor: () => ({}),getDocument: vi.fn((type: string) => (type === 'markdown' ? '' : undefined)),isEmpty: true,setDocument: vi.fn(),@@ -261,6 +294,7 @@ describe('useChatInputDraft', () => {const editor = {cleanDocument: vi.fn(),focus,+ getLexicalEditor: () => ({}),getDocument: vi.fn((type: string) => (type === 'markdown' ? '' : undefined)),isEmpty: true,setDocument: vi.fn(),@@ -343,6 +377,7 @@ describe('useChatInputDraft', () => {it('does not overwrite current editor input when restoring a draft', () => {const setDocument = vi.fn();const editor = {+ getLexicalEditor: () => ({}),getDocument: vi.fn(),isEmpty: false,setDocument,diff --git a/src/features/ChatInput/hooks/useChatInputDraft.ts b/src/features/ChatInput/hooks/useChatInputDraft.tsindex d0f8452db37..8132d22d617 100644--- a/src/features/ChatInput/hooks/useChatInputDraft.ts+++ b/src/features/ChatInput/hooks/useChatInputDraft.ts@@ -3,6 +3,7 @@ import { debounce } from 'es-toolkit/compat';import { useCallback, useEffect, useMemo, useRef } from 'react';import { getDraftEntry, removeDraftIfUnchanged, saveDraft } from '../draftStorage';+import { canSerialize, writeDocument } from '../editorDocument';import { useStoreApi } from '../store';const SAVE_DEBOUNCE_MS = 500;@@ -19,7 +20,9 @@ export const useChatInputDraft = () => {const persistDraftFor = useCallback((draftKey: string, removeEmpty = true) => {const { editor, getMarkdownContent, getJSONState } = storeApi.getState();- if (!editor) return;+ // A composer that can no longer serialize reads as empty, and an empty read+ // under a key transition removes the draft the user actually typed.+ if (!canSerialize(editor)) return;if (getMarkdownContent().trim().length === 0) {const loadedDraft = loadedDraftRef.current;@@ -69,12 +72,14 @@ export const useChatInputDraft = () => {const { draftKey } = storeApi.getState();if (!draftKey) return;+ if (!canSerialize(editor)) return;+const draft = getDraftEntry(draftKey);loadedDraftRef.current = { draftKey, updatedAt: draft?.updatedAt };if (!editor.isEmpty) return;- if (draft) editor.setDocument('json', draft.json);+ if (draft) writeDocument(editor, 'json', draft.json);},[storeApi],);@@ -94,10 +99,10 @@ export const useChatInputDraft = () => {if (prevState.draftKey) persistDraftFor(prevState.draftKey);const { editor } = state;- if (!editor) return;- editor.cleanDocument();- restoreDraft(editor);- if (!state.mobile) editor.focus();+ if (!canSerialize(editor)) return;+ editor!.cleanDocument();+ restoreDraft(editor!);+ if (!state.mobile) editor!.focus();}),[persistDraftFor, restoreDraft, saveDraftDebounced, storeApi],);diff --git a/src/features/ChatInput/store/action.test.ts b/src/features/ChatInput/store/action.test.tsindex c264e3bfe21..7b0df93012b 100644--- a/src/features/ChatInput/store/action.test.ts+++ b/src/features/ChatInput/store/action.test.ts@@ -42,6 +42,7 @@ describe('ChatInput store actions', () => {const editor = {cleanDocument: vi.fn(),focus: vi.fn(),+ getLexicalEditor: () => ({}),getDocument: vi.fn((type: string) => (type === 'markdown' ? 'Hello' : editorData)),};const store = createStore({@@ -64,6 +65,7 @@ describe('ChatInput store actions', () => {const editor = {cleanDocument: vi.fn(),focus: vi.fn(),+ getLexicalEditor: () => ({}),getDocument: vi.fn((type: string) => (type === 'markdown' ? 'Hello' : { text: 'Hello' })),};saveDraft('main_agt_a_tpc_1', { text: 'Hello' });@@ -84,6 +86,7 @@ describe('ChatInput store actions', () => {const editor = {cleanDocument: vi.fn(),focus: vi.fn(),+ getLexicalEditor: () => ({}),getDocument: vi.fn((type: string) => (type === 'markdown' ? 'Hello' : { text: 'Hello' })),};saveDraft('main_agt_a_tpc_1', { text: 'Hello' });@@ -107,6 +110,7 @@ describe('ChatInput store actions', () => {const editor = {cleanDocument: vi.fn(),focus: vi.fn(),+ getLexicalEditor: () => ({}),getDocument: vi.fn((type: string) => (type === 'markdown' ? 'Hello' : editorData)),};const store = createStore({@@ -133,6 +137,7 @@ describe('ChatInput store actions', () => {const editor = {cleanDocument: vi.fn(),focus: vi.fn(),+ getLexicalEditor: () => ({}),getDocument: vi.fn((type: string) =>type === 'markdown' ? '/goal Ship the homepage' : { root: {} },),@@ -152,6 +157,7 @@ describe('ChatInput store actions', () => {const editor = {cleanDocument: vi.fn(),focus: vi.fn(),+ getLexicalEditor: () => ({}),getDocument: vi.fn((type: string) => (type === 'markdown' ? 'Hello' : { root: {} })),};const store = createStore({@@ -174,6 +180,7 @@ describe('ChatInput store actions', () => {cleanDocument: vi.fn(),dispatchCommand,focus: vi.fn(),+ getLexicalEditor: () => ({}),getDocument: vi.fn((type: string) => (type === 'markdown' ? 'Hello' : { root: {} })),};const store = createStore({@@ -192,6 +199,7 @@ describe('ChatInput store actions', () => {cleanDocument: vi.fn(),dispatchCommand,focus: vi.fn(),+ getLexicalEditor: () => ({}),getDocument: vi.fn((type: string) => (type === 'markdown' ? 'Hello' : { root: {} })),};const store = createStore({@@ -212,6 +220,7 @@ describe('ChatInput store actions', () => {const editor = {cleanDocument: vi.fn(),focus: vi.fn(),+ getLexicalEditor: () => ({}),getDocument: vi.fn((type: string) => (type === 'markdown' ? 'Hello' : { root: {} })),};const store = createStore({@@ -231,6 +240,7 @@ describe('ChatInput store actions', () => {const editor = {cleanDocument: vi.fn(),focus: vi.fn(),+ getLexicalEditor: () => ({}),getDocument: vi.fn((type: string) => (type === 'markdown' ? 'Hello' : { root: {} })),};const store = createStore({@@ -250,6 +260,7 @@ describe('ChatInput store actions', () => {const editor = {cleanDocument: vi.fn(),focus: vi.fn(),+ getLexicalEditor: () => ({}),getDocument: vi.fn((type: string) => (type === 'markdown' ? 'Hello' : { root: {} })),};const store = createStore({@@ -267,6 +278,7 @@ describe('ChatInput store actions', () => {const editor = {cleanDocument: vi.fn(),focus: vi.fn(),+ getLexicalEditor: () => ({}),getDocument: vi.fn((type: string) => (type === 'markdown' ? 'Hello' : { root: {} })),};const store = createStore({diff --git a/src/features/ChatInput/store/action.ts b/src/features/ChatInput/store/action.tsindex c5081bb7908..6171bce08fc 100644--- a/src/features/ChatInput/store/action.ts+++ b/src/features/ChatInput/store/action.ts@@ -6,6 +6,7 @@ import { useUserStore } from '@/store/user';import { systemAgentSelectors, userProfileSelectors } from '@/store/user/selectors';import { removeDraft } from '../draftStorage';+import { readDocument, writeDocument } from '../editorDocument';import { addInputHistory } from '../inputHistoryStorage';import { type PublicState, type State } from './initialState';import { initialState } from './initialState';@@ -53,10 +54,10 @@ export const store: CreateStore = (publicState) => (set, get) => ({},getJSONState: () => {- return get().editor?.getDocument('json') as Record<string, any> | undefined;+ return readDocument(get().editor, 'json') as Record<string, any> | undefined;},getMarkdownContent: () => {- return String(get().editor?.getDocument('markdown') || '').trimEnd();+ return String(readDocument(get().editor, 'markdown') || '').trimEnd();},handleSendButton: () => {const editor = get().editor;@@ -133,17 +134,17 @@ export const store: CreateStore = (publicState) => (set, get) => ({},setDocument: (type, content, options) => {- get().editor?.setDocument(type, content, options);+ writeDocument(get().editor, type, content, options);},setExpand: (expand) => {const editor = get().editor;- const _savedEditorState = editor?.getDocument('json') as Record<string, any> | undefined;+ const _savedEditorState = readDocument(editor, 'json') as Record<string, any> | undefined;set({ _savedEditorState, expand });},setJSONState: (content) => {- get().editor?.setDocument('json', content);+ writeDocument(get().editor, 'json', content);},setShowTypoBar: (showTypoBar) => {