mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 09:39:53 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The Plugins page is where a person connects tools to agents and approves the actions that those tools request > - #22869 turned Connectors into a Plugins marketplace. Three review findings stayed open after the merge > - The page also did not show clearly which account needs attention, and the Reviews page was a plain queue > - A person must see what waits for a decision and must be able to leave a setup step > - This pull request fixes the three findings, adds a review chip and a Reviews page with decision cards, marks the account rows that need attention, and adds a Close button to the chat connection purpose step > - The benefit is a Plugins page that shows pending work, and permission controls that do not accept changes on stale data ## Linked Issues or Issue Description Refs #22869 **What existing behavior does this improve?** The Plugins marketplace pages under `ui/src/pages/apps`: the plugin page, the header, the Reviews page, and the chat connection setup. **Subsystem affected** UI, Plugins (Apps catalog) pages. **Current behavior** - After a failed refresh of the permissions, the menus stay enabled and work on stale data. - The plugin page shows a different category from Browse for Composio and Arcade apps. - Browse classifies each plugin one time for each category on each render. - A chat connection that needs attention shows only text in its row. - The header shows a count only. The Reviews page shows a plain queue. - The "Choose how to connect" step has no control to leave the flow. **Proposed behavior** - After a failed refresh, the actions stay visible, the menus are disabled, and a status line offers "Try again". - The plugin page uses the same category as Browse. - Browse classifies each plugin one time for each render. - A chat connection row that needs attention shows a small warning glyph with a text alternative. - The header shows the logos of the plugins with pending requests (maximum four), an "N to review" chip, and a chevron. It opens the Reviews page. - The Reviews page shows a back button, a title, a count sentence, and one decision card for each request with "Decline" and "Allow once". - The "Choose how to connect" step has a Close button that returns to Plugins. **Reason and benefit** A person sees what waits for a decision and where. Permission changes do not run on stale data. The render cost of Browse does not grow with the number of categories. **Breaking changes** None. The default layout of the review queue on the app detail page does not change. ## What Changed - `plugin-categories.ts`: add `groupPluginsByCategory`, a single pass that classifies each row one time. `Browse.tsx` uses it. - `Browse.tsx`: the plugin page reads its category label from the same function as Browse. Chat connection rows show a warning glyph when `chatEndpointAttention` returns a reason. - `PluginPermissions.tsx`: `staleReads` finds the reads with an error. The menus are disabled while a read is stale, and a status line with "Try again" refetches the stale queries. - `useReviewCount.ts`: add `useReviewQueue`, which returns the count and the application names from the same query. - `PluginsHeader.tsx`: the review button shows stacked plugin logos, the count chip, and a chevron. - `AppsReview.tsx` and `ReviewQueueCard.tsx`: the Reviews page has a header and a `decisions` layout that reuses the coordinator decision card parts. - `ChatEndpointSetup.tsx`: `ChatConnectionPurpose` accepts `onClose` and shows a Close button. - `Browse.tsx`, `PluginMarketplace.tsx`, `AssistantConnection.tsx`: the Installed tab shows the same tiles as the rest of the page. The account rows stay on the plugin page. Assistant Connection (MCP) has a tile of its own. - `ReviewQueueCard.tsx` (review fixes): linked requests use the compact decision presentation of the interaction card, the fallback card is masked as a whole, and the agents list is indexed by id one time. - Specs: `connection-reviews` reads the "Deny" label. `agentmail`, `ai-connections-app`, and `runner-e2e/connection-flow` open the plugin page from an Installed tile. ## Verification These checks ran on the change before the rebase onto current master. The rebase did not touch `ui/src/pages/apps`. - `cd ui && pnpm typecheck`: pass. - `cd ui && npx vitest run src/pages/apps src/features/connections src/lib/analytics`: 539 tests pass. - `pnpm run check:token-gates`: pass. - `node scripts/check-query-error-rendering.mjs`: 0 findings. - Playwright specs `connection-reviews`, `plugins-browse`, and `one-click-connect`: 7 tests pass. - Manual check in a browser with four sample requests: the header chip and the Reviews page render the logos, the count, and the cards. - After the Installed tiles change: 478 unit tests in `src/pages/apps`, `src/lib/analytics`, and the deep-link routing test pass. The `agentmail`, `plugins-browse`, and `one-click-connect` Playwright specs pass. A manual check in a browser shows the tiles on the Installed tab. Not run or not seen: - The full UI Vitest suite and the Storybook build did not run locally. CI supplies that coverage. - The Close button and the row warning glyph were not seen in a browser. Unit tests cover them. - The decision card layout has no unit test of its own. - The stale-permissions state is tested through the `staleReads` helper only. - The edits to `tests/ai-connections-app/app.spec.ts` and `tests/runner-e2e/connection-flow.ts` did not run locally. ## Risks Low risk. The change is UI only, with no schema or API change. - The decision cards say "Decline", and the "Always allow" action is in a menu. This differs from the design exploration, because the product has no snooze and requests carry no written summary. - The review chip counts pending requests only. It does not count accounts that need attention. - The Installed tab no longer lists account rows. A person opens the plugin page to manage an account or to set a default model account. The "Manage connectors" link on an agent opens the Installed tab. - On an instance without the assistant connection route, the Assistant Connection tile shows the attention mark. ## Model Used Claude Fable 5.2 (`claude-fable-5-2`) in Claude Code, with tool use, code execution, and extended thinking. ## 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) - [ ] 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 - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
178 lines
14 KiB
TypeScript
178 lines
14 KiB
TypeScript
import { useEffect, useState } from "react";
|
||
import { assistantClientNames, mcpAuthorizationHandoffInstructions, mcpInvitation, mcpSetupSteps, type AssistantClient, type McpConnection } from "@paperclipai/shared";
|
||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||
import { Check, Copy, ExternalLink, Globe, Paperclip, Plug, Terminal } from "lucide-react";
|
||
import { publicMcpApi } from "@/api/publicMcp";
|
||
import { QueryErrorState, useQueryView } from "@/components/QueryView";
|
||
import { useCompany } from "@/context/CompanyContext";
|
||
import { useBreadcrumbs } from "@/context/BreadcrumbContext";
|
||
import { Link } from "@/lib/router";
|
||
import { copyTextToClipboard } from "@/lib/clipboard";
|
||
import { deriveInitials, Identity } from "@/components/Identity";
|
||
import { assistantConnectionDisplayName } from "./connection-owner";
|
||
import { AgentSetupPrompt } from "@/components/AgentSetupPrompt";
|
||
import { OpenCodeLogoIcon } from "@/components/OpenCodeLogoIcon";
|
||
import { CompanyPatternIcon } from "@/components/CompanyPatternIcon";
|
||
import { Button } from "@/components/ui/button";
|
||
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||
import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy";
|
||
import { cn } from "@/lib/utils";
|
||
import { PluginTile } from "./PluginMarketplace";
|
||
|
||
export const ASSISTANT_CONNECTION_PATH = "/apps/assistant-connection";
|
||
const connectionsKey = ["mcp-connections"];
|
||
type Assistant = AssistantClient;
|
||
const assistants = assistantClientNames;
|
||
|
||
function AssistantIcon({ assistant }: { assistant: Assistant }) {
|
||
if (assistant === "codex" || assistant === "claude") return <img src={`/brands/${assistant}-color.svg`} alt="" className="size-4 shrink-0" />;
|
||
if (assistant === "opencode") return <span aria-hidden="true" className="inline-flex shrink-0"><OpenCodeLogoIcon className="size-4" /></span>;
|
||
const Icon = assistant === "browser" ? Globe : assistant === "headless" ? Terminal : Plug;
|
||
return <Icon className="size-4" aria-hidden="true" />;
|
||
}
|
||
|
||
export function useAssistantConnections(poll = false) {
|
||
const { selectedCompanyId } = useCompany();
|
||
const query = useQuery({
|
||
queryKey: connectionsKey, queryFn: publicMcpApi.connections,
|
||
enabled: Boolean(selectedCompanyId), refetchInterval: poll ? 5000 : false,
|
||
});
|
||
const view = useQueryView(query);
|
||
return {
|
||
...query,
|
||
view,
|
||
/** Loaded rows are shown through a transient refetch failure (`stale`) as well as `ready`. */
|
||
loaded: view.kind === "ready" || view.kind === "stale",
|
||
rows: (query.data ?? []).filter(row => row.companyId === selectedCompanyId && !row.revokedAt && !row.scopes.includes("paperclip:agent")),
|
||
};
|
||
}
|
||
|
||
/** Inbound assistant access belongs beside the existing outbound connectors. */
|
||
export function AssistantConnectionCard({ onNavigate }: { onNavigate: (href: string) => void }) {
|
||
const connections = useAssistantConnections();
|
||
const active = connections.rows;
|
||
const action = !connections.loaded ? "Open" : active.length ? "Manage" : "Set up";
|
||
return <div role="listitem" data-app-slug="assistant-connection" data-connected={connections.loaded ? String(active.length > 0) : undefined} className="overflow-hidden rounded-xl border border-border">
|
||
<div className="flex flex-wrap items-center gap-3 px-4 py-4">
|
||
<Paperclip className="size-9 shrink-0 p-1 text-foreground" aria-hidden="true" />
|
||
<div className="min-w-0 flex-1">
|
||
<h2 className="text-sm font-semibold text-foreground">Assistant Connection (MCP)</h2>
|
||
<p className="mt-0.5 text-xs text-muted-foreground">Use your Paperclip organization from Codex, Claude, OpenCode, or another assistant.</p>
|
||
</div>
|
||
<Button type="button" size="sm" variant="outline" onClick={() => onNavigate(ASSISTANT_CONNECTION_PATH)} aria-label={`${action} Assistant Connection (MCP)`}>{action}</Button>
|
||
</div>
|
||
{(connections.isPending || connections.view.kind === "reconnecting") && <p className="border-t border-border px-4 py-3 text-xs text-muted-foreground">Checking your connection status…</p>}
|
||
{connections.view.kind === "error" && <div className="border-t border-border px-4 py-3">
|
||
<QueryErrorState error={connections.error} action="load your connection status" onRetry={connections.view.retry} retrying={connections.view.isFetching} />
|
||
</div>}
|
||
{connections.loaded && active.length > 0 && <div className="flex flex-wrap items-center gap-2 border-t border-border px-4 py-3 text-sm">
|
||
{active.map(row => <Identity key={row.id} name={assistantConnectionDisplayName(row)} avatarUrl={row.user?.image} initials={deriveInitials(row.user?.name ?? "You")} size="sm" />)}
|
||
</div>}
|
||
</div>;
|
||
}
|
||
|
||
/** The same entry as a marketplace tile, for the Installed grid. Opening it shows the accounts and any load failure in full. */
|
||
export function AssistantConnectionTile({ onNavigate }: { onNavigate: (href: string) => void }) {
|
||
const connections = useAssistantConnections();
|
||
const failed = connections.view.kind === "error";
|
||
return <PluginTile
|
||
slug="assistant-connection"
|
||
name="Assistant Connection (MCP)"
|
||
description={failed ? "Couldn’t load your connection status. Open it to try again." : "Use your Paperclip organization from Codex, Claude, OpenCode, or another assistant."}
|
||
brandKey="paperclip"
|
||
icon={<Paperclip className="size-8 shrink-0 p-1 text-foreground" aria-hidden="true" />}
|
||
state={failed ? "attention" : connections.loaded && connections.rows.length > 0 ? "connected" : "available"}
|
||
statusLabel={failed ? "Needs attention" : "Connected"}
|
||
action={null}
|
||
onOpen={() => onNavigate(ASSISTANT_CONNECTION_PATH)}
|
||
/>;
|
||
}
|
||
|
||
/** Only copy user-visible, non-secret setup values. Never execute them here. */
|
||
function CopyValue({ value, label }: { value: string; label: string }) {
|
||
const [copied, setCopied] = useState(false);
|
||
const [error, setError] = useState(false);
|
||
useEffect(() => { setCopied(false); setError(false); }, [value]);
|
||
return <div className="space-y-2">
|
||
<div className="flex items-start gap-3 rounded-md border border-border bg-muted/30 p-3">
|
||
<pre className={cn("min-w-0 flex-1 overflow-x-auto whitespace-pre-wrap break-words font-mono text-xs leading-relaxed", ANALYTICS_MASK_CLASS)}>{value}</pre>
|
||
<Button type="button" variant="ghost" size="icon" className="size-8 shrink-0" aria-label={`Copy ${label}`} onClick={async () => {
|
||
try { await copyTextToClipboard(value); setCopied(true); setError(false); }
|
||
catch { setError(true); }
|
||
}}>{copied ? <Check className="size-4" /> : <Copy className="size-4" />}</Button>
|
||
</div>
|
||
<p role="status" className="text-xs text-muted-foreground">{error ? "Couldn’t copy. Select and copy the text above." : copied ? "Copied" : null}</p>
|
||
</div>;
|
||
}
|
||
|
||
/** Setup copy that depends on the instance, not on the request: signed out, or no public URL configured. */
|
||
function setupUnavailableCopy(errorKind: "auth" | "not_found"): string {
|
||
if (errorKind === "auth") return "Sign in to connect an assistant. This requires a Paperclip instance with authenticated user accounts.";
|
||
return "Assistant connections need an authenticated instance with a public HTTPS URL. Ask your instance administrator to configure the public URL, then try again.";
|
||
}
|
||
|
||
export function AssistantConnection({ initialAssistant = "codex" }: { initialAssistant?: Assistant } = {}) {
|
||
const { selectedCompany, selectedCompanyId } = useCompany();
|
||
const { setBreadcrumbs } = useBreadcrumbs();
|
||
const client = useQueryClient();
|
||
const [assistant, setAssistant] = useState<Assistant>(initialAssistant);
|
||
const setup = useQuery({ queryKey: ["mcp-setup"], queryFn: publicMcpApi.setup, refetchOnWindowFocus: "always", refetchOnMount: "always" });
|
||
const setupView = useQueryView(setup);
|
||
const connections = useAssistantConnections(setup.isSuccess);
|
||
const revoke = useMutation({ mutationFn: publicMcpApi.revoke, onSuccess: (_, id) => {
|
||
client.setQueryData<McpConnection[]>(connectionsKey, rows => rows?.filter(row => row.id !== id));
|
||
return client.invalidateQueries({ queryKey: connectionsKey });
|
||
} });
|
||
useEffect(() => {
|
||
setBreadcrumbs([{ label: "Plugins", href: "/apps" }, { label: "Assistant Connection (MCP)" }]);
|
||
return () => setBreadcrumbs([]);
|
||
}, [setBreadcrumbs]);
|
||
if (!selectedCompanyId || !selectedCompany) return <p className="text-sm text-muted-foreground">Select an organization to connect an assistant.</p>;
|
||
const serverUrl = setup.data?.serverUrl ?? "";
|
||
const invitation = serverUrl ? mcpInvitation(serverUrl, { id: selectedCompanyId, name: selectedCompany.name }) : "";
|
||
return <div className="max-w-3xl space-y-6 pb-8">
|
||
<header className="space-y-4">
|
||
<div className="flex items-center gap-3"><Paperclip className="size-7 shrink-0" /><h1 className="text-xl font-semibold">Assistant Connection (MCP)</h1></div>
|
||
<div className="flex items-center gap-3">
|
||
<CompanyPatternIcon companyName={selectedCompany.name} logoUrl={selectedCompany.logoUrl} className="size-12 shrink-0 rounded-lg" />
|
||
<div className="space-y-1"><p className="font-medium">{selectedCompany.name}</p><p className="text-sm text-muted-foreground">Connect your assistant to Paperclip. Review work, create tasks, and follow up using your account’s access to this organization.</p></div>
|
||
</div>
|
||
</header>
|
||
{(setup.isPending || setupView.kind === "reconnecting") && <p className="text-sm text-muted-foreground">Loading assistant setup…</p>}
|
||
{setupView.kind === "error" && (setupView.errorKind === "auth" || setupView.errorKind === "not_found"
|
||
? <div role="alert" className="space-y-3"><p className="text-sm text-destructive">{setupUnavailableCopy(setupView.errorKind)}</p><Button variant="outline" disabled={setupView.isFetching} onClick={setupView.retry}>Try again</Button></div>
|
||
: <QueryErrorState error={setup.error} action="load assistant setup" onRetry={setupView.retry} retrying={setupView.isFetching} />)}
|
||
{setup.data && <>
|
||
<section className="space-y-4" aria-label="Invite your assistant">
|
||
<p className="text-sm text-muted-foreground">Paste this invitation into your assistant. It will help set up the connection and ask you to approve access in Paperclip.</p>
|
||
<div className="flex justify-end">
|
||
<AgentSetupPrompt prompt={invitation} label="Copy invitation" title="Invite your assistant" description="Paste this invitation into your assistant. It will help set up the connection and ask you to approve access in Paperclip." side="bottom" align="end" />
|
||
</div>
|
||
</section>
|
||
<details className="space-y-4 text-sm">
|
||
<summary className="cursor-pointer text-muted-foreground">Set up manually</summary>
|
||
<Tabs value={assistant} onValueChange={value => setAssistant(value as Assistant)} className="min-w-0"><div className="overflow-x-auto overflow-y-hidden scrollbar-none border-b border-border"><TabsList variant="line" className="min-w-full justify-start" aria-label="Assistant setup instructions">{Object.entries(assistants).map(([value, name]) => <TabsTrigger key={value} value={value} className="flex-none"><AssistantIcon assistant={value as Assistant} />{name}</TabsTrigger>)}</TabsList></div></Tabs>
|
||
<section className="space-y-4" aria-label={`Set up ${assistants[assistant]}`}>
|
||
{mcpSetupSteps(serverUrl, assistant).map((step, index) => <div key={`${assistant}-${index}`} className="space-y-2"><p className="text-sm text-muted-foreground">{step.text}</p>{step.code && <CopyValue value={step.code} label={`${assistants[assistant]} setup step ${index + 1}`} />}</div>)}
|
||
{assistant !== "browser" && <p className="text-sm text-muted-foreground">{mcpAuthorizationHandoffInstructions}</p>}
|
||
<p className="text-sm">Choose <strong>{selectedCompany.name}</strong>, review access, then click <strong>Connect organization</strong>.</p>
|
||
<p className="text-xs text-muted-foreground">Creating tasks and adding comments may start agent work using the organization’s configured execution budget.</p>
|
||
</section>
|
||
<CopyValue value={serverUrl} label="MCP server URL" />
|
||
</details>
|
||
</>}
|
||
<section className="space-y-3" aria-labelledby="connected-assistants">
|
||
<h2 id="connected-assistants" className="text-sm font-semibold">Your connected assistants</h2>
|
||
{(connections.isPending || connections.view.kind === "reconnecting") && <p className="text-sm text-muted-foreground">Loading connections…</p>}
|
||
{revoke.error && <p role="alert" className="text-sm text-destructive">Couldn’t revoke this connection. Try again. <button type="button" className="underline" onClick={() => void connections.refetch()}>Refresh</button></p>}
|
||
{connections.view.kind === "error" && <QueryErrorState error={connections.error} action="load your connections" onRetry={connections.view.retry} retrying={connections.view.isFetching} />}
|
||
{connections.loaded && connections.rows.length === 0 && <p className="text-sm text-muted-foreground">No assistants connected to {selectedCompany.name} yet.</p>}
|
||
<div className="divide-y divide-border">{connections.rows.map(row => <div key={row.id} className="flex flex-wrap items-center justify-between gap-3 py-3">
|
||
<div className="min-w-0 flex-1 space-y-1"><Identity name={assistantConnectionDisplayName(row)} avatarUrl={row.user?.image} initials={deriveInitials(row.user?.name ?? "You")} className="font-medium" /><p className="text-xs text-muted-foreground">{`Connected as you · ${row.scopes.includes("paperclip:write") ? "Read and write" : "Read only"}${row.scopes.includes("paperclip:configure") ? " · Configure agents, projects and skills" : ""}`}</p></div>
|
||
<Button variant="outline" size="sm" disabled={revoke.isPending} onClick={() => revoke.mutate(row.id)} aria-label={`Revoke ${assistantConnectionDisplayName(row)}`}>Revoke</Button>
|
||
</div>)}</div>
|
||
</section>
|
||
<footer className="flex items-center justify-between gap-3 border-t border-border pt-4"><Button variant="ghost" asChild><Link to="/apps">Back to Connections</Link></Button><a className="inline-flex items-center gap-1 text-xs text-muted-foreground underline" href={assistant === "opencode" ? "https://opencode.ai/docs/mcp-servers/" : assistant === "claude" ? "https://code.claude.com/docs/en/mcp" : "https://developers.openai.com/codex/mcp"} target="_blank" rel="noreferrer">Setup documentation <ExternalLink className="size-3" /></a></footer>
|
||
</div>;
|
||
}
|