mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-18 05:23:39 +02:00
fix(mcp): personalize assistant connections and hide revoked grants (#15411)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Assistant connections let people use their organization from another assistant. > - Setup begins with an invitation and returns to a list of connected assistants. > - Client-only labels obscure the authorizing person, while revoked rows clutter that list. > - This pull request shows the person’s avatar, names connections by owner and client, and hides revoked rows. > - It also shortens the copied invitation while keeping the approval instructions. ## Linked Issues or Issue Description Related: #14933 and #15380. **What existing behavior does this improve?** Invitation copy and assistant connection management, in the organization’s Connections screen and the account-wide management page. **Subsystem affected** Cross-cutting: shared MCP connection types, server profile projection, UI and Storybook. **Current behavior** Connections are labeled only with a client name such as “Codex.” Revoked connections remain visible. The invitation includes an extra sentence about agent identity. **Proposed behavior** Show the authorizing person’s avatar and use names such as “Dotta’s Codex connection.” Hide revoked rows after successful revocation and when loading retained revoked grants. Failed revocation leaves the connection visible. Remove the extra identity sentence from invitation copy. **Reason and benefit** Make connection identity clear and keep the list focused on usable connections. **Breaking changes** The connection response adds optional `user` metadata with name and image. Older servers remain usable. Names and revoked-row visibility change in the UI; OAuth client identity, authorization and audit retention remain unchanged. ## What Changed - Shorten the shared invitation text. - Project the authorizing person’s name and avatar through the user-scoped connection endpoint, without returning email or credentials. - Reuse the existing Identity component and owner naming conventions across the connection page, catalog card and account-wide list. - Hide revoked grants and remove a successfully revoked row from the shared cache, even if the subsequent refresh fails. - Update documentation, regression tests and production-page Storybook fixtures and revocation journeys. ## Verification - `pnpm -r typecheck`, `pnpm build`, `pnpm build-storybook` and `pnpm check:token-gates` pass. Final UI type checks also pass. - Focused consent and connection UI tests: 31 pass, including company filtering, legacy metadata, custom client names, user-initial fallbacks, failed revocation, retained revoked rows and refresh failure after successful revocation. - Existing MCP regression suite: 6 pass; 71 database checks are skipped locally because embedded PostgreSQL cannot start on this machine. The added database check verifies user-profile isolation and retained revocation history; CI runs these checks. - Browser verification with Storybook fixtures: owner avatar and name render; revocation removes the selected row in both production pages, leaves other connections visible, and restores the empty state after the last revocation. - All 54 current-head CI checks pass, with two optional Storybook jobs skipped. CI includes database, browser, runner, typecheck, build and clean-install canary coverage. - Greptile reviewed commit `1368d79e1066b418712224378d89d64c2b11cb86`: 5/5, no actionable findings or unresolved threads. - The full local `pnpm test:run` was stopped after complete CI passed. Local database coverage remains unavailable because embedded PostgreSQL cannot start; no full local-suite pass is claimed. ## Risks Low risk. The additive profile field is optional for compatibility. Revoked grants are filtered only from management UI and retained for audit. Revocation failure does not hide an active connection. No authorization scopes, token handling or schema changes. ## Model Used OpenAI GPT-6 through Codex, with code editing, command execution and browser verification. The exact deployment ID and context-window size are not exposed in this session. ## 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>
This commit is contained in:
1 parent
a9a20fb5c6
commit
99a9de9940
12 files changed
+132
-33
No files matched your search
+3
-1
@@ -88,7 +88,9 @@ or refetching does not undo a write-access opt-out. Nothing is authorized until
|
||||
|
||||
Return to the same Connections entry to see your connected assistants, their
|
||||
read/write access, and revoke access. The list refreshes after consent and only
|
||||
shows your grants for the selected organization. The legacy
|
||||
shows your active grants for the selected organization. Each connection shows your
|
||||
profile avatar and defaults to a name such as “Dotta’s Codex connection.” Revoked
|
||||
connections disappear from the list; their audit records remain. The legacy
|
||||
`/assistant-connections` URL remains available for account-wide management.
|
||||
|
||||
`GET /api/mcp/setup` returns the live experimental gate, canonical endpoint,
|
||||
|
||||
@@ -10,7 +10,7 @@ export function mcpSetupUrl(serverUrl: string, companyId?: string) {
|
||||
return url.toString();
|
||||
}
|
||||
export function mcpInvitation(serverUrl: string, company?: { id: string; name: string }) {
|
||||
return `Connect to my ${company ? `${company.name} ` : ""}Paperclip organization using the instructions at ${mcpSetupUrl(serverUrl, company?.id)}. Start authorization, give me the approval link, and verify the connection after I approve. This connects as me, not as a Paperclip agent.`;
|
||||
return `Connect to my ${company ? `${company.name} ` : ""}Paperclip organization using the instructions at ${mcpSetupUrl(serverUrl, company?.id)}. Start authorization, give me the approval link, and verify the connection after I approve.`;
|
||||
}
|
||||
export function mcpSetupSteps(serverUrl: string, assistant: AssistantClient) {
|
||||
const quoted = `'${serverUrl.replaceAll("'", "'\"'\"'")}'`;
|
||||
|
||||
@@ -36,6 +36,8 @@ export interface McpConnection {
|
||||
companyId: string;
|
||||
clientName: string;
|
||||
companyName: string;
|
||||
/** The signed-in person who authorized this connection; absent on older servers. */
|
||||
user?: { name: string; image: string | null } | null;
|
||||
scopes: string[];
|
||||
createdAt: string;
|
||||
revokedAt: string | null;
|
||||
|
||||
@@ -120,6 +120,19 @@ describe.skipIf(!support.supported)("public MCP OAuth and tool boundary", () =>
|
||||
return { actor, company: company!, membership: membership!, client, tokens, exchange };
|
||||
}
|
||||
|
||||
it("returns only the authorizing person’s profile with their connection list", async () => {
|
||||
const f = await fixture();
|
||||
const other = await fixture();
|
||||
await db.update(authUsers).set({ name: "Dotta", image: "https://avatars.example/dotta.png" }).where(eq(authUsers.id, f.actor.userId!));
|
||||
const rows = await oauth.listConnections(f.actor.userId!);
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0]).toMatchObject({ companyId: f.company.id, user: { name: "Dotta", image: "https://avatars.example/dotta.png" } });
|
||||
expect(JSON.stringify(rows)).not.toContain(other.actor.userId!);
|
||||
expect(JSON.stringify(rows)).not.toContain("@example.com");
|
||||
await oauth.revokeConnection(rows[0]!.id, f.actor.userId!);
|
||||
expect((await oauth.listConnections(f.actor.userId!))[0]?.revokedAt).not.toBeNull();
|
||||
});
|
||||
|
||||
async function deviceFixture() {
|
||||
const f = await fixture();
|
||||
const client = await oauth.register({ client_name: "Device client", redirect_uris: [], grant_types: [DEVICE_GRANT, "refresh_token"], response_types: [] }, randomUUID());
|
||||
|
||||
@@ -4,7 +4,7 @@ import { and, eq, gt, inArray, isNull, lt, lte, notExists, sql } from "drizzle-o
|
||||
import { z } from "zod";
|
||||
import type { Request } from "express";
|
||||
import {
|
||||
type Db, activityLog, companies, companyLogos, mcpOauthClients, mcpOauthGrants, mcpOauthRequests, mcpOauthTokens, mcpOauthDeviceRequests, mcpOauthMetadataAdmissions,
|
||||
type Db, activityLog, authUsers, companies, companyLogos, mcpOauthClients, mcpOauthGrants, mcpOauthRequests, mcpOauthTokens, mcpOauthDeviceRequests, mcpOauthMetadataAdmissions,
|
||||
} from "@paperclipai/db";
|
||||
import { PUBLIC_MCP_PATH, PUBLIC_MCP_SCOPES, type McpConnectionRequest } from "@paperclipai/shared";
|
||||
import { boardAuthService } from "../board-auth.js";
|
||||
@@ -459,12 +459,14 @@ export function createPublicMcpOAuth(db: Db, config: PublicMcpConfig, options: {
|
||||
});
|
||||
},
|
||||
async listConnections(userId: string) {
|
||||
const rows = await db.select({ grant: mcpOauthGrants, clientName: mcpOauthClients.name, companyName: companies.name })
|
||||
const rows = await db.select({ grant: mcpOauthGrants, clientName: mcpOauthClients.name, companyName: companies.name, userName: authUsers.name, userImage: authUsers.image })
|
||||
.from(mcpOauthGrants).innerJoin(mcpOauthClients, eq(mcpOauthGrants.clientId, mcpOauthClients.id))
|
||||
.innerJoin(companies, eq(companies.id, mcpOauthGrants.companyId))
|
||||
.leftJoin(authUsers, eq(authUsers.id, mcpOauthGrants.userId))
|
||||
.where(eq(mcpOauthGrants.userId, userId));
|
||||
return rows.map(({ grant, clientName, companyName }) => ({
|
||||
id: grant.id, companyId: grant.companyId, clientName, companyName, scopes: grant.scopes,
|
||||
return rows.map(({ grant, clientName, companyName, userName, userImage }) => ({
|
||||
id: grant.id, companyId: grant.companyId, clientName, companyName,
|
||||
user: userName === null ? null : { name: userName, image: userImage }, scopes: grant.scopes,
|
||||
createdAt: grant.createdAt.toISOString(), revokedAt: grant.revokedAt?.toISOString() ?? null,
|
||||
}));
|
||||
},
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { Globe, Paperclip } from "lucide-react";
|
||||
import { Link, useParams } from "@/lib/router";
|
||||
import type { McpConnection, McpConnectionRequest } from "@paperclipai/shared";
|
||||
import { deriveInitials, Identity } from "@/components/Identity";
|
||||
import { assistantConnectionDisplayName } from "./apps/connection-owner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
@@ -116,20 +118,25 @@ function McpConnectRequest({ id, device = false, onEditCode }: { id: string; dev
|
||||
}
|
||||
|
||||
export function AssistantConnectionsPage() {
|
||||
const client = useQueryClient();
|
||||
const connections = useQuery({ queryKey: ["mcp-connections"], queryFn: () => api.get<McpConnection[]>("/mcp/connections"), retry: false });
|
||||
const revoke = useMutation({ mutationFn: (id: string) => api.delete(`/mcp/connections/${id}`), onSuccess: () => { void connections.refetch(); } });
|
||||
const active = connections.data?.filter(connection => !connection.revokedAt);
|
||||
const revoke = useMutation({ mutationFn: (id: string) => api.delete(`/mcp/connections/${id}`), onSuccess: (_, id) => {
|
||||
client.setQueryData<McpConnection[]>(["mcp-connections"], rows => rows?.filter(row => row.id !== id));
|
||||
return client.invalidateQueries({ queryKey: ["mcp-connections"] });
|
||||
} });
|
||||
return <div className="mx-auto max-w-xl space-y-4 py-10">
|
||||
<h1 className="text-xl font-semibold">Assistant connections</h1>
|
||||
<p className="text-sm text-muted-foreground">Revoking a connection stops its future tool calls. Work already delegated continues under your organization’s normal controls.</p>
|
||||
{connections.isPending && <p className="text-sm">Loading connections…</p>}
|
||||
{(connections.error || revoke.error) && <p className="text-sm text-destructive">{(connections.error ?? revoke.error)?.message}</p>}
|
||||
{connections.data?.length === 0 && <p className="text-sm">No assistant connections.</p>}
|
||||
{connections.data?.map((connection) => <Card key={connection.id} className="block space-y-2 p-4">
|
||||
<h2 className="font-medium">{connection.clientName}</h2>
|
||||
{active?.length === 0 && <p className="text-sm">No assistant connections.</p>}
|
||||
{active?.map((connection) => <Card key={connection.id} className="block space-y-2 p-4">
|
||||
<h2 className="font-medium"><Identity name={assistantConnectionDisplayName(connection)} avatarUrl={connection.user?.image} initials={deriveInitials(connection.user?.name ?? "You")} /></h2>
|
||||
<p className="text-sm text-muted-foreground">Organization: {connection.companyName}</p>
|
||||
<p className="text-sm">{connection.scopes.includes("paperclip:write") ? "Read and edit work" : "Read only"}</p>
|
||||
{connection.scopes.includes("paperclip:configure") && <p className="text-sm">Configure agents, projects and skills</p>}
|
||||
{connection.revokedAt ? <p className="text-sm text-muted-foreground">Revoked</p> : <Button variant="outline" disabled={revoke.isPending} onClick={() => revoke.mutate(connection.id)}>Revoke connection</Button>}
|
||||
<Button variant="outline" disabled={revoke.isPending} onClick={() => revoke.mutate(connection.id)}>Revoke connection</Button>
|
||||
</Card>)}
|
||||
<Link className="text-sm underline" to="/">Back to Paperclip</Link>
|
||||
</div>;
|
||||
|
||||
@@ -12,7 +12,7 @@ vi.mock("@/context/CompanyContext", () => ({ useCompany: () => ({ selectedCompan
|
||||
vi.mock("@/context/BreadcrumbContext", () => ({ useBreadcrumbs: () => ({ setBreadcrumbs: mocks.breadcrumbs }) }));
|
||||
vi.mock("@/lib/router", () => ({ Link: ({ children, to, ...props }: { children: React.ReactNode; to: string }) => <a href={to} {...props}>{children}</a> }));
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
|
||||
const grant = { id: "grant", companyId: "butter", companyName: "Butter", clientName: "OpenCode", scopes: ["paperclip:read", "paperclip:write"], createdAt: "2026-10-05T00:00:00Z", revokedAt: null };
|
||||
const grant = { id: "grant", companyId: "butter", companyName: "Butter", clientName: "OpenCode", user: { name: "Dotta", image: "/avatar.jpg" }, scopes: ["paperclip:read", "paperclip:write"], createdAt: "2026-10-05T00:00:00Z", revokedAt: null };
|
||||
let root: Root, container: HTMLDivElement, client: QueryClient;
|
||||
async function flush() { await act(async () => { await new Promise(resolve => setTimeout(resolve, 20)); }); }
|
||||
async function render(element: React.ReactNode = <AssistantConnection initialAssistant="opencode" />) {
|
||||
@@ -72,13 +72,63 @@ describe("assistant setup from Connections", () => {
|
||||
await render();
|
||||
expect(container.textContent).not.toContain("Other secret client");
|
||||
expect(container.textContent).toContain("Connected as you · Read and write");
|
||||
expect(container.textContent).toContain("Dotta’s OpenCode connection");
|
||||
expect(container.querySelector('[data-slot="avatar"]')).not.toBeNull();
|
||||
mocks.connections.mockResolvedValue([{ ...grant, revokedAt: "2026-10-05T00:00:00Z" }]);
|
||||
await act(async () => container.querySelector<HTMLButtonElement>('[aria-label="Revoke OpenCode connection"]')!.click());
|
||||
await act(async () => container.querySelector<HTMLButtonElement>('[aria-label="Revoke Dotta’s OpenCode connection"]')!.click());
|
||||
await flush();
|
||||
expect(mocks.revoke.mock.calls[0]?.[0]).toBe("grant");
|
||||
expect(container.textContent).toContain("Revoked");
|
||||
expect(container.textContent).not.toContain("Revoked");
|
||||
expect(container.textContent).not.toContain("Dotta’s OpenCode connection");
|
||||
expect(container.querySelector('[data-slot="avatar"]')).toBeNull();
|
||||
expect(container.textContent).toContain("No assistants connected to Butter yet");
|
||||
expect(container.querySelector('[aria-label="Copy first prompt"]')).toBeNull();
|
||||
});
|
||||
it("hides retained revoked grants in both the page and catalog card", async () => {
|
||||
mocks.connections.mockResolvedValue([{ ...grant, revokedAt: "2026-10-05T00:00:00Z" }]);
|
||||
await render();
|
||||
expect(container.textContent).toContain("No assistants connected to Butter yet");
|
||||
expect(container.textContent).not.toContain("Dotta’s OpenCode connection");
|
||||
await render(<AssistantConnectionCard onNavigate={vi.fn()} />);
|
||||
expect(container.querySelector('[aria-label="Set up Assistant Connection (MCP)"]')).not.toBeNull();
|
||||
expect(container.textContent).not.toContain("Dotta’s OpenCode connection");
|
||||
});
|
||||
it.each(["https://assistant.example", "my_assistant", "Custom Assistant"])("preserves a custom client’s name: %s", async (clientName) => {
|
||||
mocks.connections.mockResolvedValue([{ ...grant, clientName }]);
|
||||
await render();
|
||||
expect(container.textContent).toContain(`Dotta’s ${clientName} connection`);
|
||||
expect(container.querySelector('button[aria-label^="Revoke Dotta’s"]')?.getAttribute("aria-label")).toBe(`Revoke Dotta’s ${clientName} connection`);
|
||||
});
|
||||
it("uses the person’s initials when they have no profile image", async () => {
|
||||
mocks.connections.mockResolvedValue([{ ...grant, user: { name: "Dotta", image: null } }]);
|
||||
await render();
|
||||
expect(container.querySelector('[data-slot="avatar-fallback"]')?.textContent).toBe("DO");
|
||||
expect(container.textContent).toContain("Dotta’s OpenCode connection");
|
||||
});
|
||||
it("keeps an older server’s connection usable without profile metadata", async () => {
|
||||
mocks.connections.mockResolvedValue([{ ...grant, user: undefined }]);
|
||||
await render();
|
||||
expect(container.textContent).toContain("OpenCode connection");
|
||||
expect(container.querySelector('[aria-label="Revoke OpenCode connection"]')).not.toBeNull();
|
||||
});
|
||||
it("retains the connection when revocation fails", async () => {
|
||||
mocks.connections.mockResolvedValue([grant]);
|
||||
mocks.revoke.mockRejectedValueOnce(new Error("offline"));
|
||||
await render();
|
||||
await act(async () => container.querySelector<HTMLButtonElement>('[aria-label="Revoke Dotta’s OpenCode connection"]')!.click());
|
||||
await flush();
|
||||
expect(container.textContent).toContain("Couldn’t revoke this connection");
|
||||
expect(container.textContent).toContain("Dotta’s OpenCode connection");
|
||||
});
|
||||
it("hides a successfully revoked connection even if the follow-up refresh fails", async () => {
|
||||
mocks.connections.mockResolvedValue([grant]);
|
||||
await render();
|
||||
mocks.connections.mockRejectedValue(new Error("offline"));
|
||||
await act(async () => container.querySelector<HTMLButtonElement>('[aria-label="Revoke Dotta’s OpenCode connection"]')!.click());
|
||||
await flush();
|
||||
expect(mocks.revoke).toHaveBeenCalledWith("grant", expect.anything());
|
||||
expect(container.textContent).not.toContain("Dotta’s OpenCode connection");
|
||||
});
|
||||
it("shows a real grant when the list refreshes after assistant sign-in", async () => {
|
||||
await render();
|
||||
mocks.connections.mockResolvedValue([grant]);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { assistantClientNames, mcpAuthorizationHandoffInstructions, mcpInvitation, mcpSetupSteps, type AssistantClient } from "@paperclipai/shared";
|
||||
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";
|
||||
@@ -8,6 +8,8 @@ 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";
|
||||
@@ -32,13 +34,13 @@ export function useAssistantConnections(poll = false) {
|
||||
queryKey: connectionsKey, queryFn: publicMcpApi.connections, retry: false,
|
||||
enabled: Boolean(selectedCompanyId), refetchInterval: poll ? 5000 : false,
|
||||
});
|
||||
return { ...query, rows: (query.data ?? []).filter(row => row.companyId === selectedCompanyId) };
|
||||
return { ...query, rows: (query.data ?? []).filter(row => row.companyId === selectedCompanyId && !row.revokedAt) };
|
||||
}
|
||||
|
||||
/** Inbound assistant access belongs beside the existing outbound connectors. */
|
||||
export function AssistantConnectionCard({ onNavigate }: { onNavigate: (href: string) => void }) {
|
||||
const connections = useAssistantConnections();
|
||||
const active = connections.rows.filter(row => !row.revokedAt);
|
||||
const active = connections.rows;
|
||||
const action = !connections.isSuccess ? "Open" : active.length ? "Manage" : "Set up";
|
||||
return <div role="listitem" data-app-slug="assistant-connection" data-connected={connections.isSuccess ? 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">
|
||||
@@ -55,9 +57,7 @@ export function AssistantConnectionCard({ onNavigate }: { onNavigate: (href: str
|
||||
<Button size="sm" variant="ghost" disabled={connections.isFetching} onClick={() => void connections.refetch()}>Try again</Button>
|
||||
</div>}
|
||||
{connections.isSuccess && active.length > 0 && <div className="flex flex-wrap items-center gap-2 border-t border-border px-4 py-3 text-sm">
|
||||
<Check className="size-4 text-muted-foreground" aria-hidden="true" />
|
||||
<span>{active.map(row => row.clientName).join(", ")}</span>
|
||||
<span className="text-xs text-muted-foreground">Connected as you</span>
|
||||
{active.map(row => <Identity key={row.id} name={assistantConnectionDisplayName(row)} avatarUrl={row.user?.image} initials={deriveInitials(row.user?.name ?? "You")} size="sm" />)}
|
||||
</div>}
|
||||
</div>;
|
||||
}
|
||||
@@ -92,7 +92,10 @@ export function AssistantConnection({ initialAssistant = "codex" }: { initialAss
|
||||
const [assistant, setAssistant] = useState<Assistant>(initialAssistant);
|
||||
const setup = useQuery({ queryKey: ["mcp-setup"], queryFn: publicMcpApi.setup, retry: false, refetchOnWindowFocus: "always", refetchOnMount: "always" });
|
||||
const connections = useAssistantConnections(setup.data?.enabled === true);
|
||||
const revoke = useMutation({ mutationFn: publicMcpApi.revoke, onSuccess: () => client.invalidateQueries({ queryKey: connectionsKey }) });
|
||||
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: "Connectors", href: "/apps" }, { label: "Assistant Connection (MCP)" }]);
|
||||
return () => setBreadcrumbs([]);
|
||||
@@ -140,8 +143,8 @@ export function AssistantConnection({ initialAssistant = "codex" }: { initialAss
|
||||
{(connections.error || revoke.error) && <p role="alert" className="text-sm text-destructive">{revoke.error ? "Couldn’t revoke this connection. Try again." : "Couldn’t load your connections. Try again."} <button type="button" className="underline" onClick={() => void connections.refetch()}>Refresh</button></p>}
|
||||
{connections.isSuccess && 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="space-y-1"><p className="text-sm font-medium">{row.clientName}</p><p className="text-xs text-muted-foreground">{row.revokedAt ? "Revoked" : `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>
|
||||
{!row.revokedAt && <Button variant="outline" size="sm" disabled={revoke.isPending} onClick={() => revoke.mutate(row.id)} aria-label={`Revoke ${row.clientName} connection`}>Revoke</Button>}
|
||||
<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>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ToolConnection } from "@paperclipai/shared";
|
||||
import type { McpConnection, ToolConnection } from "@paperclipai/shared";
|
||||
import { humanizeConnectionDisplayName } from "@paperclipai/shared";
|
||||
import { Identity } from "@/components/Identity";
|
||||
import type { CompanyUserProfile } from "@/lib/company-members";
|
||||
@@ -52,6 +52,13 @@ export function connectionDisplayNameForOwner(
|
||||
return `${possessive(ownerGivenName(owner.label))} ${applicationName}`;
|
||||
}
|
||||
|
||||
/** Use the same owner naming as outbound connections, without changing OAuth client identity. */
|
||||
export function assistantConnectionDisplayName(connection: McpConnection): string {
|
||||
const clientName = connection.clientName.trim();
|
||||
const owner = connection.user ? `${possessive(ownerGivenName(connection.user.name))} ` : "";
|
||||
return `${owner}${clientName} connection`;
|
||||
}
|
||||
|
||||
export function ConnectionOwnerIdentity({ owner }: { owner: ConnectionOwnerProfile | null }) {
|
||||
if (!owner) return <span className="text-xs text-muted-foreground">Unknown</span>;
|
||||
return (
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { instanceExperimentalSettingsSchema, type InstanceExperimentalSettingsWithManaged, type McpConnection, type McpConnectionRequest } from "@paperclipai/shared";
|
||||
import { fn } from "storybook/test";
|
||||
|
||||
// Local portrait fixture keeps avatar previews independent of third-party image hosts.
|
||||
export const connectedUser = { name: "Dotta", image: `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="32" fill="#626972"/><circle cx="32" cy="24" r="12" fill="#eef0f2"/><path d="M10 64v-8a22 22 0 0 1 44 0v8" fill="#eef0f2"/></svg>')}` };
|
||||
|
||||
export const consentSubmission = fn();
|
||||
export const request: McpConnectionRequest = {
|
||||
id: "storybook-request", clientName: "Codex", redirectOrigin: "https://chatgpt.com",
|
||||
@@ -11,8 +14,8 @@ export const request: McpConnectionRequest = {
|
||||
], setupUrl: null,
|
||||
};
|
||||
const connections: McpConnection[] = [
|
||||
{ id: "codex", companyId: request.companies[0].id, companyName: "Acme Research", clientName: "Codex", scopes: ["paperclip:read", "paperclip:write"], createdAt: "2020-01-01T00:00:00Z", revokedAt: null },
|
||||
{ id: "claude", companyId: request.companies[1].id, companyName: "Design Partners", clientName: "Claude", scopes: ["paperclip:read"], createdAt: "2020-01-01T00:00:00Z", revokedAt: null },
|
||||
{ id: "codex", companyId: request.companies[0].id, companyName: "Acme Research", clientName: "Codex", user: connectedUser, scopes: ["paperclip:read", "paperclip:write"], createdAt: "2020-01-01T00:00:00Z", revokedAt: null },
|
||||
{ id: "claude", companyId: request.companies[1].id, companyName: "Design Partners", clientName: "Claude", user: connectedUser, scopes: ["paperclip:read"], createdAt: "2020-01-01T00:00:00Z", revokedAt: null },
|
||||
];
|
||||
export interface PublicMcpFixture {
|
||||
request?: Partial<McpConnectionRequest>;
|
||||
@@ -33,7 +36,7 @@ export interface PublicMcpFixture {
|
||||
export function installPublicMcpFixture(fixture: PublicMcpFixture = {}) {
|
||||
consentSubmission.mockClear();
|
||||
const original = window.fetch;
|
||||
let rows = fixture.empty ? [] : (fixture.connections ?? connections).map(row => ({ ...row, revokedAt: fixture.revoked ? "2020-01-02T00:00:00Z" : null }));
|
||||
let rows = fixture.empty ? [] : (fixture.connections ?? connections).map(row => ({ ...row, revokedAt: fixture.revoked ? "2020-01-02T00:00:00Z" : row.revokedAt }));
|
||||
let settings: InstanceExperimentalSettingsWithManaged = { ...instanceExperimentalSettingsSchema.parse({}), enablePublicMcp: Boolean(fixture.enabled), managedKeys: fixture.managed ? { enablePublicMcp: { managed: true, managedBy: "paperclip-cloud" } } : {} };
|
||||
const error = (message: string, status = 503) => Response.json({ error: message }, { status });
|
||||
window.fetch = async (input, init) => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { expect, userEvent, within } from "storybook/test";
|
||||
import { expect, userEvent, waitFor, within } from "storybook/test";
|
||||
import { AssistantConnectionsPage } from "@/pages/McpConnect";
|
||||
import { installPublicMcpFixture } from "../fixtures/publicMcp";
|
||||
const meta = {
|
||||
@@ -13,11 +13,14 @@ export const Connected: Story = {};
|
||||
export const Empty: Story = { parameters: { fixture: { empty: true } } };
|
||||
export const Loading: Story = { parameters: { fixture: { loading: true } } };
|
||||
export const Unavailable: Story = { parameters: { fixture: { unavailable: true } } };
|
||||
export const AlreadyRevoked: Story = { parameters: { fixture: { revoked: true } } };
|
||||
export const AlreadyRevoked: Story = { parameters: { fixture: { revoked: true } }, play: async ({ canvasElement }) => {
|
||||
await expect(await within(canvasElement).findByText("No assistant connections.")).toBeVisible();
|
||||
} };
|
||||
export const Revoke: Story = { play: async ({ canvasElement }) => {
|
||||
const c = within(canvasElement);
|
||||
await userEvent.click((await c.findAllByRole("button", { name: "Revoke connection" }))[0]);
|
||||
await c.findByText("Revoked");
|
||||
await waitFor(() => expect(c.queryByText("Dotta’s Codex connection")).not.toBeInTheDocument());
|
||||
await c.findByText("Dotta’s Claude connection");
|
||||
await expect(c.getAllByRole("button", { name: "Revoke connection" })).toHaveLength(1);
|
||||
} };
|
||||
export const RevokeFailed: Story = { parameters: { fixture: { mutationError: true } }, play: async ({ canvasElement }) => {
|
||||
|
||||
@@ -7,7 +7,7 @@ import { Browse } from "@/pages/apps/Browse";
|
||||
import { AssistantConnection } from "@/pages/apps/AssistantConnection";
|
||||
import { InstanceExperimentalSettings } from "@/pages/InstanceExperimentalSettings";
|
||||
import { PublicMcpPresenter } from "./public-mcp-presenter";
|
||||
import { installPublicMcpFixture } from "../fixtures/publicMcp";
|
||||
import { connectedUser, installPublicMcpFixture } from "../fixtures/publicMcp";
|
||||
|
||||
function ConnectionJourney({ assistant = "opencode" }: { assistant?: "codex" | "claude" | "opencode" | "other" }) {
|
||||
return <PluginLauncherProvider><Routes>
|
||||
@@ -39,7 +39,7 @@ export const OpenCodeSetup: Story = { parameters: { initialEntries: ["/PAP/apps/
|
||||
export const CodexSetup: Story = { ...OpenCodeSetup, args: { assistant: "codex" } };
|
||||
export const ClaudeSetup: Story = { ...OpenCodeSetup, args: { assistant: "claude" } };
|
||||
export const Connected: Story = { parameters: { initialEntries: ["/PAP/apps/assistant-connection"], fixture: { enabled: true, empty: false, connections: [
|
||||
{ id: "opencode", companyId: "company-storybook", companyName: "Paperclip", clientName: "OpenCode", scopes: ["paperclip:read", "paperclip:write", "offline_access"], createdAt: "2026-10-05T12:00:00Z", revokedAt: null },
|
||||
{ id: "opencode", companyId: "company-storybook", companyName: "Paperclip", clientName: "OpenCode", user: connectedUser, scopes: ["paperclip:read", "paperclip:write", "offline_access"], createdAt: "2026-10-05T12:00:00Z", revokedAt: null },
|
||||
{ id: "other-org", companyId: "another-company", companyName: "Other organization", clientName: "Private other client", scopes: ["paperclip:read"], createdAt: "2026-10-05T12:00:00Z", revokedAt: null },
|
||||
] } } };
|
||||
export const Unavailable: Story = { parameters: { initialEntries: ["/PAP/apps/assistant-connection"], fixture: { unavailable: true } } };
|
||||
@@ -65,3 +65,10 @@ export const InvitationCopied: Story = { ...OpenCodeSetup, play: async ({ canvas
|
||||
await expect(await navigator.clipboard.readText()).toContain("/mcp/setup?company=");
|
||||
} };
|
||||
export const ManualSetup: Story = { ...OpenCodeSetup, play: async ({ canvasElement }) => { await userEvent.click(await within(canvasElement).findByText("Set up manually")); } };
|
||||
|
||||
export const RevokeConnection: Story = { ...Connected, play: async ({ canvasElement }) => {
|
||||
const c = within(canvasElement);
|
||||
await userEvent.click(await c.findByRole("button", { name: "Revoke Dotta’s OpenCode connection" }));
|
||||
await expect(await c.findByText("No assistants connected to Paperclip Storybook yet.")).toBeVisible();
|
||||
await expect(c.queryByText("Dotta’s OpenCode connection")).not.toBeInTheDocument();
|
||||
} };
|
||||
Reference in new issue
Block a user