Files
PaperClipAI/ui/src/pages/apps/AssistantConnection.test.tsx
T
DottaandPaperclip 99a9de9940 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>
2026-10-06 22:09:41 -05:00

150 lines
10 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// @vitest-environment jsdom
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { AssistantConnection, AssistantConnectionCard } from "./AssistantConnection";
const mocks = vi.hoisted(() => ({ setup: vi.fn(), connections: vi.fn(), revoke: vi.fn(), breadcrumbs: vi.fn(), copy: vi.fn() }));
vi.mock("@/hooks/usePrefersReducedMotion", () => ({ usePrefersReducedMotion: () => true }));
vi.mock("@/lib/clipboard", () => ({ copyTextToClipboard: mocks.copy }));
vi.mock("@/api/publicMcp", () => ({ publicMcpApi: mocks }));
vi.mock("@/context/CompanyContext", () => ({ useCompany: () => ({ selectedCompanyId: "butter", selectedCompany: { id: "butter", name: "Butter", logoUrl: null } }) }));
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", 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" />) {
await act(async () => root.render(<QueryClientProvider client={client}>{element}</QueryClientProvider>));
await flush();
}
beforeEach(() => {
mocks.setup.mockResolvedValue({ enabled: true, serverUrl: "https://canonical.example/mcp/paperclip" });
mocks.connections.mockResolvedValue([]);
mocks.revoke.mockResolvedValue(undefined);
client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
container = document.createElement("div"); document.body.append(container); root = createRoot(container);
});
afterEach(async () => { await act(async () => root.unmount()); client.clear(); container.remove(); vi.clearAllMocks(); });
describe("assistant setup from Connections", () => {
it("copies a scoped instruction link with no credential and keeps manual configuration collapsed", async () => {
await render();
expect(container.querySelector("details")?.open).toBe(false);
await act(async () => container.querySelector<HTMLButtonElement>('[aria-label="Copy invitation"]')!.click());
expect(mocks.copy).toHaveBeenLastCalledWith(expect.stringContaining("https://canonical.example/mcp/setup?company=butter"));
expect(mocks.copy).toHaveBeenLastCalledWith(expect.stringContaining("after I approve"));
expect(document.body.textContent).toContain("Copied to clipboard");
expect(container.textContent).not.toContain("Copy link");
expect(container.textContent).not.toContain("Open setup instructions");
expect(mocks.revoke).not.toHaveBeenCalled();
});
it("surfaces catalog status failures and recovers without claiming there are no connections", async () => {
mocks.connections.mockRejectedValue(new Error("offline"));
await render(<AssistantConnectionCard onNavigate={vi.fn()} />);
expect(container.querySelector('[role="alert"]')?.textContent).toContain("Couldn’t load your connection status");
expect(container.querySelector('[aria-label="Set up Assistant Connection (MCP)"]')).toBeNull();
expect(container.querySelector('[data-connected]')).toBeNull();
mocks.connections.mockResolvedValue([grant]);
await act(async () => Array.from(container.querySelectorAll('button')).find(b => b.textContent === "Try again")!.click());
await flush();
expect(container.querySelector('[aria-label="Manage Assistant Connection (MCP)"]')).not.toBeNull();
expect(container.querySelector('[role="alert"]')).toBeNull();
});
it("uses the canonical URL and explains how OpenCode opens consent without granting access", async () => {
await render();
const config = Array.from(container.querySelectorAll("pre")).map(p => p.textContent!).find(p => p.startsWith("{"))!;
expect(JSON.parse(config).mcp.paperclip).toEqual({ type: "remote", url: "https://canonical.example/mcp/paperclip", enabled: true, oauth: { scope: "paperclip:read paperclip:write paperclip:configure offline_access" } });
expect(container.textContent).toContain("opencode mcp auth paperclip");
expect(container.textContent).toContain("No assistants connected to Butter yet");
expect(container.querySelector('[role="combobox"]')).toBeNull();
expect(mocks.revoke).not.toHaveBeenCalled();
});
it("shows the enable path while disabled, with no usable setup instructions", async () => {
mocks.setup.mockResolvedValue({ enabled: false, serverUrl: "https://canonical.example/mcp/paperclip" });
await render();
expect(container.querySelector('a[href="/company/settings/instance/experimental"]')).not.toBeNull();
expect(container.textContent).not.toContain("opencode mcp auth");
expect(container.textContent).not.toContain("https://canonical.example");
});
it("only shows this organization’s grants and revokes the selected grant", async () => {
mocks.connections.mockResolvedValue([grant, { ...grant, id: "other", companyId: "elsewhere", clientName: "Other secret client" }]);
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 Dotta’s OpenCode connection"]')!.click());
await flush();
expect(mocks.revoke.mock.calls[0]?.[0]).toBe("grant");
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]);
await act(async () => { await client.invalidateQueries({ queryKey: ["mcp-connections"] }); });
await flush();
expect(container.textContent).toContain("Connected as you · Read and write");
expect(container.querySelector('[aria-label="Copy first prompt"]')).toBeNull();
});
it("shows a recoverable error instead of pretending setup succeeded", async () => {
mocks.setup.mockRejectedValue(new Error("offline"));
await render();
expect(container.querySelector('[role="alert"]')?.textContent).toContain("Couldn’t load assistant setup");
mocks.setup.mockResolvedValue({ enabled: true, serverUrl: "https://canonical.example/mcp/paperclip" });
await act(async () => Array.from(container.querySelectorAll('button')).find(b => b.textContent === "Try again")!.click());
await flush();
expect(container.textContent).toContain("opencode mcp auth paperclip");
});
});