🤯 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: restore composer only when cancelling an unaccepted send (#19674)
Arvin Xu5fe21123b801
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.tsindex fbe9b7acc2f..001c3e6221e 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts@@ -243,6 +243,41 @@ describe('ConversationControl actions', () => {expect(mockSetJSONState).toHaveBeenCalledWith(editorState);});+ it('does not restore a completed send or an older cancelled draft', () => {+ const context = { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID };+ const editor = { setJSONState: vi.fn() };+ const store = useChatStore.getState();+ const older = store.startOperation({ context, type: 'sendMessage' });+ store.updateOperationMetadata(older.operationId, {+ inputEditorTempState: { content: 'older cancelled draft' },+ });+ store.cancelOperation(older.operationId);+ const latest = store.startOperation({ context, type: 'sendMessage' });+ store.updateOperationMetadata(latest.operationId, {+ inputEditorTempState: { content: 'already sent' },+ });+ store.completeOperation(latest.operationId);++ store.cancelSendMessageInServer(context, editor as any);++ expect(editor.setJSONState).not.toHaveBeenCalled();+ });++ it('restores a pending send only once after stop has cancelled operations', () => {+ const context = { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID };+ const editor = { setJSONState: vi.fn() };+ const store = useChatStore.getState();+ const { operationId } = store.startOperation({ context, type: 'sendMessage' });+ const snapshot = { content: 'still sending' };+ store.updateOperationMetadata(operationId, { inputEditorTempState: snapshot });+ store.cancelOperation(operationId);++ store.cancelSendMessageInServer(context, editor as any);+ store.cancelSendMessageInServer(context, editor as any);++ expect(editor.setJSONState).toHaveBeenCalledExactlyOnceWith(snapshot);+ });+it('should cancel operation for specified topic ID', () => {const { result } = renderHook(() => useChatStore());const customTopicId = 'custom-topic-id';diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.tsindex 7abad999068..8a68056cb27 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts@@ -3,6 +3,7 @@ import { act, renderHook, waitFor } from '@testing-library/react';import { TRPCClientError } from '@trpc/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { getDraft, removeDraft } from '@/features/ChatInput/draftStorage';import { agentService } from '@/services/agent';import { aiAgentService } from '@/services/aiAgent';import { aiChatService } from '@/services/aiChat';@@ -507,6 +508,83 @@ describe('ConversationLifecycle actions', () => {expect(sendMessageOperation?.metadata.inputSendErrorMsg).toBeTruthy();});+ it.each(['unchanged', 'edited', 'cleared'] as const)(+ 'preserves the %s live draft when a cancelled first send rolls back asynchronously',+ async (change) => {+ const context = createTestContext();+ const draftKey = messageMapKey(context);+ const snapshot = {+ root: { children: [{ text: 'Cancelled first message' }], type: 'root' },+ };+ const latestDraft = {+ root: {+ children:+ change === 'cleared' ? [] : [{ text: 'Cancelled first message with edits' }],+ type: 'root',+ },+ };+ let editorState = snapshot;+ const editor = {+ getJSONState: vi.fn(() => editorState),+ setJSONState: vi.fn((state) => {+ editorState = state;+ }),+ };+ removeDraft(draftKey);+ const executeGatewayAgent = vi.fn().mockImplementation(async (params) => {+ const store = useChatStore.getState();+ store.cancelOperation(params.parentOperationId);+ store.cancelSendMessageInServer(params.messageContext, editor as any);+ expect(editorState).toEqual(snapshot);+ // User edits after restoration, before the aborted request unwinds.+ await Promise.resolve();+ if (change !== 'unchanged') editorState = latestDraft;+ throw new DOMException('Stopped before dispatch', 'AbortError');+ });+ useChatStore.setState({ executeGatewayAgent, isGatewayModeEnabled: () => true });++ await useChatStore.getState().sendMessage({+ context,+ editorData: snapshot as any,+ inputEditor: editor as any,+ message: 'Cancelled first message',+ });++ expect(executeGatewayAgent).toHaveBeenCalledOnce();+ expect(getDraft(draftKey)).toEqual(change === 'unchanged' ? snapshot : latestDraft);+ removeDraft(draftKey);+ },+ );++ it('does not restore an accepted gateway message when stopped during setup', async () => {+ const context = { ...createTestContext(), topicId: TEST_IDS.TOPIC_ID };+ const setJSONState = vi.fn();+ const editor = {+ getJSONState: vi.fn().mockReturnValue({ content: 'already sent' }),+ setDocument: vi.fn(),+ setJSONState,+ };+ const executeGatewayAgent = vi.fn().mockImplementation(async (params) => {+ params.onMessageAccepted();+ useChatStore.getState().cancelSendMessageInServer(context, editor as any);+ throw new DOMException('Stopped', 'AbortError');+ });+ useChatStore.setState({+ executeGatewayAgent,+ isGatewayModeEnabled: () => true,+ mainInputEditor: editor as any,+ });++ await useChatStore.getState().sendMessage({+ context,+ editorData: { content: 'already sent' } as any,+ message: 'already sent',+ });++ expect(executeGatewayAgent).toHaveBeenCalledOnce();+ expect(setJSONState).not.toHaveBeenCalled();+ });+it('should not restore the composer when gateway setup fails after message acceptance', async () => {const { result } = renderHook(() => useChatStore());const setDocument = vi.fn();diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.tsindex e73831193ab..6bdb0e20bb5 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts@@ -491,13 +491,16 @@ export class ConversationControlActionImpl {const targetEditor =editor ?? (contextKey === messageMapKey(activeContext) ? this.#get().mainInputEditor : null);if (targetEditor) {- // Find the latest sendMessage operation with editor state- for (const opId of [...operationIds].reverse()) {- const op = this.#get().operations[opId];- if (op && op.type === 'sendMessage' && op.metadata.inputEditorTempState) {- targetEditor.setJSONState(op.metadata.inputEditorTempState);- break;- }+ // Only the latest send can own the draft. Never fall back to a stale+ // snapshot from an earlier turn when stopping an accepted message.+ const operationId = [...operationIds]+ .reverse()+ .find((id) => this.#get().operations[id]?.type === 'sendMessage');+ const operation = operationId ? this.#get().operations[operationId] : undefined;+ if (operation?.status === 'cancelled' && operation.metadata.inputEditorTempState) {+ const snapshot = operation.metadata.inputEditorTempState;+ this.#get().updateOperationMetadata(operation.id, { inputEditorTempState: null });+ targetEditor.setJSONState(snapshot);}}};diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex 335a4aca732..301e00b397e 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -27,6 +27,7 @@ import { toast } from '@lobehub/ui/base-ui';import { t } from 'i18next';import { type ChatInputEditor } from '@/features/ChatInput';+import { saveDraft } from '@/features/ChatInput/draftStorage';import {ensureAgentManagementAccess,getRuntimeCanManageAgent,@@ -335,6 +336,7 @@ export class ConversationLifecycleActionImpl {let detachCallerAbort = () => {};let hasNotifiedMessageAccepted = false;+ let sendOperationId: string | undefined = undefined;const detachUnacceptedCallerAbort = () => {if (!hasNotifiedMessageAccepted) detachCallerAbort();};@@ -342,6 +344,11 @@ export class ConversationLifecycleActionImpl {if (hasNotifiedMessageAccepted) return;hasNotifiedMessageAccepted = true;+ // Queued messages are accepted before a send operation exists. For actual+ // sends, acceptance ends the optimistic phase for every runtime.+ if (sendOperationId) {+ this.#get().updateOperationMetadata(sendOperationId, { inputEditorTempState: null });+ }detachCallerAbort();try {onMessageAccepted?.();@@ -860,6 +867,7 @@ export class ConversationLifecycleActionImpl {inThread: !!operationContext.threadId,},});+ sendOperationId = operationId;// Voice recording starts before a first-send topic exists, so its upload// transaction and local row initially live in the legacy `_new` bucket.// Adopt the client-minted topic context before looking up that row; otherwise@@ -1301,6 +1309,19 @@ export class ConversationLifecycleActionImpl {messageMapKey({ ...operationContext, topicId: null }),);if (this.#get().activeTopicId === optimisticTopic.id) {+ // Cancelling restores the editor before the optimistic topic rolls back.+ // Read the live editor: the user may have edited or cleared the restored draft+ // while the cancelled request was unwinding. Preserve it across the topic switch.+ if (+ !hasNotifiedMessageAccepted &&+ this.#get().operations[operationId]?.status === 'cancelled' &&+ jsonState+ ) {+ saveDraft(+ messageMapKey({ ...operationContext, topicId: null }),+ targetInputEditor?.getJSONState() ?? jsonState,+ );+ }void this.#get().switchTopic(null, { skipRefreshMessage: true });}this.#get().internal_dispatchTopic(@@ -1531,13 +1552,6 @@ export class ConversationLifecycleActionImpl {this.#get().completeOperation(operationId);notifyMessagePersisted();- // Clear editor temp state — the user's message is already persisted, so- // a later Stop click must NOT restore it into the input (would feel like- // the app re-sent the message). Client/Gateway paths clear this at- // line 684-686 after `sendMessageInServer` resolves, but the hetero- // branch returns early (line 498) and never reaches that clear.- this.#get().updateOperationMetadata(operationId, { inputEditorTempState: null });-if (abortController.signal.aborted) {return {assistantMessageId: heteroData.assistantMessageId,@@ -2054,11 +2068,6 @@ export class ConversationLifecycleActionImpl {});}- // Clear editor temp state after message created- if (data) {- this.#get().updateOperationMetadata(operationId, { inputEditorTempState: null });- }-if (!data) {detachUnacceptedCallerAbort();rollbackOptimisticTopic('sendMessage/rollbackOptimisticTopic');