Files
PaperClipAI/ui/src/pages/apps/AssistantConnection.test.tsx
T
DottaandClaude Opus 5.5 904c01d1a3 feat(mcp): graduate Assistant connections (MCP) out of experimental (#22015)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Assistant connections (MCP) let an outside assistant, or another
Paperclip instance, sign in as a person and use the `/mcp/paperclip`
endpoint
> - The feature was behind the experimental `enablePublicMcp` setting.
The setting was off by default and in practice off on Cloud stacks
> - Instance-to-instance work (one person's agent files a task on a
colleague's instance) fails when the receiving instance has the setting
off
> - This pull request moves the feature out of Experimental. It is now
always on, and a stored or Cloud-managed "off" value is ignored
> - The benefit is that every authenticated instance with a public URL,
including Cloud workspaces, accepts assistant connections with no setup
step

## Linked Issues or Issue Description

**Subsystem affected**
Public MCP (`server/src/services/public-mcp/`), instance settings,
Connectors → Assistant Connection (MCP) setup page, Experimental
settings page.

**Problem or motivation**
A remote MCP connector on one instance cannot use another instance's
`/mcp/paperclip` unless an admin on the other instance finds and turns
on an experimental toggle. On Cloud, the toggle is off and is managed by
the fleet. Instance-to-instance delegation therefore does not work by
default.

**Proposed solution**
Remove the gate. Keep `enablePublicMcp` only as a compatibility key, the
same way `enableApps` was graduated: old stored rows, PATCH bodies and
Cloud managed configs still parse, but the effective value is always
`true`.

**Alternatives considered**
An instance-admin kill switch that defaults ON. I did not keep one. Each
person already controls access: a connection exists only after that
person approves OAuth consent for one company, and the person or an
admin can revoke it. Deployment policy (authenticated mode and a valid
public URL) still decides whether the endpoint exists. A second switch
would add a state that can silently break instance-to-instance work
again. A schema migration was also not needed: the value lives in the
`experimental` JSON column, and the stored key becomes inert.

**Roadmap alignment**
Requested by the maintainer to enable instance-to-instance
communication.

## What Changed

- `packages/shared`: `enablePublicMcp` is a deprecated compatibility
key. The schema default is `true`. The feature catalog entry is
"Assistant connections (compatibility)" with both defaults `true`.
- `server` instance settings: normalization always returns
`enablePublicMcp: true`. The Cloud managed overlay skips the key, so a
fleet value of `false` cannot disable it. Removed the key from the Cloud
staging experimental-key list. Removed the client-mirror policy step
that ran only when the toggle changed.
- `server` public MCP: personal discovery, OAuth, tools, setup and event
delivery no longer read instance settings (`isEnabled()` returns `true`
for the personal endpoint without a DB read). Dot, Grok and Muse agent
connections keep their own experimental settings.
- `server` Cloud paths: the client-mirror sync, the hosted event
authority, the ingress-handoff expiry worker and the idle sleep proof
treat the front door as enabled. The warm-standby `503
workspace_unclaimed` behavior is unchanged.
- `server` Dot/Grok gates: they no longer also require
`enablePublicMcp`. Error messages no longer tell people to enable
Assistant connections.
- `ui`: removed the Experimental toggle, the "Enable assistant
connections / Open Experimental settings" block on the Assistant
Connection page, and the "Enable Assistant connections (MCP)" hint in
Dot setup. Updated the Dot and Grok copy.
- Storybook: deleted the Experimental-setting story and removed the
"enable the experiment" step from the journey and presenter.
- Docs: `doc/public-mcp.md` ("Enable an instance", "Start from
Connections", `GET /api/mcp/setup`), `doc/openai-dot-runner.md`,
`doc/idle-grok-dispatch.md`, and the agent-access map.
- Tests: new red/green tests for "enabled with no setting stored" and "a
stored or managed off value is ignored". Removed the tests for the
"disabled" behavior, which no longer exists.

## Verification

- Red/green: with the old source and the new tests,
`instance-settings-readonly.test.ts`,
`instance-settings-service.test.ts` and `public-mcp.test.ts` fail (4
failures, and the public-MCP suite fails in `beforeAll` because
`isEnabled()` was `false` with no setting stored). With the new source
they pass.
- `server`: `public-mcp.test.ts`, instance-settings (readonly, service,
managed overlay), `managed-config`, `cloud-event-authority`,
`events-work`, `dot-runner`, `dot-oauth-onboarding` and
`agent-runtime-assignments`. 354 passed.
- Cloud client-mirror lifecycle
(`client-mirror-lifecycle.postgres.test.ts`, skipped in CI) passed
against a local Postgres 17 with
`PAPERCLIP_MCP_SLEEP_TEST_DATABASE_URL`. 6/6, plus `events-work` 28/28.
- Idle and sleep: `idle-incoming-wake` (service and route),
`idle-deadline-proof`, `idle-incoming-wake-capability`,
`idle-sleep-proof`, `client-mirror-ack`, `recovery-deadline-acceptance`
and `idle-completed-history` pass. The warm-standby test now also
asserts that discovery after the claim does no SQL read.
- `ui`: `InstanceExperimentalSettings`, `AssistantConnection`,
`NewAgentDialog`, `NewAgent` and `ExternalAgentInviteDialog.muse` pass.
267 passed.
- Typecheck: `packages/shared`, `server` and `ui` pass. `node
scripts/check-maps.mjs` passes.
- `pnpm verify`: see the CI checks on this PR.
- After the deploy: confirm
`/.well-known/oauth-protected-resource/mcp/paperclip` and `/mcp/setup`
return 200 on paperclip.staging without changing any setting.

## Risks

- Behavior change: instances that had the setting off now serve
discovery, OAuth and `/mcp/paperclip`. Security invariants are
unchanged: the endpoint is still mounted only in authenticated mode with
a valid public URL, OAuth still needs a real signed-in user's consent,
local implicit board authority cannot approve, and revocation works the
same way.
- Cloud sleep: on a managed stack, the MCP sleep proof blocks sleep
until the client mirror publishes the tenant front door to Cloud. The
client-mirror sync runs at boot and does this once. Stacks that already
had the flag on use this path today. A stack whose Cloud connector
cannot publish the mirror would stay awake. Watch fleet sleep after the
deploy.
- Personal public-MCP requests now read instance settings one time less.
- Fleet admin: the Cloud fleet catalog can still show and set
`enablePublicMcp`. The value is ignored. Removing it from the fleet
catalog is a separate change in the Cloud repo.
- No migration. The `0354` trigger still compares the stored key. That
causes at most one extra connector-runtime invalidation if an old client
writes the key.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, 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
- [x] 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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 11:42:36 -06:00

214 lines
15 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 { ApiError } from "@/api/client";
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 === "Retry")!.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 setup without an experimental-settings step", async () => {
await render();
expect(container.querySelector('a[href="/company/settings/instance/experimental"]')).toBeNull();
expect(container.textContent).not.toContain("Experimental settings");
expect(container.textContent).toContain("opencode mcp auth");
});
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("keeps Dot agent grants out of personal assistant setup and connected status", async () => {
const dot = { ...grant, id: "dot", clientName: "Dedicated Dot", scopes: ["paperclip:agent", "offline_access"] };
mocks.connections.mockResolvedValue([dot]);
await render(<AssistantConnectionCard onNavigate={vi.fn()} />);
expect(container.querySelector('[data-connected]')?.getAttribute("data-connected")).toBe("false");
expect(container.textContent).not.toContain("Connected as you");
await render();
expect(container.textContent).toContain("No assistants connected to Butter yet");
expect(container.textContent).not.toContain("Dedicated Dot");
mocks.connections.mockResolvedValue([dot, 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="Revoke Dotta’s OpenCode connection"]')).not.toBeNull();
expect(container.textContent).not.toContain("Dedicated Dot");
expect(container.querySelector('[aria-label="Revoke Dotta’s Dedicated Dot connection"]')).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 === "Retry")!.click());
await flush();
expect(container.textContent).toContain("opencode mcp auth paperclip");
});
it("keeps the card's loaded connection status through a transient refetch failure", async () => {
mocks.connections.mockResolvedValue([grant]);
await render(<AssistantConnectionCard onNavigate={vi.fn()} />);
expect(container.querySelector('[aria-label="Manage Assistant Connection (MCP)"]')).not.toBeNull();
mocks.connections.mockRejectedValue(new ApiError("Paperclip is restarting.", 503, { error: "tenant_app_unavailable" }));
await act(async () => { await client.invalidateQueries({ queryKey: ["mcp-connections"] }); });
await flush();
expect(container.querySelector('[aria-label="Manage Assistant Connection (MCP)"]')).not.toBeNull();
expect(container.querySelector('[data-connected]')?.getAttribute("data-connected")).toBe("true");
expect(container.textContent).toContain("Dotta’s OpenCode connection");
expect(container.querySelector('[data-query-view="error"]')).toBeNull();
expect(container.textContent).not.toContain("Paperclip is restarting.");
});
it("keeps connected assistants listed when the page's refetch fails transiently", async () => {
mocks.connections.mockResolvedValue([grant]);
await render();
expect(container.textContent).toContain("Dotta’s OpenCode connection");
mocks.connections.mockRejectedValue(new ApiError("Paperclip is restarting.", 503, { error: "tenant_app_unavailable" }));
await act(async () => { await client.invalidateQueries({ queryKey: ["mcp-connections"] }); });
await flush();
expect(container.textContent).toContain("Dotta’s OpenCode connection");
expect(container.querySelector('[aria-label="Revoke Dotta’s OpenCode connection"]')).not.toBeNull();
expect(container.textContent).not.toContain("No assistants connected");
expect(container.querySelector('[data-query-view="error"]')).toBeNull();
expect(container.textContent).not.toContain("Paperclip is restarting.");
});
it("shows readable copy and a Retry when the connection list fails for real", async () => {
mocks.connections.mockRejectedValueOnce(new ApiError("Boom", 500, { error: "Boom" }));
await render();
const errorView = container.querySelector('[data-query-view="error"]');
expect(errorView?.textContent).toContain("Couldn't load your connections");
expect(container.textContent).not.toContain("No assistants connected");
mocks.connections.mockResolvedValue([grant]);
await act(async () => Array.from(errorView!.querySelectorAll("button")).find(b => b.textContent === "Retry")!.click());
await flush();
expect(container.querySelector('[data-query-view="error"]')).toBeNull();
expect(container.textContent).toContain("Dotta’s OpenCode connection");
});
it.each([
[401, "Sign in to connect an assistant."],
[404, "Assistant connections need an authenticated instance with a public HTTPS URL."],
])("explains a %s setup response with instance-specific copy", async (status, copy) => {
mocks.setup.mockRejectedValue(new ApiError("Request failed", status, { error: "Request failed" }));
await render();
expect(container.querySelector('[role="alert"]')?.textContent).toContain(copy);
expect(container.querySelector('[data-query-view="error"]')).toBeNull();
});
});