feat(FN-3325): remove monolithic PlanningModeModal test file
Removed the monolithic PlanningModeModal test file (3,476 lines), completing the refactor of the test suite for this component. Fusion-Task-Id: FN-3325
This commit is contained in:
@@ -0,0 +1,523 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { act, render, renderHook, screen, fireEvent, waitFor, within } from "@testing-library/react";
|
||||
import * as api from "../../api";
|
||||
import { PlanningModeModal } from "../PlanningModeModal";
|
||||
import { TaskDetailModal } from "../TaskDetailModal";
|
||||
import { useSessionLock } from "../../hooks/useSessionLock";
|
||||
import { getSessionTabId } from "../../utils/getSessionTabId";
|
||||
import type { MergeResult } from "@fusion/core";
|
||||
import {
|
||||
mockStartPlanning,
|
||||
mockStartPlanningStreaming,
|
||||
mockCreatePlanningDraft,
|
||||
mockConnectPlanningStream,
|
||||
mockRespondToPlanning,
|
||||
mockRetryPlanningSession,
|
||||
mockCancelPlanning,
|
||||
mockStopPlanningGeneration,
|
||||
mockUpdatePlanningSessionDraft,
|
||||
mockCreateTaskFromPlanning,
|
||||
mockStartPlanningBreakdown,
|
||||
mockCreateTasksFromPlanning,
|
||||
mockFetchAiSession,
|
||||
mockParseConversationHistory,
|
||||
mockFetchModels,
|
||||
mockAcquireSessionLock,
|
||||
mockReleaseSessionLock,
|
||||
mockForceAcquireSessionLock,
|
||||
mockUploadAttachment,
|
||||
mockDeleteAttachment,
|
||||
mockUpdateTask,
|
||||
mockPauseTask,
|
||||
mockUnpauseTask,
|
||||
mockFetchTaskDetail,
|
||||
mockRequestSpecRevision,
|
||||
mockApprovePlan,
|
||||
mockRejectPlan,
|
||||
mockRefineTask,
|
||||
mockFetchAiSessions,
|
||||
mockConfirm,
|
||||
mockUseViewportMode,
|
||||
mockUseMobileKeyboard,
|
||||
mockTasks,
|
||||
mockModels,
|
||||
mockQuestion,
|
||||
mockSummary,
|
||||
mockTaskDetail,
|
||||
MockEventSource,
|
||||
getMediaBlocks,
|
||||
mockViewport,
|
||||
} from "./PlanningModeModal.test-helpers";
|
||||
|
||||
vi.mock("../../api", () => ({
|
||||
startPlanning: (...args: any[]) => mockStartPlanning(...args),
|
||||
startPlanningStreaming: (...args: any[]) => mockStartPlanningStreaming(...args),
|
||||
createPlanningDraft: (...args: any[]) => mockCreatePlanningDraft(...args),
|
||||
connectPlanningStream: (...args: any[]) => mockConnectPlanningStream(...args),
|
||||
respondToPlanning: (...args: any[]) => mockRespondToPlanning(...args),
|
||||
retryPlanningSession: (...args: any[]) => mockRetryPlanningSession(...args),
|
||||
cancelPlanning: (...args: any[]) => mockCancelPlanning(...args),
|
||||
stopPlanningGeneration: (...args: any[]) => mockStopPlanningGeneration(...args),
|
||||
updatePlanningSessionDraft: (...args: any[]) => mockUpdatePlanningSessionDraft(...args),
|
||||
createTaskFromPlanning: (...args: any[]) => mockCreateTaskFromPlanning(...args),
|
||||
startPlanningBreakdown: (...args: any[]) => mockStartPlanningBreakdown(...args),
|
||||
createTasksFromPlanning: (...args: any[]) => mockCreateTasksFromPlanning(...args),
|
||||
fetchAiSession: (...args: any[]) => mockFetchAiSession(...args),
|
||||
parseConversationHistory: (...args: any[]) => mockParseConversationHistory(...args),
|
||||
acquireSessionLock: (...args: any[]) => mockAcquireSessionLock(...args),
|
||||
releaseSessionLock: (...args: any[]) => mockReleaseSessionLock(...args),
|
||||
forceAcquireSessionLock: (...args: any[]) => mockForceAcquireSessionLock(...args),
|
||||
uploadAttachment: (...args: any[]) => mockUploadAttachment(...args),
|
||||
deleteAttachment: (...args: any[]) => mockDeleteAttachment(...args),
|
||||
updateTask: (...args: any[]) => mockUpdateTask(...args),
|
||||
pauseTask: (...args: any[]) => mockPauseTask(...args),
|
||||
unpauseTask: (...args: any[]) => mockUnpauseTask(...args),
|
||||
fetchTaskDetail: (...args: any[]) => mockFetchTaskDetail(...args),
|
||||
requestSpecRevision: (...args: any[]) => mockRequestSpecRevision(...args),
|
||||
approvePlan: (...args: any[]) => mockApprovePlan(...args),
|
||||
rejectPlan: (...args: any[]) => mockRejectPlan(...args),
|
||||
refineTask: (...args: any[]) => mockRefineTask(...args),
|
||||
fetchSettings: vi.fn().mockResolvedValue({ modelPresets: [], autoSelectModelPreset: false, defaultPresetBySize: {} }),
|
||||
fetchModels: (...args: any[]) => mockFetchModels(...args),
|
||||
fetchWorkflowSteps: vi.fn().mockResolvedValue([]),
|
||||
refineText: vi.fn(),
|
||||
getRefineErrorMessage: vi.fn((err: any) => err?.message || "Failed to refine"),
|
||||
updateGlobalSettings: vi.fn().mockResolvedValue({}),
|
||||
duplicateTask: vi.fn().mockResolvedValue({}),
|
||||
fetchAiSessions: (...args: any[]) => mockFetchAiSessions(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../../hooks/useConfirm", () => ({
|
||||
useConfirm: () => ({ confirm: mockConfirm }),
|
||||
}));
|
||||
|
||||
vi.mock("../../hooks/useViewportMode", () => ({
|
||||
useViewportMode: () => mockUseViewportMode(),
|
||||
}));
|
||||
|
||||
vi.mock("../../hooks/useMobileKeyboard", () => ({
|
||||
useMobileKeyboard: (...args: any[]) => mockUseMobileKeyboard(...args),
|
||||
}));
|
||||
|
||||
describe("PlanningModeModal", () => {
|
||||
const mockOnClose = vi.fn();
|
||||
const mockOnTaskCreated = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockConfirm.mockReset();
|
||||
mockConfirm.mockResolvedValue(true);
|
||||
MockEventSource.reset();
|
||||
vi.stubGlobal("EventSource", MockEventSource as any);
|
||||
window.sessionStorage.clear();
|
||||
// Default to desktop viewport; mobile-specific tests override per-test.
|
||||
mockViewport("desktop");
|
||||
|
||||
// Default mock for streaming
|
||||
mockStartPlanningStreaming.mockResolvedValue({ sessionId: "session-123" });
|
||||
// Server's createDraftSession always returns the placeholder title; the
|
||||
// real summarized title only arrives later via blur/close summarize or
|
||||
// when the session transitions out of draft. Mirror that in the mock so
|
||||
// the sidebar render rule (preview while title === placeholder) behaves
|
||||
// realistically in tests.
|
||||
mockCreatePlanningDraft.mockResolvedValue({ sessionId: "draft-123", title: "New planning session" });
|
||||
mockRetryPlanningSession.mockResolvedValue({ success: true, sessionId: "session-123" });
|
||||
mockStartPlanningBreakdown.mockResolvedValue({ sessionId: "session-123", subtasks: [] });
|
||||
mockFetchAiSession.mockResolvedValue(null);
|
||||
mockFetchAiSessions.mockResolvedValue([]);
|
||||
mockParseConversationHistory.mockImplementation((raw: string) => {
|
||||
if (!raw) return [];
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
return Array.isArray(parsed) ? parsed : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
});
|
||||
mockFetchModels.mockResolvedValue({
|
||||
models: mockModels,
|
||||
favoriteProviders: [],
|
||||
favoriteModels: [],
|
||||
resolvedPlanningProvider: "openai",
|
||||
resolvedPlanningModelId: "gpt-4o",
|
||||
});
|
||||
mockAcquireSessionLock.mockResolvedValue({ acquired: true, currentHolder: null });
|
||||
mockReleaseSessionLock.mockResolvedValue(undefined);
|
||||
mockForceAcquireSessionLock.mockResolvedValue(undefined);
|
||||
mockCancelPlanning.mockResolvedValue(undefined);
|
||||
mockUpdatePlanningSessionDraft.mockResolvedValue({ ok: true });
|
||||
mockStopPlanningGeneration.mockResolvedValue({ success: true });
|
||||
|
||||
// Default: simulate receiving a question after a brief delay
|
||||
mockConnectPlanningStream.mockImplementation((_sessionId: string, _projectId: string | undefined, handlers: any) => {
|
||||
setTimeout(() => {
|
||||
handlers.onQuestion?.(mockQuestion);
|
||||
}, 10);
|
||||
|
||||
return {
|
||||
close: vi.fn(),
|
||||
isConnected: vi.fn().mockReturnValue(true),
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
describe("Model favorites persistence", () => {
|
||||
it("persists provider favorite toggle to global settings", async () => {
|
||||
mockFetchModels.mockResolvedValue({
|
||||
models: mockModels,
|
||||
favoriteProviders: ["anthropic"],
|
||||
favoriteModels: [],
|
||||
});
|
||||
vi.mocked(api.updateGlobalSettings).mockResolvedValue({} as any);
|
||||
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockFetchModels).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Advanced planning settings" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Planning Model" }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(document.body.querySelector('[data-testid="model-combobox-portal"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
const portal = document.body.querySelector('[data-testid="model-combobox-portal"]') as HTMLElement;
|
||||
// When provider is favorited, the optgroup header shows "Remove" button
|
||||
const removeButton = within(portal).queryByRole("button", { name: "Remove anthropic from favorites" });
|
||||
expect(removeButton).not.toBeNull();
|
||||
fireEvent.click(removeButton!);
|
||||
|
||||
expect(api.updateGlobalSettings).toHaveBeenCalledWith({
|
||||
favoriteProviders: [],
|
||||
favoriteModels: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("persists model favorite toggle to global settings", async () => {
|
||||
mockFetchModels.mockResolvedValue({
|
||||
models: mockModels,
|
||||
favoriteProviders: [],
|
||||
favoriteModels: ["anthropic/claude-sonnet-4-5"],
|
||||
});
|
||||
vi.mocked(api.updateGlobalSettings).mockResolvedValue({} as any);
|
||||
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockFetchModels).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Advanced planning settings" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Planning Model" }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(document.body.querySelector('[data-testid="model-combobox-portal"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
const portal = document.body.querySelector('[data-testid="model-combobox-portal"]') as HTMLElement;
|
||||
// When model is favorited, it appears as a pinned row with "Remove" button
|
||||
// There may be duplicates (in pinned row + provider group), use first one
|
||||
const removeButtons = within(portal).queryAllByRole("button", { name: "Remove Claude Sonnet 4.5 from favorites" });
|
||||
expect(removeButtons.length).toBeGreaterThan(0);
|
||||
fireEvent.click(removeButtons[0]);
|
||||
|
||||
expect(api.updateGlobalSettings).toHaveBeenCalledWith({
|
||||
favoriteProviders: [],
|
||||
favoriteModels: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("adds provider to favorites", async () => {
|
||||
mockFetchModels.mockResolvedValue({
|
||||
models: mockModels,
|
||||
favoriteProviders: [],
|
||||
favoriteModels: [],
|
||||
});
|
||||
vi.mocked(api.updateGlobalSettings).mockResolvedValue({} as any);
|
||||
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockFetchModels).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Advanced planning settings" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Planning Model" }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(document.body.querySelector('[data-testid="model-combobox-portal"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
const portal = document.body.querySelector('[data-testid="model-combobox-portal"]') as HTMLElement;
|
||||
const addButton = within(portal).getByRole("button", { name: "Add anthropic to favorites" });
|
||||
fireEvent.click(addButton);
|
||||
|
||||
expect(api.updateGlobalSettings).toHaveBeenCalledWith({
|
||||
favoriteProviders: ["anthropic"],
|
||||
favoriteModels: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("rolls back local favorite state when updateGlobalSettings fails", async () => {
|
||||
mockFetchModels.mockResolvedValue({
|
||||
models: mockModels,
|
||||
favoriteProviders: ["anthropic"],
|
||||
favoriteModels: [],
|
||||
});
|
||||
vi.mocked(api.updateGlobalSettings).mockRejectedValueOnce(new Error("Network error"));
|
||||
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockFetchModels).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Advanced planning settings" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Planning Model" }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(document.body.querySelector('[data-testid="model-combobox-portal"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
const portal = document.body.querySelector('[data-testid="model-combobox-portal"]') as HTMLElement;
|
||||
const removeButton = within(portal).getByRole("button", { name: "Remove anthropic from favorites" });
|
||||
fireEvent.click(removeButton);
|
||||
|
||||
// Wait for the rejected promise to settle
|
||||
await waitFor(() => {
|
||||
expect(api.updateGlobalSettings).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// After rollback, the provider should still show as favorited (★ button with "Remove" aria-label)
|
||||
const portalAfterRollback = document.body.querySelector('[data-testid="model-combobox-portal"]') as HTMLElement;
|
||||
expect(within(portalAfterRollback).getByRole("button", { name: "Remove anthropic from favorites" })).toBeTruthy();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("getSessionTabId", () => {
|
||||
it("creates and persists a per-tab id in sessionStorage", () => {
|
||||
window.sessionStorage.clear();
|
||||
|
||||
const first = getSessionTabId();
|
||||
const second = getSessionTabId();
|
||||
|
||||
expect(first).toBeTruthy();
|
||||
expect(second).toBe(first);
|
||||
expect(window.sessionStorage.getItem("fusion-tab-id")).toBe(first);
|
||||
});
|
||||
});
|
||||
|
||||
describe("useSessionLock", () => {
|
||||
beforeEach(() => {
|
||||
MockEventSource.reset();
|
||||
vi.stubGlobal("EventSource", MockEventSource as any);
|
||||
window.sessionStorage.clear();
|
||||
mockAcquireSessionLock.mockResolvedValue({ acquired: true, currentHolder: null });
|
||||
mockReleaseSessionLock.mockResolvedValue(undefined);
|
||||
mockForceAcquireSessionLock.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("acquires on mount and releases on unmount", async () => {
|
||||
window.sessionStorage.setItem("fusion-tab-id", "tab-self");
|
||||
|
||||
const { unmount } = renderHook(() => useSessionLock("session-1"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockAcquireSessionLock).toHaveBeenCalledWith("session-1", "tab-self");
|
||||
});
|
||||
|
||||
unmount();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockReleaseSessionLock).toHaveBeenCalledWith("session-1", "tab-self");
|
||||
});
|
||||
});
|
||||
|
||||
it("exposes locked state and allows taking control", async () => {
|
||||
window.sessionStorage.setItem("fusion-tab-id", "tab-self");
|
||||
mockAcquireSessionLock.mockResolvedValueOnce({ acquired: false, currentHolder: "tab-other" });
|
||||
|
||||
const { result } = renderHook(() => useSessionLock("session-2"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLockedByOther).toBe(true);
|
||||
expect(result.current.currentHolder).toBe("tab-other");
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.takeControl();
|
||||
});
|
||||
|
||||
expect(mockForceAcquireSessionLock).toHaveBeenCalledWith("session-2", "tab-self");
|
||||
expect(result.current.isLockedByOther).toBe(false);
|
||||
expect(result.current.currentHolder).toBeNull();
|
||||
});
|
||||
|
||||
it("updates lock state from ai_session:updated SSE events and uses sendBeacon on beforeunload", async () => {
|
||||
window.sessionStorage.setItem("fusion-tab-id", "tab-self");
|
||||
const sendBeaconSpy = vi.fn(() => true);
|
||||
vi.stubGlobal("navigator", {
|
||||
...window.navigator,
|
||||
sendBeacon: sendBeaconSpy,
|
||||
} as Navigator);
|
||||
|
||||
const { result } = renderHook(() => useSessionLock("session-3"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockAcquireSessionLock).toHaveBeenCalledWith("session-3", "tab-self");
|
||||
});
|
||||
|
||||
const source = MockEventSource.instances[0];
|
||||
expect(source).toBeDefined();
|
||||
|
||||
act(() => {
|
||||
source?.emit("ai_session:updated", {
|
||||
id: "session-3",
|
||||
type: "planning",
|
||||
status: "awaiting_input",
|
||||
title: "Session",
|
||||
projectId: null,
|
||||
lockedByTab: "tab-other",
|
||||
updatedAt: new Date().toISOString(),
|
||||
});
|
||||
});
|
||||
|
||||
expect(result.current.isLockedByOther).toBe(true);
|
||||
expect(result.current.currentHolder).toBe("tab-other");
|
||||
|
||||
act(() => {
|
||||
source?.emit("ai_session:updated", {
|
||||
id: "session-3",
|
||||
type: "planning",
|
||||
status: "awaiting_input",
|
||||
title: "Session",
|
||||
projectId: null,
|
||||
lockedByTab: "tab-self",
|
||||
updatedAt: new Date().toISOString(),
|
||||
});
|
||||
});
|
||||
|
||||
expect(result.current.isLockedByOther).toBe(false);
|
||||
|
||||
act(() => {
|
||||
window.dispatchEvent(new Event("beforeunload"));
|
||||
});
|
||||
|
||||
expect(sendBeaconSpy).toHaveBeenCalledWith(
|
||||
"/api/ai-sessions/session-3/lock/beacon?tabId=tab-self",
|
||||
);
|
||||
});
|
||||
|
||||
describe("Mobile keyboard behavior (FN-3337)", () => {
|
||||
beforeEach(() => {
|
||||
mockUseViewportMode.mockReturnValue("desktop");
|
||||
mockUseMobileKeyboard.mockReturnValue({
|
||||
keyboardOverlap: 0,
|
||||
viewportHeight: null,
|
||||
viewportOffsetTop: 0,
|
||||
keyboardOpen: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("applies keyboard CSS variables when keyboard is open on mobile", () => {
|
||||
mockUseViewportMode.mockReturnValue("mobile");
|
||||
mockUseMobileKeyboard.mockReturnValue({
|
||||
keyboardOverlap: 300,
|
||||
viewportHeight: 400,
|
||||
viewportOffsetTop: 50,
|
||||
keyboardOpen: true,
|
||||
});
|
||||
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
const modal = screen.getByRole("dialog").querySelector(".planning-modal");
|
||||
expect(modal).toBeTruthy();
|
||||
expect(modal!.getAttribute("style")).toContain("--keyboard-overlap");
|
||||
expect(modal!.getAttribute("style")).toContain("--vv-height");
|
||||
expect(modal!.getAttribute("style")).toContain("--vv-offset-top");
|
||||
});
|
||||
|
||||
it("does not apply keyboard CSS variables when keyboard is closed", () => {
|
||||
mockUseViewportMode.mockReturnValue("mobile");
|
||||
mockUseMobileKeyboard.mockReturnValue({
|
||||
keyboardOverlap: 0,
|
||||
viewportHeight: null,
|
||||
viewportOffsetTop: 0,
|
||||
keyboardOpen: false,
|
||||
});
|
||||
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
const modal = screen.getByRole("dialog").querySelector(".planning-modal");
|
||||
expect(modal).toBeTruthy();
|
||||
expect(modal!.getAttribute("style")).toBeNull();
|
||||
});
|
||||
|
||||
it("does not apply keyboard CSS variables on desktop", () => {
|
||||
mockUseViewportMode.mockReturnValue("desktop");
|
||||
mockUseMobileKeyboard.mockReturnValue({
|
||||
keyboardOverlap: 0,
|
||||
viewportHeight: null,
|
||||
viewportOffsetTop: 0,
|
||||
keyboardOpen: false,
|
||||
});
|
||||
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
const modal = screen.getByRole("dialog").querySelector(".planning-modal");
|
||||
expect(modal).toBeTruthy();
|
||||
expect(modal!.getAttribute("style")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
@@ -0,0 +1,600 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { act, render, renderHook, screen, fireEvent, waitFor, within } from "@testing-library/react";
|
||||
import * as api from "../../api";
|
||||
import { PlanningModeModal } from "../PlanningModeModal";
|
||||
import { TaskDetailModal } from "../TaskDetailModal";
|
||||
import { useSessionLock } from "../../hooks/useSessionLock";
|
||||
import { getSessionTabId } from "../../utils/getSessionTabId";
|
||||
import type { MergeResult } from "@fusion/core";
|
||||
import {
|
||||
mockStartPlanning,
|
||||
mockStartPlanningStreaming,
|
||||
mockCreatePlanningDraft,
|
||||
mockConnectPlanningStream,
|
||||
mockRespondToPlanning,
|
||||
mockRetryPlanningSession,
|
||||
mockCancelPlanning,
|
||||
mockStopPlanningGeneration,
|
||||
mockUpdatePlanningSessionDraft,
|
||||
mockCreateTaskFromPlanning,
|
||||
mockStartPlanningBreakdown,
|
||||
mockCreateTasksFromPlanning,
|
||||
mockFetchAiSession,
|
||||
mockParseConversationHistory,
|
||||
mockFetchModels,
|
||||
mockAcquireSessionLock,
|
||||
mockReleaseSessionLock,
|
||||
mockForceAcquireSessionLock,
|
||||
mockUploadAttachment,
|
||||
mockDeleteAttachment,
|
||||
mockUpdateTask,
|
||||
mockPauseTask,
|
||||
mockUnpauseTask,
|
||||
mockFetchTaskDetail,
|
||||
mockRequestSpecRevision,
|
||||
mockApprovePlan,
|
||||
mockRejectPlan,
|
||||
mockRefineTask,
|
||||
mockFetchAiSessions,
|
||||
mockConfirm,
|
||||
mockUseViewportMode,
|
||||
mockUseMobileKeyboard,
|
||||
mockTasks,
|
||||
mockModels,
|
||||
mockQuestion,
|
||||
mockSummary,
|
||||
mockTaskDetail,
|
||||
MockEventSource,
|
||||
getMediaBlocks,
|
||||
mockViewport,
|
||||
} from "./PlanningModeModal.test-helpers";
|
||||
|
||||
vi.mock("../../api", () => ({
|
||||
startPlanning: (...args: any[]) => mockStartPlanning(...args),
|
||||
startPlanningStreaming: (...args: any[]) => mockStartPlanningStreaming(...args),
|
||||
createPlanningDraft: (...args: any[]) => mockCreatePlanningDraft(...args),
|
||||
connectPlanningStream: (...args: any[]) => mockConnectPlanningStream(...args),
|
||||
respondToPlanning: (...args: any[]) => mockRespondToPlanning(...args),
|
||||
retryPlanningSession: (...args: any[]) => mockRetryPlanningSession(...args),
|
||||
cancelPlanning: (...args: any[]) => mockCancelPlanning(...args),
|
||||
stopPlanningGeneration: (...args: any[]) => mockStopPlanningGeneration(...args),
|
||||
updatePlanningSessionDraft: (...args: any[]) => mockUpdatePlanningSessionDraft(...args),
|
||||
createTaskFromPlanning: (...args: any[]) => mockCreateTaskFromPlanning(...args),
|
||||
startPlanningBreakdown: (...args: any[]) => mockStartPlanningBreakdown(...args),
|
||||
createTasksFromPlanning: (...args: any[]) => mockCreateTasksFromPlanning(...args),
|
||||
fetchAiSession: (...args: any[]) => mockFetchAiSession(...args),
|
||||
parseConversationHistory: (...args: any[]) => mockParseConversationHistory(...args),
|
||||
acquireSessionLock: (...args: any[]) => mockAcquireSessionLock(...args),
|
||||
releaseSessionLock: (...args: any[]) => mockReleaseSessionLock(...args),
|
||||
forceAcquireSessionLock: (...args: any[]) => mockForceAcquireSessionLock(...args),
|
||||
uploadAttachment: (...args: any[]) => mockUploadAttachment(...args),
|
||||
deleteAttachment: (...args: any[]) => mockDeleteAttachment(...args),
|
||||
updateTask: (...args: any[]) => mockUpdateTask(...args),
|
||||
pauseTask: (...args: any[]) => mockPauseTask(...args),
|
||||
unpauseTask: (...args: any[]) => mockUnpauseTask(...args),
|
||||
fetchTaskDetail: (...args: any[]) => mockFetchTaskDetail(...args),
|
||||
requestSpecRevision: (...args: any[]) => mockRequestSpecRevision(...args),
|
||||
approvePlan: (...args: any[]) => mockApprovePlan(...args),
|
||||
rejectPlan: (...args: any[]) => mockRejectPlan(...args),
|
||||
refineTask: (...args: any[]) => mockRefineTask(...args),
|
||||
fetchSettings: vi.fn().mockResolvedValue({ modelPresets: [], autoSelectModelPreset: false, defaultPresetBySize: {} }),
|
||||
fetchModels: (...args: any[]) => mockFetchModels(...args),
|
||||
fetchWorkflowSteps: vi.fn().mockResolvedValue([]),
|
||||
refineText: vi.fn(),
|
||||
getRefineErrorMessage: vi.fn((err: any) => err?.message || "Failed to refine"),
|
||||
updateGlobalSettings: vi.fn().mockResolvedValue({}),
|
||||
duplicateTask: vi.fn().mockResolvedValue({}),
|
||||
fetchAiSessions: (...args: any[]) => mockFetchAiSessions(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../../hooks/useConfirm", () => ({
|
||||
useConfirm: () => ({ confirm: mockConfirm }),
|
||||
}));
|
||||
|
||||
vi.mock("../../hooks/useViewportMode", () => ({
|
||||
useViewportMode: () => mockUseViewportMode(),
|
||||
}));
|
||||
|
||||
vi.mock("../../hooks/useMobileKeyboard", () => ({
|
||||
useMobileKeyboard: (...args: any[]) => mockUseMobileKeyboard(...args),
|
||||
}));
|
||||
|
||||
describe("PlanningModeModal", () => {
|
||||
const mockOnClose = vi.fn();
|
||||
const mockOnTaskCreated = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockConfirm.mockReset();
|
||||
mockConfirm.mockResolvedValue(true);
|
||||
MockEventSource.reset();
|
||||
vi.stubGlobal("EventSource", MockEventSource as any);
|
||||
window.sessionStorage.clear();
|
||||
// Default to desktop viewport; mobile-specific tests override per-test.
|
||||
mockViewport("desktop");
|
||||
|
||||
// Default mock for streaming
|
||||
mockStartPlanningStreaming.mockResolvedValue({ sessionId: "session-123" });
|
||||
// Server's createDraftSession always returns the placeholder title; the
|
||||
// real summarized title only arrives later via blur/close summarize or
|
||||
// when the session transitions out of draft. Mirror that in the mock so
|
||||
// the sidebar render rule (preview while title === placeholder) behaves
|
||||
// realistically in tests.
|
||||
mockCreatePlanningDraft.mockResolvedValue({ sessionId: "draft-123", title: "New planning session" });
|
||||
mockRetryPlanningSession.mockResolvedValue({ success: true, sessionId: "session-123" });
|
||||
mockStartPlanningBreakdown.mockResolvedValue({ sessionId: "session-123", subtasks: [] });
|
||||
mockFetchAiSession.mockResolvedValue(null);
|
||||
mockFetchAiSessions.mockResolvedValue([]);
|
||||
mockParseConversationHistory.mockImplementation((raw: string) => {
|
||||
if (!raw) return [];
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
return Array.isArray(parsed) ? parsed : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
});
|
||||
mockFetchModels.mockResolvedValue({
|
||||
models: mockModels,
|
||||
favoriteProviders: [],
|
||||
favoriteModels: [],
|
||||
resolvedPlanningProvider: "openai",
|
||||
resolvedPlanningModelId: "gpt-4o",
|
||||
});
|
||||
mockAcquireSessionLock.mockResolvedValue({ acquired: true, currentHolder: null });
|
||||
mockReleaseSessionLock.mockResolvedValue(undefined);
|
||||
mockForceAcquireSessionLock.mockResolvedValue(undefined);
|
||||
mockCancelPlanning.mockResolvedValue(undefined);
|
||||
mockUpdatePlanningSessionDraft.mockResolvedValue({ ok: true });
|
||||
mockStopPlanningGeneration.mockResolvedValue({ success: true });
|
||||
|
||||
// Default: simulate receiving a question after a brief delay
|
||||
mockConnectPlanningStream.mockImplementation((_sessionId: string, _projectId: string | undefined, handlers: any) => {
|
||||
setTimeout(() => {
|
||||
handlers.onQuestion?.(mockQuestion);
|
||||
}, 10);
|
||||
|
||||
return {
|
||||
close: vi.fn(),
|
||||
isConnected: vi.fn().mockReturnValue(true),
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
describe("Initial view", () => {
|
||||
it("renders the initial input view when open", () => {
|
||||
const { container } = render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText("Planning Mode")).toBeDefined();
|
||||
expect(screen.getByPlaceholderText(/e.g., Build a user authentication/)).toBeDefined();
|
||||
expect(container.querySelector(".planning-modal-body")).not.toBeNull();
|
||||
expect(container.querySelector(".planning-modal-body")?.classList.contains("modal-body")).toBe(false);
|
||||
expect(container.querySelector(".planning-examples-label")?.textContent).toBe("Try an example:");
|
||||
});
|
||||
|
||||
it("does not render when closed", () => {
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={false}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.queryByText("Planning Mode")).toBeNull();
|
||||
});
|
||||
|
||||
it("mobile close path blurs focused input and resets viewport scroll", () => {
|
||||
mockViewport("mobile");
|
||||
const scrollToSpy = vi.spyOn(window, "scrollTo").mockImplementation(() => undefined);
|
||||
const rafSpy = vi
|
||||
.spyOn(window, "requestAnimationFrame")
|
||||
.mockImplementation((callback: FrameRequestCallback) => {
|
||||
callback(0);
|
||||
return 1;
|
||||
});
|
||||
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>
|
||||
);
|
||||
|
||||
const textarea = screen.getByPlaceholderText(/e.g., Build a user authentication/) as HTMLTextAreaElement;
|
||||
act(() => {
|
||||
textarea.focus();
|
||||
});
|
||||
const blurSpy = vi.spyOn(textarea, "blur");
|
||||
|
||||
act(() => {
|
||||
fireEvent.click(screen.getByRole("button", { name: "Close" }));
|
||||
});
|
||||
|
||||
expect(blurSpy).toHaveBeenCalledTimes(1);
|
||||
expect(scrollToSpy).toHaveBeenCalledWith(0, 0);
|
||||
expect(rafSpy).toHaveBeenCalled();
|
||||
expect(mockOnClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("hides send to background button in initial state", () => {
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.queryByLabelText("Send to background")).toBeNull();
|
||||
});
|
||||
|
||||
it("enables start button when text is entered", () => {
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>
|
||||
);
|
||||
|
||||
const startButton = screen.getByText("Start Planning");
|
||||
expect(startButton.closest("button")?.hasAttribute("disabled")).toBe(true);
|
||||
|
||||
const textarea = screen.getByPlaceholderText(/e.g., Build a user authentication/);
|
||||
fireEvent.change(textarea, { target: { value: "Test plan" } });
|
||||
|
||||
expect(startButton.closest("button")?.hasAttribute("disabled")).toBe(false);
|
||||
});
|
||||
|
||||
it("shows example chips", () => {
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText(/Build a user authentication/)).toBeDefined();
|
||||
});
|
||||
|
||||
it("renders planning model dropdown in initial view", async () => {
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByRole("button", { name: "Advanced planning settings" })).toBeDefined();
|
||||
expect(screen.queryByRole("button", { name: "Planning Model" })).toBeNull();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Advanced planning settings" }));
|
||||
|
||||
const modelTrigger = screen.getByRole("button", { name: "Planning Model" });
|
||||
expect(modelTrigger).toBeDefined();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockFetchModels).toHaveBeenCalledTimes(1);
|
||||
expect(screen.getByText("openai/gpt-4o")).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
it("shows resolved default model badge and switches to override badge when selected", async () => {
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockFetchModels).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Advanced planning settings" }));
|
||||
expect(screen.getByText("openai/gpt-4o")).toBeDefined();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Planning Model" }));
|
||||
fireEvent.click(screen.getByRole("option", { name: /Claude Sonnet 4.5/ }));
|
||||
|
||||
expect(screen.getByText("anthropic/claude-sonnet-4-5")).toBeDefined();
|
||||
});
|
||||
|
||||
it("passes selected planning model to startPlanningStreaming", async () => {
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockFetchModels).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Advanced planning settings" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Planning Model" }));
|
||||
fireEvent.click(screen.getByRole("option", { name: /Claude Sonnet 4.5/ }));
|
||||
|
||||
const textarea = screen.getByPlaceholderText(/e.g., Build a user authentication/);
|
||||
fireEvent.change(textarea, { target: { value: "Build auth system" } });
|
||||
fireEvent.click(screen.getByText("Start Planning"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockStartPlanningStreaming).toHaveBeenCalledWith("Build auth system", undefined, {
|
||||
planningModelProvider: "anthropic",
|
||||
planningModelId: "claude-sonnet-4-5",
|
||||
}, {
|
||||
planningDepth: "medium",
|
||||
customQuestionCount: undefined,
|
||||
}, undefined);
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps advanced disclosure collapsed by default and reveals controls when expanded", async () => {
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>
|
||||
);
|
||||
|
||||
const disclosureButton = screen.getByRole("button", { name: "Advanced planning settings" });
|
||||
expect(disclosureButton).toBeDefined();
|
||||
|
||||
const disclosure = disclosureButton.closest(".onboarding-disclosure");
|
||||
expect(disclosure).not.toBeNull();
|
||||
const disclosureScope = within(disclosure as HTMLElement);
|
||||
|
||||
expect(disclosureButton.getAttribute("aria-expanded")).toBe("false");
|
||||
expect(disclosureScope.queryByRole("button", { name: "Planning Model" })).toBeNull();
|
||||
expect(disclosureScope.queryByText(/Selects which model runs the planning interview/)).toBeNull();
|
||||
|
||||
fireEvent.click(disclosureButton);
|
||||
expect(disclosureButton.getAttribute("aria-expanded")).toBe("true");
|
||||
|
||||
expect(disclosureScope.getByRole("button", { name: "Planning Model" })).toBeDefined();
|
||||
await waitFor(() => {
|
||||
expect(disclosureScope.getByText("openai/gpt-4o")).toBeDefined();
|
||||
});
|
||||
expect(disclosureScope.getByText(/Selects which model runs the planning interview/)).toBeDefined();
|
||||
expect(disclosureScope.getByText(/Plan size sets default interview depth/)).toBeDefined();
|
||||
expect(disclosureScope.getByRole("button", { name: "Small" })).toBeDefined();
|
||||
expect(disclosureScope.getByRole("button", { name: "Medium" }).getAttribute("aria-pressed")).toBe("true");
|
||||
expect(disclosureScope.getByRole("button", { name: "Large" })).toBeDefined();
|
||||
expect(disclosureScope.getByLabelText("Questions")).toBeDefined();
|
||||
});
|
||||
|
||||
it("updates selected depth and sends custom question count", async () => {
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Advanced planning settings" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Large" }));
|
||||
fireEvent.change(screen.getByLabelText("Questions"), { target: { value: "7" } });
|
||||
fireEvent.change(screen.getByPlaceholderText(/e.g., Build a user authentication/), {
|
||||
target: { value: "Build auth system" },
|
||||
});
|
||||
fireEvent.click(screen.getByText("Start Planning"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockStartPlanningStreaming).toHaveBeenCalledWith("Build auth system", undefined, undefined, {
|
||||
planningDepth: "large",
|
||||
customQuestionCount: 7,
|
||||
}, undefined);
|
||||
});
|
||||
});
|
||||
|
||||
it("calls startPlanningStreaming without model override when none selected", async () => {
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>
|
||||
);
|
||||
|
||||
const textarea = screen.getByPlaceholderText(/e.g., Build a user authentication/);
|
||||
fireEvent.change(textarea, { target: { value: "Build auth system" } });
|
||||
fireEvent.click(screen.getByText("Start Planning"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockStartPlanningStreaming).toHaveBeenCalledWith("Build auth system", undefined, undefined, {
|
||||
planningDepth: "medium",
|
||||
customQuestionCount: undefined,
|
||||
}, undefined);
|
||||
});
|
||||
});
|
||||
|
||||
it("auto-creates a draft after typing and reuses it when starting", async () => {
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>,
|
||||
);
|
||||
|
||||
const textarea = screen.getByPlaceholderText(/e.g., Build a user authentication/);
|
||||
fireEvent.change(textarea, { target: { value: "Build a detailed auth system plan" } });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockCreatePlanningDraft).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
expect(mockCreatePlanningDraft).toHaveBeenCalledWith(
|
||||
"Build a detailed auth system plan",
|
||||
undefined,
|
||||
undefined,
|
||||
);
|
||||
|
||||
// Sidebar shows the inputPayload-derived preview for draft rows so
|
||||
// multiple drafts are distinguishable, not the placeholder title that
|
||||
// createDraftSession returns. The text also appears in the textarea
|
||||
// value, so scope the query to the sidebar item title element.
|
||||
const sidebarItem = document.querySelector(".planning-sidebar-item-title");
|
||||
expect(sidebarItem?.textContent).toBe("Build a detailed auth system plan");
|
||||
|
||||
fireEvent.change(textarea, { target: { value: "Build a detailed auth system plan with extras" } });
|
||||
await new Promise((resolve) => setTimeout(resolve, 350));
|
||||
expect(mockCreatePlanningDraft).toHaveBeenCalledTimes(1);
|
||||
|
||||
fireEvent.click(screen.getByText("Start Planning"));
|
||||
await waitFor(() => {
|
||||
expect(mockStartPlanningStreaming).toHaveBeenCalledWith(
|
||||
"Build a detailed auth system plan with extras",
|
||||
undefined,
|
||||
undefined,
|
||||
{
|
||||
planningDepth: "medium",
|
||||
customQuestionCount: undefined,
|
||||
},
|
||||
"draft-123",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("auto-starts planning when initialPlan prop is provided", async () => {
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
initialPlan="Build a login system from new task dialog"
|
||||
/>
|
||||
);
|
||||
|
||||
// Wait for startPlanningStreaming to be called (allow time for setTimeout in useEffect)
|
||||
await waitFor(() => {
|
||||
expect(mockStartPlanningStreaming).toHaveBeenCalledWith("Build a login system from new task dialog", undefined, undefined, {
|
||||
planningDepth: "medium",
|
||||
customQuestionCount: undefined,
|
||||
}, undefined);
|
||||
}, { timeout: 2000 });
|
||||
|
||||
// Should transition to question view
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("What is the scope?")).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
it("sets initial plan text in textarea when initialPlan prop is provided", async () => {
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
initialPlan="Pre-filled plan from new task"
|
||||
/>
|
||||
);
|
||||
|
||||
// The auto-start should happen with the initial plan (allow time for setTimeout in useEffect)
|
||||
await waitFor(() => {
|
||||
expect(mockStartPlanningStreaming).toHaveBeenCalledWith("Pre-filled plan from new task", undefined, undefined, {
|
||||
planningDepth: "medium",
|
||||
customQuestionCount: undefined,
|
||||
}, undefined);
|
||||
}, { timeout: 2000 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("modal height constraint regression", () => {
|
||||
it("desktop planning modal max-height accounts for overlay padding", async () => {
|
||||
const { container } = render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>
|
||||
);
|
||||
|
||||
const modal = container.querySelector(".planning-modal");
|
||||
expect(modal).toBeTruthy();
|
||||
|
||||
const { loadAllAppCss } = await import("../../test/cssFixture");
|
||||
const css = loadAllAppCss();
|
||||
|
||||
const blockMatch = css.match(
|
||||
/\.planning-modal\s*\{[^}]*max-height:\s*([^;]+);/,
|
||||
);
|
||||
expect(blockMatch).toBeTruthy();
|
||||
|
||||
const maxHeightValue = blockMatch![1].trim();
|
||||
expect(maxHeightValue).toContain("calc(");
|
||||
expect(maxHeightValue).toContain("100dvh");
|
||||
expect(maxHeightValue).toContain("--overlay-padding-top");
|
||||
});
|
||||
|
||||
it("uses planning-scoped disclosure overrides to remove inherited content indent", async () => {
|
||||
const { loadAllAppCssBaseOnly } = await import("../../test/cssFixture");
|
||||
const css = loadAllAppCssBaseOnly();
|
||||
|
||||
const blockMatch = css.match(
|
||||
/\.planning-advanced-disclosure\s+\.onboarding-disclosure-content\s*\{[^}]*\}/,
|
||||
);
|
||||
expect(blockMatch).toBeTruthy();
|
||||
expect(blockMatch![0]).toContain("padding-inline-start: 0;");
|
||||
expect(blockMatch![0]).toContain("justify-content: center;");
|
||||
});
|
||||
|
||||
it("keeps mobile question view top spacing compact", async () => {
|
||||
const { loadAllAppCss } = await import("../../test/cssFixture");
|
||||
const css = loadAllAppCss();
|
||||
const mobileBlocks = getMediaBlocks(css, "@media (max-width: 768px)");
|
||||
const mobileCss = mobileBlocks.join("\n");
|
||||
|
||||
expect(mobileCss).toContain(".planning-question-scroll");
|
||||
expect(mobileCss).toContain("padding-top: var(--space-sm);");
|
||||
expect(mobileCss).toContain("gap: var(--space-md);");
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,200 @@
|
||||
import { vi } from "vitest";
|
||||
import type { Task, TaskDetail, PlanningQuestion, PlanningSummary, MergeResult } from "@fusion/core";
|
||||
|
||||
export const mockStartPlanning = vi.fn();
|
||||
export const mockStartPlanningStreaming = vi.fn();
|
||||
export const mockCreatePlanningDraft = vi.fn();
|
||||
export const mockConnectPlanningStream = vi.fn();
|
||||
export const mockRespondToPlanning = vi.fn();
|
||||
export const mockRetryPlanningSession = vi.fn();
|
||||
export const mockCancelPlanning = vi.fn();
|
||||
export const mockStopPlanningGeneration = vi.fn();
|
||||
export const mockUpdatePlanningSessionDraft = vi.fn();
|
||||
export const mockCreateTaskFromPlanning = vi.fn();
|
||||
export const mockStartPlanningBreakdown = vi.fn();
|
||||
export const mockCreateTasksFromPlanning = vi.fn();
|
||||
export const mockFetchAiSession = vi.fn();
|
||||
export const mockParseConversationHistory = vi.fn();
|
||||
export const mockFetchModels = vi.fn();
|
||||
export const mockAcquireSessionLock = vi.fn();
|
||||
export const mockReleaseSessionLock = vi.fn();
|
||||
export const mockForceAcquireSessionLock = vi.fn();
|
||||
export const mockUploadAttachment = vi.fn();
|
||||
export const mockDeleteAttachment = vi.fn();
|
||||
export const mockUpdateTask = vi.fn();
|
||||
export const mockPauseTask = vi.fn();
|
||||
export const mockUnpauseTask = vi.fn();
|
||||
export const mockFetchTaskDetail = vi.fn();
|
||||
export const mockRequestSpecRevision = vi.fn();
|
||||
export const mockApprovePlan = vi.fn();
|
||||
export const mockRejectPlan = vi.fn();
|
||||
export const mockRefineTask = vi.fn();
|
||||
export const mockFetchAiSessions = vi.fn();
|
||||
|
||||
export const mockConfirm = vi.fn();
|
||||
|
||||
export const mockUseViewportMode = vi.fn<() => "mobile" | "tablet" | "desktop">(() => "desktop");
|
||||
|
||||
export const mockUseMobileKeyboard = vi.fn<() => {
|
||||
keyboardOverlap: number;
|
||||
viewportHeight: number | null;
|
||||
viewportOffsetTop: number;
|
||||
keyboardOpen: boolean;
|
||||
}>(() => ({
|
||||
keyboardOverlap: 0,
|
||||
viewportHeight: null,
|
||||
viewportOffsetTop: 0,
|
||||
keyboardOpen: false,
|
||||
}));
|
||||
|
||||
export const mockTasks: Task[] = [
|
||||
{
|
||||
id: "FN-001",
|
||||
description: "Existing task 1",
|
||||
column: "todo",
|
||||
dependencies: [],
|
||||
steps: [],
|
||||
currentStep: 0,
|
||||
log: [],
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
];
|
||||
|
||||
export const mockModels = [
|
||||
{
|
||||
provider: "anthropic",
|
||||
id: "claude-sonnet-4-5",
|
||||
name: "Claude Sonnet 4.5",
|
||||
reasoning: true,
|
||||
contextWindow: 200000,
|
||||
},
|
||||
{
|
||||
provider: "google",
|
||||
id: "gemini-2.5-pro",
|
||||
name: "Gemini 2.5 Pro",
|
||||
reasoning: true,
|
||||
contextWindow: 1048576,
|
||||
},
|
||||
];
|
||||
|
||||
export const mockQuestion: PlanningQuestion = {
|
||||
id: "q-scope",
|
||||
type: "single_select",
|
||||
question: "What is the scope?",
|
||||
description: "Choose the scope of this task",
|
||||
options: [
|
||||
{ id: "small", label: "Small" },
|
||||
{ id: "medium", label: "Medium" },
|
||||
{ id: "large", label: "Large" },
|
||||
],
|
||||
};
|
||||
|
||||
export const mockSummary: PlanningSummary = {
|
||||
title: "Build authentication system",
|
||||
description: "Implement user auth with login and signup",
|
||||
suggestedSize: "M",
|
||||
suggestedDependencies: [],
|
||||
keyDeliverables: ["Login page", "Signup page", "Auth API"],
|
||||
};
|
||||
|
||||
export const mockTaskDetail = {
|
||||
id: "KB-999",
|
||||
title: "Example task",
|
||||
description: "Example description",
|
||||
column: "todo",
|
||||
dependencies: [],
|
||||
steps: [],
|
||||
currentStep: 0,
|
||||
log: [],
|
||||
attachments: [],
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
prompt: "# Task\n\nExample prompt",
|
||||
paused: false,
|
||||
} as TaskDetail;
|
||||
|
||||
export class MockEventSource {
|
||||
static instances: MockEventSource[] = [];
|
||||
|
||||
url: string;
|
||||
closed = false;
|
||||
private listeners = new Map<string, Set<(event: MessageEvent) => void>>();
|
||||
|
||||
constructor(url: string) {
|
||||
this.url = url;
|
||||
MockEventSource.instances.push(this);
|
||||
}
|
||||
|
||||
addEventListener(event: string, listener: (event: MessageEvent) => void): void {
|
||||
const set = this.listeners.get(event) ?? new Set();
|
||||
set.add(listener);
|
||||
this.listeners.set(event, set);
|
||||
}
|
||||
|
||||
removeEventListener(event: string, listener: (event: MessageEvent) => void): void {
|
||||
const set = this.listeners.get(event);
|
||||
if (!set) return;
|
||||
set.delete(listener);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.closed = true;
|
||||
}
|
||||
|
||||
emit(event: string, data: unknown): void {
|
||||
const listeners = this.listeners.get(event);
|
||||
if (!listeners) return;
|
||||
const message = { data: JSON.stringify(data) } as MessageEvent;
|
||||
listeners.forEach((listener) => listener(message));
|
||||
}
|
||||
|
||||
static reset(): void {
|
||||
MockEventSource.instances = [];
|
||||
}
|
||||
}
|
||||
|
||||
export function getMediaBlocks(css: string, mediaQuery: string): string[] {
|
||||
const blocks: string[] = [];
|
||||
let searchStart = 0;
|
||||
|
||||
while (searchStart < css.length) {
|
||||
const start = css.indexOf(mediaQuery, searchStart);
|
||||
if (start === -1) break;
|
||||
|
||||
const blockStart = css.indexOf("{", start);
|
||||
if (blockStart === -1) break;
|
||||
|
||||
let depth = 1;
|
||||
let cursor = blockStart + 1;
|
||||
while (cursor < css.length && depth > 0) {
|
||||
if (css[cursor] === "{") depth += 1;
|
||||
else if (css[cursor] === "}") depth -= 1;
|
||||
cursor += 1;
|
||||
}
|
||||
|
||||
blocks.push(css.slice(start, cursor));
|
||||
searchStart = cursor;
|
||||
}
|
||||
|
||||
return blocks;
|
||||
}
|
||||
|
||||
export function mockViewport(mode: "mobile" | "desktop" | "tablet") {
|
||||
mockUseViewportMode.mockReturnValue(mode);
|
||||
Object.defineProperty(window, "matchMedia", {
|
||||
writable: true,
|
||||
value: vi.fn().mockImplementation((query: string) => {
|
||||
const isMobileQuery = query === "(max-width: 768px)";
|
||||
const isTabletQuery = query === "(min-width: 769px) and (max-width: 1024px)";
|
||||
return {
|
||||
matches: mode === "mobile" ? isMobileQuery : mode === "tablet" ? isTabletQuery : false,
|
||||
media: query,
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
};
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
export type { Task, TaskDetail, PlanningQuestion, PlanningSummary, MergeResult };
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,722 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { act, render, renderHook, screen, fireEvent, waitFor, within } from "@testing-library/react";
|
||||
import * as api from "../../api";
|
||||
import { PlanningModeModal } from "../PlanningModeModal";
|
||||
import { TaskDetailModal } from "../TaskDetailModal";
|
||||
import { useSessionLock } from "../../hooks/useSessionLock";
|
||||
import { getSessionTabId } from "../../utils/getSessionTabId";
|
||||
import type { MergeResult } from "@fusion/core";
|
||||
import {
|
||||
mockStartPlanning,
|
||||
mockStartPlanningStreaming,
|
||||
mockCreatePlanningDraft,
|
||||
mockConnectPlanningStream,
|
||||
mockRespondToPlanning,
|
||||
mockRetryPlanningSession,
|
||||
mockCancelPlanning,
|
||||
mockStopPlanningGeneration,
|
||||
mockUpdatePlanningSessionDraft,
|
||||
mockCreateTaskFromPlanning,
|
||||
mockStartPlanningBreakdown,
|
||||
mockCreateTasksFromPlanning,
|
||||
mockFetchAiSession,
|
||||
mockParseConversationHistory,
|
||||
mockFetchModels,
|
||||
mockAcquireSessionLock,
|
||||
mockReleaseSessionLock,
|
||||
mockForceAcquireSessionLock,
|
||||
mockUploadAttachment,
|
||||
mockDeleteAttachment,
|
||||
mockUpdateTask,
|
||||
mockPauseTask,
|
||||
mockUnpauseTask,
|
||||
mockFetchTaskDetail,
|
||||
mockRequestSpecRevision,
|
||||
mockApprovePlan,
|
||||
mockRejectPlan,
|
||||
mockRefineTask,
|
||||
mockFetchAiSessions,
|
||||
mockConfirm,
|
||||
mockUseViewportMode,
|
||||
mockUseMobileKeyboard,
|
||||
mockTasks,
|
||||
mockModels,
|
||||
mockQuestion,
|
||||
mockSummary,
|
||||
mockTaskDetail,
|
||||
MockEventSource,
|
||||
getMediaBlocks,
|
||||
mockViewport,
|
||||
} from "./PlanningModeModal.test-helpers";
|
||||
|
||||
vi.mock("../../api", () => ({
|
||||
startPlanning: (...args: any[]) => mockStartPlanning(...args),
|
||||
startPlanningStreaming: (...args: any[]) => mockStartPlanningStreaming(...args),
|
||||
createPlanningDraft: (...args: any[]) => mockCreatePlanningDraft(...args),
|
||||
connectPlanningStream: (...args: any[]) => mockConnectPlanningStream(...args),
|
||||
respondToPlanning: (...args: any[]) => mockRespondToPlanning(...args),
|
||||
retryPlanningSession: (...args: any[]) => mockRetryPlanningSession(...args),
|
||||
cancelPlanning: (...args: any[]) => mockCancelPlanning(...args),
|
||||
stopPlanningGeneration: (...args: any[]) => mockStopPlanningGeneration(...args),
|
||||
updatePlanningSessionDraft: (...args: any[]) => mockUpdatePlanningSessionDraft(...args),
|
||||
createTaskFromPlanning: (...args: any[]) => mockCreateTaskFromPlanning(...args),
|
||||
startPlanningBreakdown: (...args: any[]) => mockStartPlanningBreakdown(...args),
|
||||
createTasksFromPlanning: (...args: any[]) => mockCreateTasksFromPlanning(...args),
|
||||
fetchAiSession: (...args: any[]) => mockFetchAiSession(...args),
|
||||
parseConversationHistory: (...args: any[]) => mockParseConversationHistory(...args),
|
||||
acquireSessionLock: (...args: any[]) => mockAcquireSessionLock(...args),
|
||||
releaseSessionLock: (...args: any[]) => mockReleaseSessionLock(...args),
|
||||
forceAcquireSessionLock: (...args: any[]) => mockForceAcquireSessionLock(...args),
|
||||
uploadAttachment: (...args: any[]) => mockUploadAttachment(...args),
|
||||
deleteAttachment: (...args: any[]) => mockDeleteAttachment(...args),
|
||||
updateTask: (...args: any[]) => mockUpdateTask(...args),
|
||||
pauseTask: (...args: any[]) => mockPauseTask(...args),
|
||||
unpauseTask: (...args: any[]) => mockUnpauseTask(...args),
|
||||
fetchTaskDetail: (...args: any[]) => mockFetchTaskDetail(...args),
|
||||
requestSpecRevision: (...args: any[]) => mockRequestSpecRevision(...args),
|
||||
approvePlan: (...args: any[]) => mockApprovePlan(...args),
|
||||
rejectPlan: (...args: any[]) => mockRejectPlan(...args),
|
||||
refineTask: (...args: any[]) => mockRefineTask(...args),
|
||||
fetchSettings: vi.fn().mockResolvedValue({ modelPresets: [], autoSelectModelPreset: false, defaultPresetBySize: {} }),
|
||||
fetchModels: (...args: any[]) => mockFetchModels(...args),
|
||||
fetchWorkflowSteps: vi.fn().mockResolvedValue([]),
|
||||
refineText: vi.fn(),
|
||||
getRefineErrorMessage: vi.fn((err: any) => err?.message || "Failed to refine"),
|
||||
updateGlobalSettings: vi.fn().mockResolvedValue({}),
|
||||
duplicateTask: vi.fn().mockResolvedValue({}),
|
||||
fetchAiSessions: (...args: any[]) => mockFetchAiSessions(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../../hooks/useConfirm", () => ({
|
||||
useConfirm: () => ({ confirm: mockConfirm }),
|
||||
}));
|
||||
|
||||
vi.mock("../../hooks/useViewportMode", () => ({
|
||||
useViewportMode: () => mockUseViewportMode(),
|
||||
}));
|
||||
|
||||
vi.mock("../../hooks/useMobileKeyboard", () => ({
|
||||
useMobileKeyboard: (...args: any[]) => mockUseMobileKeyboard(...args),
|
||||
}));
|
||||
|
||||
describe("PlanningModeModal", () => {
|
||||
const mockOnClose = vi.fn();
|
||||
const mockOnTaskCreated = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockConfirm.mockReset();
|
||||
mockConfirm.mockResolvedValue(true);
|
||||
MockEventSource.reset();
|
||||
vi.stubGlobal("EventSource", MockEventSource as any);
|
||||
window.sessionStorage.clear();
|
||||
// Default to desktop viewport; mobile-specific tests override per-test.
|
||||
mockViewport("desktop");
|
||||
|
||||
// Default mock for streaming
|
||||
mockStartPlanningStreaming.mockResolvedValue({ sessionId: "session-123" });
|
||||
// Server's createDraftSession always returns the placeholder title; the
|
||||
// real summarized title only arrives later via blur/close summarize or
|
||||
// when the session transitions out of draft. Mirror that in the mock so
|
||||
// the sidebar render rule (preview while title === placeholder) behaves
|
||||
// realistically in tests.
|
||||
mockCreatePlanningDraft.mockResolvedValue({ sessionId: "draft-123", title: "New planning session" });
|
||||
mockRetryPlanningSession.mockResolvedValue({ success: true, sessionId: "session-123" });
|
||||
mockStartPlanningBreakdown.mockResolvedValue({ sessionId: "session-123", subtasks: [] });
|
||||
mockFetchAiSession.mockResolvedValue(null);
|
||||
mockFetchAiSessions.mockResolvedValue([]);
|
||||
mockParseConversationHistory.mockImplementation((raw: string) => {
|
||||
if (!raw) return [];
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
return Array.isArray(parsed) ? parsed : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
});
|
||||
mockFetchModels.mockResolvedValue({
|
||||
models: mockModels,
|
||||
favoriteProviders: [],
|
||||
favoriteModels: [],
|
||||
resolvedPlanningProvider: "openai",
|
||||
resolvedPlanningModelId: "gpt-4o",
|
||||
});
|
||||
mockAcquireSessionLock.mockResolvedValue({ acquired: true, currentHolder: null });
|
||||
mockReleaseSessionLock.mockResolvedValue(undefined);
|
||||
mockForceAcquireSessionLock.mockResolvedValue(undefined);
|
||||
mockCancelPlanning.mockResolvedValue(undefined);
|
||||
mockUpdatePlanningSessionDraft.mockResolvedValue({ ok: true });
|
||||
mockStopPlanningGeneration.mockResolvedValue({ success: true });
|
||||
|
||||
// Default: simulate receiving a question after a brief delay
|
||||
mockConnectPlanningStream.mockImplementation((_sessionId: string, _projectId: string | undefined, handlers: any) => {
|
||||
setTimeout(() => {
|
||||
handlers.onQuestion?.(mockQuestion);
|
||||
}, 10);
|
||||
|
||||
return {
|
||||
close: vi.fn(),
|
||||
isConnected: vi.fn().mockReturnValue(true),
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
describe("Modal smoke checks", () => {
|
||||
it("renders TaskDetailModal with the standard detail body structure", () => {
|
||||
const onMoveTask = vi.fn<(_: string, __: any) => Promise<Task>>().mockResolvedValue(mockTasks[0]);
|
||||
const onDeleteTask = vi.fn<(_: string) => Promise<Task>>().mockResolvedValue(mockTasks[0]);
|
||||
const onMergeTask = vi
|
||||
.fn<(_: string) => Promise<MergeResult>>()
|
||||
.mockResolvedValue({ merged: true, branch: "fusion/fn-999", task: mockTasks[0], worktreeRemoved: true, branchDeleted: true });
|
||||
|
||||
const { container } = render(
|
||||
<TaskDetailModal
|
||||
task={mockTaskDetail}
|
||||
tasks={mockTasks}
|
||||
onClose={mockOnClose}
|
||||
onOpenDetail={vi.fn()}
|
||||
onMoveTask={onMoveTask}
|
||||
onDeleteTask={onDeleteTask}
|
||||
onMergeTask={onMergeTask}
|
||||
addToast={vi.fn()}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText("Definition")).toBeDefined();
|
||||
expect(container.querySelector(".detail-body")).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Loading state", () => {
|
||||
it("shows 'Generating next question...' text when loading without streaming content", async () => {
|
||||
// Mock to delay the question response so we stay in loading state
|
||||
mockConnectPlanningStream.mockImplementationOnce((_sessionId: string, _projectId: string | undefined, handlers: any) => {
|
||||
// Don't call any handlers - stay in loading state
|
||||
return {
|
||||
close: vi.fn(),
|
||||
isConnected: vi.fn().mockReturnValue(true),
|
||||
};
|
||||
});
|
||||
|
||||
const { container } = render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>
|
||||
);
|
||||
|
||||
const textarea = screen.getByPlaceholderText(/e.g., Build a user authentication/);
|
||||
fireEvent.change(textarea, { target: { value: "Build auth system" } });
|
||||
fireEvent.click(screen.getByText("Start Planning"));
|
||||
|
||||
// Wait for loading state to appear
|
||||
await waitFor(() => {
|
||||
expect(container.querySelector(".planning-loading")).not.toBeNull();
|
||||
});
|
||||
|
||||
// Should show "Generating next question..." not "Connecting..."
|
||||
expect(screen.getByText("Generating next question...")).toBeDefined();
|
||||
expect(screen.queryByText("Connecting...")).toBeNull();
|
||||
});
|
||||
|
||||
it("shows thinking container even when streaming output is initially empty", async () => {
|
||||
// Mock to delay the question response so we stay in loading state
|
||||
mockConnectPlanningStream.mockImplementationOnce((_sessionId: string, _projectId: string | undefined, handlers: any) => {
|
||||
// Don't call any handlers - stay in loading state
|
||||
return {
|
||||
close: vi.fn(),
|
||||
isConnected: vi.fn().mockReturnValue(true),
|
||||
};
|
||||
});
|
||||
|
||||
const { container } = render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>
|
||||
);
|
||||
|
||||
const textarea = screen.getByPlaceholderText(/e.g., Build a user authentication/);
|
||||
fireEvent.change(textarea, { target: { value: "Build auth system" } });
|
||||
fireEvent.click(screen.getByText("Start Planning"));
|
||||
|
||||
// Wait for loading state to appear
|
||||
await waitFor(() => {
|
||||
expect(container.querySelector(".planning-loading")).not.toBeNull();
|
||||
});
|
||||
|
||||
// Thinking container should be visible even without streaming content
|
||||
expect(container.querySelector(".planning-thinking-container")).not.toBeNull();
|
||||
// showThinking defaults to true, so button shows "Hide thinking"
|
||||
expect(screen.getByText("Hide thinking")).toBeDefined();
|
||||
});
|
||||
|
||||
it("shows 'AI is thinking...' text and renders streaming content when it arrives", async () => {
|
||||
let streamHandlers: any = null;
|
||||
|
||||
mockConnectPlanningStream.mockImplementationOnce((_sessionId: string, _projectId: string | undefined, handlers: any) => {
|
||||
streamHandlers = handlers;
|
||||
return {
|
||||
close: vi.fn(),
|
||||
isConnected: vi.fn().mockReturnValue(true),
|
||||
};
|
||||
});
|
||||
|
||||
const { container } = render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>
|
||||
);
|
||||
|
||||
const textarea = screen.getByPlaceholderText(/e.g., Build a user authentication/);
|
||||
fireEvent.change(textarea, { target: { value: "Build auth system" } });
|
||||
fireEvent.click(screen.getByText("Start Planning"));
|
||||
|
||||
// Wait for loading state to appear
|
||||
await waitFor(() => {
|
||||
expect(container.querySelector(".planning-loading")).not.toBeNull();
|
||||
});
|
||||
|
||||
// Initially shows "Generating next question..."
|
||||
expect(screen.getByText("Generating next question...")).toBeDefined();
|
||||
|
||||
// Simulate streaming content arriving
|
||||
await waitFor(() => {
|
||||
streamHandlers.onThinking?.("Analyzing requirements...");
|
||||
});
|
||||
|
||||
// Now should show "AI is thinking..."
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("AI is thinking...")).toBeDefined();
|
||||
});
|
||||
|
||||
// The streaming content should be visible (showThinking defaults to true)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Analyzing requirements...")).toBeDefined();
|
||||
});
|
||||
|
||||
// Click "Hide thinking" to hide the output
|
||||
fireEvent.click(screen.getByText("Hide thinking"));
|
||||
|
||||
// The output should now be hidden
|
||||
expect(screen.queryByText("Analyzing requirements...")).toBeNull();
|
||||
});
|
||||
|
||||
it("shows loading state with appropriate text after submitting a response", async () => {
|
||||
const secondQuestion: PlanningQuestion = {
|
||||
id: "q-requirements",
|
||||
type: "text",
|
||||
question: "What are the key requirements?",
|
||||
description: "Describe the requirements",
|
||||
};
|
||||
|
||||
let streamHandlers: any = null;
|
||||
|
||||
mockConnectPlanningStream.mockImplementation((_sessionId: string, _projectId: string | undefined, handlers: any) => {
|
||||
streamHandlers = handlers;
|
||||
|
||||
setTimeout(() => {
|
||||
handlers.onQuestion?.(mockQuestion);
|
||||
}, 10);
|
||||
|
||||
return {
|
||||
close: vi.fn(),
|
||||
isConnected: vi.fn().mockReturnValue(true),
|
||||
};
|
||||
});
|
||||
|
||||
mockRespondToPlanning.mockImplementation(async () => {
|
||||
// Simulate server broadcasting second question via the existing SSE connection
|
||||
setTimeout(() => {
|
||||
if (streamHandlers) {
|
||||
streamHandlers.onQuestion?.(secondQuestion);
|
||||
}
|
||||
}, 50);
|
||||
return { sessionId: "session-123", currentQuestion: null, summary: null };
|
||||
});
|
||||
|
||||
const { container } = render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>
|
||||
);
|
||||
|
||||
const textarea = screen.getByPlaceholderText(/e.g., Build a user authentication/);
|
||||
fireEvent.change(textarea, { target: { value: "Build auth system" } });
|
||||
fireEvent.click(screen.getByText("Start Planning"));
|
||||
|
||||
// Wait for first question
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("What is the scope?")).toBeDefined();
|
||||
});
|
||||
|
||||
// Answer the first question
|
||||
fireEvent.click(screen.getByText("Medium"));
|
||||
fireEvent.click(screen.getByText("Continue"));
|
||||
|
||||
// Verify loading state appears with correct message
|
||||
await waitFor(() => {
|
||||
expect(container.querySelector(".planning-loading")).not.toBeNull();
|
||||
expect(screen.getByText("Generating next question...")).toBeDefined();
|
||||
});
|
||||
|
||||
// Verify thinking container is visible during loading
|
||||
expect(container.querySelector(".planning-thinking-container")).not.toBeNull();
|
||||
|
||||
// Wait for second question to appear
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("What are the key requirements?")).toBeDefined();
|
||||
}, { timeout: 3000 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Modal close behavior", () => {
|
||||
it("no confirmation shown when no progress made (initial state)", () => {
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>
|
||||
);
|
||||
|
||||
// Click X button while still in initial state (no planning started)
|
||||
const closeButton = screen.getByLabelText("Close");
|
||||
fireEvent.click(closeButton);
|
||||
|
||||
expect(mockConfirm).not.toHaveBeenCalled();
|
||||
expect(mockCancelPlanning).not.toHaveBeenCalled();
|
||||
expect(mockOnClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("closes active question session WITHOUT abandoning the server session", async () => {
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>
|
||||
);
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText(/e.g., Build a user authentication/), {
|
||||
target: { value: "Build auth system" },
|
||||
});
|
||||
fireEvent.click(screen.getByText("Start Planning"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("What is the scope?")).toBeDefined();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByLabelText("Close"));
|
||||
|
||||
expect(mockConfirm).not.toHaveBeenCalled();
|
||||
// Closing the modal should leave the server session intact so it stays in the sidebar list
|
||||
expect(mockCancelPlanning).not.toHaveBeenCalled();
|
||||
expect(mockOnClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("closes summary view WITHOUT abandoning the server session", async () => {
|
||||
mockConnectPlanningStream.mockImplementationOnce((_sessionId: string, _projectId: string | undefined, handlers: any) => {
|
||||
setTimeout(() => {
|
||||
handlers.onSummary?.(mockSummary);
|
||||
}, 10);
|
||||
|
||||
return {
|
||||
close: vi.fn(),
|
||||
isConnected: vi.fn().mockReturnValue(true),
|
||||
};
|
||||
});
|
||||
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>
|
||||
);
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText(/e.g., Build a user authentication/), {
|
||||
target: { value: "Build auth system" },
|
||||
});
|
||||
fireEvent.click(screen.getByText("Start Planning"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Planning Complete!")).toBeDefined();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByLabelText("Close"));
|
||||
|
||||
expect(mockConfirm).not.toHaveBeenCalled();
|
||||
// Completed sessions remain available to resume; closing must not cancel them
|
||||
expect(mockCancelPlanning).not.toHaveBeenCalled();
|
||||
expect(mockOnClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("closes via overlay WITHOUT abandoning the server session", async () => {
|
||||
const { container } = render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>
|
||||
);
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText(/e.g., Build a user authentication/), {
|
||||
target: { value: "Build auth system" },
|
||||
});
|
||||
fireEvent.click(screen.getByText("Start Planning"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("What is the scope?")).toBeDefined();
|
||||
});
|
||||
|
||||
const overlay = container.querySelector(".modal-overlay");
|
||||
expect(overlay).not.toBeNull();
|
||||
// Simulate a real overlay click — both mousedown and click must originate
|
||||
// on the overlay, otherwise the dismissal guard suppresses close.
|
||||
fireEvent.mouseDown(overlay!);
|
||||
fireEvent.click(overlay!);
|
||||
|
||||
expect(mockConfirm).not.toHaveBeenCalled();
|
||||
// Sessions persist in the sidebar; overlay click should not cancel
|
||||
expect(mockCancelPlanning).not.toHaveBeenCalled();
|
||||
expect(mockOnClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("closes during loading state WITHOUT abandoning the server session", async () => {
|
||||
mockConnectPlanningStream.mockImplementationOnce(() => ({
|
||||
close: vi.fn(),
|
||||
isConnected: vi.fn().mockReturnValue(true),
|
||||
}));
|
||||
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>
|
||||
);
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText(/e.g., Build a user authentication/), {
|
||||
target: { value: "Build auth system" },
|
||||
});
|
||||
fireEvent.click(screen.getByText("Start Planning"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Generating next question...")).toBeDefined();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByLabelText("Close"));
|
||||
|
||||
expect(mockConfirm).not.toHaveBeenCalled();
|
||||
// Loading state means the session is still being generated server-side; preserve it
|
||||
expect(mockCancelPlanning).not.toHaveBeenCalled();
|
||||
expect(mockOnClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("close (X) drops the local stream but preserves the server session", async () => {
|
||||
// The "Send to background" button was removed — closing the modal now
|
||||
// has the same semantics: tear down the SSE stream, keep the persisted
|
||||
// session alive so the user can reopen and resume it.
|
||||
const closeSpy = vi.fn();
|
||||
|
||||
mockConnectPlanningStream.mockImplementationOnce(() => ({
|
||||
close: closeSpy,
|
||||
isConnected: vi.fn().mockReturnValue(true),
|
||||
}));
|
||||
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>
|
||||
);
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText(/e.g., Build a user authentication/), {
|
||||
target: { value: "Build auth system" },
|
||||
});
|
||||
fireEvent.click(screen.getByText("Start Planning"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Generating next question...")).toBeDefined();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByLabelText("Close"));
|
||||
|
||||
expect(closeSpy).toHaveBeenCalledTimes(1);
|
||||
expect(mockCancelPlanning).not.toHaveBeenCalled();
|
||||
expect(mockOnClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("disconnects the SSE stream on close (but keeps the server session)", async () => {
|
||||
const closeSpy = vi.fn();
|
||||
|
||||
mockConnectPlanningStream.mockImplementationOnce(() => ({
|
||||
close: closeSpy,
|
||||
isConnected: vi.fn().mockReturnValue(true),
|
||||
}));
|
||||
|
||||
render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>
|
||||
);
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText(/e.g., Build a user authentication/), {
|
||||
target: { value: "Build auth system" },
|
||||
});
|
||||
fireEvent.click(screen.getByText("Start Planning"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Generating next question...")).toBeDefined();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByLabelText("Close"));
|
||||
|
||||
expect(closeSpy).toHaveBeenCalledTimes(1);
|
||||
// The local SSE stream closes on modal close, but the server session is preserved
|
||||
// for later resume from the sidebar list.
|
||||
expect(mockCancelPlanning).not.toHaveBeenCalled();
|
||||
expect(mockOnClose).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Mobile empty-session routing (FN-3269)", () => {
|
||||
it("shows detail pane on mobile when session list is empty", async () => {
|
||||
mockViewport("mobile");
|
||||
mockFetchAiSessions.mockResolvedValue([]);
|
||||
|
||||
const { container } = render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockFetchAiSessions).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// Wait for the session list to load and the routing effect to fire
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
});
|
||||
|
||||
// The modal body should show detail pane (composer), not list pane
|
||||
const body = container.querySelector(".planning-modal-body");
|
||||
expect(body?.classList.contains("planning-modal-body--show-detail")).toBe(true);
|
||||
expect(body?.classList.contains("planning-modal-body--show-list")).toBe(false);
|
||||
|
||||
// The composer textarea should be visible
|
||||
expect(screen.getByPlaceholderText(/e.g., Build a user authentication/)).toBeDefined();
|
||||
});
|
||||
|
||||
it("stays on list pane on mobile when sessions exist", async () => {
|
||||
mockViewport("mobile");
|
||||
mockFetchAiSessions.mockResolvedValue([
|
||||
{
|
||||
id: "session-existing",
|
||||
type: "planning",
|
||||
status: "complete",
|
||||
title: "Existing session",
|
||||
preview: "An existing planning session",
|
||||
projectId: null,
|
||||
lockedByTab: null,
|
||||
updatedAt: new Date().toISOString(),
|
||||
archived: false,
|
||||
},
|
||||
]);
|
||||
|
||||
const { container } = render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockFetchAiSessions).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// Wait one more tick to let state updates settle
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
});
|
||||
|
||||
// The modal body should show list pane (sidebar), not detail pane
|
||||
const body = container.querySelector(".planning-modal-body");
|
||||
expect(body?.classList.contains("planning-modal-body--show-list")).toBe(true);
|
||||
expect(body?.classList.contains("planning-modal-body--show-detail")).toBe(false);
|
||||
});
|
||||
|
||||
it("does not auto-show detail pane on desktop with empty sessions", async () => {
|
||||
mockViewport("desktop");
|
||||
mockFetchAiSessions.mockResolvedValue([]);
|
||||
|
||||
const { container } = render(
|
||||
<PlanningModeModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onTaskCreated={mockOnTaskCreated}
|
||||
onTasksCreated={vi.fn()}
|
||||
tasks={mockTasks}
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockFetchAiSessions).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// Wait one more tick to let state updates settle
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
});
|
||||
|
||||
// Desktop shows both panes in split view regardless of mobileShowDetail.
|
||||
// Both sidebar and detail pane should be present in the DOM.
|
||||
expect(container.querySelector(".planning-sidebar")).not.toBeNull();
|
||||
expect(container.querySelector(".planning-detail")).not.toBeNull();
|
||||
// The mobile-only back button should NOT be visible (it's gated on mobileShowDetail,
|
||||
// which stays false on desktop since the routing effect skips non-mobile viewports).
|
||||
expect(container.querySelector(".planning-mobile-back")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
Reference in New Issue
Block a user