// @vitest-environment jsdom import { act } from "react"; import { createRoot, type Root } from "react-dom/client"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import type { Issue } from "@paperclipai/shared"; import { afterEach, beforeEach, expect, it, vi, type MockInstance } from "vitest"; import { api } from "@/api/client"; import type { TaskPluginPanel } from "@/hooks/useTaskPluginPanels"; import { taskPanelPluginTab, writeTaskSidePanelState } from "@/lib/task-side-panel-state"; import type { ResolvedPluginSlot } from "@/plugins/slots"; import { TooltipProvider } from "@/components/ui/tooltip"; import { TaskSidePanel } from "./TaskSidePanel"; (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; vi.mock("@/lib/router", () => ({ useLocation: () => ({ pathname: "/task", search: "", hash: "", state: null }), useNavigate: () => vi.fn() })); vi.mock("@/plugins/slots", () => ({ PluginSlotMount: ({ slot }: { slot: ResolvedPluginSlot }) =>
{slot.displayName}
})); vi.mock("@/hooks/useAgentChatEnabled", () => ({ useAgentChatEnabled: () => ({ enabled: false }) })); vi.mock("@/hooks/useCoordinatorWorkspaceEnabled", () => ({ useCoordinatorWorkspaceEnabled: () => ({ enabled: false }) })); vi.mock("@/hooks/useTaskBrowsers", () => ({ useTaskBrowsers: () => ({ data: [] }) })); vi.mock("@/hooks/useIssueDocuments", () => ({ useIssueDocuments: () => ({ data: [] }) })); vi.mock("@/hooks/useIssuePlanDocument", () => ({ useIssuePlanDocument: () => ({ data: null }) })); const issue = { id: "task", companyId: "company", identifier: "TASK-1", title: "Task" } as Issue; function panel(pluginId: string, displayName: string, closePath?: string, runId: string | null = "run"): TaskPluginPanel { const slot = { type: "detailTab", id: "screen", displayName, exportName: "View", entityTypes: ["agent"], pluginId, pluginKey: `example.${pluginId}`, pluginDisplayName: displayName, pluginVersion: "1.0.0", taskSidePanel: { availabilityPath: "/agents/:entityId/view/availability", ...(closePath ? { closePath } : {}) } } as ResolvedPluginSlot; return { entityId: "agent", ...(runId ? { runId } : {}), autoOpen: false, slot }; } const live = panel("live-view", "Live view", "/agents/:entityId/view/close"); const other = panel("other-view", "Other view", "/views/:entityId/release"); let root: Root, container: HTMLDivElement, client: QueryClient, post: MockInstance; function seed(panels: TaskPluginPanel[], activeTabId: string) { writeTaskSidePanelState("account", issue.companyId, issue.id, { state: { tabs: panels.map(taskPanelPluginTab), activeTabId }, launcherOpen: false, userInteracted: true, autoPlanHandled: true, updatedAt: Date.now() }); } async function render(pluginPanels: TaskPluginPanel[]) { await act(async () => root.render( undefined} /> )); } function button(label: string) { const element = container.querySelector(`button[aria-label="${label}"]`); if (!element) throw new Error(`Missing ${label}`); return element; } async function click(label: string) { await act(async () => button(label).click()); } beforeEach(() => { window.localStorage.clear(); vi.stubGlobal("ResizeObserver", class { observe() {} unobserve() {} disconnect() {} }); Element.prototype.scrollTo = () => undefined; client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); container = document.createElement("div"); document.body.append(container); root = createRoot(container); vi.spyOn(api, "get").mockResolvedValue([]); post = vi.spyOn(api, "post").mockResolvedValue({}); }); afterEach(async () => { await act(async () => root.unmount()); client.clear(); container.remove(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); it("tells the plugin once when the person closes the active panel tab", async () => { seed([live, other], "plugin:example.live-view:screen:agent"); await render([live, other]); expect(container.querySelector("[data-testid=plugin-view]")?.textContent).toBe("Live view"); await click("Close Live view"); expect(post).toHaveBeenCalledTimes(1); expect(post).toHaveBeenCalledWith("/plugins/live-view/api/agents/agent/view/close?runId=run&issueId=task", {}); }); it("tells the plugin when the person closes a background panel tab that is not mounted", async () => { seed([live, other], "plugin:example.live-view:screen:agent"); await render([live, other]); expect(container.textContent).not.toContain("Other view"); await click("Close Other view"); expect(post).toHaveBeenCalledTimes(1); expect(post).toHaveBeenCalledWith("/plugins/other-view/api/views/agent/release?runId=run&issueId=task", {}); expect(container.querySelector("[data-testid=plugin-view]")?.textContent).toBe("Live view"); }); it("sends nothing when the person switches tabs or leaves the task", async () => { seed([live, other], "plugin:example.live-view:screen:agent"); await render([live, other]); await click("Other view"); expect(container.querySelector("[data-testid=plugin-view]")?.textContent).toBe("Other view"); await click("Live view"); await act(async () => root.unmount()); root = createRoot(container); expect(post).not.toHaveBeenCalled(); }); it("sends nothing when Core removes a panel that stopped being available", async () => { seed([live, other], "plugin:example.live-view:screen:agent"); await render([live, other]); await render([other]); expect(container.textContent).not.toContain("Live view"); expect(post).not.toHaveBeenCalled(); }); it("sends nothing for a panel without a close route", async () => { const plain = panel("plain-view", "Plain view"); seed([plain], "plugin:example.plain-view:screen:agent"); await render([plain]); await click("Close Plain view"); expect(post).not.toHaveBeenCalled(); expect(container.querySelector("[data-testid=plugin-view]")).toBeNull(); }); it("omits the run for an idle task and closes the tab even when the request fails", async () => { const idle = panel("live-view", "Live view", "/agents/:entityId/view/close", null); seed([idle], "plugin:example.live-view:screen:agent"); post.mockRejectedValue(new Error("offline")); const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); await render([idle]); await click("Close Live view"); await act(async () => undefined); expect(post).toHaveBeenCalledExactlyOnceWith("/plugins/live-view/api/agents/agent/view/close?issueId=task", {}); expect(container.querySelector("[data-testid=plugin-view]")).toBeNull(); expect(warn).toHaveBeenCalledTimes(1); });