π OpenHands: AI-Driven Development
fix(chat): keep the message text in the composer after "Branch from here" (#18014)
Engel Nyst9eb056cc3daf
diff --git a/__tests__/components/features/chat/user-assistant-event-message.test.tsx b/__tests__/components/features/chat/user-assistant-event-message.test.tsxindex 06412cda07..bf409dbf54 100644--- a/__tests__/components/features/chat/user-assistant-event-message.test.tsx+++ b/__tests__/components/features/chat/user-assistant-event-message.test.tsx@@ -1,26 +1,22 @@-import { fireEvent, screen, waitFor } from "@testing-library/react";-import { describe, it, expect, vi, beforeEach } from "vitest";+import { act, fireEvent, screen, waitFor } from "@testing-library/react";+import { describe, it, expect, vi, beforeEach, onTestFinished } from "vitest";import { renderWithProviders } from "test-utils";import type { MessageEvent } from "#/types/agent-server/core";import { I18nKey } from "#/i18n/declaration";import { UserAssistantEventMessage } from "#/components/conversation-events/chat/event-message-components/user-assistant-event-message";-import { useConversationStore } from "#/stores/conversation-store";+import { CustomChatInput } from "#/components/features/chat/custom-chat-input";+import { getConversationState } from "#/utils/conversation-local-storage";import ConversationService from "#/api/conversation-service/conversation-service.api";import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";import type { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";import type { DirectConversationInfo } from "#/api/agent-server-adapter";-const {- useActiveBackendMock,- useOptionalConversationIdMock,- setMessageToSendMock,- navigateMock,-} = vi.hoisted(() => ({- useActiveBackendMock: vi.fn(),- useOptionalConversationIdMock: vi.fn(),- setMessageToSendMock: vi.fn(),- navigateMock: vi.fn(),-}));+const { useActiveBackendMock, useOptionalConversationIdMock, navigateMock } =+ vi.hoisted(() => ({+ useActiveBackendMock: vi.fn(),+ useOptionalConversationIdMock: vi.fn(),+ navigateMock: vi.fn(),+ }));// These provide test context (backend kind, conversation id, navigation); the// fork behaviour is exercised through the real hook against a mocked service@@ -80,13 +76,16 @@ const renderMessage = (event: MessageEvent) =>/>,);+// The fork's saved composer draft, which its composer restores on open.+const forkDraft = () => getConversationState(forkResult.id).draftMessage;+describe("UserAssistantEventMessage β branch action", () => {beforeEach(() => {vi.restoreAllMocks();useActiveBackendMock.mockReset();useOptionalConversationIdMock.mockReset();- setMessageToSendMock.mockReset();navigateMock.mockReset();+ localStorage.clear();useActiveBackendMock.mockReturnValue({backend: { kind: "local" },@@ -94,7 +93,6 @@ describe("UserAssistantEventMessage β branch action", () => {});useOptionalConversationIdMock.mockReturnValue({ conversationId: "conv-1" });- useConversationStore.setState({ setMessageToSend: setMessageToSendMock });ConversationService.setCurrentConversation(null);forkSpy = vi@@ -126,25 +124,54 @@ describe("UserAssistantEventMessage β branch action", () => {);expect(parentSpy).not.toHaveBeenCalled();expect(forkSpy).toHaveBeenCalledWith("conv-1", "evt-agent", undefined);- expect(setMessageToSendMock).not.toHaveBeenCalled();+ expect(forkDraft()).toBeNull();});- it("edits a user message: branches at its parent and loads its text into the composer", async () => {- renderMessage(makeEvent("user", "evt-user"));+ it("edits a user message: branches at its parent and the fork's composer opens with its text", async () => {+ // jsdom has no innerText, which the composer reads its text from.+ Object.defineProperty(HTMLElement.prototype, "innerText", {+ configurable: true,+ get(this: HTMLElement) {+ return this.textContent ?? "";+ },+ });+ onTestFinished(() => {+ Reflect.deleteProperty(HTMLElement.prototype, "innerText");+ });+ const onSubmit = vi.fn();+ // The real composer stays mounted across the route change, as in the app.+ const page = () => (+ <>+ <UserAssistantEventMessage+ event={makeEvent("user", "evt-user")}+ isLastMessage={false}+ isFromPlanningAgent={false}+ />+ <CustomChatInput onSubmit={onSubmit} />+ </>+ );+ const { rerender } = renderWithProviders(page());fireEvent.mouseEnter(screen.getByTestId("user-message"));fireEvent.click(screen.getByRole("button", { name: BRANCH_LABEL }));await waitFor(() =>- expect(forkSpy).toHaveBeenCalledWith("conv-1", "evt-parent", undefined),+ expect(navigateMock).toHaveBeenCalledWith("/conversations/fork-123"),);expect(parentSpy).toHaveBeenCalledWith("conv-1", "evt-user");- expect(navigateMock).toHaveBeenCalledWith("/conversations/fork-123");+ expect(forkSpy).toHaveBeenCalledWith("conv-1", "evt-parent", undefined);++ // The router commits the new route after the click handler's own tasks.+ await act(() => new Promise((resolve) => setTimeout(resolve, 0)));+ useOptionalConversationIdMock.mockReturnValue({+ conversationId: "fork-123",+ });+ rerender(page());+await waitFor(() =>- expect(setMessageToSendMock).toHaveBeenCalledWith(- expect.stringContaining("Hello world"),- ),+ expect(screen.getByTestId("chat-input").textContent).toBe("Hello world"),);+ expect(onSubmit).not.toHaveBeenCalled();});it("does not prefill the composer when the message has no parent (inclusive fallback)", async () => {@@ -155,9 +182,10 @@ describe("UserAssistantEventMessage β branch action", () => {fireEvent.click(screen.getByRole("button", { name: BRANCH_LABEL }));await waitFor(() =>- expect(forkSpy).toHaveBeenCalledWith("conv-1", "evt-user", undefined),+ expect(navigateMock).toHaveBeenCalledWith("/conversations/fork-123"),);- expect(setMessageToSendMock).not.toHaveBeenCalled();+ expect(forkSpy).toHaveBeenCalledWith("conv-1", "evt-user", undefined);+ expect(forkDraft()).toBeNull();});it("titles the fork distinctly from its source conversation", async () => {@@ -196,7 +224,7 @@ describe("UserAssistantEventMessage β branch action", () => {await waitFor(() =>expect(navigateMock).toHaveBeenCalledWith("/conversations/fork-123"),);- expect(setMessageToSendMock).not.toHaveBeenCalled();+ expect(forkDraft()).toBeNull();});it("branches an image-only user message inclusively (keeps the image, no prefill)", async () => {@@ -208,10 +236,11 @@ describe("UserAssistantEventMessage β branch action", () => {// No text to edit β branch at the message (inclusive), no parent lookup,// no prefill, so the image is not dropped.await waitFor(() =>- expect(forkSpy).toHaveBeenCalledWith("conv-1", "evt-img", undefined),+ expect(navigateMock).toHaveBeenCalledWith("/conversations/fork-123"),);+ expect(forkSpy).toHaveBeenCalledWith("conv-1", "evt-img", undefined);expect(parentSpy).not.toHaveBeenCalled();- expect(setMessageToSendMock).not.toHaveBeenCalled();+ expect(forkDraft()).toBeNull();});it("omits the fork title when the tracked conversation is a different one", async () => {@@ -257,7 +286,9 @@ describe("UserAssistantEventMessage β branch action", () => {});it("hides the branch action outside of a conversation", () => {- useOptionalConversationIdMock.mockReturnValue({ conversationId: undefined });+ useOptionalConversationIdMock.mockReturnValue({+ conversationId: undefined,+ });renderMessage(makeEvent("agent", "evt-agent"));diff --git a/src/components/conversation-events/chat/event-message-components/user-assistant-event-message.tsx b/src/components/conversation-events/chat/event-message-components/user-assistant-event-message.tsxindex a2b89387ee..a56db1c34e 100644--- a/src/components/conversation-events/chat/event-message-components/user-assistant-event-message.tsx+++ b/src/components/conversation-events/chat/event-message-components/user-assistant-event-message.tsx@@ -16,7 +16,7 @@ import { I18nKey } from "#/i18n/declaration";import { useOptionalConversationId } from "#/hooks/use-conversation-id";import { useActiveBackend } from "#/contexts/active-backend-context";import { useForkConversation } from "#/hooks/mutation/use-fork-conversation";-import { useConversationStore } from "#/stores/conversation-store";+import { setConversationState } from "#/utils/conversation-local-storage";import ConversationService from "#/api/conversation-service/conversation-service.api";import { displayErrorToast } from "#/utils/custom-toast-handlers";@@ -36,9 +36,6 @@ function UserAssistantEventMessageComponent({const isCloud = useActiveBackend().backend.kind === "cloud";const { mutate: forkConversation, isPending: isForking } =useForkConversation();- const setMessageToSend = useConversationStore(- (state) => state.setMessageToSend,- );// Blocks a same-tick double-click, before `isForking` flips.const forkInFlightRef = React.useRef(false);@@ -97,12 +94,14 @@ function UserAssistantEventMessageComponent({},{onSuccess: ({ info, excluded }) => {- navigate(`/conversations/${info.id}`);- // Prefill only when excluded (else the send duplicates it). Deferred- // so the new conversation's composer receives it (as useLaunchSkillInChat).+ // Prefill only when excluded (else the send duplicates it). Seed the+ // fork's saved draft before navigating: the composer clears itself+ // on the conversation switch and then restores that draft, so text+ // pushed into it before the route settles would be wiped.if (excluded) {- window.setTimeout(() => setMessageToSend(message), 0);+ setConversationState(info.id, { draftMessage: message });}+ navigate(`/conversations/${info.id}`);},onError: (error) =>displayErrorToast(error instanceof Error ? error.message : null),