diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 829a2f6d481..9c9d4c7e805 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -1692,6 +1692,7 @@ export type { ToolProfileSummary, ToolProfileStatus, ToolProfileWithDetails, + ToolProfileListItem, ToolProfileConfiguration, ToolRateLimitCounter, ToolRateLimitRule, diff --git a/packages/shared/src/types/index.ts b/packages/shared/src/types/index.ts index 90954cf80a1..9f48e26be0a 100644 --- a/packages/shared/src/types/index.ts +++ b/packages/shared/src/types/index.ts @@ -654,6 +654,7 @@ export type { ToolProfileSummary, ToolProfileStatus, ToolProfileWithDetails, + ToolProfileListItem, ToolProfileConfiguration, ToolRateLimitCounter, ToolRateLimitRule, diff --git a/packages/shared/src/types/tool-access.ts b/packages/shared/src/types/tool-access.ts index 6006d7fbd9b..dd1cfc8b5e3 100644 --- a/packages/shared/src/types/tool-access.ts +++ b/packages/shared/src/types/tool-access.ts @@ -863,6 +863,10 @@ export interface ToolProfileWithDetails extends ToolProfile { summary: ToolProfileSummary; } +export type ToolProfileListItem = Pick & { + newToolsPendingCount: number; +}; + export type ToolProfileNewToolReviewDecision = "allow" | "keep_blocked"; export interface ToolProfileNewToolReviewItem { diff --git a/server/src/__tests__/connection-management.integration.test.ts b/server/src/__tests__/connection-management.integration.test.ts index 070ae0c35c7..82a61dc4636 100644 --- a/server/src/__tests__/connection-management.integration.test.ts +++ b/server/src/__tests__/connection-management.integration.test.ts @@ -394,12 +394,22 @@ describe("connection management with production default agents", () => { expect(await f.request("GET", `/tool-profiles/${profileIds[1]}/new-tools`)).toMatchObject({ status: 200, body: { tools: [expect.objectContaining({ connectionName: "Private profile account", description: "Private tool metadata" })] } }); const effectivePath = `/companies/${f.companyId}/tools/profiles/effective/agents/${f.agentId}`; expect((await f.request("GET", effectivePath)).body.allowedTools.some((tool: { toolName: string }) => tool.toolName === "private_tool")).toBe(true); + const profileListPath = `/companies/${f.companyId}/tools/profiles`; + const summaryPath = `${profileListPath}/summary`; + const fullProfiles = await f.request("GET", profileListPath); + expect(fullProfiles.body.profiles.map((profile: { id: string }) => profile.id)).toContain(profileIds[0]); + const summary = await f.request("GET", summaryPath); + expect(summary).toEqual({ status: 200, body: { profiles: fullProfiles.body.profiles.map( + ({ id, name, status, updatedAt, summary, newToolsPendingCount }: Record) => + ({ id, name, status, updatedAt, summary, newToolsPendingCount }), + ) } }); expect(await f.request("PUT", `/tool-connections/${second.body.id}/installs`, { installs: [{ targetType: "agent", targetId: f.agentId }] })).toMatchObject({ status: 200 }); await server.db.update(toolConnections).set({ credentialPolicy: "per_user", createdByUserId: randomUUID() }).where(eq(toolConnections.id, second.body.id)); for (const token of [f.key.token, f.jwt]) { expect(await f.request("GET", `/tool-profiles/${profileIds[1]}/new-tools`, undefined, token)).toMatchObject({ status: 403 }); for (const id of profileIds) expect(await f.request("GET", `/tool-profiles/${id}/new-tools`, undefined, token)).toMatchObject({ status: 403 }); - expect((await f.request("GET", `/companies/${f.companyId}/tools/profiles`, undefined, token)).body.profiles).toEqual([]); + expect((await f.request("GET", profileListPath, undefined, token)).body.profiles).toEqual([]); + expect(await f.request("GET", summaryPath, undefined, token)).toEqual({ status: 200, body: { profiles: [] } }); expect(await f.request("GET", effectivePath, undefined, token)).toMatchObject({ status: 403 }); } for (const [index, entry] of selectors.entries()) expect(await f.request("POST", `/companies/${f.companyId}/tools/profiles`, { profileKey: `private-attempt-${index}`, name: `Private attempt ${index}`, entries: [entry] })).toMatchObject({ status: 403 }); diff --git a/server/src/__tests__/tool-profile-review-service.test.ts b/server/src/__tests__/tool-profile-review-service.test.ts index edfa2a4d33c..fc3fda942bf 100644 --- a/server/src/__tests__/tool-profile-review-service.test.ts +++ b/server/src/__tests__/tool-profile-review-service.test.ts @@ -16,6 +16,10 @@ describeDatabase("pending profile tools through profile and attention services", const now = () => new Date("2026-02-01T00:00:00Z"), service = createToolProfileService(db, now), attention = createToolAppAttention(db, now); const assertCounts = async (expected: number) => { const profiles = await service.listProfiles(f.company.id); + expect(await service.listProfileSummaries(f.company.id)).toEqual( + profiles.map(({ id, name, status, updatedAt, summary, newToolsPendingCount }) => + ({ id, name, status, updatedAt, summary, newToolsPendingCount })), + ); expect(profiles.find(p => p.id === f.profiles[0].id)?.newToolsPendingCount).toBe(expected); expect(profiles.find(p => p.id === f.profiles[1].id)?.newToolsPendingCount).toBe(0); expect((await service.listProfileNewTools(f.profiles[0].id, f.company.id)).pendingCount).toBe(expected); @@ -29,8 +33,42 @@ describeDatabase("pending profile tools through profile and attention services", await assertCounts(2); await db.update(toolProfiles).set({ newToolsReviewedAt: now() }).where(eq(toolProfiles.id, f.profiles[0].id)); await assertCounts(0); + await db.update(toolProfiles).set({ status: "archived" }).where(eq(toolProfiles.id, f.profiles[0].id)); + await assertCounts(0); const foreign = await createProfileProjectionFixture(db, { profiles: 2, tools: 5, rules: 2 }); expect((await service.listProfiles(foreign.company.id)).map(p => p.companyId)).toEqual([foreign.company.id, foreign.company.id]); + expect((await service.listProfileSummaries(foreign.company.id)).map(p => p.id).sort()).toEqual(foreign.profiles.map(p => p.id).sort()); expect((await db.select().from(toolProfileEntries).where(eq(toolProfileEntries.id, exclude.id)))[0].effect).toBe("exclude"); }); + it("keeps independent effects, null keys, and duplicate and unknown selectors across shared groups", async () => { + const f = await createProfileProjectionFixture(db, { profiles: 6, tools: 8, rules: 0 }); + const service = createToolProfileService(db, () => new Date()); + const [application, connection, catalogEntry, toolName, riskLevel] = f.profiles; + const [first, second] = f.catalog; + await db.update(toolCatalogEntries).set({ applicationId: null }).where(eq(toolCatalogEntries.id, first.id)); + type Entry = typeof toolProfileEntries.$inferInsert; + const add = (profileId: string, selector: Pick & Partial): Entry => + ({ companyId: f.company.id, profileId, effect: "include", ...selector }); + const includeName = { selectorType: "tool_name", toolName: second.toolName } as const; + await db.insert(toolProfileEntries).values([ + add(application.id, { selectorType: "application", applicationId: f.application.id }), + add(application.id, { selectorType: "application", applicationId: null }), + add(connection.id, { selectorType: "connection", connectionId: f.connection.id }), + add(connection.id, { selectorType: "catalog_entry", effect: "exclude", catalogEntryId: first.id }), + add(catalogEntry.id, { selectorType: "catalog_entry", catalogEntryId: first.id, applicationId: f.application.id }), + add(catalogEntry.id, { selectorType: "catalog_entry", catalogEntryId: first.id }), + add(catalogEntry.id, { selectorType: "legacy_unknown" as Entry["selectorType"], catalogEntryId: second.id }), + add(toolName.id, includeName), + add(toolName.id, includeName), + add(riskLevel.id, includeName), + add(riskLevel.id, { ...includeName, effect: "exclude" }), + add(riskLevel.id, { selectorType: "risk_level", riskLevel: "read" }), + ]); + const detail = await service.listProfiles(f.company.id); + const summaries = await service.listProfileSummaries(f.company.id); + expect(summaries).toEqual(detail.map(({ id, name, status, updatedAt, summary, newToolsPendingCount }) => + ({ id, name, status, updatedAt, summary, newToolsPendingCount }))); + const counts = new Map(summaries.map(({ id, summary }) => [id, summary.allowedToolCount])); + expect(f.profiles.map(({ id }) => counts.get(id))).toEqual([8, 7, 1, 1, 7, 0]); + }); }); diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index 46a904aba4e..aac0d81e584 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -13041,6 +13041,15 @@ registerCurrentRoute({ summary: "List tool access profiles with entries and bindings", }); +registerCurrentRoute({ + "x-paperclip-transport": "rest", + "x-paperclip-connection-management": "connections:profiles", + method: "get", + path: "/api/companies/{companyId}/tools/profiles/summary", + tags: ["tool-access"], + summary: "List tool access profile summaries", +}); + registerCurrentRoute({ "x-paperclip-transport": "rest", "x-paperclip-connection-management": "connections:profiles", diff --git a/server/src/routes/tool-access.ts b/server/src/routes/tool-access.ts index 2d8c9226772..4aed848a535 100644 --- a/server/src/routes/tool-access.ts +++ b/server/src/routes/tool-access.ts @@ -2668,6 +2668,14 @@ function connectorEnrollmentPrincipal(req: Request): string { res.json({ profiles: await filterConnectionManagementRows(db, req, "connections:profiles", await svc.listProfiles(companyId), row => ({ profileId: row.id })) }); }); + router.get("/companies/:companyId/tools/profiles/summary", managementGuard("connections:profiles", "GET /companies/:companyId/tools/profiles/summary", { personal: true }), async (req, res) => { + assertBoardOrAgent(req); + const companyId = req.params.companyId as string; + assertCompanyAccess(req, companyId); + const profiles = await svc.listProfileSummaries(companyId); + res.json({ profiles: await filterConnectionManagementRows(db, req, "connections:profiles", profiles, row => ({ profileId: row.id })) }); + }); + router.get("/tool-connections/:connectionId/profile-configuration", managementGuard("connections:profiles", "GET /tool-connections/:connectionId/profile-configuration", { personal: true }), async (req, res) => { assertBoardOrAgent(req); const existing = await getAccessibleResource(req, res, svc.getConnection(req.params.connectionId as string), "Tool connection not found"); diff --git a/server/src/services/tool-access/profiles/projection.ts b/server/src/services/tool-access/profiles/projection.ts index 877c2606fd4..05b7c5b35c8 100644 --- a/server/src/services/tool-access/profiles/projection.ts +++ b/server/src/services/tool-access/profiles/projection.ts @@ -83,6 +83,18 @@ export type ProfileConnection = Pick; +export const profileSummaryEntryColumns = { + catalogEntryId: toolProfileEntries.catalogEntryId, + connectionId: toolProfileEntries.connectionId, + applicationId: toolProfileEntries.applicationId, + selectorType: toolProfileEntries.selectorType, + effect: toolProfileEntries.effect, + toolName: toolProfileEntries.toolName, + riskLevel: toolProfileEntries.riskLevel, +}; + +type ProfileSummaryEntry = ProfileEntryMatch & Pick; + export type ProfileCatalogMatch = Pick; @@ -122,9 +134,9 @@ export function profileCatalogMatcher(entries: ProfileEntryMatch[]) { } export function summarizeProfile(input: { - profile: typeof toolProfiles.$inferSelect; - entries: Array; - bindings: Array; + profile: Pick; + entries: ProfileSummaryEntry[]; + bindings: Pick[]; catalog: ProfileCatalogEntry[]; agentIds: string[]; }): ToolProfileSummary { @@ -180,7 +192,7 @@ export function summarizeProfile(input: { } export function profileCoversCatalogScope(input: { - entry: typeof toolProfileEntries.$inferSelect; + entry: ProfileSummaryEntry; catalogEntry: ProfileCatalogEntry; catalogById: Map; }): boolean { @@ -204,8 +216,8 @@ export function profileCoversCatalogScope(input: { } export function pendingNewToolsForProfile(input: { - profile: typeof toolProfiles.$inferSelect; - entries: Array; + profile: Pick; + entries: ProfileSummaryEntry[]; catalog: ProfileCatalogEntry[]; applicationsById?: Map; connectionsById?: Map; diff --git a/server/src/services/tool-access/profiles/service.ts b/server/src/services/tool-access/profiles/service.ts index d9622039d39..9a70f008f14 100644 --- a/server/src/services/tool-access/profiles/service.ts +++ b/server/src/services/tool-access/profiles/service.ts @@ -4,15 +4,25 @@ import { createConnectionProfileConfigurationReader } from "./connection-configu import { connectionActorUserId } from "../actor.js"; import { assertProfileEntryInputs } from "../../tool-profile-entry-validation.js"; import { randomUUID } from "node:crypto"; -import { and, asc, desc, eq, inArray } from "drizzle-orm"; +import { and, asc, desc, eq, inArray, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { agents, issues, projects, routines, toolApplications, toolCatalogEntries, toolConnections, toolMcpGateways, toolProfileBindings, toolProfileEntries, toolProfiles } from "@paperclipai/db"; -import type { CreateToolProfileBindingForProfile, CreateToolProfileEntryForProfile, CreateToolProfileWithEntries, DeleteToolProfile, DuplicateToolProfile, ToolProfile, ToolProfileBinding, ToolProfileEntry, ToolProfileNewToolReviewItem, ToolProfileNewToolsReview, ToolProfileNewToolsReviewResult, ToolProfileSummary, ToolProfileWithDetails, ReviewToolProfileNewTools, UpdateToolProfileEntry, UpdateToolProfileWithEntries, UnbindToolProfileBinding } from "@paperclipai/shared"; +import type { CreateToolProfileBindingForProfile, CreateToolProfileEntryForProfile, CreateToolProfileWithEntries, DeleteToolProfile, DuplicateToolProfile, ToolProfile, ToolProfileBinding, ToolProfileEntry, ToolProfileListItem, ToolProfileNewToolReviewItem, ToolProfileNewToolsReview, ToolProfileNewToolsReviewResult, ToolProfileSummary, ToolProfileWithDetails, ReviewToolProfileNewTools, UpdateToolProfileEntry, UpdateToolProfileWithEntries, UnbindToolProfileBinding } from "@paperclipai/shared"; import { badRequest, conflict, notFound, unprocessable } from "../../../errors.js"; import type { ActorInfo, ToolAccessMutationDb } from "../types.js"; import { lockProfileEntryReferences, lockToolAssignmentAgents } from "../assignment-locks.js"; import { normalizeKey } from "../identifiers.js"; -import { toProfile, toProfileEntry, toProfileBinding, profileCatalogColumns, profileReviewCatalogColumns, pendingNewToolsForProfile, buildProfileDetails } from "./projection.js"; +import { toProfile, toProfileEntry, toProfileBinding, profileCatalogColumns, profileReviewCatalogColumns, pendingNewToolsForProfile, buildProfileDetails, profileSummaryEntryColumns, summarizeProfile } from "./projection.js"; + +function groupByProfile(rows: T[]) { + const groups = new Map(); + for (const row of rows) { + const group = groups.get(row.profileId); + if (group) group.push(row); + else groups.set(row.profileId, [row]); + } + return groups; +} export function createToolProfileService(db: Db, now: () => Date) { async function getProfileRow(profileId: string, companyId?: string, dbClient: ToolAccessMutationDb = db) { @@ -364,6 +374,59 @@ export function createToolProfileService(db: Db, now: () => Date) { return { listConnectionProfileConfiguration: createConnectionProfileConfigurationReader(db), + async listProfileSummaries(companyId: string): Promise { + const profiles = await db.select({ + id: toolProfiles.id, + name: toolProfiles.name, + status: toolProfiles.status, + updatedAt: toolProfiles.updatedAt, + companyId: toolProfiles.companyId, + defaultAction: toolProfiles.defaultAction, + createdAt: toolProfiles.createdAt, + newToolsReviewedAt: toolProfiles.newToolsReviewedAt, + }).from(toolProfiles).where(eq(toolProfiles.companyId, companyId)).orderBy(desc(toolProfiles.updatedAt)); + if (!profiles.length) return []; + const ids = profiles.map(profile => profile.id); + const [entryGroups, bindings, catalog, companyAgents] = await Promise.all([ + db.select({ + ...profileSummaryEntryColumns, + profiles: sql`json_agg(summary_profiles.ordinal)`, + }).from(toolProfileEntries) + .innerJoin(sql`unnest(${sql.param(ids)}::uuid[]) with ordinality as summary_profiles(id, ordinal)`, + sql`summary_profiles.id = ${toolProfileEntries.profileId}`) + .where(eq(toolProfileEntries.companyId, companyId)) + .groupBy(...Object.values(profileSummaryEntryColumns)), + db.select({ + profileId: toolProfileBindings.profileId, + targetType: toolProfileBindings.targetType, + targetId: toolProfileBindings.targetId, + }).from(toolProfileBindings).where(and( + eq(toolProfileBindings.companyId, companyId), inArray(toolProfileBindings.profileId, ids), + )), + db.select(profileCatalogColumns).from(toolCatalogEntries).where(and( + eq(toolCatalogEntries.companyId, companyId), eq(toolCatalogEntries.status, "active"), + )), + db.select({ id: agents.id }).from(agents).where(eq(agents.companyId, companyId)), + ]); + type Entry = Omit<(typeof entryGroups)[number], "profiles">; + const entriesByProfile = ids.map((): Entry[] => []); + for (const { profiles: ordinals, ...entry } of entryGroups) { + for (const ordinal of ordinals) entriesByProfile[ordinal - 1].push(entry); + } + const bindingsByProfile = groupByProfile(bindings); + const agentIds = companyAgents.map(agent => agent.id); + return profiles.map((profile, index) => { + const { id, name, status, updatedAt } = profile; + const entries = entriesByProfile[index]; + const bindings = bindingsByProfile.get(id) ?? []; + return { + id, name, status, updatedAt, + newToolsPendingCount: pendingNewToolsForProfile({ profile, entries, catalog }).length, + summary: summarizeProfile({ profile, entries, bindings, catalog, agentIds }), + }; + }); + }, + listProfiles: async ( companyId: string, ): Promise => { @@ -427,24 +490,8 @@ export function createToolProfileService(db: Db, now: () => Date) { .from(toolConnections) .where(eq(toolConnections.companyId, companyId)), ]); - const entriesByProfile = new Map< - string, - Array - >(); - const bindingsByProfile = new Map< - string, - Array - >(); - for (const entry of entries) { - const list = entriesByProfile.get(entry.profileId) ?? []; - list.push(entry); - entriesByProfile.set(entry.profileId, list); - } - for (const binding of bindings) { - const list = bindingsByProfile.get(binding.profileId) ?? []; - list.push(binding); - bindingsByProfile.set(binding.profileId, list); - } + const entriesByProfile = groupByProfile(entries); + const bindingsByProfile = groupByProfile(bindings); const agentIds = companyAgents.map((agent) => agent.id); const applicationsById = new Map( applications.map((application) => [application.id, application]), diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 939916854a3..bcdc78a96f7 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -272,7 +272,7 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "829a2f6d4816ee1844c3d5334937b22cac08457c", + "packages/shared/src/index.ts": "9c9d4c7e805c2d701a3367ce3c2fe9863210f7ea", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", @@ -429,7 +429,7 @@ "packages/shared/src/types/inbox-agent-policy.ts": "cb9d41d9681e80b834889268ad96015a39df92f6", "packages/shared/src/types/inbox-dismissal.ts": "58fb7013847396ac9971eb5799dd0bf0486e0371", "packages/shared/src/types/inbox-mine.ts": "1d302b531d34842189704abd2f75f8743d09490d", - "packages/shared/src/types/index.ts": "90954cf80a138fb0e2f79468bcc9c405b1cead93", + "packages/shared/src/types/index.ts": "9f48e26be0a09a76de5bf5327f06e5108f77ebc9", "packages/shared/src/types/instance.ts": "77b0052be0f64a5531c5ebf0fd078c9854084479", "packages/shared/src/types/issue-tree-control.ts": "75489fffd491b8350b05caf57d7796419797d9df", "packages/shared/src/types/issue.ts": "849b293fb2263ed41d9a0a74276534ad5c2ff7b8", @@ -453,7 +453,7 @@ "packages/shared/src/types/tailscale.ts": "d02a917945d7779009a2dea4c4b535e9478e0680", "packages/shared/src/types/task-workspace.ts": "a23afa13d2cb58dc2eb72692ed28c16ed6fb84fb", "packages/shared/src/types/teams-catalog.ts": "632fe75f8e5a4cfc455843c2a1a2daff28a022be", - "packages/shared/src/types/tool-access.ts": "6006d7fbd9b70f69a2e4d734a384638dbdf053df", + "packages/shared/src/types/tool-access.ts": "dd1cfc8b5e36f3ec572890022625402fe3fb637e", "packages/shared/src/types/user-profile.ts": "1ac26e033a79fab21dc267fd983959814c8b680f", "packages/shared/src/types/voice-sessions.ts": "95e3b62cdd51f62290e68536728ddd7297bc0459", "packages/shared/src/types/work-product.ts": "26f9129f606a207ce7a218ccef40f96747283086", diff --git a/ui/src/api/tools.ts b/ui/src/api/tools.ts index 38ec7939404..eed67960c40 100644 --- a/ui/src/api/tools.ts +++ b/ui/src/api/tools.ts @@ -38,6 +38,7 @@ import type { ToolProfileEntrySelectorType, ToolProfileStatus, ToolProfileWithDetails, + ToolProfileListItem, ToolProfileConfiguration, ToolProfileNewToolReviewDecision, ToolProfileNewToolsReview, @@ -525,6 +526,8 @@ export const toolsApi = { api.get<{ profiles: ToolProfileConfiguration[] }>(`/tool-connections/${connectionId}/profile-configuration`, options), listProfiles: (companyId: string) => api.get(`/companies/${companyId}/tools/profiles`), + listProfileSummaries: (companyId: string) => + api.get<{ profiles: ToolProfileListItem[] }>(`/companies/${companyId}/tools/profiles/summary`), getProfileNewTools: (profileId: string) => api.get(`/tool-profiles/${profileId}/new-tools`), reviewProfileNewTools: (profileId: string, input: ReviewNewToolsInput) => diff --git a/ui/src/pages/tools/profiles/ProfileActionDialog.tsx b/ui/src/pages/tools/profiles/ProfileActionDialog.tsx index 2142332b62c..b20bfa7cbcb 100644 --- a/ui/src/pages/tools/profiles/ProfileActionDialog.tsx +++ b/ui/src/pages/tools/profiles/ProfileActionDialog.tsx @@ -1,5 +1,5 @@ import { AlertTriangle } from "lucide-react"; -import type { ToolProfileWithDetails } from "@paperclipai/shared"; +import type { ToolProfileListItem } from "@paperclipai/shared"; import { Button } from "@/components/ui/button"; import { Dialog, @@ -22,7 +22,7 @@ export function ProfileActionDialog({ onDelete, }: { kind: ProfileActionDialogKind | null; - profile: ToolProfileWithDetails | null; + profile: Pick | null; pending: boolean; onClose: () => void; onArchive: () => void; diff --git a/ui/src/pages/tools/profiles/ProfilesIndex.test.tsx b/ui/src/pages/tools/profiles/ProfilesIndex.test.tsx index be7d0810968..932691b1a3e 100644 --- a/ui/src/pages/tools/profiles/ProfilesIndex.test.tsx +++ b/ui/src/pages/tools/profiles/ProfilesIndex.test.tsx @@ -52,7 +52,7 @@ vi.mock("@/components/ui/dropdown-menu", () => ({ DropdownMenuSeparator: () => createElement("hr"), })); -vi.mock("./useProfilesData", () => ({ useProfilesData: () => profilesData.current })); +vi.mock("./useProfilesData", () => ({ useProfileIndexData: () => profilesData.current })); import { ApiError } from "@/api/client"; import { ProfilesIndex } from "./ProfilesIndex"; diff --git a/ui/src/pages/tools/profiles/ProfilesIndex.tsx b/ui/src/pages/tools/profiles/ProfilesIndex.tsx index 25aedf11812..e13a172baf5 100644 --- a/ui/src/pages/tools/profiles/ProfilesIndex.tsx +++ b/ui/src/pages/tools/profiles/ProfilesIndex.tsx @@ -1,7 +1,7 @@ import { useEffect, useMemo, useState } from "react"; import { useMutation, useQueryClient } from "@tanstack/react-query"; import { ArchiveRestore, MoreHorizontal, Plus, ShieldCheck, Users } from "lucide-react"; -import type { ToolProfileWithDetails } from "@paperclipai/shared"; +import type { ToolProfileListItem } from "@paperclipai/shared"; import { useNavigate } from "@/lib/router"; import { toolsApi } from "@/api/tools"; import { queryKeys } from "@/lib/queryKeys"; @@ -28,7 +28,7 @@ import { EffectiveAgentPanel } from "../ProfilesTab"; import { LoadingState, RelativeTime, ToolsPageHeader } from "../shared"; import { ProfileActionDialog, type ProfileActionDialogKind } from "./ProfileActionDialog"; import { TEMPLATES, type TemplateKey } from "./profile-model"; -import { useProfilesData } from "./useProfilesData"; +import { useProfileIndexData } from "./useProfilesData"; import { allowsLabel, assignedLabel, isDraft, STATUS_LABEL } from "./profile-summary"; /** The wizard route for a fresh profile, optionally seeded with a template. */ @@ -38,7 +38,7 @@ function newProfileHref(template?: TemplateKey): string { : "/apps/advanced/profiles/new"; } -function statusVariant(status: ToolProfileWithDetails["status"]): "default" | "secondary" | "outline" { +function statusVariant(status: ToolProfileListItem["status"]): "default" | "secondary" | "outline" { if (status === "active") return "default"; if (status === "draft") return "secondary"; return "outline"; @@ -56,13 +56,13 @@ export function ProfilesIndex({ const navigate = useNavigate(); const queryClient = useQueryClient(); const { pushToast } = useToast(); - const { profiles, agents } = useProfilesData(companyId); + const { profiles, agents } = useProfileIndexData(companyId); const profilesView = useQueryView(profiles); const [resolverOpen, setResolverOpen] = useState(Boolean(initialResolverOpen)); const [statusFilter, setStatusFilter] = useState<"active" | "archived">(initialStatusFilter ?? "active"); const [actionDialog, setActionDialog] = useState<{ kind: ProfileActionDialogKind; - profile: ToolProfileWithDetails; + profile: ToolProfileListItem; } | null>(null); useEffect(() => { @@ -82,7 +82,7 @@ export function ProfilesIndex({ const errorBody = (error: unknown) => String((error as Error)?.message ?? error); const duplicate = useMutation({ - mutationFn: (profile: ToolProfileWithDetails) => + mutationFn: (profile: ToolProfileListItem) => toolsApi.duplicateProfile(profile.id, { name: `${profile.name} (copy)` }), onSuccess: () => { pushToast({ title: "Profile duplicated", body: "The copy is not assigned to anyone yet.", tone: "success" }); @@ -93,7 +93,7 @@ export function ProfilesIndex({ }); const archive = useMutation({ - mutationFn: (profile: ToolProfileWithDetails) => + mutationFn: (profile: ToolProfileListItem) => toolsApi.updateProfile(profile.id, { status: "archived" }), onSuccess: () => { pushToast({ title: "Profile archived", tone: "success" }); @@ -103,7 +103,7 @@ export function ProfilesIndex({ }); const restore = useMutation({ - mutationFn: (profile: ToolProfileWithDetails) => + mutationFn: (profile: ToolProfileListItem) => toolsApi.updateProfile(profile.id, { status: "active" }), onSuccess: () => { pushToast({ title: "Profile restored", tone: "success" }); @@ -113,7 +113,7 @@ export function ProfilesIndex({ }); const remove = useMutation({ - mutationFn: (profile: ToolProfileWithDetails) => toolsApi.deleteProfile(profile.id), + mutationFn: (profile: ToolProfileListItem) => toolsApi.deleteProfile(profile.id), onSuccess: () => { pushToast({ title: "Profile deleted", tone: "success" }); invalidate(); diff --git a/ui/src/pages/tools/profiles/useProfilesData.test.ts b/ui/src/pages/tools/profiles/useProfilesData.test.ts new file mode 100644 index 00000000000..65275be3626 --- /dev/null +++ b/ui/src/pages/tools/profiles/useProfilesData.test.ts @@ -0,0 +1,48 @@ +import { expect, it, vi } from "vitest"; +import { QueryClient, useQuery, useQueries } from "@tanstack/react-query"; +import { agentsApi } from "@/api/agents"; +import { toolsApi } from "@/api/tools"; +import { queryKeys } from "@/lib/queryKeys"; +import { useProfileIndexData } from "./useProfilesData"; + +vi.mock("@tanstack/react-query", async (importOriginal) => ({ + ...await importOriginal(), + useQueries: vi.fn(), + useQuery: vi.fn(), +})); +vi.mock("@/api/agents", () => ({ agentsApi: { list: vi.fn() } })); +vi.mock("@/api/tools", () => ({ toolsApi: { listProfileSummaries: vi.fn() } })); + +it("loads the profile summaries and resolver agents without the editor's catalog queries", async () => { + useProfileIndexData("company"); + expect(useQueries).not.toHaveBeenCalled(); + const queries = vi.mocked(useQuery).mock.calls.map(([options]) => options); + expect(queries.map(query => query.queryKey)).toEqual([ + [...queryKeys.tools.profiles("company"), "summary"], + queryKeys.agents.list("company"), + ]); + for (const query of queries) { + const run = query.queryFn; + if (typeof run === "function") { + await run({} as Parameters[0]); + } + } + expect(toolsApi.listProfileSummaries).toHaveBeenCalledExactlyOnceWith("company"); + expect(agentsApi.list).toHaveBeenCalledExactlyOnceWith("company"); +}); + + +it("invalidates the index summary with the existing company profile key", async () => { + vi.mocked(useQuery).mockClear(); + useProfileIndexData("company"); + const summaryKey = vi.mocked(useQuery).mock.calls[0][0].queryKey; + const profilesKey = queryKeys.tools.profiles("company"); + const client = new QueryClient(); + client.setQueryData(summaryKey, { profiles: [] }); + client.setQueryData(profilesKey, { profiles: [] }); + + await client.invalidateQueries({ queryKey: profilesKey }); + + expect(client.getQueryState(summaryKey)?.isInvalidated).toBe(true); + expect(client.getQueryState(profilesKey)?.isInvalidated).toBe(true); +}); diff --git a/ui/src/pages/tools/profiles/useProfilesData.ts b/ui/src/pages/tools/profiles/useProfilesData.ts index 6b201519370..d477dbd48ec 100644 --- a/ui/src/pages/tools/profiles/useProfilesData.ts +++ b/ui/src/pages/tools/profiles/useProfilesData.ts @@ -7,8 +7,20 @@ import { queryKeys } from "@/lib/queryKeys"; import { groupCatalogByApp } from "./profile-model"; import { companyProjectsQuery } from "@/lib/company-projects-query"; +export function useProfileIndexData(companyId: string) { + const profiles = useQuery({ + queryKey: [...queryKeys.tools.profiles(companyId), "summary"], + queryFn: () => toolsApi.listProfileSummaries(companyId), + }); + const agents = useQuery({ + queryKey: queryKeys.agents.list(companyId), + queryFn: () => agentsApi.list(companyId), + }); + return { profiles, agents }; +} + /** - * Shared data layer for the access-profiles index and wizard. Assembles the + * Shared data layer for profile detail and the wizard. Assembles the * company-wide catalog (there is no aggregate endpoint, so we fan out per * connection) and the lookup maps both surfaces need. */