diff --git a/ui/src/api/tools.ts b/ui/src/api/tools.ts index 2903ec92f1a..786afb8929b 100644 --- a/ui/src/api/tools.ts +++ b/ui/src/api/tools.ts @@ -364,14 +364,14 @@ export const toolsApi = { listConnections: (companyId: string, options?: RequestOptions) => options ? api.get(`/companies/${companyId}/tools/connections`, options) : api.get(`/companies/${companyId}/tools/connections`), - getConnection: (connectionId: string) => - api.get(`/tool-connections/${connectionId}`), + getConnection: (connectionId: string, options?: RequestOptions) => + api.get(`/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(`/companies/${companyId}/tools/profiles`), getProfileNewTools: (profileId: string) => @@ -549,8 +549,8 @@ export const toolsApi = { api.get(`/tool-gateway/runtime-slots?companyId=${encodeURIComponent(companyId)}`), // --- Policies (trust rules + decision simulator) --- - listPolicies: (companyId: string) => - api.get(`/companies/${companyId}/tools/policies`), + listPolicies: (companyId: string, options?: RequestOptions) => + api.get(`/companies/${companyId}/tools/policies`, options), createPolicy: (companyId: string, input: CreateToolPolicy) => api.post(`/companies/${companyId}/tools/policies`, input), reorderPolicies: (companyId: string, input: ReorderToolPolicies) => diff --git a/ui/src/pages/apps/AppDetail.test.tsx b/ui/src/pages/apps/AppDetail.test.tsx index b2ffb27d485..885a7029f3a 100644 --- a/ui/src/pages/apps/AppDetail.test.tsx +++ b/ui/src/pages/apps/AppDetail.test.tsx @@ -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('[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('[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('[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("@/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([ + ["/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(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('[aria-label="Write issue: Off"]')!.click(); + } else { + Array.from(container.querySelectorAll('[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('[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('[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('[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({ diff --git a/ui/src/pages/apps/AppDetail.tsx b/ui/src/pages/apps/AppDetail.tsx index 5922fabfc65..993d67873ba 100644 --- a/ui/src/pages/apps/AppDetail.tsx +++ b/ui/src/pages/apps/AppDetail.tsx @@ -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

Loading connection…

; if (view.kind === "error" && view.errorKind === "not_found") return ; @@ -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; - askFirst: Set; - access: AccessDraft; - reviewed?: Set; - }) => { - 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; askFirst?: Set; access?: AccessDraft; reviewed?: Set; }) => - 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" ? : 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} /> ({ 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()); + 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); +}); diff --git a/ui/src/pages/apps/app-detail/AgentConnectionAccess.tsx b/ui/src/pages/apps/app-detail/AgentConnectionAccess.tsx index 7c19dac18c2..a65eacde535 100644 --- a/ui/src/pages/apps/app-detail/AgentConnectionAccess.tsx +++ b/ui/src/pages/apps/app-detail/AgentConnectionAccess.tsx @@ -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(null); const [error, setError] = useState(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(); + 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 {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
@@ -59,10 +81,7 @@ export function AgentConnectionAccess({ connectionId, profiles, policies, catalo
    {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
  • {tool.title || tool.toolName} {askFirst ? "Ask first" : "Allowed"} diff --git a/ui/src/pages/apps/app-detail/PermissionsPanel.performance.test.tsx b/ui/src/pages/apps/app-detail/PermissionsPanel.performance.test.tsx new file mode 100644 index 00000000000..fd8f0449730 --- /dev/null +++ b/ui/src/pages/apps/app-detail/PermissionsPanel.performance.test.tsx @@ -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 ? : null; + }, +})); +vi.mock("@/components/ProviderToolIcon", () => ({ ProviderToolIcon: () => { icon(); return null; } })); + +let root: ReturnType; +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() }, + 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(), + 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(); + await act(render); + return { props, render }; +} + +function setSearch(value: string) { + const input = container.querySelector('[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('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); + }); +}); diff --git a/ui/src/pages/apps/app-detail/PermissionsPanel.tsx b/ui/src/pages/apps/app-detail/PermissionsPanel.tsx index 5c1f1c47f7f..388cc481f6e 100644 --- a/ui/src/pages/apps/app-detail/PermissionsPanel.tsx +++ b/ui/src/pages/apps/app-detail/PermissionsPanel.tsx @@ -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("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 ( +

    Actions

    @@ -317,6 +318,8 @@ export function ActionsSection({ ) : (
    { - setShowPermissionChangeWarning(true); - onSetPermission(ids, next); - }} + onSetPermission={setPermission} /> { - setShowPermissionChangeWarning(true); - onSetPermission(ids, next); - }} + onSetPermission={setPermission} />
    )}
    +
    ); } @@ -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}
- {actions.map((action) => ( + {visibleActions.map((action) => ( ))}
+ {visibleLimit < actions.length ? ( + + ) : null}
); } @@ -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({
{canConfigure ? ( -
- ) : ( {PERMISSION_OPTIONS.find((option) => option.value === value)?.label} @@ -567,16 +586,16 @@ function ActionRow({
- + /> : null} ); -} +}); function actionPermission( id: string, diff --git a/ui/src/pages/apps/app-detail/SetupPanel.tsx b/ui/src/pages/apps/app-detail/SetupPanel.tsx index 399fe9014db..174966197dc 100644 --- a/ui/src/pages/apps/app-detail/SetupPanel.tsx +++ b/ui/src/pages/apps/app-detail/SetupPanel.tsx @@ -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>(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({
- {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({ ); })}
+ {visibleLimit < count ? ( + + ) : null}
{selectedIds.length} of {count} will be on diff --git a/ui/src/pages/apps/app-detail/constants.ts b/ui/src/pages/apps/app-detail/constants.ts new file mode 100644 index 00000000000..d3cdb76314d --- /dev/null +++ b/ui/src/pages/apps/app-detail/constants.ts @@ -0,0 +1 @@ +export const ACTION_PAGE_SIZE = 50; diff --git a/ui/src/pages/apps/app-detail/useConnectionPermissionSave.ts b/ui/src/pages/apps/app-detail/useConnectionPermissionSave.ts new file mode 100644 index 00000000000..3be56af6c78 --- /dev/null +++ b/ui/src/pages/apps/app-detail/useConnectionPermissionSave.ts @@ -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; + askFirst: Set; + access: AccessDraft; + reviewed?: Set; +} + +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(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 }; +}