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>
This commit is contained in:
TonioandClaude Fable 5.2 authored and GitHub committed 2026-11-26 02:23:18 +00:00
1 parent ff5e35dd36
commit 5ea8c99717
20 files changed
+458 -73

No files matched your search

+5 -3
View File
@@ -105,9 +105,11 @@ test("personal provider defaults move the crown only after saving and survive re
const announcement = page.getByRole("button", { name: "Dismiss announcement" });
if (await announcement.isVisible()) await announcement.click();
const provider = page.locator('[data-app-slug="openai"]');
// Installed lists plugins as tiles; the accounts are on the plugin page, always open.
const expand = async () => {
const trigger = provider.getByRole("button", { name: /^\d+ connections$/ });
if (await trigger.getAttribute("data-state") === "closed") await trigger.click();
const tile = provider.locator("h3 button");
if (await tile.count()) await tile.click();
await expect(provider.getByRole("button", { name: "Your default for OpenAI" })).toBeVisible();
};
await expect(provider).toBeVisible();
await expand();
@@ -176,7 +178,7 @@ test("personal provider defaults expose crown meaning on touch in both themes at
const announcement = page.getByRole("button", { name: "Dismiss announcement" });
if (await announcement.isVisible()) await announcement.click();
const provider = page.locator('[data-app-slug="openai"]');
await provider.getByRole("button", { name: /^\d+ connections$/ }).tap();
await provider.locator("h3 button").tap();
const crown = provider.getByRole("button", { name: "Your default for OpenAI" });
await crown.scrollIntoViewIfNeeded();
await crown.tap();
+2 -1
View File
@@ -262,8 +262,9 @@ test("AgentMail setup and email work through the normal task conversation", asyn
await page.screenshot({ path: test.info().outputPath("agentmail-permission-denied.png"), fullPage: true });
await page.getByRole("button", { name: "More workspace pages", exact: true }).click();
await page.getByRole("link", { name: "Plugins", exact: true }).click();
// Account rows, including one waiting on setup, are listed under Installed.
// Installed lists plugins as tiles; account rows, including one waiting on setup, are on the plugin page.
await page.getByRole("radio", { name: "Installed", exact: true }).click();
await page.locator('[data-app-slug="agentmail"] h3 button').click();
await page.getByRole("button", { name: "Finish setup", exact: true }).click();
await expect(page.getByText("mail-agent-free@verified.example.test", { exact: true })).toBeVisible();
await expect(addressField).toHaveCount(0);
+3 -3
View File
@@ -254,7 +254,7 @@ for (const journey of [
queue = await context.newPage();
await queue.goto(`/${seed.prefix}/apps/review`);
await expect(
queue.getByRole("button", { name: "Decline", exact: true }),
queue.getByRole("button", { name: "Deny", exact: true }),
).toBeVisible({ timeout: 20_000 });
}
if (journey === "restart") {
@@ -290,7 +290,7 @@ for (const journey of [
if (journey === "decline") {
// Resolve from Connections and observe the still-open task tab update.
await queue!
.getByRole("button", { name: "Decline", exact: true })
.getByRole("button", { name: "Deny", exact: true })
.click();
} else {
@@ -339,7 +339,7 @@ for (const journey of [
).not.toBeVisible();
if (queue) {
await expect(
queue.getByRole("button", { name: "Decline", exact: true }),
queue.getByRole("button", { name: "Deny", exact: true }),
).not.toBeVisible({ timeout: 20_000 });
}
await page.bringToFront();
+3
View File
@@ -204,6 +204,9 @@ async function createConnectionThroughUi(input: ConnectionFlowInput, agentURL: s
} else if (connection.provider !== harness.provider) throw new ConnectionFailure("saved_provider_mismatch");
// Navigate away and return through the normal list: proof includes durable UI state.
await page.goto(`${api.origin}/${company.issuePrefix}/apps?source=installed`, { waitUntil: "domcontentloaded" });
// Installed lists plugins as tiles; search by account name, then open the plugin page that lists its accounts.
await page.getByPlaceholder("Search plugins…").fill(connection.name);
await page.locator('[role="listitem"][data-connected="true"] h3 button').first().click();
await expect(page.getByText(connection.name, { exact: true }).first()).toBeVisible();
await page.reload({ waitUntil: "domcontentloaded" });
await expect(page.getByText(connection.name, { exact: true }).first()).toBeVisible();
+19 -11
View File
@@ -5,6 +5,7 @@ import { Button } from "@/components/ui/button";
import { useBreadcrumbs } from "@/context/BreadcrumbContext";
import { useCompany } from "@/context/CompanyContext";
import { ReviewQueueCard } from "./ReviewQueueCard";
import { useReviewQueue } from "./useReviewCount";
/**
* Review — the "decisions waiting on you" inbox (PAP-12371, Finding B).
@@ -19,11 +20,12 @@ import { ReviewQueueCard } from "./ReviewQueueCard";
export function AppsReview() {
const { selectedCompanyId } = useCompany();
const { setBreadcrumbs } = useBreadcrumbs();
const queue = useReviewQueue();
useEffect(() => {
setBreadcrumbs([
{ label: "Plugins", href: "/apps" },
{ label: "Review" },
{ label: "Reviews" },
]);
return () => setBreadcrumbs([]);
}, [setBreadcrumbs]);
@@ -33,18 +35,24 @@ export function AppsReview() {
}
return (
<div className="mx-auto w-full max-w-3xl space-y-6 pb-12">
<Button asChild variant="ghost" size="sm" className="-ml-3 h-8 text-muted-foreground">
<Link to="/apps"><ArrowLeft className="size-4" aria-hidden />Plugins</Link>
</Button>
<header>
<h1 className="text-2xl font-bold tracking-tight">Review</h1>
<p className="mt-1 text-sm text-muted-foreground">
Actions your agents want to run that need your OK first. Approve, always-allow, or decline.
</p>
<div className="mx-auto flex w-full max-w-3xl flex-col gap-8 pb-16">
<header className="flex flex-col gap-3">
<Button asChild variant="ghost" size="sm" className="-ml-3 h-8 self-start text-muted-foreground">
<Link to="/apps"><ArrowLeft className="size-4" aria-hidden />Plugins</Link>
</Button>
<div className="flex flex-col gap-1">
<h1 className="text-2xl leading-8 font-semibold tracking-tight text-foreground">Reviews</h1>
{queue.loaded ? (
<p className="text-sm leading-5 text-muted-foreground">
{queue.count === 0
? "Nothing is waiting on you."
: `${queue.count} ${queue.count === 1 ? "request" : "requests"} from your plugins ${queue.count === 1 ? "is" : "are"} waiting on you.`}
</p>
) : null}
</div>
</header>
<ReviewQueueCard emptyState="reassure" heading="Waiting for your OK" />
<ReviewQueueCard layout="decisions" />
</div>
);
}
+18
View File
@@ -17,6 +17,7 @@ import { Button } from "@/components/ui/button";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy";
import { cn } from "@/lib/utils";
import { PluginTile } from "./PluginMarketplace";
export const ASSISTANT_CONNECTION_PATH = "/apps/assistant-connection";
const connectionsKey = ["mcp-connections"];
@@ -70,6 +71,23 @@ export function AssistantConnectionCard({ onNavigate }: { onNavigate: (href: str
</div>;
}
/** The same entry as a marketplace tile, for the Installed grid. Opening it shows the accounts and any load failure in full. */
export function AssistantConnectionTile({ onNavigate }: { onNavigate: (href: string) => void }) {
const connections = useAssistantConnections();
const failed = connections.view.kind === "error";
return <PluginTile
slug="assistant-connection"
name="Assistant Connection (MCP)"
description={failed ? "Couldn’t load your connection status. Open it to try again." : "Use your Paperclip organization from Codex, Claude, OpenCode, or another assistant."}
brandKey="paperclip"
icon={<Paperclip className="size-8 shrink-0 p-1 text-foreground" aria-hidden="true" />}
state={failed ? "attention" : connections.loaded && connections.rows.length > 0 ? "connected" : "available"}
statusLabel={failed ? "Needs attention" : "Connected"}
action={null}
onOpen={() => onNavigate(ASSISTANT_CONNECTION_PATH)}
/>;
}
/** Only copy user-visible, non-secret setup values. Never execute them here. */
function CopyValue({ value, label }: { value: string; label: string }) {
const [copied, setCopied] = useState(false);
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { ToolConnection } from "@paperclipai/shared";
import { pluginTileState, type ConnectorRowModel } from "./Browse";
import { pluginTileState, type ConnectorRowModel, chatEndpointAttention } from "./Browse";
const gateway = { id: "gateway-1", status: "active", enabled: true, healthStatus: "ok", connectionPurpose: "tool", config: {} } as unknown as ToolConnection;
const gateways = new Map([[gateway.id, gateway]]);
@@ -31,3 +31,12 @@ describe("pluginTileState", () => {
expect(pluginTileState(aggregatorRow("ACTIVE"), paused)).toBe("attention");
});
});
describe("chatEndpointAttention", () => {
it("says why a chat connection needs the user, and nothing when it is fine", () => {
expect(chatEndpointAttention({ status: "active", setup: null } as never)).toBeNull();
expect(chatEndpointAttention({ status: "draft", setup: null } as never)).toBe("Setup not finished");
expect(chatEndpointAttention({ status: "attention", setup: null } as never)).toBe("Needs attention");
expect(chatEndpointAttention({ status: "revoked", setup: null } as never)).toBe("Access revoked");
});
});
+33 -25
View File
@@ -13,7 +13,7 @@ import {
isRetiredComposioConnection,
RETIRED_COMPOSIO_MESSAGE,
} from "@paperclipai/shared";
import { AssistantConnectionCard, useAssistantConnections } from "./AssistantConnection";
import { AssistantConnectionTile, useAssistantConnections } from "./AssistantConnection";
import { TailscaleConnectorCard } from "./TailscaleConnector";
import { useTailscaleConnections } from "@/hooks/useTailscaleConnections";
import type { TailscaleConnection } from "@/api/tailscale";
@@ -53,7 +53,7 @@ import {
} from "@paperclipai/shared";
import { useNavigate, useParams } from "@/lib/router";
import { PLUGIN_CATEGORIES, PLUGIN_CATEGORY_ORDER, PLUGIN_GRID, PluginCategories, PluginShelf, PluginTile, isPluginCategoryId, pluginCategoryId, pluginCategorySectionId, type PluginCategoryId, type PluginTileState } from "./PluginMarketplace";
import { aggregatorPluginCategory } from "./plugin-categories";
import { aggregatorPluginCategory, groupPluginsByCategory } from "./plugin-categories";
import { PluginSkills } from "./PluginSkills";
import { ONE_CLICK_PARAM, isOneClickOAuthApp, reserveOneClickPopup } from "@/features/connections/one-click-oauth";
import { PluginPermissions } from "./PluginPermissions";
@@ -362,6 +362,13 @@ export function pluginTileState(row: ConnectorRowModel, connectionById?: Readonl
return needsAttention ? "attention" : "connected";
}
/** Why a chat connection is asking for the user, or null when it is fine. */
export function chatEndpointAttention(endpoint: Pick<ChatEndpoint, "status" | "setup">): string | null {
if (endpoint.status === "revoked") return "Access revoked";
if (endpoint.status === "attention") return "Needs attention";
return chatEndpointNeedsSetup(endpoint as ChatEndpoint) ? "Setup not finished" : null;
}
function connectorAction(
row: ConnectorRowModel,
chatConnectorsEnabled: boolean,
@@ -1065,10 +1072,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
const noteworthyRows = marketplace ? fullRows(NOTEWORTHY_PLUGIN_SLUGS.flatMap((slug) => visibleRows.filter((row) => row.slug === slug && !row.entry?.featured)), 6) : [];
const shelvedKeys = new Set([...featuredRows, ...noteworthyRows].map((row) => row.key));
const categoryGroups = marketplace
? PLUGIN_CATEGORY_ORDER.map((id) => {
const all = visibleRows.filter((row) => rowCategory(row) === id);
return { id, total: all.length, rows: all.filter((row) => !shelvedKeys.has(row.key)).slice(0, CATEGORY_BLOCK_SIZE) };
}).filter((group) => group.total > 0)
? groupPluginsByCategory(visibleRows, PLUGIN_CATEGORY_ORDER, rowCategory, (row) => shelvedKeys.has(row.key), CATEGORY_BLOCK_SIZE)
: [];
const openCategory = (id: PluginCategoryId) => { navigate(`/apps/category/${id}`); catalogTop.current?.scrollIntoView?.({ block: "start" }); };
const setupEnabledFor = (row: ConnectorRowModel) => connectorAvailability.enabled(row.entry ?? getConnectableAppDefinition(row.slug))
@@ -1217,7 +1221,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
</Button>
<PluginPageHeader
name={openRow.name}
kind={`Connector · ${PLUGIN_CATEGORIES[pluginCategoryId(openRow.entry?.categories)].label}`}
kind={`Connector · ${PLUGIN_CATEGORIES[rowCategory(openRow)].label}`}
description={openRow.description}
brandKey={openRow.brandKey}
logoUrl={openRow.logoUrl}
@@ -1246,7 +1250,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
onNavigate={navigate}
/>
<PluginInformation
category={PLUGIN_CATEGORIES[pluginCategoryId(openRow.entry?.categories)].label}
category={PLUGIN_CATEGORIES[rowCategory(openRow)].label}
signIn={pluginSignIn(openRow.entry?.methods)}
host={pluginHost(openRow.entry?.methods)}
docsUrl={openRow.entry?.docsUrl}
@@ -1257,13 +1261,6 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
<p>This plugin isn’t in the catalog anymore.</p>
<Button variant="outline" size="sm" onClick={() => navigate("/apps")}>Back to Plugins</Button>
</div>
) : source === "installed" && !categoryId ? (
<div className={cn("space-y-3", ANALYTICS_MASK_CLASS)} role="list" aria-label="Connector list">
{showAssistantConnection && <AssistantConnectionCard onNavigate={navigate} />}
{paginatedRows.map((row) => (
row.networkConnections ? <TailscaleConnectorCard key={row.key} onNavigate={navigate} /> : <div key={row.key} role="presentation" className="contents">{renderConnectorCard(row)}</div>
))}
</div>
) : marketplace ? (
<div className={cn("flex flex-col gap-10", ANALYTICS_MASK_CLASS)} role="list" aria-label="Connector list">
{featuredRows.length > 0 ? <PluginShelf id="plugins-most-used" title="Most used">{featuredRows.map(renderTile)}</PluginShelf> : null}
@@ -1276,7 +1273,10 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
</div>
) : (
<div className={cn("flex flex-col gap-3", ANALYTICS_MASK_CLASS)} role="list" aria-label="Connector list">
<div className={PLUGIN_GRID}>{paginatedRows.map(renderTile)}</div>
<div className={PLUGIN_GRID}>
{showAssistantConnection && !categoryId ? <AssistantConnectionTile onNavigate={navigate} /> : null}
{paginatedRows.map(renderTile)}
</div>
</div>
)
)}
@@ -1584,15 +1584,23 @@ export function ConnectorCard({
<AgentAvatar agent={chatAgentById?.get(endpoint.assignedAgentId) ?? { id: endpoint.assignedAgentId, name: endpoint.assignedAgentName }}
size={40} label={`${endpoint.assignedAgentName} avatar`} />
<div className="min-w-0">
<button
type="button"
className="block max-w-full truncate text-left text-sm font-medium hover:underline"
onClick={() =>
onNavigate(`/apps/chat/${endpoint.id}/settings`)
}
>
{endpoint.assignedAgentName} · {endpoint.provider === "agentmail" ? "Email" : endpoint.provider === "github" ? "Code review bot" : "Chat"}
</button>
<div className="flex min-w-0 items-center gap-1.5">
<button
type="button"
className="block min-w-0 truncate text-left text-sm font-medium hover:underline"
onClick={() =>
onNavigate(`/apps/chat/${endpoint.id}/settings`)
}
>
{endpoint.assignedAgentName} · {endpoint.provider === "agentmail" ? "Email" : endpoint.provider === "github" ? "Code review bot" : "Chat"}
</button>
{chatEndpointAttention(endpoint) ? (
<span className="shrink-0 text-(--status-task-icon-todo)" title={chatEndpointAttention(endpoint) ?? undefined} data-testid="account-attention">
<AlertTriangle className="size-3.5" aria-hidden="true" />
<span className="sr-only">{chatEndpointAttention(endpoint)}</span>
</span>
) : null}
</div>
<p className="truncate text-xs text-muted-foreground">
{endpoint.providerAccountLabel ??
endpoint.botLabel ??
+4 -1
View File
@@ -55,6 +55,7 @@ export function PluginTile({
statusLabel,
action,
onOpen,
icon,
}: {
slug: string;
name: string;
@@ -66,6 +67,8 @@ export function PluginTile({
statusLabel: string;
action: PluginTileAction | null;
onOpen: () => void;
/** Replaces the brand logo for an entry that is not a catalog app. */
icon?: ReactNode;
}) {
const installed = state !== "available";
return (
@@ -76,7 +79,7 @@ export function PluginTile({
className="group relative flex min-w-0 flex-col gap-3 rounded-2xl bg-muted/50 p-5 transition-colors hover:bg-muted"
>
<div className="flex min-h-8 items-center gap-3">
<AppLogo name={name} brandKey={brandKey} logoUrl={logoUrl} darkLogoUrl={darkLogoUrl} size={32} compact className="bg-transparent" />
{icon ?? <AppLogo name={name} brandKey={brandKey} logoUrl={logoUrl} darkLogoUrl={darkLogoUrl} size={32} compact className="bg-transparent" />}
<h3 className="min-w-0 flex-1 truncate text-sm font-semibold text-foreground">
<button
type="button"
+10 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { actionPolicy, groupPolicy } from "./PluginPermissions";
import { actionPolicy, groupPolicy, staleReads } from "./PluginPermissions";
const enabled = new Set(["read", "ask", "stale-ask"]);
const askFirst = new Set(["ask", "off-ask"]);
@@ -18,3 +18,12 @@ describe("plugin permission policies", () => {
expect(groupPolicy(["missing", "off-ask"], enabled, askFirst)).toBe("off");
});
});
describe("staleReads", () => {
it("names the reads that failed, even when they still hold earlier data", () => {
const fresh = { error: null, data: [1] };
const failedRefresh = { error: new Error("offline"), data: [1] };
expect(staleReads([fresh, fresh])).toEqual([]);
expect(staleReads([fresh, failedRefresh])).toEqual([failedRefresh]);
});
});
+17 -1
View File
@@ -181,7 +181,10 @@ function ConnectionPermissions({ companyId, connection }: { companyId: string; c
if (!loaded) return <p className={NOTE}>Loading actions…</p>;
if (reads.length + writes.length === 0) return <p className={NOTE}>This account hasn’t listed any actions yet.</p>;
const canConfigure = grantsQuery.data?.capabilities?.canConfigure === true;
// After a failed refresh the values on screen may be out of date, and a save replaces what is stored,
// so changes wait until every read succeeds again.
const stale = staleReads(queries);
const canConfigure = grantsQuery.data?.capabilities?.canConfigure === true && stale.length === 0;
const change = (ids: string[], next: ActionPolicy) => {
setSaveError(null);
save({ ...actionPermissionMutation(ids, next, enabledIds, askFirstIds), access: savedAccess });
@@ -190,6 +193,14 @@ function ConnectionPermissions({ companyId, connection }: { companyId: string; c
<>
{reads.length > 0 ? <ActionBlock title="Reads" entries={reads} enabledIds={enabledIds} askFirstIds={askFirstIds} disabled={!canConfigure || pending} onChange={change} /> : null}
{writes.length > 0 ? <ActionBlock title="Writes" entries={writes} enabledIds={enabledIds} askFirstIds={askFirstIds} disabled={!canConfigure || pending} onChange={change} /> : null}
{stale.length > 0 ? (
<p role="status" className="flex flex-wrap items-center gap-x-2 px-4 text-sm text-muted-foreground">
Couldn’t refresh these permissions, so changes are paused.
<Button type="button" variant="link" size="sm" className="h-auto p-0" disabled={stale.some((query) => query.isFetching)} onClick={() => stale.forEach((query) => void query.refetch())}>
Try again
</Button>
</p>
) : null}
{saveError ? (
<p role="alert" className="px-4 text-sm text-destructive">
Couldn’t save that. {saveError}
@@ -199,6 +210,11 @@ function ConnectionPermissions({ companyId, connection }: { companyId: string; c
);
}
/** The reads whose last attempt failed: what they loaded earlier may no longer match what is saved. */
export function staleReads<T extends { error: unknown }>(reads: readonly T[]): T[] {
return reads.filter((read) => read.error != null);
}
/** Tool permissions for a connected plugin: one block for what it reads and one for what it changes, per account. */
export function PluginPermissions({
companyId,
+10 -5
View File
@@ -3,8 +3,9 @@ import { describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { PluginsHeader } from "./PluginsHeader";
const reviewCount = vi.hoisted(() => ({ value: 0 }));
vi.mock("./useReviewCount", () => ({ useReviewCount: () => reviewCount.value }));
const reviewCount = vi.hoisted(() => ({ value: 0, apps: [] as string[] }));
vi.mock("./useReviewCount", () => ({ useReviewQueue: () => ({ count: reviewCount.value, loaded: true, apps: reviewCount.apps }) }));
vi.mock("./AppLogo", () => ({ AppLogo: ({ name }: { name: string }) => <span data-logo={name} /> }));
vi.mock("@/lib/router", () => ({
Link: ({ to, children, ...rest }: { to: string; children: React.ReactNode }) => <a href={to} {...rest}>{children}</a>,
}));
@@ -12,18 +13,22 @@ vi.mock("@/lib/router", () => ({
const options = [{ id: "mcp", title: "MCP server URL", description: "A custom server.", href: "/apps/byo" }];
describe("PluginsHeader", () => {
it("links to Review and offers Add when nothing is waiting", () => {
it("links to Reviews and offers Add when nothing is waiting", () => {
reviewCount.value = 0;
const html = renderToStaticMarkup(<PluginsHeader options={options} onNavigate={() => {}} />);
expect(html).toContain('href="/apps/review"');
expect(html).toContain('aria-label="Open Review"');
expect(html).toContain('aria-label="Open Reviews"');
expect(html).toContain("Add");
expect(html).not.toContain("data-logo");
});
it("counts the requests waiting for review", () => {
reviewCount.value = 3;
reviewCount.apps = ["GitHub", "Slack"];
const html = renderToStaticMarkup(<PluginsHeader options={options} onNavigate={() => {}} />);
expect(html).toContain('aria-label="3 to review, open Review"');
expect(html).toContain('aria-label="3 to review, open Reviews"');
expect(html).toContain("3 to review");
expect(html).toContain('data-logo="GitHub"');
expect(html).toContain('data-logo="Slack"');
});
});
+22 -9
View File
@@ -8,22 +8,35 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy";
import { useReviewCount } from "./useReviewCount";
import { AppLogo } from "./AppLogo";
import { useReviewQueue } from "./useReviewCount";
export type PluginsAddOption = { id: string; title: string; description: string; href: string };
/** Opens the Review page, and counts the requests waiting for the user's OK when there are any. */
/** How many plugin logos the review shortcut stacks before the count. */
const STACKED_LOGOS = 4;
/** Opens Reviews. When requests are waiting it shows the plugins they come from and how many there are. */
function ReviewButton() {
const count = useReviewCount();
const { count, apps } = useReviewQueue();
return (
<Button asChild variant="ghost" className="h-9 shrink-0 gap-2 px-3 text-muted-foreground">
<Link to="/apps/review" aria-label={count > 0 ? `${count} to review, open Review` : "Open Review"}>
<Button asChild variant="ghost" className="h-9 shrink-0 gap-3 px-2 pr-3 text-muted-foreground">
<Link to="/apps/review" aria-label={count > 0 ? `${count} to review, open Reviews` : "Open Reviews"}>
{count > 0 ? (
<span className="inline-flex h-6 items-center rounded-md bg-(--status-task-todo)/15 px-2 text-xs font-normal text-(--status-task-icon-todo) tabular-nums">
{count} to review
</span>
<>
{apps.length > 0 ? (
<span aria-hidden className="flex items-center -space-x-1.5">
{apps.slice(0, STACKED_LOGOS).map((name) => (
<AppLogo key={name} name={name} size={28} className="rounded-lg ring-2 ring-background" />
))}
</span>
) : null}
<span className="inline-flex h-6 items-center rounded-md bg-(--status-task-todo)/15 px-2 text-xs font-normal text-(--status-task-icon-todo) tabular-nums">
{count} to review
</span>
</>
) : (
"Review"
<span className="pl-1">Reviews</span>
)}
<ChevronRight className="size-4" aria-hidden />
</Link>
@@ -0,0 +1,25 @@
import { describe, expect, it } from "vitest";
import { indexAgentsById } from "./ReviewQueueCard";
describe("indexAgentsById", () => {
it("reads each agent once however many requests look one up", () => {
const AGENTS = 2000;
const REQUESTS = 500;
let reads = 0;
const agents = Array.from({ length: AGENTS }, (_, index) => ({
get id() {
reads += 1;
if (reads > AGENTS) throw new Error(`agent ids were read ${reads} times for ${AGENTS} agents`);
return `agent-${index}`;
},
name: `Agent ${index}`,
}));
const byId = indexAgentsById(agents);
const found = Array.from({ length: REQUESTS }, (_, index) => byId.get(`agent-${(index * 7) % AGENTS}`));
expect(reads).toBe(AGENTS);
expect(found.every((agent) => agent !== undefined)).toBe(true);
expect(byId.get("agent-missing")).toBeUndefined();
});
});
+144 -3
View File
@@ -1,7 +1,7 @@
import { useMemo, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Check, Loader2, ShieldQuestion, X } from "lucide-react";
import type { ToolActionRequestListItem } from "@paperclipai/shared";
import { ArrowUpRight, Check, Loader2, MoreHorizontal, ShieldQuestion, X } from "lucide-react";
import type { Agent, ToolActionRequestListItem } from "@paperclipai/shared";
import { googleWorkspaceToolTitle, humanizeConnectionDisplayName } from "@paperclipai/shared";
import { useCompany } from "@/context/CompanyContext";
import { useToast } from "@/context/ToastContext";
@@ -14,6 +14,15 @@ import { toolsApi } from "@/api/tools";
import { Button } from "@/components/ui/button";
import { MarkdownBody } from "@/components/MarkdownBody";
import { describeError } from "@/api/errors";
import { agentsApi } from "@/api/agents";
import { Link } from "@/lib/router";
import { cn } from "@/lib/utils";
import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy";
import { AgentAvatar } from "@/components/AgentAvatar";
import { DecisionCardFooter } from "@/components/DecisionCardFooter";
import { NeedsYouPanel, NeedsYouPanelNote, NeedsYouPanelRow } from "@/components/coordinator/NeedsYouCardKit";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { AppLogo } from "./AppLogo";
/**
* "Ask first" review queue (M1b float / M9 card, PAP-10859).
@@ -25,17 +34,22 @@ import { describeError } from "@/api/errors";
*
* Pass `connectionId` to scope the queue to a single app (App detail); omit it
* to show every pending request (Needs attention page).
*
* `layout="decisions"` draws each request as a decision card with no section
* heading, for the Reviews page, which carries its own title and count.
*/
export function ReviewQueueCard({
connectionId,
emptyState = "hidden",
heading = "Waiting for your OK",
plain = false,
layout = "queue",
}: {
connectionId?: string;
emptyState?: "hidden" | "reassure";
heading?: string;
plain?: boolean;
layout?: "queue" | "decisions";
}) {
const { selectedCompanyId } = useCompany();
@@ -52,6 +66,14 @@ export function ReviewQueueCard({
return connectionId ? all.filter((item) => item.connectionId === connectionId) : all;
}, [query.data, connectionId]);
const decisions = layout === "decisions";
const agentsQuery = useQuery({
queryKey: queryKeys.agents.list(selectedCompanyId ?? "__none__"),
queryFn: () => agentsApi.list(selectedCompanyId!),
enabled: decisions && !!selectedCompanyId && items.some((item) => item.requestedByAgentId),
});
const agents = useMemo(() => indexAgentsById(agentsQuery.data ?? []), [agentsQuery.data]);
if (!selectedCompanyId) return null;
if (query.isLoading || view.kind === "reconnecting") return null;
if (view.kind === "error") return <QueryErrorState error={query.error} action="load connection reviews" onRetry={view.retry} retrying={view.isFetching} />;
@@ -65,6 +87,18 @@ export function ReviewQueueCard({
);
}
if (decisions) {
return (
<ul aria-label="Requests to review" className="flex flex-col gap-3">
{items.map((item) => (
<li key={item.request.id}>
<ReviewRow companyId={selectedCompanyId} item={item} plain={false} decision agent={item.requestedByAgentId ? agents.get(item.requestedByAgentId) ?? null : null} />
</li>
))}
</ul>
);
}
return (
<section className="space-y-3">
<div className="flex items-center gap-2">
@@ -87,10 +121,14 @@ function ReviewRow({
companyId,
item,
plain,
decision = false,
agent = null,
}: {
companyId: string;
item: ToolActionRequestListItem;
plain: boolean;
decision?: boolean;
agent?: Agent | null;
}) {
const queryClient = useQueryClient();
const { pushToast } = useToast();
@@ -159,8 +197,19 @@ function ReviewRow({
onSettled: () => setResolving(null),
});
if (linkedInteraction) return <IssueThreadInteractionCard
if (decision && interactionQuery.isLoading) {
return (
<article className="coordinator-decision-card" aria-busy="true">
<p className="text-sm text-muted-foreground">Loading request…</p>
</article>
);
}
if (linkedInteraction) {
const card = <IssueThreadInteractionCard
interaction={linkedInteraction}
presentationVariant={decision ? "coordinator-decision" : "default"}
primaryActionOnRight={decision}
onAcceptInteraction={async (_interaction, _keys, _options, rememberAction) => {
try { await toolsApi.approveActionRequest(companyId, item.request.id, rememberAction); }
finally { invalidate(); }
@@ -170,9 +219,85 @@ function ReviewRow({
finally { invalidate(); }
}}
/>;
return decision ? <article className="coordinator-decision-card space-y-3">{card}</article> : card;
}
const busy = resolving !== null;
const preview = item.request.previewMarkdown?.trim();
const canAlwaysAllow = Boolean(item.requestedByAgentId && item.connectionId && !item.request.approvalId);
if (decision) {
const action = actionLabel(item);
const app = item.applicationName ? humanizeConnectionDisplayName(item.applicationName) : null;
const risk = item.riskLevel ? RISK_LABELS[item.riskLevel] : null;
return (
<article className={cn("coordinator-decision-card space-y-3", ANALYTICS_MASK_CLASS)} aria-label={app ? `${action} in ${app}` : action}>
<div className="flex items-center justify-between gap-4">
<span className="min-w-0 truncate text-xs leading-4.5 text-muted-foreground">Approve tool access</span>
<div className="flex shrink-0 items-center gap-3" data-attention-context>
{agent ? (
<span className="inline-flex min-w-0 items-center gap-2 text-xs leading-4.5 text-muted-foreground">
<AgentAvatar agent={agent} size={20} />
<span className="truncate">from {agent.name}</span>
</span>
) : null}
<time className="shrink-0 text-xs leading-4.5 text-muted-foreground" dateTime={new Date(item.request.createdAt).toISOString()}>
{timeAgo(item.request.createdAt)}
</time>
{canAlwaysAllow ? (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button type="button" variant="ghost" size="icon-sm" className="-mr-1.5 size-7 text-muted-foreground" aria-label={`More for ${action}`} disabled={busy}>
<MoreHorizontal aria-hidden />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className={`w-72 ${ANALYTICS_MASK_CLASS}`}>
<DropdownMenuItem className="flex flex-col items-start gap-0.5 py-2" onSelect={() => alwaysAllow.mutate()}>
<span className="text-sm text-foreground">Always allow</span>
<span className="text-xs text-muted-foreground">This agent can run this action on this connection without asking again.</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
) : null}
</div>
</div>
<div className="space-y-1.5">
<h2>{app ? `${action} in ${app}` : action}</h2>
<p className="text-sm text-muted-foreground">
{app ? `${action} is set to Ask first in ${app}, so it waits for your OK.` : "This action is set to Ask first, so it waits for your OK."} Allow once runs it now.
</p>
</div>
<NeedsYouPanel>
{app ? (
<NeedsYouPanelRow
icon={<AppLogo name={app} size={20} compact className="bg-transparent" />}
title={app}
meta={<>{action}{risk ? <> · <span className={cn(risk.danger && "text-destructive")}>{risk.label}</span></> : null}</>}
/>
) : null}
{preview ? <div className="text-sm"><MarkdownBody>{preview}</MarkdownBody></div> : null}
{agent ? <NeedsYouPanelNote>Requested by {agent.name}.</NeedsYouPanelNote> : null}
</NeedsYouPanel>
<DecisionCardFooter
leading={item.request.issueId ? (
<Link to={`/issues/${item.request.issueId}`} className="flex max-w-full min-w-0 items-center gap-1.5 text-(length:--text-compact) leading-5 text-muted-foreground hover:text-foreground">
<span className="min-w-0 truncate">{agent ? `Open task · Chat with ${agent.name}` : "Open task"}</span>
<ArrowUpRight className="size-4 shrink-0" aria-hidden />
</Link>
) : undefined}
>
<Button type="button" variant="ghost" onClick={() => decline.mutate()} disabled={busy}>
{resolving === "decline" ? <Loader2 className="animate-spin" aria-hidden /> : null}
Decline
</Button>
<Button type="button" onClick={() => allowOnce.mutate()} disabled={busy}>
{resolving === "allow" || resolving === "always" ? <Loader2 className="animate-spin" aria-hidden /> : null}
Allow once
</Button>
</DecisionCardFooter>
</article>
);
}
return (
<div className={plain ? "py-3" : "rounded-xl border border-border bg-card p-4"}>
@@ -215,6 +340,22 @@ function ReviewRow({
);
}
const RISK_LABELS: Record<NonNullable<ToolActionRequestListItem["riskLevel"]>, { label: string; danger: boolean }> = {
low: { label: "Low risk", danger: false },
medium: { label: "Medium risk", danger: false },
high: { label: "High risk", danger: true },
critical: { label: "Critical risk", danger: true },
read: { label: "Reads data", danger: false },
write: { label: "Changes data", danger: false },
destructive: { label: "Destructive", danger: true },
};
export function indexAgentsById<T extends { id: string }>(agents: readonly T[]): Map<string, T> {
const byId = new Map<string, T>();
for (const agent of agents) byId.set(agent.id, agent);
return byId;
}
function actionLabel(item: ToolActionRequestListItem): string {
if (!item.toolTitle && !item.toolName) return "This action";
return humanizeConnectionDisplayName(item.toolName ?? "", { title: googleWorkspaceToolTitle(item.toolName ?? "", item.toolTitle) });
@@ -0,0 +1,43 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from "vitest";
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { ChatConnectionPurpose } from "./ChatEndpointSetup";
vi.mock("@/context/BreadcrumbContext", () => ({ useBreadcrumbs: () => ({ setBreadcrumbs: () => {} }) }));
vi.mock("@/components/chat/ChatSetupNavigation", () => ({ ChatSetupNavigation: () => null }));
vi.mock("@/components/AgentAvatar", () => ({ AgentAvatar: () => null }));
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
let root: Root | null = null;
let host: HTMLElement | null = null;
function render(onClose?: () => void) {
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
act(() => root!.render(<ChatConnectionPurpose provider="slack" onChat={() => {}} onTools={() => {}} onClose={onClose} />));
return host;
}
afterEach(() => {
act(() => root?.unmount());
host?.remove();
root = null;
host = null;
});
describe("ChatConnectionPurpose", () => {
it("offers a close button that leaves the choice", () => {
const onClose = vi.fn();
const close = render(onClose).querySelector<HTMLButtonElement>('button[aria-label="Close"]');
expect(close).not.toBeNull();
act(() => close!.click());
expect(onClose).toHaveBeenCalledTimes(1);
});
it("has no close button when nothing handles it", () => {
expect(render().querySelector('button[aria-label="Close"]')).toBeNull();
});
});
+16 -8
View File
@@ -25,7 +25,7 @@ import {
} from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useQueryView } from "@/components/QueryView";
import { AlertTriangle, CheckCircle2, Copy, CircleHelp, ExternalLink, Eye, EyeOff, Hammer, Loader2 } from "lucide-react";
import { AlertTriangle, CheckCircle2, Copy, CircleHelp, ExternalLink, Eye, EyeOff, Hammer, Loader2, X } from "lucide-react";
import { AgentAvatar } from "@/components/AgentAvatar";
import { AgentCharacter } from "@/components/AgentCharacter";
import { AgentSelect } from "@/components/AgentMultiSelect";
@@ -114,10 +114,11 @@ export function isChatEndpointRepairing(
);
}
export function ChatConnectionPurpose({ provider, onChat, onTools, slackLabels }: {
export function ChatConnectionPurpose({ provider, onChat, onTools, onClose, slackLabels }: {
provider: ChatProvider;
onChat: () => void;
onTools: () => void;
onClose?: () => void;
slackLabels?: string[];
}) {
const { setBreadcrumbs } = useBreadcrumbs();
@@ -128,11 +129,18 @@ export function ChatConnectionPurpose({ provider, onChat, onTools, slackLabels }
return (
<div className="max-w-2xl space-y-6">
<ChatSetupNavigation labels={provider === "slack" ? slackLabels ?? ["Choose agent", "Connect"] : undefined} step={0} availableStep={0} onSelect={onChat} />
<div>
<h1 className="text-xl font-bold">Choose how to connect</h1>
<p className="mt-1 text-sm text-muted-foreground">
What should this {providerNames[provider]} connection do?
</p>
<div className="flex items-start justify-between gap-4">
<div className="min-w-0">
<h1 className="text-xl font-bold">Choose how to connect</h1>
<p className="mt-1 text-sm text-muted-foreground">
What should this {providerNames[provider]} connection do?
</p>
</div>
{onClose ? (
<Button type="button" variant="ghost" size="icon" className="-mt-1 -mr-2 shrink-0 text-muted-foreground" aria-label="Close" title="Close" onClick={onClose}>
<X aria-hidden />
</Button>
) : null}
</div>
<div className="grid gap-3">
<button
@@ -538,7 +546,7 @@ function ChatSdkEndpointSetup() {
);
if (purpose === "choice" && provider !== "speko") {
return <ChatConnectionPurpose provider={provider} slackLabels={slackNavigation.labels} onChat={() => setPurpose("chat")} onTools={() => navigate(toolHref)} />;
return <ChatConnectionPurpose provider={provider} slackLabels={slackNavigation.labels} onChat={() => setPurpose("chat")} onTools={() => navigate(toolHref)} onClose={() => navigate("/apps")} />;
}
return (
+32 -1
View File
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { AGGREGATOR_APP_CATALOG } from "@paperclipai/shared/aggregator-app-catalog";
import { aggregatorPluginCategory } from "./plugin-categories";
import { aggregatorPluginCategory, groupPluginsByCategory } from "./plugin-categories";
import { PLUGIN_CATEGORY_ORDER, type PluginCategoryId } from "./PluginMarketplace";
describe("aggregatorPluginCategory", () => {
it("uses the provider's own category when the catalog states one", () => {
@@ -19,3 +20,33 @@ describe("aggregatorPluginCategory", () => {
expect(AGGREGATOR_APP_CATALOG.some((app) => app.category === "productivity")).toBe(true);
});
});
describe("groupPluginsByCategory", () => {
it("classifies each app in the shipped catalog once", () => {
expect(AGGREGATOR_APP_CATALOG.length).toBeGreaterThan(1000);
let calls = 0;
const categoryOf = (app: (typeof AGGREGATOR_APP_CATALOG)[number]): PluginCategoryId => {
calls += 1;
if (calls > AGGREGATOR_APP_CATALOG.length) throw new Error("Classified an app more than once");
return aggregatorPluginCategory(app);
};
const groups = groupPluginsByCategory(AGGREGATOR_APP_CATALOG, PLUGIN_CATEGORY_ORDER, categoryOf, () => false, 9);
expect(calls).toBe(AGGREGATOR_APP_CATALOG.length);
expect(groups.reduce((sum, group) => sum + group.total, 0)).toBe(AGGREGATOR_APP_CATALOG.length);
expect(groups.every((group) => group.rows.length <= 9)).toBe(true);
});
it("keeps category order, counts shelved rows and leaves them out of the block", () => {
const items = [
{ key: "a", category: "developer" as const },
{ key: "b", category: "productivity" as const },
{ key: "c", category: "developer" as const },
{ key: "d", category: "developer" as const },
];
const groups = groupPluginsByCategory(items, ["productivity", "developer", "other"], (item) => item.category, (item) => item.key === "a", 1);
expect(groups).toEqual([
{ id: "productivity", total: 1, rows: [items[1]] },
{ id: "developer", total: 3, rows: [items[2]] },
]);
});
});
+22
View File
@@ -37,3 +37,25 @@ export function aggregatorPluginCategory(app: Pick<AggregatorAppCatalogEntry, "n
const name = app.name.toLowerCase().replace(/[^a-z0-9]+/g, " ");
return KEYWORDS.find(([, words]) => words.test(name))?.[0] ?? "other";
}
/**
* Splits catalog rows into category blocks in one pass, classifying each row once.
* `total` counts every row in the category; `rows` holds the first `blockSize` that are not already on a shelf.
*/
export function groupPluginsByCategory<T>(
items: readonly T[],
order: readonly PluginCategoryId[],
categoryOf: (item: T) => PluginCategoryId,
isShelved: (item: T) => boolean,
blockSize: number,
): { id: PluginCategoryId; total: number; rows: T[] }[] {
const groups = new Map<PluginCategoryId, { id: PluginCategoryId; total: number; rows: T[] }>();
for (const id of order) groups.set(id, { id, total: 0, rows: [] });
for (const item of items) {
const group = groups.get(categoryOf(item));
if (!group) continue;
group.total += 1;
if (group.rows.length < blockSize && !isShelved(item)) group.rows.push(item);
}
return [...groups.values()].filter((group) => group.total > 0);
}
+20
View File
@@ -1,4 +1,6 @@
import { useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import { humanizeConnectionDisplayName } from "@paperclipai/shared";
import { useCompany } from "@/context/CompanyContext";
import { queryKeys } from "@/lib/queryKeys";
import { toolsApi } from "@/api/tools";
@@ -20,3 +22,21 @@ export function useReviewCount(): number {
});
return query.data?.actionRequests.length ?? 0;
}
/** The same queue, with the plugins the waiting requests come from, newest request first and each plugin once. */
export function useReviewQueue(): { count: number; loaded: boolean; apps: string[] } {
const { selectedCompanyId } = useCompany();
const query = useQuery({
queryKey: queryKeys.tools.actionRequests(selectedCompanyId ?? "__none__", "pending"),
queryFn: () => toolsApi.listActionRequests(selectedCompanyId!, "pending"),
enabled: !!selectedCompanyId,
refetchInterval: 20_000,
});
const requests = query.data?.actionRequests;
const apps = useMemo(() => {
const names = new Set<string>();
for (const item of requests ?? []) if (item.applicationName) names.add(humanizeConnectionDisplayName(item.applicationName));
return [...names];
}, [requests]);
return { count: requests?.length ?? 0, loaded: requests !== undefined, apps };
}