feat(apps): support multiple provider connections (#11060)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The Apps subsystem connects company tools through governed provider
connections.
> - A company can need more than one account for the same provider.
> - The current database constraint and Apps flow assume one named
connection per company.
> - New quarantined actions also need an explicit review decision before
activation.
> - This pull request supports multiple provider connections and
complete action review decisions.
> - The benefit is safer access control and a clear multi-account Apps
workflow.

## Linked Issues or Issue Description

Refs: #11040

**Subsystem affected**

Cross-cutting. This change affects the Apps UI, the tool access API, the
shared request contract, and the database schema.

**Problem or motivation**

The connection name constraint prevents a company from keeping more than
one connection for a provider. The Apps UI also reuses an existing OAuth
connection when a user asks to connect another account. Action review
can enable selected entries without recording a decision for every
quarantined action.

**Proposed solution**

Remove the company and connection name uniqueness constraint. Let users
open, count, edit, and create multiple provider connections. Require the
finish request to cover every quarantined action exactly once before the
server activates reviewed entries.

**Alternatives considered**

The UI could generate unique internal names and keep the database
constraint. This would preserve a one-connection assumption in the data
model and would make display names part of identity. The server could
also infer review decisions from enabled actions. This would not
distinguish a reviewed disabled action from an action that the user did
not review.

**Roadmap alignment**

This change extends the completed MCP Tool Gateway and Apps milestone.
It also supports the Connected Apps roadmap item. It follows the
navigation and connection management work in #11040.

## What Changed

- Remove the company-scoped connection name uniqueness index with an
ordered and idempotent migration.
- Add a reviewed action list to the finish-app contract and reject
incomplete or duplicate review decisions.
- Activate reviewed entries and keep unreviewed quarantined entries
blocked.
- Enable a completed connection and preserve the company and connection
scope in all updates.
- Show provider connection counts and open the provider setup page from
Browse.
- Let users edit existing connections or connect another account without
reusing an active OAuth connection.
- Update focused server and UI coverage for multiple connections and
action review.

## Verification

- Ran the focused Apps UI suite. All 116 tests passed in 11 files.
- Ran the focused server and CLI suite. All 276 tests passed in 3 files.
- Ran `pnpm --filter @paperclipai/db check:migrations`. The migration
safety check passed.
- Ran `pnpm -r typecheck`. All projects passed.
- Ran `pnpm build`. All projects built successfully.
- Ran `pnpm test:run`. It passed 3,735 tests and skipped 4 tests. One
worktree-safety assertion failed because the execution workspace reloads
its worktree marker. The same test passed with an isolated non-worktree
marker.
- Ran `pnpm check:token-gates`. It reports 12 existing violations in the
unchanged `PaperclipOrbit3D.tsx` file from the target branch.
- Started the six affected Playwright specifications. Chromium could not
start because the host does not provide `libatk-1.0.so.0`. The GitHub
e2e jobs will verify these specifications.
- GitHub Actions passed every final-head CI gate, including all three
e2e shards and the aggregate `e2e` and `verify` jobs.
- Greptile reviewed final commit `9af9200426` at 5/5 with zero review
threads.

## Risks

- Removing the name uniqueness index permits duplicate display names.
Stable connection IDs and UIDs remain unique within a company.
- The finish-app endpoint accepts the new review field as optional for
backward compatibility. When clients send it, the server requires a
complete decision for all quarantined actions.
- Multiple OAuth connections depend on the explicit new-connection route
flag. Focused tests cover active and draft connection reuse.
- The migration is ordered after migration 0210. Its `DROP INDEX IF
EXISTS` statement is safe to repeat.

> 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

OpenAI Codex with the `gpt-5.6-sol` model assisted this change. The
agent used repository tools, code execution, test execution, and agentic
reasoning. The Codex runtime manages the context window.

## 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:
Dotta 2026-08-07 16:28:04 -05:00 committed by GitHub
parent a71b9cf628
commit 0a511ed1b0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
32 changed files with 39376 additions and 131 deletions

View File

@ -0,0 +1 @@
DROP INDEX IF EXISTS "tool_connections_company_name_uq";

File diff suppressed because it is too large Load Diff

View File

@ -1464,6 +1464,13 @@
"when": 1786032087897,
"tag": "0210_heartbeat_context_taskkey_index",
"breakpoints": true
},
{
"idx": 211,
"version": "7",
"when": 1786129601533,
"tag": "0211_bright_morg",
"breakpoints": true
}
]
}

View File

@ -141,7 +141,6 @@ export const toolConnections = pgTable(
index("tool_connections_company_idx").on(table.companyId),
index("tool_connections_application_idx").on(table.applicationId),
index("tool_connections_company_enabled_idx").on(table.companyId, table.enabled),
uniqueIndex("tool_connections_company_name_uq").on(table.companyId, table.name),
uniqueIndex("tool_connections_company_uid_uq").on(table.companyId, table.uid),
unique("tool_connections_company_id_uq").on(table.companyId, table.id),
],

View File

@ -281,6 +281,7 @@ export type ReconnectToolApp = z.infer<typeof reconnectToolAppSchema>;
export const finishToolAppSchema = z.object({
enabledCatalogEntryIds: z.array(z.string().uuid()).max(500).default([]),
askFirstCatalogEntryIds: z.array(z.string().uuid()).max(500).default([]),
reviewedCatalogEntryIds: z.array(z.string().uuid()).max(500).optional(),
access: z.union([
z.literal("all_agents"),
z.object({ agentIds: z.array(z.string().uuid()).min(1).max(250) }),

View File

@ -3045,7 +3045,7 @@ describeEmbeddedPostgres("tool access service", () => {
expect(callbackRes.body.connection).toMatchObject({
id: connectRes.body.connectionId,
status: "active",
enabled: false,
enabled: true,
credentialSecretRefs: [
expect.objectContaining({ configPath: "oauth.access_token", label: "OAuth access token" }),
expect.objectContaining({ configPath: "oauth.refresh_token", label: "OAuth refresh token" }),
@ -3713,7 +3713,7 @@ describeEmbeddedPostgres("tool access service", () => {
.select()
.from(toolConnections)
.where(eq(toolConnections.id, connect.connectionId));
expect(preserved).toMatchObject({ status: "active", enabled: false });
expect(preserved).toMatchObject({ status: "active", enabled: true });
expect(preserved.credentialSecretRefs.map((ref) => ref.configPath)).toEqual(expect.arrayContaining([
"oauth.access_token",
"oauth.refresh_token",
@ -4501,6 +4501,36 @@ describeEmbeddedPostgres("tool access service", () => {
}, { actorType: "user", actorId: "board" })).rejects.toMatchObject({ status: 404 });
});
it("allows multiple same-named connections on one application", async () => {
const company = await createCompany(db);
const service = toolAccessService(db);
mockToolsList([
{
name: "read_items",
description: "Read items.",
inputSchema: { type: "object", properties: {} },
annotations: { readOnlyHint: true },
},
]);
const first = await service.connectGalleryApp(company.id, {
link: "https://first.example.test/actions",
name: "Notion",
}, { actorType: "user", actorId: "board" });
const second = await service.connectGalleryApp(company.id, {
link: "https://second.example.test/actions",
name: "Notion",
applicationId: first.application.id,
}, { actorType: "user", actorId: "board" });
expect(second.application.id).toBe(first.application.id);
expect(second.connectionId).not.toBe(first.connectionId);
const rows = await db.select().from(toolConnections).where(eq(toolConnections.applicationId, first.application.id));
expect(rows).toHaveLength(2);
expect(rows.map((row) => row.name)).toEqual(["Notion", "Notion"]);
expect(new Set(rows.map((row) => row.uid))).toHaveProperty("size", 2);
});
it("does not delete a reused application when the connect rolls back", async () => {
const company = await createCompany(db);
const service = toolAccessService(db);
@ -5084,6 +5114,56 @@ describeEmbeddedPostgres("tool access service", () => {
catalogEntryId: updateEntry.id,
}),
});
const createEntry = rereview.catalog.find((entry) => entry.toolName === "create_zap")!;
await service.finishGalleryAppConnection(company.id, connect.connectionId, {
enabledCatalogEntryIds: [listEntry.id, updateEntry.id],
askFirstCatalogEntryIds: [updateEntry.id],
access: { agentIds: [agent.id] },
}, { actorType: "user", actorId: "board" });
const stillQuarantined = await db
.select()
.from(toolCatalogEntries)
.where(eq(toolCatalogEntries.connectionId, connect.connectionId));
expect(stillQuarantined).toEqual(expect.arrayContaining([
expect.objectContaining({ id: updateEntry.id, status: "quarantined" }),
expect.objectContaining({ id: createEntry.id, status: "quarantined" }),
]));
await expect(service.finishGalleryAppConnection(company.id, connect.connectionId, {
enabledCatalogEntryIds: [listEntry.id, createEntry.id],
askFirstCatalogEntryIds: [createEntry.id],
reviewedCatalogEntryIds: [createEntry.id],
access: { agentIds: [agent.id] },
}, { actorType: "user", actorId: "board" })).rejects.toMatchObject({
status: 400,
message: "Action review decisions must cover every currently quarantined action exactly once",
});
const reviewed = await service.finishGalleryAppConnection(company.id, connect.connectionId, {
enabledCatalogEntryIds: [listEntry.id, createEntry.id],
askFirstCatalogEntryIds: [createEntry.id],
reviewedCatalogEntryIds: [updateEntry.id, createEntry.id],
access: { agentIds: [agent.id] },
}, { actorType: "user", actorId: "board" });
expect(reviewed.profileEntries).toEqual(expect.arrayContaining([
expect.objectContaining({ catalogEntryId: listEntry.id }),
expect.objectContaining({ catalogEntryId: createEntry.id }),
]));
expect(reviewed.profileEntries).not.toEqual(expect.arrayContaining([
expect.objectContaining({ catalogEntryId: updateEntry.id }),
]));
const reviewedCatalog = await db
.select()
.from(toolCatalogEntries)
.where(eq(toolCatalogEntries.connectionId, connect.connectionId));
expect(reviewedCatalog).toEqual(expect.arrayContaining([
expect.objectContaining({ id: updateEntry.id, status: "active", reviewedAt: expect.any(Date), quarantineReason: null }),
expect.objectContaining({ id: createEntry.id, status: "active", reviewedAt: expect.any(Date), quarantineReason: null }),
]));
const attentionAfterReview = await service.listAppsNeedingAttention(company.id);
expect(attentionAfterReview.apps).toEqual([]);
});
it("resolves Notion reads as allowed, mutations as ask-first, and denies cross-company use", async () => {

View File

@ -378,6 +378,7 @@ export function toolAccessRoutes(
profileEntryCount: result.profileEntries.length,
profileBindingCount: result.profileBindings.length,
askFirstPolicyCount: result.policies.length,
reviewedCatalogEntryCount: req.body.reviewedCatalogEntryIds?.length ?? 0,
access: req.body.access,
},
});

View File

@ -5177,8 +5177,31 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
const connection = await getConnectionRow(connectionId, companyId);
if (connection.status === "archived") throw conflict("Archived app connections cannot be finished");
const enabledIds = [...new Set([...input.enabledCatalogEntryIds, ...input.askFirstCatalogEntryIds])];
const requestedReviewedIds = input.reviewedCatalogEntryIds ?? [];
const reviewedIds = [...new Set(requestedReviewedIds)];
if (reviewedIds.length !== requestedReviewedIds.length) {
throw badRequest("Action review decisions must not contain duplicate catalogEntryId values");
}
const enabledRows = await assertCatalogEntriesForConnection(companyId, connection.id, enabledIds);
const askFirstRows = await assertCatalogEntriesForConnection(companyId, connection.id, input.askFirstCatalogEntryIds);
if (reviewedIds.length > 0) {
await assertCatalogEntriesForConnection(companyId, connection.id, reviewedIds);
const quarantinedRows = await db
.select({ id: toolCatalogEntries.id })
.from(toolCatalogEntries)
.where(and(
eq(toolCatalogEntries.companyId, companyId),
eq(toolCatalogEntries.connectionId, connection.id),
eq(toolCatalogEntries.status, "quarantined"),
));
const reviewedIdSet = new Set(reviewedIds);
if (
quarantinedRows.length !== reviewedIdSet.size
|| quarantinedRows.some((entry) => !reviewedIdSet.has(entry.id))
) {
throw badRequest("Action review decisions must cover every currently quarantined action exactly once");
}
}
if (input.access !== "all_agents") await assertAgentsInCompany(companyId, input.access.agentIds);
const entries: CreateToolProfileEntryForProfile[] = enabledRows.map((entry) => ({
@ -5281,6 +5304,25 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
}
const reviewedAt = new Date();
if (reviewedIds.length > 0) {
await tx
.update(toolCatalogEntries)
.set({
status: "active",
reviewedAt,
reviewedByAgentId: actor?.actorType === "agent" ? actor.actorId ?? null : null,
reviewedByUserId: actor?.actorType === "user" ? actor.actorId ?? null : null,
quarantinedAt: null,
quarantineReason: null,
updatedAt: reviewedAt,
})
.where(and(
eq(toolCatalogEntries.companyId, companyId),
eq(toolCatalogEntries.connectionId, connection.id),
inArray(toolCatalogEntries.id, reviewedIds),
eq(toolCatalogEntries.status, "quarantined"),
));
}
if (enabledIds.length > 0) {
await tx
.update(toolCatalogEntries)
@ -5293,7 +5335,11 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
quarantineReason: null,
updatedAt: reviewedAt,
})
.where(and(eq(toolCatalogEntries.companyId, companyId), inArray(toolCatalogEntries.id, enabledIds)));
.where(and(
eq(toolCatalogEntries.companyId, companyId),
inArray(toolCatalogEntries.id, enabledIds),
ne(toolCatalogEntries.status, "quarantined"),
));
}
const policies = await upsertAskFirstPolicies({
@ -5720,7 +5766,7 @@ export function toolAccessService(db: Db, options: ToolAccessServiceOptions = {}
.update(toolConnections)
.set({
status: "active",
enabled: isSmokeLabOAuthFixture(connection) ? true : false,
enabled: true,
config: nextConfig,
transportConfig: nextConfig,
credentialSecretRefs: nextCredentialSecretRefs,

View File

@ -143,14 +143,16 @@ test.describe.serial("not-connected app page", () => {
expect(appConns[0].status).not.toBe("archived");
});
test("connected app page redirects from the app route and its row says Open", async ({ page }) => {
test("draft app connection stays on provider setup until setup finishes", async ({ page }) => {
await page.goto(`/${seed.prefix}/apps/app/${applicationId}`);
await expect(page).toHaveURL(new RegExp(`/${seed.prefix}/apps/${connectionId}/setup$`), { timeout: 20_000 });
await expect(page).toHaveURL(new RegExp(`/${seed.prefix}/apps/app/${applicationId}/setup$`), { timeout: 20_000 });
await expect(page.getByText("Not connected", { exact: true })).toBeVisible();
await expect(page.getByRole("heading", { name: "Connect this app" })).toBeVisible();
await page.goto(`/${seed.prefix}/apps/connections`);
const row = page.locator("tbody tr", { hasText: "Bla" });
await expect(row).toBeVisible({ timeout: 30_000 });
await expect(row.getByRole("button", { name: /Open|Review/ })).toBeVisible();
await expect(row.getByRole("button", { name: "Connect" })).toBeVisible();
await page.screenshot({ path: `${SCREENSHOT_DIR}/apps-nav-w6-03-reconnected-row.png`, fullPage: true });
});

View File

@ -88,7 +88,7 @@ test.describe.serial("applications lifecycle", () => {
// background health sweep then probes the connection endpoint. The test
// endpoint is an unreachable fixture URL, so the probe fails and the pill
// becomes "Needs attention" and the action becomes "Reconnect". Both are
// connected states that navigate to the same connection detail. This test
// connected states that navigate to the same provider setup page. This test
// proves the connected-vs-not-connected split, not the transient health
// label, so accept either connected state instead of the racy exact label.
// The pill is derived from two react-query fetches (applications +
@ -107,11 +107,17 @@ test.describe.serial("applications lifecycle", () => {
await page.screenshot({ path: `${SCREENSHOT_DIR}/applications-crud-current-list.png`, fullPage: true });
await connectedRow.getByRole("button", { name: /^(Open|Reconnect)$/ }).click();
await expect(page).toHaveURL(new RegExp(`/${seed.prefix}/apps/${connected.id}`), { timeout: 20_000 });
await expect(page).toHaveURL(
new RegExp(`/${seed.prefix}/apps/app/${connected.applicationId}/setup$`),
{ timeout: 20_000 },
);
await gotoApps(page, seed.prefix);
await notConnectedRow.getByRole("button", { name: "Connect" }).click();
await expect(page).toHaveURL(new RegExp(`/${seed.prefix}/apps/app/${notConnected.id}`), { timeout: 20_000 });
await expect(page).toHaveURL(
new RegExp(`/${seed.prefix}/apps/app/${notConnected.id}/setup$`),
{ timeout: 20_000 },
);
});
test("connected app detail supports pause, rename, and removal", async ({ page, request }) => {

View File

@ -248,6 +248,7 @@ export const toolsApi = {
finishApp: (companyId: string, connectionId: string, input: {
enabledCatalogEntryIds: string[];
askFirstCatalogEntryIds: string[];
reviewedCatalogEntryIds?: string[];
access: "all_agents" | { agentIds: string[] };
}) =>
api.post<FinishToolAppResult>(

View File

@ -171,7 +171,7 @@ describe("AppConnectionSidebar", () => {
expect(container.textContent).toContain("GitHub");
expect(container.querySelectorAll("[data-to]").length).toBe(6);
expect(sidebarNavItemMock).toHaveBeenCalledWith(expect.objectContaining({ to: "/apps/conn-1/setup", label: "Setup", end: true }));
expect(sidebarNavItemMock).toHaveBeenCalledWith(expect.objectContaining({ to: "/apps/conn-1/review", label: "Review", badge: 5, badgeTone: "danger" }));
expect(sidebarNavItemMock).toHaveBeenCalledWith(expect.objectContaining({ to: "/apps/conn-1/review", label: "Review", badge: 3, badgeTone: "danger" }));
expect(sidebarNavItemMock).toHaveBeenCalledWith(expect.objectContaining({ to: "/apps/conn-1/permissions", label: "Permissions", end: true }));
expect(sidebarNavItemMock).toHaveBeenCalledWith(expect.objectContaining({ to: "/apps/conn-1/test", label: "Test", end: true }));
expect(sidebarNavItemMock).toHaveBeenCalledWith(expect.objectContaining({ to: "/apps/conn-1/activity", label: "Activity", end: true }));

View File

@ -77,7 +77,8 @@ export function AppDetailSidebar(props: AppDetailSidebarProps) {
? attentionQuery.data?.apps.find((app) => app.connection.id === reviewConnectionId)
: null;
const reviewCount =
(attentionItem?.pendingActionRequestCount ?? 0) + (attentionItem?.quarantinedCatalogEntryCount ?? 0);
(attentionItem?.pendingActionRequestCount ?? 0) +
((attentionItem?.quarantinedCatalogEntryCount ?? 0) > 0 ? 1 : 0);
return (
<aside className="flex h-full min-h-0 w-full flex-col border-r border-border bg-background">

View File

@ -126,7 +126,7 @@ describe("AppsSidebar", () => {
// "Run your own" / "Paste a config" moved to the Connect-an-app page (PAP-10922);
// assert their absence at the item level below.
// Three peer consumer doors: Browse (store) · Connections · Review (PAP-13254).
// Consumer doors stay above the Developer boundary.
expect(sidebarNavItemMock).toHaveBeenCalledWith(
expect.objectContaining({ to: "/apps", label: "Browse", end: true }),
);
@ -136,6 +136,8 @@ describe("AppsSidebar", () => {
expect(sidebarNavItemMock).toHaveBeenCalledWith(
expect.objectContaining({ to: "/apps/review", label: "Review" }),
);
const sidebarText = container.textContent ?? "";
expect(sidebarText.indexOf("Connections")).toBeGreaterThan(sidebarText.indexOf("Developer"));
// "Needs attention" is no longer a top-level door — it folds into Connections.
expect(sidebarNavItemMock).not.toHaveBeenCalledWith(
expect.objectContaining({ label: "Needs attention" }),

View File

@ -14,12 +14,11 @@ import { SidebarNavItem } from "./SidebarNavItem";
* Secondary sidebar for the prosumer Apps area (PAP-10856; three-door IA
* PAP-13254 / U3).
*
* Back · APPS: Browse / Connections / Review (n)
* DEVELOPER: Gateways / Profiles / Rules / Health / Activity
* Back · APPS: Browse / Review (n)
* DEVELOPER: Connections / Gateways / Profiles / Rules / Health / Activity
*
* The three consumer doors are peers: "Browse" (the store discover + add),
* "Connections" (your connected tools + health), and "Review" (PAP-12371,
* Finding B decisions waiting on your OK, with a live pending count).
* "Browse" is the store and "Review" holds decisions waiting on the user's
* OK. Connection management lives with the Developer tools.
* "Needs attention" is no longer a door: health/error triage folds into
* Connections as a status filter + banner, so approvals are never buried
* behind an error label. The Developer section was folded in from the retired
@ -72,7 +71,6 @@ export function AppsSidebar() {
</div>
<div className="flex flex-col gap-0.5">
<SidebarNavItem to="/apps" label="Browse" icon={Store} end />
<SidebarNavItem to="/apps/connections" label="Connections" icon={AppWindow} end />
<SidebarNavItem
to="/apps/review"
label="Review"
@ -89,6 +87,7 @@ export function AppsSidebar() {
Advanced setup for developers. Most teams never open this.
</p>
<div className="flex flex-col gap-0.5">
<SidebarNavItem to="/apps/connections" label="Connections" icon={AppWindow} end />
{developerTabs.map((tab) => (
<SidebarNavItem
key={tab.key}

View File

@ -608,7 +608,7 @@ describe("Layout", () => {
// Reserved Apps subroutes are not connection ids. They must keep the
// top-level Apps sidebar, never mount a detail sidebar for a phantom app.
it.each(["browse", "review"])("keeps the Apps sidebar on the %s surface", async (route) => {
it.each(["browse", "connections", "review"])("keeps the Apps sidebar on the %s surface", async (route) => {
currentPathname = `/PAP/apps/${route}`;
const root = createRoot(container);
const queryClient = new QueryClient({

View File

@ -59,7 +59,16 @@ function getCompanyPathSegments(pathname: string, companyPrefix: string | undefi
return segments.slice(1);
}
const RESERVED_APP_SUBPATHS = new Set(["browse", "connect", "review", "attention", "gateways", "advanced", "app"]);
const RESERVED_APP_SUBPATHS = new Set([
"browse",
"connections",
"connect",
"review",
"attention",
"gateways",
"advanced",
"app",
]);
function isSkillsStoreRoute(pathname: string, companyPrefix: string | undefined) {
const segments = pathname.split("/").filter(Boolean);

View File

@ -294,7 +294,7 @@ describe("AppDetail", () => {
it.each([
["setup", "Agents can use this app"],
["review", "1 new action to review"],
["review", "Review 1 new action"],
["permissions", "Action permissions"],
["activity", "No activity yet."],
["advanced", "Technical details"],
@ -326,20 +326,72 @@ describe("AppDetail", () => {
expect(container.textContent).not.toContain("zapier-secret");
});
it("shows new quarantined actions on the review tab instead of an empty state", async () => {
it("reviews quarantined actions as one toggle list and saves allowed and blocked choices together", async () => {
mockParams.tab = "review";
listCatalogMock.mockResolvedValue({
catalog: [
catalogEntry(),
catalogEntry({
id: "catalog-write",
toolName: "write_issue",
title: "Write issue",
isReadOnly: false,
}),
catalogEntry({
id: "catalog-quarantined-allow",
toolName: "delete_repo",
title: "Delete repo",
status: "quarantined",
isReadOnly: false,
}),
catalogEntry({
id: "catalog-quarantined-block",
toolName: "archive_repo",
title: "Archive repo",
status: "quarantined",
isReadOnly: false,
}),
],
});
await renderAppDetail();
expect(container.textContent).toContain("1 new action to review");
expect(container.textContent).toContain("Review 2 new actions");
expect(container.textContent).toContain("Delete repo");
expect(container.textContent).toContain("Archive repo");
expect(container.textContent).not.toContain("Nothing is waiting for your OK right now.");
const allowToggle = container.querySelector<HTMLButtonElement>(
'button[role="switch"][aria-label="Delete repo allowed"]',
);
expect(allowToggle?.getAttribute("aria-checked")).toBe("false");
await act(async () => {
allowToggle?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
await flushReact();
await act(async () => {
Array.from(container.querySelectorAll("button"))
.find((button) => button.textContent?.trim() === "Review")
.find((button) => button.textContent?.trim() === "Save choices")
?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
await flushReact();
expect(container.textContent).toContain("Delete repo");
expect(container.textContent).not.toContain("Nothing is waiting for your OK right now.");
expect(finishAppMock).toHaveBeenCalledWith("company-1", "conn-1", {
enabledCatalogEntryIds: expect.arrayContaining([
"catalog-read",
"catalog-write",
"catalog-quarantined-allow",
]),
askFirstCatalogEntryIds: ["catalog-write"],
reviewedCatalogEntryIds: expect.arrayContaining([
"catalog-quarantined-allow",
"catalog-quarantined-block",
]),
access: "all_agents",
});
const finishInput = finishAppMock.mock.calls.at(-1)?.[2] as { enabledCatalogEntryIds: string[] };
expect(finishInput.enabledCatalogEntryIds).not.toContain("catalog-quarantined-block");
});
it("keeps setup focused on description and lifecycle", async () => {
@ -476,7 +528,7 @@ describe("AppDetail", () => {
expect(container.textContent).toContain("Can make changes");
expect(container.textContent).toContain("Read repo");
expect(container.textContent).toContain("Write issue");
expect(container.textContent).toContain("1 new action to review");
expect(container.textContent).toContain("Review 1 new action");
const readSelect = container.querySelector<HTMLSelectElement>('select[aria-label="Read repo permission"]');
const writeSelect = container.querySelector<HTMLSelectElement>('select[aria-label="Write issue permission"]');
expect(readSelect?.value).toBe("allowed");

View File

@ -159,10 +159,16 @@ export function AppDetail() {
const [pending, setPending] = useState(false);
const persist = useMutation({
mutationFn: (next: { enabled: Set<string>; askFirst: Set<string>; access: AccessDraft }) =>
mutationFn: (next: {
enabled: Set<string>;
askFirst: Set<string>;
access: AccessDraft;
reviewed?: Set<string>;
}) =>
toolsApi.finishApp(selectedCompanyId!, connectionId, {
enabledCatalogEntryIds: [...next.enabled],
askFirstCatalogEntryIds: [...next.askFirst].filter((id) => next.enabled.has(id)),
...(next.reviewed ? { reviewedCatalogEntryIds: [...next.reviewed] } : {}),
access: next.access.mode === "all" ? "all_agents" : { agentIds: [...next.access.agentIds] },
}),
onMutate: () => setPending(true),
@ -317,13 +323,26 @@ export function AppDetail() {
}),
});
const apply = (mutate: { enabled?: Set<string>; askFirst?: Set<string>; access?: AccessDraft }) =>
const apply = (mutate: {
enabled?: Set<string>;
askFirst?: Set<string>;
access?: AccessDraft;
reviewed?: Set<string>;
}) =>
persist.mutate({
enabled: mutate.enabled ?? new Set(enabledIds),
askFirst: mutate.askFirst ?? new Set(askFirstIds),
access: mutate.access ?? access,
reviewed: mutate.reviewed,
});
const reviewQuarantined = (allowedIds: string[]) => {
const quarantinedIds = new Set(quarantined.map((entry) => entry.id));
const nextEnabled = new Set([...enabledIds].filter((id) => !quarantinedIds.has(id)));
for (const id of allowedIds) nextEnabled.add(id);
apply({ enabled: nextEnabled, reviewed: quarantinedIds });
};
if (!connectionId || !activeTab) {
return <Navigate replace to={connectionId ? appTabHref(connectionId, "setup") : "/apps/connections"} />;
}
@ -411,7 +430,7 @@ export function AppDetail() {
connectionId={connectionId}
quarantined={quarantined}
pending={pending}
onTurnOnQuarantined={(ids) => apply({ enabled: addAll(new Set(enabledIds), ids) })}
onReviewQuarantined={reviewQuarantined}
/>
)}
{activeTab === "permissions" && (
@ -432,7 +451,7 @@ export function AppDetail() {
onSaveInstall={(next) => persistInstall.mutate(next)}
onRefreshActions={() => refreshTools.mutate()}
onSetActionPermission={(id, next) => apply(actionPermissionMutation(id, next, enabledIds, askFirstIds))}
onTurnOnQuarantined={(ids) => apply({ enabled: addAll(new Set(enabledIds), ids) })}
onReviewQuarantined={reviewQuarantined}
/>
)}
{activeTab === "test" && (
@ -624,12 +643,6 @@ function galleryEntryFor(
null;
}
function addAll(set: Set<string>, ids: string[]): Set<string> {
const next = new Set(set);
for (const id of ids) next.add(id);
return next;
}
function actionPermissionMutation(
id: string,
next: "off" | "allowed" | "ask",

View File

@ -194,6 +194,57 @@ describe("AppNotConnected", () => {
expect(navigateComponentMock).toHaveBeenCalledWith({ to: "/apps/conn-live/permissions", replace: true });
});
it("shows all existing provider connections before connecting another", async () => {
listApplicationsMock.mockResolvedValue({
applications: [
application({
id: "app-1",
applicationKey: "app-gallery:notion:one",
name: "Notion",
metadata: { sourceTemplateKey: "notion" },
}),
application({
id: "app-2",
applicationKey: "app-gallery:notion:two",
name: "Notion workspace",
metadata: { sourceTemplateKey: "notion" },
}),
],
});
listConnectionsMock.mockResolvedValue({
connections: [
connection({ id: "conn-one", applicationId: "app-1", name: "Notion", status: "active" }),
connection({ id: "conn-two", applicationId: "app-2", name: "Notion team", status: "active" }),
],
});
await renderPage();
expect(navigateComponentMock).not.toHaveBeenCalled();
expect(container.textContent).toContain("2 connected");
expect(container.textContent).toContain("Already connected to Notion");
expect(container.textContent).toContain("Notion team");
expect(container.textContent).toContain("Connect another");
const editRows = Array.from(container.querySelectorAll("button")).filter((button) =>
button.textContent?.includes("Edit"),
);
await act(async () => {
editRows[1]?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
expect(mockNavigate).toHaveBeenCalledWith("/apps/conn-two/setup");
const connectAnother = Array.from(container.querySelectorAll("button")).find(
(button) => button.textContent?.trim() === "Connect another",
);
await act(async () => {
connectAnother?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
expect(mockNavigate).toHaveBeenCalledWith(
"/apps/connect?applicationId=app-1&name=Notion&new=1&source=notion",
);
});
it.each([
["setup", "Reconnect this app"],
["review", "Nothing is waiting for your OK right now."],

View File

@ -1,6 +1,11 @@
import { useEffect, useMemo } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { ToolConnection } from "@paperclipai/shared";
import {
connectionDisplaySecondaryHint,
humanizeConnectionDisplayName,
isToolConnectionAttentionHealth,
} from "@paperclipai/shared";
import { Navigate, useNavigate, useParams } from "@/lib/router";
import { useCompany } from "@/context/CompanyContext";
import { useBreadcrumbs } from "@/context/BreadcrumbContext";
@ -13,11 +18,13 @@ import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { AppLogo } from "./AppLogo";
import {
appApplicationSourceSlug,
appDefinitionLogoUrl,
appDefinitionName,
appDefinitionSlug,
type AppGalleryDisplayEntry,
} from "./app-definition-display";
import { isMcpDirectOAuthConnectSlug } from "./app-connect-policy";
import { connectionAddress, connectionTransportLabel, DangerZone } from "./AppDetail";
import { ActivityPanel } from "./app-detail/ActivityPanel";
import { ReviewPanel } from "./app-detail/ReviewPanel";
@ -52,11 +59,25 @@ export function AppNotConnected() {
() => (applicationsQuery.data?.applications ?? []).find((app) => app.id === applicationId),
[applicationsQuery.data, applicationId],
);
const appSourceSlug = appApplicationSourceSlug(application);
const relatedApplicationIds = useMemo(() => {
if (!application) return new Set<string>();
if (!appSourceSlug) return new Set([application.id]);
return new Set(
(applicationsQuery.data?.applications ?? [])
.filter((candidate) => appApplicationSourceSlug(candidate) === appSourceSlug)
.map((candidate) => candidate.id),
);
}, [application, applicationsQuery.data, appSourceSlug]);
const appConnections = useMemo(
() => (connectionsQuery.data?.connections ?? []).filter((c) => c.applicationId === applicationId),
[connectionsQuery.data, applicationId],
() => (connectionsQuery.data?.connections ?? []).filter((c) => relatedApplicationIds.has(c.applicationId)),
[connectionsQuery.data, relatedApplicationIds],
);
const activeConnection = appConnections.find((c) => c.status !== "archived") ?? null;
const activeConnections = useMemo(
() => appConnections.filter((c) => c.status !== "archived" && c.status !== "draft"),
[appConnections],
);
const activeConnection = activeConnections[0] ?? null;
const previousConnection = useMemo(() => latestArchivedConnection(appConnections), [appConnections]);
const activityQuery = useQuery({
queryKey: queryKeys.tools.connectionActivity(previousConnection?.id ?? "__none__"),
@ -123,35 +144,44 @@ export function AppNotConnected() {
</div>
);
}
if (activeConnection) {
if (activeConnection && activeTab !== "setup") {
return <Navigate to={appTabHref(activeConnection.id, activeTab)} replace />;
}
const gallery = (galleryQuery.data?.apps ?? []) as AppGalleryDisplayEntry[];
const logoUrl =
(application.applicationKey
? appDefinitionLogoUrl(gallery.find((entry) => appDefinitionSlug(entry) === application.applicationKey))
(appSourceSlug
? appDefinitionLogoUrl(gallery.find((entry) => appDefinitionSlug(entry) === appSourceSlug))
: undefined) ??
appDefinitionLogoUrl(
gallery.find((entry) => appDefinitionName(entry).toLowerCase() === application.name.toLowerCase()),
);
const previousAddress = previousConnection ? connectionAddress(previousConnection) : null;
const connectHref = reconnectHref({
const connectHref = newConnectionHref({
applicationId,
appName: application.name,
previousAddress,
sourceSlug: appSourceSlug,
});
return (
<div className="max-w-3xl space-y-6 pb-12">
<ApplicationHeader applicationName={application.name} description={application.description} logoUrl={logoUrl} />
<ApplicationHeader
applicationName={application.name}
description={application.description}
logoUrl={logoUrl}
connectedCount={activeConnections.length}
/>
{activeTab === "setup" && (
<SetupTab
applicationName={application.name}
activeConnections={activeConnections}
previousConnection={previousConnection}
previousAddress={previousAddress}
onConnect={() => navigate(connectHref)}
onEdit={(connectionId) => navigate(appTabHref(connectionId, "setup"))}
/>
)}
{activeTab === "review" && (
@ -215,10 +245,12 @@ function ApplicationHeader({
applicationName,
description,
logoUrl,
connectedCount,
}: {
applicationName: string;
description: string | null;
logoUrl: string | undefined;
connectedCount: number;
}) {
return (
<header className="flex flex-wrap items-center gap-4">
@ -227,7 +259,7 @@ function ApplicationHeader({
<div className="flex items-center gap-2">
<h1 className="truncate text-2xl font-bold tracking-tight">{applicationName}</h1>
<span className="inline-flex items-center rounded-full border border-border bg-background px-2 py-0.5 text-xs font-medium text-muted-foreground">
Not connected
{connectedCount > 0 ? `${connectedCount} connected` : "Not connected"}
</span>
</div>
{description && (
@ -239,14 +271,75 @@ function ApplicationHeader({
}
function SetupTab({
applicationName,
activeConnections,
previousConnection,
previousAddress,
onConnect,
onEdit,
}: {
applicationName: string;
activeConnections: ToolConnection[];
previousConnection: ToolConnection | null;
previousAddress: string | null;
onConnect: () => void;
onEdit: (connectionId: string) => void;
}) {
if (activeConnections.length > 0) {
return (
<div className="space-y-6">
<section className="space-y-3">
<div>
<h2 className="text-sm font-bold text-foreground">Already connected to {applicationName}</h2>
<p className="mt-0.5 text-sm text-muted-foreground">
Open a connection to edit it, or add another account.
</p>
</div>
<div className="overflow-hidden rounded-lg border border-border">
{activeConnections.map((connection) => {
const secondary = connectionDisplaySecondaryHint(connection) ??
(connection.lastUsedAt ? `Last used ${timeAgo(connection.lastUsedAt)}` : "Not used yet");
const status = connection.enabled === false || connection.status === "disabled"
? "Paused"
: isToolConnectionAttentionHealth(connection.healthStatus)
? "Needs attention"
: "Connected";
return (
<button
key={connection.id}
type="button"
onClick={() => onEdit(connection.id)}
className="flex w-full items-center gap-3 border-b border-border px-4 py-3 text-left transition-colors last:border-0 hover:bg-muted/30"
>
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-medium text-foreground">
{humanizeConnectionDisplayName(connection)}
</div>
<div className="truncate text-xs text-muted-foreground">{secondary}</div>
</div>
<span className="text-xs text-muted-foreground">{status}</span>
<span className="text-xs font-semibold text-primary">Edit </span>
</button>
);
})}
</div>
</section>
<section className="rounded-xl border border-border bg-card px-5 py-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h2 className="text-sm font-bold text-foreground">Connect another</h2>
<p className="mt-0.5 text-sm text-muted-foreground">
Add another {applicationName} account without changing the connections above.
</p>
</div>
<Button onClick={onConnect}>Connect another</Button>
</div>
</section>
</div>
);
}
return (
<div className="space-y-6">
<section className="rounded-xl border border-border bg-card px-5 py-4">
@ -366,16 +459,20 @@ function latestArchivedConnection(connections: ToolConnection[]): ToolConnection
});
}
function reconnectHref({
function newConnectionHref({
applicationId,
appName,
previousAddress,
sourceSlug,
}: {
applicationId: string;
appName: string;
previousAddress: string | null;
sourceSlug: string | null;
}): string {
const params = new URLSearchParams({ byo: "1", applicationId, name: appName });
const params = new URLSearchParams({ applicationId, name: appName, new: "1" });
if (sourceSlug) params.set("source", sourceSlug);
if (!isMcpDirectOAuthConnectSlug(sourceSlug)) params.set("byo", "1");
if (previousAddress && /^https?:\/\//i.test(previousAddress)) params.set("link", previousAddress);
return `/apps/connect?${params.toString()}`;
}

View File

@ -288,6 +288,58 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {
);
});
it("creates a fresh Notion OAuth connection when the provider landing requests another", async () => {
mockSearch.value = "source=notion&applicationId=app-notion&new=1";
listGalleryMock.mockResolvedValueOnce({ apps: [NOTION] });
listApplicationsMock.mockResolvedValueOnce({
applications: [{
id: "app-notion",
status: "active",
metadata: { sourceTemplateKey: "notion" },
}],
});
listConnectionsMock.mockResolvedValueOnce({
connections: [{
id: "conn-existing",
applicationId: "app-notion",
authKind: "oauth",
status: "active",
config: { sourceTemplateKey: "notion" },
transportConfig: {},
}, {
id: "conn-other-draft",
applicationId: "app-other",
authKind: "oauth",
status: "draft",
config: { sourceTemplateKey: "notion" },
transportConfig: {},
}],
});
connectAppMock.mockResolvedValueOnce({
connectionId: "conn-new",
application: { id: "app-notion", name: "Notion" },
connection: { id: "conn-new" },
actions: { readOnly: [], canMakeChanges: [] },
catalog: [],
suggestedDefaults: {},
auth: { kind: "oauth", startUrl: "https://mcp.notion.com/authorize?state=new" },
});
await render();
expect(startOAuthMock).not.toHaveBeenCalledWith("conn-existing");
expect(connectAppMock).toHaveBeenCalledWith("company-1", {
galleryKey: "notion",
name: "Notion",
credentialValues: {},
configValues: undefined,
applicationId: "app-notion",
});
expect(navigateTopLevelMock).toHaveBeenCalledWith(
"https://mcp.notion.com/authorize?state=new",
);
});
it("waits for fresh connection data before creating a Notion OAuth draft", async () => {
mockSearch.value = "source=notion";
listGalleryMock.mockResolvedValueOnce({ apps: [NOTION] });

View File

@ -109,18 +109,27 @@ function reusableOAuthConnection(
sourceSlug: string | null,
applications: ToolApplication[],
connections: ToolConnection[],
options: { applicationId?: string; draftOnly?: boolean } = {},
): ToolConnection | null {
if (!sourceSlug) return null;
const matchingApplicationIds = new Set(
applications
.filter((application) => application.status !== "archived" && appSourceSlug(application) === sourceSlug)
.filter((application) =>
application.status !== "archived" &&
appSourceSlug(application) === sourceSlug &&
(!options.applicationId || application.id === options.applicationId)
)
.map((application) => application.id),
);
return connections.find((connection) =>
connection.status !== "archived" &&
connection.authKind === "oauth" &&
(matchingApplicationIds.has(connection.applicationId) || connectionSourceSlug(connection) === sourceSlug)
) ?? null;
return connections.find((connection) => {
const matchesApplication = options.applicationId
? connection.applicationId === options.applicationId
: matchingApplicationIds.has(connection.applicationId) || connectionSourceSlug(connection) === sourceSlug;
return connection.status !== "archived" &&
(!options.draftOnly || connection.status === "draft") &&
connection.authKind === "oauth" &&
matchesApplication;
}) ?? null;
}
export function AppsConnect() {
@ -132,6 +141,7 @@ export function AppsConnect() {
const [searchParams] = useSearchParams();
const appKey = routeParams.appKey ?? searchParams.get("appKey") ?? undefined;
const sourceSlug = searchParams.get("source")?.trim() || null;
const createNewConnection = searchParams.get("new") === "1";
const directOAuthSource = isMcpDirectOAuthConnectSlug(sourceSlug) ? sourceSlug : null;
const requestedAppKey = appKey ?? directOAuthSource ?? undefined;
const zapierSource = sourceSlug === "zapier";
@ -216,8 +226,11 @@ export function AppsConnect() {
directOAuthSource,
applicationsQuery.data?.applications ?? [],
connectionsQuery.data?.connections ?? [],
createNewConnection
? { applicationId: prefill.applicationId, draftOnly: true }
: {},
),
[applicationsQuery.data, connectionsQuery.data, directOAuthSource],
[applicationsQuery.data, connectionsQuery.data, createNewConnection, directOAuthSource, prefill.applicationId],
);
const directOAuthEntry = entry &&
@ -467,6 +480,9 @@ export function AppsConnect() {
directOAuthSource,
applicationsResult.data?.applications ?? [],
connectionsResult.data?.connections ?? [],
createNewConnection
? { applicationId: prefill.applicationId, draftOnly: true }
: {},
);
if (refreshedConnection) {
startOAuth(refreshedConnection.id);

View File

@ -7,11 +7,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { Browse } from "./Browse";
const listGalleryMock = vi.hoisted(() => vi.fn());
const listApplicationsMock = vi.hoisted(() => vi.fn());
const listConnectionsMock = vi.hoisted(() => vi.fn());
const navigateMock = vi.hoisted(() => vi.fn());
vi.mock("@/api/tools", () => ({
toolsApi: {
listGallery: (companyId: string) => listGalleryMock(companyId),
listApplications: (companyId: string) => listApplicationsMock(companyId),
listConnections: (companyId: string) => listConnectionsMock(companyId),
},
}));
@ -80,6 +84,8 @@ describe("Browse store door (PAP-13254 door 1)", () => {
galleryEntry({ key: "acme", name: "Acme CRM", tagline: "Sync deals and contacts." }),
],
});
listApplicationsMock.mockResolvedValue({ applications: [] });
listConnectionsMock.mockResolvedValue({ connections: [] });
container = document.createElement("div");
document.body.appendChild(container);
});
@ -108,7 +114,9 @@ describe("Browse store door (PAP-13254 door 1)", () => {
const text = container.textContent ?? "";
expect(text).toContain("Browse");
expect(text).toContain("Connect Notion, Zapier, or your own MCP server.");
expect(text).toContain("Choose an app or connect your own MCP server.");
expect(text).not.toContain("More integrations are coming soon.");
expect(text).not.toContain("Other integrations are previews.");
expect(text).toContain("Popular");
expect(text).toContain("All apps");
expect(text).toContain("GitHub");
@ -186,6 +194,34 @@ describe("Browse store door (PAP-13254 door 1)", () => {
expect(text).not.toContain("Popular");
});
it("shows existing connection counts and opens the provider landing page", async () => {
listApplicationsMock.mockResolvedValue({
applications: [
{ id: "app-notion", status: "active", applicationKey: "app-gallery:notion:one", metadata: {} },
],
});
listConnectionsMock.mockResolvedValue({
connections: [
{ id: "conn-one", applicationId: "app-notion", status: "active" },
{ id: "conn-two", applicationId: "app-notion", status: "disabled" },
{ id: "conn-draft", applicationId: "app-notion", status: "draft" },
],
});
await renderBrowse();
const notionTiles = Array.from(container.querySelectorAll("button")).filter((button) =>
button.textContent?.includes("Notion"),
);
expect(notionTiles).toHaveLength(2);
expect(notionTiles.every((button) => button.textContent?.includes("2 connected already"))).toBe(true);
await act(async () => {
notionTiles[0]?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
expect(navigateMock).toHaveBeenCalledWith("/apps/app/app-notion/setup");
});
it("keeps the custom URL option available when gallery search has no matches", async () => {
await renderBrowse();

View File

@ -9,6 +9,7 @@ import { toolsApi } from "@/api/tools";
import { Skeleton } from "@/components/ui/skeleton";
import { AppLogo } from "./AppLogo";
import {
appApplicationSourceSlug,
appDefinitionDescription,
appDefinitionLogoUrl,
appDefinitionName,
@ -58,6 +59,16 @@ export function Browse() {
queryFn: () => toolsApi.listGallery(selectedCompanyId!),
enabled: !!selectedCompanyId,
});
const applicationsQuery = useQuery({
queryKey: queryKeys.tools.applications(selectedCompanyId ?? "__none__"),
queryFn: () => toolsApi.listApplications(selectedCompanyId!),
enabled: !!selectedCompanyId,
});
const connectionsQuery = useQuery({
queryKey: queryKeys.tools.connections(selectedCompanyId ?? "__none__"),
queryFn: () => toolsApi.listConnections(selectedCompanyId!),
enabled: !!selectedCompanyId,
});
const gallery = (galleryQuery.data?.apps ?? []) as AppGalleryDisplayEntry[];
const popular = useMemo(
@ -77,19 +88,57 @@ export function Browse() {
appDefinitionDescription(entry).toLowerCase().includes(trimmed),
);
}, [gallery, trimmed]);
const connectionSummaryBySlug = useMemo(() => {
const connections = connectionsQuery.data?.connections ?? [];
const connectedCountByApplicationId = new Map<string, number>();
for (const connection of connections) {
if (connection.status === "archived" || connection.status === "draft") continue;
connectedCountByApplicationId.set(
connection.applicationId,
(connectedCountByApplicationId.get(connection.applicationId) ?? 0) + 1,
);
}
const summaries = new Map<string, { applicationId: string; count: number }>();
for (const application of applicationsQuery.data?.applications ?? []) {
if (application.status === "archived") continue;
const slug = appApplicationSourceSlug(application);
if (!slug) continue;
const count = connectedCountByApplicationId.get(application.id) ?? 0;
const current = summaries.get(slug);
summaries.set(slug, {
applicationId: current?.applicationId ?? application.id,
count: (current?.count ?? 0) + count,
});
}
return summaries;
}, [applicationsQuery.data, connectionsQuery.data]);
if (!selectedCompanyId) {
return <div className="p-6 text-sm text-muted-foreground">Select a company to browse apps.</div>;
}
const loading = galleryQuery.isLoading;
const loading = galleryQuery.isLoading || applicationsQuery.isLoading || connectionsQuery.isLoading;
const tileProps = (entry: AppGalleryDisplayEntry) => {
const summary = connectionSummaryBySlug.get(appDefinitionSlug(entry));
const connectHref = connectHrefFor(entry);
return {
connectedCount: summary?.count ?? 0,
onOpen: summary && summary.count > 0
? () => navigate(`/apps/app/${summary.applicationId}/setup`)
: connectHref
? () => navigate(connectHref)
: undefined,
};
};
return (
<div className="max-w-5xl space-y-8 pb-12">
<header>
<h1 className="text-2xl font-bold tracking-tight">Browse</h1>
<p className="mt-1 text-sm text-muted-foreground">
Connect Notion, Zapier, or your own MCP server. More integrations are coming soon.
Choose an app or connect your own MCP server.
</p>
</header>
@ -123,7 +172,7 @@ export function Browse() {
<AppTile
key={appDefinitionSlug(entry)}
entry={entry}
onConnect={connectHrefFor(entry) ? () => navigate(connectHrefFor(entry)!) : undefined}
{...tileProps(entry)}
compact
/>
))}
@ -146,7 +195,7 @@ export function Browse() {
<AppTile
key={appDefinitionSlug(entry)}
entry={entry}
onConnect={connectHrefFor(entry) ? () => navigate(connectHrefFor(entry)!) : undefined}
{...tileProps(entry)}
/>
))}
</div>
@ -155,10 +204,7 @@ export function Browse() {
<ByoConnectCard onConnect={() => navigate(BYO_CONNECT_HREF)} />
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="text-xs text-muted-foreground">
Notion connects with secure sign-in. Zapier connects with its MCP URL. Other integrations are previews.
</p>
<div className="flex justify-end">
<AdvancedToolsLink />
</div>
</>
@ -169,20 +215,27 @@ export function Browse() {
function AppTile({
entry,
onConnect,
onOpen,
connectedCount,
compact = false,
}: {
entry: AppGalleryDisplayEntry;
onConnect?: () => void;
onOpen?: () => void;
connectedCount: number;
compact?: boolean;
}) {
const disabled = !onConnect;
const disabled = !onOpen;
const actionLabel = connectedCount > 0
? `${connectedCount} connected already`
: disabled
? "Coming soon"
: "Connect →";
if (compact) {
return (
<button
type="button"
disabled={disabled}
onClick={onConnect}
onClick={onOpen}
className={disabled
? "flex cursor-not-allowed flex-col items-center gap-2 rounded-xl border border-border bg-background px-3 py-4 text-center opacity-60"
: "flex flex-col items-center gap-2 rounded-xl border border-border bg-background px-3 py-4 text-center transition-colors hover:border-foreground/30 hover:bg-accent/40"}
@ -190,7 +243,7 @@ function AppTile({
<AppLogo name={appDefinitionName(entry)} logoUrl={appDefinitionLogoUrl(entry)} size={36} />
<span className="text-xs font-medium text-foreground">{appDefinitionName(entry)}</span>
<span className={disabled ? "text-xs text-muted-foreground" : "text-xs font-semibold text-primary"}>
{disabled ? "Coming soon" : "Connect →"}
{actionLabel}
</span>
</button>
);
@ -199,7 +252,7 @@ function AppTile({
<button
type="button"
disabled={disabled}
onClick={onConnect}
onClick={onOpen}
className={disabled
? "flex h-full cursor-not-allowed items-start gap-3 rounded-xl border border-border bg-card px-4 py-4 text-left opacity-60"
: "flex h-full items-start gap-3 rounded-xl border border-border bg-card px-4 py-4 text-left transition-colors hover:border-foreground/30 hover:bg-accent/40"}
@ -210,7 +263,7 @@ function AppTile({
<div className="mt-0.5 line-clamp-2 text-xs text-muted-foreground">{appDefinitionDescription(entry)}</div>
</div>
<span className={disabled ? "shrink-0 text-xs font-semibold text-muted-foreground" : "shrink-0 text-xs font-semibold text-primary"}>
{disabled ? "Coming soon" : "Connect →"}
{actionLabel}
</span>
</button>
);

View File

@ -196,14 +196,14 @@ describe("Connections table (M1b / PAP-13254 door 2)", () => {
tr.textContent?.includes("GitHub"),
);
row?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
expect(mockNavigate).toHaveBeenCalledWith("/apps/app/app-github");
expect(mockNavigate).toHaveBeenCalledWith("/apps/app/app-github/setup");
mockNavigate.mockClear();
const connectButton = Array.from(container.querySelectorAll("button")).find((button) =>
button.textContent?.includes("Connect") && !button.textContent.includes("Connect an app"),
);
connectButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
expect(mockNavigate).toHaveBeenCalledWith("/apps/app/app-github");
expect(mockNavigate).toHaveBeenCalledWith("/apps/app/app-github/setup");
});
it("rolls up multi-connection status, attention count, actions, and navigation by application", async () => {
@ -274,13 +274,13 @@ describe("Connections table (M1b / PAP-13254 door 2)", () => {
expect(text).toContain("0 on");
// 5. Last used renders a relative timestamp when present, dash when absent.
expect(text).toContain("—");
// 6. Multi-connection app appears once and opens its first connection detail.
// 6. Multi-connection app appears once and opens its provider landing page.
expect(Array.from(container.querySelectorAll("tbody tr")).filter((tr) => tr.textContent?.includes("Slack"))).toHaveLength(1);
const slackRow = Array.from(container.querySelectorAll("tbody tr")).find((tr) =>
tr.textContent?.includes("Slack"),
);
slackRow?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
expect(mockNavigate).toHaveBeenCalledWith("/apps/c-attention");
expect(mockNavigate).toHaveBeenCalledWith("/apps/app/app-slack/setup");
// 7. Button labels are honest: broken health says Reconnect, healthy/paused say Open.
const rowButtonLabel = (name: string) =>
Array.from(container.querySelectorAll("tbody tr"))
@ -328,7 +328,7 @@ describe("Connections table (M1b / PAP-13254 door 2)", () => {
const button = row?.querySelector("td:last-child button");
expect(button?.textContent).toBe("Open");
button?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
expect(mockNavigate).toHaveBeenCalledWith("/apps/c-healthy");
expect(mockNavigate).toHaveBeenCalledWith("/apps/app/app-github/setup");
});
it("deletes a connection only after trash-can confirmation", async () => {

View File

@ -52,6 +52,7 @@ type AppStatus = {
type AppRow = {
application: ToolApplication;
primaryConnection: ToolConnection | null;
connectionCount: number;
agentAvailableConnectionCount: number;
status: AppStatus;
actionCount: number;
@ -218,6 +219,7 @@ export function Connections() {
return {
application,
primaryConnection,
connectionCount: appConnections.length,
agentAvailableConnectionCount: appConnections.filter(
(connection) => connection.status === "active" && connection.enabled,
).length,
@ -336,10 +338,10 @@ export function Connections() {
? "Paused — agents cant use it right now."
: status.tone === "not_connected"
? "Connect it so agents can use it."
: null;
const appHref = primaryConnection
? `/apps/${primaryConnection.id}`
: `/apps/app/${application.id}`;
: row.connectionCount > 1
? `${row.connectionCount} connections`
: null;
const appHref = `/apps/app/${application.id}/setup`;
const actionLabel = !primaryConnection
? "Connect"
: status.tone === "attention"

View File

@ -1,4 +1,4 @@
import type { AppDefinition } from "@paperclipai/shared";
import type { AppDefinition, ToolApplication } from "@paperclipai/shared";
export type AppGalleryDisplayEntry = AppDefinition & {
key?: string;
@ -22,3 +22,15 @@ export function appDefinitionDescription(entry: AppGalleryDisplayEntry | null |
export function appDefinitionLogoUrl(entry: AppGalleryDisplayEntry | null | undefined): string | undefined {
return entry?.branding?.logoUrl ?? entry?.logoUrl;
}
export function appApplicationSourceSlug(application: ToolApplication | null | undefined): string | null {
if (!application) return null;
const metadata = application.metadata;
const source = metadata?.sourceTemplateKey ?? metadata?.galleryKey;
if (typeof source === "string" && source.trim()) return source.trim();
const key = application.applicationKey?.trim();
if (!key) return null;
const galleryPrefix = "app-gallery:";
if (key.startsWith(galleryPrefix)) return key.slice(galleryPrefix.length).split(":")[0] || null;
return key;
}

View File

@ -14,7 +14,7 @@ import {
installInfoNotice,
type InstallState,
} from "@/lib/tool-installs";
import { QuarantinePill } from "./SetupPanel";
import { QuarantinedActionsReview } from "./SetupPanel";
import type { AccessDraft, AppDetailSectionProps } from "./types";
type ActionPermission = "off" | "allowed" | "ask";
@ -34,7 +34,7 @@ export function PermissionsPanel({
onSaveAccess,
onSaveInstall,
onSetActionPermission,
onTurnOnQuarantined,
onReviewQuarantined,
onRefreshActions,
refreshPending,
}: Pick<
@ -47,7 +47,7 @@ export function PermissionsPanel({
onSaveAccess: (next: AccessDraft) => void;
onSaveInstall: (next: InstallState) => void;
onSetActionPermission: (id: string, next: ActionPermission) => void;
onTurnOnQuarantined: (ids: string[]) => void;
onReviewQuarantined: (enabledIds: string[]) => void;
onRefreshActions: () => void;
refreshPending: boolean;
}) {
@ -76,7 +76,7 @@ export function PermissionsPanel({
refreshPending={refreshPending}
focusId={focusId}
onSetPermission={onSetActionPermission}
onTurnOnQuarantined={onTurnOnQuarantined}
onReviewQuarantined={onReviewQuarantined}
onRefreshActions={onRefreshActions}
/>
</div>
@ -316,7 +316,7 @@ function ActionsSection({
refreshPending,
focusId,
onSetPermission,
onTurnOnQuarantined,
onReviewQuarantined,
onRefreshActions,
}: {
readOnly: ToolCatalogEntry[];
@ -328,7 +328,7 @@ function ActionsSection({
refreshPending: boolean;
focusId?: string | null;
onSetPermission: (id: string, next: ActionPermission) => void;
onTurnOnQuarantined: (ids: string[]) => void;
onReviewQuarantined: (enabledIds: string[]) => void;
onRefreshActions: () => void;
}) {
return (
@ -359,11 +359,10 @@ function ActionsSection({
</div>
{quarantined.length > 0 && (
<QuarantinePill
count={quarantined.length}
<QuarantinedActionsReview
entries={quarantined}
disabled={disabled}
onTurnOn={onTurnOnQuarantined}
onSubmit={onReviewQuarantined}
/>
)}

View File

@ -1,26 +1,25 @@
import { ReviewQueueCard } from "../ReviewQueueCard";
import { QuarantinePill } from "./SetupPanel";
import { QuarantinedActionsReview } from "./SetupPanel";
import type { AppDetailSectionProps } from "./types";
export function ReviewPanel({
connectionId,
quarantined = [],
pending = false,
onTurnOnQuarantined,
onReviewQuarantined,
}: Pick<AppDetailSectionProps, "connectionId"> &
Partial<Pick<AppDetailSectionProps, "quarantined" | "pending">> & {
onTurnOnQuarantined?: (ids: string[]) => void;
onReviewQuarantined?: (enabledIds: string[]) => void;
}) {
const showsQuarantinedActions = quarantined.length > 0 && !!onTurnOnQuarantined;
const showsQuarantinedActions = quarantined.length > 0 && !!onReviewQuarantined;
return (
<div className="space-y-4">
{showsQuarantinedActions ? (
<QuarantinePill
count={quarantined.length}
<QuarantinedActionsReview
entries={quarantined}
disabled={pending}
onTurnOn={onTurnOnQuarantined}
onSubmit={onReviewQuarantined}
/>
) : null}
<ReviewQueueCard

View File

@ -230,53 +230,85 @@ export function AppLifecycleSection({
);
}
export function QuarantinePill({
count,
export function QuarantinedActionsReview({
entries,
disabled,
onTurnOn,
onSubmit,
}: {
count: number;
entries: ToolCatalogEntry[];
disabled: boolean;
onTurnOn: (ids: string[]) => void;
onSubmit: (enabledIds: string[]) => void;
}) {
const [open, setOpen] = useState(false);
const [enabledIds, setEnabledIds] = useState<Set<string>>(new Set());
const count = entries.length;
const selectedIds = entries.filter((entry) => enabledIds.has(entry.id)).map((entry) => entry.id);
return (
<div className="rounded-xl border border-amber-500/40 bg-amber-500/[0.08] p-4">
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="text-sm font-semibold text-amber-800 dark:text-amber-200">
{count} new {count === 1 ? "action" : "actions"} to review
<section className="overflow-hidden rounded-xl border border-amber-500/40 bg-amber-500/[0.08]">
<div className="flex flex-wrap items-start justify-between gap-3 px-4 py-3">
<div>
<div className="text-sm font-semibold text-amber-800 dark:text-amber-200">
Review {count} new {count === 1 ? "action" : "actions"}
</div>
<p className="mt-1 text-xs text-amber-700 dark:text-amber-300">
Turn on the actions agents may use. Anything left off stays blocked when you save.
</p>
</div>
<div className="flex items-center gap-2">
<Button size="sm" variant="outline" onClick={() => setOpen((v) => !v)}>
{open ? "Hide" : "Review"}
</Button>
<Button size="sm" disabled={disabled} onClick={() => onTurnOn(entries.map((e) => e.id))}>
Turn on all
</Button>
<button
type="button"
className="text-xs font-medium text-amber-800 hover:text-amber-950 dark:text-amber-200 dark:hover:text-amber-50"
disabled={disabled}
onClick={() => setEnabledIds(new Set(entries.map((entry) => entry.id)))}
>
Turn all on
</button>
<button
type="button"
className="text-xs font-medium text-amber-800 hover:text-amber-950 dark:text-amber-200 dark:hover:text-amber-50"
disabled={disabled}
onClick={() => setEnabledIds(new Set())}
>
Turn all off
</button>
</div>
</div>
<p className="mt-1 text-xs text-amber-700 dark:text-amber-300">
This app added actions since you set it up. They stay off until you turn them on.
</p>
{open && (
<div className="mt-3 divide-y divide-amber-500/25 rounded-lg border border-amber-500/40 bg-background">
{entries.map((entry) => (
<div key={entry.id} className="flex items-center gap-3 px-4 py-2.5">
<div className="divide-y divide-amber-500/25 border-y border-amber-500/25 bg-background">
{entries.map((entry) => {
const enabled = enabledIds.has(entry.id);
const label = entry.title ?? entry.toolName;
return (
<div key={entry.id} className="flex items-center gap-3 px-4 py-3">
<div className="min-w-0 flex-1">
<div className="text-sm font-medium text-foreground">{entry.title ?? entry.toolName}</div>
<div className="text-sm font-medium text-foreground">{label}</div>
{entry.description && (
<div className="truncate text-xs text-muted-foreground">{entry.description}</div>
)}
</div>
<Button size="sm" variant="outline" disabled={disabled} onClick={() => onTurnOn([entry.id])}>
Turn on
</Button>
<ToggleSwitch
aria-label={`${label} allowed`}
checked={enabled}
disabled={disabled}
onCheckedChange={(next) => {
setEnabledIds((current) => {
const updated = new Set(current);
if (next) updated.add(entry.id);
else updated.delete(entry.id);
return updated;
});
}}
/>
</div>
))}
</div>
)}
</div>
);
})}
</div>
<div className="flex items-center justify-between gap-3 px-4 py-3">
<span className="text-xs text-amber-700 dark:text-amber-300">
{selectedIds.length} of {count} will be on
</span>
<Button size="sm" disabled={disabled} onClick={() => onSubmit(selectedIds)}>
{disabled ? "Saving…" : "Save choices"}
</Button>
</div>
</section>
);
}

View File

@ -119,7 +119,7 @@ function PanelHarness({ access, install }: { access: AccessDraft; install: Insta
onSaveAccess={() => {}}
onSaveInstall={setState}
onSetActionPermission={() => {}}
onTurnOnQuarantined={() => {}}
onReviewQuarantined={() => {}}
onRefreshActions={() => {}}
/>
</div>