fix(ui): keep Composio connect navigation from closing back to /apps (#23845)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The Plugins page lets users connect third-party apps directly or
through aggregators like Composio and Arcade.
> - When an app offers multiple aggregators, clicking Connect opens
AggregatorConnectDialog so the user can choose a provider.
> - Selecting Composio with no saved Composio gateway, or clicking
Connect new account, called onNavigate and then immediately called
onClose.
> - In Browse, closeAggregatorSetup checked window.location.search for
source=composio, matched the URL that onNavigate had just pushed, and
replaced the route with /apps.
> - This pull request stops in-app dialog navigation from calling
onClose, clears dialog state in Browse's navigation handler, and reads
React Router's location.search instead of window.location.search.
> - The benefit is that choosing Composio or adding a new Composio
account from the connect modal navigates cleanly to /apps/connect while
dismissing the modal still strips ?source=composio.

## Linked Issues or Issue Description

No public GitHub issue exists for this report (searched open and closed
issues and PRs for duplicates).

**What happened?**

When going to Plugins -> Slack -> Connect and clicking Composio without
a saved Composio gateway, the connect modal closed and redirected back
to /apps instead of opening
/apps/connect?source=composio&targetToolkit=slack. The same redirect
happened when opening the modal via
/apps?source=composio&targetToolkit=slack and clicking Connect new
account.

**Expected behavior**

Clicking Composio with no saved Composio gateway navigates to
/apps/connect?source=composio&targetToolkit=slack. Clicking Connect new
account navigates to
/apps/connect?source=composio&targetToolkit=slack&new=1. Dismissing the
modal without navigating still closes it and strips ?source=composio
back to /apps.

**Steps to reproduce**

1. Open Plugins on a Cloud instance where Slack yields to aggregators
and no Composio gateway is saved.
2. Open Slack and click Connect.
3. Click Composio in the Connect Slack dialog.
4. Observe that the dialog closes and the page stays on /apps instead of
navigating to /apps/connect?source=composio&targetToolkit=slack.

**Access context**

Board (human operator)

## What Changed

- Updated `ui/src/pages/apps/AggregatorConnectDialog.tsx` so in-app
navigation handlers (`choose`, `onConnectNew`, and the non-Composio
"Connect a new account" button) call only `onNavigate` without also
invoking `onClose`.
- Updated `ui/src/pages/apps/Browse.tsx` to pass
`navigateFromAggregatorSetup` as `AggregatorConnectDialog`'s
`onNavigate` prop so navigation clears dialog state without triggering
`closeAggregatorSetup`'s `?source=composio` redirect cleanup.
- Switched `Browse.tsx` from `window.location.search` to React Router's
`useLocation().search` for the `?source=...` effect and dismissal
cleanup.
- Added `ui/src/pages/apps/Browse.aggregatorConnect.test.tsx` with real
`BrowserRouter` regression tests covering Plugins -> Slack -> Connect ->
Composio, new-account navigation from `?source=composio`, dismissal
cleanup, and staying on the plugin page when cancelling.

## Verification

- Verified TDD red-before / green-after on
`ui/src/pages/apps/Browse.aggregatorConnect.test.tsx`: before the fix,
both Composio navigation tests failed with `Received: "/PAP/apps"`
instead of `/PAP/apps/connect?source=composio&targetToolkit=slack` and
`...&new=1`.
- Ran `pnpm vitest run
ui/src/pages/apps/Browse.aggregatorConnect.test.tsx
ui/src/pages/apps/Browse.pluginTileState.test.ts
ui/src/pages/apps/AppsConnect.test.tsx
ui/src/lib/analytics/replay-masking.test.tsx` on rebased HEAD
`c605d6358c`: 4 test files, 243 tests passed.
- Ran `pnpm --filter @paperclipai/ui typecheck`: passed with 0 errors.
- CI covers repo-wide typecheck, build, and test suites on the pushed PR
revision.

## Risks

- Low risk. Changes are scoped to `AggregatorConnectDialog` and
`Browse`'s aggregator connect dialog wiring. Dismissal actions (Cancel,
Escape, dialog close, completion, and external management links) still
invoke `closeAggregatorSetup` to invalidate aggregator queries and strip
`?source=composio`.

## Model Used

- Google Gemini 4 (Antigravity agent with extended reasoning and local
tool/test execution).

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-12-04 20:56:22 -06:00
1 parent 2d7bb6392d
commit 042cb67370
3 files changed
+301 -8

No files matched your search

@@ -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 <Dialog open onOpenChange={(open) => { if (!open) onClose(); }}>
@@ -66,14 +66,14 @@ export function AggregatorConnectDialog({ app, connections, initialProvider, onC
</select>
</div> : null}
{selected.provider === "composio" ? <ComposioAppSetup name={app.name} toolkit={selected.toolkit} connections={existing.filter(connection => 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}
</div>}
{selected?.provider !== "composio" ? <DialogFooter className="sm:items-center sm:justify-between">
<Button variant="ghost" onClick={selected && canChooseProvider ? () => setSelected(null) : onClose}>{selected && canChooseProvider ? "Back" : "Cancel"}</Button>
{selected ? <div className="flex flex-wrap items-center gap-3">
{managementUrl ? <Button asChild><a href={managementUrl} target="_blank" rel="noopener noreferrer" onClick={onClose}>Continue<ExternalLink className="size-4" /></a></Button> : null}
<Button variant="link" size="sm" className="h-auto p-0 text-xs text-muted-foreground hover:text-foreground" onClick={() => { onNavigate(`${aggregatorAppConnectHref(selected)}&new=1`); onClose(); }}>Connect a new account</Button>
<Button variant="link" size="sm" className="h-auto p-0 text-xs text-muted-foreground hover:text-foreground" onClick={() => onNavigate(`${aggregatorAppConnectHref(selected)}&new=1`)}>Connect a new account</Button>
</div> : null}
</DialogFooter> : null}
</DialogContent>
@@ -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<typeof import("@/hooks/useChatConnectorsEnabled")>();
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 <div data-testid="connect-destination">{`${location.pathname}${location.search}`}</div>;
}
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(
<QueryClientProvider client={client}>
<ToastProvider>
<BreadcrumbProvider>
<TooltipProvider>
<BrowserRouter>
<Routes>
<Route path="/:companyPrefix/apps" element={<Browse />} />
<Route path="/:companyPrefix/apps/plugin/:pluginKey" element={<Browse />} />
<Route path="/:companyPrefix/apps/connect" element={<ConnectDestination />} />
</Routes>
</BrowserRouter>
</TooltipProvider>
</BreadcrumbProvider>
</ToastProvider>
</QueryClientProvider>,
);
});
}
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",
);
});
});
+10 -5
View File
@@ -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) ? <ManagedAiConnectionRow connection={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
</div>
</nav> : null}
{aggregatorToConnect && !loading && !loadFailed ? <AggregatorConnectDialog key={aggregatorToConnect.slug} app={aggregatorToConnect} initialProvider={initialAggregatorProvider} connections={aggregatorConnections} onClose={closeAggregatorSetup} onNavigate={navigate} /> : null}
{aggregatorToConnect && !loading && !loadFailed ? <AggregatorConnectDialog key={aggregatorToConnect.slug} app={aggregatorToConnect} initialProvider={initialAggregatorProvider} connections={aggregatorConnections} onClose={closeAggregatorSetup} onNavigate={navigateFromAggregatorSetup} /> : null}
{aggregatorToManage ? <AggregatorAppManager key={aggregatorToManage.app.slug} {...aggregatorToManage} initialConnectionId={aggregatorToManage.connectionId} connections={aggregatorGateways.filter(connection => aggregatorToManage.app.routes.some(route => route.provider === appConnectionSourceSlug(connection)))} onClose={() => setAggregatorToManage(null)} /> : null}
{executorToConfigure ? <ExecutorManagementSetup connection={executorToConfigure} onClose={() => setExecutorToConfigure(null)} /> : null}