mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-20 18:26:40 +01:00
fix(ui): keep connector permission forms responsive (#22008)
## Thinking Path
> - Paperclip helps people manage AI agents and their access to
connected apps.
> - The connector permission page controls agent access and tool
approvals.
> - Large action lists mounted a test dialog for every action, even when
closed.
> - Form edits repeated that work and waited for reads before showing
saved values.
> - This pull request limits the visible controls and mounts test
dialogs when opened.
> - The form shows a pending choice at once and uses the saved response
for the next edit.
> - The benefit is fast feedback with the same server permission checks.
## Linked Issues or Issue Description
**What happened?**
Changing Any agent to selected agents was slow on connector permission
pages. Agent selection and action controls also slowed down as the
action list grew.
**Expected behavior**
Form controls must respond quickly. Search and bulk changes must cover
the full action list. A failed save must restore the saved choice.
**Steps to reproduce**
1. Open a connector permission page with hundreds of actions.
2. Switch the agent access mode and select an agent.
3. Search, filter, or change an action permission.
4. Observe the repeated render work and delayed selection feedback.
**Paperclip version or commit**
The issue was reproduced against 3659a3a947. The branch also includes
the current master revision.
## What Changed
- Show 50 actions per group at first. Keep full-list search and bulk
changes. Keep direct links to hidden actions usable.
- Mount each test dialog only when its Test button is used. Memoize
action rows and catalog groups.
- Show pending permission choices at once. Restore saved values after an
error. Update query data from the save response before the next edit.
- Limit new-action review controls to 50 at first. Keep full-list
selections and save results.
- Index agent grants and approval policies to remove repeated list
scans. Compare 100 and 500 actions to guard against quadratic growth.
- Use fresh cancellable permission reads so an older shared response
cannot replace saved choices. Share one page-size constant.
- Add regression tests with 500 actions and delayed save responses.
## Verification
- Failing-before tests showed 500 closed dialogs, 500 action rows, 500
repeated icon renders, delayed access selection feedback, and 500
new-action switches.
- A grant test failed when repeated entry scans exceeded 1,000 reads for
500 actions. The fixed path passes.
- Focused form, page, and group tests pass. They cover pending-save
rollback and a second edit while refresh reads remain pending.
- UI typecheck passes. An initial typecheck found a mutation return-type
error and a fixture cast error. Both were corrected.
- Final revision: `834f77e8b452eec85936591070df9e89d8eda091`.
- Final focused run: 120 tests pass across AppDetail, permission
controls, group changes, grant performance, API helpers, and the request
client. AI saves cover both access modes and saved install cache entries
during pending reads.
- Two tests use the real request client with shared reads started before
a save. Both fail without the fix when the old responses arrive after
the save. Both pass with fresh cancellable reads for connection,
install, profile, and policy data. The tool case also checks the next
save payload.
- The broad local selection passed 8,783 UI tests. Its overall result
was invalidated by later edits. Two unrelated CLI cases failed because
the sandbox starts with file mask 0077. Both test files pass all 24
tests with the expected mask: `umask 022; pnpm exec vitest run
cli/src/__tests__/install-store.test.ts
cli/src/__tests__/mcp-auth.test.ts`.
- Production Chromium checks use 500 actions and 100 agents. A quiet
sample measured mode changes at 49 ms (272 ms before), agent selection
at 30 ms (273 ms before), search clear at 89 ms (432 ms before), and
bulk write changes at 76 ms (300 ms before). All tested controls work.
Closed dialogs make no test-agent request. Opening Test makes one
request. Measurements are single samples and exclude provider network
latency.
- Greptile and Paperclip review both report 5/5 for the final revision.
All review threads are resolved.
- Final-revision CI passed on
`834f77e8b452eec85936591070df9e89d8eda091`: [run
44101128245](https://github.com/paperclipai/paperclip/actions/runs/44101128245).
This includes build, typecheck, general and serialized tests, browser
tests, and Runner verification. Checks ran on GitHub Actions Linux
runners.
- The private staging link was not accessible through the web tool.
Browser checks use a local component harness with 500 actions and 100
agents.
## Risks
- Large lists now require Show more to display further rows. Search and
bulk changes still use all matching actions.
- Pending choices affect the form display only. Server authorization
remains authoritative. The form prevents another save while one is
pending.
- The query cache now uses save responses. Regression tests cover failed
saves and edits during slow refresh reads.
- No schema or server API change is required.
## Model Used
OpenAI Codex, based on GPT-6, with reasoning, tools, and code execution.
This runtime does not expose a more specific model identifier.
## 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:
1 parent
bc0a236b95
commit
a312bdd347
10 files changed
+506
-109
No files matched your search
+8
-8
@@ -364,14 +364,14 @@ export const toolsApi = {
|
||||
listConnections: (companyId: string, options?: RequestOptions) =>
|
||||
options ? api.get<ToolConnectionsResponse>(`/companies/${companyId}/tools/connections`, options)
|
||||
: api.get<ToolConnectionsResponse>(`/companies/${companyId}/tools/connections`),
|
||||
getConnection: (connectionId: string) =>
|
||||
api.get<ToolConnection>(`/tool-connections/${connectionId}`),
|
||||
getConnection: (connectionId: string, options?: RequestOptions) =>
|
||||
api.get<ToolConnection>(`/tool-connections/${connectionId}`, options),
|
||||
// --- Installs (Phase 3b, PAP-13618): which agents carry this connection's
|
||||
// tools in their runtime context. `installed ⊆ permitted`; the server
|
||||
// auto-extends access (adds profile bindings) for any newly-installed target.
|
||||
getConnectionInstalls: (connectionId: string) =>
|
||||
getConnectionInstalls: (connectionId: string, options?: RequestOptions) =>
|
||||
api.get<{ connectionId: string; installs: ToolConnectionInstall[] }>(
|
||||
`/tool-connections/${connectionId}/installs`,
|
||||
`/tool-connections/${connectionId}/installs`, options,
|
||||
),
|
||||
putConnectionInstalls: (
|
||||
connectionId: string,
|
||||
@@ -499,8 +499,8 @@ export const toolsApi = {
|
||||
),
|
||||
|
||||
// --- Profiles ---
|
||||
listConnectionProfileConfiguration: (connectionId: string) =>
|
||||
api.get<{ profiles: ToolProfileConfiguration[] }>(`/tool-connections/${connectionId}/profile-configuration`),
|
||||
listConnectionProfileConfiguration: (connectionId: string, options?: RequestOptions) =>
|
||||
api.get<{ profiles: ToolProfileConfiguration[] }>(`/tool-connections/${connectionId}/profile-configuration`, options),
|
||||
listProfiles: (companyId: string) =>
|
||||
api.get<ToolProfilesResponse>(`/companies/${companyId}/tools/profiles`),
|
||||
getProfileNewTools: (profileId: string) =>
|
||||
@@ -549,8 +549,8 @@ export const toolsApi = {
|
||||
api.get<ToolRuntimeSlot[]>(`/tool-gateway/runtime-slots?companyId=${encodeURIComponent(companyId)}`),
|
||||
|
||||
// --- Policies (trust rules + decision simulator) ---
|
||||
listPolicies: (companyId: string) =>
|
||||
api.get<ToolPoliciesResponse>(`/companies/${companyId}/tools/policies`),
|
||||
listPolicies: (companyId: string, options?: RequestOptions) =>
|
||||
api.get<ToolPoliciesResponse>(`/companies/${companyId}/tools/policies`, options),
|
||||
createPolicy: (companyId: string, input: CreateToolPolicy) =>
|
||||
api.post<ToolPolicy>(`/companies/${companyId}/tools/policies`, input),
|
||||
reorderPolicies: (companyId: string, input: ReorderToolPolicies) =>
|
||||
|
||||
@@ -7,7 +7,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { getAppStoreDefinition, googleWorkspaceSelectedScopes } from "@paperclipai/shared";
|
||||
import type { AggregatorAppSnapshot, AggregatorAppsResponse } from "@paperclipai/shared/aggregator-apps";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { api, ApiError, detachInflightGets, type RequestOptions } from "@/api/client";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import { rememberSkillSourceReturn, skillSourceReturnPath } from "@/lib/skill-source-connect-return";
|
||||
import { AppDetail } from "./AppDetail";
|
||||
@@ -59,15 +59,15 @@ vi.mock("@/api/tools", () => ({
|
||||
toolsApi: {
|
||||
listAggregatorApps: (connectionId: string) => listAggregatorAppsMock(connectionId),
|
||||
syncAggregatorApps: (connectionId: string, force: boolean) => syncAggregatorAppsMock(connectionId, force),
|
||||
getConnection: (connectionId: string) => getConnectionMock(connectionId),
|
||||
getConnectionInstalls: (connectionId: string) => getConnectionInstallsMock(connectionId),
|
||||
getConnection: (connectionId: string, options?: RequestOptions) => options ? getConnectionMock(connectionId, options) : getConnectionMock(connectionId),
|
||||
getConnectionInstalls: (connectionId: string, options?: RequestOptions) => options ? getConnectionInstallsMock(connectionId, options) : getConnectionInstallsMock(connectionId),
|
||||
listApplications: (companyId: string) => listApplicationsMock(companyId),
|
||||
listGallery: (companyId: string) => listGalleryMock(companyId),
|
||||
listConnections: (companyId: string) => listConnectionsMock(companyId),
|
||||
listCatalog: (connectionId: string) => listCatalogMock(connectionId),
|
||||
listConnectionProfileConfiguration: (connectionId: string) => listConnectionProfileConfigurationMock(connectionId),
|
||||
listConnectionProfileConfiguration: (connectionId: string, options?: RequestOptions) => options ? listConnectionProfileConfigurationMock(connectionId, options) : listConnectionProfileConfigurationMock(connectionId),
|
||||
deleteProfile: (profileId: string) => deleteProfileMock(profileId),
|
||||
listPolicies: (companyId: string) => listPoliciesMock(companyId),
|
||||
listPolicies: (companyId: string, options?: RequestOptions) => options ? listPoliciesMock(companyId, options) : listPoliciesMock(companyId),
|
||||
listConnectionActivity: (connectionId: string, limit: number) =>
|
||||
listConnectionActivityMock(connectionId, limit),
|
||||
listActionRequests: (companyId: string, status: string) =>
|
||||
@@ -1094,7 +1094,7 @@ describe("AppDetail", () => {
|
||||
|
||||
it("fetches the connection configuration under a distinct child of the profiles cache", async () => {
|
||||
await renderAppDetail();
|
||||
expect(listConnectionProfileConfigurationMock).toHaveBeenCalledWith("conn-1");
|
||||
expect(listConnectionProfileConfigurationMock).toHaveBeenCalledWith("conn-1", expect.objectContaining({ signal: expect.any(AbortSignal), fresh: true }));
|
||||
expect(queryKeys.tools.connectionProfileConfiguration("company-1", "conn-1").slice(0, 3))
|
||||
.toEqual(queryKeys.tools.profiles("company-1"));
|
||||
expect(queryKeys.tools.connectionProfileConfiguration("company-1", "conn-1"))
|
||||
@@ -1143,6 +1143,144 @@ describe("AppDetail", () => {
|
||||
expect(button.disabled).toBe(false);
|
||||
});
|
||||
|
||||
it("saves AI agent access through installs and keeps the response during refresh", async () => {
|
||||
getConnectionMock.mockResolvedValue(connection({ connectionPurpose: "ai", transport: "runtime_auth", config: { provider: "openai", method: "api_key" } }));
|
||||
const client = await renderAppDetail();
|
||||
getConnectionInstallsMock.mockReturnValue(new Promise(() => {}));
|
||||
const saved = { connectionId: "conn-1", installs: [{ targetType: "company", targetId: "company-1" }] };
|
||||
putConnectionInstallsMock.mockResolvedValueOnce(saved);
|
||||
const accessRadio = (label: string) => Array.from(container.querySelectorAll<HTMLButtonElement>('[role="radio"]'))
|
||||
.find(radio => radio.textContent?.includes(label))!;
|
||||
await act(() => accessRadio("Any agent").click());
|
||||
await flushReact();
|
||||
expect(putConnectionInstallsMock).toHaveBeenLastCalledWith("conn-1", [{ targetType: "company", targetId: "company-1" }]);
|
||||
expect(client.getQueryData(queryKeys.tools.connectionInstalls("conn-1"))).toEqual(saved);
|
||||
expect(accessRadio("Any agent").getAttribute("aria-checked")).toBe("true");
|
||||
await act(() => accessRadio("Just agents I pick").click());
|
||||
await flushReact();
|
||||
expect(putConnectionInstallsMock).toHaveBeenLastCalledWith("conn-1", []);
|
||||
expect(client.getQueryData(queryKeys.tools.connectionInstalls("conn-1"))).toEqual({ connectionId: "conn-1", installs: [] });
|
||||
expect(accessRadio("Just agents I pick").getAttribute("aria-checked")).toBe("true");
|
||||
expect(finishAppMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the saved permission response for the next edit while refresh reads are pending", async () => {
|
||||
const client = await renderAppDetail();
|
||||
listConnectionProfileConfigurationMock.mockReturnValue(new Promise(() => {}));
|
||||
listPoliciesMock.mockReturnValue(new Promise(() => {}));
|
||||
finishAppMock.mockResolvedValue({
|
||||
connection: connection(),
|
||||
profile: { id: "app-profile", profileKey: "app:conn-1" },
|
||||
profileEntries: [{ effect: "include", catalogEntryId: "catalog-read" }],
|
||||
profileBindings: [{ targetType: "company", targetId: "company-1" }],
|
||||
policies: [],
|
||||
});
|
||||
const writeOff = container.querySelector<HTMLButtonElement>('[aria-label="Write issue: Off"]')!;
|
||||
await act(() => writeOff.click());
|
||||
await flushReact();
|
||||
expect(writeOff.getAttribute("aria-checked")).toBe("true");
|
||||
expect(writeOff.disabled).toBe(false);
|
||||
expect(client.getQueryData(queryKeys.tools.policies("company-1"))).toEqual({ policies: [] });
|
||||
await act(() => container.querySelector<HTMLButtonElement>('[aria-label="Read repo: Ask first"]')!.click());
|
||||
await flushReact();
|
||||
expect(finishAppMock).toHaveBeenLastCalledWith("company-1", "conn-1", {
|
||||
enabledCatalogEntryIds: ["catalog-read"],
|
||||
askFirstCatalogEntryIds: ["catalog-read"],
|
||||
access: "all_agents",
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["tool", "ai"])("keeps saved %s permissions when shared pre-save reads arrive late", async (connectionPurpose) => {
|
||||
getConnectionMock.mockResolvedValue(connection({ connectionPurpose }));
|
||||
const client = await renderAppDetail();
|
||||
const { toolsApi: realToolsApi } = await vi.importActual<typeof import("@/api/tools")>("@/api/tools");
|
||||
const savedConnection = connection({ connectionPurpose, name: "Saved connection" });
|
||||
const savedProfile = {
|
||||
id: "app-profile", profileKey: "app:conn-1",
|
||||
entries: [{ effect: "include", catalogEntryId: "catalog-read" }],
|
||||
bindings: [{ targetType: "company", targetId: "company-1" }],
|
||||
};
|
||||
const savedInstalls = { connectionId: "conn-1", installs: [{ targetType: "company", targetId: "company-1" }] };
|
||||
const snapshots = new Map<string, { key: readonly unknown[]; data: unknown }>([
|
||||
["/tool-connections/conn-1", { key: queryKeys.tools.connection("conn-1"), data: savedConnection }],
|
||||
["/tool-connections/conn-1/installs", { key: queryKeys.tools.connectionInstalls("conn-1"), data: savedInstalls }],
|
||||
["/tool-connections/conn-1/profile-configuration", { key: queryKeys.tools.connectionProfileConfiguration("company-1", "conn-1"), data: { profiles: [savedProfile] } }],
|
||||
["/companies/company-1/tools/policies", { key: queryKeys.tools.policies("company-1"), data: { policies: [] } }],
|
||||
]);
|
||||
const resolveOldReads: Array<() => void> = [];
|
||||
let saved = false;
|
||||
const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {
|
||||
const path = String(input).replace(/^\/api/, "");
|
||||
const snapshot = snapshots.get(path);
|
||||
if (!snapshot) throw new Error(`Unexpected fetch: ${path}`);
|
||||
if (!saved) {
|
||||
const stale = client.getQueryData(snapshot.key);
|
||||
return new Promise<Response>(resolve => resolveOldReads.push(() => resolve(Response.json(stale))));
|
||||
}
|
||||
return Response.json(snapshot.data);
|
||||
});
|
||||
const sharedReads = [...snapshots.keys()].map(path => api.get(path));
|
||||
getConnectionMock.mockImplementation(realToolsApi.getConnection);
|
||||
getConnectionInstallsMock.mockImplementation(realToolsApi.getConnectionInstalls);
|
||||
listConnectionProfileConfigurationMock.mockImplementation(realToolsApi.listConnectionProfileConfiguration);
|
||||
listPoliciesMock.mockImplementation(realToolsApi.listPolicies);
|
||||
try {
|
||||
void client.refetchQueries({ predicate: query => [...snapshots.values()].some(snapshot => JSON.stringify(snapshot.key) === JSON.stringify(query.queryKey)) });
|
||||
await flushReact();
|
||||
finishAppMock.mockImplementation(async () => {
|
||||
saved = true;
|
||||
return { connection: savedConnection, profile: savedProfile,
|
||||
profileEntries: savedProfile.entries, profileBindings: savedProfile.bindings, policies: [] };
|
||||
});
|
||||
putConnectionInstallsMock.mockImplementation(async () => { saved = true; return savedInstalls; });
|
||||
await act(() => {
|
||||
if (connectionPurpose === "tool") {
|
||||
container.querySelector<HTMLButtonElement>('[aria-label="Write issue: Off"]')!.click();
|
||||
} else {
|
||||
Array.from(container.querySelectorAll<HTMLButtonElement>('[role="radio"]'))
|
||||
.find(radio => radio.textContent?.includes("Any agent"))!.click();
|
||||
}
|
||||
});
|
||||
await flushReact();
|
||||
resolveOldReads.forEach(resolve => resolve());
|
||||
await Promise.all(sharedReads);
|
||||
await flushReact();
|
||||
for (const snapshot of snapshots.values()) expect(client.getQueryData(snapshot.key)).toEqual(JSON.parse(JSON.stringify(snapshot.data)));
|
||||
if (connectionPurpose === "tool") {
|
||||
await act(() => container.querySelector<HTMLButtonElement>('[aria-label="Read repo: Ask first"]')!.click());
|
||||
await flushReact();
|
||||
expect(finishAppMock).toHaveBeenLastCalledWith("company-1", "conn-1", {
|
||||
enabledCatalogEntryIds: ["catalog-read"], askFirstCatalogEntryIds: ["catalog-read"], access: "all_agents",
|
||||
});
|
||||
} else {
|
||||
expect(Array.from(container.querySelectorAll<HTMLButtonElement>('[role="radio"]'))
|
||||
.find(radio => radio.textContent?.includes("Any agent"))!.getAttribute("aria-checked")).toBe("true");
|
||||
}
|
||||
} finally {
|
||||
resolveOldReads.forEach(resolve => resolve());
|
||||
await Promise.all(sharedReads);
|
||||
detachInflightGets();
|
||||
fetchSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows an agent access change immediately and restores it if the save fails", async () => {
|
||||
let rejectSave!: (error: Error) => void;
|
||||
finishAppMock.mockReturnValue(new Promise((_, reject) => { rejectSave = reject; }));
|
||||
await renderAppDetail();
|
||||
const picked = Array.from(container.querySelectorAll<HTMLButtonElement>('[role="radio"]'))
|
||||
.find(radio => radio.textContent?.includes("Just agents I pick"))!;
|
||||
await act(() => picked.click());
|
||||
expect(picked.getAttribute("aria-checked")).toBe("true");
|
||||
expect(container.textContent).toContain("Choose agents");
|
||||
expect(picked.disabled).toBe(true);
|
||||
await act(async () => rejectSave(new Error("Save rejected")));
|
||||
await flushReact();
|
||||
expect(picked.getAttribute("aria-checked")).toBe("false");
|
||||
expect(picked.disabled).toBe(false);
|
||||
expect(pushToastMock).toHaveBeenCalledWith(expect.objectContaining({ title: "Couldn't save that", tone: "error" }));
|
||||
});
|
||||
|
||||
it("persists agent access independently from always-installed agents", async () => {
|
||||
mockParams.tab = "permissions";
|
||||
listConnectionProfileConfigurationMock.mockResolvedValue({
|
||||
|
||||
@@ -8,7 +8,7 @@ import { isRetiredComposioConnection, RETIRED_COMPOSIO_MESSAGE, isRemoteMcpConne
|
||||
import { RemoteMcpManagement } from "@/features/connections/remote-mcp/RemoteMcpManagement";
|
||||
import { remoteMcpProviders } from "@/features/connections/remote-mcp/providers";
|
||||
import { ManagedAiConnectionDetails } from "@/components/ai-connections/ManagedAiConnectionDetails";
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { EmailConnectionAccess } from "@/components/EmailConnectionAccess";
|
||||
import { EmailConnectionInboxes } from "./chat/EmailEndpointSetup";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
@@ -62,6 +62,7 @@ import { PermissionsPanel } from "./app-detail/PermissionsPanel";
|
||||
import { AgentConnectionAccess } from "./app-detail/AgentConnectionAccess";
|
||||
import { ConnectedAggregatorApps } from "./app-detail/ConnectedAggregatorApps";
|
||||
import { isAppAggregator } from "@paperclipai/shared/aggregator-apps";
|
||||
import { useConnectionPermissionSave } from "./app-detail/useConnectionPermissionSave";
|
||||
import { actionPermissionMutation } from "./app-detail/action-permissions";
|
||||
import { RailwayAccessPanel } from "./app-detail/RailwayAccessPanel";
|
||||
import { ReviewPanel } from "./app-detail/ReviewPanel";
|
||||
@@ -83,7 +84,7 @@ export { connectionAddress, connectionTransportLabel };
|
||||
|
||||
export function AppDetail(props: { renderActions?: (connection: ToolConnection) => ReactNode; renderAgentSettings?: (connection: ToolConnection) => ReactNode; renderConnectionSettings?: (connection: ToolConnection) => ReactNode; onReconnect?: (connection: ToolConnection) => void } = {}) {
|
||||
const { connectionId = "" } = useParams<{ connectionId: string }>();
|
||||
const connection = useQuery({ queryKey: queryKeys.tools.connection(connectionId), queryFn: () => toolsApi.getConnection(connectionId), enabled: !!connectionId });
|
||||
const connection = useQuery({ queryKey: queryKeys.tools.connection(connectionId), queryFn: ({ signal }) => toolsApi.getConnection(connectionId, { signal, fresh: true }), enabled: !!connectionId });
|
||||
const view = useQueryView(connection);
|
||||
if (connection.isPending || view.kind === "reconnecting") return <p role="status">Loading connection…</p>;
|
||||
if (view.kind === "error" && view.errorKind === "not_found") return <AppNotFound />;
|
||||
@@ -116,7 +117,7 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio
|
||||
|
||||
const connectionQuery = useQuery({
|
||||
queryKey: queryKeys.tools.connection(connectionId),
|
||||
queryFn: () => toolsApi.getConnection(connectionId),
|
||||
queryFn: ({ signal }) => toolsApi.getConnection(connectionId, { signal, fresh: true }),
|
||||
enabled: !!connectionId && !!activeTab,
|
||||
});
|
||||
const applicationsQuery = useQuery({
|
||||
@@ -126,7 +127,7 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio
|
||||
});
|
||||
const installsQuery = useQuery({
|
||||
queryKey: queryKeys.tools.connectionInstalls(connectionId),
|
||||
queryFn: () => toolsApi.getConnectionInstalls(connectionId),
|
||||
queryFn: ({ signal }) => toolsApi.getConnectionInstalls(connectionId, { signal, fresh: true }),
|
||||
enabled: !!connectionId && activeTab === "permissions",
|
||||
});
|
||||
const galleryQuery = useQuery({
|
||||
@@ -141,12 +142,12 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio
|
||||
});
|
||||
const profilesQuery = useQuery({
|
||||
queryKey: queryKeys.tools.connectionProfileConfiguration(selectedCompanyId ?? "__none__", connectionId),
|
||||
queryFn: () => toolsApi.listConnectionProfileConfiguration(connectionId),
|
||||
queryFn: ({ signal }) => toolsApi.listConnectionProfileConfiguration(connectionId, { signal, fresh: true }),
|
||||
enabled: !!selectedCompanyId && !!connectionId && (activeTab === "review" || activeTab === "permissions"),
|
||||
});
|
||||
const policiesQuery = useQuery({
|
||||
queryKey: queryKeys.tools.policies(selectedCompanyId ?? "__none__"),
|
||||
queryFn: () => toolsApi.listPolicies(selectedCompanyId!),
|
||||
queryFn: ({ signal }) => toolsApi.listPolicies(selectedCompanyId!, { signal, fresh: true }),
|
||||
enabled: !!selectedCompanyId && (activeTab === "review" || activeTab === "permissions"),
|
||||
});
|
||||
const agentsQuery = useQuery({
|
||||
@@ -277,13 +278,28 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio
|
||||
return () => setBreadcrumbs([]);
|
||||
}, [setBreadcrumbs, appName, connectionId, activeTab]);
|
||||
|
||||
const catalog = catalogQuery.data?.catalog ?? [];
|
||||
const { catalog, active, quarantined, readOnly, canChange } = useMemo(() => {
|
||||
const catalog = catalogQuery.data?.catalog ?? [];
|
||||
const active = catalog.filter(entry => entry.status === "active");
|
||||
return {
|
||||
catalog, active,
|
||||
quarantined: catalog.filter(entry => entry.status === "quarantined"),
|
||||
readOnly: active.filter(entry => entry.isReadOnly),
|
||||
canChange: active.filter(entry => !entry.isReadOnly),
|
||||
};
|
||||
}, [catalogQuery.data]);
|
||||
const { draft: permissionDraft, pending, save: savePermissions } = useConnectionPermissionSave({
|
||||
companyId: selectedCompanyId,
|
||||
connectionId,
|
||||
connection,
|
||||
onError: error => pushToast({ title: "Couldn't save that", body: describeError(error).body, tone: "error" }),
|
||||
});
|
||||
const profile = useMemo(
|
||||
() => (profilesQuery.data?.profiles ?? []).find((p) => p.profileKey === `app:${connectionId}`),
|
||||
[profilesQuery.data, connectionId],
|
||||
);
|
||||
const enabledIds = useMemo(() => enabledCatalogIds(profile), [profile]);
|
||||
const askFirstIds = useMemo(
|
||||
const savedEnabledIds = useMemo(() => enabledCatalogIds(profile), [profile]);
|
||||
const savedAskFirstIds = useMemo(
|
||||
() => askFirstCatalogIds(policiesQuery.data?.policies ?? [], connectionId),
|
||||
[policiesQuery.data, connectionId],
|
||||
);
|
||||
@@ -291,7 +307,10 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio
|
||||
() => installStateFrom(installsQuery.data?.installs ?? connection?.installs),
|
||||
[connection?.installs, installsQuery.data?.installs],
|
||||
);
|
||||
const access = useMemo(() => accessFrom(connection?.connectionPurpose === "ai" ? undefined : profile, install), [connection?.connectionPurpose, profile, install]);
|
||||
const savedAccess = useMemo(() => accessFrom(connection?.connectionPurpose === "ai" ? undefined : profile, install), [connection?.connectionPurpose, profile, install]);
|
||||
const enabledIds = permissionDraft?.enabled ?? savedEnabledIds;
|
||||
const askFirstIds = permissionDraft?.askFirst ?? savedAskFirstIds;
|
||||
const access = permissionDraft?.access ?? savedAccess;
|
||||
const managesRemoteMcpAccess = isRemoteMcpConnectorMethod(connection?.config?.sourceTemplateKey, connection?.config?.connectionMethodKey);
|
||||
const agents = agentsQuery.data ?? [];
|
||||
const disconnectRemote = useMutation({
|
||||
@@ -305,43 +324,6 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio
|
||||
},
|
||||
onError: (error) => pushToast({ title: "Couldn't disconnect", body: describeError(error).body, tone: "error" }),
|
||||
});
|
||||
const [pending, setPending] = useState(false);
|
||||
const persist = useMutation({
|
||||
mutationFn: async (next: {
|
||||
enabled: Set<string>;
|
||||
askFirst: Set<string>;
|
||||
access: AccessDraft;
|
||||
reviewed?: Set<string>;
|
||||
}) => {
|
||||
return connection?.connectionPurpose === "ai"
|
||||
? toolsApi.putConnectionInstalls(connectionId, next.access.mode === "all" ? [{ targetType: "company", targetId: selectedCompanyId! }] : [...next.access.agentIds].map(targetId => ({ targetType: "agent" as const, targetId })))
|
||||
: 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),
|
||||
onSuccess: () => {
|
||||
void installsQuery.refetch();
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.tools.testAgentAccessesForConnection(connectionId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.tools.connection(connectionId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.tools.catalog(connectionId) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.tools.profiles(selectedCompanyId!) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.tools.policies(selectedCompanyId!) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.tools.connections(selectedCompanyId!) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.apps.attention(selectedCompanyId!) });
|
||||
},
|
||||
onError: (error) =>
|
||||
pushToast({
|
||||
title: "Couldn't save that",
|
||||
body: describeError(error).body,
|
||||
tone: "error",
|
||||
}),
|
||||
onSettled: () => setPending(false),
|
||||
});
|
||||
|
||||
const [renaming, setRenaming] = useState(false);
|
||||
const [nameDraft, setNameDraft] = useState("");
|
||||
const rename = useMutation({
|
||||
@@ -500,18 +482,21 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio
|
||||
},
|
||||
});
|
||||
|
||||
const apply = (mutate: {
|
||||
const apply = useCallback((mutate: {
|
||||
enabled?: Set<string>;
|
||||
askFirst?: Set<string>;
|
||||
access?: AccessDraft;
|
||||
reviewed?: Set<string>;
|
||||
}) =>
|
||||
persist.mutate({
|
||||
savePermissions({
|
||||
enabled: mutate.enabled ?? new Set(enabledIds),
|
||||
askFirst: mutate.askFirst ?? new Set(askFirstIds),
|
||||
access: mutate.access ?? access,
|
||||
reviewed: mutate.reviewed,
|
||||
});
|
||||
}), [savePermissions, enabledIds, askFirstIds, access]);
|
||||
const setActionPermission = useCallback((ids: string[], next: "off" | "ask" | "allowed") => {
|
||||
apply(actionPermissionMutation(ids, next, enabledIds, askFirstIds));
|
||||
}, [apply, enabledIds, askFirstIds]);
|
||||
|
||||
const reviewQuarantined = (allowedIds: string[]) => {
|
||||
const quarantinedIds = new Set(quarantined.map((entry) => entry.id));
|
||||
@@ -574,10 +559,6 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio
|
||||
const status: StatusInfo = aiGrantRevoked ? { label: "Revoked", tone: "attention" } : statusFor(connection);
|
||||
const needsReconnect = connection.requiresReauthorization
|
||||
?? (status.tone === "attention" && connection.healthStatus !== "unknown");
|
||||
const quarantined = catalog.filter((e) => e.status === "quarantined");
|
||||
const active = catalog.filter((e) => e.status === "active");
|
||||
const readOnly = active.filter((e) => e.isReadOnly);
|
||||
const canChange = active.filter((e) => !e.isReadOnly);
|
||||
const actionsContent = renderActions?.(connection) ?? (connection.connectionPurpose === "ai" ? <ManagedAiConnectionDetails connection={connection} /> : undefined);
|
||||
const actionCount = actionsContent !== undefined ? null : catalogQuery.data ? active.length : null;
|
||||
const reviewViews = [catalogView, profilesView, policiesView];
|
||||
@@ -734,7 +715,7 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio
|
||||
}
|
||||
onSaveAccess={(next) => apply({ access: connection.connectionPurpose === "ai" || connection.connectionPurpose === "tool" ? next : accessIncludingInstalls(next, install) })}
|
||||
onRefreshActions={() => refreshTools.mutate()}
|
||||
onSetActionPermission={(ids, next) => apply(actionPermissionMutation(ids, next, enabledIds, askFirstIds))}
|
||||
onSetActionPermission={setActionPermission}
|
||||
onReviewQuarantined={reviewQuarantined}
|
||||
/>
|
||||
<AgentConnectionAccess
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import type { ToolCatalogEntry, ToolPolicy, ToolProfileConfiguration } from "@paperclipai/shared";
|
||||
import { AgentConnectionAccess } from "./AgentConnectionAccess";
|
||||
|
||||
async function renderGrant(catalogSize: number) {
|
||||
let entryReads = 0;
|
||||
let policyReads = 0;
|
||||
const catalog = Array.from({ length: catalogSize }, (_, index) => ({ id: `tool-${index}`, toolName: `Tool ${index}` })) as ToolCatalogEntry[];
|
||||
const entries = catalog.map(tool => ({ effect: "include", get catalogEntryId() {
|
||||
if (++entryReads > catalogSize * 20) throw new Error("Grant matching scans the full entry list for each tool");
|
||||
return tool.id;
|
||||
} }));
|
||||
const profiles = [{ id: "profile-1", profileKey: "connection-intent:conn-1:agent-1", status: "active",
|
||||
metadata: { source: "connection_intent", connectionId: "conn-1", agentId: "agent-1" },
|
||||
bindings: [{ targetType: "agent", targetId: "agent-1" }], entries,
|
||||
}] as unknown as ToolProfileConfiguration[];
|
||||
const policies = catalog.map(tool => ({ enabled: true, policyType: "require_approval", selectors: { catalogEntryId: tool.id },
|
||||
get config() {
|
||||
if (++policyReads > catalogSize * 20) throw new Error("Grant matching scans the policy list for each tool");
|
||||
return { source: "connection_intent", connectionId: "conn-1", agentId: "agent-1" };
|
||||
},
|
||||
})) as unknown as ToolPolicy[];
|
||||
const container = document.createElement("div");
|
||||
document.body.append(container);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(() => root.render(<AgentConnectionAccess connectionId="conn-1" profiles={profiles} policies={policies}
|
||||
catalog={catalog} agents={[]} canManage onRemove={vi.fn()} />));
|
||||
expect(container.querySelectorAll("li")).toHaveLength(catalogSize);
|
||||
expect(container.querySelectorAll("li")[catalogSize - 1]?.textContent).toContain("Ask first");
|
||||
return { entryReads, policyReads };
|
||||
} finally {
|
||||
await act(() => root.unmount());
|
||||
container.remove();
|
||||
}
|
||||
}
|
||||
|
||||
it("keeps grant entry and policy matching below quadratic growth", async () => {
|
||||
const small = await renderGrant(100);
|
||||
const large = await renderGrant(500);
|
||||
expect(small.entryReads).toBeGreaterThan(0);
|
||||
expect(small.policyReads).toBeGreaterThan(0);
|
||||
expect(large.entryReads).toBeLessThan(small.entryReads * 10);
|
||||
expect(large.policyReads).toBeLessThan(small.policyReads * 10);
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from "react";
|
||||
import { useMemo, useState } from "react";
|
||||
import type { Agent, ToolCatalogEntry, ToolPolicy, ToolProfileConfiguration } from "@paperclipai/shared";
|
||||
import { AgentAvatar } from "@/components/AgentAvatar";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -15,7 +15,7 @@ export function AgentConnectionAccess({ connectionId, profiles, policies, catalo
|
||||
}) {
|
||||
const [pending, setPending] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const grants = profiles.filter(profile => {
|
||||
const grants = useMemo(() => profiles.filter(profile => {
|
||||
const agentId = profile.metadata?.agentId;
|
||||
return profile.status === "active"
|
||||
&& profile.metadata?.source === "connection_intent"
|
||||
@@ -23,7 +23,29 @@ export function AgentConnectionAccess({ connectionId, profiles, policies, catalo
|
||||
&& typeof agentId === "string"
|
||||
&& profile.profileKey === `connection-intent:${connectionId}:${agentId}`
|
||||
&& profile.bindings.some(binding => binding.targetType === "agent" && binding.targetId === agentId);
|
||||
});
|
||||
}), [profiles, connectionId]);
|
||||
const agentsById = useMemo(() => new Map(agents.map(agent => [agent.id, agent])), [agents]);
|
||||
const approvalKeys = useMemo(() => {
|
||||
const keys = new Set<string>();
|
||||
for (const policy of policies) {
|
||||
if (policy.enabled && policy.policyType === "require_approval"
|
||||
&& policy.config?.source === "connection_intent" && policy.config.connectionId === connectionId) {
|
||||
keys.add(`${policy.config.agentId}:${policy.selectors?.catalogEntryId}`);
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
}, [policies, connectionId]);
|
||||
const toolsByProfileId = useMemo(() => {
|
||||
const byId = new Map(catalog.map((tool, index) => [tool.id, { tool, index }]));
|
||||
return new Map(grants.map(profile => {
|
||||
const ids = new Set(profile.entries.filter(entry => entry.effect === "include").map(entry => entry.catalogEntryId));
|
||||
const tools = [...ids].flatMap(id => {
|
||||
const entry = id ? byId.get(id) : undefined;
|
||||
return entry ? [entry] : [];
|
||||
}).sort((a, b) => a.index - b.index).map(entry => entry.tool);
|
||||
return [profile.id, tools];
|
||||
}));
|
||||
}, [grants, catalog]);
|
||||
if (grants.length === 0) return null;
|
||||
|
||||
async function remove(profileId: string) {
|
||||
@@ -45,8 +67,8 @@ export function AgentConnectionAccess({ connectionId, profiles, policies, catalo
|
||||
</div>
|
||||
{grants.map(profile => {
|
||||
const agentId = profile.metadata!.agentId as string;
|
||||
const agent = agents.find(candidate => candidate.id === agentId);
|
||||
const tools = catalog.filter(tool => profile.entries.some(entry => entry.effect === "include" && entry.catalogEntryId === tool.id));
|
||||
const agent = agentsById.get(agentId);
|
||||
const tools = toolsByProfileId.get(profile.id) ?? [];
|
||||
return <div key={profile.id} className="space-y-3 rounded-lg border border-border p-4">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
@@ -59,10 +81,7 @@ export function AgentConnectionAccess({ connectionId, profiles, policies, catalo
|
||||
</div>
|
||||
<ul className="space-y-2">
|
||||
{tools.map(tool => {
|
||||
const askFirst = policies.some(policy => policy.enabled && policy.policyType === "require_approval"
|
||||
&& policy.config?.source === "connection_intent"
|
||||
&& policy.config.connectionId === connectionId && policy.config.agentId === agentId
|
||||
&& policy.selectors?.catalogEntryId === tool.id);
|
||||
const askFirst = approvalKeys.has(`${agentId}:${tool.id}`);
|
||||
return <li key={tool.id} className="flex items-center justify-between gap-4 text-sm">
|
||||
<span className="min-w-0 break-all">{tool.title || tool.toolName}</span>
|
||||
<span className="shrink-0 text-muted-foreground">{askFirst ? "Ask first" : "Allowed"}</span>
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { Agent, ToolCatalogEntry, ToolConnectionCapabilities } from "@paperclipai/shared";
|
||||
import { PermissionsPanel } from "./PermissionsPanel";
|
||||
import { installStateFrom } from "@/lib/tool-installs";
|
||||
|
||||
const { dialog, icon } = vi.hoisted(() => ({ dialog: vi.fn(), icon: vi.fn() }));
|
||||
vi.mock("./ActionTestDialog", () => ({
|
||||
ActionTestDialog: (props: { open: boolean; onOpenChange: (open: boolean) => void }) => {
|
||||
dialog(props);
|
||||
return props.open ? <button onClick={() => props.onOpenChange(false)}>Close test</button> : null;
|
||||
},
|
||||
}));
|
||||
vi.mock("@/components/ProviderToolIcon", () => ({ ProviderToolIcon: () => { icon(); return null; } }));
|
||||
|
||||
let root: ReturnType<typeof createRoot>;
|
||||
let container: HTMLDivElement;
|
||||
afterEach(async () => {
|
||||
await act(() => root?.unmount());
|
||||
container?.remove();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
function entries() {
|
||||
return Array.from({ length: 500 }, (_, index) => ({
|
||||
id: `action-${index}`, toolName: `action_${index}`, title: `Action ${String(index).padStart(3, "0")}`,
|
||||
description: `Action number ${index}`, status: "active", isReadOnly: index < 250,
|
||||
riskLevel: index < 250 ? "read" : "write", icons: [{ src: "https://example.test/icon.svg" }],
|
||||
}) as ToolCatalogEntry);
|
||||
}
|
||||
|
||||
async function setup(focus = "", review = false) {
|
||||
const catalog = entries();
|
||||
const props = {
|
||||
connectionId: "conn-1", appName: "App", agents: [] as Agent[],
|
||||
access: { mode: "all" as "all" | "specific", agentIds: new Set<string>() },
|
||||
install: installStateFrom([]), capabilities: { canConfigure: true } as ToolConnectionCapabilities,
|
||||
readOnly: catalog.slice(0, 250), canChange: catalog.slice(250), quarantined: review ? catalog : [],
|
||||
enabledIds: new Set(catalog.map(entry => entry.id)), askFirstIds: new Set<string>(),
|
||||
pending: false, refreshPending: false, onSaveAccess: vi.fn(), onSetActionPermission: vi.fn(),
|
||||
onReviewQuarantined: vi.fn(), onRefreshActions: vi.fn(),
|
||||
};
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
const render = () => root.render(<MemoryRouter initialEntries={[`/?focus=${focus}`]}><PermissionsPanel {...props} /></MemoryRouter>);
|
||||
await act(render);
|
||||
return { props, render };
|
||||
}
|
||||
|
||||
function setSearch(value: string) {
|
||||
const input = container.querySelector<HTMLInputElement>('[aria-label="Find an action"]')!;
|
||||
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
}
|
||||
|
||||
describe("permission form work with a large catalog", () => {
|
||||
it("mounts a test dialog only when its Test button is used", async () => {
|
||||
await setup();
|
||||
expect(dialog).not.toHaveBeenCalled();
|
||||
const test = Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Test")!;
|
||||
await act(() => test.click());
|
||||
expect(dialog).toHaveBeenCalledTimes(1);
|
||||
await act(() => Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Close test")!.click());
|
||||
expect(container.textContent).not.toContain("Close test");
|
||||
});
|
||||
|
||||
it("bounds rendered rows while bulk permissions still include hidden actions", async () => {
|
||||
const { props } = await setup();
|
||||
expect(container.querySelectorAll("[data-action-id]").length).toBeLessThanOrEqual(100);
|
||||
const select = container.querySelector<HTMLSelectElement>('select[aria-label="Set every action in Write (250)"]')!;
|
||||
await act(() => { select.value = "ask"; select.dispatchEvent(new Event("change", { bubbles: true })); });
|
||||
expect(props.onSetActionPermission).toHaveBeenCalledWith(props.canChange.map(entry => entry.id), "ask");
|
||||
const more = Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Show more read actions")!;
|
||||
await act(() => more.click());
|
||||
expect(container.querySelectorAll("[data-action-id]")).toHaveLength(150);
|
||||
await act(() => setSearch("Action 499"));
|
||||
expect(container.querySelectorAll("[data-action-id]")).toHaveLength(1);
|
||||
expect(container.querySelector('[data-action-id="action-499"]')).toBeTruthy();
|
||||
});
|
||||
|
||||
it("does not rerender action controls for an agent access change", async () => {
|
||||
const { props, render } = await setup();
|
||||
icon.mockClear();
|
||||
props.access = { mode: "specific", agentIds: new Set() };
|
||||
await act(render);
|
||||
expect(icon).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("bounds new-action review controls and saves choices for the full list", async () => {
|
||||
const { props } = await setup("", true);
|
||||
expect(container.querySelectorAll('[role="switch"]').length).toBeLessThanOrEqual(50);
|
||||
const button = (label: string) => Array.from(container.querySelectorAll("button")).find(button => button.textContent === label)!;
|
||||
await act(() => button("Turn all on").click());
|
||||
expect(container.textContent).toContain("500 of 500 will be on");
|
||||
await act(() => button("Show more new actions").click());
|
||||
expect(container.querySelectorAll('[role="switch"]')).toHaveLength(100);
|
||||
await act(() => button("Save choices").click());
|
||||
expect(props.onReviewQuarantined).toHaveBeenCalledWith(entries().map(entry => entry.id));
|
||||
});
|
||||
|
||||
it("shows an action linked beyond the first page", async () => {
|
||||
Element.prototype.scrollIntoView = vi.fn();
|
||||
await setup("action-499");
|
||||
expect(container.querySelector('[data-action-id="action-499"]')).toBeTruthy();
|
||||
expect(container.querySelectorAll("[data-action-id]").length).toBeLessThanOrEqual(101);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { AgentAvatar } from "@/components/AgentAvatar";
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { Ban, Check, FlaskConical, Loader2, RefreshCw, Search, ShieldQuestion } from "lucide-react";
|
||||
import type { Agent, ToolCatalogEntry, ToolConnectionCapabilities } from "@paperclipai/shared";
|
||||
import { useSearchParams } from "@/lib/router";
|
||||
@@ -13,6 +13,7 @@ import { cn } from "@/lib/utils";
|
||||
import { type InstallState } from "@/lib/tool-installs";
|
||||
import { QuarantinedActionsReview } from "./SetupPanel";
|
||||
import { ActionTestDialog } from "./ActionTestDialog";
|
||||
import { ACTION_PAGE_SIZE } from "./constants";
|
||||
import { ProviderToolIcon } from "@/components/ProviderToolIcon";
|
||||
|
||||
/** Action rows without a provider icon show none, as before. */
|
||||
@@ -120,12 +121,14 @@ function AgentAccessSection({
|
||||
disabled: boolean;
|
||||
onSave: (next: AccessDraft) => void;
|
||||
}) {
|
||||
const liveAgents = agents.filter((agent) => agent.status !== "terminated");
|
||||
const liveAgents = useMemo(() => agents.filter((agent) => agent.status !== "terminated"), [agents]);
|
||||
const canManage = capabilities?.canConfigure ?? false;
|
||||
const editableAgentIds = capabilities?.editableAgentIds;
|
||||
const selectableAgents = editableAgentIds
|
||||
? liveAgents.filter((agent) => editableAgentIds.includes(agent.id))
|
||||
: liveAgents;
|
||||
const selectableAgents = useMemo(() => {
|
||||
if (!editableAgentIds) return liveAgents;
|
||||
const editable = new Set(editableAgentIds);
|
||||
return liveAgents.filter((agent) => editable.has(agent.id));
|
||||
}, [editableAgentIds, liveAgents]);
|
||||
const selectedAgents = liveAgents.filter((agent) => access.agentIds.has(agent.id));
|
||||
const requiredAgentIds = install.agentIds;
|
||||
|
||||
@@ -239,21 +242,19 @@ export function ActionsSection({
|
||||
const [query, setQuery] = useState("");
|
||||
const [kindFilter, setKindFilter] = useState<ActionKindFilter>("all");
|
||||
const [showPermissionChangeWarning, setShowPermissionChangeWarning] = useState(false);
|
||||
const byName = (a: ToolCatalogEntry, b: ToolCatalogEntry) =>
|
||||
(a.title ?? a.toolName).localeCompare(b.title ?? b.toolName);
|
||||
const sortedRead = useMemo(() => [...readOnly].sort(byName), [readOnly]);
|
||||
const sortedWrite = useMemo(() => [...canChange].sort(byName), [canChange]);
|
||||
const matches = (entry: ToolCatalogEntry) => {
|
||||
const needle = query.trim().toLowerCase();
|
||||
if (!needle) return true;
|
||||
return (entry.title ?? entry.toolName).toLowerCase().includes(needle)
|
||||
|| (entry.description ?? "").toLowerCase().includes(needle);
|
||||
};
|
||||
const visibleRead = kindFilter === "write" ? [] : sortedRead.filter(matches);
|
||||
const visibleWrite = kindFilter === "read" ? [] : sortedWrite.filter(matches);
|
||||
const needle = query.trim().toLowerCase();
|
||||
const visibleRead = useMemo(() => kindFilter === "write" ? [] : sortedRead.filter(entry => matchesAction(entry, needle)), [kindFilter, needle, sortedRead]);
|
||||
const visibleWrite = useMemo(() => kindFilter === "read" ? [] : sortedWrite.filter(entry => matchesAction(entry, needle)), [kindFilter, needle, sortedWrite]);
|
||||
const setPermission = useCallback((ids: string[], next: ActionPermission) => {
|
||||
setShowPermissionChangeWarning(true);
|
||||
onSetPermission(ids, next);
|
||||
}, [onSetPermission]);
|
||||
const visibleCount = visibleRead.length + visibleWrite.length;
|
||||
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<section className="space-y-6 border-t border-border pt-8">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<h2 className="text-lg font-semibold text-foreground">Actions</h2>
|
||||
@@ -317,6 +318,8 @@ export function ActionsSection({
|
||||
) : (
|
||||
<div className="space-y-6">
|
||||
<ActionGroup
|
||||
key={`read:${needle}:${kindFilter}`}
|
||||
kind="read"
|
||||
title={`Read (${visibleRead.length})`}
|
||||
actions={visibleRead}
|
||||
connectionId={connectionId}
|
||||
@@ -326,12 +329,11 @@ export function ActionsSection({
|
||||
disabled={disabled}
|
||||
focusId={focusId}
|
||||
canConfigure={canConfigure}
|
||||
onSetPermission={(ids, next) => {
|
||||
setShowPermissionChangeWarning(true);
|
||||
onSetPermission(ids, next);
|
||||
}}
|
||||
onSetPermission={setPermission}
|
||||
/>
|
||||
<ActionGroup
|
||||
key={`write:${needle}:${kindFilter}`}
|
||||
kind="write"
|
||||
title={`Write (${visibleWrite.length})`}
|
||||
actions={visibleWrite}
|
||||
connectionId={connectionId}
|
||||
@@ -341,14 +343,12 @@ export function ActionsSection({
|
||||
disabled={disabled}
|
||||
focusId={focusId}
|
||||
canConfigure={canConfigure}
|
||||
onSetPermission={(ids, next) => {
|
||||
setShowPermissionChangeWarning(true);
|
||||
onSetPermission(ids, next);
|
||||
}}
|
||||
onSetPermission={setPermission}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -370,7 +370,18 @@ function FilterChip({ label, active, onClick }: { label: string; active: boolean
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
function byName(a: ToolCatalogEntry, b: ToolCatalogEntry) {
|
||||
return (a.title ?? a.toolName).localeCompare(b.title ?? b.toolName);
|
||||
}
|
||||
|
||||
function matchesAction(entry: ToolCatalogEntry, needle: string) {
|
||||
return !needle || (entry.title ?? entry.toolName).toLowerCase().includes(needle)
|
||||
|| (entry.description ?? "").toLowerCase().includes(needle);
|
||||
}
|
||||
|
||||
function ActionGroup({
|
||||
kind,
|
||||
title,
|
||||
actions,
|
||||
connectionId,
|
||||
@@ -382,6 +393,7 @@ function ActionGroup({
|
||||
canConfigure,
|
||||
onSetPermission,
|
||||
}: {
|
||||
kind: "read" | "write";
|
||||
title: string;
|
||||
actions: ToolCatalogEntry[];
|
||||
connectionId: string;
|
||||
@@ -393,6 +405,10 @@ function ActionGroup({
|
||||
canConfigure: boolean;
|
||||
onSetPermission: (ids: string[], next: ActionPermission) => void;
|
||||
}) {
|
||||
const [visibleLimit, setVisibleLimit] = useState(ACTION_PAGE_SIZE);
|
||||
const visibleActions = actions.slice(0, visibleLimit);
|
||||
const focusedAction = focusId ? actions.find(action => action.id === focusId) : undefined;
|
||||
if (focusedAction && !visibleActions.includes(focusedAction)) visibleActions.push(focusedAction);
|
||||
if (actions.length === 0) return null;
|
||||
const groupValue = (() => {
|
||||
const first = actionPermission(actions[0]!.id, enabledIds, askFirstIds);
|
||||
@@ -431,7 +447,7 @@ function ActionGroup({
|
||||
) : null}
|
||||
</div>
|
||||
<div className="divide-y divide-border">
|
||||
{actions.map((action) => (
|
||||
{visibleActions.map((action) => (
|
||||
<ActionRow
|
||||
key={action.id}
|
||||
action={action}
|
||||
@@ -445,6 +461,11 @@ function ActionGroup({
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{visibleLimit < actions.length ? (
|
||||
<Button type="button" variant="outline" size="sm" className="mt-3" onClick={() => setVisibleLimit(limit => limit + ACTION_PAGE_SIZE)}>
|
||||
Show more {kind} actions
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -460,7 +481,7 @@ const PERMISSION_OPTIONS: Array<{
|
||||
{ value: "allowed", label: "Allowed", description: "Runs without approval.", icon: Check },
|
||||
];
|
||||
|
||||
function ActionRow({
|
||||
const ActionRow = memo(function ActionRow({
|
||||
action,
|
||||
connectionId,
|
||||
appName,
|
||||
@@ -519,7 +540,6 @@ function ActionRow({
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
{canConfigure ? (
|
||||
<TooltipProvider>
|
||||
<div
|
||||
role="radiogroup"
|
||||
aria-label={`${title} permission`}
|
||||
@@ -555,7 +575,6 @@ function ActionRow({
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
) : (
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{PERMISSION_OPTIONS.find((option) => option.value === value)?.label}
|
||||
@@ -567,16 +586,16 @@ function ActionRow({
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<ActionTestDialog
|
||||
{testOpen ? <ActionTestDialog
|
||||
connectionId={connectionId}
|
||||
appName={appName}
|
||||
entry={action}
|
||||
open={testOpen}
|
||||
onOpenChange={setTestOpen}
|
||||
/>
|
||||
/> : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
function actionPermission(
|
||||
id: string,
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { ToolCatalogEntry, ToolConnection } from "@paperclipai/shared";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { ToggleSwitch } from "@/components/ui/toggle-switch";
|
||||
import { ACTION_PAGE_SIZE } from "./constants";
|
||||
import { appDefinitionSlug } from "../app-definition-display";
|
||||
import type { AppDetailSectionProps } from "./types";
|
||||
import { googleSheetsConfigWithAllowlist, parseGoogleSheetIds } from "../google-sheets";
|
||||
@@ -254,6 +255,7 @@ export function QuarantinedActionsReview({
|
||||
onSubmit: (enabledIds: string[]) => void;
|
||||
}) {
|
||||
const [enabledIds, setEnabledIds] = useState<Set<string>>(new Set());
|
||||
const [visibleLimit, setVisibleLimit] = useState(ACTION_PAGE_SIZE);
|
||||
const count = entries.length;
|
||||
const selectedIds = entries.filter((entry) => enabledIds.has(entry.id)).map((entry) => entry.id);
|
||||
return (
|
||||
@@ -287,7 +289,7 @@ export function QuarantinedActionsReview({
|
||||
</div>
|
||||
</div>
|
||||
<div className="divide-y divide-border">
|
||||
{entries.map((entry) => {
|
||||
{entries.slice(0, visibleLimit).map((entry) => {
|
||||
const enabled = enabledIds.has(entry.id);
|
||||
const label = entry.title ?? entry.toolName;
|
||||
return (
|
||||
@@ -315,6 +317,11 @@ export function QuarantinedActionsReview({
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{visibleLimit < count ? (
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => setVisibleLimit(limit => limit + ACTION_PAGE_SIZE)}>
|
||||
Show more new actions
|
||||
</Button>
|
||||
) : null}
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-xs text-amber-700 dark:text-amber-300">
|
||||
{selectedIds.length} of {count} will be on
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
export const ACTION_PAGE_SIZE = 50;
|
||||
@@ -0,0 +1,73 @@
|
||||
import { useState } from "react";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import type { ToolConnection, ToolPolicy, ToolProfileConfiguration } from "@paperclipai/shared";
|
||||
import { toolsApi } from "@/api/tools";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import type { AccessDraft } from "./types";
|
||||
|
||||
interface PermissionDraft {
|
||||
enabled: Set<string>;
|
||||
askFirst: Set<string>;
|
||||
access: AccessDraft;
|
||||
reviewed?: Set<string>;
|
||||
}
|
||||
|
||||
export function useConnectionPermissionSave({ companyId, connectionId, connection, onError }: {
|
||||
companyId: string | null;
|
||||
connectionId: string;
|
||||
connection: ToolConnection | undefined;
|
||||
onError: (error: Error) => void;
|
||||
}) {
|
||||
const client = useQueryClient();
|
||||
const [draft, setDraft] = useState<PermissionDraft | null>(null);
|
||||
const mutation = useMutation({
|
||||
mutationFn: async (next: PermissionDraft) => connection?.connectionPurpose === "ai"
|
||||
? toolsApi.putConnectionInstalls(connectionId, next.access.mode === "all"
|
||||
? [{ targetType: "company", targetId: companyId! }]
|
||||
: [...next.access.agentIds].map(targetId => ({ targetType: "agent" as const, targetId })))
|
||||
: toolsApi.finishApp(companyId!, 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: async (next) => {
|
||||
setDraft(next);
|
||||
await Promise.all([
|
||||
queryKeys.tools.connectionProfileConfiguration(companyId!, connectionId),
|
||||
queryKeys.tools.policies(companyId!),
|
||||
queryKeys.tools.connection(connectionId),
|
||||
queryKeys.tools.connectionInstalls(connectionId),
|
||||
].map(queryKey => client.cancelQueries({ queryKey })));
|
||||
},
|
||||
onSuccess: (result) => {
|
||||
if ("profile" in result) {
|
||||
const configuration = { ...result.profile, entries: result.profileEntries, bindings: result.profileBindings };
|
||||
client.setQueryData<{ profiles: ToolProfileConfiguration[] }>(
|
||||
queryKeys.tools.connectionProfileConfiguration(companyId!, connectionId),
|
||||
previous => ({ profiles: [...(previous?.profiles ?? []).filter(profile => profile.profileKey !== result.profile.profileKey), configuration] }),
|
||||
);
|
||||
client.setQueryData<{ policies: ToolPolicy[] }>(queryKeys.tools.policies(companyId!), previous => ({
|
||||
policies: [...(previous?.policies ?? []).filter(policy => !(policy.policyType === "require_approval"
|
||||
&& policy.config?.source === "app_gallery_finish" && policy.config.connectionId === connectionId)), ...result.policies],
|
||||
}));
|
||||
client.setQueryData(queryKeys.tools.connection(connectionId), result.connection);
|
||||
} else if ("installs" in result) {
|
||||
client.setQueryData(queryKeys.tools.connectionInstalls(connectionId), result);
|
||||
}
|
||||
for (const queryKey of [
|
||||
queryKeys.tools.connectionInstalls(connectionId),
|
||||
queryKeys.tools.testAgentAccessesForConnection(connectionId),
|
||||
queryKeys.tools.connection(connectionId),
|
||||
queryKeys.tools.catalog(connectionId),
|
||||
queryKeys.tools.profiles(companyId!),
|
||||
queryKeys.tools.policies(companyId!),
|
||||
queryKeys.tools.connections(companyId!),
|
||||
queryKeys.apps.attention(companyId!),
|
||||
]) void client.invalidateQueries({ queryKey });
|
||||
},
|
||||
onError,
|
||||
onSettled: () => setDraft(null),
|
||||
});
|
||||
return { draft, pending: mutation.isPending, save: mutation.mutate };
|
||||
}
|
||||
Reference in new issue
Block a user