π OpenHands: AI-Driven Development
fix(chat): clear the saved draft of slash commands handled in the chat (#18553)
Engel Nystf452d9d78e93
diff --git a/.pr/modeldraft/after-model-list-composer-empty.png b/.pr/modeldraft/after-model-list-composer-empty.pngnew file mode 100644index 0000000000..a8ba3acb93Binary files /dev/null and b/.pr/modeldraft/after-model-list-composer-empty.png differdiff --git a/.pr/modeldraft/after-model-returned-empty.png b/.pr/modeldraft/after-model-returned-empty.pngnew file mode 100644index 0000000000..832044ac1bBinary files /dev/null and b/.pr/modeldraft/after-model-returned-empty.png differdiff --git a/.pr/modeldraft/after-new-returned-empty.png b/.pr/modeldraft/after-new-returned-empty.pngnew file mode 100644index 0000000000..5d37ac320aBinary files /dev/null and b/.pr/modeldraft/after-new-returned-empty.png differdiff --git a/.pr/modeldraft/before-model-revived.png b/.pr/modeldraft/before-model-revived.pngnew file mode 100644index 0000000000..432cbbe125Binary files /dev/null and b/.pr/modeldraft/before-model-revived.png differdiff --git a/.pr/modeldraft/before-new-revived.png b/.pr/modeldraft/before-new-revived.pngnew file mode 100644index 0000000000..ce8a3415a1Binary files /dev/null and b/.pr/modeldraft/before-new-revived.png differdiff --git a/__tests__/components/chat/chat-interface.test.tsx b/__tests__/components/chat/chat-interface.test.tsxindex 84b3806146..7e88bf1818 100644--- a/__tests__/components/chat/chat-interface.test.tsx+++ b/__tests__/components/chat/chat-interface.test.tsx@@ -1,6 +1,7 @@import { afterEach, beforeEach, describe, expect, it, test, vi } from "vitest";import {fireEvent,+ cleanup,render,screen,waitFor,@@ -32,6 +33,8 @@ import { AgentState } from "#/types/agent-state";import { useConversationStore } from "#/stores/conversation-store";import { useGoalStore } from "#/stores/goal-store";import { act } from "@testing-library/react";+import ProfilesService from "#/api/profiles-service/profiles-service.api";+import { getConversationState } from "#/utils/conversation-local-storage";const mockSend = vi.fn();vi.mock("#/hooks/use-send-message", () => ({@@ -784,6 +787,94 @@ describe("ChatInterface - Pending message queue", () => {});});+describe("ChatInterface - Saved draft after submit", () => {+ const CONVERSATION_ID = "test-conversation-id";+ let listProfilesSpy: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ // jsdom has no innerText, which the composer reads its text from.+ Object.defineProperty(HTMLElement.prototype, "innerText", {+ configurable: true,+ get(this: HTMLElement) {+ return this.textContent ?? "";+ },+ });+ mockSend.mockReset();+ mockSend.mockResolvedValue({ queued: false });+ localStorage.clear();+ useOptimisticUserMessageStore.getState().clearPendingMessages();+ (useConfig as unknown as ReturnType<typeof vi.fn>).mockReturnValue({+ data: {},+ });+ (+ useUnifiedUploadFiles as unknown as ReturnType<typeof vi.fn>+ ).mockReturnValue({ mutateAsync: vi.fn(), isLoading: false });+ listProfilesSpy = vi+ .spyOn(ProfilesService, "listProfiles")+ .mockResolvedValue({+ profiles: [],+ active_profile: null,+ } as Awaited<ReturnType<typeof ProfilesService.listProfiles>>);+ });++ afterEach(() => {+ // Unmount before restoring mocks, so no late re-render reads a restored mock.+ cleanup();+ Reflect.deleteProperty(HTMLElement.prototype, "innerText");+ listProfilesSpy.mockRestore();+ useOptimisticUserMessageStore.getState().clearPendingMessages();+ });++ function renderInterface() {+ render(+ <QueryClientProvider client={new QueryClient()}>+ <MemoryRouter initialEntries={[`/${CONVERSATION_ID}`]}>+ <Routes>+ <Route path=":conversationId" element={<ChatInterface />} />+ </Routes>+ </MemoryRouter>+ </QueryClientProvider>,+ );+ }++ async function typeAndWaitForSavedDraft(text: string) {+ const input = screen.getByTestId("chat-input");+ input.textContent = text;+ fireEvent.input(input);+ // The draft is saved after the input debounce.+ await waitFor(+ () =>+ expect(getConversationState(CONVERSATION_ID).draftMessage).toBe(text),+ { timeout: 2000 },+ );+ return input;+ }++ it.each(["/model", "/new"])(+ "clears the saved draft of a %s command that the chat handles itself",+ async (command) => {+ renderInterface();+ const input = await typeAndWaitForSavedDraft(command);++ fireEvent.keyDown(input, { key: "Enter" });++ expect(input).toHaveTextContent("");+ expect(getConversationState(CONVERSATION_ID).draftMessage).toBeNull();+ expect(mockSend).not.toHaveBeenCalled();+ },+ );++ it("keeps the saved draft of a sent message until the agent confirms it", async () => {+ renderInterface();+ const input = await typeAndWaitForSavedDraft("hello");++ fireEvent.keyDown(input, { key: "Enter" });++ await waitFor(() => expect(mockSend).toHaveBeenCalled());+ expect(getConversationState(CONVERSATION_ID).draftMessage).toBe("hello");+ });+});+describe("ChatInterface - Auto-scroll on submit (issue #817)", () => {let queryClient: QueryClient;diff --git a/src/components/features/chat/chat-interface.tsx b/src/components/features/chat/chat-interface.tsxindex 8d06878278..f30307656c 100644--- a/src/components/features/chat/chat-interface.tsx+++ b/src/components/features/chat/chat-interface.tsx@@ -53,6 +53,7 @@ import ChatStatusIndicator from "./chat-status-indicator";import { getStatusColor, getStatusText } from "#/utils/utils";import { useNewConversationCommand } from "#/hooks/mutation/use-new-conversation-command";import { useOptionalConversationId } from "#/hooks/use-conversation-id";+import { setConversationState } from "#/utils/conversation-local-storage";import { useActiveConversation } from "#/hooks/query/use-active-conversation";import { I18nKey } from "#/i18n/declaration";import { hasConversationStarted } from "./components/resolve-picker-kind";@@ -342,6 +343,9 @@ export function ChatInterface({displayErrorToast(t(I18nKey.CONVERSATION$CLEAR_NO_ID));return;}+ // The command never reaches the agent, so no echo clears its saved+ // draft; clear it here so the cleared composer stays empty.+ setConversationState(conversationId, { draftMessage: null });if (totalEvents === 0) {displayErrorToast(t(I18nKey.CONVERSATION$CLEAR_EMPTY));return;diff --git a/src/components/features/chat/interactive-chat-box.tsx b/src/components/features/chat/interactive-chat-box.tsxindex 61392be629..18b3ef919d 100644--- a/src/components/features/chat/interactive-chat-box.tsx+++ b/src/components/features/chat/interactive-chat-box.tsx@@ -1,3 +1,4 @@+import { useCallback, useRef } from "react";import { CustomChatInput } from "./custom-chat-input";import { useBtwInterceptor } from "#/hooks/chat/use-btw-interceptor";import { useGoalInterceptor } from "#/hooks/chat/use-goal-interceptor";@@ -13,6 +14,7 @@ import { useAgentState } from "#/hooks/use-agent-state";import { useSubConversationTaskPolling } from "#/hooks/query/use-sub-conversation-task-polling";import { partitionImagesForUpload } from "#/components/features/chat/utils/chat-input.utils";import { isTaskPolling } from "#/utils/utils";+import { setConversationState } from "#/utils/conversation-local-storage";interface InteractiveChatBoxProps {onSubmit: (message: string, images: File[], files: File[]) => void;@@ -52,7 +54,10 @@ export function InteractiveChatBox({const { handleUpload } = useChatAttachmentUpload();+ // Set when a submission reaches the agent rather than a slash-command handler.+ const sentToAgentRef = useRef(false);const handleAfterGoal = useBtwInterceptor(conversationId, (message) => {+ sentToAgentRef.current = true;const { imagesToEmbed, imagesAsFiles } = partitionImagesForUpload(images,imagesMarkedUploadAsFile,@@ -69,7 +74,23 @@ export function InteractiveChatBox({conversationId,handleAfterPlanMode,);- const handleSubmit = useModelInterceptor(conversationId, handleAfterModel);+ const handleInterceptedSubmit = useModelInterceptor(+ conversationId,+ handleAfterModel,+ );+ const handleSubmit = useCallback(+ (message: string) => {+ sentToAgentRef.current = false;+ handleInterceptedSubmit(message);+ // A sent message's saved draft is cleared when the agent echoes it back.+ // A command handled here (such as /model) is never echoed, so clear its+ // draft now, or the cleared composer would restore it on return.+ if (!sentToAgentRef.current && persistDraft && routeConversationId) {+ setConversationState(routeConversationId, { draftMessage: null });+ }+ },+ [handleInterceptedSubmit, persistDraft, routeConversationId],+ );const handleSuggestionsClick = (suggestion: string) => {handleSubmit(suggestion);