Files
PaperClipAI/tests/e2e/connection-reviews.spec.ts
T
TonioandClaude Fable 5.2 5ea8c99717 fix(ui): close the Plugins review follow-ups and add the Reviews page (#23005)
## 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>
2026-11-26 02:23:18 +00:00

418 lines
17 KiB
TypeScript

import { expect, test, type APIRequestContext } from "@playwright/test";
import { readFile, writeFile } from "node:fs/promises";
import { startReviewProvider } from "../fixtures/connection-review-provider";
type Json = Record<string, unknown>;
type Seed = { companyId: string; prefix: string };
type Agent = { id: string; name: string };
async function json<T = Json>(
response: Awaited<ReturnType<APIRequestContext["get"]>>,
): Promise<T> {
expect(
response.ok(),
`${response.url()} failed ${response.status()}: ${await response.text()}`,
).toBe(true);
return (await response.json()) as T;
}
async function newCompany(request: APIRequestContext): Promise<Seed> {
const company = await json<{ id: string; issuePrefix: string }>(
await request.post("/api/companies", {
data: { name: `Connection review E2E ${Date.now()}` },
}),
);
return { companyId: company.id, prefix: company.issuePrefix };
}
async function createAgent(
request: APIRequestContext,
companyId: string,
name: string,
): Promise<Agent> {
return await json<Agent>(
await request.post(`/api/companies/${companyId}/agents`, {
data: {
name,
role: "qa",
title: "Connection intent fixture agent",
capabilities: "Exercises deterministic connection intent wiring.",
adapterType: "process",
adapterConfig: {
command: process.execPath,
args: ["--input-type=module", "-e", "process.exit(0)"],
},
},
}),
);
}
function reviewAgentScript(connectionId: string, query: string) {
return `
const base = process.env.PAPERCLIP_API_URL + "/api";
const headers = { authorization: "Bearer " + process.env.PAPERCLIP_API_KEY, "content-type": "application/json", "x-paperclip-run-id": process.env.PAPERCLIP_RUN_ID };
const api = async (path, method = "GET", body) => {
const response = await fetch(base + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
if (!response.ok) throw new Error(await response.text());
return await response.json();
};
const describePages = (raw) => {
let value = raw;
if (typeof value === "string") { try { value = JSON.parse(value); } catch {} }
const content = typeof value === "string" ? value : typeof value?.content === "string" ? value.content : value?.data?.content?.filter(item => item.type === "text").map(item => item.text).join(" ") ?? "No pages returned.";
return "I found these recent pages: " + content.replace(/^Pages: /, "") + ".";
};
const issueId = process.env.PAPERCLIP_TASK_ID ?? (await api("/heartbeat-runs/" + process.env.PAPERCLIP_RUN_ID)).contextSnapshot.issueId;
const interactions = await api("/issues/" + issueId + "/interactions");
const review = interactions.find(i => i.payload?.toolAction);
if (review?.status === "pending") { console.log("Still waiting for the existing review; no retry."); process.exit(0); }
if (review && review.status !== "pending") {
const result = review.result?.toolAction;
if (review.status === "accepted" && (!result || ["approved", "executing"].includes(result.status))) {
console.log("Review accepted; waiting for the stored execution result. No retry.");
process.exit(0);
}
const message = review.status === "rejected" ? "Review declined. No pages were read." : result?.status === "failed" ? "Read failed: " + result.errorMessage : ["expired", "cancelled"].includes(review.status) ? "The review expired or was cancelled. No pages were read." : describePages(result?.resultSummary);
await api("/issues/" + issueId + "/comments", "POST", { body: message });
await api("/issues/" + issueId, "PATCH", { status: "done" });
console.log(message);
process.exit(0);
}
const session = await api("/tool-gateway/sessions", "POST", { runId: process.env.PAPERCLIP_RUN_ID, ttlMs: 60000 });
const gatewayHeaders = { "x-paperclip-tool-gateway-token": session.token, "content-type": "application/json" };
const tools = await (await fetch(base + "/tool-gateway/tools", { headers: gatewayHeaders })).json();
const tool = tools.find(t => t.connectionId === ${JSON.stringify(connectionId)} && t.upstreamToolName === "notion:list_pages");
if (!tool) throw new Error("Missing fixture connection");
const call = await fetch(base + "/tool-gateway/tools/call", { method: "POST", headers: gatewayHeaders, body: JSON.stringify({ tool: tool.name, parameters: { query: ${JSON.stringify(query)} } }) });
const result = await call.json();
if (!call.ok) {
if (result.reasonCode !== "approval_required" && result.code !== "approval_required" && !JSON.stringify(result).includes("approval_required")) throw new Error(JSON.stringify(result));
await api("/issues/" + issueId, "PATCH", { status: "in_review" });
console.log("Waiting for human review. No retry.");
process.exit(0);
}
await api("/issues/" + issueId + "/comments", "POST", { body: describePages(result.result) });
await api("/issues/" + issueId, "PATCH", { status: "done" });
`;
}
for (const journey of [
"approve",
"decline",
"always",
"failure",
"restart",
] as const) {
test(`connection review: ${journey}, synchronized task history and actual continuation`, async ({
page,
context,
request,
}, testInfo) => {
test.setTimeout(180_000);
test.skip(
journey === "restart" && !process.env.PAPERCLIP_REVIEW_RESTART_FILE,
"Use connection-reviews.config.ts for controlled server restart",
);
let suppressReviewEvents = journey === "decline";
if (journey === "decline") {
// Reproduce a review arriving between the initial fetch and subscription:
// return an empty first snapshot and drop its live creation notification.
const initialSnapshots = new Set<string>();
await page.route("**/api/issues/*/interactions", async (route) => {
const url = route.request().url();
if (route.request().method() === "GET" && !initialSnapshots.has(url)) {
initialSnapshots.add(url);
await route.fulfill({ json: [] });
} else await route.continue();
});
await page.routeWebSocket("**/api/companies/*/events/ws", (socket) => {
const server = socket.connectToServer();
server.onMessage((message) => {
if (suppressReviewEvents && String(message).includes("issue.thread_interaction_")) return;
socket.send(message);
});
});
}
const fullUiSetup = journey === "approve" || journey === "decline" || journey === "restart";
const provider = await startReviewProvider();
try {
const seed = await newCompany(request);
const agent = await createAgent(request, seed.companyId, "Page reader");
let connectionId: string;
if (fullUiSetup) {
await page.goto(`/${seed.prefix}/apps`);
await page.getByRole("button", { name: "Add", exact: true }).click();
await page.getByRole("menuitem", { name: /MCP server URL/ }).click();
await page
.getByPlaceholder("https://example.com/actions")
.fill(provider.url);
await page.getByRole("button", { name: "Continue", exact: true }).click();
await page.getByRole("button", { name: /Check link/i }).click();
await expect(
page.getByRole("heading", { name: /is ready/i }),
).toBeVisible({ timeout: 30_000 });
const {
connections: [connection],
} = await json<{ connections: Array<{ id: string }> }>(
await request.get(`/api/companies/${seed.companyId}/tools/connections`),
);
connectionId = connection.id;
await json(
await request.put(`/api/tool-connections/${connectionId}/installs`, {
data: { installs: [{ targetType: "agent", targetId: agent.id }] },
}),
);
await page.goto(`/${seed.prefix}/apps/${connectionId}/permissions`);
const [permissionSave] = await Promise.all([
page.waitForResponse(response => response.request().method() === "POST" &&
new URL(response.url()).pathname === `/api/companies/${seed.companyId}/tools/apps/${connectionId}/finish`),
page.getByRole("radio", { name: "List fixture pages: Ask first" }).click(),
]);
expect(permissionSave.ok()).toBe(true);
} else {
const connected = await json<{ connectionId: string; catalog: Array<{ id: string }> }>(
await request.post(`/api/companies/${seed.companyId}/tools/apps/connect`, {
data: { link: provider.url },
}),
);
connectionId = connected.connectionId;
const catalogIds = connected.catalog.map((entry) => entry.id);
await json(
await request.post(`/api/companies/${seed.companyId}/tools/apps/${connectionId}/finish`, {
data: {
enabledCatalogEntryIds: catalogIds,
askFirstCatalogEntryIds: catalogIds,
access: { agentIds: [agent.id] },
},
}),
);
}
const configureAgent = async (query: string) =>
json(
await request.patch(`/api/agents/${agent.id}`, {
data: {
adapterConfig: {
command: process.execPath,
args: [
"--input-type=module",
"-e",
reviewAgentScript(connectionId, query),
],
},
replaceAdapterConfig: true,
},
}),
);
await configureAgent(journey === "failure" ? "fail" : "recent");
const issue = await json<{ id: string; identifier: string }>(
await request.post(`/api/companies/${seed.companyId}/issues`, {
data: {
title: "Read recent pages",
status: "in_progress",
assigneeAgentId: agent.id,
},
}),
);
await page.goto(`/${seed.prefix}/issues/${issue.identifier}`);
await expect(
page.getByRole("button", { name: "Approve & run", exact: true }),
).toBeVisible({ timeout: 45_000 });
suppressReviewEvents = false;
const originatingReviews = await json<Array<{ id: string; sourceRunId: string | null }>>(await request.get(`/api/issues/${issue.id}/interactions`));
const originatingReview = originatingReviews[0];
const calls = () =>
provider.captures.filter((c) => c.method === "tools/call").length;
expect(calls()).toBe(0);
let queue: Awaited<ReturnType<typeof context.newPage>> | null = null;
if (fullUiSetup) {
await page.screenshot({
path: testInfo.outputPath("pending-review.png"),
});
await page
.getByRole("button", { name: "Dismiss Approve tool action" })
.click();
await expect(
page.getByRole("button", { name: "Approve & run", exact: true }),
).not.toBeVisible();
await page.reload();
await expect(page.getByRole("button", { name: "Review request", exact: true })).toBeVisible({ timeout: 30_000 });
await expect(
page.getByRole("button", { name: "Approve & run", exact: true }),
).not.toBeVisible();
await json(
await request.post(`/api/issues/${issue.id}/comments`, {
data: { body: "Keeping this review pending while I check." },
}),
);
await page
.getByRole("button", { name: "Review request", exact: true })
.click();
await expect(
page.getByRole("button", { name: "Approve & run", exact: true }),
).toBeVisible();
queue = await context.newPage();
await queue.goto(`/${seed.prefix}/apps/review`);
await expect(
queue.getByRole("button", { name: "Deny", exact: true }),
).toBeVisible({ timeout: 20_000 });
}
if (journey === "restart") {
const control = process.env.PAPERCLIP_REVIEW_RESTART_FILE!;
const token = String(Date.now());
await writeFile(control, `restart:${token}`);
await expect
.poll(() => readFile(control, "utf8"), { timeout: 60_000 })
.toBe(`started:${token}`);
await expect
.poll(
async () => {
try {
return (await request.get("/api/health")).ok();
} catch {
return false;
}
},
{ timeout: 60_000 },
)
.toBe(true);
await page.reload();
await queue!.reload();
await expect(
page.getByRole("button", { name: "Approve & run", exact: true }),
).not.toBeVisible();
await page.getByRole("button", { name: "Review request", exact: true }).click();
await expect(
page.getByRole("button", { name: "Approve & run", exact: true }),
).toBeVisible();
expect(calls()).toBe(0);
}
if (journey === "decline") {
// Resolve from Connections and observe the still-open task tab update.
await queue!
.getByRole("button", { name: "Deny", exact: true })
.click();
} else {
if (journey === "always") {
await page.getByRole("button", { name: "Approval options", exact: true }).click();
await page.getByRole("menuitem", { name: "Always allow", exact: true }).click();
} else {
await page.getByRole("button", { name: "Approve & run", exact: true }).click();
}
}
await expect
.poll(
async () =>
(
await json<Array<{ body: string }>>(
await request.get(`/api/issues/${issue.id}/comments`),
)
)
.map((c) => c.body)
.join("\n"),
{ timeout: 60_000 },
)
.toContain(
journey === "decline"
? "Review declined"
: journey === "failure"
? "Read failed"
: "Roadmap",
);
const replies = await json<Array<{ id: string; body: string; authorAgentId: string | null; createdByRunId: string | null }>>(await request.get(`/api/issues/${issue.id}/comments`));
const reply = replies.find(comment => comment.authorAgentId === agent.id)!;
expect(reply.createdByRunId).toBeTruthy();
expect(originatingReview.sourceRunId).toBeTruthy();
expect(reply.createdByRunId).not.toBe(originatingReview.sourceRunId);
expect(reply.body).not.toContain('"content":');
if (!["decline", "failure"].includes(journey)) {
await expect(page.getByRole("button", { name: "Show result details" })).toBeVisible();
await expect(page.locator("pre")).not.toBeVisible();
await page.getByRole("button", { name: "Show result details" }).click();
await expect(page.locator("pre")).toContainText('"content":');
await page.getByRole("button", { name: "Hide result details" }).click();
}
expect(calls()).toBe(journey === "decline" ? 0 : 1);
await expect(
page.getByRole("button", { name: "Approve & run", exact: true }),
).not.toBeVisible();
if (queue) {
await expect(
queue.getByRole("button", { name: "Deny", exact: true }),
).not.toBeVisible({ timeout: 20_000 });
}
await page.bringToFront();
expect(await page.evaluate(() => document.visibilityState)).toBe("visible");
await page.reload();
const resolvedReview = page.locator(`[id=${JSON.stringify(`interaction-${originatingReview.id}`)}]`);
if (!["decline", "failure"].includes(journey)) {
await expect(resolvedReview.getByRole("button", { name: "Show result details", exact: true }).filter({ hasText: "Succeeded" })).toBeVisible();
} else {
await expect(resolvedReview.getByText(journey === "decline" ? "Declined" : "Execution failed", { exact: false })).toBeVisible();
}
await expect(resolvedReview).toContainText("List fixture pages");
const persistedReply = page.locator(`[id=${JSON.stringify(`comment-${reply.id}`)}]`);
await expect(persistedReply).toBeVisible();
await expect(persistedReply).toContainText(
journey === "decline" ? "Review declined" : journey === "failure" ? "Read failed" : "Roadmap",
);
await expect(page.getByTestId("task-chat-history-content")).toBeVisible({
timeout: 30_000,
});
await page.screenshot({
path: testInfo.outputPath("resolved-review.png"),
});
if (journey === "always") {
await configureAgent("different search options");
const later = await json<{ id: string }>(
await request.post(`/api/companies/${seed.companyId}/issues`, {
data: {
title: "Read pages with different arguments",
status: "in_progress",
assigneeAgentId: agent.id,
},
}),
);
await expect
.poll(
async () =>
(
await json<Array<{ body: string }>>(
await request.get(`/api/issues/${later.id}/comments`),
)
)
.map((c) => c.body)
.join("\n"),
{ timeout: 45_000 },
)
.toContain("Roadmap");
expect(calls()).toBe(2);
expect(
await json<unknown[]>(
await request.get(`/api/issues/${later.id}/interactions`),
),
).toHaveLength(0);
}
await testInfo.attach("journey", {
body: JSON.stringify(
{
source: "local MCP fixture; no live Notion",
journey,
...seed,
issue,
agent,
providerCalls: calls(),
},
null,
2,
),
contentType: "application/json",
});
await queue?.close();
} finally {
await provider.close();
}
});
}