π OpenHands: AI-Driven Development
test: strengthen change-agent control (#17365)
aivong-openhandsc552b0704fe3
diff --git a/__tests__/components/features/chat/change-agent-button.test.tsx b/__tests__/components/features/chat/change-agent-button.test.tsxindex 8eba5b6c47..ed8c51f45b 100644--- a/__tests__/components/features/chat/change-agent-button.test.tsx+++ b/__tests__/components/features/chat/change-agent-button.test.tsx@@ -1,14 +1,36 @@-import type { ReactNode } from "react";-import { screen, waitFor } from "@testing-library/react";-import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";-import { QueryClient } from "@tanstack/react-query";+import type { ReactNode, SVGProps } from "react";+import { act, fireEvent, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi } from "vitest";import { ChangeAgentButton } from "#/components/features/chat/change-agent-button";-import { renderWithProviders } from "../../../../test-utils";+import { AgentState } from "#/types/agent-state";import { useConversationStore } from "#/stores/conversation-store";+import { renderWithProviders } from "../../../../test-utils";++const mocks = vi.hoisted(() => ({+ webSocketStatus: "OPEN",+ agentState: "awaiting_user_input",+ conversation: {+ id: "parent-conversation-123",+ sub_conversation_ids: [] as string[],+ } as+ | {+ id: string;+ sub_conversation_ids: string[];+ }+ | undefined,+ taskStatus: undefined as string | undefined,+ subConversationId: undefined as string | undefined,+ isCreatingConversation: false,+ handlePlanClick: vi.fn(+ (event?: { preventDefault?: () => void; stopPropagation?: () => void }) => {+ event?.preventDefault?.();+ event?.stopPropagation?.();+ },+ ),+ invalidateQueries: vi.fn(),+}));-// Stub StyledTooltip so its content renders eagerly. HeroUI's Tooltip (the-// real engine) only mounts content on real-DOM hover, which jsdom doesn't-// fire reliably, so we surface the content as a marker element instead.vi.mock("#/components/shared/buttons/styled-tooltip", () => ({StyledTooltip: ({content,@@ -24,193 +46,403 @@ vi.mock("#/components/shared/buttons/styled-tooltip", () => ({),}));-// Mock WebSocket status. Controllable so a test can simulate a ready-// connection and isolate the home-page disable from the no-connection one.-const wsState = vi.hoisted(() => ({ status: "CONNECTED" }));+vi.mock("#/icons/lesson-plan.svg?react", () => ({+ default: (props: SVGProps<SVGSVGElement>) => (+ <svg data-testid="plan-agent-icon" {...props} />+ ),+}));++vi.mock("#/icons/code-pill", () => ({+ CodePillIcon: (props: SVGProps<SVGSVGElement>) => (+ <svg data-testid="code-agent-icon" {...props} />+ ),+}));+vi.mock("#/hooks/use-unified-websocket-status", () => ({- useUnifiedWebSocketStatus: () => wsState.status,+ useUnifiedWebSocketStatus: () => mocks.webSocketStatus,}));-// Mock agent statevi.mock("#/hooks/use-agent-state", () => ({- useAgentState: () => ({ curAgentState: "IDLE" }),+ useAgentState: () => ({ curAgentState: mocks.agentState }),}));-// Track invalidateQueries calls-const mockInvalidateQueries = vi.fn();--// Mock react-query to track invalidateQueries callsvi.mock("@tanstack/react-query", async () => {const actual = await vi.importActual("@tanstack/react-query");return {...actual,useQueryClient: () => ({- invalidateQueries: mockInvalidateQueries,+ invalidateQueries: mocks.invalidateQueries,}),};});-// Mock the active conversation hook-const mockConversationData = {- id: "parent-conversation-123",- sub_conversation_ids: [],-};-vi.mock("#/hooks/query/use-active-conversation", () => ({useActiveConversation: () => ({- data: mockConversationData,+ data: mocks.conversation,isFetched: true,refetch: vi.fn(),}),}));-// Mock the sub-conversation task polling hook to control task status-const mockTaskPollingResult = {- task: null as any,- taskStatus: undefined as string | undefined,- taskDetail: null,- taskError: null,- isLoadingTask: false,- subConversationId: undefined as string | undefined,-};-vi.mock("#/hooks/query/use-sub-conversation-task-polling", () => ({- useSubConversationTaskPolling: () => mockTaskPollingResult,+ useSubConversationTaskPolling: (+ _taskId: string | null,+ parentConversationId: string | null,+ ) => {+ const hasExpectedParent =+ parentConversationId === (mocks.conversation?.id ?? null);++ return {+ taskStatus: hasExpectedParent ? mocks.taskStatus : undefined,+ subConversationId: hasExpectedParent+ ? mocks.subConversationId+ : undefined,+ };+ },}));-// Mock the handle plan click hookvi.mock("#/hooks/use-handle-plan-click", () => ({useHandlePlanClick: () => ({- handlePlanClick: vi.fn(),- isCreatingConversation: false,+ handlePlanClick: mocks.handlePlanClick,+ isCreatingConversation: mocks.isCreatingConversation,}),}));-describe("ChangeAgentButton - Cache Invalidation", () => {- beforeEach(() => {- vi.clearAllMocks();- // Reset store state- useConversationStore.setState({- conversationMode: "code",- subConversationTaskId: null,- });- // Reset mock task polling result- mockTaskPollingResult.taskStatus = undefined;- mockTaskPollingResult.subConversationId = undefined;- wsState.status = "CONNECTED";+type RenderOverrides = {+ conversationMode?: "code" | "plan";+ subConversationTaskId?: string | null;+ conversationId?: string | null;+ activeConversationId?: string | null;+ webSocketStatus?: "CONNECTING" | "OPEN" | "CLOSED" | "CLOSING";+ agentState?: AgentState;+ isCreatingConversation?: boolean;+ taskStatus?: string;+ subConversationId?: string;+};++function renderButton(overrides: RenderOverrides = {}) {+ mocks.invalidateQueries.mockReset();+ mocks.handlePlanClick.mockReset();+ mocks.webSocketStatus = overrides.webSocketStatus ?? "OPEN";+ mocks.agentState = overrides.agentState ?? AgentState.AWAITING_USER_INPUT;+ mocks.conversation =+ overrides.activeConversationId === null+ ? undefined+ : {+ id: overrides.activeConversationId ?? "parent-conversation-123",+ sub_conversation_ids: [],+ };+ mocks.taskStatus = overrides.taskStatus;+ mocks.subConversationId = overrides.subConversationId;+ mocks.isCreatingConversation = overrides.isCreatingConversation ?? false;++ useConversationStore.setState({+ conversationMode: overrides.conversationMode ?? "code",+ subConversationTaskId: overrides.subConversationTaskId ?? null,+ });++ mocks.handlePlanClick.mockImplementation((event) => {+ event?.preventDefault?.();+ event?.stopPropagation?.();+ useConversationStore.getState().setConversationMode("plan");+ });++ return renderWithProviders(<ChangeAgentButton />, {+ navigation: {+ conversationId:+ overrides.conversationId === undefined+ ? "route-conversation-123"+ : overrides.conversationId,+ },});+}- afterEach(() => {- vi.clearAllMocks();+function getModeButton() {+ return screen.getByRole("button", {+ name: /COMMON\$(CODE|PLAN)/,});+}- it("should invalidate parent conversation cache exactly once when task becomes READY", async () => {- // Arrange - Set up a task ID in the store- useConversationStore.setState({+describe("ChangeAgentButton cache refresh", () => {+ it("refreshes the parent once per ready task", async () => {+ const { rerender } = renderButton({subConversationTaskId: "task-456",+ taskStatus: "READY",+ subConversationId: "sub-conversation-789",});- // Simulate task becoming READY- mockTaskPollingResult.taskStatus = "READY";- mockTaskPollingResult.subConversationId = "sub-conversation-789";+ await waitFor(() => {+ expect(mocks.invalidateQueries).toHaveBeenCalledTimes(1);+ });+ expect(mocks.invalidateQueries).toHaveBeenLastCalledWith({+ queryKey: ["user", "conversation", "parent-conversation-123"],+ });- // Act - Render the component- renderWithProviders(<ChangeAgentButton />);+ mocks.subConversationId = "sub-conversation-790";+ rerender(<ChangeAgentButton />);+ expect(mocks.invalidateQueries).toHaveBeenCalledTimes(1);- // Assert - Cache should be invalidated exactly once- await waitFor(() => {- expect(mockInvalidateQueries).toHaveBeenCalledTimes(1);+ act(() => {+ useConversationStore.setState({ subConversationTaskId: "task-457" });});- expect(mockInvalidateQueries).toHaveBeenCalledWith({- queryKey: ["user", "conversation", "parent-conversation-123"],+ await waitFor(() => {+ expect(mocks.invalidateQueries).toHaveBeenCalledTimes(2);});});- it("should not invalidate cache when task status is not READY", async () => {- // Arrange - Set up a task ID with WORKING status- useConversationStore.setState({- subConversationTaskId: "task-456",- });+ it.each([+ {+ condition: "the task is still working",+ overrides: {+ subConversationTaskId: "task-456",+ taskStatus: "WORKING",+ subConversationId: "sub-conversation-789",+ },+ },+ {+ condition: "the task has no sub-conversation yet",+ overrides: {+ subConversationTaskId: "task-456",+ taskStatus: "READY",+ },+ },+ {+ condition: "the parent conversation is unavailable",+ overrides: {+ subConversationTaskId: "task-456",+ taskStatus: "READY",+ subConversationId: "sub-conversation-789",+ activeConversationId: null,+ },+ },+ {+ condition: "there is no task to refresh",+ overrides: {+ taskStatus: "READY",+ subConversationId: "sub-conversation-789",+ },+ },+ ])("does not refresh when $condition", ({ overrides }) => {+ renderButton(overrides);++ expect(mocks.invalidateQueries).not.toHaveBeenCalled();+ });+});- mockTaskPollingResult.taskStatus = "WORKING";- mockTaskPollingResult.subConversationId = undefined;+describe("ChangeAgentButton mode selection", () => {+ it("shows the current mode and toggles its menu", async () => {+ const user = userEvent.setup();+ renderButton();++ const button = getModeButton();+ expect(button).toBeEnabled();+ expect(button).toHaveTextContent("COMMON$CODE");+ expect(button).toHaveClass(+ "flex",+ "items-center",+ "rounded-[100px]",+ "border",+ "border-transparent",+ "text-[var(--oh-muted)]",+ "cursor-pointer",+ "hover:text-white",+ "hover:bg-white/10",+ );+ expect(screen.getByTestId("code-agent-icon")).toBeInTheDocument();+ expect(screen.queryByTestId("plan-agent-icon")).not.toBeInTheDocument();+ expect(+ screen.queryByTestId("styled-tooltip-content"),+ ).not.toBeInTheDocument();- // Act- renderWithProviders(<ChangeAgentButton />);+ await user.click(button);+ expect(screen.getByTestId("change-agent-context-menu")).toBeInTheDocument();- // Assert - Wait a bit then verify no invalidation occurred- await new Promise((resolve) => {- setTimeout(resolve, 100);- });- expect(mockInvalidateQueries).not.toHaveBeenCalled();+ await user.click(button);+ expect(+ screen.queryByTestId("change-agent-context-menu"),+ ).not.toBeInTheDocument();});- it("should not invalidate cache when there is no subConversationTaskId", async () => {- // Arrange - No task ID set- useConversationStore.setState({- subConversationTaskId: null,- });+ it("selects plan and code modes from the menu", async () => {+ const user = userEvent.setup();+ renderButton();++ await user.click(getModeButton());+ await user.click(screen.getByTestId("plan-option"));++ expect(getModeButton()).toHaveTextContent("COMMON$PLAN");+ expect(getModeButton()).toHaveClass(+ "border",+ "border-[#597FF4]",+ "bg-[#4A67BD]",+ "cursor-pointer",+ "text-white",+ "hover:bg-[#597FF4]",+ );+ expect(getModeButton()).not.toHaveClass("border-transparent");+ expect(screen.getByTestId("plan-agent-icon")).toBeInTheDocument();+ expect(screen.queryByTestId("code-agent-icon")).not.toBeInTheDocument();+ expect(+ screen.queryByTestId("change-agent-context-menu"),+ ).not.toBeInTheDocument();- mockTaskPollingResult.taskStatus = "READY";- mockTaskPollingResult.subConversationId = "sub-conversation-789";+ await user.click(getModeButton());+ await user.click(screen.getByTestId("code-option"));- // Act- renderWithProviders(<ChangeAgentButton />);+ expect(getModeButton()).toHaveTextContent("COMMON$CODE");+ expect(screen.getByTestId("code-agent-icon")).toBeInTheDocument();+ expect(+ screen.queryByTestId("change-agent-context-menu"),+ ).not.toBeInTheDocument();+ });- // Assert- await new Promise((resolve) => {- setTimeout(resolve, 100);+ it("cycles modes with Shift+Tab without leaking the shortcut", async () => {+ renderButton();++ fireEvent.keyDown(document, { key: "Tab", shiftKey: false });+ fireEvent.keyDown(document, { key: "x", shiftKey: true });+ expect(getModeButton()).toHaveTextContent("COMMON$CODE");+ expect(mocks.handlePlanClick).not.toHaveBeenCalled();++ const propagated = vi.fn();+ window.addEventListener("keydown", propagated);+ const planEvent = new KeyboardEvent("keydown", {+ key: "Tab",+ shiftKey: true,+ bubbles: true,+ cancelable: true,});- expect(mockInvalidateQueries).not.toHaveBeenCalled();- });+ let dispatched = true;+ act(() => {+ dispatched = document.dispatchEvent(planEvent);+ });+ window.removeEventListener("keydown", propagated);- it("should render the button when planning agent feature is enabled", () => {- // Arrange & Act- renderWithProviders(<ChangeAgentButton />);+ expect(dispatched).toBe(false);+ expect(planEvent.defaultPrevented).toBe(true);+ expect(propagated).not.toHaveBeenCalled();+ expect(mocks.handlePlanClick).toHaveBeenCalledWith(planEvent);+ await waitFor(() => {+ expect(getModeButton()).toHaveTextContent("COMMON$PLAN");+ });- // Assert- const button = screen.getByRole("button");- expect(button).toBeInTheDocument();+ const codeEvent = new KeyboardEvent("keydown", {+ key: "Tab",+ shiftKey: true,+ bubbles: true,+ cancelable: true,+ });+ act(() => {+ document.dispatchEvent(codeEvent);+ });++ expect(codeEvent.defaultPrevented).toBe(true);+ expect(getModeButton()).toHaveTextContent("COMMON$CODE");+ expect(mocks.handlePlanClick).toHaveBeenCalledTimes(1);});});-describe("ChangeAgentButton - Home page", () => {- beforeEach(() => {- vi.clearAllMocks();- useConversationStore.setState({- conversationMode: "code",- subConversationTaskId: null,+describe("ChangeAgentButton availability", () => {+ it.each([+ {+ condition: "no conversation has started",+ overrides: { conversationId: null },+ },+ {+ condition: "the agent is running",+ overrides: { agentState: AgentState.RUNNING },+ },+ {+ condition: "a plan conversation is being created",+ overrides: {+ conversationMode: "plan" as const,+ isCreatingConversation: true,+ },+ },+ {+ condition: "the websocket is disconnected",+ overrides: { webSocketStatus: "CLOSED" as const },+ },+ ])("disables mode changes when $condition", async ({ overrides }) => {+ const user = userEvent.setup();+ renderButton(overrides);++ const button = getModeButton();+ expect(button).toBeDisabled();+ expect(button).toHaveClass("opacity-50", "cursor-not-allowed");+ [+ "cursor-pointer",+ "hover:text-white",+ "hover:bg-white/10",+ "text-white",+ "hover:bg-[#597FF4]",+ ].forEach((interactiveClass) => {+ expect(button).not.toHaveClass(interactiveClass);});- mockTaskPollingResult.taskStatus = undefined;- mockTaskPollingResult.subConversationId = undefined;- // A ready websocket isolates the home-page disable: the only reason the- // button is disabled here is the absence of a started conversation.- wsState.status = "OPEN";++ await user.click(button);+ fireEvent.keyDown(document, { key: "Tab", shiftKey: true });++ expect(+ screen.queryByTestId("change-agent-context-menu"),+ ).not.toBeInTheDocument();+ expect(mocks.handlePlanClick).not.toHaveBeenCalled();});- it("disables the button and explains why via a tooltip on the home page", () => {- // Arrange & Act - render with no active conversation (the home page)- renderWithProviders(<ChangeAgentButton />, {- navigation: { conversationId: null },+ it("keeps disabled Plan styling non-interactive", () => {+ renderButton({+ conversationMode: "plan",+ isCreatingConversation: true,});- // Assert - button stays disabled and the explanatory tooltip is wired up- expect(screen.getByRole("button")).toBeDisabled();- expect(screen.getByTestId("styled-tooltip-content")).toHaveTextContent(- "CHANGE_AGENT$SWITCH_AFTER_CONVERSATION",+ expect(getModeButton()).toHaveClass(+ "border",+ "border-[#597FF4]",+ "bg-[#4A67BD]",+ "opacity-50",+ "cursor-not-allowed",);+ expect(getModeButton()).not.toHaveClass("border-transparent");});- it("drops the explanatory tooltip once a conversation has begun", () => {- // Arrange & Act - render inside an active conversation- renderWithProviders(<ChangeAgentButton />, {- navigation: { conversationId: "conversation-1" },+ it.each([+ {+ transition: "the agent starts running",+ applyTransition: () => {+ mocks.agentState = AgentState.RUNNING;+ },+ },+ {+ transition: "the websocket disconnects",+ applyTransition: () => {+ mocks.webSocketStatus = "CLOSED";+ },+ },+ ])("closes an open menu when $transition", async ({ applyTransition }) => {+ const user = userEvent.setup();+ const { rerender } = renderButton();++ await user.click(getModeButton());+ expect(screen.getByTestId("change-agent-context-menu")).toBeInTheDocument();++ applyTransition();+ rerender(<ChangeAgentButton />);++ await waitFor(() => {+ expect(+ screen.queryByTestId("change-agent-context-menu"),+ ).not.toBeInTheDocument();});+ expect(getModeButton()).toBeDisabled();+ });- // Assert - no home-page tooltip wrapper is rendered- expect(- screen.queryByTestId("styled-tooltip-content"),- ).not.toBeInTheDocument();+ it("explains why mode selection is unavailable before a conversation starts", () => {+ renderButton({ conversationId: null });++ expect(getModeButton()).toBeDisabled();+ expect(screen.getByTestId("styled-tooltip-content")).toHaveTextContent(+ "CHANGE_AGENT$SWITCH_AFTER_CONVERSATION",+ );});});