Files
PaperClipAI/ui/src/pages/apps/gateways/GatewaysList.tsx
T
DottaandPaperclip 8c3b8c432a Simplify app connections and enable managed Google access (#12728)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The Apps subsystem gives humans and agents governed access to
external tools.
> - The current connection flow hides Apps behind an experimental gate
and repeats setup text.
> - Google sharing choices and generic MCP permissions do not use one
consistent opening model.
> - Self-hosted installs also need a safe default origin for managed
OAuth without a manual config file.
> - This pull request makes Apps available, simplifies connection setup,
and applies one governed permissions model.
> - The benefit is a shorter connection flow that works on a clean
self-hosted install.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

This improves the Apps connection setup flow, managed Google connection
flow, generic MCP connection flow, navigation, and runtime origin
discovery.

**Subsystem affected**

Cross-cutting. This changes `ui/`, `server/`, `packages/shared/`,
connector documentation, and browser tests.

**Current behavior**

Apps require an experimental switch. Setup pages repeat titles and
explanatory copy. Connection names require manual input. Google
credential sharing does not always offer both personal and organization
access. Generic MCP providers do not start with the same permission
choices. Managed OAuth needs a public URL setting even when the request
already has a safe HTTPS origin.

**Proposed behavior**

Apps are available by default. Setup asks only for required permissions
and sharing choices. Paperclip creates conflict-free connection names.
Google apps and generic MCP providers use the same human and agent
access model. Managed OAuth derives a validated same-origin HTTPS URL
when no explicit public URL is set.

**Reason and benefit**

A clean self-hosted install can connect a managed Google app without
hidden setup. Humans can share a service account with their
organization. The shorter flow reduces duplicated choices and setup
errors.

**Breaking changes**

The Apps experimental switch is removed. Existing connection APIs remain
compatible. New connections can receive a numeric suffix when a name
already exists.

No duplicate or related public issue was found.

## What Changed

- Removed the Apps experimental gate and the breadcrumb that leaves the
Apps section.
- Simplified all connection setup pages and moved optional provider
requirements into one small link.
- Added consistent human and agent access choices for Google apps,
Zapier, and generic MCP connections.
- Added organization sharing to Google Workspace credentials while
keeping personal access available.
- Generated connection names automatically and resolved name conflicts
with numeric suffixes.
- Derived a validated public HTTPS origin from the request for
config-free managed OAuth.
- Updated connector contracts, tests, browser coverage, and authoring
documentation.

## Verification

- `pnpm check:token-gates`
- `pnpm -r typecheck`
- `pnpm build`
- `pnpm exec vitest run server/src/__tests__/tool-access-service.test.ts
server/src/__tests__/generic-mcp-connection.test.ts` (273 passed)
- Targeted UI/service regression suite (308 passed)
- Six targeted Playwright connection journeys on a fresh onboarding
instance (6 passed)
- Fresh-install browser proof through Tailscale HTTPS: enrolled with
Paperclip Cloud, connected managed Google Drive, and completed a real
read operation.
- [Exact-head CI
run](https://github.com/paperclipai/paperclip/actions/runs/33669760711):
all 23 matrix jobs passed, including build, typecheck, server,
serialized, canary, and all browser shards.
- Greptile 5/5 on `0ae2a859f269984ee950d0af231a5b09a06f3dfd`, with no
unresolved review threads.

## Risks

Apps are now visible to all operators. The removed experimental flag no
longer hides unfinished app definitions. Managed Google availability
still depends on the Cloud profile rollout and active instance
enrollment. Automatic conflict handling changes only the display name of
a newly conflicting connection.

> I checked [`ROADMAP.md`](ROADMAP.md). MCP Tool Gateway and Apps are
shipped. Connected Apps is planned, and this change improves the
existing shipped connection flow.

## Model Used

OpenAI Codex, GPT-5, with reasoning, browser control, tool use, and code
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
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] 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>
2026-09-02 14:05:53 -05:00

336 lines
14 KiB
TypeScript

import { type ReactNode, useEffect, useMemo, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Plus, Search } from "lucide-react";
import type { ToolMcpGatewayWithTokens } from "@paperclipai/shared";
import { useNavigate } from "@/lib/router";
import { useCompany } from "@/context/CompanyContext";
import { useBreadcrumbs } from "@/context/BreadcrumbContext";
import { useToast } from "@/context/ToastContext";
import { queryKeys } from "@/lib/queryKeys";
import { toolsApi } from "@/api/tools";
import { agentsApi } from "@/api/agents";
import { projectsApi } from "@/api/projects";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Skeleton } from "@/components/ui/skeleton";
import { ToggleSwitch } from "@/components/ui/toggle-switch";
import { ErrorState, RelativeTime } from "@/pages/tools/shared";
import { CopyableGatewayUrl } from "./CopyableGatewayUrl";
import { NewGatewayDialog, gatewaysQueryKey } from "./NewGatewayDialog";
import { gatewayTabHref } from "./gateway-tabs";
import {
activeTokenCount,
allowedToolsLabel,
deriveGatewayApps,
expiringTokenCount,
formatScope,
isGatewayOn,
latestTokenActivity,
} from "./gateway-helpers";
export function GatewaysList() {
const navigate = useNavigate();
const queryClient = useQueryClient();
const { pushToast } = useToast();
const { selectedCompanyId } = useCompany();
const { setBreadcrumbs } = useBreadcrumbs();
const [search, setSearch] = useState("");
const [creating, setCreating] = useState(false);
useEffect(() => {
setBreadcrumbs([
{ label: "Connectors", href: "/apps" },
{ label: "Gateways" },
]);
return () => setBreadcrumbs([]);
}, [setBreadcrumbs]);
const gatewaysQuery = useQuery({
queryKey: gatewaysQueryKey(selectedCompanyId ?? "__none__"),
queryFn: () => toolsApi.listGateways(selectedCompanyId!),
enabled: !!selectedCompanyId,
});
const profilesQuery = useQuery({
queryKey: queryKeys.tools.profiles(selectedCompanyId ?? "__none__"),
queryFn: () => toolsApi.listProfiles(selectedCompanyId!),
enabled: !!selectedCompanyId,
});
const connectionsQuery = useQuery({
queryKey: queryKeys.tools.connections(selectedCompanyId ?? "__none__"),
queryFn: () => toolsApi.listConnections(selectedCompanyId!),
enabled: !!selectedCompanyId,
});
const applicationsQuery = useQuery({
queryKey: queryKeys.tools.applications(selectedCompanyId ?? "__none__"),
queryFn: () => toolsApi.listApplications(selectedCompanyId!),
enabled: !!selectedCompanyId,
});
const agentsQuery = useQuery({
queryKey: queryKeys.agents.list(selectedCompanyId ?? "__none__"),
queryFn: () => agentsApi.list(selectedCompanyId!),
enabled: !!selectedCompanyId,
});
const projectsQuery = useQuery({
queryKey: queryKeys.projects.list(selectedCompanyId ?? "__none__"),
queryFn: () => projectsApi.list(selectedCompanyId!),
enabled: !!selectedCompanyId,
});
const profileById = useMemo(
() => new Map((profilesQuery.data?.profiles ?? []).map((profile) => [profile.id, profile])),
[profilesQuery.data],
);
const agentNames = useMemo(
() => new Map((agentsQuery.data ?? []).map((agent) => [agent.id, agent.name])),
[agentsQuery.data],
);
const projectNames = useMemo(
() => new Map((projectsQuery.data ?? []).map((project) => [project.id, project.name])),
[projectsQuery.data],
);
const toggleMutation = useMutation({
mutationFn: ({ gateway }: { gateway: ToolMcpGatewayWithTokens }) =>
toolsApi.updateGateway(selectedCompanyId!, gateway.id, {
status: isGatewayOn(gateway) ? "disabled" : "active",
}),
onSuccess: async (gateway) => {
pushToast({
title: gateway.status === "active" ? "Gateway on" : "Gateway off",
body:
gateway.status === "active"
? `${gateway.name} is exposing its tools again.`
: `${gateway.name} is off — every client goes silent.`,
tone: "success",
});
await queryClient.invalidateQueries({ queryKey: gatewaysQueryKey(selectedCompanyId!) });
},
onError: (error) =>
pushToast({
title: "Couldn't update the gateway",
body: error instanceof Error ? error.message : String(error),
tone: "error",
}),
});
if (!selectedCompanyId) {
return <div className="p-6 text-sm text-muted-foreground">Select an organization to manage gateways.</div>;
}
const gateways = gatewaysQuery.data?.gateways ?? [];
const term = search.trim().toLowerCase();
const filtered = term
? gateways.filter((gateway) => {
const scope = formatScope(gateway, projectNames, agentNames).toLowerCase();
return (
gateway.name.toLowerCase().includes(term) ||
gateway.displaySlug.toLowerCase().includes(term) ||
scope.includes(term)
);
})
: gateways;
return (
<div className="max-w-5xl space-y-5">
<header className="space-y-1">
<h1 className="text-2xl font-bold tracking-tight">Apps</h1>
<p className="text-sm text-muted-foreground">
A gateway is one safe MCP endpoint that exposes only the apps you assign. Hand it to a client
like Cursor or Claude Desktop.
</p>
</header>
{gatewaysQuery.isLoading ? (
<div className="space-y-3 pt-2">
<Skeleton className="h-9 w-full max-w-sm" />
<Skeleton className="h-52 w-full" />
</div>
) : gatewaysQuery.isError ? (
<ErrorState error={gatewaysQuery.error} onRetry={() => gatewaysQuery.refetch()} />
) : gateways.length === 0 ? (
<EmptyGateways onCreate={() => setCreating(true)} />
) : (
<div className="space-y-4 pt-1">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="relative w-full max-w-sm">
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
value={search}
onChange={(event) => setSearch(event.target.value)}
placeholder="Search by name, app, or owner"
className="pl-9"
aria-label="Search gateways"
/>
</div>
<Button onClick={() => setCreating(true)}>
<Plus className="mr-1.5 h-4 w-4" />
New gateway
</Button>
</div>
{(() => {
const rows = filtered.map((gateway) => {
const profile = profileById.get(gateway.profileId);
const apps = deriveGatewayApps(
profile,
applicationsQuery.data?.applications ?? [],
connectionsQuery.data?.connections ?? [],
);
return {
gateway,
profile,
scope: formatScope(gateway, projectNames, agentNames),
appsLabel: `${apps.length} ${apps.length === 1 ? "app" : "apps"}${
profile ? ` · ${allowedToolsLabel(profile)}` : ""
}`,
active: activeTokenCount(gateway),
expiring: expiringTokenCount(gateway),
lastUsed: latestTokenActivity(gateway),
href: gatewayTabHref(gateway.id, "overview"),
};
});
const toggle = (gateway: ToolMcpGatewayWithTokens) => (
<ToggleSwitch
checked={isGatewayOn(gateway)}
disabled={toggleMutation.isPending}
onClick={(event) => event.stopPropagation()}
onCheckedChange={() => toggleMutation.mutate({ gateway })}
aria-label={`Turn ${gateway.name} ${isGatewayOn(gateway) ? "off" : "on"}`}
/>
);
const empty = (
<div className="px-4 py-8 text-center text-sm text-muted-foreground">
No gateways match “{search.trim()}”.
</div>
);
return (
<>
{/* Desktop / tablet: full table. */}
<div className="hidden overflow-x-auto rounded-lg border border-border sm:block">
<table className="w-full min-w-(--sz-40rem) text-sm">
<thead>
<tr className="border-b border-border bg-muted/40 text-left text-(length:--text-micro) font-semibold uppercase tracking-wide text-muted-foreground">
<th className="whitespace-nowrap px-4 py-2.5">Gateway</th>
<th className="whitespace-nowrap px-4 py-2.5">Scope</th>
<th className="whitespace-nowrap px-4 py-2.5">Apps</th>
<th className="whitespace-nowrap px-4 py-2.5">Tokens</th>
<th className="whitespace-nowrap px-4 py-2.5">Last used</th>
<th className="whitespace-nowrap px-4 py-2.5 text-right">On</th>
</tr>
</thead>
<tbody>
{rows.map(({ gateway, scope, appsLabel, active, expiring, lastUsed, href }) => (
<tr
key={gateway.id}
onClick={() => navigate(href)}
className="cursor-pointer border-b border-border transition-colors last:border-0 hover:bg-muted/30"
>
<td className="w-64 max-w-64 whitespace-nowrap px-4 py-3">
<div className="font-medium text-foreground">{gateway.name}</div>
<CopyableGatewayUrl endpointPath={gateway.endpointPath} />
</td>
<td className="whitespace-nowrap px-4 py-3 text-muted-foreground">{scope}</td>
<td className="whitespace-nowrap px-4 py-3 text-muted-foreground">{appsLabel}</td>
<td className="whitespace-nowrap px-4 py-3 text-muted-foreground">
{active} active{expiring > 0 ? ` · ${expiring} expiring` : ""}
</td>
<td className="whitespace-nowrap px-4 py-3 text-muted-foreground">
{lastUsed ? <RelativeTime value={lastUsed} /> : "—"}
</td>
<td className="px-4 py-3">
<div className="flex justify-end">{toggle(gateway)}</div>
</td>
</tr>
))}
{rows.length === 0 ? (
<tr>
<td colSpan={6}>{empty}</td>
</tr>
) : null}
</tbody>
</table>
</div>
{/* Mobile: stacked cards so the On toggle stays reachable and thumb-sized. */}
<div className="space-y-3 sm:hidden">
{rows.map(({ gateway, scope, appsLabel, active, expiring, lastUsed, href }) => (
<div
key={gateway.id}
onClick={() => navigate(href)}
className="cursor-pointer rounded-lg border border-border p-4 transition-colors hover:bg-muted/30"
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="font-medium text-foreground">{gateway.name}</div>
<CopyableGatewayUrl endpointPath={gateway.endpointPath} />
</div>
<div className="shrink-0">{toggle(gateway)}</div>
</div>
<dl className="mt-3 grid grid-cols-2 gap-x-4 gap-y-2 text-sm">
<MobileField label="Scope" value={scope} />
<MobileField label="Apps" value={appsLabel} />
<MobileField
label="Tokens"
value={`${active} active${expiring > 0 ? ` · ${expiring} expiring` : ""}`}
/>
<MobileField
label="Last used"
value={lastUsed ? <RelativeTime value={lastUsed} /> : "—"}
/>
</dl>
</div>
))}
{rows.length === 0 ? (
<div className="rounded-lg border border-border">{empty}</div>
) : null}
</div>
</>
);
})()}
<div className="rounded-lg border border-border bg-muted/30 px-4 py-3">
<div className="text-sm font-semibold text-foreground">Why a gateway?</div>
<p className="mt-1 text-sm text-muted-foreground">
You pick which apps go through it, who can use it, and how. Revoke the token, the whole
gateway goes silent — no app-by-app cleanup.
</p>
</div>
</div>
)}
<NewGatewayDialog
companyId={selectedCompanyId}
open={creating}
onOpenChange={setCreating}
onCreated={(gatewayId) => navigate(gatewayTabHref(gatewayId, "overview"))}
/>
</div>
);
}
/** One label:value pair inside a mobile stacked card. */
function MobileField({ label, value }: { label: string; value: ReactNode }) {
return (
<div className="min-w-0">
<dt className="text-(length:--text-micro) font-semibold uppercase tracking-wide text-muted-foreground">{label}</dt>
<dd className="mt-0.5 truncate text-foreground">{value}</dd>
</div>
);
}
function EmptyGateways({ onCreate }: { onCreate: () => void }) {
return (
<div className="rounded-2xl border border-dashed border-border p-12 text-center">
<h2 className="text-lg font-semibold text-foreground">No gateways yet</h2>
<p className="mx-auto mt-2 max-w-sm text-sm text-muted-foreground">
Group your connected apps into one safe endpoint you can hand to a client, then revoke it in one
move.
</p>
<Button className="mt-5" onClick={onCreate}>
<Plus className="mr-1.5 h-4 w-4" />
New gateway
</Button>
</div>
);
}