🤯 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 deleting unsent composer drafts (#18097)
Inneic0a4f1bf1cd5
diff --git a/src/features/ChatInput/draftStorage.ts b/src/features/ChatInput/draftStorage.tsindex e968911fd10..4ed55a03886 100644--- a/src/features/ChatInput/draftStorage.ts+++ b/src/features/ChatInput/draftStorage.ts@@ -100,16 +100,20 @@ export const useHasDraft = (key: string | undefined): boolean =>() => false,);-export const getDraft = (key: string): Record<string, unknown> | undefined => {+export const getDraftEntry = (key: string): ChatInputDraftEntry | undefined => {if (!key) return undefined;- return readAll()[key]?.json;+ return readAll()[key];};-export const saveDraft = (key: string, json: Record<string, unknown>): void => {+export const getDraft = (key: string): Record<string, unknown> | undefined =>+ getDraftEntry(key)?.json;++export const saveDraft = (key: string, json: Record<string, unknown>): number | undefined => {if (!key) return;const map = readAll();- map[key] = { json, updatedAt: Date.now() };+ const updatedAt = Math.max(Date.now(), (map[key]?.updatedAt ?? 0) + 1);+ map[key] = { json, updatedAt };const keys = Object.keys(map);if (keys.length > MAX_DRAFTS) {@@ -121,8 +125,9 @@ export const saveDraft = (key: string, json: Record<string, unknown>): void => {});}- writeAll(map);+ if (!writeAll(map)) return;syncDraftKeys(map);+ return updatedAt;};export const removeDraft = (key: string): void => {@@ -135,3 +140,20 @@ export const removeDraft = (key: string): void => {writeAll(map);syncDraftKeys(map);};++export const removeDraftIfUnchanged = (+ key: string,+ expectedUpdatedAt: number | undefined,+): boolean => {+ if (!key) return false;++ const map = readAll();+ const entry = map[key];+ if (entry?.updatedAt !== expectedUpdatedAt) return false;+ if (!entry) return true;++ delete map[key];+ if (!writeAll(map)) return false;+ syncDraftKeys(map);+ return true;+};diff --git a/src/features/ChatInput/hooks/useChatInputDraft.test.tsx b/src/features/ChatInput/hooks/useChatInputDraft.test.tsxindex 9244f8b0362..d0f2f6d0743 100644--- a/src/features/ChatInput/hooks/useChatInputDraft.test.tsx+++ b/src/features/ChatInput/hooks/useChatInputDraft.test.tsx@@ -7,6 +7,26 @@ import { getDraft, saveDraft } from '../draftStorage';import { createStore, Provider } from '../store';import { useChatInputDraft } from './useChatInputDraft';+const createFakeEditor = () => {+ let json: Record<string, unknown> | undefined;++ return {+ cleanDocument: vi.fn(() => {+ json = undefined;+ }),+ focus: vi.fn(),+ getDocument: vi.fn((type: string) =>+ type === 'markdown' ? ((json?.text as string) ?? '') : json,+ ),+ get isEmpty() {+ return !json?.text;+ },+ setDocument: vi.fn((_type: string, content: Record<string, unknown>) => {+ json = content;+ }),+ } as unknown as IEditor;+};+describe('useChatInputDraft', () => {beforeEach(() => {vi.useFakeTimers();@@ -41,6 +61,111 @@ describe('useChatInputDraft', () => {expect(getDraft('main_agent_topic')).toEqual(draftJson);});+ it('persists live editor content on unmount when no save is pending yet', () => {+ const editor = createFakeEditor();+ const store = createStore({ draftKey: 'main_agt_a_tpc_1', editor });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <Provider createStore={() => store}>{children}</Provider>+ );++ const { result, unmount } = renderHook(() => useChatInputDraft(), { wrapper });++ act(() => {+ result.current.restoreDraft(editor);+ // the editor's own change notification is debounced, so text typed right+ // before the composer unmounts has not scheduled a save yet+ editor.setDocument('json', { text: 'typed right before leaving' });+ });++ unmount();++ expect(getDraft('main_agt_a_tpc_1')).toEqual({ text: 'typed right before leaving' });+ });++ it('restores input the previous composer instance persisted on unmount', () => {+ const editor = createFakeEditor();+ const store = createStore({ draftKey: 'main_agt_a_tpc_1', editor });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <Provider createStore={() => store}>{children}</Provider>+ );++ const first = renderHook(() => useChatInputDraft(), { wrapper });+ act(() => {+ first.result.current.restoreDraft(editor);+ editor.setDocument('json', { text: 'typed a moment before remount' });+ });+ first.unmount();++ // remounting the composer re-seeds the editor from the empty `content`+ // prop, so the text can only come back through the stored draft+ editor.cleanDocument();++ const second = renderHook(() => useChatInputDraft(), { wrapper });+ act(() => {+ second.result.current.restoreDraft(editor);+ });++ expect(editor.getDocument('markdown')).toBe('typed a moment before remount');+ });++ it('keeps a newer draft when an empty composer flushes a pending save on unmount', () => {+ const draftKey = 'main_agt_a_tpc_shared';+ const emptyEditor = createFakeEditor();+ const writerEditor = createFakeEditor();+ const emptyStore = createStore({ draftKey, editor: emptyEditor });+ const writerStore = createStore({ draftKey, editor: writerEditor });+ const emptyWrapper = ({ children }: { children: ReactNode }) => (+ <Provider createStore={() => emptyStore}>{children}</Provider>+ );+ const writerWrapper = ({ children }: { children: ReactNode }) => (+ <Provider createStore={() => writerStore}>{children}</Provider>+ );++ const emptyComposer = renderHook(() => useChatInputDraft(), { wrapper: emptyWrapper });+ const writerComposer = renderHook(() => useChatInputDraft(), { wrapper: writerWrapper });++ act(() => {+ emptyComposer.result.current.restoreDraft(emptyEditor);+ writerComposer.result.current.restoreDraft(writerEditor);+ emptyComposer.result.current.saveDraftDebounced();+ writerEditor.setDocument('json', { text: 'draft from the other tab' });+ writerComposer.result.current.saveDraftDebounced();+ writerComposer.result.current.saveDraftDebounced.flush();+ });++ expect(getDraft(draftKey)).toEqual({ text: 'draft from the other tab' });++ emptyComposer.unmount();++ expect(getDraft(draftKey)).toEqual({ text: 'draft from the other tab' });++ writerComposer.unmount();+ });++ it('removes its unchanged draft when flushing a pending clear on unmount', () => {+ const draftKey = 'main_agt_a_tpc_owned';+ const editor = createFakeEditor();+ const store = createStore({ draftKey, editor });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <Provider createStore={() => store}>{children}</Provider>+ );+ saveDraft(draftKey, { text: 'draft to clear' });++ const { result, unmount } = renderHook(() => useChatInputDraft(), { wrapper });++ act(() => {+ result.current.restoreDraft(editor);+ editor.cleanDocument();+ result.current.saveDraftDebounced();+ });++ expect(getDraft(draftKey)).toEqual({ text: 'draft to clear' });++ unmount();++ expect(getDraft(draftKey)).toBeUndefined();+ });+it('restores a draft when the editor is empty', () => {const draftJson = { root: { children: [{ text: 'draft' }] } };const setDocument = vi.fn();@@ -155,20 +280,19 @@ describe('useChatInputDraft', () => {});it('removes the old draft when leaving with an emptied editor', () => {- const editor = {- cleanDocument: vi.fn(),- focus: vi.fn(),- getDocument: vi.fn((type: string) => (type === 'markdown' ? '' : undefined)),- isEmpty: true,- setDocument: vi.fn(),- } as unknown as IEditor;+ const editor = createFakeEditor();const store = createStore({ draftKey: 'main_agt_a_tpc_1', editor });const wrapper = ({ children }: { children: ReactNode }) => (<Provider createStore={() => store}>{children}</Provider>);- saveDraft('main_agt_a_tpc_1', { root: { children: [{ text: 'stale' }] } });+ saveDraft('main_agt_a_tpc_1', { text: 'stale' });- renderHook(() => useChatInputDraft(), { wrapper });+ const { result } = renderHook(() => useChatInputDraft(), { wrapper });++ act(() => {+ result.current.restoreDraft(editor);+ editor.cleanDocument();+ });act(() => {store.setState({ draftKey: 'main_agt_a_tpc_2' });@@ -177,6 +301,45 @@ describe('useChatInputDraft', () => {expect(getDraft('main_agt_a_tpc_1')).toBeUndefined();});+ it('keeps a draft the editor has not loaded yet when the draft key changes', () => {+ const editor = createFakeEditor();+ const store = createStore({ draftKey: 'main_agt_a_tpc_1', editor });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <Provider createStore={() => store}>{children}</Provider>+ );+ saveDraft('main_agt_a_tpc_1', { text: 'unsent draft' });++ // no restoreDraft: mirrors the window between mount and the restore frame,+ // where the editor is empty simply because nothing loaded it yet+ renderHook(() => useChatInputDraft(), { wrapper });++ act(() => {+ store.setState({ draftKey: 'main_agt_a_tpc_2' });+ });++ expect(getDraft('main_agt_a_tpc_1')).toEqual({ text: 'unsent draft' });+ });++ it('keeps a draft the editor has not loaded yet when the debounced save runs', () => {+ const editor = createFakeEditor();+ const store = createStore({ draftKey: 'main_agt_a_tpc_1', editor });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <Provider createStore={() => store}>{children}</Provider>+ );+ saveDraft('main_agt_a_tpc_1', { text: 'unsent draft' });++ const { result } = renderHook(() => useChatInputDraft(), { wrapper });++ // the editor reports every commit, selection-only ones included, so a save+ // can be scheduled before the restore frame lands+ act(() => {+ result.current.saveDraftDebounced();+ vi.runAllTimers();+ });++ expect(getDraft('main_agt_a_tpc_1')).toEqual({ text: 'unsent draft' });+ });+it('does not overwrite current editor input when restoring a draft', () => {const setDocument = vi.fn();const editor = {diff --git a/src/features/ChatInput/hooks/useChatInputDraft.ts b/src/features/ChatInput/hooks/useChatInputDraft.tsindex 24d8dbc510a..d0f8452db37 100644--- a/src/features/ChatInput/hooks/useChatInputDraft.ts+++ b/src/features/ChatInput/hooks/useChatInputDraft.ts@@ -1,27 +1,43 @@import type { IEditor } from '@lobehub/editor';import { debounce } from 'es-toolkit/compat';-import { useCallback, useEffect, useMemo } from 'react';+import { useCallback, useEffect, useMemo, useRef } from 'react';-import { getDraft, removeDraft, saveDraft } from '../draftStorage';+import { getDraftEntry, removeDraftIfUnchanged, saveDraft } from '../draftStorage';import { useStoreApi } from '../store';const SAVE_DEBOUNCE_MS = 500;export const useChatInputDraft = () => {const storeApi = useStoreApi();+ // The storage revision whose document the editor is currently carrying. An+ // empty editor may remove only that revision: before restore it owns none,+ // and after another composer writes the same key its revision is stale.+ const loadedDraftRef = useRef<{ draftKey: string; updatedAt: number | undefined } | undefined>(+ undefined,+ );const persistDraftFor = useCallback(- (draftKey: string) => {+ (draftKey: string, removeEmpty = true) => {const { editor, getMarkdownContent, getJSONState } = storeApi.getState();if (!editor) return;if (getMarkdownContent().trim().length === 0) {- removeDraft(draftKey);+ const loadedDraft = loadedDraftRef.current;+ if (+ removeEmpty &&+ loadedDraft?.draftKey === draftKey &&+ removeDraftIfUnchanged(draftKey, loadedDraft.updatedAt)+ ) {+ loadedDraftRef.current = { draftKey, updatedAt: undefined };+ }return;}const json = getJSONState();- if (json) saveDraft(draftKey, json);+ if (json) {+ const updatedAt = saveDraft(draftKey, json);+ if (updatedAt !== undefined) loadedDraftRef.current = { draftKey, updatedAt };+ }},[storeApi],);@@ -35,17 +51,30 @@ export const useChatInputDraft = () => {[persistDraftFor, storeApi],);- useEffect(() => () => saveDraftDebounced.flush(), [saveDraftDebounced]);+ // Flush locally scheduled work first so an intentional clear still removes+ // the revision this editor owns. Then save live non-empty content that may+ // not have reached the debounce yet. The unconditional pass must not remove+ // an empty draft: a different composer may have written the shared key.+ useEffect(+ () => () => {+ saveDraftDebounced.flush();+ const { draftKey } = storeApi.getState();+ if (draftKey) persistDraftFor(draftKey, false);+ },+ [persistDraftFor, saveDraftDebounced, storeApi],+ );const restoreDraft = useCallback((editor: IEditor) => {const { draftKey } = storeApi.getState();if (!draftKey) return;+ const draft = getDraftEntry(draftKey);+ loadedDraftRef.current = { draftKey, updatedAt: draft?.updatedAt };+if (!editor.isEmpty) return;- const draft = getDraft(draftKey);- if (draft) editor.setDocument('json', draft);+ if (draft) editor.setDocument('json', draft.json);},[storeApi],);diff --git a/src/features/ChatInput/store/action.test.ts b/src/features/ChatInput/store/action.test.tsindex c89b6a581b5..43740c822e7 100644--- a/src/features/ChatInput/store/action.test.ts+++ b/src/features/ChatInput/store/action.test.ts@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { useAgentStore } from '@/store/agent';import { systemAgentSelectors } from '@/store/user/selectors';+import { getDraft, saveDraft } from '../draftStorage';import { getInputHistory } from '../inputHistoryStorage';import { createStore, selectors } from '.';@@ -52,6 +53,46 @@ describe('ChatInput store actions', () => {});});+ it('drops the stored draft once the send handler clears the composer', () => {+ const editor = {+ cleanDocument: vi.fn(),+ focus: vi.fn(),+ getDocument: vi.fn((type: string) => (type === 'markdown' ? 'Hello' : { text: 'Hello' })),+ };+ saveDraft('main_agt_a_tpc_1', { text: 'Hello' });+ const store = createStore({+ draftKey: 'main_agt_a_tpc_1',+ editor: editor as unknown as IEditor,+ onSend: ({ clearContent }) => {+ clearContent();+ },+ });++ store.getState().handleSendButton();++ expect(getDraft('main_agt_a_tpc_1')).toBeUndefined();+ });++ it('keeps the stored draft when the send handler declines to clear the composer', () => {+ const editor = {+ cleanDocument: vi.fn(),+ focus: vi.fn(),+ getDocument: vi.fn((type: string) => (type === 'markdown' ? 'Hello' : { text: 'Hello' })),+ };+ saveDraft('main_agt_a_tpc_1', { text: 'Hello' });+ const store = createStore({+ draftKey: 'main_agt_a_tpc_1',+ editor: editor as unknown as IEditor,+ // a scheduled send that the server rejects leaves the text in the+ // composer, so the draft behind it must survive+ onSend: () => {},+ });++ store.getState().handleSendButton();++ expect(getDraft('main_agt_a_tpc_1')).toEqual({ text: 'Hello' });+ });+it('records sent input in the active agent history when no agent id is provided', () => {useAgentStore.setState({ activeAgentId: 'active-agent' });diff --git a/src/features/ChatInput/store/action.ts b/src/features/ChatInput/store/action.tsindex d930bae527a..61f363f3491 100644--- a/src/features/ChatInput/store/action.ts+++ b/src/features/ChatInput/store/action.ts@@ -86,9 +86,16 @@ export const store: CreateStore = (publicState) => (set, get) => ({}: undefined;+ // Tie the draft's fate to the composer actually being cleared: a host may+ // decline the send after the fact (a rejected scheduled send keeps the text+ // on screen), and the key is captured here because committing the send can+ // move the conversation to a freshly created topic.+ const sentDraftKey = get().draftKey;+onSend?.({clearContent: () => {editor?.cleanDocument();+ if (sentDraftKey) removeDraft(sentDraftKey);set({ goalMode: false });},editor: editor!,@@ -103,9 +110,6 @@ export const store: CreateStore = (publicState) => (set, get) => ({addInputHistory(historySnapshot);}- const { draftKey } = get();- if (draftKey) removeDraft(draftKey);-if (get().expand) {set({ _savedEditorState: undefined, expand: false });}