diff --git a/ui/src/pages/apps/AggregatorConnectDialog.tsx b/ui/src/pages/apps/AggregatorConnectDialog.tsx index 073db9b5b19..d6d12940514 100644 --- a/ui/src/pages/apps/AggregatorConnectDialog.tsx +++ b/ui/src/pages/apps/AggregatorConnectDialog.tsx @@ -35,7 +35,7 @@ export function AggregatorConnectDialog({ app, connections, initialProvider, onC const provider = selected ? remoteMcpProviders[selected.provider] : null; function choose(route: AggregatorAppRoute) { const accounts = connections[route.provider] ?? []; - if (accounts.length === 0) { onNavigate(aggregatorAppConnectHref(route)); onClose(); } + if (accounts.length === 0) onNavigate(aggregatorAppConnectHref(route)); else setSelected(route); } return { if (!open) onClose(); }}> @@ -66,14 +66,14 @@ export function AggregatorConnectDialog({ app, connections, initialProvider, onC : null} {selected.provider === "composio" ? connection.status === "active" && connection.enabled && !isToolConnectionAttentionHealth(connection.healthStatus))} onClose={onClose} - onBack={canChooseProvider ? () => setSelected(null) : undefined} onConnectNew={() => { onNavigate(`${aggregatorAppConnectHref(selected)}&new=1`); onClose(); }} /> : null} + onBack={canChooseProvider ? () => setSelected(null) : undefined} onConnectNew={() => onNavigate(`${aggregatorAppConnectHref(selected)}&new=1`)} /> : null} } {selected?.provider !== "composio" ? {selected ?
{managementUrl ? : null} - +
: null}
: null} diff --git a/ui/src/pages/apps/Browse.aggregatorConnect.test.tsx b/ui/src/pages/apps/Browse.aggregatorConnect.test.tsx new file mode 100644 index 00000000000..568d6a28071 --- /dev/null +++ b/ui/src/pages/apps/Browse.aggregatorConnect.test.tsx @@ -0,0 +1,288 @@ +// @vitest-environment jsdom +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { BrowserRouter, Route, Routes, useLocation } from "react-router-dom"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { getConnectableAppDefinition, type ToolConnection } from "@paperclipai/shared"; +import { BreadcrumbProvider } from "@/context/BreadcrumbContext"; +import { ToastProvider } from "@/context/ToastContext"; +import { TooltipProvider } from "@/components/ui/tooltip"; +import { Browse } from "./Browse"; + +vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + +const fixtures = vi.hoisted(() => ({ + connections: [] as ToolConnection[], +})); + +vi.mock("@/context/CompanyContext", () => ({ + useCompany: () => ({ + selectedCompanyId: "company-1", + selectedCompany: { id: "company-1", issuePrefix: "PAP" }, + }), +})); + +vi.mock("@/hooks/useCloudInstance", () => ({ + useCloudInstance: () => ({ managed: true }), +})); + +vi.mock("@/hooks/useChatConnectorsEnabled", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, useChatConnectorsEnabled: () => ({ enabled: false }) }; +}); + +vi.mock("@/hooks/useMemoryConnectorsEnabled", () => ({ + useMemoryConnectorsEnabled: () => ({ enabled: false }), +})); + +vi.mock("@/hooks/useConnectorAvailability", () => ({ + useConnectorAvailability: () => ({ enabled: () => true }), +})); + +vi.mock("@/api/companies-query", () => ({ + useAccountIdentity: () => ({ userId: "user-1", settled: true }), +})); + +vi.mock("./AssistantConnection", () => ({ + AssistantConnectionTile: () => null, + useAssistantConnections: () => ({ loaded: true, rows: [] }), +})); + +vi.mock("@/hooks/useTailscaleConnections", () => ({ + useTailscaleConnections: () => ({ canManage: false, data: [] }), +})); + +vi.mock("@/api/tools", () => ({ + toolsApi: { + listGallery: vi.fn(async () => ({ apps: [getConnectableAppDefinition("slack")!] })), + listApplications: vi.fn(async () => ({ applications: [] })), + listConnections: vi.fn(async () => ({ connections: fixtures.connections })), + listAggregatorApps: vi.fn(async () => ({ + apps: [], + discovery: { availability: "unavailable" }, + sync: { status: "idle" }, + })), + syncAggregatorApps: vi.fn(async () => ({ + apps: [], + discovery: { availability: "unavailable" }, + sync: { status: "idle" }, + })), + }, +})); + +vi.mock("@/api/chatEndpoints", () => ({ + chatEndpointsApi: { list: vi.fn(async () => []) }, +})); + +vi.mock("@/api/agents", () => ({ + agentsApi: { list: vi.fn(async () => []) }, +})); + +vi.mock("@/api/access", () => ({ + accessApi: { listUserDirectory: vi.fn(async () => ({ users: [] })) }, +})); + +vi.mock("@/api/mcpSkills", () => ({ + mcpSkillsApi: { list: vi.fn(async () => []) }, +})); + +vi.mock("@/api/companySkills", () => ({ + companySkillsApi: { + catalogList: vi.fn(async () => []), + list: vi.fn(async () => []), + installCatalog: vi.fn(), + }, +})); + +function ConnectDestination() { + const location = useLocation(); + return
{`${location.pathname}${location.search}`}
; +} + +function activeComposioConnection(): ToolConnection { + return { + id: "conn-composio-1", + companyId: "company-1", + applicationId: "app-composio-1", + name: "Work Composio", + transport: "mcp_remote", + authKind: "oauth", + status: "active", + enabled: true, + healthStatus: "ok", + connectionPurpose: "tool", + credentialPolicy: "organization", + config: { sourceTemplateKey: "composio" }, + } as unknown as ToolConnection; +} + +let host: HTMLDivElement; +let root: Root; + +beforeEach(() => { + fixtures.connections = []; + host = document.createElement("div"); + document.body.append(host); + root = createRoot(host); +}); + +afterEach(async () => { + await act(async () => { + root.unmount(); + }); + host.remove(); + document.body.innerHTML = ""; + window.history.replaceState({}, "", "/"); + vi.clearAllMocks(); +}); + +async function renderBrowseAt(url: string) { + window.history.replaceState({}, "", url); + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + await act(async () => { + root.render( + + + + + + + } /> + } /> + } /> + + + + + + , + ); + }); +} + +function findButton(label: string | RegExp, container: ParentNode = document): HTMLButtonElement | undefined { + return [...container.querySelectorAll("button")].find((button) => { + const text = button.textContent?.trim() ?? ""; + const aria = button.getAttribute("aria-label") ?? ""; + return typeof label === "string" + ? text === label || aria === label + : label.test(text) || label.test(aria); + }); +} + +describe("Browse aggregator connect dialog navigation", () => { + it("navigates to Composio setup when clicking Composio from Plugins -> Slack -> Connect with no saved Composio gateway", async () => { + await renderBrowseAt("/PAP/apps/plugin/aggregator%3Aslack"); + + await vi.waitFor(() => { + expect(findButton("Connect Slack")).toBeDefined(); + }); + + await act(async () => { + findButton("Connect Slack")!.click(); + }); + + await vi.waitFor(() => { + const dialog = document.querySelector('[role="dialog"]'); + expect(dialog?.textContent).toContain("Connect Slack"); + expect(findButton(/Composio/, dialog!)).toBeDefined(); + }); + + const dialog = document.querySelector('[role="dialog"]')!; + await act(async () => { + findButton(/Composio/, dialog)!.click(); + }); + + expect(`${window.location.pathname}${window.location.search}`).toBe( + "/PAP/apps/connect?source=composio&targetToolkit=slack", + ); + expect(host.querySelector('[data-testid="connect-destination"]')?.textContent).toBe( + "/PAP/apps/connect?source=composio&targetToolkit=slack", + ); + }); + + it("navigates to new Composio account setup instead of bouncing back to /apps when opened via ?source=composio", async () => { + fixtures.connections = [activeComposioConnection()]; + await renderBrowseAt("/PAP/apps?source=composio&targetToolkit=slack"); + + await vi.waitFor(() => { + expect(document.querySelector('[role="dialog"]')?.textContent).toContain( + "Connect Slack through Composio", + ); + }); + + const select = document.querySelector("#composio-app-account") as HTMLSelectElement | null; + expect(select).not.toBeNull(); + await act(async () => { + select!.value = "__new__"; + select!.dispatchEvent(new Event("change", { bubbles: true })); + }); + + await vi.waitFor(() => { + expect(findButton("Connect new account")).toBeDefined(); + }); + + await act(async () => { + findButton("Connect new account")!.click(); + }); + + expect(`${window.location.pathname}${window.location.search}`).toBe( + "/PAP/apps/connect?source=composio&targetToolkit=slack&new=1", + ); + expect(host.querySelector('[data-testid="connect-destination"]')?.textContent).toBe( + "/PAP/apps/connect?source=composio&targetToolkit=slack&new=1", + ); + }); + + it("strips ?source=composio back to /apps when the dialog is dismissed without navigating", async () => { + fixtures.connections = [activeComposioConnection()]; + await renderBrowseAt("/PAP/apps?source=composio&targetToolkit=slack"); + + await vi.waitFor(() => { + expect(document.querySelector('[role="dialog"]')?.textContent).toContain( + "Connect Slack through Composio", + ); + }); + + await act(async () => { + findButton("Back")!.click(); + }); + await vi.waitFor(() => { + expect(findButton("Cancel")).toBeDefined(); + }); + await act(async () => { + findButton("Cancel")!.click(); + }); + + await vi.waitFor(() => { + expect(document.querySelector('[role="dialog"]')).toBeNull(); + }); + expect(`${window.location.pathname}${window.location.search}`).toBe("/PAP/apps"); + }); + + it("stays on the Slack plugin page when the connect dialog is cancelled", async () => { + await renderBrowseAt("/PAP/apps/plugin/aggregator%3Aslack"); + + await vi.waitFor(() => { + expect(findButton("Connect Slack")).toBeDefined(); + }); + + await act(async () => { + findButton("Connect Slack")!.click(); + }); + await vi.waitFor(() => { + expect(findButton("Cancel")).toBeDefined(); + }); + await act(async () => { + findButton("Cancel")!.click(); + }); + + await vi.waitFor(() => { + expect(document.querySelector('[role="dialog"]')).toBeNull(); + }); + expect(`${window.location.pathname}${window.location.search}`).toBe( + "/PAP/apps/plugin/aggregator%3Aslack", + ); + }); +}); diff --git a/ui/src/pages/apps/Browse.tsx b/ui/src/pages/apps/Browse.tsx index 09eeaabe081..2a60da9a586 100644 --- a/ui/src/pages/apps/Browse.tsx +++ b/ui/src/pages/apps/Browse.tsx @@ -51,7 +51,7 @@ import { normalizeConnectionQuery, nativeConnectorRequiresCustomerOAuthApp, } from "@paperclipai/shared"; -import { useNavigate, useParams } from "@/lib/router"; +import { useLocation, useNavigate, useParams } from "@/lib/router"; import { PLUGIN_CATEGORIES, PLUGIN_CATEGORY_ORDER, PLUGIN_GRID, PluginCategories, PluginShelf, PluginTile, isPluginCategoryId, pluginCategoryId, pluginCategorySectionId, type PluginCategoryId, type PluginTileState } from "./PluginMarketplace"; import { aggregatorPluginCategory, groupPluginsByCategory } from "./plugin-categories"; import { PluginSkills } from "./PluginSkills"; @@ -453,6 +453,7 @@ function accountActionHref( * account; unconnected providers retain the same catalog setup flows. */ export function Browse({ renderAccountDetails = (connection) => connection.connectionPurpose === "ai" && !aiConnectionRouterPluginKey(connection) ? : null }: { renderAccountDetails?: (connection: ToolConnection) => ReactNode } = {}) { + const location = useLocation(); const navigate = useNavigate(); const { pluginKey, categoryId: categoryParam } = useParams<{ pluginKey?: string; categoryId?: string }>(); const categoryId = isPluginCategoryId(categoryParam) ? categoryParam : null; @@ -489,13 +490,13 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne useEffect(() => { setQuery(""); setPage(1); setSource("all"); setArcadeToConfigure(null); setAggregatorToConnect(null); setAggregatorToManage(null); setInitialAggregatorProvider(undefined); setConnectionToRemove(null); }, [selectedCompanyId]); useEffect(() => { - const params = new URLSearchParams(window.location.search); + const params = new URLSearchParams(location.search); if (params.get("source") === "installed") setSource("installed"); if (params.get("source") === "composio") { setAggregatorToConnect((params.get("targetToolkit") ? findComposioCatalogApp(params.get("targetToolkit")!) : null) ?? null); setInitialAggregatorProvider("composio"); } - }, [selectedCompanyId]); + }, [selectedCompanyId, location.search]); const galleryQuery = useQuery({ queryKey: queryKeys.apps.gallery(selectedCompanyId ?? "__none__"), @@ -1051,7 +1052,11 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne function closeAggregatorSetup() { setAggregatorToConnect(null); void queryClient.invalidateQueries({ queryKey: ["tools", "aggregator-apps"] }); - if (new URLSearchParams(window.location.search).get("source") === "composio") navigate("/apps", { replace: true }); + if (new URLSearchParams(location.search).get("source") === "composio") navigate("/apps", { replace: true }); + } + function navigateFromAggregatorSetup(href: string) { + setAggregatorToConnect(null); + navigate(href); } function connectAggregator(app: AggregatorAppCatalogEntry) { setInitialAggregatorProvider(undefined); @@ -1296,7 +1301,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne : null} - {aggregatorToConnect && !loading && !loadFailed ? : null} + {aggregatorToConnect && !loading && !loadFailed ? : null} {aggregatorToManage ? aggregatorToManage.app.routes.some(route => route.provider === appConnectionSourceSlug(connection)))} onClose={() => setAggregatorToManage(null)} /> : null} {executorToConfigure ? setExecutorToConfigure(null)} /> : null}