The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
feat(apps): add connection intent setup experience (#12347)
Dottac90d90477902
diff --git a/tests/e2e/app-not-connected.spec.ts b/tests/e2e/app-not-connected.spec.tsindex 9eaa9be013..60328294c5 100644--- a/tests/e2e/app-not-connected.spec.ts+++ b/tests/e2e/app-not-connected.spec.ts@@ -123,7 +123,9 @@ test.describe.serial("not-connected app page", () => {await page.screenshot({ path: `${SCREENSHOT_DIR}/apps-nav-w6-02-reconnect-prefilled.png`, fullPage: true });await page.getByRole("button", { name: "Check link" }).click();- await expect(page.getByRole("heading", { name: "Bla is ready." })).toBeVisible({ timeout: 20_000 });+ // Reconnect retains the previous identity and application, so the generic+ // check can commit the restored connection transactionally.+ await expect(page.getByRole("heading", { name: "Bla is ready." })).toBeVisible({ timeout: 30_000 });const apps = await request.get(`/api/companies/${seed.companyId}/tools/applications`);const appsBody = await apps.json();@@ -180,6 +182,7 @@ test.describe.serial("not-connected app page", () => {await page.goto(`/${seed.prefix}/apps/app/${secondBody.application.id}/advanced`);await expect(page.getByText("Danger zone")).toBeVisible({ timeout: 30_000 });+ await page.getByText("Danger zone", { exact: true }).click();await page.getByRole("button", { name: "Remove app", exact: true }).click();await page.screenshot({ path: `${SCREENSHOT_DIR}/apps-nav-w6-04-app-page-danger.png`, fullPage: true });await page.getByRole("button", { name: "Yes, remove it" }).click();diff --git a/tests/e2e/application-delete-screenshot.spec.ts b/tests/e2e/application-delete-screenshot.spec.tsindex 1bdb468362..cfb15c7acb 100644--- a/tests/e2e/application-delete-screenshot.spec.ts+++ b/tests/e2e/application-delete-screenshot.spec.ts@@ -23,7 +23,7 @@ test("captures the current app removal confirmations", async ({ page }) => {await page.goto(`/${prefix}/apps/app/${application.id}/advanced`);await expect(page.getByRole("heading", { name: "Demo Notes" })).toBeVisible({ timeout: 15_000 });- await expect(page.getByText("Danger zone")).toBeVisible();+ await page.getByRole("button", { name: "Danger zone" }).click();await page.getByRole("button", { name: "Remove app", exact: true }).click();await expect(page.getByRole("button", { name: "Yes, remove it" })).toBeVisible();await page.screenshot({ path: "test-results/pap-10817-delete-dialog.png", fullPage: true });@@ -41,6 +41,7 @@ test("captures the current app removal confirmations", async ({ page }) => {await page.goto(`/${prefix}/apps/${connection.id}/advanced`);await expect(page.getByRole("heading", { name: "Primary connection" })).toBeVisible({ timeout: 15_000 });+ await page.getByRole("button", { name: "Danger zone" }).click();await page.getByRole("button", { name: "Remove app", exact: true }).click();await expect(page.getByRole("button", { name: "Yes, remove it" })).toBeVisible();await page.screenshot({ path: "test-results/pap-10817-delete-dialog-guarded.png", fullPage: true });diff --git a/tests/e2e/applications-crud.spec.ts b/tests/e2e/applications-crud.spec.tsindex db89eb6239..75a729a757 100644--- a/tests/e2e/applications-crud.spec.ts+++ b/tests/e2e/applications-crud.spec.ts@@ -130,12 +130,8 @@ test.describe.serial("applications lifecycle", () => {await page.goto(`/${seed.prefix}/apps/${connection.id}/setup`);await expect(page.getByRole("heading", { name: appName })).toBeVisible({ timeout: 30_000 });- await expect(page.getByRole("heading", { name: "Agents can use this app" })).toBeVisible();-- await page.getByRole("switch", { name: "Pause this app" }).click();- await expect(page.getByRole("heading", { name: "This app is paused" })).toBeVisible({ timeout: 15_000 });- await page.getByRole("switch", { name: "Resume this app" }).click();- await expect(page.getByRole("heading", { name: "Agents can use this app" })).toBeVisible({ timeout: 15_000 });+ await expect(page.getByRole("heading", { name: "Account" })).toBeVisible();+ await expect(page.getByText("Anyone in your company can use this connection")).toBeVisible();await page.getByRole("button", { name: "Rename app" }).click();await page.getByLabel("App name").fill(renamed);@@ -143,8 +139,15 @@ test.describe.serial("applications lifecycle", () => {await expect(page.getByRole("heading", { name: renamed })).toBeVisible({ timeout: 15_000 });await page.screenshot({ path: `${SCREENSHOT_DIR}/applications-crud-current-detail.png`, fullPage: true });- await page.goto(`/${seed.prefix}/apps/${connection.id}/advanced`);- await expect(page.getByText("Danger zone")).toBeVisible({ timeout: 15_000 });+ await page.getByRole("button", { name: "Danger zone" }).click();+ const pauseConnection = page.getByRole("switch", { name: "Pause connection" });+ await pauseConnection.click();+ await expect(pauseConnection).toBeChecked({ timeout: 15_000 });+ await expect(page.getByText("App paused").first()).toBeVisible();+ await pauseConnection.click();+ await expect(pauseConnection).not.toBeChecked({ timeout: 15_000 });+ await expect(page.getByText("App resumed").first()).toBeVisible();+await page.getByRole("button", { name: "Remove app", exact: true }).click();await expect(page.getByRole("button", { name: "Yes, remove it" })).toBeVisible();await page.screenshot({ path: `${SCREENSHOT_DIR}/applications-crud-current-remove-connected.png`, fullPage: true });@@ -161,7 +164,7 @@ test.describe.serial("applications lifecycle", () => {await page.goto(`/${seed.prefix}/apps/app/${cleanApp.id}/advanced`);await expect(page.getByRole("heading", { name: cleanAppName })).toBeVisible({ timeout: 30_000 });- await expect(page.getByText("Danger zone")).toBeVisible();+ await page.getByRole("button", { name: "Danger zone" }).click();await page.getByRole("button", { name: "Remove app", exact: true }).click();await page.screenshot({ path: `${SCREENSHOT_DIR}/applications-crud-current-remove-not-connected.png`, fullPage: true });await page.getByRole("button", { name: "Yes, remove it" }).click();diff --git a/tests/e2e/apps-dark-mode-shots.spec.ts b/tests/e2e/apps-dark-mode-shots.spec.tsindex c8eb1199ef..c7afab7f1f 100644--- a/tests/e2e/apps-dark-mode-shots.spec.ts+++ b/tests/e2e/apps-dark-mode-shots.spec.ts@@ -157,12 +157,12 @@ test.describe.serial("dark-mode Apps surfaces", () => {await page.screenshot({ path: `${SCREENSHOT_DIR}/apps-nav-04-advanced-paste-dark.png`, fullPage: true });});- test("developer tabs share the merged Apps sidebar", async ({ page }) => {+ test("developer routes share the merged Apps sidebar without hidden tabs", async ({ page }) => {await forceDark(page);await page.goto(`/${seed.prefix}/apps/advanced/profiles`);await expect(page.getByRole("heading", { name: "Access profiles" })).toBeVisible({ timeout: 30_000 });- await expect(page.locator('a[href$="/apps/advanced/gateways"]', { hasText: "Gateways" })).toBeVisible();- await expect(page.locator('a[href$="/apps/advanced/profiles"]', { hasText: "Profiles" })).toBeVisible();+ await expect(page.locator('a[href$="/apps/advanced/gateways"]', { hasText: "Gateways" })).toHaveCount(0);+ await expect(page.locator('a[href$="/apps/advanced/profiles"]', { hasText: "Profiles" })).toHaveCount(0);await expect(page.locator('a[href$="/apps/advanced/audit"]', { hasText: "Activity" })).toBeVisible();await expect(page.getByRole("link", { name: "Applications", exact: true })).toHaveCount(0);// Apps section lives in the same sidebar now.@@ -180,6 +180,7 @@ test.describe.serial("dark-mode Apps surfaces", () => {await page.getByLabel("App name").fill("QA Renamed App");await page.getByRole("button", { name: "Save", exact: true }).click();await expect(page.getByRole("heading", { name: "QA Renamed App" })).toBeVisible({ timeout: 20_000 });+ await page.getByText("Danger zone", { exact: true }).click();await page.getByRole("button", { name: "Remove app", exact: true }).click();await page.screenshot({ path: `${SCREENSHOT_DIR}/apps-nav-06-danger-zone-dark.png`, fullPage: true });await page.getByRole("button", { name: "Yes, remove it" }).click();diff --git a/tests/e2e/apps-prosumer-mcp-flow.spec.ts b/tests/e2e/apps-prosumer-mcp-flow.spec.tsindex ea663c476b..ea8335da80 100644--- a/tests/e2e/apps-prosumer-mcp-flow.spec.ts+++ b/tests/e2e/apps-prosumer-mcp-flow.spec.ts@@ -166,9 +166,9 @@ test.describe.serial("prosumer MCP flow prosumer MCP flow", () => {// Submit (button label is "Check link").await page.getByRole("button", { name: /Check link/i }).click();- // Link-mode setup uses the safe organization/any-agent defaults, enables- // discovered actions, and applies risk-based ask-first defaults in one- // commit. Classification remains covered by the server suite.+ // The Access choice was captured before credentials. A successful generic+ // probe now commits discovered actions and risk defaults transactionally,+ // so the key check lands directly on success.await expect(page.getByRole("heading", { name: /is ready\.$/i })).toBeVisible({ timeout: 30_000 });await page.screenshot({ path: `${SCREENSHOT_DIR}/prosumer-mcp-05-success.png`, fullPage: true });diff --git a/tests/e2e/connection-intents.spec.ts b/tests/e2e/connection-intents.spec.tsnew file mode 100644index 0000000000..65d12deec0--- /dev/null+++ b/tests/e2e/connection-intents.spec.ts@@ -0,0 +1,373 @@+import { expect, test, type APIRequestContext } from "@playwright/test";+import { createServer, type Server } from "node:http";+import { listenOnFetchAllowedPort } from "./fetch-allowed-port";++type Json = Record<string, unknown>;+type Seed = { companyId: string; prefix: string };+type Agent = { id: string; name: string };++async function json<T = Json>(+ response: Awaited<ReturnType<APIRequestContext["get"]>>,+): Promise<T> {+ expect(+ response.ok(),+ `${response.url()} failed ${response.status()}: ${await response.text()}`,+ ).toBe(true);+ return (await response.json()) as T;+}++async function newCompany(request: APIRequestContext): Promise<Seed> {+ const company = await json<{ id: string; issuePrefix: string }>(+ await request.post("/api/companies", {+ data: { name: `Connection intent E2E ${Date.now()}` },+ }),+ );+ await json(+ await request.patch("/api/instance/settings/experimental", {+ data: { enableApps: true },+ }),+ );+ return { companyId: company.id, prefix: company.issuePrefix };+}++async function createAgent(+ request: APIRequestContext,+ companyId: string,+ name: string,+): Promise<Agent> {+ return await json<Agent>(+ await request.post(`/api/companies/${companyId}/agents`, {+ data: {+ name,+ role: "qa",+ title: "Connection intent fixture agent",+ capabilities: "Exercises deterministic connection intent wiring.",+ adapterType: "process",+ adapterConfig: {+ command: process.execPath,+ args: ["--input-type=module", "-e", "process.exit(0)"],+ },+ },+ }),+ );+}++async function startFakeProvider() {+ const captures: Array<{ method: string; toolName: string | null }> = [];+ const server: Server = createServer(async (req, res) => {+ const chunks: Buffer[] = [];+ for await (const chunk of req) chunks.push(chunk as Buffer);+ const payload = JSON.parse(+ Buffer.concat(chunks).toString("utf8") || "{}",+ ) as {+ id?: string | number;+ method?: string;+ params?: { name?: string };+ };+ captures.push({+ method: String(payload.method ?? "<unknown>"),+ toolName: payload.params?.name ?? null,+ });+ res.writeHead(200, { "Content-Type": "application/json" });+ if (payload.method === "tools/list") {+ res.end(+ JSON.stringify({+ jsonrpc: "2.0",+ id: payload.id ?? null,+ result: {+ tools: [+ {+ name: "notion:list_pages",+ title: "List fixture pages",+ description:+ "Reads deterministic pages from the fake Notion provider.",+ inputSchema: {+ type: "object",+ properties: {},+ additionalProperties: false,+ },+ },+ ],+ },+ }),+ );+ return;+ }+ if (payload.method === "tools/call") {+ res.end(+ JSON.stringify({+ jsonrpc: "2.0",+ id: payload.id ?? null,+ result: {+ content: [{ type: "text", text: "Fixture page inventory" }],+ },+ }),+ );+ return;+ }+ res.end(+ JSON.stringify({ jsonrpc: "2.0", id: payload.id ?? null, result: {} }),+ );+ });+ const port = await listenOnFetchAllowedPort(server);+ return {+ url: `http://127.0.0.1:${port}/`,+ captures,+ close: () => new Promise<void>((resolve) => server.close(() => resolve())),+ };+}++function connectionAwareScript(connectionId: string) {+ return `+const post = async (url, body, token = process.env.PAPERCLIP_RUNTIME_TOOLS_TOKEN) => {+ const response = await fetch(url, {+ method: "POST",+ headers: { authorization: \`Bearer \${token}\`, "content-type": "application/json" },+ body: JSON.stringify(body)+ });+ if (!response.ok) throw new Error(\`\${response.status}: \${await response.text()}\`);+ return await response.json();+};+const search = await post(process.env.PAPERCLIP_RUNTIME_TOOLS_CONNECTIONS_SEARCH_URL, { query: "notion" });+const notion = search.results.find((result) => result.service === "notion");+if (!notion) throw new Error("Notion was not advertised");+if (notion.state !== "ready") {+ const requested = await post(process.env.PAPERCLIP_RUNTIME_TOOLS_CONNECTION_REQUEST_URL, { service: notion.service });+ if (requested.state !== "needs_user_action") throw new Error("Expected a user-action request");+ console.log("waiting for connection intent");+ process.exit(0);+}+const apiHeaders = { authorization: \`Bearer \${process.env.PAPERCLIP_API_KEY}\`, "content-type": "application/json" };+const sessionResponse = await fetch(\`\${process.env.PAPERCLIP_API_URL}/api/tool-gateway/sessions\`, {+ method: "POST",+ headers: apiHeaders,+ body: JSON.stringify({ runId: process.env.PAPERCLIP_RUN_ID, ttlMs: 60000 })+});+if (!sessionResponse.ok) throw new Error(await sessionResponse.text());+const session = await sessionResponse.json();+const toolsResponse = await fetch(\`\${process.env.PAPERCLIP_API_URL}/api/tool-gateway/tools\`, {+ headers: { "x-paperclip-tool-gateway-token": session.token }+});+const tools = await toolsResponse.json();+const tool = tools.find((entry) => entry.connectionId === ${JSON.stringify(connectionId)} && entry.upstreamToolName === "notion:list_pages");+if (!tool) throw new Error("Continuation did not receive the installed Notion tool");+const call = await fetch(\`\${process.env.PAPERCLIP_API_URL}/api/tool-gateway/tools/call\`, {+ method: "POST",+ headers: { "x-paperclip-tool-gateway-token": session.token, "content-type": "application/json" },+ body: JSON.stringify({ tool: tool.name, parameters: {} })+});+if (!call.ok) throw new Error(await call.text());+console.log(await call.text());+`;+}++function escapeRegExp(value: string) {+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}++async function waitForAgentRun(+ request: APIRequestContext,+ companyId: string,+ agentId: string,+) {+ let terminalRun: { id: string; status: string } | null = null;+ await expect+ .poll(+ async () => {+ const runs = await json<Array<{ id: string; status: string }>>(+ await request.get(+ `/api/companies/${companyId}/heartbeat-runs?agentId=${agentId}&limit=10`,+ ),+ );+ terminalRun =+ runs.find((run) => !["queued", "running"].includes(run.status)) ??+ null;+ return terminalRun?.status ?? null;+ },+ { timeout: 45_000 },+ )+ .toBe("succeeded");+ if (!terminalRun)+ throw new Error("Agent run completed without a run receipt");+ return terminalRun;+}++test("store setup and task connection intent share one fake provider through continuation", async ({+ page,+ request,+}) => {+ test.setTimeout(180_000);+ const provider = await startFakeProvider();+ try {+ const seed = await newCompany(request);+ const holder = await createAgent(+ request,+ seed.companyId,+ "Existing access holder",+ );++ // Entry point one: connect and test the provider through the Connections store.+ await page.goto(`/${seed.prefix}/apps`);+ await expect(page.getByRole("heading", { name: "Browse" })).toBeVisible({+ timeout: 30_000,+ });+ await page.getByRole("button", { name: /Connect your own tool/i }).click();+ await page+ .getByPlaceholder("https://example.com/actions")+ .fill(provider.url);+ await page.getByRole("button", { name: "Continue" }).click();+ await page.getByRole("button", { name: /Check link/i }).click();+ // A no-auth read-only provider can complete the access/install defaults in+ // one commit. Other methods exercise the same intermediate steps in the+ // shared-flow component suite.+ await expect(page.getByRole("heading", { name: /is ready/i })).toBeVisible({+ timeout: 30_000,+ });++ const connections = await json<{+ connections: Array<{ id: string; name: string; config: Json }>;+ }>(await request.get(`/api/companies/${seed.companyId}/tools/connections`));+ expect(connections.connections).toHaveLength(1);+ const connection = connections.connections[0]!;+ const connectionId = connection.id;+ await json(+ await request.patch(`/api/tool-connections/${connectionId}`, {+ data: {+ config: {+ ...connection.config,+ url: provider.url,+ sourceTemplateKey: "notion",+ },+ },+ }),+ );+ await json(+ await request.put(`/api/tool-connections/${connectionId}/installs`, {+ data: {+ installs: [{ targetType: "agent", targetId: holder.id }],+ },+ }),+ );++ await page.goto(`/${seed.prefix}/apps/${connectionId}/test`);+ await expect(+ page.getByRole("heading", { name: "Test an action" }),+ ).toBeVisible({ timeout: 30_000 });+ await page.getByRole("button", { name: /List fixture pages/i }).click();+ await page.getByRole("button", { name: "Run", exact: true }).click();+ await expect(page.getByText("Fixture page inventory")).toBeVisible({+ timeout: 30_000,+ });++ // Entry point two: a scripted agent requests Notion, then the same shared+ // provider is reused from the task dialog and appears in the fresh run.+ const scout = await createAgent(+ request,+ seed.companyId,+ "Connection requester",+ );+ await json(+ await request.patch(`/api/agents/${scout.id}`, {+ data: {+ adapterType: "process",+ adapterConfig: {+ command: process.execPath,+ args: [+ "--input-type=module",+ "-e",+ connectionAwareScript(connectionId),+ ],+ },+ replaceAdapterConfig: true,+ },+ }),+ );+ const issue = await json<{ id: string; identifier: string }>(+ await request.post(`/api/companies/${seed.companyId}/issues`, {+ data: {+ title: "Read our Notion pages",+ status: "in_progress",+ assigneeAgentId: scout.id,+ },+ }),+ );+ // Assigning an in-progress task is the production wake path. Waiting for+ // that run avoids creating a second artificial request from an explicit+ // heartbeat invocation.+ const firstRun = await waitForAgentRun(request, seed.companyId, scout.id);++ const taskUrl = `/${seed.prefix}/issues/${issue.identifier}`;+ await page.goto(taskUrl);+ await expect(+ page.getByText("Connection requester needs Notion"),+ ).toBeVisible({ timeout: 30_000 });+ await page.getByRole("button", { name: "Connect / Use existing" }).click();+ await expect(+ page.getByRole("heading", { name: "Use an existing connection" }),+ ).toBeVisible();+ await page+ .getByRole("button", { name: new RegExp(escapeRegExp(connection.name)) })+ .click();++ await expect(page.getByText("Notion connected")).toBeVisible({+ timeout: 30_000,+ });+ await expect(page).toHaveURL(new RegExp(`${taskUrl}$`));+ await expect(+ page+ .getByTestId("connection-intent-focus-target")+ .filter({ hasText: "Notion connected" }),+ ).toBeFocused();+ expect(await page.locator("body").innerText()).not.toMatch(+ /\/authorize\?|authorizationUrl/,+ );++ await expect+ .poll(+ async () => {+ const runs = await json<Array<{ id: string; status: string }>>(+ await request.get(+ `/api/companies/${seed.companyId}/heartbeat-runs?agentId=${scout.id}&limit=10`,+ ),+ );+ return runs.find((run) => run.id !== firstRun.id)?.status ?? null;+ },+ { timeout: 45_000 },+ )+ .toBe("succeeded");+ await expect+ .poll(() =>+ provider.captures.some(+ (capture) =>+ capture.method === "tools/call" &&+ capture.toolName === "notion:list_pages",+ ),+ )+ .toBe(true);++ const interactions = await json<Array<{ kind: string; status: string }>>(+ await request.get(`/api/issues/${issue.id}/interactions`),+ );+ const connectionIntents = interactions.filter(+ (interaction) => interaction.kind === "connection_intent",+ );+ expect(+ connectionIntents.filter(+ (interaction) => interaction.status === "accepted",+ ),+ ).toHaveLength(1);+ expect(+ connectionIntents.filter(+ (interaction) => interaction.status === "pending",+ ),+ ).toHaveLength(0);+ expect(+ connectionIntents.every((interaction) =>+ ["accepted", "expired"].includes(interaction.status),+ ),+ ).toBe(true);+ expect(holder.id).not.toBe(scout.id);+ } finally {+ await provider.close();+ }+});diff --git a/ui/src/App.test.tsx b/ui/src/App.test.tsxindex 56bf0c032a..73b591f416 100644--- a/ui/src/App.test.tsx+++ b/ui/src/App.test.tsx@@ -250,6 +250,9 @@ describe("Apps routes", () => {expect(appSource).toContain('<Route path="apps/browse" element={<Navigate to="/apps" replace />} />');expect(appSource).toContain('<Route path="apps/connections" element={<Connections />} />');expect(appSource).toContain('<Route path="apps/byo" element={<AppsConnect byoOnly />} />');+ expect(appSource).toContain('path="apps/vercel-connect"');+ expect(appSource).toContain('<AppsConnectEntryRoute credentialSource="vercel_connect" />');+ expect(appSource).toContain('<AppsConnect credentialSource={credentialSource} />');expect(appSource).toContain('<Route path="apps/connect/:appKey" element={<Navigate to="/apps" replace />} />');expect(appSource).toContain('<Route path="apps/connect/:appKey/:stage" element={<Navigate to="/apps" replace />} />');expect(appSource).toContain('<Route path="apps/advanced/gateways" element={<GatewaysList />} />');diff --git a/ui/src/App.tsx b/ui/src/App.tsxindex e1184a6452..bc88dd5211 100644--- a/ui/src/App.tsx+++ b/ui/src/App.tsx@@ -1,4 +1,5 @@import { lazy, Suspense } from "react";+import type { ToolConnectionCredentialSource } from "@paperclipai/shared";import { Navigate, Outlet, Route, Routes, useActiveCompanyPrefix, useLocation, useParams } from "@/lib/router";import { Button } from "@/components/ui/button";import { useTranslation } from "@/i18n";@@ -157,6 +158,10 @@ function boardRoutes() {<Route path="apps/browse" element={<Navigate to="/apps" replace />} /><Route path="apps/connections" element={<Connections />} /><Route path="apps/byo" element={<AppsConnect byoOnly />} />+ <Route+ path="apps/vercel-connect"+ element={<AppsConnectEntryRoute credentialSource="vercel_connect" />}+ /><Route path="apps/connect" element={<AppsConnectEntryRoute />} /><Route path="apps/connect/:appKey" element={<Navigate to="/apps" replace />} /><Route path="apps/connect/:appKey/:stage" element={<Navigate to="/apps" replace />} />@@ -350,10 +355,16 @@ function boardRoutes() {);}-function AppsConnectEntryRoute() {+function AppsConnectEntryRoute({+ credentialSource = "paperclip_vault",+}: {+ credentialSource?: ToolConnectionCredentialSource;+} = {}) {const location = useLocation();const searchParams = new URLSearchParams(location.search);- return canEnterAppsConnect(searchParams) ? <AppsConnect /> : <Navigate to="/apps" replace />;+ return canEnterAppsConnect(searchParams)+ ? <AppsConnect credentialSource={credentialSource} />+ : <Navigate to="/apps" replace />;}function InboxRootRedirect() {diff --git a/ui/src/api/connection-intents.ts b/ui/src/api/connection-intents.tsindex 7407dd64fb..19605178ce 100644--- a/ui/src/api/connection-intents.ts+++ b/ui/src/api/connection-intents.ts@@ -9,6 +9,14 @@ export const connectionIntentsApi = {api.get<ConnectionIntentSetupOptions>(`/connection-intents/${interactionId}/setup-options`,),+ setPhase: (+ interactionId: string,+ phase: ConnectionIntentInteraction["payload"]["phase"],+ ) =>+ api.post<ConnectionIntentInteraction>(+ `/connection-intents/${interactionId}/phase`,+ { phase },+ ),complete: (interactionId: string, connectionId: string) =>api.post<ConnectionIntentInteraction>(`/connection-intents/${interactionId}/complete`,diff --git a/ui/src/api/tools.ts b/ui/src/api/tools.tsindex fa2ac051c5..bd7ec6f241 100644--- a/ui/src/api/tools.ts+++ b/ui/src/api/tools.ts@@ -6,12 +6,12 @@ import type {} from "@/pages/apps/composio-services";import type {ToolApplication,- ConnectToolApp,ToolConnection,ToolConnectionInstall,ToolConnectionInstallSnapshot,ToolConnectionRemovalSummary,ConnectToolAppResult,+ ConnectToolApp,FinishToolAppResult,ToolCatalogEntry,ToolRuntimeSlot,@@ -61,9 +61,11 @@ import type {CreateToolTrustRuleFromActionRequest,ToolRedactedValueSummary,ConnectionGrant,+ ConnectionGrantKind,ConnectionGrantDelegation,ConnectionGrantsResponse,ToolConnectionCreateCapabilities,+ ToolAppMetadataPreflightResult,} from "@paperclipai/shared";import { api } from "./client";@@ -87,6 +89,15 @@ export type ToolProfilesResponse = { profiles: ToolProfileWithDetails[] };export type ToolGalleryResponse = {apps: AppDefinition[];capabilities: ToolConnectionCreateCapabilities;+ credentialSources: {+ vercelConnect: {+ available: boolean;+ enabled: boolean;+ authentication: "workload_oidc" | "access_token" | null;+ manageUrl: string;+ reason: string | null;+ };+ };};export type ToolMcpGatewaysResponse = { gateways: ToolMcpGatewayWithTokens[] };export type CreateGatewayTokenInput = Omit<CreateToolMcpGatewayToken, "expiresAt"> & {@@ -268,12 +279,30 @@ export const toolsApi = {// --- Applications ---listGallery: (companyId: string) =>api.get<ToolGalleryResponse>(`/companies/${companyId}/tools/gallery`),+ preflightAppMetadata: (companyId: string, galleryKey: string, methodKey?: string | null) => {+ const query = methodKey ? `?methodKey=${encodeURIComponent(methodKey)}` : "";+ return api.get<ToolAppMetadataPreflightResult>(+ `/companies/${companyId}/tools/apps/${encodeURIComponent(galleryKey)}/preflight${query}`,+ );+ },connectApp: (companyId: string, input: ConnectToolApp) =>api.post<ConnectToolAppResult>(`/companies/${companyId}/tools/apps/connect`, input),- startOAuth: (connectionId: string, interactionId?: string) =>- api.post<ToolOAuthStartResult>(- `/tools/oauth/${connectionId}/start`,- interactionId ? { interactionId } : {},+ startOAuth: (+ connectionId: string,+ input: {+ asCurrentUser?: boolean;+ interactionId?: string;+ } = {},+ ) =>+ api.post<ToolOAuthStartResult>(`/tools/oauth/${connectionId}/start`, input),+ finalizeOAuthAccess: (+ companyId: string,+ connectionId: string,+ input: { grantKind: ConnectionGrantKind },+ ) =>+ api.post<FinishToolAppResult>(+ `/companies/${companyId}/tools/apps/${connectionId}/finalize-oauth-access`,+ input,),finishApp: (companyId: string, connectionId: string, input: {enabledCatalogEntryIds: string[];diff --git a/ui/src/components/AppConnectionSidebar.tsx b/ui/src/components/AppConnectionSidebar.tsxindex 5189f7a2dd..762d532c5e 100644--- a/ui/src/components/AppConnectionSidebar.tsx+++ b/ui/src/components/AppConnectionSidebar.tsx@@ -20,6 +20,7 @@ import { AppLogo } from "@/pages/apps/AppLogo";import {appApplicationSourceSlug,appConnectionSourceSlug,+ appDefinitionDarkLogoUrl,appDefinitionLogoUrl,appDefinitionName,appDefinitionSlug,@@ -106,6 +107,7 @@ export function AppDetailSidebar(props: AppDetailSidebarProps) {brandKey={brandKey}logoUrl={appDefinitionLogoUrl(logoEntry)}allowRemoteFallback={!applicationsQuery.isPending}+ darkLogoUrl={appDefinitionDarkLogoUrl(logoEntry)}size={28}/><span className="flex-1 truncate text-sm font-bold text-foreground">{appName}</span>diff --git a/ui/src/components/AppsSidebar.test.tsx b/ui/src/components/AppsSidebar.test.tsxindex 45e3c6621a..9a6fc0f61e 100644--- a/ui/src/components/AppsSidebar.test.tsx+++ b/ui/src/components/AppsSidebar.test.tsx@@ -146,8 +146,11 @@ describe("AppsSidebar", () => {expect(sidebarNavItemMock).not.toHaveBeenCalledWith(expect.objectContaining({ label: "Applications" }),);- expect(sidebarNavItemMock).toHaveBeenCalledWith(- expect.objectContaining({ to: "/apps/advanced/profiles", label: "Profiles", end: true }),+ expect(sidebarNavItemMock).not.toHaveBeenCalledWith(+ expect.objectContaining({ to: "/apps/advanced/gateways", label: "Gateways" }),+ );+ expect(sidebarNavItemMock).not.toHaveBeenCalledWith(+ expect.objectContaining({ to: "/apps/advanced/profiles", label: "Profiles" }),);expect(sidebarNavItemMock).not.toHaveBeenCalledWith(expect.objectContaining({ label: "Rules" }));expect(sidebarNavItemMock).not.toHaveBeenCalledWith(expect.objectContaining({ label: "Health" }));diff --git a/ui/src/components/AppsSidebar.tsx b/ui/src/components/AppsSidebar.tsxindex bca01e789a..729e64de93 100644--- a/ui/src/components/AppsSidebar.tsx+++ b/ui/src/components/AppsSidebar.tsx@@ -12,7 +12,7 @@ import { SidebarNavItem } from "./SidebarNavItem";* PAP-13254 / U3).** ← Back · APPS: Browse / Review (n)- * DEVELOPER: Connections / Gateways / Profiles / Activity+ * DEVELOPER: Connections / Activity** "Browse" is the store and "Review" holds decisions waiting on the user's* OK. Connection management lives with the Developer tools.@@ -30,9 +30,12 @@ export function AppsSidebar() {const reviewCount = useReviewCount();const { enabled: smokeLabEnabled } = useSmokeLabEnabled();- const developerTabs = DEVELOPER_TABS.filter(- (tab) => !isExperimentalToolTab(tab.key) || smokeLabEnabled,- );+ const developerTabs = DEVELOPER_TABS.filter((tab) => {+ // Temporarily hide Gateways and Profiles until they are ready to ship.+ // Keep their tab definitions and routes intact so we can bring them back later.+ if (tab.key === "gateways" || tab.key === "profiles") return false;+ return !isExperimentalToolTab(tab.key) || smokeLabEnabled;+ });return (<aside className="w-full h-full min-h-0 border-r border-border bg-background flex flex-col">diff --git a/ui/src/components/ConnectionIntentInteractionBody.tsx b/ui/src/components/ConnectionIntentInteractionBody.tsxdeleted file mode 100644index 448335e6ff..0000000000--- a/ui/src/components/ConnectionIntentInteractionBody.tsx+++ /dev/null@@ -1,178 +0,0 @@-import { useEffect, useState } from "react";-import { CheckCircle2, Clock, Loader2, Plug, XCircle } from "lucide-react";-import type {- ConnectionIntentInteraction,- ConnectionIntentSetupOptions,-} from "@paperclipai/shared";-import { connectionIntentsApi } from "@/api/connection-intents";-import { Link } from "@/lib/router";-import { AppLogo } from "@/pages/apps/AppLogo";-import { appSourceConnectHref, isMcpDirectOAuthConnectSlug } from "@/pages/apps/app-connect-policy";-import { Button } from "./ui/button";--export interface ConnectionIntentInteractionBodyProps {- interaction: ConnectionIntentInteraction;- currentUserId?: string | null;- addresseeLabel: string;-}--export function ConnectionIntentInteractionBody({- interaction,- currentUserId,- addresseeLabel,-}: ConnectionIntentInteractionBodyProps) {- const [current, setCurrent] = useState(interaction);- const [options, setOptions] = useState<ConnectionIntentSetupOptions | null>(null);- const [expanded, setExpanded] = useState(false);- const [pendingAction, setPendingAction] = useState<string | null>(null);- const [error, setError] = useState<string | null>(null);-- useEffect(() => setCurrent(interaction), [interaction]);-- const isAddressee = Boolean(currentUserId && current.addresseeUserId === currentUserId);- const connectHref = isMcpDirectOAuthConnectSlug(current.payload.serviceSlug)- ? appSourceConnectHref(current.payload.serviceSlug, current.id)- : `/apps/connect?${new URLSearchParams({- byo: "1",- appKey: current.payload.serviceSlug,- intent: current.id,- }).toString()}`;-- async function loadOptions() {- setExpanded(true);- setPendingAction("load");- setError(null);- try {- setOptions(await connectionIntentsApi.setupOptions(current.id));- } catch (cause) {- setError(cause instanceof Error ? cause.message : "Couldn’t load connection options.");- } finally {- setPendingAction(null);- }- }-- async function complete(connectionId: string) {- setPendingAction(connectionId);- setError(null);- try {- setCurrent(await connectionIntentsApi.complete(current.id, connectionId));- } catch (cause) {- setError(cause instanceof Error ? cause.message : "Couldn’t use this connection.");- } finally {- setPendingAction(null);- }- }-- async function decline() {- setPendingAction("decline");- setError(null);- try {- setCurrent(await connectionIntentsApi.decline(current.id));- } catch (cause) {- setError(cause instanceof Error ? cause.message : "Couldn’t decline this request.");- } finally {- setPendingAction(null);- }- }-- if (current.status === "accepted" || current.status === "rejected" || current.status === "expired") {- const connected = current.status === "accepted";- const StatusIcon = connected ? CheckCircle2 : XCircle;- const title = connected- ? `${current.payload.serviceName} connected`- : current.status === "rejected"- ? "Connection declined"- : "Connection request expired";- return (- <div className="flex items-start gap-3" data-testid="connection-intent-terminal">- <StatusIcon className="mt-0.5 h-5 w-5 shrink-0 text-muted-foreground" />- <div>- <p className="font-medium text-foreground">{title}</p>- <p className="mt-1 text-sm text-muted-foreground">- {connected- ? `${current.payload.requestingAgentName} can use this connection on its continuation run.`- : `${current.payload.requestingAgentName} can continue without this connection.`}- </p>- </div>- </div>- );- }-- if (!isAddressee) {- return (- <div className="flex items-start gap-3" data-testid="connection-intent-waiting">- <Clock className="mt-0.5 h-5 w-5 shrink-0 text-muted-foreground" />- <div>- <p className="font-medium text-foreground">Waiting for {addresseeLabel}</p>- <p className="mt-1 text-sm text-muted-foreground">- Only the addressed person can choose or create a connection.- </p>- </div>- </div>- );- }-- return (- <div data-testid="connection-intent-actions">- <div className="flex items-start gap-3">- <AppLogo- name={current.payload.serviceName}- brandKey={current.payload.serviceSlug}- logoUrl={current.payload.serviceLogoUrl}- size={40}- />- <div>- <p className="font-medium text-foreground">- {current.payload.requestingAgentName} needs {current.payload.serviceName}- </p>- <p className="mt-1 text-sm text-muted-foreground">- Reuse an eligible connection or connect a new identity for this agent.- </p>- </div>- </div>-- <div className="mt-4 flex flex-wrap gap-2">- <Button type="button" onClick={() => void loadOptions()} disabled={pendingAction !== null}>- {pendingAction === "load" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plug className="h-4 w-4" />}- Connect / Use existing- </Button>- <Button- type="button"- variant="ghost"- onClick={() => void decline()}- disabled={pendingAction !== null}- >- Not now- </Button>- </div>-- {expanded && pendingAction === "load" ? (- <p className="mt-3 text-sm text-muted-foreground">Loading connection options…</p>- ) : null}- {expanded && options ? (- <div className="mt-3 space-y-2 rounded-md border border-border bg-muted/30 p-3">- {options.existingConnections.map((connection) => (- <Button- key={connection.id}- type="button"- variant="outline"- className="w-full justify-start"- onClick={() => void complete(connection.id)}- disabled={pendingAction !== null}- >- {pendingAction === connection.id ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plug className="h-4 w-4" />}- Use {connection.name}- </Button>- ))}- <Button asChild type="button" variant="outline" className="w-full justify-start">- <Link to={connectHref}>Connect a new {current.payload.serviceName} identity</Link>- </Button>- <p className="text-xs text-muted-foreground">- Finishing setup will grant the new identity and resolve this request automatically.- </p>- </div>- ) : null}- {error ? <p className="mt-3 text-sm text-destructive" role="alert">{error}</p> : null}- </div>- );-}diff --git a/ui/src/components/IssueThreadInteractionCard.test.tsx b/ui/src/components/IssueThreadInteractionCard.test.tsxindex 6fffdab4ff..fff0a67dd3 100644--- a/ui/src/components/IssueThreadInteractionCard.test.tsx+++ b/ui/src/components/IssueThreadInteractionCard.test.tsx@@ -4,6 +4,7 @@ import { act as reactAct, type ComponentProps, type ReactNode } from "react";import { flushSync } from "react-dom";import { createRoot, type Root } from "react-dom/client";import { afterEach, describe, expect, it, vi } from "vitest";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import type { Agent } from "@paperclipai/shared";import { ApiError } from "../api/client";import { IssueThreadInteractionCard } from "./IssueThreadInteractionCard";@@ -48,6 +49,8 @@ import {companyCappedRequestConfirmationInteraction,legacyRestrictedRequestConfirmationInteraction,pendingConnectionIntentInteraction,+ retryConnectionIntentInteraction,+ connectedConnectionIntentInteraction,} from "../fixtures/issueThreadInteractionFixtures";let root: Root | null = null;@@ -89,17 +92,22 @@ function renderCard(container = document.createElement("div");document.body.appendChild(container);root = createRoot(container);+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });act(() => {root?.render(- <TooltipProvider>- <ThemeProvider>- <IssueThreadInteractionCard- interaction={pendingAskUserQuestionsInteraction}- {...props}- />- </ThemeProvider>- </TooltipProvider>,+ <QueryClientProvider client={queryClient}>+ <TooltipProvider>+ <ThemeProvider>+ <IssueThreadInteractionCard+ interaction={pendingAskUserQuestionsInteraction}+ {...props}+ />+ </ThemeProvider>+ </TooltipProvider>+ </QueryClientProvider>,);});@@ -116,7 +124,7 @@ afterEach(() => {});describe("IssueThreadInteractionCard", () => {- it("offers connection resolution actions to the addressed user", async () => {+ it("opens the shared connection setup for the addressed user", async () => {connectionIntentsApiMocks.setupOptions.mockResolvedValue({ existingConnections: [] });const host = renderCard({interaction: pendingConnectionIntentInteraction,@@ -133,12 +141,15 @@ describe("IssueThreadInteractionCard", () => {loadButton?.click();await Promise.resolve();});- const connectLink = Array.from(host.querySelectorAll("a")).find((link) =>- link.textContent === "Connect a new Notion identity",- );- expect(connectLink?.getAttribute("href")).toBe(- "/apps/connect?source=notion&intent=interaction-connection-intent-default",+ await vi.waitFor(() =>+ expect(connectionIntentsApiMocks.setupOptions).toHaveBeenCalledWith(+ "interaction-connection-intent-default",+ ),);+ const dialog = document.body.querySelector('[role="dialog"]');+ expect(dialog).toBeTruthy();+ expect(dialog?.textContent).toContain("Connect Notion");+ expect(dialog?.textContent).toContain("Complete connection setup without leaving this task.");});it("keeps connection resolution controls exclusive to the addressed user", () => {@@ -1391,6 +1402,55 @@ describe("IssueThreadInteractionCard connection-authorization card", () => {});});+describe("IssueThreadInteractionCard connection-intent card", () => {+ const USER_LABELS = new Map([[issueThreadInteractionFixtureMeta.currentUserId, "Carol"]]);++ it("offers the addressed user the shared setup entry point and Not now", () => {+ const host = renderCard({+ interaction: pendingConnectionIntentInteraction,+ currentUserId: issueThreadInteractionFixtureMeta.currentUserId,+ });+ expect(host.querySelector('[data-testid="connection-intent-actions"]')).not.toBeNull();+ const labels = Array.from(host.querySelectorAll("button")).map((button) => button.textContent?.trim());+ expect(labels).toContain("Connect / Use existing");+ expect(labels).toContain("Not now");+ expect(host.textContent).toContain("Access is added only for this agent");+ });++ it("shows another viewer only who it is waiting for", () => {+ const host = renderCard({+ interaction: pendingConnectionIntentInteraction,+ currentUserId: "user-someone-else",+ userLabelMap: USER_LABELS,+ });+ expect(host.querySelector('[data-testid="connection-intent-waiting"]')?.textContent)+ .toContain("Waiting for Carol");+ expect(host.querySelector('[data-testid="connection-intent-actions"]')).toBeNull();+ expect(host.querySelectorAll("button")).toHaveLength(0);+ expect(host.innerHTML).not.toContain("authorizationUrl");+ });++ it("renders retry and connected terminal states without generic confirmation actions", () => {+ const retry = renderCard({+ interaction: retryConnectionIntentInteraction,+ currentUserId: issueThreadInteractionFixtureMeta.currentUserId,+ });+ expect(retry.textContent).toContain("Authorization didn’t finish");+ expect(retry.textContent).toContain("Try again");++ act(() => root?.unmount());+ retry.remove();+ root = null;+ const connected = renderCard({+ interaction: connectedConnectionIntentInteraction,+ currentUserId: issueThreadInteractionFixtureMeta.currentUserId,+ });+ expect(connected.querySelector('[data-testid="connection-intent-terminal"]')?.textContent)+ .toContain("Notion connected");+ expect(connected.textContent).not.toContain("Approve");+ });+});+describe("IssueThreadInteractionCard resolver audience", () => {it("shows an open audience on a pending card created without a restriction", () => {const host = renderCard({ interaction: pendingRequestConfirmationInteraction });diff --git a/ui/src/components/IssueThreadInteractionCard.tsx b/ui/src/components/IssueThreadInteractionCard.tsxindex d86d631e58..1578f29a67 100644--- a/ui/src/components/IssueThreadInteractionCard.tsx+++ b/ui/src/components/IssueThreadInteractionCard.tsx@@ -41,7 +41,7 @@ import { Textarea } from "./ui/textarea";import { Tooltip, TooltipContent, TooltipTrigger } from "./ui/tooltip";import { Badge } from "@/components/ui/badge";import { ProposalJustification } from "../pages/secrets/proposal-review";-import { ConnectionIntentInteractionBody } from "./ConnectionIntentInteractionBody";+import { ConnectionIntentInteractionBody } from "@/features/connections/ConnectionIntentInteractionBody";const OTHER_ANSWER_ID = "__paperclip_other__";@@ -200,6 +200,8 @@ function interactionKindLabel(kind: IssueThreadInteraction["kind"]) {return "Checkbox confirmation";case "request_item_verdicts":return "Item verdicts";+ case "connection_intent":+ return "Connection request";default:return kind;}@@ -4082,7 +4084,7 @@ export function IssueThreadInteractionCard({below, because the closing sentence depends on whether thereader is the person who may consent. Rendering the summary hereas well would be the second body PAP-17859 removed. */}- {interaction.summary && !connectionAuthorization ? (+ {interaction.summary && !connectionAuthorization && interaction.kind !== "connection_intent" ? (<p className="mt-2 max-w-3xl text-sm leading-6 text-muted-foreground">{interaction.summary}</p>@@ -4162,18 +4164,18 @@ export function IssueThreadInteractionCard({onRejectInteraction={onRejectInteraction}externalReferences={externalReferences}/>- ) : interaction.kind === "request_item_verdicts" ? (- <RequestItemVerdictsCard- interaction={interaction}- onSubmitInteractionVerdicts={onSubmitInteractionVerdicts}- externalReferences={externalReferences}- />) : interaction.kind === "connection_intent" ? (<ConnectionIntentInteractionBodyinteraction={interaction}currentUserId={currentUserId}addresseeLabel={addresseeLabel ?? "the addressed person"}/>+ ) : interaction.kind === "request_item_verdicts" ? (+ <RequestItemVerdictsCard+ interaction={interaction}+ onSubmitInteractionVerdicts={onSubmitInteractionVerdicts}+ externalReferences={externalReferences}+ />) : (<RequestConfirmationCardinteraction={interaction}diff --git a/ui/src/components/Layout.test.tsx b/ui/src/components/Layout.test.tsxindex 6cdd9b8363..b39ce59406 100644--- a/ui/src/components/Layout.test.tsx+++ b/ui/src/components/Layout.test.tsx@@ -644,7 +644,7 @@ describe("Layout", () => {// Reserved Apps subroutes are not connection ids. They must keep the// top-level Apps sidebar, never mount a detail sidebar for a phantom app.- it.each(["browse", "connections", "review"])("keeps the Apps sidebar on the %s surface", async (route) => {+ it.each(["browse", "connections", "vercel-connect", "review"])("keeps the Apps sidebar on the %s surface", async (route) => {currentPathname = `/PAP/apps/${route}`;const root = createRoot(container);const queryClient = new QueryClient({diff --git a/ui/src/components/Layout.tsx b/ui/src/components/Layout.tsxindex 205ff57c4a..4b5528121d 100644--- a/ui/src/components/Layout.tsx+++ b/ui/src/components/Layout.tsx@@ -64,6 +64,7 @@ const RESERVED_APP_SUBPATHS = new Set(["browse","connections","connect",+ "vercel-connect","review","attention","gateways",diff --git a/ui/src/features/connections/ConnectionIntentInteractionBody.test.tsx b/ui/src/features/connections/ConnectionIntentInteractionBody.test.tsxnew file mode 100644index 0000000000..b3fcc1b73d--- /dev/null+++ b/ui/src/features/connections/ConnectionIntentInteractionBody.test.tsx@@ -0,0 +1,347 @@+// @vitest-environment jsdom++import { act as reactAct, type ReactNode } from "react";+import { createRoot, type Root } from "react-dom/client";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type {+ ConnectionIntentInteraction,+ ToolConnection,+} from "@paperclipai/shared";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ connectedConnectionIntentInteraction,+ issueThreadInteractionFixtureMeta,+ pendingConnectionIntentInteraction,+ retryConnectionIntentInteraction,+} from "@/fixtures/issueThreadInteractionFixtures";+import { ConnectionIntentInteractionBody } from "./ConnectionIntentInteractionBody";++const setupOptionsMock = vi.hoisted(() => vi.fn());+const completeMock = vi.hoisted(() => vi.fn());+const declineMock = vi.hoisted(() => vi.fn());+const setPhaseMock = vi.hoisted(() => vi.fn());++vi.mock("@/api/connection-intents", () => ({+ connectionIntentsApi: {+ setupOptions: (...args: unknown[]) => setupOptionsMock(...args),+ complete: (...args: unknown[]) => completeMock(...args),+ decline: (...args: unknown[]) => declineMock(...args),+ setPhase: (...args: unknown[]) => setPhaseMock(...args),+ },+}));++vi.mock("./ConnectionSetupFlow", () => ({+ ConnectionSetupFlow: (props: {+ requestedAgentId?: string;+ existingConnections?: ToolConnection[];+ onUseExisting?: (id: string) => Promise<void>;+ onComplete?: (completion: { connectionId: string }) => void;+ onPhaseChange?: (phase: "needs_retry") => void;+ onCancel?: () => void;+ }) => (+ <div data-testid="shared-connection-setup">+ <span data-testid="requested-agent">{props.requestedAgentId}</span>+ <span data-testid="existing-count">+ {props.existingConnections?.length ?? 0}+ </span>+ {props.existingConnections?.map((connection) => (+ <button+ key={connection.id}+ onClick={() => void props.onUseExisting?.(connection.id)}+ >+ Use {connection.name}+ </button>+ ))}+ <button+ onClick={() => props.onComplete?.({ connectionId: "connection-new" })}+ >+ Connect new+ </button>+ <button onClick={() => props.onPhaseChange?.("needs_retry")}>+ Simulate retry+ </button>+ <button onClick={props.onCancel}>Cancel setup</button>+ </div>+ ),+}));++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++let root: Root | null = null;+let host: HTMLDivElement | null = null;+let queryClient: QueryClient;++async function act(callback: () => void | Promise<void>) {+ await reactAct(callback);+}++async function flush() {+ await act(async () => {+ await Promise.resolve();+ await new Promise((resolve) => window.setTimeout(resolve, 0));+ });+}++async function waitForAssertion(assertion: () => void, attempts = 20) {+ let lastError: unknown;+ for (let attempt = 0; attempt < attempts; attempt += 1) {+ try {+ assertion();+ return;+ } catch (error) {+ lastError = error;+ await flush();+ }+ }+ throw lastError;+}++function terminal(+ status: ConnectionIntentInteraction["status"],+ outcome: "declined" | "superseded" | "expired",+): ConnectionIntentInteraction {+ return {+ ...pendingConnectionIntentInteraction,+ id: `interaction-${outcome}`,+ status,+ resolvedAt: new Date("2026-08-26T12:00:00.000Z"),+ result: { version: 1, outcome },+ } as ConnectionIntentInteraction;+}++function renderBody(+ interaction: ConnectionIntentInteraction = pendingConnectionIntentInteraction,+ currentUserId:+ string | null = issueThreadInteractionFixtureMeta.currentUserId,+) {+ host = document.createElement("div");+ document.body.appendChild(host);+ root = createRoot(host);+ queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ void act(() => {+ root?.render(+ <QueryClientProvider client={queryClient}>+ <ConnectionIntentInteractionBody+ interaction={interaction}+ currentUserId={currentUserId}+ addresseeLabel="Carol"+ />+ </QueryClientProvider>,+ );+ });+ return host;+}++function button(label: string) {+ return Array.from(document.body.querySelectorAll("button")).find(+ (candidate) => candidate.textContent?.trim() === label,+ ) as HTMLButtonElement | undefined;+}++beforeEach(() => {+ setupOptionsMock.mockReset();+ completeMock.mockReset();+ declineMock.mockReset();+ setPhaseMock.mockReset();+ setupOptionsMock.mockResolvedValue({+ requestedAgentId:+ pendingConnectionIntentInteraction.payload.requestingAgentId,+ existingConnections: [],+ });+ completeMock.mockResolvedValue({});+ declineMock.mockResolvedValue({});+ setPhaseMock.mockResolvedValue({});+});++afterEach(async () => {+ if (root) await act(() => root?.unmount());+ host?.remove();+ document.body+ .querySelectorAll("[data-radix-focus-guard]")+ .forEach((node) => node.remove());+ root = null;+ host = null;+});++describe("ConnectionIntentInteractionBody states and audience", () => {+ it.each([+ [pendingConnectionIntentInteraction, "Connect / Use existing"],+ [+ {+ ...pendingConnectionIntentInteraction,+ payload: {+ ...pendingConnectionIntentInteraction.payload,+ phase: "authorizing",+ },+ },+ "Authorizing…",+ ],+ [retryConnectionIntentInteraction, "Try again"],+ [connectedConnectionIntentInteraction, "Notion connected"],+ [terminal("rejected", "declined"), "Connection declined"],+ [terminal("expired", "superseded"), "Request superseded"],+ [terminal("expired", "expired"), "Connection request expired"],+ ] as const)("renders the %s state", (interaction, expected) => {+ renderBody(interaction as ConnectionIntentInteraction);+ expect(document.body.textContent).toContain(expected);+ });++ it("shows non-addressees only the waiting state and never loads setup", () => {+ renderBody(pendingConnectionIntentInteraction, "other-user");+ expect(document.body.textContent).toContain("Waiting for Carol");+ expect(button("Connect / Use existing")).toBeUndefined();+ expect(button("Not now")).toBeUndefined();+ expect(setupOptionsMock).not.toHaveBeenCalled();+ expect(document.body.innerHTML).not.toMatch(+ /authorizationUrl|bearer|credential/i,+ );+ });+});++describe("ConnectionIntentInteractionBody dialog behavior", () => {+ it("shows loading, then passes existing choices and the locked requesting agent to the shared flow", async () => {+ let resolveSetup!: (value: unknown) => void;+ setupOptionsMock.mockReturnValue(+ new Promise((resolve) => {+ resolveSetup = resolve;+ }),+ );+ renderBody();++ await act(() => button("Connect / Use existing")?.click());+ expect(document.body.textContent).toContain("Loading connection options…");++ await act(async () => {+ resolveSetup({+ requestedAgentId: "agent-requesting",+ existingConnections: [+ { id: "connection-one", name: "Carol's Notion" },+ { id: "connection-two", name: "Team Notion" },+ ],+ });+ });+ await flush();++ expect(+ document.querySelector('[data-testid="requested-agent"]')?.textContent,+ ).toBe("agent-requesting");+ expect(+ document.querySelector('[data-testid="existing-count"]')?.textContent,+ ).toBe("2");+ expect(button("Use Carol's Notion")).toBeDefined();+ expect(button("Use Team Notion")).toBeDefined();+ expect(button("Connect new")).toBeDefined();+ });++ it("keeps a load failure open and recovers through the query retry", async () => {+ setupOptionsMock.mockRejectedValueOnce(new Error("setup unavailable"));+ renderBody();+ await act(() => button("Connect / Use existing")?.click());+ await flush();++ expect(document.body.textContent).toContain(+ "Couldn’t load connection setup",+ );+ expect(document.body.textContent).toContain("setup unavailable");+ setupOptionsMock.mockResolvedValueOnce({+ requestedAgentId: "agent-requesting",+ existingConnections: [],+ });+ await act(() => button("Try again")?.click());+ await flush();+ expect(+ document.querySelector('[data-testid="shared-connection-setup"]'),+ ).not.toBeNull();+ });++ it("completes an existing connection, closes, restores focus, and invalidates each task query once", async () => {+ setupOptionsMock.mockResolvedValue({+ requestedAgentId: "agent-requesting",+ existingConnections: [{ id: "connection-one", name: "Carol's Notion" }],+ });+ renderBody();+ const trigger = button("Connect / Use existing")!;+ const invalidation = vi.spyOn(queryClient, "invalidateQueries");++ await act(() => trigger.click());+ await flush();+ await act(() => button("Use Carol's Notion")?.click());+ await flush();++ expect(completeMock).toHaveBeenCalledWith(+ pendingConnectionIntentInteraction.id,+ "connection-one",+ );+ expect(+ document.querySelector('[data-testid="shared-connection-setup"]'),+ ).toBeNull();+ await waitForAssertion(() =>+ expect(document.activeElement).toBe(+ document.querySelector(+ '[data-testid="connection-intent-focus-target"]',+ ),+ ),+ );+ expect(invalidation).toHaveBeenCalledTimes(2);+ expect(invalidation).toHaveBeenCalledWith({+ queryKey: ["issues", "interactions"],+ });+ expect(invalidation).toHaveBeenCalledWith({+ queryKey: ["issues", "detail"],+ });+ });++ it("keeps the dialog open and surfaces completion failures", async () => {+ completeMock.mockRejectedValue(new Error("install commit failed"));+ renderBody();+ await act(() => button("Connect / Use existing")?.click());+ await flush();+ await act(() => button("Connect new")?.click());+ await flush();++ expect(+ document.querySelector('[data-testid="shared-connection-setup"]'),+ ).not.toBeNull();+ expect(+ document.body.querySelector('[role="alert"]')?.textContent,+ ).toContain("install commit failed");+ });++ it("declines once with pending controls disabled and invalidates each task query once", async () => {+ let finishDecline!: () => void;+ declineMock.mockReturnValue(+ new Promise<void>((resolve) => {+ finishDecline = resolve;+ }),+ );+ renderBody();+ const invalidation = vi.spyOn(queryClient, "invalidateQueries");+ const decline = button("Not now")!;++ await act(() => decline.click());+ await flush();+ expect(decline.disabled).toBe(true);+ decline.click();+ expect(declineMock).toHaveBeenCalledTimes(1);+ await act(async () => finishDecline());+ await flush();++ expect(invalidation).toHaveBeenCalledTimes(2);+ });++ it("turns shared-flow retry signals into the server-authored retry phase", async () => {+ renderBody();+ await act(() => button("Connect / Use existing")?.click());+ await flush();+ await act(() => button("Simulate retry")?.click());+ await flush();+ expect(setPhaseMock).toHaveBeenCalledWith(+ pendingConnectionIntentInteraction.id,+ "needs_retry",+ );+ });+});diff --git a/ui/src/features/connections/ConnectionIntentInteractionBody.tsx b/ui/src/features/connections/ConnectionIntentInteractionBody.tsxnew file mode 100644index 0000000000..ab6653080e--- /dev/null+++ b/ui/src/features/connections/ConnectionIntentInteractionBody.tsx@@ -0,0 +1,334 @@+import { useCallback, useRef, useState } from "react";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import {+ CheckCircle2,+ Clock,+ Loader2,+ Plug,+ RotateCcw,+ XCircle,+} from "lucide-react";+import type { ConnectionIntentInteraction } from "@paperclipai/shared";+import { connectionIntentsApi } from "@/api/connection-intents";+import { AppLogo } from "@/pages/apps/AppLogo";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@/components/ui/dialog";+import {+ ConnectionSetupFlow,+ type ConnectionSetupCompletion,+} from "./ConnectionSetupFlow";++export interface ConnectionIntentInteractionBodyProps {+ interaction: ConnectionIntentInteraction;+ currentUserId?: string | null;+ addresseeLabel: string;+}++export function ConnectionIntentInteractionBody({+ interaction,+ currentUserId,+ addresseeLabel,+}: ConnectionIntentInteractionBodyProps) {+ const [open, setOpen] = useState(false);+ const focusTargetRef = useRef<HTMLDivElement>(null);+ const queryClient = useQueryClient();+ const isAddressee = Boolean(+ currentUserId && interaction.addresseeUserId === currentUserId,+ );+ const isPending = interaction.status === "pending";++ const invalidateTask = async (+ updatedInteraction?: ConnectionIntentInteraction,+ ) => {+ if (updatedInteraction) {+ queryClient.setQueriesData<ConnectionIntentInteraction[]>(+ { queryKey: ["issues", "interactions"] },+ (current) =>+ current?.map((candidate) =>+ candidate.id === updatedInteraction.id+ ? updatedInteraction+ : candidate,+ ),+ );+ }+ await Promise.all([+ // Task routes may key these caches by either UUID or human identifier.+ // Prefix invalidation reaches the mounted task without requiring that+ // routing identity to leak into the reusable interaction card.+ queryClient.invalidateQueries({ queryKey: ["issues", "interactions"] }),+ queryClient.invalidateQueries({ queryKey: ["issues", "detail"] }),+ ]);+ };+ const returnFocusToCard = () => {+ window.requestAnimationFrame(() => focusTargetRef.current?.focus());+ };++ const setupQuery = useQuery({+ queryKey: ["connection-intent", interaction.id, "setup-options"],+ queryFn: () => connectionIntentsApi.setupOptions(interaction.id),+ enabled: open && isAddressee && isPending,+ refetchInterval: open && isPending ? 2_000 : false,+ });++ const completeMutation = useMutation({+ mutationFn: (connectionId: string) =>+ connectionIntentsApi.complete(interaction.id, connectionId),+ onSuccess: async (updatedInteraction) => {+ await invalidateTask(updatedInteraction);+ setOpen(false);+ returnFocusToCard();+ },+ });+ const declineMutation = useMutation({+ mutationFn: () => connectionIntentsApi.decline(interaction.id),+ onSuccess: async (updatedInteraction) => {+ await invalidateTask(updatedInteraction);+ setOpen(false);+ returnFocusToCard();+ },+ });+ const phaseMutation = useMutation({+ mutationFn: (phase: ConnectionIntentInteraction["payload"]["phase"]) =>+ connectionIntentsApi.setPhase(interaction.id, phase),+ onSuccess: invalidateTask,+ });+ const mutatePhase = phaseMutation.mutate;+ const handlePhaseChange = useCallback(+ (phase: ConnectionIntentInteraction["payload"]["phase"]) =>+ mutatePhase(phase),+ [mutatePhase],+ );++ const finishNewConnection = async (completion: ConnectionSetupCompletion) => {+ if (completion.resolvedByCallback) {+ await invalidateTask();+ setOpen(false);+ returnFocusToCard();+ return;+ }+ completeMutation.mutate(completion.connectionId);+ };++ const resultOutcome = interaction.result?.outcome;+ const status =+ interaction.status === "accepted"+ ? {+ icon: CheckCircle2,+ title: `${interaction.payload.serviceName} connected`,+ body: `${interaction.payload.requestingAgentName} can use this connection on the continuation run.`,+ }+ : interaction.status === "rejected"+ ? {+ icon: XCircle,+ title: "Connection declined",+ body: `${interaction.payload.requestingAgentName} was notified and can continue without it.`,+ }+ : interaction.status === "expired"+ ? {+ icon: Clock,+ title:+ resultOutcome === "superseded"+ ? "Request superseded"+ : "Connection request expired",+ body:+ resultOutcome === "superseded"+ ? "A newer run requested this connection. Use the latest card instead."+ : "This request is no longer active.",+ }+ : null;+ const StatusIcon = status?.icon;++ if (status && StatusIcon) {+ return (+ <div+ ref={focusTargetRef}+ tabIndex={-1}+ data-testid="connection-intent-focus-target"+ >+ <div+ className="flex items-start gap-3"+ data-testid="connection-intent-terminal"+ >+ <StatusIcon className="mt-0.5 h-5 w-5 shrink-0 text-muted-foreground" />+ <div>+ <p className="font-medium text-foreground">{status.title}</p>+ <p className="mt-1 text-sm text-muted-foreground">{status.body}</p>+ </div>+ </div>+ </div>+ );+ }++ if (!isAddressee) {+ return (+ <div+ ref={focusTargetRef}+ tabIndex={-1}+ data-testid="connection-intent-focus-target"+ >+ <div+ className="flex items-start gap-3"+ data-testid="connection-intent-waiting"+ >+ <Clock className="mt-0.5 h-5 w-5 shrink-0 text-muted-foreground" />+ <div>+ <p className="font-medium text-foreground">+ Waiting for {addresseeLabel}+ </p>+ <p className="mt-1 text-sm text-muted-foreground">+ Only the addressed person can choose an identity or authorize this+ connection.+ </p>+ </div>+ </div>+ </div>+ );+ }++ const needsRetry = interaction.payload.phase === "needs_retry";+ const authorizing = interaction.payload.phase === "authorizing";++ return (+ <div+ ref={focusTargetRef}+ tabIndex={-1}+ data-testid="connection-intent-focus-target"+ >+ <div data-testid="connection-intent-actions">+ <div className="flex items-start gap-3">+ <AppLogo+ name={interaction.payload.serviceName}+ logoUrl={interaction.payload.serviceLogoUrl}+ darkLogoUrl={interaction.payload.serviceDarkLogoUrl}+ size={40}+ />+ <div>+ <p className="font-medium text-foreground">+ {interaction.payload.requestingAgentName} needs{" "}+ {interaction.payload.serviceName}+ </p>+ <p className="mt-1 text-sm text-muted-foreground">+ Connect your identity or reuse an eligible connection. Access is+ added only for this agent.+ </p>+ </div>+ </div>++ {needsRetry ? (+ <p className="mt-4 flex items-center gap-2 text-sm text-destructive">+ <RotateCcw className="h-4 w-4" />+ Authorization didn’t finish. Your previous choices are safe; try+ again.+ </p>+ ) : null}++ <div className="mt-4 flex flex-wrap gap-2">+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogTrigger asChild>+ <Button type="button" disabled={authorizing}>+ {authorizing ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <Plug className="h-4 w-4" />+ )}+ {authorizing+ ? "Authorizing…"+ : needsRetry+ ? "Try again"+ : "Connect / Use existing"}+ </Button>+ </DialogTrigger>+ <DialogContent+ className="!max-w-(--pct-90) max-h-(--sz-85vh) w-full overflow-y-auto sm:max-w-5xl"+ onCloseAutoFocus={(event) => {+ event.preventDefault();+ focusTargetRef.current?.focus();+ }}+ >+ <DialogHeader className="sr-only">+ <DialogTitle>+ Connect {interaction.payload.serviceName}+ </DialogTitle>+ <DialogDescription>+ Complete connection setup without leaving this task.+ </DialogDescription>+ </DialogHeader>+ {setupQuery.isLoading ? (+ <div className="flex min-h-48 items-center justify-center gap-2 text-sm text-muted-foreground">+ <Loader2 className="h-4 w-4 animate-spin" /> Loading+ connection options…+ </div>+ ) : setupQuery.isError ? (+ <div className="py-8 text-center">+ <p className="font-medium text-foreground">+ Couldn’t load connection setup+ </p>+ <p className="mt-1 text-sm text-muted-foreground">+ {setupQuery.error instanceof Error+ ? setupQuery.error.message+ : "Try again."}+ </p>+ <Button+ className="mt-4"+ variant="outline"+ onClick={() => setupQuery.refetch()}+ >+ Try again+ </Button>+ </div>+ ) : setupQuery.data ? (+ <ConnectionSetupFlow+ host="dialog"+ serviceSlug={interaction.payload.serviceSlug}+ requestedAgentId={setupQuery.data.requestedAgentId}+ interactionId={interaction.id}+ existingConnections={setupQuery.data.existingConnections}+ onUseExisting={async (connectionId) => {+ await completeMutation.mutateAsync(connectionId);+ }}+ onComplete={(completion) => {+ void finishNewConnection(completion);+ }}+ onOAuthDeclined={() => declineMutation.mutate()}+ onPhaseChange={handlePhaseChange}+ onCancel={() => setOpen(false)}+ />+ ) : null}+ </DialogContent>+ </Dialog>+ <Button+ type="button"+ variant="ghost"+ disabled={declineMutation.isPending || authorizing}+ onClick={() => declineMutation.mutate()}+ >+ Not now+ </Button>+ </div>++ {completeMutation.isError ||+ declineMutation.isError ||+ phaseMutation.isError ? (+ <p className="mt-3 text-sm text-destructive" role="alert">+ {(completeMutation.error ??+ declineMutation.error ??+ phaseMutation.error) instanceof Error+ ? (+ completeMutation.error ??+ declineMutation.error ??+ phaseMutation.error+ )?.message+ : "Couldn’t update this connection request."}+ </p>+ ) : null}+ </div>+ </div>+ );+}diff --git a/ui/src/features/connections/ConnectionSetupFlow.architecture.test.ts b/ui/src/features/connections/ConnectionSetupFlow.architecture.test.tsnew file mode 100644index 0000000000..ff337678b9--- /dev/null+++ b/ui/src/features/connections/ConnectionSetupFlow.architecture.test.ts@@ -0,0 +1,26 @@+import { readFileSync } from "node:fs";+import { describe, expect, it } from "vitest";++function source(relativePath: string) {+ return readFileSync(new URL(relativePath, import.meta.url), "utf8");+}++describe("shared connection setup architecture", () => {+ it("keeps both hosts thin and routes provider setup through ConnectionSetupFlow", () => {+ const pageHost = source("../../pages/apps/AppsConnect.tsx");+ const taskHost = source("./ConnectionIntentInteractionBody.tsx");++ for (const host of [pageHost, taskHost]) {+ expect(host).toContain("ConnectionSetupFlow");+ expect(host).not.toContain("CONNECTABLE_APP_DEFINITIONS");+ expect(host).not.toContain("ProviderCredentialField");+ expect(host).not.toContain("getAvailableConnectionMethods");+ expect(host).not.toContain("toolsApi.connectApp");+ expect(host).not.toContain("toolsApi.startOAuth");+ }++ expect(pageHost).not.toContain("connectionIntentsApi");+ expect(taskHost).not.toContain("connect-helpers");+ expect(taskHost).not.toContain("connect-ui");+ });+});diff --git a/ui/src/features/connections/ConnectionSetupFlow.oauth.test.ts b/ui/src/features/connections/ConnectionSetupFlow.oauth.test.tsnew file mode 100644index 0000000000..80e2c62b58--- /dev/null+++ b/ui/src/features/connections/ConnectionSetupFlow.oauth.test.ts@@ -0,0 +1,226 @@+// @vitest-environment jsdom++import { describe, expect, it } from "vitest";+import type { ToolApplication, ToolConnection } from "@paperclipai/shared";+import { getConnectableAppDefinition } from "@paperclipai/shared";+import {+ isConnectionDefinitionUnavailable,+ isVercelConnectUnavailable,+ readConnectionIntentOAuthOutcome,+ retainedReconnectMatches,+ requestedConnectionSetupResolution,+ requestedConnectionEntry,+} from "./ConnectionSetupFlow";++const origin = "https://paperclip.test";+const interactionId = "interaction-123";++function event(data: unknown, eventOrigin = origin) {+ return { origin: eventOrigin, data };+}++describe("connection intent OAuth window messages", () => {+ it.each(["connected", "declined", "failed"] as const)(+ "accepts a matching %s outcome",+ (outcome) => {+ expect(+ readConnectionIntentOAuthOutcome(+ event({+ type: "paperclip.connection-intent.oauth",+ interactionId,+ outcome,+ }),+ origin,+ interactionId,+ ),+ ).toBe(outcome);+ },+ );++ it.each([+ [+ "foreign origin",+ event(+ {+ type: "paperclip.connection-intent.oauth",+ interactionId,+ outcome: "connected",+ },+ "https://attacker.test",+ ),+ ],+ [+ "wrong interaction",+ event({+ type: "paperclip.connection-intent.oauth",+ interactionId: "other",+ outcome: "connected",+ }),+ ],+ [+ "wrong message type",+ event({ type: "other", interactionId, outcome: "connected" }),+ ],+ [+ "unknown outcome",+ event({+ type: "paperclip.connection-intent.oauth",+ interactionId,+ outcome: "authorized",+ }),+ ],+ ["non-object payload", event("connected")],+ ])("ignores a %s message", (_label, candidate) => {+ expect(+ readConnectionIntentOAuthOutcome(candidate, origin, interactionId),+ ).toBeNull();+ });+});++describe("retained reconnect definition lookup", () => {+ const connection = { applicationId: "app-1" } as ToolConnection;++ it("restores a hidden provider only for its exact retained application", () => {+ const githubApplication = {+ id: "app-1",+ applicationKey: "github",+ metadata: { sourceTemplateKey: "github" },+ } as unknown as ToolApplication;++ expect(requestedConnectionEntry({+ requestedAppKey: "github",+ galleryApps: [],+ reconnectConnection: connection,+ applications: [githubApplication],+ })?.slug).toBe("github");+ expect(requestedConnectionEntry({+ requestedAppKey: "notion",+ galleryApps: [],+ reconnectConnection: connection,+ applications: [githubApplication],+ })).toBeNull();+ });++ it("ends unavailable retained reconnects instead of leaving them loading", () => {+ expect(requestedConnectionSetupResolution({+ reconnectConnectionId: "connection-1",+ hasRequestedEntry: false,+ supportedMethodCount: 0,+ unsupportedOAuth: false,+ vercelUnavailable: false,+ definitionUnavailable: false,+ })).toBe("reconnect_unavailable");+ expect(requestedConnectionSetupResolution({+ reconnectConnectionId: "connection-1",+ hasRequestedEntry: true,+ supportedMethodCount: 0,+ unsupportedOAuth: false,+ vercelUnavailable: false,+ definitionUnavailable: false,+ })).toBe("reconnect_unavailable");+ expect(requestedConnectionSetupResolution({+ reconnectConnectionId: null,+ hasRequestedEntry: false,+ supportedMethodCount: 0,+ unsupportedOAuth: false,+ vercelUnavailable: false,+ definitionUnavailable: false,+ })).toBe("fallback");+ expect(requestedConnectionSetupResolution({+ reconnectConnectionId: "connection-1",+ hasRequestedEntry: true,+ supportedMethodCount: 1,+ unsupportedOAuth: false,+ vercelUnavailable: false,+ definitionUnavailable: false,+ })).toBe("ready");+ });++ it("does not expose a hidden provider without an exact reconnect target", () => {+ expect(requestedConnectionEntry({+ requestedAppKey: "github",+ galleryApps: [],+ reconnectConnection: null,+ applications: [],+ })).toBeNull();+ const visibleNotion = getConnectableAppDefinition("notion")!;+ expect(requestedConnectionEntry({+ requestedAppKey: "notion",+ galleryApps: [visibleNotion],+ reconnectConnection: null,+ applications: [],+ })).toBe(visibleNotion);+ });++ it("does not apply fresh-setup availability to an exact retained reconnect", () => {+ expect(isVercelConnectUnavailable({+ credentialSource: "vercel_connect",+ available: false,+ retainedReconnectMatches: true,+ })).toBe(false);+ expect(isVercelConnectUnavailable({+ credentialSource: "vercel_connect",+ available: false,+ retainedReconnectMatches: false,+ })).toBe(true);+ expect(isConnectionDefinitionUnavailable({+ available: false,+ reconnectConnectionId: "connection-1",+ reconnectSourceMatches: true,+ })).toBe(false);+ expect(isConnectionDefinitionUnavailable({+ available: false,+ reconnectConnectionId: "connection-1",+ reconnectSourceMatches: false,+ })).toBe(true);+ expect(isConnectionDefinitionUnavailable({+ available: false,+ reconnectConnectionId: undefined,+ reconnectSourceMatches: true,+ })).toBe(true);+ });+});++describe("retained reconnect target matching", () => {+ const connection = { applicationId: "app-1" } as ToolConnection;+ const application = { id: "app-1", applicationKey: "custom-mcp" } as ToolApplication;++ it("accepts a generic reconnect only for its exact retained application", () => {+ expect(retainedReconnectMatches({+ requestedAppKey: undefined,+ byo: true,+ applicationId: "app-1",+ reconnectConnection: connection,+ reconnectApplication: application,+ })).toBe(true);+ expect(retainedReconnectMatches({+ requestedAppKey: undefined,+ byo: true,+ applicationId: "app-other",+ reconnectConnection: connection,+ reconnectApplication: application,+ })).toBe(false);+ });++ it("keeps curated reconnects bound to their provider", () => {+ const curated = {+ id: "app-1",+ applicationKey: "github",+ metadata: { sourceTemplateKey: "github" },+ } as unknown as ToolApplication;+ expect(retainedReconnectMatches({+ requestedAppKey: "github",+ byo: false,+ applicationId: "app-1",+ reconnectConnection: connection,+ reconnectApplication: curated,+ })).toBe(true);+ expect(retainedReconnectMatches({+ requestedAppKey: "notion",+ byo: false,+ applicationId: "app-1",+ reconnectConnection: connection,+ reconnectApplication: curated,+ })).toBe(false);+ });+});diff --git a/ui/src/features/connections/ConnectionSetupFlow.tsx b/ui/src/features/connections/ConnectionSetupFlow.tsxnew file mode 100644index 0000000000..7c5249321a--- /dev/null+++ b/ui/src/features/connections/ConnectionSetupFlow.tsx@@ -0,0 +1,3811 @@+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useMutation, useQuery } from "@tanstack/react-query";+import {+ ArrowUpRight,+ Bot,+ Building2,+ Check,+ ChevronDown,+ ChevronRight,+ Copy,+ ClipboardPaste,+ Link2,+ Loader2,+ Lock,+ Search,+ ShieldCheck,+ TerminalSquare,+ UserRound,+ UsersRound,+} from "lucide-react";+import type { LucideIcon } from "lucide-react";+import type {+ Agent,+ AppDefinition,+ ConnectionGrantKind,+ ConnectionMethodDef,+ ConnectToolAppResult,+ FieldDef,+ ToolApplication,+ ToolConnection,+ ToolConnectionAuthKind,+ ToolConnectionCredentialSource,+ ToolConnectionCreateCapabilities,+} from "@paperclipai/shared";+import {+ connectionMethodAcceptsCustomerOAuthClient,+ connectionMethodRequiresConfiguration,+ connectionMethodSupportsAutomaticOAuth,+ credentialConfigPath,+ getAppDefinitionForUrl,+ getConnectableAppDefinition,+ getAvailableConnectionMethod,+ getAvailableConnectionMethods,+ getRecommendedConnectionMethod,+} from "@paperclipai/shared";+import { useNavigate, useParams, useSearchParams } from "@/lib/router";+import { useCompany } from "@/context/CompanyContext";+import { useBreadcrumbs } from "@/context/BreadcrumbContext";+import { useToast } from "@/context/ToastContext";+import { queryKeys } from "@/lib/queryKeys";+import { RadioCardGroup } from "@/components/ui/radio-card";+import { ApiError } from "@/api/client";+import { toolsApi } from "@/api/tools";+import { agentsApi } from "@/api/agents";+import { appCopyFor, credentialFieldLabel } from "@/lib/app-gallery-copy";+import { advancedTabHref } from "@/pages/tools/tool-tabs";+import { AgentIcon } from "@/components/AgentIconPicker";+import { AgentMultiSelect } from "@/components/AgentMultiSelect";+import { InlineBanner } from "@/components/InlineBanner";+import { Button } from "@/components/ui/button";+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";+import { Input } from "@/components/ui/input";+import { Textarea } from "@/components/ui/textarea";+import { ToggleSwitch } from "@/components/ui/toggle-switch";+import { Skeleton } from "@/components/ui/skeleton";+import { cn } from "@/lib/utils";+import { copyTextToClipboard } from "@/lib/clipboard";+import { resolveAuthorizationTarget } from "@/lib/authorizationUrl";+import { navigateTopLevel } from "@/lib/browserNavigation";+import { redactUrlSecrets } from "@/lib/redact-url-secrets";+import { AppLogo } from "@/pages/apps/AppLogo";+import { appApplicationSourceSlug } from "@/pages/apps/app-definition-display";+import { UnverifiedServerBadge } from "@/pages/apps/UnverifiedServerBadge";+import {+ appSourceConnectHref,+ isMcpDirectOAuthConnectSlug,+ resolveAppsConnectRouteKey,+ vercelConnectSourceHref,+} from "@/pages/apps/app-connect-policy";+import { parseGoogleSheetIds } from "@/pages/apps/google-sheets";+import { connectionNameForGrantKind } from "@/pages/apps/connection-identity";+import {+ canSubmitGenericConnect,+ customHeaderError,+ defaultGenericMcpName,+ endpointHost,+ genericConnectGuidance,+ genericConnectPayload,+ newCustomHeaderRow,+ oauthCallbackUrlForBrowser,+ type CustomHeaderRow,+ type GenericConnectDraft,+ type GenericConnectGuidance,+ type GenericMcpAuthMode,+} from "@/pages/apps/generic-mcp-connect";+import { autoExtendNotice, INSTALL_ALL_WARNING, installInfoNotice, installPayload } from "@/lib/tool-installs";++type Step = "gallery" | "access" | "key" | "success";+export type OAuthConnectPhase = "entry" | "starting" | "redirecting" | "error";++const ROUTE_STAGE_BY_STEP: Partial<Record<Step, string>> = {+ access: "access",+ key: "setup",+ success: "complete",+};++export function requestedConnectionEntry(input: {+ requestedAppKey: string;+ galleryApps: readonly AppDefinition[];+ reconnectConnection: ToolConnection | null;+ applications: readonly ToolApplication[];+}): AppDefinition | null {+ const visible = input.galleryApps.find((candidate) => candidate.slug === input.requestedAppKey);+ if (visible) return visible;+ if (!input.reconnectConnection) return null;+ const application = input.applications.find(+ (candidate) => candidate.id === input.reconnectConnection?.applicationId,+ );+ if (appApplicationSourceSlug(application) !== input.requestedAppKey) return null;+ return getConnectableAppDefinition(input.requestedAppKey);+}++export function retainedReconnectMatches(input: {+ requestedAppKey: string | undefined;+ byo: boolean;+ applicationId: string | undefined;+ reconnectConnection: ToolConnection | null;+ reconnectApplication: ToolApplication | null;+}): boolean {+ if (+ !input.reconnectConnection+ || !input.reconnectApplication+ || input.reconnectConnection.applicationId !== input.reconnectApplication.id+ ) return false;+ if (input.requestedAppKey) {+ return appApplicationSourceSlug(input.reconnectApplication) === input.requestedAppKey;+ }+ // Generic MCP applications intentionally have no provider slug. Their+ // reconnect URL instead carries the exact retained application identity.+ return input.byo && input.applicationId === input.reconnectApplication.id;+}++export function isVercelConnectUnavailable(input: {+ credentialSource: ToolConnectionCredentialSource;+ available: boolean;+ retainedReconnectMatches: boolean;+}): boolean {+ return input.credentialSource === "vercel_connect"+ && !input.available+ && !input.retainedReconnectMatches;+}++export function isConnectionDefinitionUnavailable(input: {+ available: boolean | undefined;+ reconnectConnectionId: string | null | undefined;+ reconnectSourceMatches: boolean;+}): boolean {+ return input.available === false+ && !(input.reconnectConnectionId && input.reconnectSourceMatches);+}++export function requestedConnectionSetupResolution(input: {+ reconnectConnectionId: string | null | undefined;+ hasRequestedEntry: boolean;+ supportedMethodCount: number;+ unsupportedOAuth: boolean;+ vercelUnavailable: boolean;+ definitionUnavailable: boolean;+}): "ready" | "fallback" | "reconnect_unavailable" {+ const unavailable = !input.hasRequestedEntry+ || input.supportedMethodCount === 0+ || input.unsupportedOAuth+ || input.vercelUnavailable+ || input.definitionUnavailable;+ if (!unavailable) return "ready";+ return input.reconnectConnectionId ? "reconnect_unavailable" : "fallback";+}++function appConnectHref(+ appKey: string,+ step: Step,+ credentialSource: ToolConnectionCredentialSource,+ existing?: {+ resumeConnectionId?: string | null;+ reconnectConnectionId?: string | null;+ interactionId?: string | null;+ },+): string {+ const stage = ROUTE_STAGE_BY_STEP[step] ?? "setup";+ const params = new URLSearchParams({ source: appKey, stage });+ if (existing?.resumeConnectionId) params.set("resume", existing.resumeConnectionId);+ if (existing?.reconnectConnectionId) params.set("reconnect", existing.reconnectConnectionId);+ if (existing?.interactionId) params.set("intent", existing.interactionId);+ const path = credentialSource === "vercel_connect" ? "/apps/vercel-connect" : "/apps/connect";+ return `${path}?${params.toString()}`;+}++function withConnectionIntent(href: string, interactionId?: string | null): string {+ if (!interactionId) return href;+ const [path, query = ""] = href.split("?", 2);+ const params = new URLSearchParams(query);+ params.set("intent", interactionId);+ return `${path}?${params.toString()}`;+}++type AppAccessSelection = "all_agents" | { agentIds: string[] };++// Access comes before credentials so the reader knows what identity and reach+// the secret is about to get before they share it (PAP-17835).+const STEP_LABELS = ["Pick app", "Access", "Add your key"];+const STEP_INDEX: Record<Exclude<Step, "success">, number> = {+ gallery: 0,+ access: 1,+ key: 2,+};+const ZAPIER_STEP_INDEX: Record<Exclude<Step, "gallery" | "success">, number> = {+ key: 0,+ access: 1,+};+const ZAPIER_STEP_LABELS = ["Add MCP URL"];++/**+ * Which identity a fresh connection should default to (PAP-17835).+ *+ * Company identity is the product default whenever the selected method permits+ * it. Personal-only methods still stay personal, and reconnects preserve their+ * original identity through the explicit reconnect hint.+ */+function defaultGrantKindFor(method: ConnectionMethodDef | null): ConnectionGrantKind {+ if (method?.grantKinds?.length === 1) return method.grantKinds[0]!;+ return "organization";+}++function isGoogleSheetsRobotMethod(+ entry: AppDefinition | null,+ method: ConnectionMethodDef | string | null | undefined,+): boolean {+ const methodKey = typeof method === "string" ? method : method?.key;+ return entry?.slug === "google-sheets" && methodKey === "local";+}++function defaultMethodConfig(method: ConnectionMethodDef | null): Record<string, string | boolean> {+ if (!method) return {};+ return Object.fromEntries(+ [...(method.tenantFields ?? []), ...(method.extensionFields ?? [])]+ .filter((field) => field.defaultValue !== undefined)+ .map((field) => [field.key, field.defaultValue!]),+ );+}++function connectionMethodsForCredentialSource(+ entry: AppDefinition | null | undefined,+ credentialSource: ToolConnectionCredentialSource,+): ConnectionMethodDef[] {+ if (!entry) return [];+ const methods = getAvailableConnectionMethods(entry);+ return credentialSource === "vercel_connect"+ ? methods.filter((method) => Boolean(method.credentialSources?.vercelConnect))+ : methods;+}++function recommendedSetupConnectionMethod(+ methods: readonly ConnectionMethodDef[],+): ConnectionMethodDef | null {+ const recommended = getRecommendedConnectionMethod(methods);+ // Capability choices (for example Google Workspace read versus write) have+ // an intentional default. Unrelated region/authentication variants should+ // still ask the operator to choose unless only one is available.+ return methods.length === 1 || recommended?.capabilityProfile+ ? recommended+ : null;+}++function canUseAutomaticOAuthFastPath(entry: AppDefinition | null | undefined): boolean {+ if (!entry) return false;+ const methods = getAvailableConnectionMethods(entry);+ const method = methods.length === 1 ? methods[0] : null;+ return Boolean(+ method+ && connectionMethodSupportsAutomaticOAuth(method)+ && !connectionMethodRequiresConfiguration(method),+ );+}++function automaticOAuthMethod(entry: AppDefinition | null | undefined): ConnectionMethodDef | null {+ if (!entry) return null;+ const methods = getAvailableConnectionMethods(entry);+ const method = methods.length === 1 ? methods[0] : null;+ return method && connectionMethodSupportsAutomaticOAuth(method) ? method : null;+}++function appSourceSlug(application: ToolApplication): string | null {+ const metadata = application.metadata;+ if (!metadata) return null;+ const source = metadata.sourceTemplateKey ?? metadata.galleryKey;+ return typeof source === "string" ? source : null;+}++function connectionSourceSlug(connection: ToolConnection): string | null {+ const source = connection.config?.sourceTemplateKey ?? connection.transportConfig.sourceTemplateKey;+ return typeof source === "string" ? source : null;+}++function reusableOAuthConnection(+ sourceSlug: string | null,+ applications: ToolApplication[],+ connections: ToolConnection[],+ options: { applicationId?: string; draftOnly?: boolean } = {},+): ToolConnection | null {+ if (!sourceSlug) return null;+ const matchingApplicationIds = new Set(+ applications+ .filter((application) =>+ application.status !== "archived" &&+ appSourceSlug(application) === sourceSlug &&+ (!options.applicationId || application.id === options.applicationId)+ )+ .map((application) => application.id),+ );+ return connections.find((connection) => {+ const matchesApplication = options.applicationId+ ? connection.applicationId === options.applicationId+ : matchingApplicationIds.has(connection.applicationId) || connectionSourceSlug(connection) === sourceSlug;+ return connection.status !== "archived" &&+ (!options.draftOnly || connection.status === "draft") &&+ connection.authKind === "oauth" &&+ matchesApplication;+ }) ?? null;+}++export type ConnectionSetupCompletion =+ | { connectionId: string; resolvedByCallback?: false }+ /** OAuth callbacks finalize server-side before notifying their opener. */+ | { resolvedByCallback: true };++export type ConnectionIntentOAuthOutcome = "connected" | "declined" | "failed";++export function readConnectionIntentOAuthOutcome(+ event: Pick<MessageEvent, "origin" | "data">,+ expectedOrigin: string,+ interactionId: string,+): ConnectionIntentOAuthOutcome | null {+ if (event.origin !== expectedOrigin || !event.data || typeof event.data !== "object") return null;+ const message = event.data as {+ type?: unknown;+ interactionId?: unknown;+ outcome?: unknown;+ };+ if (+ message.type !== "paperclip.connection-intent.oauth"+ || message.interactionId !== interactionId+ ) return null;+ return message.outcome === "connected"+ || message.outcome === "declined"+ || message.outcome === "failed"+ ? message.outcome+ : null;+}++export interface ConnectionSetupFlowProps {+ byoOnly?: boolean;+ credentialSource?: ToolConnectionCredentialSource;+ host?: "page" | "dialog";+ serviceSlug?: string;+ requestedAgentId?: string;+ interactionId?: string;+ existingConnections?: ToolConnection[];+ onUseExisting?: (connectionId: string) => Promise<void>;+ onComplete?: (result: ConnectionSetupCompletion) => void;+ onOAuthDeclined?: () => void;+ onPhaseChange?: (phase: "requested" | "authorizing" | "needs_retry") => void;+ onCancel?: () => void;+}++/**+ * The single connection setup implementation used by both the Apps store and+ * task-hosted connection intents. Hosts supply presentation and completion+ * callbacks; provider fields, validation, OAuth, access, and finishing remain+ * here so a provider can never drift between entry points.+ */+export function ConnectionSetupFlow({+ byoOnly = false,+ credentialSource = "paperclip_vault",+ host = "page",+ serviceSlug,+ requestedAgentId,+ interactionId,+ existingConnections = [],+ onUseExisting,+ onComplete,+ onOAuthDeclined,+ onPhaseChange,+ onCancel,+}: ConnectionSetupFlowProps = {}) {+ const routeNavigate = useNavigate();+ const navigate = useCallback((to: string, options?: { replace?: boolean }) => {+ if (host !== "page") return;+ if (options) routeNavigate(to, options);+ else routeNavigate(to);+ }, [host, routeNavigate]);+ const routeParams = useParams<{ appKey?: string }>();+ const { selectedCompany, selectedCompanyId } = useCompany();+ const { setBreadcrumbs } = useBreadcrumbs();+ const { pushToast } = useToast();+ const [searchParams] = useSearchParams();+ const connectionIntentId = interactionId?.trim()+ || searchParams.get("intent")?.trim()+ || null;+ const appKey = routeParams.appKey ?? searchParams.get("appKey") ?? undefined;+ const sourceSlug = searchParams.get("source")?.trim() || null;+ const createNewConnection = searchParams.get("new") === "1";+ const resumeConnectionId = searchParams.get("resume")?.trim() || null;+ const oauthCallbackOutcome = searchParams.get("oauth");+ const reconnectConnectionId = searchParams.get("reconnect")?.trim() || null;+ const reconnectGrantKindHint: ConnectionGrantKind | null = searchParams.get("identity") === "user"+ ? "user"+ : searchParams.get("identity") === "organization"+ ? "organization"+ : null;+ const vercelConnectMode = credentialSource === "vercel_connect";+ const directOAuthCandidate = serviceSlug ?? sourceSlug;+ const directOAuthSource = credentialSource === "paperclip_vault"+ && isMcpDirectOAuthConnectSlug(directOAuthCandidate)+ ? directOAuthCandidate+ : null;+ // `source` is the generic curated-app route contract, not an OAuth-only+ // shortcut. Manual OAuth, API-key, no-auth, and configured MCP definitions+ // must all enter the same branded setup flow when Browse links to them.+ const routeAppKey = resolveAppsConnectRouteKey({ serviceSlug, appKey, sourceSlug });+ const zapierSource = (serviceSlug ?? sourceSlug ?? appKey) === "zapier";+ const requestedAppKey = zapierSource ? undefined : routeAppKey;+ const byo = host === "page" && (byoOnly || searchParams.get("byo") === "1");++ // Prefill arrives from the app page for reconnects; read once so later+ // wizard navigation doesn't fight the URL.+ const [prefill] = useState(() => {+ const rawLink = searchParams.get("link")?.trim() ?? "";+ return {+ link: /^https?:\/\//i.test(rawLink) ? rawLink : "",+ name: searchParams.get("name")?.trim() ?? "",+ applicationId: searchParams.get("applicationId")?.trim() || undefined,+ };+ });++ const [step, setStep] = useState<Step>(requestedAppKey || prefill.link || zapierSource ? "key" : "gallery");+ const [entry, setEntry] = useState<AppDefinition | null>(null);+ const [galleryName, setGalleryName] = useState("");+ const [linkUrl, setLinkUrl] = useState(prefill.link);+ const [linkName, setLinkName] = useState(prefill.name || (zapierSource ? "Zapier" : ""));+ const [linkNeedsKey, setLinkNeedsKey] = useState(false);+ const [linkKey, setLinkKey] = useState("");+ // Generic ("connect your own MCP server") flow state. `authMode: auto` is the+ // simple path: Paperclip probes the endpoint and branches on what it finds.+ const [linkAuthMode, setLinkAuthMode] = useState<GenericMcpAuthMode>("auto");+ const [linkHeaders, setLinkHeaders] = useState<CustomHeaderRow[]>(() => [newCustomHeaderRow()]);+ const [linkOAuthClientId, setLinkOAuthClientId] = useState("");+ const [linkOAuthClientSecret, setLinkOAuthClientSecret] = useState("");+ const [linkAdvancedOpen, setLinkAdvancedOpen] = useState(false);+ const [linkGuidance, setLinkGuidance] = useState<GenericConnectGuidance | null>(null);+ const [genericOAuthPending, setGenericOAuthPending] = useState(false);+ const [credentials, setCredentials] = useState<Record<string, string>>({});+ const [curatedOAuthClientId, setCuratedOAuthClientId] = useState("");+ const [curatedOAuthClientSecret, setCuratedOAuthClientSecret] = useState("");+ const [vercelConnector, setVercelConnector] = useState("");+ const [connectionMethodKey, setConnectionMethodKey] = useState("");+ const [configValues, setConfigValues] = useState<Record<string, string | boolean>>({});+ const [googleSheetsLinks, setGoogleSheetsLinks] = useState("");+ const [googleSheetsError, setGoogleSheetsError] = useState<string | null>(null);+ const [connectResult, setConnectResult] = useState<ConnectToolAppResult | null>(null);+ const [enabled, setEnabled] = useState<Record<string, boolean>>({});+ const [access, setAccess] = useState<"all" | "specific">("all");+ const [agentIds, setAgentIds] = useState<Set<string>>(new Set());+ const [installAgentIds, setInstallAgentIds] = useState<Set<string>>(+ () => new Set(requestedAgentId ? [requestedAgentId] : []),+ );+ /**+ * Access-step selections (PAP-17835). These are chosen before the credential+ * and committed with it, so they must survive a failed submit and a trip+ * backwards through the wizard.+ */+ const [grantKind, setGrantKind] = useState<ConnectionGrantKind>(+ reconnectGrantKindHint ?? "organization",+ );+ const [installChoice, setInstallChoice] = useState<"specific" | "all">(+ requestedAgentId ? "specific" : "all",+ );+ const resumingAfterOAuthFailure = Boolean(+ resumeConnectionId+ && (oauthCallbackOutcome === "failed" || oauthCallbackOutcome === "denied"),+ );+ const [oauthPhase, setOAuthPhase] = useState<OAuthConnectPhase>(+ resumingAfterOAuthFailure ? "error" : "entry",+ );+ const [oauthError, setOAuthError] = useState<string | null>(() => {+ if (!resumingAfterOAuthFailure) return null;+ return oauthCallbackOutcome === "denied"+ ? "Authorization was cancelled or declined. Your saved connection was not changed."+ : "Authorization did not complete. Your saved connection is still here, so you can try again.";+ });+ /** Host of the page the operator is about to be sent to, shown while redirecting. */+ const [authorizationHost, setAuthorizationHost] = useState<string | null>(null);+ const directOAuthAccessConfirmedRef = useRef(false);+ const directOAuthRetryingRef = useRef(false);+ const hydratedResumeConnectionIdRef = useRef<string | null>(null);+ const [hydratedResumeConnectionId, setHydratedResumeConnectionId] = useState<string | null>(null);+ const oauthPopupRef = useRef<Window | null>(null);+ const [showConnectionChoice, setShowConnectionChoice] = useState(+ existingConnections.length > 0 && Boolean(onUseExisting),+ );+ const [existingConnectionPendingId, setExistingConnectionPendingId] = useState<string | null>(null);+ const [existingConnectionError, setExistingConnectionError] = useState<string | null>(null);+ const [unavailableReconnectId, setUnavailableReconnectId] = useState<string | null>(null);++ const reserveOAuthPopup = useCallback(() => {+ if (host !== "dialog" || oauthPopupRef.current?.closed === false) return;+ oauthPopupRef.current = window.open(+ "about:blank",+ "paperclip-connection-oauth",+ "popup,width=720,height=760,resizable=yes,scrollbars=yes",+ );+ }, [host]);++ const openAuthorization = useCallback((url: string) => {+ if (host !== "dialog") {+ navigateTopLevel(url);+ return;+ }+ const popup = oauthPopupRef.current;+ if (!popup || popup.closed) {+ setOAuthPhase("error");+ setOAuthError("Paperclip couldn’t open the sign-in window. Allow popups for this site and try again.");+ onPhaseChange?.("needs_retry");+ return;+ }+ popup.location.assign(url);+ popup.focus();+ }, [host, onPhaseChange]);++ useEffect(() => {+ if (host !== "dialog" || !connectionIntentId) return;+ const receiveOAuthOutcome = (event: MessageEvent) => {+ const outcome = readConnectionIntentOAuthOutcome(event, window.location.origin, connectionIntentId);+ if (outcome === "connected") {+ onComplete?.({ resolvedByCallback: true });+ return;+ }+ if (outcome === "declined") {+ onOAuthDeclined?.();+ return;+ }+ if (outcome !== "failed") return;+ setOAuthPhase("error");+ setOAuthError("Authorization did not complete. Try again when you’re ready.");+ };+ window.addEventListener("message", receiveOAuthOutcome);+ return () => window.removeEventListener("message", receiveOAuthOutcome);+ }, [connectionIntentId, host, onComplete, onOAuthDeclined]);++ const resetGenericAuthState = () => {+ setLinkAuthMode("auto");+ setLinkHeaders([newCustomHeaderRow()]);+ setLinkOAuthClientId("");+ setLinkOAuthClientSecret("");+ setLinkAdvancedOpen(false);+ setLinkGuidance(null);+ setGenericOAuthPending(false);+ };++ /**+ * Switch to a curated app's branded setup. Reached from the gallery grid and, as+ * a convenience, from the guided generic flow when the pasted endpoint matches a+ * definition — the generic path stays available either way.+ */+ const useMatchedGalleryEntry = (picked: AppDefinition) => {+ if (picked.slug === "zapier") {+ setEntry(null);+ setGalleryName("");+ setLinkUrl("");+ setLinkName("Zapier");+ setLinkNeedsKey(false);+ setLinkKey("");+ resetGenericAuthState();+ setCredentials({});+ setConnectResult(null);+ setStep("key");+ navigate(withConnectionIntent("/apps/connect?byo=1&source=zapier", connectionIntentId));+ return;+ }+ if (credentialSource === "paperclip_vault" && canUseAutomaticOAuthFastPath(picked)) {+ navigate(appSourceConnectHref(picked.slug, connectionIntentId));+ return;+ }+ setEntry(picked);+ setGalleryName(picked.name);+ setLinkUrl("");+ setLinkName("");+ setLinkNeedsKey(false);+ setLinkKey("");+ resetGenericAuthState();+ setCredentials({});+ setCuratedOAuthClientId("");+ setCuratedOAuthClientSecret("");+ setVercelConnector("");+ const methods = connectionMethodsForCredentialSource(picked, credentialSource);+ const initialMethod = recommendedSetupConnectionMethod(methods);+ setConnectionMethodKey(initialMethod?.key ?? "");+ setConfigValues(defaultMethodConfig(initialMethod));+ setGoogleSheetsLinks("");+ setGoogleSheetsError(null);+ setConnectResult(null);+ setInstallAgentIds(new Set(requestedAgentId ? [requestedAgentId] : []));+ setInstallChoice(requestedAgentId ? "specific" : "all");+ setGrantKind(reconnectGrantKind ?? defaultGrantKindFor(initialMethod));+ setStep("access");+ navigate(+ credentialSource === "vercel_connect"+ ? withConnectionIntent(vercelConnectSourceHref(picked.slug), connectionIntentId)+ : appSourceConnectHref(picked.slug, connectionIntentId),+ );+ };++ const openGallery = () => {+ setEntry(null);+ setGalleryName("");+ setLinkUrl("");+ setLinkName("");+ setLinkNeedsKey(false);+ setLinkKey("");+ resetGenericAuthState();+ setCredentials({});+ setCuratedOAuthClientId("");+ setCuratedOAuthClientSecret("");+ setVercelConnector("");+ setConnectionMethodKey("");+ setConfigValues({});+ setGoogleSheetsLinks("");+ setGoogleSheetsError(null);+ setConnectResult(null);+ setInstallAgentIds(new Set(requestedAgentId ? [requestedAgentId] : []));+ setInstallChoice(requestedAgentId ? "specific" : "all");+ setGrantKind("organization");+ setStep("gallery");+ navigate(withConnectionIntent(+ credentialSource === "vercel_connect"+ ? vercelConnectSourceHref()+ : byoOnly ? "/apps/byo" : "/apps/connect?byo=1",+ connectionIntentId,+ ));+ };++ useEffect(() => {+ if (host !== "page") return;+ setBreadcrumbs([+ { label: selectedCompany?.name ?? "Company", href: "/dashboard" },+ { label: "Apps", href: "/apps" },+ { label: vercelConnectMode ? "Vercel Connect" : byoOnly ? "Connect your own tool" : "Connect an app" },+ ]);+ return () => setBreadcrumbs([]);+ }, [byoOnly, host, setBreadcrumbs, selectedCompany?.name, vercelConnectMode]);++ const galleryQuery = useQuery({+ queryKey: queryKeys.apps.gallery(selectedCompanyId ?? "__none__"),+ queryFn: () => toolsApi.listGallery(selectedCompanyId!),+ enabled: !!selectedCompanyId,+ });+ const applicationsQuery = useQuery({+ queryKey: queryKeys.tools.applications(selectedCompanyId ?? "__none__"),+ queryFn: () => toolsApi.listApplications(selectedCompanyId!),+ enabled: !!selectedCompanyId && (!!directOAuthSource || !!resumeConnectionId || !!reconnectConnectionId),+ refetchOnMount: "always",+ });+ const connectionsQuery = useQuery({+ queryKey: queryKeys.tools.connections(selectedCompanyId ?? "__none__"),+ queryFn: () => toolsApi.listConnections(selectedCompanyId!),+ enabled: !!selectedCompanyId && (!!directOAuthSource || !!resumeConnectionId || !!reconnectConnectionId),+ refetchOnMount: "always",+ });+ const existingOAuthConnection = useMemo(+ () => reusableOAuthConnection(+ directOAuthSource,+ applicationsQuery.data?.applications ?? [],+ connectionsQuery.data?.connections ?? [],+ createNewConnection+ ? { applicationId: prefill.applicationId, draftOnly: true }+ : {},+ ),+ [applicationsQuery.data, connectionsQuery.data, createNewConnection, directOAuthSource, prefill.applicationId],+ );+ const reconnectConnection = useMemo(+ () => reconnectConnectionId+ ? (connectionsQuery.data?.connections ?? []).find((connection) => connection.id === reconnectConnectionId) ?? null+ : null,+ [connectionsQuery.data, reconnectConnectionId],+ );+ const reconnectApplication = useMemo(+ () => reconnectConnection+ ? (applicationsQuery.data?.applications ?? []).find(+ (application) => application.id === reconnectConnection.applicationId,+ ) ?? null+ : null,+ [applicationsQuery.data, reconnectConnection],+ );+ const reconnectSourceMatches = retainedReconnectMatches({+ requestedAppKey,+ byo,+ applicationId: prefill.applicationId,+ reconnectConnection,+ reconnectApplication,+ });+ const resumeConnection = useMemo(+ () => resumeConnectionId+ ? (connectionsQuery.data?.connections ?? []).find((connection) => connection.id === resumeConnectionId) ?? null+ : null,+ [connectionsQuery.data, resumeConnectionId],+ );+ const identityConnection = resumeConnection ?? reconnectConnection;+ const reconnectGrantKind: ConnectionGrantKind | null = identityConnection+ ? identityConnection.credentialPolicy === "per_user"+ ? "user"+ : "organization"+ : reconnectGrantKindHint;+ const resumableOAuthConnection = resumeConnection?.authKind === "oauth"+ ? resumeConnection+ : existingOAuthConnection;+ const existingOAuthGrantKind: ConnectionGrantKind | null = existingOAuthConnection+ ? existingOAuthConnection.credentialPolicy === "per_user"+ ? "user"+ : "organization"+ : null;+ const fixedGrantKind = reconnectGrantKind ?? existingOAuthGrantKind;++ useEffect(() => {+ if (fixedGrantKind) setGrantKind(fixedGrantKind);+ }, [fixedGrantKind]);++ // A curated definition covering the pasted endpoint is offered as a branded+ // convenience only; the generic flow remains the default and stays complete.+ const linkMatchedEntry = useMemo(+ () => (linkUrl && !entry ? getAppDefinitionForUrl(linkUrl, galleryQuery.data?.apps ?? []) : null),+ [entry, galleryQuery.data, linkUrl],+ );++ const entryAutomaticOAuthMethod = automaticOAuthMethod(entry);+ const automaticOAuthEntry = credentialSource === "paperclip_vault" && entryAutomaticOAuthMethod ? entry : null;+ const directOAuthEntry = credentialSource === "paperclip_vault" && canUseAutomaticOAuthFastPath(entry) ? entry : null;+ const directOAuthLookupPending = Boolean(directOAuthSource) && (+ !applicationsQuery.isFetchedAfterMount || !connectionsQuery.isFetchedAfterMount+ );++ const setAppStep = (nextStep: Step) => {+ setStep(nextStep);+ if (entry) {+ navigate(appConnectHref(entry.slug, nextStep, credentialSource, {+ resumeConnectionId,+ reconnectConnectionId,+ interactionId: connectionIntentId,+ }));+ }+ };++ const oauthStartMutation = useMutation({+ // Retry/reconnect reads identity from the durable connection. Provider is+ // not identity: an organization Notion connection must stay organization-+ // scoped, while a personal one must put its token back on that user grant.+ mutationFn: (connection: ToolConnection) => toolsApi.startOAuth(connection.id, {+ asCurrentUser: connection.credentialPolicy === "per_user",+ ...(connectionIntentId ? { interactionId: connectionIntentId } : {}),+ }),+ onSuccess: ({ authorizationUrl }) => {+ // The endpoint chose this address, so it is checked here too — this is the+ // line where an unsafe scheme would actually run (PAP-17099).+ const target = resolveAuthorizationTarget(authorizationUrl);+ if (!target.ok) {+ setOAuthPhase("error");+ setOAuthError(target.message);+ onPhaseChange?.("needs_retry");+ return;+ }+ setAuthorizationHost(target.host);+ setOAuthPhase("redirecting");+ openAuthorization(target.url);+ },+ onError: (error) => {+ const details = error instanceof ApiError && error.body && typeof error.body === "object"+ ? (error.body as { details?: { code?: unknown } }).details+ : null;+ setOAuthPhase("error");+ onPhaseChange?.("needs_retry");+ setOAuthError(+ details?.code === "invalid_grant"+ ? "Your authorization expired or was revoked. Reconnect to continue."+ : error instanceof Error+ ? error.message+ : "Paperclip couldn’t start secure sign-in. Try again.",+ );+ },+ });+ const mutateOAuthStart = oauthStartMutation.mutate;+ const startOAuth = useCallback((connection: ToolConnection) => {+ onPhaseChange?.("authorizing");+ reserveOAuthPopup();+ mutateOAuthStart(connection);+ }, [mutateOAuthStart, onPhaseChange, reserveOAuthPopup]);++ /**+ * Commit the Access step's agent reach for a connection. Shared by the+ * key-path finish and the OAuth redirect, so both routes through the wizard+ * apply the same selection.+ */+ const applyAccessInstalls = async (connectionId: string) => {+ const installState = installChoice === "all"+ ? { onAll: true, agentIds: new Set<string>() }+ : { onAll: false, agentIds: installAgentIds };+ await toolsApi.putConnectionInstalls(connectionId, installPayload(selectedCompanyId!, installState));+ };++ const effectiveGrantKind = fixedGrantKind ?? grantKind;+ const connectMutation = useMutation({+ mutationFn: async (entryOverride?: AppDefinition) => {+ const connectEntry = entryOverride ?? entry;+ let result: ConnectToolAppResult;+ if (connectEntry) {+ const requestedGrantKind = fixedGrantKind ?? grantKind;+ const selectedMethod = getAvailableConnectionMethod(connectEntry, connectionMethodKey || null);+ const sheetIds = isGoogleSheetsRobotMethod(connectEntry, selectedMethod)+ ? parseGoogleSheetIds(googleSheetsLinks).ids+ : [];+ const trimmedGalleryName = galleryName.trim();+ const connectionName = connectionNameForGrantKind(+ trimmedGalleryName || connectEntry.name,+ requestedGrantKind,+ );+ result = await toolsApi.connectApp(selectedCompanyId!, {+ galleryKey: connectEntry.slug,+ ...(connectionMethodKey ? { connectionMethodKey } : {}),+ name: connectionName,+ credentialSource,+ ...(credentialSource === "paperclip_vault" ? { credentialValues: credentials } : {}),+ ...(credentialSource === "vercel_connect"+ ? { vercelConnect: { connector: vercelConnector.trim() } }+ : {}),+ ...(curatedOAuthClientId.trim()+ ? {+ oauthClient: {+ clientId: curatedOAuthClientId.trim(),+ ...(curatedOAuthClientSecret ? { clientSecret: curatedOAuthClientSecret } : {}),+ },+ }+ : {}),+ configValues: isGoogleSheetsRobotMethod(connectEntry, selectedMethod)+ ? { allowedSpreadsheetIds: sheetIds }+ : Object.keys(configValues).length > 0+ ? configValues+ : undefined,+ applicationId: prefill.applicationId,+ ...(resumeConnectionId ? { resumeConnectionId } : {}),+ ...(requestedGrantKind === "user" ? { grantKind: requestedGrantKind } : {}),+ });+ } else {+ const genericPayload = genericConnectPayload({+ link: linkUrl,+ name: linkName,+ authMode: linkAuthMode,+ needsKey: linkNeedsKey,+ keyValue: linkKey,+ headers: linkHeaders,+ oauthClientId: linkOAuthClientId,+ oauthClientSecret: linkOAuthClientSecret,+ });+ const connectionName = connectionNameForGrantKind(+ genericPayload.name ?? defaultGenericMcpName(linkUrl) ?? "Custom app",+ effectiveGrantKind,+ );+ result = await toolsApi.connectApp(selectedCompanyId!, {+ ...genericPayload,+ // Zapier issues a credential-bearing URL, so its branded setup keeps+ // the compact pasted-URL step. It is still a curated app, though: the+ // gallery identity must reach the server or Browse can only see a+ // generic `link` application after setup succeeds.+ ...(zapierSource || linkMatchedEntry?.slug === "zapier"+ ? {+ galleryKey: "zapier",+ connectionMethodKey: "generated-url",+ }+ : {}),+ name: connectionName,+ applicationId: prefill.applicationId,+ ...(effectiveGrantKind === "user" ? { grantKind: effectiveGrantKind } : {}),+ });+ }+ // A resumable draft already owns its identity and install reach. Replacing+ // those choices with this page's defaults would turn "finish setup" into a+ // silent access change. Fresh connections still persist the Access step+ // before the browser leaves Paperclip.+ if (result.auth?.kind === "oauth" && !resumeConnectionId && !reconnectConnectionId) {+ await applyAccessInstalls(result.connectionId);+ }+ return result;+ },+ onSuccess: (result) => {+ if (result.auth?.kind === "oauth") {+ setConnectResult(result);+ // The mutation saves the Access selection before this callback opens+ // the provider, so the authorization handoff cannot outrun agent reach.+ // Discovery worked but this authorization server insists on a client the+ // operator registers themselves. Keep the draft and ask for it in place+ // rather than sending them back to the start.+ if (result.auth.manualClientRequired) {+ setLinkGuidance(genericConnectGuidance("oauth_manual_client_required", null));+ setLinkAuthMode("oauth");+ setLinkAdvancedOpen(true);+ setGenericOAuthPending(false);+ return;+ }+ if (host === "dialog") {+ setOAuthPhase("starting");+ setGenericOAuthPending(!entry);+ startOAuth(result.connection);+ return;+ }+ const startUrl = result.auth.startUrl?.trim();+ if (!startUrl) {+ setOAuthPhase("starting");+ setGenericOAuthPending(true);+ startOAuth(result.connection);+ return;+ }+ const target = resolveAuthorizationTarget(startUrl);+ if (!target.ok) {+ setGenericOAuthPending(true);+ setOAuthPhase("error");+ setOAuthError(target.message);+ onPhaseChange?.("needs_retry");+ return;+ }+ setAuthorizationHost(target.host);+ setOAuthPhase("redirecting");+ setGenericOAuthPending(true);+ openAuthorization(target.url);+ return;+ }+ setLinkGuidance(null);+ setConnectResult(result);+ const defaults: Record<string, boolean> = {};+ for (const a of result.actions.readOnly) defaults[a.catalogEntryId] = true;+ for (const a of result.actions.canMakeChanges) defaults[a.catalogEntryId] = true;+ setEnabled(defaults);+ finishMutation.mutate({ result, enabled: defaults });+ },+ onError: (error) => {+ const details = error instanceof ApiError && error.body && typeof error.body === "object"+ ? (error.body as { details?: { code?: unknown } }).details+ : null;+ if (automaticOAuthEntry) {+ setOAuthPhase("error");+ onPhaseChange?.("needs_retry");+ setOAuthError(+ details?.code === "invalid_grant"+ ? "Your authorization expired or was revoked. Reconnect to continue."+ : error instanceof Error+ ? error.message+ : "Paperclip couldn’t start secure sign-in. Try again.",+ );+ return;+ }+ // The generic URL path explains the specific corrective action inline,+ // beside the fields the operator has to change. A toast can't do that, and+ // for a pasted address "check your key" is usually the wrong advice.+ if (!entry && linkUrl) {+ const code = typeof details?.code === "string" ? details.code : null;+ const guidance = genericConnectGuidance(code, error instanceof Error ? error.message : null);+ setLinkGuidance(guidance);+ setGenericOAuthPending(false);+ if (guidance.focus === "credentials") setLinkAdvancedOpen(true);+ return;+ }+ pushToast({+ title: "Couldn’t connect",+ body: error instanceof Error ? error.message : "Please check your key and try again.",+ tone: "error",+ });+ },+ });+ const mutateConnect = connectMutation.mutate;+ const connectApp = useCallback((entryOverride?: AppDefinition) => {+ const connectEntry = entryOverride ?? entry;+ const method = connectEntry+ ? getAvailableConnectionMethod(connectEntry, connectionMethodKey || null)+ : null;+ if (method?.auth === "oauth") {+ reserveOAuthPopup();+ }+ mutateConnect(entryOverride);+ }, [connectionMethodKey, entry, mutateConnect, reserveOAuthPopup]);++ useEffect(() => {+ if (!requestedAppKey || galleryQuery.isLoading || !galleryQuery.data) return;++ if (reconnectConnectionId && (+ !connectionsQuery.isFetchedAfterMount+ || !applicationsQuery.isFetchedAfterMount+ )) return;++ const requestedEntry = requestedConnectionEntry({+ requestedAppKey,+ galleryApps: galleryQuery.data.apps,+ reconnectConnection,+ applications: applicationsQuery.data?.applications ?? [],+ });+ const methods = connectionMethodsForCredentialSource(requestedEntry, credentialSource);+ const method = methods.length === 1 ? methods[0]! : null;+ const automaticOAuth = credentialSource === "paperclip_vault" && Boolean(automaticOAuthMethod(requestedEntry));+ const vercelUnavailable = isVercelConnectUnavailable({+ credentialSource,+ available: galleryQuery.data.credentialSources?.vercelConnect.available === true,+ retainedReconnectMatches: Boolean(reconnectConnectionId && reconnectSourceMatches),+ });+ const unsupportedOAuth = methods.length === 1+ && method?.auth === "oauth"+ && !connectionMethodSupportsAutomaticOAuth(method)+ && !connectionMethodAcceptsCustomerOAuthClient(method);+ const definitionUnavailable = isConnectionDefinitionUnavailable({+ available: requestedEntry?.availability?.available,+ reconnectConnectionId,+ reconnectSourceMatches,+ });+ const setupResolution = requestedConnectionSetupResolution({+ reconnectConnectionId,+ hasRequestedEntry: Boolean(requestedEntry),+ supportedMethodCount: methods.length,+ unsupportedOAuth,+ vercelUnavailable,+ definitionUnavailable,+ });+ if (setupResolution !== "ready") {+ setEntry(null);+ setStep("gallery");+ if (setupResolution === "reconnect_unavailable" && reconnectConnectionId) {+ setUnavailableReconnectId(reconnectConnectionId);+ return;+ }+ navigate(withConnectionIntent(+ credentialSource === "vercel_connect" ? vercelConnectSourceHref() : "/apps/connect",+ connectionIntentId,+ ), { replace: true });+ return;+ }+ setUnavailableReconnectId(null);+ if (!requestedEntry) return;++ if (entry?.slug !== requestedEntry.slug) {+ setEntry(requestedEntry);+ setGalleryName(requestedEntry.name);+ setLinkUrl("");+ setLinkName("");+ setLinkNeedsKey(false);+ setLinkKey("");+ setCredentials({});+ setCuratedOAuthClientId("");+ setCuratedOAuthClientSecret("");+ setVercelConnector("");+ const initialMethod = recommendedSetupConnectionMethod(methods);+ setConnectionMethodKey(initialMethod?.key ?? "");+ setConfigValues(defaultMethodConfig(initialMethod));+ setGoogleSheetsLinks("");+ setGoogleSheetsError(null);+ setConnectResult(null);+ setGrantKind(reconnectGrantKind ?? defaultGrantKindFor(initialMethod));+ setInstallAgentIds(new Set(requestedAgentId ? [requestedAgentId] : []));+ setInstallChoice(requestedAgentId ? "specific" : "all");+ // Route/service selection initializes the wizard once. Later renders must+ // preserve the user's current step in both hosts instead of snapping back+ // to Access after they continue.+ setStep(resumeConnectionId ? "key" : "access");+ }++ if (automaticOAuth && (+ !applicationsQuery.isFetchedAfterMount ||+ !connectionsQuery.isFetchedAfterMount+ )) return;+ if (automaticOAuth && directOAuthRetryingRef.current) return;+ if (automaticOAuth && (applicationsQuery.isError || connectionsQuery.isError)) {+ setOAuthPhase("error");+ setOAuthError("Paperclip couldn’t check for an existing connection. Try again.");+ setStep("key");+ return;+ }+ }, [+ applicationsQuery.isError,+ applicationsQuery.isFetchedAfterMount,+ applicationsQuery.data,+ connectionsQuery.isError,+ connectionsQuery.isFetchedAfterMount,+ credentialSource,+ entry?.slug,+ galleryQuery.data,+ galleryQuery.isLoading,+ navigate,+ reconnectGrantKind,+ reconnectConnection,+ reconnectConnectionId,+ reconnectSourceMatches,+ resumeConnectionId,+ requestedAppKey,+ requestedAgentId,+ ]);++ // Resume the exact method and non-secret provider configuration that the+ // interrupted draft already chose. Secrets are intentionally never read back+ // into the browser; credential-based methods ask for a replacement value.+ useEffect(() => {+ hydratedResumeConnectionIdRef.current = null;+ setHydratedResumeConnectionId(null);+ }, [resumeConnectionId]);++ useEffect(() => {+ if (+ !resumeConnection+ || !entry+ || resumeConnection.status !== "draft"+ || hydratedResumeConnectionIdRef.current === resumeConnection.id+ ) return;+ const storedConfig = resumeConnection.config && typeof resumeConnection.config === "object"+ ? resumeConnection.config+ : {};+ const storedSource = typeof storedConfig.sourceTemplateKey === "string"+ ? storedConfig.sourceTemplateKey+ : null;+ if (storedSource && storedSource !== entry.slug) return;++ const storedMethodKey = typeof storedConfig.connectionMethodKey === "string"+ ? storedConfig.connectionMethodKey+ : null;+ const resumedMethod = storedMethodKey+ ? connectionMethodsForCredentialSource(entry, credentialSource).find(+ (candidate) => candidate.key === storedMethodKey,+ ) ?? null+ : null;+ setGalleryName(resumeConnection.name || entry.name);+ if (resumedMethod) {+ setConnectionMethodKey(resumedMethod.key);+ const storedMethodConfig = storedConfig.methodConfig && typeof storedConfig.methodConfig === "object"+ ? storedConfig.methodConfig as Record<string, unknown>+ : {};+ setConfigValues({+ ...defaultMethodConfig(resumedMethod),+ ...Object.fromEntries(+ Object.entries(storedMethodConfig).filter(+ (entry): entry is [string, string | boolean] =>+ typeof entry[1] === "string" || typeof entry[1] === "boolean",+ ),+ ),+ });+ }+ const storedOAuth = storedConfig.oauth && typeof storedConfig.oauth === "object"+ ? storedConfig.oauth as Record<string, unknown>+ : null;+ // Only an operator-owned client belongs in the editable Advanced fields.+ // Rehydrating a DCR/CIMD client id there would submit it as customer-owned+ // and corrupt the automatic registration's provenance on the next click.+ if (+ storedOAuth?.clientRegistrationSource === "manual"+ && typeof storedOAuth.clientId === "string"+ ) {+ setCuratedOAuthClientId(storedOAuth.clientId);+ }+ // A draft exists only after the first half of setup has been saved. Resume+ // at the credential/provider checkpoint instead of asking for identity and+ // agent reach again. Automatic OAuth renders the dedicated one-action+ // screen; configured methods render their saved setup form with secrets+ // intentionally blank.+ if (oauthCallbackOutcome === "failed" || oauthCallbackOutcome === "denied") {+ setOAuthPhase("error");+ setOAuthError(+ oauthCallbackOutcome === "denied"+ ? "Authorization was cancelled or declined. Your saved connection was not changed."+ : "Authorization did not complete. Your saved connection is still here, so you can try again.",+ );+ } else {+ setOAuthPhase("entry");+ setOAuthError(null);+ }+ setStep("key");+ hydratedResumeConnectionIdRef.current = resumeConnection.id;+ setHydratedResumeConnectionId(resumeConnection.id);+ }, [credentialSource, entry, oauthCallbackOutcome, resumeConnection]);++ /**+ * Commit the connection: action defaults, agent reach, and installs.+ *+ * Takes the connect result and the enabled set as arguments rather than+ * reading them from state. The Access step removed the separate who/install+ * screens, so this now runs in the same tick as the `setConnectResult` /+ * `setEnabled` that precede it, where that state has not been applied yet.+ */+ const finishMutation = useMutation({+ mutationFn: async (input: { result: ConnectToolAppResult; enabled: Record<string, boolean> }) => {+ const { result: connected, enabled: enabledMap } = input;+ const enabledIds = Object.entries(enabledMap)+ .filter(([, on]) => on)+ .map(([id]) => id);+ const askFirstRiskLevels = new Set(+ Array.isArray(connected.suggestedDefaults.askFirstRiskLevels)+ ? connected.suggestedDefaults.askFirstRiskLevels.filter(+ (riskLevel): riskLevel is string => typeof riskLevel === "string",+ )+ : [],+ );+ const askFirstIds = connected.actions.canMakeChanges+ .filter((action) => enabledMap[action.catalogEntryId] && askFirstRiskLevels.has(action.riskLevel))+ .map((action) => action.catalogEntryId);+ // The Access step asks one question about agent reach, so profile access+ // and installs are committed to the same target set instead of drifting+ // apart behind two separate wizard screens.+ const selection: AppAccessSelection = installChoice === "all"+ ? "all_agents"+ : { agentIds: Array.from(installAgentIds) };+ const finished = await toolsApi.finishApp(selectedCompanyId!, connected.connectionId, {+ enabledCatalogEntryIds: enabledIds,+ askFirstCatalogEntryIds: askFirstIds,+ access: selection,+ });+ await applyAccessInstalls(connected.connectionId);+ return finished;+ },+ onSuccess: (_finished, input) => {+ setAppStep("success");+ onComplete?.({ connectionId: input.result.connectionId });+ },+ onError: (error) => {+ // Creation must feel transactional: a failed commit returns the operator+ // to Access with their identity and agent selections intact rather than+ // stranding them on a half-made connection.+ setAppStep("access");+ pushToast({+ title: "Couldn’t finish setup",+ body: error instanceof Error ? error.message : "Please try again.",+ tone: "error",+ });+ },+ });++ if (!selectedCompanyId) {+ return <div className="p-6 text-sm text-muted-foreground">Select a company to connect apps.</div>;+ }++ if (+ (resumeConnectionId || reconnectConnectionId)+ && (connectionsQuery.isError || applicationsQuery.isError)+ ) {+ return (+ <div className="mx-auto max-w-xl rounded-xl border border-border bg-card p-6">+ <h2 className="text-lg font-semibold text-foreground">Couldn’t load connection setup</h2>+ <p className="mt-2 text-sm text-muted-foreground">+ Paperclip couldn’t check the retained connection. The retained connection was not changed.+ </p>+ <div className="mt-5 flex flex-wrap gap-2">+ <Button+ type="button"+ onClick={async () => {+ const [connectionsResult, applicationsResult] = await Promise.all([+ connectionsQuery.refetch(),+ applicationsQuery.refetch(),+ ]);+ if (!connectionsResult.isError && !applicationsResult.isError) {+ setOAuthError(null);+ setOAuthPhase("entry");+ }+ }}+ >+ Try again+ </Button>+ <Button type="button" variant="outline" onClick={() => navigate("/apps")}>+ Back to apps+ </Button>+ </div>+ </div>+ );+ }++ if (resumeConnectionId && connectionsQuery.isFetchedAfterMount && !resumeConnection) {+ return (+ <div className="mx-auto max-w-xl rounded-xl border border-border bg-card p-6">+ <h2 className="text-lg font-semibold text-foreground">This setup can’t be resumed</h2>+ <p className="mt-2 text-sm text-muted-foreground">+ The saved connection no longer exists or is not available to this company.+ </p>+ <Button type="button" variant="outline" className="mt-5" onClick={() => navigate("/apps")}>+ Back to apps+ </Button>+ </div>+ );+ }++ if (+ reconnectConnectionId+ && connectionsQuery.isFetchedAfterMount+ && applicationsQuery.isFetchedAfterMount+ && (!reconnectConnection || !reconnectSourceMatches)+ ) {+ return (+ <div className="mx-auto max-w-xl rounded-xl border border-border bg-card p-6">+ <h2 className="text-lg font-semibold text-foreground">This connection can’t be reconnected</h2>+ <p className="mt-2 text-sm text-muted-foreground">+ {!reconnectConnection+ ? "The retained connection no longer exists or is not available to this company."+ : "This reconnect link does not match the retained connection's provider."}+ </p>+ <Button type="button" variant="outline" className="mt-5" onClick={() => navigate("/apps")}>+ Back to apps+ </Button>+ </div>+ );+ }++ if ((resumeConnectionId || reconnectConnectionId) && galleryQuery.isError) {+ return (+ <div className="mx-auto max-w-xl rounded-xl border border-border bg-card p-6">+ <h2 className="text-lg font-semibold text-foreground">Couldn’t load connection setup</h2>+ <p className="mt-2 text-sm text-muted-foreground">+ Paperclip couldn’t load the provider details needed to restore this connection. The retained connection was not changed.+ </p>+ <div className="mt-5 flex flex-wrap gap-2">+ <Button type="button" onClick={() => void galleryQuery.refetch()}>+ Try again+ </Button>+ <Button type="button" variant="outline" onClick={() => navigate("/apps")}>+ Back to apps+ </Button>+ </div>+ </div>+ );+ }++ if (reconnectConnectionId && unavailableReconnectId === reconnectConnectionId) {+ return (+ <div className="mx-auto max-w-xl rounded-xl border border-border bg-card p-6">+ <h2 className="text-lg font-semibold text-foreground">This connection can’t be reconnected</h2>+ <p className="mt-2 text-sm text-muted-foreground">+ Paperclip no longer has a supported setup method for this retained connection. The retained connection was not changed.+ </p>+ <Button type="button" variant="outline" className="mt-5" onClick={() => navigate("/apps")}>+ Back to apps+ </Button>+ </div>+ );+ }++ if (resumeConnectionId && (+ !connectionsQuery.isFetchedAfterMount+ || galleryQuery.isLoading+ || !entry+ || hydratedResumeConnectionId !== resumeConnection?.id+ )) {+ return (+ <div className="mx-auto max-w-xl space-y-4" aria-label="Loading saved connection setup">+ <Skeleton className="h-8 w-48" />+ <Skeleton className="h-40 w-full rounded-xl" />+ </div>+ );+ }++ if (reconnectConnectionId && (+ !connectionsQuery.isFetchedAfterMount+ || !applicationsQuery.isFetchedAfterMount+ || galleryQuery.isLoading+ || Boolean(requestedAppKey && !entry)+ )) {+ return (+ <div className="mx-auto max-w-xl space-y-4" aria-label="Loading retained connection setup">+ <Skeleton className="h-8 w-48" />+ <Skeleton className="h-40 w-full rounded-xl" />+ </div>+ );+ }++ if (showConnectionChoice && onUseExisting) {+ return (+ <div className="max-w-5xl" data-testid="connection-existing-choice">+ <div className="mb-6">+ <h1 className="text-2xl font-bold tracking-tight">+ Use an existing {requestedAppKey ? "connection" : "app connection"}+ </h1>+ <p className="mt-1 text-sm text-muted-foreground">+ Reuse a connection without changing who already has access, or connect a new one.+ </p>+ </div>+ <div className="space-y-2">+ {existingConnections.map((connection) => (+ <button+ key={connection.id}+ type="button"+ className="flex w-full items-center justify-between gap-4 rounded-lg border border-border bg-card p-4 text-left transition-colors hover:bg-accent disabled:cursor-not-allowed disabled:opacity-60"+ disabled={existingConnectionPendingId !== null}+ onClick={async () => {+ setExistingConnectionPendingId(connection.id);+ setExistingConnectionError(null);+ try {+ await onUseExisting(connection.id);+ } catch (error) {+ setExistingConnectionError(error instanceof Error ? error.message : "Couldn’t use this connection.");+ setExistingConnectionPendingId(null);+ }+ }}+ >+ <span>+ <span className="block font-medium text-foreground">{connection.name}</span>+ <span className="mt-1 block text-xs text-muted-foreground">+ {connection.status === "active" && connection.enabled ? "Ready to use" : "Setup needs attention"}+ </span>+ </span>+ {existingConnectionPendingId === connection.id ? (+ <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />+ ) : (+ <ChevronRight className="h-4 w-4 text-muted-foreground" />+ )}+ </button>+ ))}+ </div>+ {existingConnectionError ? (+ <InlineBanner tone="danger" className="mt-4">{existingConnectionError}</InlineBanner>+ ) : null}+ <div className="mt-5 flex flex-wrap gap-2">+ <Button type="button" variant="outline" onClick={() => setShowConnectionChoice(false)}>+ Connect new+ </Button>+ {onCancel ? <Button type="button" variant="ghost" onClick={onCancel}>Cancel</Button> : null}+ </div>+ </div>+ );+ }++ const showCuratedOAuthState = Boolean(+ automaticOAuthEntry+ && step === "key"+ && (directOAuthEntry || oauthPhase !== "entry"),+ );++ if (showCuratedOAuthState && automaticOAuthEntry) {+ return (+ <OAuthConnectStateScreen+ entry={automaticOAuthEntry}+ resuming={Boolean(resumeConnectionId)}+ phase={oauthPhase}+ error={oauthError}+ authorizationHost={authorizationHost}+ onRetry={async () => {+ setOAuthError(null);+ setOAuthPhase("starting");+ const connection = connectResult?.connection ?? resumableOAuthConnection;+ if (connection) {+ startOAuth(connection);+ return;+ }++ // The create request may have reached the server even when its+ // response did not reach the browser. Re-read both resources before+ // creating again so Retry resumes that durable draft instead of+ // duplicating it.+ directOAuthRetryingRef.current = true;+ try {+ const [applicationsResult, connectionsResult] = await Promise.all([+ applicationsQuery.refetch(),+ connectionsQuery.refetch(),+ ]);+ if (applicationsResult.isError || connectionsResult.isError) {+ setOAuthPhase("error");+ setOAuthError("Paperclip couldn’t check for an existing connection. Try again.");+ return;+ }+ const refreshedResumeConnection = resumeConnectionId+ ? (connectionsResult.data?.connections ?? []).find(+ (candidate) => candidate.id === resumeConnectionId && candidate.authKind === "oauth",+ ) ?? null+ : null;+ const refreshedConnection = refreshedResumeConnection ?? reusableOAuthConnection(+ directOAuthSource,+ applicationsResult.data?.applications ?? [],+ connectionsResult.data?.connections ?? [],+ createNewConnection+ ? { applicationId: prefill.applicationId, draftOnly: true }+ : {},+ );+ if (!directOAuthAccessConfirmedRef.current && !resumeConnectionId) {+ if (refreshedConnection) {+ setGrantKind(refreshedConnection.credentialPolicy === "per_user" ? "user" : "organization");+ }+ setOAuthPhase("entry");+ setOAuthError(null);+ setStep("access");+ return;+ }+ if (refreshedConnection) {+ startOAuth(refreshedConnection);+ } else {+ connectMutation.mutate(automaticOAuthEntry);+ }+ } finally {+ directOAuthRetryingRef.current = false;+ }+ }}+ onCancel={onCancel ?? (() => navigate("/apps/browse"))}+ />+ );+ }++ // A pasted endpoint that needs browser sign-in gets the same waiting/retry+ // screen a curated OAuth app does, minus the branding it doesn't have.+ if (genericOAuthPending && !entry && linkUrl && step === "key") {+ return (+ <OAuthConnectStateScreen+ identity={{+ name: linkName.trim() || endpointHost(linkUrl) || "this server",+ unverifiedHost: endpointHost(linkUrl),+ }}+ phase={oauthPhase}+ error={oauthError}+ authorizationHost={authorizationHost}+ onRetry={() => {+ setOAuthError(null);+ const connection = connectResult?.connection;+ if (connection) {+ setOAuthPhase("starting");+ startOAuth(connection);+ return;+ }+ // No draft to resume, so fall back to the setup screen rather than+ // creating a second connection for the same endpoint.+ setGenericOAuthPending(false);+ setOAuthPhase("entry");+ }}+ onCancel={() => {+ setGenericOAuthPending(false);+ setOAuthPhase("entry");+ setOAuthError(null);+ }}+ />+ );+ }++ const appName =+ connectResult?.application.name ??+ entry?.name ??+ (linkName.trim() || defaultGenericMcpName(linkUrl) || "this app");+ const credentialSourceMethods = connectionMethodsForCredentialSource(entry, credentialSource);+ const credentialSourceApps = vercelConnectMode+ ? (galleryQuery.data?.apps ?? []).filter(+ (app) => connectionMethodsForCredentialSource(app, credentialSource).length > 0,+ )+ : galleryQuery.data?.apps ?? [];+ const zapierEntry = zapierSource+ ? galleryQuery.data?.apps.find((app) => app.slug === "zapier") ?? null+ : null;+ const stepLabels = zapierSource+ ? ZAPIER_STEP_LABELS+ : entry && credentialSourceMethods.length > 1+ ? ["Pick app", "Access", "Choose connection"]+ : entry && credentialSourceMethods[0]?.auth === "oauth"+ ? ["Pick app", "Access", "Sign in"]+ : isGoogleSheetsRobotMethod(entry, connectionMethodKey)+ ? ["Pick app", "Access", "Share sheet"]+ : STEP_LABELS;+ // The Access step's identity question only makes sense when there *is* a+ // credential, so it reads the selected method's auth kind.+ const accessStepMethod = entry+ ? (connectionMethodKey+ ? credentialSourceMethods.find((m) => m.key === connectionMethodKey) ?? null+ : credentialSourceMethods[0] ?? null)+ : null;+ const accessStepAuthKind: ToolConnectionAuthKind = entry+ ? accessStepMethod?.auth ?? "none"+ : linkAuthMode === "none"+ ? "none"+ : linkAuthMode === "oauth"+ ? "oauth"+ : "api_key";+ // The primary label names the next effect, so an OAuth handoff never arrives+ // unannounced.+ const accessMethodIsKnown = !entry+ || Boolean(connectionMethodKey)+ || credentialSourceMethods.length === 1;+ const accessSubmitLabel = accessStepAuthKind === "oauth" && accessMethodIsKnown+ ? `Continue to ${entry?.name ?? "sign-in"}`+ : "Save and continue";++ const stepIndex = zapierSource && step !== "gallery" && step !== "success"+ ? ZAPIER_STEP_INDEX[step]+ : step === "success"+ ? stepLabels.length+ : STEP_INDEX[step];++ return (+ <div className="max-w-5xl">+ {step !== "success" && (+ !(byoOnly && step === "gallery") && (+ <StepHeader+ subtitle={+ step === "gallery"+ ? vercelConnectMode+ ? "Choose a reviewed app to connect through Vercel."+ : "Pick the app you want your agents to use."+ : `Step ${stepIndex + 1} of ${stepLabels.length}`+ }+ step={step}+ activeIndex={stepIndex}+ labels={stepLabels}+ appIdentity={+ zapierSource+ ? { name: "Zapier", logoUrl: zapierEntry?.branding.logoUrl ?? null, darkLogoUrl: zapierEntry?.branding.darkLogoUrl ?? null }+ : entry && step !== "gallery"+ ? { name: entry.name, logoUrl: entry.branding.logoUrl, darkLogoUrl: entry.branding.darkLogoUrl ?? null }+ : undefined+ }+ unverifiedHost={!entry && !zapierSource && step !== "gallery" ? endpointHost(linkUrl) : null}+ onCancel={onCancel ?? (() => navigate("/apps"))}+ />+ )+ )}++ {step === "gallery" && (+ <GalleryStep+ loading={galleryQuery.isLoading}+ apps={credentialSourceApps}+ vercelConnect={vercelConnectMode}+ vercelConnectAvailability={galleryQuery.data?.credentialSources?.vercelConnect ?? null}+ byo={byo}+ byoOnly={byoOnly}+ source={searchParams.get("source")}+ onPick={useMatchedGalleryEntry}+ onUseLink={(url) => {+ const matchedEntry = getAppDefinitionForUrl(url, galleryQuery.data?.apps ?? []);+ setEntry(null);+ setGalleryName("");+ setLinkUrl(url);+ setLinkName(matchedEntry?.name ?? defaultGenericMcpName(url) ?? "");+ setLinkNeedsKey(false);+ setLinkKey("");+ setCredentials({});+ setGoogleSheetsLinks("");+ setGoogleSheetsError(null);+ setInstallAgentIds(new Set());+ setInstallChoice("all");+ setGrantKind(reconnectGrantKind ?? "organization");+ setStep("key");+ }}+ onRunYourOwn={() => navigate(advancedTabHref("run-your-own"))}+ onPasteConfig={() => navigate(advancedTabHref("paste-config"))}+ />+ )}++ {step === "key" && entry && (+ <KeyStep+ entry={entry}+ name={galleryName}+ onNameChange={setGalleryName}+ values={credentials}+ onChange={setCredentials}+ oauthClientId={curatedOAuthClientId}+ onOAuthClientIdChange={setCuratedOAuthClientId}+ oauthClientSecret={curatedOAuthClientSecret}+ onOAuthClientSecretChange={setCuratedOAuthClientSecret}+ credentialSource={credentialSource}+ vercelConnector={vercelConnector}+ onVercelConnectorChange={setVercelConnector}+ vercelConnectAvailability={galleryQuery.data?.credentialSources?.vercelConnect ?? null}+ methodKey={connectionMethodKey}+ onMethodChange={(nextMethod) => {+ setConnectionMethodKey(nextMethod?.key ?? "");+ if (!reconnectGrantKind) {+ setGrantKind(defaultGrantKindFor(nextMethod));+ }+ setCredentials({});+ setCuratedOAuthClientId("");+ setCuratedOAuthClientSecret("");+ setVercelConnector("");+ setConfigValues(defaultMethodConfig(nextMethod));+ }}+ configValues={configValues}+ onConfigChange={setConfigValues}+ googleSheetsLinks={googleSheetsLinks}+ googleSheetsError={googleSheetsError}+ onGoogleSheetsLinksChange={(next) => {+ setGoogleSheetsLinks(next);+ setGoogleSheetsError(null);+ }}+ submitting={connectMutation.isPending}+ // Back returns to Access, not to the gallery: the design requires the+ // identity and agent selections to survive moving backward, and+ // `openGallery` resets them.+ onBack={() => {+ if (resumeConnectionId || reconnectConnectionId) {+ navigate("/apps");+ return;+ }+ setAppStep("access");+ }}+ onConnect={() => {+ if (isGoogleSheetsRobotMethod(entry, connectionMethodKey)) {+ const parsed = parseGoogleSheetIds(googleSheetsLinks);+ if (parsed.invalidCount > 0) {+ setGoogleSheetsError("That doesn't look like a Google Sheets link.");+ return;+ }+ if (parsed.ids.length === 0) {+ setGoogleSheetsError("Paste at least one Google Sheets link.");+ return;+ }+ }+ const selectedMethod = getAvailableConnectionMethod(entry, connectionMethodKey || null);+ const selectedMethodHasProviderFields = Boolean(+ selectedMethod?.credentialFields?.length+ || selectedMethod?.tenantFields?.some((field) => !field.hidden)+ || selectedMethod?.extensionFields?.some((field) => !field.hidden),+ );+ if (+ selectedMethod+ && connectionMethodSupportsAutomaticOAuth(selectedMethod)+ && resumableOAuthConnection+ && !selectedMethodHasProviderFields+ && !curatedOAuthClientId.trim()+ ) {+ directOAuthAccessConfirmedRef.current = true;+ setOAuthError(null);+ setOAuthPhase("starting");+ startOAuth(resumableOAuthConnection);+ return;+ }+ if (selectedMethod && connectionMethodSupportsAutomaticOAuth(selectedMethod)) {+ directOAuthAccessConfirmedRef.current = true;+ setOAuthError(null);+ setOAuthPhase("starting");+ }+ connectApp();+ }}+ />+ )}++ {step === "key" && !entry && linkUrl && !zapierSource && (+ <LinkConnectStep+ link={linkUrl}+ name={linkName}+ onNameChange={setLinkName}+ needsKey={linkNeedsKey}+ onNeedsKeyChange={(next) => {+ setLinkNeedsKey(next);+ if (!next) setLinkKey("");+ }}+ keyValue={linkKey}+ onKeyChange={setLinkKey}+ authMode={linkAuthMode}+ onAuthModeChange={(next) => {+ setLinkAuthMode(next);+ setLinkGuidance(null);+ // Leaving the simple path means the explicit choice governs; drop the+ // "does it need a key?" answer so the two can't disagree.+ if (next !== "auto") setLinkNeedsKey(false);+ if (next !== "bearer" && next !== "auto") setLinkKey("");+ }}+ headers={linkHeaders}+ onHeadersChange={(next) => {+ setLinkHeaders(next);+ setLinkGuidance(null);+ }}+ oauthClientId={linkOAuthClientId}+ onOAuthClientIdChange={setLinkOAuthClientId}+ oauthClientSecret={linkOAuthClientSecret}+ onOAuthClientSecretChange={setLinkOAuthClientSecret}+ advancedOpen={linkAdvancedOpen}+ onAdvancedOpenChange={setLinkAdvancedOpen}+ guidance={linkGuidance}+ matchedEntry={linkMatchedEntry}+ onUseMatchedEntry={linkMatchedEntry ? () => useMatchedGalleryEntry(linkMatchedEntry) : undefined}+ submitting={connectMutation.isPending || genericOAuthPending}+ onBack={() => setStep("gallery")}+ onConnect={() => {+ setLinkGuidance(null);+ connectMutation.mutate(undefined);+ }}+ />+ )}++ {step === "key" && !entry && zapierSource && (+ <ZapierConnectStep+ link={linkUrl}+ onLinkChange={setLinkUrl}+ submitting={connectMutation.isPending}+ onBack={() => navigate("/apps")}+ onConnect={() => connectMutation.mutate(undefined)}+ />+ )}++ {step === "access" && (+ <AccessStep+ appName={appName}+ providerName={entry?.name ?? appName}+ companyId={selectedCompanyId}+ authKind={accessStepAuthKind}+ grantKinds={fixedGrantKind ? [fixedGrantKind] : accessStepMethod?.grantKinds}+ grantKind={effectiveGrantKind}+ setGrantKind={setGrantKind}+ installChoice={installChoice}+ setInstallChoice={setInstallChoice}+ installAgentIds={installAgentIds}+ setInstallAgentIds={setInstallAgentIds}+ lockedAgentId={requestedAgentId}+ capabilities={galleryQuery.data?.capabilities}+ guidance={accessStepMethod?.guidanceMd}+ warnings={accessStepMethod?.warnings}+ setupPrerequisite={entry?.setupPrerequisite}+ docsUrl={accessStepMethod?.consoleLinks?.docs ?? entry?.docsUrl}+ submitLabel={accessSubmitLabel}+ identityLoading={Boolean(automaticOAuthEntry) && directOAuthLookupPending}+ preserveAgentAccess={Boolean(automaticOAuthEntry && (resumableOAuthConnection || reconnectConnection))}+ pending={connectMutation.isPending || oauthStartMutation.isPending}+ // Leaving Access abandons the app choice entirely, so this resets the+ // draft and returns to the gallery the operator came from.+ onBack={() => (entry || linkUrl ? openGallery() : navigate("/apps"))}+ onContinue={() => {+ if (directOAuthEntry) {+ directOAuthAccessConfirmedRef.current = true;+ setOAuthError(null);+ setOAuthPhase("starting");+ setAppStep("key");+ if (resumableOAuthConnection) startOAuth(resumableOAuthConnection);+ else connectApp(directOAuthEntry);+ return;+ }+ if (entry) setAppStep("key");+ else setStep("key");+ }}+ />+ )}++ {step === "success" && (+ <SuccessStep+ appName={appName}+ logoUrl={entry?.branding.logoUrl}+ darkLogoUrl={entry?.branding.darkLogoUrl}+ summary={accessSummaryLines({+ grantKind: effectiveGrantKind,+ authKind: accessStepAuthKind,+ installChoice,+ installCount: installAgentIds.size,+ enabledCount: Object.values(enabled).filter(Boolean).length,+ })}+ onDone={onCancel ?? (() => navigate("/apps/connections"))}+ />+ )}+ </div>+ );+}++function StepHeader({+ subtitle,+ step,+ activeIndex,+ labels,+ appIdentity,+ unverifiedHost,+ onCancel,+}: {+ subtitle: string;+ step: Step;+ activeIndex: number;+ labels: string[];+ appIdentity?: { name: string; logoUrl: string | null; darkLogoUrl?: string | null };+ /**+ * Host of an unknown remote MCP server. Present for the whole generic flow so+ * the operator can see whose server they are configuring at every step, not+ * just on the screen where they pasted the address.+ */+ unverifiedHost?: string | null;+ onCancel: () => void;+}) {+ return (+ <div className="mb-6">+ <div className="flex items-start justify-between gap-4">+ <div className="flex items-center gap-3">+ {appIdentity ? (+ <AppLogo name={appIdentity.name} logoUrl={appIdentity.logoUrl} darkLogoUrl={appIdentity.darkLogoUrl} size={44} />+ ) : null}+ <div>+ <h1 className="text-2xl font-bold tracking-tight">+ {appIdentity ? `Connect ${appIdentity.name}` : "Connect an app"}+ </h1>+ <p className="mt-1 text-sm text-muted-foreground">{subtitle}</p>+ {unverifiedHost ? <UnverifiedServerBadge host={unverifiedHost} className="mt-2" /> : null}+ </div>+ </div>+ <Button variant="ghost" size="sm" onClick={onCancel}>+ Cancel+ </Button>+ </div>+ {step !== "gallery" && (+ <div className="mt-4">+ <div className="flex gap-2">+ {labels.map((label, i) => (+ <div+ key={label}+ className={cn("h-1 w-20 rounded-full", i <= activeIndex ? "bg-foreground" : "bg-border")}+ />+ ))}+ </div>+ <div className="mt-2 text-xs text-muted-foreground">{labels.join(" · ")}</div>+ </div>+ )}+ </div>+ );+}++export function OAuthConnectStateScreen({+ entry,+ identity,+ resuming = false,+ phase,+ error,+ authorizationHost,+ onRetry,+ onCancel,+}: {+ /** A curated app. Omit for a generic endpoint and pass `identity` instead. */+ entry?: AppDefinition | null;+ /** Identity for an unknown remote MCP server: its own name plus its host. */+ identity?: { name: string; unverifiedHost: string | null };+ /** This screen is continuing a durable draft rather than creating a new one. */+ resuming?: boolean;+ phase: OAuthConnectPhase;+ error?: string | null;+ /**+ * Host of the authorization page being opened. A valid HTTPS authorization+ * page can still be a phishing page, so the operator sees exactly which host+ * they are being handed to (PAP-17099).+ */+ authorizationHost?: string | null;+ onRetry: () => void;+ onCancel: () => void;+}) {+ const serverName = entry?.name ?? identity?.name ?? "this server";+ const unverifiedHost = entry ? null : identity?.unverifiedHost ?? null;+ const status = phase === "entry"+ ? {+ title: resuming+ ? `Finish connecting ${serverName}`+ : `Connect ${serverName} to Paperclip`,+ body: resuming+ ? `Your connection is saved. Continue in ${serverName} to approve access; its identity and agent access will stay the same.`+ : `Paperclip will open ${serverName} so you can choose a workspace and approve access.`,+ }+ : phase === "starting"+ ? {+ title: "Preparing secure sign-in",+ body: `Paperclip is creating a secure ${serverName} connection.`,+ }+ : phase === "redirecting"+ ? {+ title: `Opening ${serverName}`,+ body: authorizationHost+ ? `Continue at ${authorizationHost} to choose a workspace and approve access. Only approve access if you recognize that address.`+ : `Continue in ${serverName} to choose a workspace and approve access.`,+ }+ : {+ title: `${serverName} couldn’t connect`,+ body: error ?? "Paperclip couldn’t start secure sign-in. Try again.",+ };++ return (+ <div className="max-w-5xl">+ <StepHeader+ subtitle="Secure MCP sign-in"+ step="key"+ activeIndex={1}+ labels={["Access", "Sign in", "Ready"]}+ appIdentity={entry ? { name: entry.name, logoUrl: entry.branding.logoUrl, darkLogoUrl: entry.branding.darkLogoUrl } : undefined}+ unverifiedHost={unverifiedHost}+ onCancel={onCancel}+ />+ <div className="mx-auto max-w-xl rounded-2xl border border-border bg-card p-8">+ <div className="flex items-start gap-3">+ <span className="mt-1 inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border border-border bg-background">+ {phase === "error" ? (+ <Link2 className="h-5 w-5 text-destructive" />+ ) : phase === "entry" ? (+ <Lock className="h-5 w-5 text-muted-foreground" />+ ) : (+ <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />+ )}+ </span>+ <div className="min-w-0">+ <h2 className="text-xl font-bold tracking-tight">{status.title}</h2>+ <p className="mt-1 text-sm text-muted-foreground">{status.body}</p>+ {unverifiedHost ? <UnverifiedServerBadge host={unverifiedHost} className="mt-2" /> : null}+ </div>+ </div>++ <div className="mt-6 flex items-center gap-2">+ {phase === "error" || phase === "entry" ? (+ <Button type="button" onClick={onRetry}>+ {phase === "entry"+ ? resuming ? `Finish with ${serverName}` : `Continue to ${serverName}`+ : "Try again"}+ </Button>+ ) : (+ <Button type="button" disabled>+ {phase === "redirecting" ? `Opening ${serverName}…` : "Preparing…"}+ </Button>+ )}+ <Button type="button" variant="ghost" onClick={onCancel}>Back to apps</Button>+ </div>+ <p className="mt-5 flex items-center gap-1.5 text-xs text-muted-foreground">+ <Lock className="h-3.5 w-3.5" />+ Your authorization stays in Paperclip’s encrypted secret store.+ </p>+ </div>+ </div>+ );+}++function ZapierConnectStep({+ link,+ onLinkChange,+ submitting,+ onBack,+ onConnect,+}: {+ link: string;+ onLinkChange: (next: string) => void;+ submitting: boolean;+ onBack: () => void;+ onConnect: () => void;+}) {+ const normalizedLink = normalizeAppLink(link);+ const zapierHostname = normalizedLink ? new URL(normalizedLink).hostname : "";+ const isZapierLink = zapierHostname === "zapier.com" || zapierHostname.endsWith(".zapier.com");++ return (+ <div className="mx-auto max-w-xl rounded-2xl border border-border bg-card p-8">+ <div className="flex items-start gap-3">+ <span className="mt-1 inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border border-border bg-background">+ <Link2 className="h-5 w-5 text-muted-foreground" />+ </span>+ <div className="min-w-0">+ <h2 className="text-xl font-bold tracking-tight">Connect Zapier</h2>+ <p className="mt-1 text-sm text-muted-foreground">+ Paste the complete MCP URL Zapier gives you, including its token.+ </p>+ </div>+ </div>++ <div className="mt-8">+ <label className="text-sm font-medium text-foreground">Zapier MCP URL</label>+ <Input+ type="password"+ autoComplete="off"+ spellCheck={false}+ value={link}+ onChange={(event) => onLinkChange(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter" && isZapierLink && !submitting) onConnect();+ }}+ placeholder="https://mcp.zapier.com/api/v1/connect?token=…"+ className="mt-2 h-11"+ autoFocus+ />+ <p className="mt-2 text-xs text-muted-foreground">+ The token is part of the URL. Paperclip stores it securely and checks the connection before enabling actions.+ </p>+ {link.trim() && !isZapierLink && (+ <p className="mt-2 text-xs text-destructive">Paste a valid Zapier URL to continue.</p>+ )}+ </div>++ <div className="mt-8 flex items-center justify-between">+ <Button variant="ghost" onClick={onBack} disabled={submitting}>+ Back+ </Button>+ <Button onClick={onConnect} disabled={submitting || !isZapierLink}>+ {submitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}+ {submitting ? "Checking…" : "Check link"}+ </Button>+ </div>+ </div>+ );+}++function GalleryStep({+ loading,+ apps,+ byo = false,+ byoOnly = false,+ vercelConnect = false,+ vercelConnectAvailability = null,+ source = null,+ onPick,+ onUseLink,+ onRunYourOwn,+ onPasteConfig,+}: {+ loading: boolean;+ apps: AppDefinition[];+ /** Entered via the "Connect your own MCP server" card (PAP-12371, Finding C): focus the link path. */+ byo?: boolean;+ /** Canonical BYO page: keep the URL path and alternate methods, without the app gallery. */+ byoOnly?: boolean;+ /** Isolated Vercel catalog: no native-provider or bring-your-own setup paths. */+ vercelConnect?: boolean;+ vercelConnectAvailability?: {+ available: boolean;+ manageUrl: string;+ reason: string | null;+ } | null;+ source?: string | null;+ onPick: (entry: AppDefinition) => void;+ onUseLink: (link: string) => void;+ onRunYourOwn: () => void;+ onPasteConfig: () => void;+}) {+ const [search, setSearch] = useState("");+ const [linkInput, setLinkInput] = useState("");+ const [linkError, setLinkError] = useState<string | null>(null);+ const linkSectionRef = useRef<HTMLDivElement>(null);+ const linkInputRef = useRef<HTMLInputElement>(null);+ const linkInputSelectedRef = useRef(false);++ // Arriving from the BYO card: scroll the URL section into view and select its+ // input so the operator can paste immediately.+ useEffect(() => {+ if (!byo || (loading && !byoOnly) || linkInputSelectedRef.current) return;+ if (!byoOnly) linkSectionRef.current?.scrollIntoView?.({ block: "center" });+ linkInputRef.current?.focus();+ linkInputRef.current?.select();+ linkInputSelectedRef.current = true;+ }, [byo, byoOnly, loading]);+ const filtered = useMemo(() => {+ const q = search.trim().toLowerCase();+ if (!q) return apps;+ return apps.filter((a) => a.name.toLowerCase().includes(q));+ }, [apps, search]);+ const normalizedLink = normalizeAppLink(linkInput);+ const matchedEntry = normalizedLink ? getAppDefinitionForUrl(normalizedLink, apps) : null;+ const zapierSource = source === "zapier";++ const continueWithLink = () => {+ const next = normalizeAppLink(linkInput);+ if (!next) {+ setLinkError("Paste a full http or https link.");+ return;+ }+ setLinkError(null);+ onUseLink(next);+ };++ if (loading && !byoOnly) {+ return (+ <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">+ {Array.from({ length: 8 }).map((_, i) => (+ <Skeleton key={i} className="h-32 w-full rounded-xl" />+ ))}+ </div>+ );+ }++ return (+ <div className="space-y-6">+ {vercelConnect ? (+ <div className="rounded-xl border border-border bg-card p-5">+ <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">+ <div>+ <h2 className="text-lg font-bold tracking-tight">Connect through Vercel</h2>+ <p className="mt-1 max-w-2xl text-sm text-muted-foreground">+ Create and manage the provider connector in Vercel. Paperclip stores its reference and applies agent access, policy, approval, and audit controls here.+ </p>+ </div>+ {vercelConnectAvailability ? (+ <Button asChild variant="outline" size="sm" className="shrink-0">+ <a href={vercelConnectAvailability.manageUrl} target="_blank" rel="noreferrer">+ Open Vercel Connect+ <ArrowUpRight className="ml-2 h-3.5 w-3.5" />+ </a>+ </Button>+ ) : null}+ </div>+ {vercelConnectAvailability?.available === false ? (+ <InlineBanner tone="danger" compact className="mt-4">+ {vercelConnectAvailability.reason ?? "Vercel Connect is unavailable on this instance."}+ </InlineBanner>+ ) : null}+ </div>+ ) : null}++ {!byoOnly && (+ <>+ <div className="relative">+ <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />+ <Input+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder="Search apps…"+ className="h-11 pl-9"+ />+ </div>++ <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">+ {filtered.map((app) => {+ const copy = appCopyFor(app.slug, app.description);+ const methods = getAvailableConnectionMethods(app);+ const oauthBlocked = methods.length === 0 || methods.every((candidate) =>+ candidate.auth === "oauth"+ && !connectionMethodSupportsAutomaticOAuth(candidate)+ && !connectionMethodAcceptsCustomerOAuthClient(candidate)+ );+ const unavailable = app.availability?.available === false+ || (vercelConnect && vercelConnectAvailability?.available !== true);+ return (+ <button+ key={app.slug}+ type="button"+ disabled={oauthBlocked || unavailable}+ title={+ unavailable+ ? app.availability?.reason ?? vercelConnectAvailability?.reason ?? undefined+ : undefined+ }+ onClick={() => onPick(app)}+ className={cn(+ "flex flex-col rounded-xl border border-border bg-card p-4 text-left transition-colors",+ oauthBlocked || unavailable ? "cursor-not-allowed opacity-60" : "hover:border-foreground/30 hover:bg-accent/40",+ )}+ >+ <AppLogo name={app.name} logoUrl={app.branding.logoUrl} darkLogoUrl={app.branding.darkLogoUrl} size={36} />+ <div className="mt-3 text-sm font-bold text-foreground">{app.name}</div>+ <div className="mt-1 line-clamp-2 text-xs text-muted-foreground">{copy.tagline}</div>+ <div className="mt-3 text-xs font-semibold text-foreground">+ {unavailable ? (+ <span className="text-muted-foreground">+ {app.availability?.reason ?? vercelConnectAvailability?.reason ?? "Unavailable on this instance."}+ </span>+ ) : oauthBlocked ? (+ <span className="text-muted-foreground">Unavailable</span>+ ) : (+ <span>Connect →</span>+ )}+ </div>+ </button>+ );+ })}+ </div>++ {filtered.length === 0 && (+ <div className="py-10 text-center text-sm text-muted-foreground">No apps match “{search}”.</div>+ )}+ </>+ )}++ {!vercelConnect ? <div+ ref={linkSectionRef}+ className={cn(+ "grid gap-4 border-t border-border pt-5 md:grid-cols-(--gtc-13)",+ byo && "-mx-3 rounded-xl border border-primary/40 bg-primary/[0.04] px-3 pb-4 md:mx-0",+ )}+ >+ <div>+ <div className="flex items-center gap-2 text-sm font-semibold text-foreground">+ <Link2 className="h-4 w-4 text-muted-foreground" />+ {zapierSource ? "Connect Zapier" : byo ? "Connect your own MCP server" : "Connect with a link"}+ </div>+ <p className="mt-1 text-xs text-muted-foreground">+ {zapierSource+ ? "Paste the complete MCP URL Zapier gives you, including its token."+ : byo+ ? "Paste your MCP server’s URL and every discovered tool will be available immediately."+ : "Paste a setup link from an app that is not listed here."}+ </p>+ {!zapierSource && (+ <p className="mt-1 text-xs text-muted-foreground">+ Any remote tool URL works here — including a local MCP server like{" "}+ <code className="rounded bg-muted px-1 py-0.5 text-xs">http://127.0.0.1:8848/mcp</code>.+ </p>+ )}+ {matchedEntry && (+ <div className="mt-3 flex items-center justify-between gap-3 rounded-lg border border-border bg-muted/40 px-3 py-2">+ <div className="flex min-w-0 items-center gap-2 text-sm">+ <AppLogo name={matchedEntry.name} logoUrl={matchedEntry.branding.logoUrl} darkLogoUrl={matchedEntry.branding.darkLogoUrl} size={24} />+ <span className="truncate">This looks like {matchedEntry.name}.</span>+ </div>+ <Button+ type="button"+ size="sm"+ variant="outline"+ disabled={matchedEntry.availability?.available === false}+ onClick={() => {+ setLinkError(null);+ if (matchedEntry.slug === "zapier") {+ continueWithLink();+ return;+ }+ onPick(matchedEntry);+ }}+ >+ {matchedEntry.availability?.available === false+ ? "Not available"+ : matchedEntry.slug === "zapier"+ ? "Continue"+ : `Use ${matchedEntry.name}`}+ </Button>+ </div>+ )}+ </div>+ <div className="flex min-w-0 flex-col gap-2 sm:min-w-(--sz-360px)">+ <div className="flex gap-2">+ <Input+ ref={linkInputRef}+ type={zapierSource || matchedEntry?.slug === "zapier" ? "password" : "url"}+ autoComplete="off"+ spellCheck={false}+ aria-label="MCP server URL"+ value={linkInput}+ onChange={(e) => {+ setLinkInput(e.target.value);+ setLinkError(null);+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter") continueWithLink();+ }}+ placeholder={zapierSource ? "https://mcp.zapier.com/api/v1/connect?token=…" : "https://example.com/actions"}+ className="h-10"+ />+ <Button type="button" variant="outline" onClick={continueWithLink}>+ Continue+ </Button>+ </div>+ {linkError && <div className="text-xs text-destructive">{linkError}</div>}+ </div>+ </div> : null}++ {!vercelConnect ? <div className="border-t border-border pt-5">+ <div className="text-sm font-semibold text-foreground">More ways to connect</div>+ <p className="mt-1 text-xs text-muted-foreground">+ For tools that aren’t in the gallery. You’ll need details from the tool’s docs.+ </p>+ <div className="mt-3 flex flex-col gap-2">+ <ConnectMethodRow+ icon={TerminalSquare}+ title="Run your own"+ description="Register a command Paperclip runs in your workspace for a tool that isn’t listed."+ onClick={onRunYourOwn}+ />+ <ConnectMethodRow+ icon={ClipboardPaste}+ title="Paste a config"+ description="Already have a setup snippet from a README? Paste it and we’ll connect it."+ onClick={onPasteConfig}+ />+ </div>+ </div> : null}+ </div>+ );+}++function ConnectMethodRow({+ icon: Icon,+ title,+ description,+ onClick,+}: {+ icon: LucideIcon;+ title: string;+ description: string;+ onClick: () => void;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ className="flex w-full items-center gap-3 rounded-lg border border-border bg-card px-4 py-3 text-left transition-colors hover:border-foreground/30 hover:bg-accent/40"+ >+ <span className="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-border bg-background">+ <Icon className="h-4 w-4 text-muted-foreground" />+ </span>+ <div className="min-w-0 flex-1">+ <div className="text-sm font-semibold text-foreground">{title}</div>+ <div className="truncate text-xs text-muted-foreground">{description}</div>+ </div>+ <ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground" />+ </button>+ );+}++function normalizeAppLink(value: string): string | null {+ try {+ const parsed = new URL(value.trim());+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;+ return parsed.toString();+ } catch {+ return null;+ }+}++/**+ * The guided universal flow for an unknown remote MCP server (PAP-17087, plan 2).+ *+ * The simple path stays exactly as short as it was — URL, name, "does it need a+ * key?" — because that is all most servers need. Everything protocol-shaped lives+ * behind "Advanced authentication", and no OAuth/DCR/CIMD jargon appears on the+ * consumer path: the operator picks how the server authenticates, not which RFC+ * Paperclip will use to satisfy it.+ *+ * The endpoint host and the "Unverified server" label stay visible the whole way+ * through, so the operator can always see whose server they are about to let+ * agents call.+ */+function LinkConnectStep({+ link,+ name,+ onNameChange,+ needsKey,+ onNeedsKeyChange,+ keyValue,+ onKeyChange,+ authMode,+ onAuthModeChange,+ headers,+ onHeadersChange,+ oauthClientId,+ onOAuthClientIdChange,+ oauthClientSecret,+ onOAuthClientSecretChange,+ advancedOpen,+ onAdvancedOpenChange,+ guidance,+ matchedEntry,+ onUseMatchedEntry,+ submitting,+ onBack,+ onConnect,+}: {+ link: string;+ name: string;+ onNameChange: (next: string) => void;+ needsKey: boolean;+ onNeedsKeyChange: (next: boolean) => void;+ keyValue: string;+ onKeyChange: (next: string) => void;+ authMode: GenericMcpAuthMode;+ onAuthModeChange: (next: GenericMcpAuthMode) => void;+ headers: CustomHeaderRow[];+ onHeadersChange: (next: CustomHeaderRow[]) => void;+ oauthClientId: string;+ onOAuthClientIdChange: (next: string) => void;+ oauthClientSecret: string;+ onOAuthClientSecretChange: (next: string) => void;+ advancedOpen: boolean;+ onAdvancedOpenChange: (next: boolean) => void;+ guidance: GenericConnectGuidance | null;+ /** A curated app whose endpoint matches, offered as a convenience only. */+ matchedEntry?: AppDefinition | null;+ onUseMatchedEntry?: () => void;+ submitting: boolean;+ onBack: () => void;+ onConnect: () => void;+}) {+ const host = endpointHost(link);+ const headerError = authMode === "custom_headers" ? customHeaderError(headers) : null;+ const draft: GenericConnectDraft = {+ link,+ name,+ authMode,+ needsKey,+ keyValue,+ headers,+ oauthClientId,+ oauthClientSecret,+ };+ const canSubmit = canSubmitGenericConnect(draft);+ const showSimpleKeyQuestion = authMode === "auto";+ const nameInputRef = useRef<HTMLInputElement>(null);+ const displayedLink = matchedEntry?.slug === "zapier" ? redactUrlSecrets(link) : link;++ useEffect(() => {+ if (guidance?.focus === "name") nameInputRef.current?.focus();+ }, [guidance]);++ const updateHeader = (id: string, patch: Partial<CustomHeaderRow>) => {+ onHeadersChange(headers.map((row) => (row.id === id ? { ...row, ...patch } : row)));+ };++ return (+ <div className="mx-auto max-w-xl rounded-2xl border border-border bg-card p-8">+ <div className="flex items-start gap-3">+ <span className="mt-1 inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border border-border bg-background">+ <Link2 className="h-5 w-5 text-muted-foreground" />+ </span>+ <div className="min-w-0">+ <h2 className="text-xl font-bold tracking-tight">Connect your own MCP server</h2>+ <p className="mt-1 truncate font-mono text-sm text-muted-foreground" title={displayedLink}>{displayedLink}</p>+ <UnverifiedServerBadge host={host} className="mt-2" />+ </div>+ </div>++ {matchedEntry && onUseMatchedEntry ? (+ <div className="mt-6 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border bg-muted/40 px-3 py-2">+ <div className="flex min-w-0 items-center gap-2 text-sm">+ <AppLogo name={matchedEntry.name} logoUrl={matchedEntry.branding.logoUrl} darkLogoUrl={matchedEntry.branding.darkLogoUrl} size={24} />+ <span className="truncate">Paperclip has a guided setup for {matchedEntry.name}.</span>+ </div>+ <Button type="button" size="sm" variant="outline" onClick={onUseMatchedEntry}>+ Use {matchedEntry.name}+ </Button>+ </div>+ ) : null}++ {guidance ? (+ <div className="mt-6">+ <InlineBanner tone="warning" title={guidance.title}>+ {guidance.body}+ </InlineBanner>+ </div>+ ) : null}++ <div className="mt-8 space-y-6">+ <div>+ <label className="text-sm font-medium text-foreground" htmlFor="generic-mcp-name">Name</label>+ <Input+ ref={nameInputRef}+ id="generic-mcp-name"+ value={name}+ onChange={(e) => onNameChange(e.target.value)}+ placeholder="My app"+ className="mt-2 h-11"+ />+ <p className="mt-2 text-xs text-muted-foreground">+ We filled this in from the address. Change it if you'd like.+ </p>+ </div>++ {showSimpleKeyQuestion && (+ <div>+ <label className="mr-2 text-sm font-medium text-foreground">Does it need a key?</label>+ <div className="mt-2 inline-flex rounded-lg border border-border bg-muted/50 p-1">+ <SegmentedOption+ label="No"+ selected={!needsKey}+ onClick={() => onNeedsKeyChange(false)}+ />+ <SegmentedOption+ label="Yes"+ selected={needsKey}+ onClick={() => onNeedsKeyChange(true)}+ />+ </div>+ <p className="mt-2 text-xs text-muted-foreground">+ {needsKey+ ? "Paste the key this app gave you."+ : "Most servers just work from the address — pick Yes only if the server gave you a key, or if it asks you to sign in."}+ </p>+ </div>+ )}++ {(showSimpleKeyQuestion && needsKey) || authMode === "bearer" ? (+ <div className="space-y-4">+ <div>+ <label className="text-sm font-medium text-foreground" htmlFor="generic-mcp-key">App key</label>+ <Input+ id="generic-mcp-key"+ type="password"+ autoComplete="off"+ value={keyValue}+ onChange={(e) => onKeyChange(e.target.value)}+ placeholder="••••••••••••••••"+ className="mt-2 h-11 font-mono"+ />+ </div>+ <StoredSecurelyNote />+ </div>+ ) : null}++ <Collapsible open={advancedOpen} onOpenChange={onAdvancedOpenChange}>+ <CollapsibleTrigger className="flex w-full items-center justify-between rounded-lg border border-border bg-background px-3 py-2 text-left text-sm font-medium text-foreground hover:bg-accent/40">+ Advanced authentication+ <ChevronDown className={cn("h-4 w-4 text-muted-foreground transition-transform", advancedOpen && "rotate-180")} />+ </CollapsibleTrigger>+ <CollapsibleContent className="space-y-5 pt-4">+ <p className="text-xs text-muted-foreground">+ Only needed when the server's docs are specific about how to authenticate.+ </p>+ <div className="flex flex-wrap gap-2">+ {GENERIC_AUTH_MODE_OPTIONS.map((option) => (+ <SegmentedOption+ key={option.mode}+ label={option.label}+ selected={authMode === option.mode}+ onClick={() => onAuthModeChange(option.mode)}+ />+ ))}+ </div>+ <p className="text-xs text-muted-foreground">+ {GENERIC_AUTH_MODE_OPTIONS.find((option) => option.mode === authMode)?.hint}+ </p>++ {authMode === "custom_headers" ? (+ <div className="space-y-3">+ {headers.map((row) => (+ <div key={row.id} className="flex items-start gap-2">+ <Input+ value={row.name}+ onChange={(e) => updateHeader(row.id, { name: e.target.value })}+ placeholder="Header name"+ aria-label="Header name"+ className="h-10 font-mono"+ />+ <Input+ type="password"+ autoComplete="off"+ value={row.value}+ onChange={(e) => updateHeader(row.id, { value: e.target.value })}+ placeholder="Value"+ aria-label={row.name.trim() ? `Value for ${row.name.trim()}` : "Header value"}+ className="h-10 font-mono"+ />+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="h-10 shrink-0"+ onClick={() => onHeadersChange(headers.filter((candidate) => candidate.id !== row.id))}+ disabled={headers.length === 1}+ >+ Remove+ </Button>+ </div>+ ))}+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => onHeadersChange([...headers, newCustomHeaderRow()])}+ >+ Add another header+ </Button>+ {headerError ? <p className="text-xs text-destructive">{headerError}</p> : null}+ <StoredSecurelyNote />+ </div>+ ) : null}++ {authMode === "oauth" ? (+ <div className="space-y-4">+ <p className="text-xs text-muted-foreground">+ Paperclip sets sign-in up on its own whenever the server allows it. Only fill these in when the+ server's docs tell you to register Paperclip yourself first.+ </p>+ <div>+ <label className="text-sm font-medium text-foreground" htmlFor="generic-mcp-client-id">+ Client ID+ </label>+ <Input+ id="generic-mcp-client-id"+ value={oauthClientId}+ onChange={(e) => onOAuthClientIdChange(e.target.value)}+ autoComplete="off"+ placeholder="Optional"+ className="mt-2 h-11 font-mono"+ />+ </div>+ <div>+ <label className="text-sm font-medium text-foreground" htmlFor="generic-mcp-client-secret">+ Client secret+ </label>+ <Input+ id="generic-mcp-client-secret"+ type="password"+ autoComplete="off"+ value={oauthClientSecret}+ onChange={(e) => onOAuthClientSecretChange(e.target.value)}+ placeholder="Optional"+ className="mt-2 h-11 font-mono"+ />+ </div>+ <StoredSecurelyNote />+ </div>+ ) : null}+ </CollapsibleContent>+ </Collapsible>+ </div>++ <div className="mt-8 flex items-center justify-between">+ <Button variant="ghost" onClick={onBack} disabled={submitting}>+ Back+ </Button>+ <div className="flex items-center gap-3">+ <span className="hidden text-xs text-muted-foreground sm:inline">+ We'll check the server before turning anything on.+ </span>+ <Button onClick={onConnect} disabled={submitting || !canSubmit || Boolean(headerError)}>+ {submitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}+ {submitting ? "Checking…" : "Check link"}+ </Button>+ </div>+ </div>+ </div>+ );+}++/**+ * What the operator is choosing is how the *server* authenticates, in its own+ * terms. Paperclip decides internally whether that means a preconfigured client,+ * a client ID metadata document, dynamic registration, or the credentials pasted+ * below — none of which belongs on this screen.+ */+const GENERIC_AUTH_MODE_OPTIONS: Array<{ mode: GenericMcpAuthMode; label: string; hint: string }> = [+ {+ mode: "auto",+ label: "Let Paperclip check",+ hint: "Paperclip asks the server what it needs and walks you through it. Start here.",+ },+ {+ mode: "none",+ label: "No sign-in needed",+ hint: "The server is open to anyone with the address.",+ },+ {+ mode: "bearer",+ label: "Key or token",+ hint: "Paperclip sends your key as an Authorization header.",+ },+ {+ mode: "custom_headers",+ label: "Custom headers",+ hint: "For servers that name their own headers. Values are stored as Paperclip secrets and can\u2019t be read back.",+ },+ {+ mode: "oauth",+ label: "Browser sign-in",+ hint: "You\u2019ll sign in at the provider. Add a client ID and secret only if the provider requires you to register Paperclip first.",+ },+];++function StoredSecurelyNote() {+ return (+ <div className="flex items-start gap-3 rounded-lg bg-muted/50 p-4">+ <Lock className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />+ <div>+ <div className="text-sm font-medium text-foreground">Stored securely.</div>+ <div className="text-xs text-muted-foreground">+ Paperclip keeps this in its encrypted secret store. You can replace it anytime from this app's page,+ but it can't be read back.+ </div>+ </div>+ </div>+ );+}++function SegmentedOption({+ label,+ selected,+ onClick,+}: {+ label: string;+ selected: boolean;+ onClick: () => void;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ aria-pressed={selected}+ className={cn(+ "min-w-(--sz-64px) rounded-md px-4 py-1.5 text-sm font-medium transition-colors",+ selected+ ? "bg-background text-foreground shadow-sm"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ {label}+ </button>+ );+}++function ConnectionNameField({+ name,+ onNameChange,+}: {+ name: string;+ onNameChange: (next: string) => void;+}) {+ return (+ <div>+ <label className="text-sm font-medium text-foreground">Name</label>+ <Input+ value={name}+ onChange={(e) => onNameChange(e.target.value)}+ placeholder="My app"+ className="mt-2 h-11"+ />+ <p className="mt-2 text-xs text-muted-foreground">+ We filled this in from the app. Change it to tell connections apart.+ </p>+ </div>+ );+}++function connectionMethodAuthenticationLabel(method: ConnectionMethodDef): string {+ if (method.auth === "api_key") return "Authentication: API key";+ if (method.auth === "none") return "Authentication: no credentials";+ if (connectionMethodSupportsAutomaticOAuth(method)) {+ return connectionMethodAcceptsCustomerOAuthClient(method)+ ? "Authentication: browser sign-in or your OAuth app"+ : "Authentication: browser sign-in";+ }+ return "Authentication: your OAuth app";+}++function KeyStep({+ entry,+ name,+ onNameChange,+ values,+ onChange,+ oauthClientId,+ onOAuthClientIdChange,+ oauthClientSecret,+ onOAuthClientSecretChange,+ credentialSource,+ vercelConnector,+ onVercelConnectorChange,+ vercelConnectAvailability,+ methodKey,+ onMethodChange,+ configValues,+ onConfigChange,+ googleSheetsLinks,+ googleSheetsError,+ onGoogleSheetsLinksChange,+ submitting,+ onBack,+ onConnect,+}: {+ entry: AppDefinition;+ name: string;+ onNameChange: (next: string) => void;+ values: Record<string, string>;+ onChange: (next: Record<string, string>) => void;+ oauthClientId: string;+ onOAuthClientIdChange: (next: string) => void;+ oauthClientSecret: string;+ onOAuthClientSecretChange: (next: string) => void;+ credentialSource: ToolConnectionCredentialSource;+ vercelConnector: string;+ onVercelConnectorChange: (next: string) => void;+ vercelConnectAvailability: {+ available: boolean;+ manageUrl: string;+ reason: string | null;+ } | null;+ methodKey: string;+ onMethodChange: (method: ConnectionMethodDef | null) => void;+ configValues: Record<string, string | boolean>;+ onConfigChange: (next: Record<string, string | boolean>) => void;+ googleSheetsLinks: string;+ googleSheetsError: string | null;+ onGoogleSheetsLinksChange: (next: string) => void;+ submitting: boolean;+ onBack: () => void;+ onConnect: () => void;+}) {+ const copy = appCopyFor(entry.slug, entry.description);+ const methods = useMemo(+ () => connectionMethodsForCredentialSource(entry, credentialSource),+ [credentialSource, entry],+ );+ const method = methodKey+ ? methods.find((candidate) => candidate.key === methodKey) ?? null+ : recommendedSetupConnectionMethod(methods);+ const capabilityGroups = useMemo(() => {+ if (!methods.some((candidate) => candidate.capabilityProfile)) return [];+ return Array.from(methods.reduce((groups, candidate) => {+ const key = candidate.capabilityProfile!.key;+ const existing = groups.get(key);+ if (existing) {+ existing.methods.push(candidate);+ } else {+ groups.set(key, {+ key,+ label: candidate.capabilityProfile?.label ?? candidate.label ?? candidate.key,+ description: candidate.capabilityProfile?.description ?? candidate.whenToUse,+ methods: [candidate],+ });+ }+ return groups;+ }, new Map<string, {+ key: string;+ label: string;+ description: string;+ methods: ConnectionMethodDef[];+ }>()),+ ).map(([, group]) => group);+ }, [methods]);+ const selectedMethodCapabilityKey = method?.capabilityProfile?.key ?? method?.key ?? "";+ const capabilityGroupKeys = capabilityGroups.map((group) => group.key).join("|");+ const [capabilityKey, setCapabilityKey] = useState(+ selectedMethodCapabilityKey+ || recommendedSetupConnectionMethod(methods)?.capabilityProfile?.key+ || (capabilityGroups.length === 1 ? capabilityGroups[0]!.key : ""),+ );+ useEffect(() => {+ if (selectedMethodCapabilityKey) {+ setCapabilityKey(selectedMethodCapabilityKey);+ return;+ }+ setCapabilityKey((current) => {+ if (capabilityGroups.some((group) => group.key === current)) return current;+ return recommendedSetupConnectionMethod(methods)?.capabilityProfile?.key+ || (capabilityGroups.length === 1 ? capabilityGroups[0]!.key : "");+ });+ }, [capabilityGroupKeys, capabilityGroups, methods, selectedMethodCapabilityKey]);+ const capabilityMethods = capabilityGroups.length > 1+ ? capabilityGroups.find((group) => group.key === capabilityKey)?.methods ?? []+ : methods;+ const fields = (method?.credentialFields ?? []).map((field) => ({+ ...field,+ configPath: credentialConfigPath(field),+ helpUrl: method?.consoleLinks?.keys ?? method?.consoleLinks?.docs ?? "",+ }));+ const vercelReview = method?.credentialSources?.vercelConnect ?? null;+ const usingVercel = credentialSource === "vercel_connect";+ const allFilled = usingVercel || fields.every(+ (f) => f.required === false || (values[f.configPath]?.trim().length ?? 0) > 0,+ );+ const acceptsCustomerOAuthClient = connectionMethodAcceptsCustomerOAuthClient(method);+ const customerOAuthClientRequired = acceptsCustomerOAuthClient+ && !connectionMethodSupportsAutomaticOAuth(method);+ const oauthClientFilled = usingVercel || !customerOAuthClientRequired || oauthClientId.trim().length > 0;+ const vercelConnectorFilled = !usingVercel || vercelConnector.trim().length > 0;+ const oauthCallbackUrl = method?.auth === "oauth" && acceptsCustomerOAuthClient+ ? oauthCallbackUrlForBrowser()+ : null;+ const allConfigFields = [...(method?.tenantFields ?? []), ...(method?.extensionFields ?? [])];+ const configFields = allConfigFields.filter((field) => !field.hidden);+ const standardConfigFields = configFields.filter((field) => field.advanced !== true);+ const advancedConfigFields = configFields.filter((field) => field.advanced === true);+ const [advancedOpen, setAdvancedOpen] = useState(false);+ const configFilled = allConfigFields.every((field) => {+ if (!field.required) return true;+ const value = configValues[field.key];+ return typeof value === "boolean" || (typeof value === "string" && value.trim().length > 0);+ });+ const alternativeKeys = method?.configRequirements?.atLeastOneOf ?? [];+ const configRequirementMet = alternativeKeys.length === 0 || alternativeKeys.some((key) => {+ const value = configValues[key];+ return typeof value === "string" && value.trim().length > 0;+ });+ const hasCapabilitySelection = capabilityGroups.length <= 1 || Boolean(capabilityKey);+ const hasMethodSelection = hasCapabilitySelection+ && (capabilityMethods.length <= 1 ? Boolean(method) : Boolean(methodKey));+ const robotEmail = entry.availability?.robotEmail ?? null;+ const unavailable = entry.availability?.available === false;+ const optionalCustomerOAuthClient = !usingVercel+ && acceptsCustomerOAuthClient+ && !customerOAuthClientRequired;+ const hasAdvancedSettings = advancedConfigFields.length > 0 || optionalCustomerOAuthClient;+ const capabilitySelection = capabilityGroups.length > 1 ? (+ <div>+ <label className="text-sm font-medium text-foreground">What should Paperclip be able to do?</label>+ <RadioCardGroup+ ariaLabel={`Access level for ${entry.name}`}+ className="mt-2"+ value={capabilityKey}+ onValueChange={(nextKey) => {+ const nextGroup = capabilityGroups.find((group) => group.key === nextKey);+ if (!nextGroup) return;+ setCapabilityKey(nextKey);+ onMethodChange(getRecommendedConnectionMethod(nextGroup.methods));+ }}+ options={capabilityGroups.map((group) => ({+ value: group.key,+ title: group.label,+ description: group.description,+ }))}+ />+ {!capabilityKey && <p className="mt-2 text-xs text-muted-foreground">Choose an access level to continue.</p>}+ </div>+ ) : null;+ const authenticationSelection = capabilityMethods.length > 1 ? (+ <div>+ <label className="text-sm font-medium text-foreground">How do you want to connect?</label>+ <RadioCardGroup+ ariaLabel={`How to connect ${entry.name}`}+ className="mt-2"+ value={methodKey}+ onValueChange={(nextKey) => {+ const nextMethod = capabilityMethods.find((candidate) => candidate.key === nextKey);+ if (nextMethod) onMethodChange(nextMethod);+ }}+ options={capabilityMethods.map((candidate) => ({+ value: candidate.key,+ title: candidate.label ?? (candidate.auth === "oauth" ? `Sign in with ${entry.name}` : "Use an API key"),+ description: `${connectionMethodAuthenticationLabel(candidate)}. ${candidate.whenToUse}`,+ }))}+ />+ {!method && <p className="mt-2 text-xs text-muted-foreground">Choose a connection method to continue.</p>}+ </div>+ ) : null;++ if (isGoogleSheetsRobotMethod(entry, method)) {+ const parsed = parseGoogleSheetIds(googleSheetsLinks);+ const canConnect = !unavailable && Boolean(robotEmail) && googleSheetsLinks.trim().length > 0;+ return (+ <div className="mx-auto max-w-xl rounded-2xl border border-border bg-card p-8">+ <div className="flex items-center gap-3">+ <AppLogo name={entry.name} logoUrl={entry.branding.logoUrl} darkLogoUrl={entry.branding.darkLogoUrl} size={48} />+ <div>+ <h2 className="text-lg font-bold tracking-tight sm:text-xl">Connect Google Sheets</h2>+ <p className="text-sm text-muted-foreground">{copy.short}</p>+ </div>+ </div>++ <div className="mt-8 space-y-6">+ {capabilitySelection}+ <ConnectionNameField name={name} onNameChange={onNameChange} />++ {robotEmail ? (+ <div>+ <label className="text-sm font-medium text-foreground">Share each sheet with this email</label>+ <div className="mt-2 flex min-w-0 flex-col gap-2 sm:flex-row">+ <div+ title={robotEmail}+ className="min-h-11 min-w-0 flex-1 rounded-md border border-input bg-muted/40 px-3 py-2.5 font-mono text-xs leading-tight text-foreground break-all"+ >+ {robotEmail}+ </div>+ <Button+ type="button"+ variant="outline"+ className="shrink-0"+ onClick={() => void copyTextToClipboard(robotEmail).catch(() => {})}+ >+ <Copy className="mr-2 h-4 w-4" />+ Copy+ </Button>+ </div>+ <p className="mt-2 text-xs text-muted-foreground">+ In Google Sheets, click Share and add this email as an Editor. Then paste the sheet links below.+ </p>+ </div>+ ) : (+ <div className="rounded-lg bg-muted/50 p-4 text-sm text-muted-foreground">+ Google Sheets is not available on this instance yet.+ </div>+ )}++ <div>+ <label className="text-sm font-medium text-foreground">Paste links to the sheets you shared</label>+ <Textarea+ value={googleSheetsLinks}+ onChange={(e) => onGoogleSheetsLinksChange(e.target.value)}+ placeholder="https://docs.google.com/spreadsheets/d/..."+ className="mt-2 min-h-28"+ />+ <div className="mt-2 text-xs text-muted-foreground">+ {parsed.ids.length > 0+ ? `${parsed.ids.length} ${parsed.ids.length === 1 ? "sheet" : "sheets"} ready to connect.`+ : "Paste one link per line. Both .../edit and .../edit#gid=... links work."}+ </div>+ {googleSheetsError && <div className="mt-2 text-xs text-destructive">{googleSheetsError}</div>}+ </div>+ </div>++ <div className="mt-8 flex items-center justify-between">+ <Button variant="ghost" onClick={onBack} disabled={submitting}>+ Back+ </Button>+ <Button onClick={onConnect} disabled={submitting || !canConnect}>+ {submitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}+ {submitting ? "Checking…" : "Connect"}+ </Button>+ </div>+ </div>+ );+ }++ return (+ <div className="mx-auto max-w-xl rounded-2xl border border-border bg-card p-8">+ <div className="flex items-center gap-3">+ <AppLogo name={entry.name} logoUrl={entry.branding.logoUrl} darkLogoUrl={entry.branding.darkLogoUrl} size={48} />+ <div>+ <h2 className="text-xl font-bold tracking-tight">Connect {entry.name}</h2>+ <p className="text-sm text-muted-foreground">{copy.short}</p>+ </div>+ </div>++ <div className="mt-8 space-y-6">+ {capabilitySelection}+ {authenticationSelection}++ {method?.warnings?.map((warning) => (+ <InlineBanner key={warning} tone="warning" compact>+ {warning}+ </InlineBanner>+ ))}++ {method ? (+ <div className="rounded-lg border border-border bg-muted/30 p-4">+ <p className="text-sm text-foreground">{method.guidanceMd}</p>+ {entry.docsUrl || method.consoleLinks?.docs ? (+ <a+ href={method.consoleLinks?.docs ?? entry.docsUrl}+ target="_blank"+ rel="noreferrer"+ className="mt-2 inline-flex items-center gap-1 text-xs font-semibold text-foreground underline underline-offset-2"+ >+ Review {entry.name} setup requirements+ <ArrowUpRight className="h-3 w-3" />+ </a>+ ) : null}+ </div>+ ) : null}++ {usingVercel && vercelReview && vercelConnectAvailability ? (+ <div className="space-y-4 rounded-lg border border-border p-4">+ <div>+ <div className="text-sm font-medium text-foreground">Create or attach the connector in Vercel</div>+ <p className="mt-1 text-xs text-muted-foreground">+ Paperclip does not copy Vercel’s setup forms. Finish connector setup there, then paste its UID below.+ </p>+ <a+ href={vercelConnectAvailability.manageUrl}+ target="_blank"+ rel="noreferrer"+ className="mt-2 inline-flex items-center gap-1 text-xs font-semibold text-foreground underline underline-offset-2"+ >+ Open Vercel Connect+ <ArrowUpRight className="h-3 w-3" />+ </a>+ </div>+ <div>+ <label className="text-sm font-medium text-foreground" htmlFor="vercel-connect-connector">+ Connector UID or ID+ </label>+ <Input+ id="vercel-connect-connector"+ value={vercelConnector}+ onChange={(event) => onVercelConnectorChange(event.target.value)}+ autoComplete="off"+ placeholder="service/my-connector or scl_…"+ className="mt-2 h-11 font-mono"+ />+ <p className="mt-2 text-xs text-muted-foreground">+ Paperclip validates the connector and stores only its reference and redacted verification metadata.+ </p>+ </div>+ </div>+ ) : null}++ <ConnectionNameField name={name} onNameChange={onNameChange} />++ {standardConfigFields.map((field) => (+ <MethodConfigField+ key={field.key}+ field={field}+ value={configValues[field.key]}+ onChange={(value) => onConfigChange({ ...configValues, [field.key]: value })}+ />+ ))}++ {hasAdvancedSettings && (+ <Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen}>+ <CollapsibleTrigger className="flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground">+ <ChevronDown className={cn("h-4 w-4 transition-transform", advancedOpen && "rotate-180")} />+ Advanced+ </CollapsibleTrigger>+ <CollapsibleContent className="pt-4">+ <div className="space-y-6">+ {advancedConfigFields.map((field) => (+ <MethodConfigField+ key={field.key}+ field={field}+ value={configValues[field.key]}+ onChange={(value) => onConfigChange({ ...configValues, [field.key]: value })}+ />+ ))}+ {optionalCustomerOAuthClient ? (+ <OAuthClientFields+ entry={entry}+ method={method!}+ callbackUrl={oauthCallbackUrl}+ clientId={oauthClientId}+ onClientIdChange={onOAuthClientIdChange}+ clientSecret={oauthClientSecret}+ onClientSecretChange={onOAuthClientSecretChange}+ required={false}+ />+ ) : null}+ </div>+ </CollapsibleContent>+ </Collapsible>+ )}++ {!usingVercel && method?.auth === "oauth" && customerOAuthClientRequired ? (+ <OAuthClientFields+ entry={entry}+ method={method}+ callbackUrl={oauthCallbackUrl}+ clientId={oauthClientId}+ onClientIdChange={onOAuthClientIdChange}+ clientSecret={oauthClientSecret}+ onClientSecretChange={onOAuthClientSecretChange}+ required+ />+ ) : null}++ {usingVercel ? null : method && fields.length === 0 ? (+ <p className="text-sm text-muted-foreground">+ {method.auth === "oauth"+ ? `You’ll continue to ${entry.name} to sign in securely.`+ : "This app doesn’t need a key. Just connect to continue."}+ </p>+ ) : (+ fields.map((field) => (+ <div key={field.configPath}>+ <label className="text-sm font-medium text-foreground">+ {credentialFieldLabel(entry.name, field.label, fields.length)}+ </label>+ <Input+ type="password"+ autoComplete="off"+ value={values[field.configPath] ?? ""}+ onChange={(e) => onChange({ ...values, [field.configPath]: e.target.value })}+ placeholder="••••••••••••••••"+ className="mt-2 h-11 font-mono"+ />+ {field.helpUrl && (+ <a+ href={field.helpUrl}+ target="_blank"+ rel="noreferrer"+ className="mt-2 inline-flex items-center gap-1 text-xs font-semibold text-foreground underline underline-offset-2"+ >+ Where do I find this?+ <ArrowUpRight className="h-3 w-3" />+ </a>+ )}+ </div>+ ))+ )}++ {!usingVercel && method?.auth === "api_key" && (+ <div className="flex items-start gap-3 rounded-lg bg-muted/50 p-4">+ <Lock className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />+ <div>+ <div className="text-sm font-medium text-foreground">Your key is stored securely.</div>+ <div className="text-xs text-muted-foreground">+ You can replace it anytime from this app’s page.+ </div>+ </div>+ </div>+ )}+ </div>++ <div className="mt-8 flex items-center justify-between">+ <Button variant="ghost" onClick={onBack} disabled={submitting}>+ Back+ </Button>+ <div className="flex items-center gap-3">+ <span className="hidden text-xs text-muted-foreground sm:inline">+ {method?.auth === "oauth"+ ? "You’ll sign in before anything turns on."+ : "We’ll check the key before turning anything on."}+ </span>+ <Button onClick={onConnect} disabled={submitting || !hasMethodSelection || !allFilled || !oauthClientFilled || !vercelConnectorFilled || !configFilled || !configRequirementMet}>+ {submitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}+ {submitting+ ? "Checking…"+ : usingVercel+ ? method?.auth === "oauth" ? "Validate and continue" : "Validate and connect"+ : method?.auth === "oauth" ? "Continue to sign in" : "Connect"}+ </Button>+ </div>+ </div>+ </div>+ );+}++function OAuthClientFields({+ entry,+ method,+ callbackUrl,+ clientId,+ onClientIdChange,+ clientSecret,+ onClientSecretChange,+ required,+}: {+ entry: AppDefinition;+ method: ConnectionMethodDef;+ callbackUrl: string | null;+ clientId: string;+ onClientIdChange: (next: string) => void;+ clientSecret: string;+ onClientSecretChange: (next: string) => void;+ required: boolean;+}) {+ return (+ <div className="space-y-4 rounded-lg border border-border p-4">+ <div>+ <div className="text-sm font-medium text-foreground">+ {required ? "Your OAuth app" : "Use your own OAuth app"}+ </div>+ <p className="mt-1 text-xs text-muted-foreground">+ Register Paperclip's callback URI in {entry.name}, then enter the customer-owned client details.+ </p>+ {method.consoleLinks?.register ? (+ <a+ href={method.consoleLinks.register}+ target="_blank"+ rel="noreferrer"+ className="mt-2 inline-flex items-center gap-1 text-xs font-semibold text-foreground underline underline-offset-2"+ >+ Open {entry.name} app settings+ <ArrowUpRight className="h-3 w-3" />+ </a>+ ) : null}+ </div>+ {callbackUrl ? (+ <div>+ <label className="text-sm font-medium text-foreground">Paperclip callback URL</label>+ <div className="mt-2 flex min-w-0 flex-col gap-2 sm:flex-row">+ <div+ title={callbackUrl}+ className="min-h-11 min-w-0 flex-1 rounded-md border border-input bg-muted/40 px-3 py-2.5 font-mono text-xs leading-tight text-foreground break-all"+ >+ {callbackUrl}+ </div>+ <Button+ type="button"+ variant="outline"+ className="shrink-0"+ onClick={() => void copyTextToClipboard(callbackUrl).catch(() => {})}+ >+ <Copy className="mr-2 h-4 w-4" />+ Copy+ </Button>+ </div>+ <p className="mt-2 text-xs text-muted-foreground">+ Add this exact URL to {entry.name} before continuing. It must match the authorization request.+ </p>+ </div>+ ) : null}+ <div>+ <label className="text-sm font-medium text-foreground" htmlFor="curated-oauth-client-id">+ Client ID+ </label>+ <Input+ id="curated-oauth-client-id"+ value={clientId}+ onChange={(event) => onClientIdChange(event.target.value)}+ autoComplete="off"+ placeholder={required ? "Required" : "Optional"}+ className="mt-2 h-11 font-mono"+ />+ </div>+ <div>+ <label className="text-sm font-medium text-foreground" htmlFor="curated-oauth-client-secret">+ Client secret+ </label>+ <Input+ id="curated-oauth-client-secret"+ type="password"+ value={clientSecret}+ onChange={(event) => onClientSecretChange(event.target.value)}+ autoComplete="off"+ placeholder="Optional for public clients"+ className="mt-2 h-11 font-mono"+ />+ </div>+ <StoredSecurelyNote />+ </div>+ );+}++function MethodConfigField({+ field,+ value,+ onChange,+}: {+ field: FieldDef;+ value: string | boolean | undefined;+ onChange: (value: string | boolean) => void;+}) {+ if (field.type === "checkbox") {+ return (+ <div className="flex items-start justify-between gap-4 rounded-lg border border-border p-4">+ <div>+ <div className="text-sm font-medium text-foreground">{field.label}</div>+ {field.helperMd && <div className="mt-1 text-xs text-muted-foreground">{field.helperMd}</div>}+ </div>+ <ToggleSwitch checked={value === true} onCheckedChange={onChange} />+ </div>+ );+ }+ return (+ <div>+ <label className="text-sm font-medium text-foreground">{field.label}</label>+ {field.type === "textarea" ? (+ <Textarea+ value={typeof value === "string" ? value : ""}+ onChange={(event) => onChange(event.target.value)}+ placeholder={field.placeholder}+ className="mt-2 min-h-24"+ />+ ) : field.type === "select" ? (+ <select+ value={typeof value === "string" ? value : ""}+ onChange={(event) => onChange(event.target.value)}+ className="mt-2 h-11 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/30"+ >+ <option value="" disabled>Select an option</option>+ {(field.options ?? []).map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}+ </select>+ ) : (+ <Input+ value={typeof value === "string" ? value : ""}+ onChange={(event) => onChange(event.target.value)}+ placeholder={field.placeholder}+ className="mt-2 h-11"+ />+ )}+ {field.helperMd && <p className="mt-2 text-xs text-muted-foreground">{field.helperMd}</p>}+ </div>+ );+}++/**+ * Access step (PAP-17835 Surface A).+ *+ * Two binary questions, asked together and *before* any credential is entered,+ * so the reader understands the identity and the reach the secret is about to+ * get. Hick's Law: two choices, not a matrix. Both use full-row radio targets.+ */+export function AccessStep({+ appName,+ providerName,+ companyId,+ authKind,+ grantKinds,+ grantKind,+ setGrantKind,+ installChoice,+ setInstallChoice,+ installAgentIds,+ setInstallAgentIds,+ lockedAgentId,+ capabilities,+ guidance,+ warnings,+ setupPrerequisite,+ docsUrl,+ submitLabel,+ identityLoading = false,+ preserveAgentAccess = false,+ pending = false,+ onBack,+ onContinue,+}: {+ appName: string;+ providerName: string;+ companyId: string;+ authKind: ToolConnectionAuthKind;+ grantKinds?: ConnectionGrantKind[];+ grantKind: ConnectionGrantKind;+ setGrantKind: (kind: ConnectionGrantKind) => void;+ installChoice: "specific" | "all";+ setInstallChoice: (choice: "specific" | "all") => void;+ installAgentIds: Set<string>;+ setInstallAgentIds: (ids: Set<string>) => void;+ /** Task-hosted intents grant reach only to the agent that requested it. */+ lockedAgentId?: string;+ capabilities?: Pick<ToolConnectionCreateCapabilities, "canSetCompanyInstall"> & {+ companyInstallReason?: string | null;+ editableAgentIds?: string[];+ } | null;+ guidance?: string;+ warnings?: string[];+ setupPrerequisite?: AppDefinition["setupPrerequisite"];+ docsUrl?: string;+ submitLabel: string;+ /** Wait for a durable OAuth connection before showing a reconnect identity. */+ identityLoading?: boolean;+ /** Reconnect changes credentials only; existing install reach stays intact. */+ preserveAgentAccess?: boolean;+ pending?: boolean;+ onBack: () => void;+ onContinue: () => void;+}) {+ const agentsQuery = useQuery({+ queryKey: queryKeys.agents.list(companyId),+ queryFn: () => agentsApi.list(companyId),+ });+ const allAgents: Agent[] = (agentsQuery.data ?? []).filter((a) => a.status !== "terminated");+ // "Agents I pick" means agents this person may actually edit. When the server+ // has not told us, fall back to every live agent rather than an empty list —+ // an empty picker would read as "you have no agents".+ const editableAgentIds = capabilities?.editableAgentIds;+ const agents = editableAgentIds+ ? allAgents.filter((agent) => editableAgentIds.includes(agent.id))+ : allAgents;+ // Company-wide install is the connection creator's to give. When it is not+ // available the option stays visible and disabled with the reason, so the+ // scope stays legible instead of quietly disappearing.+ const canSetCompanyInstall = capabilities?.canSetCompanyInstall ?? true;+ const needsIdentityChoice = authKind !== "none";+ const allowedGrantKinds = grantKinds ?? (["user", "organization"] satisfies ConnectionGrantKind[]);+ const canContinue = preserveAgentAccess+ ? true+ : lockedAgentId+ ? installAgentIds.has(lockedAgentId)+ : installChoice === "all"+ ? canSetCompanyInstall+ : installAgentIds.size > 0;+ const lockedAgentName = lockedAgentId+ ? allAgents.find((agent) => agent.id === lockedAgentId)?.name ?? "the requesting agent"+ : null;++ return (+ <div className="mx-auto max-w-2xl">+ <div className="overflow-hidden rounded-xl border border-border bg-card shadow-sm">+ <div className="flex items-start gap-3 border-b border-border p-6">+ <span className="inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">+ <ShieldCheck className="h-5 w-5" aria-hidden="true" />+ </span>+ <div>+ <h2 className="text-xl font-bold tracking-tight">+ {authKind === "oauth" ? "Choose access before sign-in" : "Choose access before adding credentials"}+ </h2>+ <p className="mt-1 text-sm text-muted-foreground">+ {authKind === "oauth"+ ? `Set the identity and agent reach first. Then ${providerName} will ask you to authorize that exact connection.`+ : "Set the identity and agent reach first. Then add the credential for that exact connection."}+ </p>+ </div>+ </div>++ {guidance || warnings?.length || setupPrerequisite || docsUrl ? (+ <div className="space-y-3 border-b border-border p-6">+ {warnings?.map((warning) => (+ <InlineBanner key={warning} tone="warning" compact>{warning}</InlineBanner>+ ))}+ {guidance ? <p className="text-sm text-foreground">{guidance}</p> : null}+ {setupPrerequisite ? (+ <div className="rounded-lg border border-border bg-muted/30 p-4">+ <h3 className="text-sm font-semibold text-foreground">{setupPrerequisite.title}</h3>+ <p className="mt-1 text-xs text-muted-foreground">{setupPrerequisite.description}</p>+ {setupPrerequisite.steps?.length ? (+ <ol+ aria-label={`${setupPrerequisite.title} steps`}+ className="mt-3 list-decimal space-y-1 pl-4 text-xs text-muted-foreground"+ >+ {setupPrerequisite.steps.map((step) => <li key={step}>{step}</li>)}+ </ol>+ ) : null}+ <a+ href={setupPrerequisite.actionUrl}+ target="_blank"+ rel="noreferrer"+ className="mt-3 inline-flex items-center gap-1 text-xs font-semibold text-foreground underline underline-offset-2"+ >+ {setupPrerequisite.actionLabel}+ <ArrowUpRight className="h-3 w-3" />+ </a>+ </div>+ ) : null}+ {docsUrl ? (+ <a+ href={docsUrl}+ target="_blank"+ rel="noreferrer"+ className="inline-flex items-center gap-1 text-xs font-semibold text-foreground underline underline-offset-2"+ >+ Review {providerName} setup requirements+ <ArrowUpRight className="h-3 w-3" />+ </a>+ ) : null}+ </div>+ ) : null}++ <div className="divide-y divide-border">+ <section className="p-6">+ <div className="flex items-start gap-3">+ <span className="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground">+ <UserRound className="h-4 w-4" aria-hidden="true" />+ </span>+ <div>+ <h3 className="text-sm font-semibold text-foreground">Who is this credential for?</h3>+ <p className="mt-1 text-xs text-muted-foreground">+ Whose {appName} account should agents act as?+ </p>+ </div>+ </div>+ {identityLoading ? (+ <div className="mt-4 grid gap-2 sm:grid-cols-2" aria-label="Loading connection identity">+ <Skeleton className="h-20 w-full rounded-md" />+ <Skeleton className="h-20 w-full rounded-md" />+ </div>+ ) : needsIdentityChoice && allowedGrantKinds.length === 1 ? (+ <div className="mt-4 flex items-start gap-3 rounded-md border border-border bg-muted/40 p-4">+ {allowedGrantKinds[0] === "user" ? (+ <UserRound className="mt-0.5 h-4 w-4 shrink-0 text-primary" aria-hidden="true" />+ ) : (+ <Building2 className="mt-0.5 h-4 w-4 shrink-0 text-primary" aria-hidden="true" />+ )}+ <div>+ <div className="text-sm font-medium text-foreground">+ {allowedGrantKinds[0] === "user" ? "Just me." : "Everyone in the company"}+ </div>+ <p className="mt-1 text-xs text-muted-foreground">+ {allowedGrantKinds[0] === "user"+ ? `Agents use this ${appName} identity only when work runs for you.`+ : `Eligible company members share this ${appName} identity.`}+ {preserveAgentAccess ? " Reconnect keeps this identity type." : null}+ </p>+ </div>+ </div>+ ) : needsIdentityChoice ? (+ <RadioCardGroup+ ariaLabel="Who is this credential for?"+ className="mt-4 sm:grid-cols-2"+ value={grantKind}+ onValueChange={(next) => setGrantKind(next as ConnectionGrantKind)}+ options={[+ {+ value: "user",+ title: "Just me",+ description: "Agents use this identity only when work runs for you.",+ },+ {+ value: "organization",+ title: "Everyone in the company",+ description: "Eligible company members use one shared identity.",+ },+ ].filter((option) => allowedGrantKinds.includes(option.value as ConnectionGrantKind))}+ />+ ) : (+ // A connection with no credential has no identity to choose, so+ // asking would be a meaningless decision.+ <p className="mt-4 text-sm text-muted-foreground">No identity required</p>+ )}+ </section>++ <section className="p-6">+ <div className="flex items-start gap-3">+ <span className="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground">+ <Bot className="h-4 w-4" aria-hidden="true" />+ </span>+ <div>+ <h3 className="text-sm font-semibold text-foreground">Which agents can use this connection?</h3>+ <p className="mt-1 text-xs text-muted-foreground">Choose where this connection will be available.</p>+ </div>+ </div>+ {preserveAgentAccess ? (+ <div className="mt-4 flex items-start gap-3 rounded-md border border-border bg-muted/40 p-4">+ <UsersRound className="mt-0.5 h-4 w-4 shrink-0 text-primary" aria-hidden="true" />+ <div>+ <div className="text-sm font-medium text-foreground">Existing agent access stays the same</div>+ <p className="mt-1 text-xs text-muted-foreground">+ Reconnecting replaces the credential without changing which agents can use it.+ </p>+ </div>+ </div>+ ) : lockedAgentId ? (+ <p className="mt-2 text-sm text-muted-foreground">+ This task grants access only to <span className="font-medium text-foreground">{lockedAgentName}</span>.+ Existing connection access is left unchanged.+ </p>+ ) : (+ <RadioCardGroup+ ariaLabel="Which agents can use this connection?"+ className="mt-4 sm:grid-cols-2"+ value={installChoice}+ onValueChange={(next) => setInstallChoice(next as "specific" | "all")}+ options={[+ {+ value: "specific",+ title: "Agents I pick",+ description: "Choose one or more agents you can edit.",+ },+ {+ value: "all",+ title: "Any agent",+ description: canSetCompanyInstall+ ? "Make this connection available to every agent."+ : capabilities?.companyInstallReason ??+ "Only someone who can configure this connection can choose this.",+ disabled: !canSetCompanyInstall,+ },+ ]}+ />+ )}+ {!preserveAgentAccess && !lockedAgentId && installChoice === "specific" ? (+ <div className="mt-3">+ <AgentMultiSelect+ agents={agents}+ selectedAgentIds={installAgentIds}+ onChange={setInstallAgentIds}+ loading={agentsQuery.isLoading}+ emptyMessage="You cannot edit any agents yet."+ showSelectionPreview={false}+ />+ </div>+ ) : null}+ </section>+ </div>+ </div>++ {/* Mobile stacks actions full-width with the primary action first in+ reading order; desktop keeps Back on the left. */}+ <div className="mt-6 flex flex-col-reverse gap-2 sm:flex-row sm:items-center sm:justify-between">+ <Button variant="ghost" className="w-full sm:w-auto" onClick={onBack} disabled={pending}>+ Back+ </Button>+ <Button+ className="w-full sm:w-auto"+ onClick={onContinue}+ disabled={!canContinue || identityLoading || pending}+ >+ {pending ? <Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" /> : null}+ {submitLabel}+ {!pending && authKind === "oauth" ? <ArrowUpRight className="h-4 w-4" aria-hidden="true" /> : null}+ </Button>+ </div>+ </div>+ );+}++/**+ * Summary of what the Access step committed. Three lines, not badges: identity,+ * reach, and the existing action summary each said once.+ */+export function accessSummaryLines(input: {+ grantKind: ConnectionGrantKind;+ authKind: ToolConnectionAuthKind;+ installChoice: "specific" | "all";+ installCount: number;+ enabledCount: number;+}): Array<{ label: string; value: string }> {+ const identity = input.authKind === "none"+ ? "No identity required"+ : input.grantKind === "user"+ ? "Your identity"+ : "Organization identity";+ const availableTo = input.installChoice === "all"+ ? "Any agent"+ : `${input.installCount} selected ${input.installCount === 1 ? "agent" : "agents"}`;+ return [+ { label: "Identity", value: identity },+ { label: "Available to", value: availableTo },+ {+ label: "Actions",+ value: `${input.enabledCount} ${input.enabledCount === 1 ? "action" : "actions"} on`,+ },+ ];+}++function Radio({ selected }: { selected: boolean }) {+ return (+ <span+ className={cn(+ "mt-0.5 inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-2",+ selected ? "border-foreground" : "border-muted-foreground/40",+ )}+ >+ {selected && <span className="h-2 w-2 rounded-full bg-foreground" />}+ </span>+ );+}++function SuccessStep({+ appName,+ logoUrl,+ darkLogoUrl,+ summary,+ onDone,+}: {+ appName: string;+ logoUrl?: string | null;+ darkLogoUrl?: string | null;+ /** Identity / Available to / Actions, as three lines rather than badges. */+ summary: Array<{ label: string; value: string }>;+ onDone: () => void;+}) {+ return (+ <div className="mx-auto max-w-md py-10 text-center">+ <div className="mx-auto flex h-20 w-20 items-center justify-center rounded-full border-2 border-emerald-500 bg-emerald-500/10">+ <Check className="h-9 w-9 text-emerald-600 dark:text-emerald-400" />+ </div>+ <div className="mt-6 flex items-center justify-center gap-2">+ <AppLogo name={appName} logoUrl={logoUrl} darkLogoUrl={darkLogoUrl} size={28} />+ <h2 className="text-2xl font-bold tracking-tight">{appName} is ready.</h2>+ </div>+ <dl className="mx-auto mt-6 max-w-xs space-y-1 text-left">+ {summary.map((line) => (+ <div key={line.label} className="flex items-baseline justify-between gap-4">+ <dt className="text-xs font-medium text-muted-foreground">{line.label}</dt>+ <dd className="text-sm text-foreground">{line.value}</dd>+ </div>+ ))}+ </dl>+ <div className="mt-8">+ <Button size="lg" className="px-10" onClick={onDone}>+ View connection+ </Button>+ </div>+ </div>+ );+}diff --git a/ui/src/fixtures/issueThreadInteractionFixtures.ts b/ui/src/fixtures/issueThreadInteractionFixtures.tsindex 036bd7ca1f..81bb314620 100644--- a/ui/src/fixtures/issueThreadInteractionFixtures.ts+++ b/ui/src/fixtures/issueThreadInteractionFixtures.ts@@ -1,5 +1,4 @@import { legacyIssueThreadInteractionResolverPolicyAlias } from "@paperclipai/shared";-import type { ConnectionIntentInteraction } from "@paperclipai/shared";import type { LiveRunForIssue } from "../api/heartbeats";import type {IssueChatComment,@@ -8,6 +7,7 @@ import type {import type { IssueTimelineEvent } from "../lib/issue-timeline-events";import type {AskUserQuestionsInteraction,+ ConnectionIntentInteraction,IssueThreadInteractionBase,RequestCheckboxConfirmationInteraction,RequestConfirmationInteraction,@@ -24,45 +24,6 @@ export const issueThreadInteractionFixtureMeta = {currentUserId: "user-board",} as const;-export const pendingConnectionIntentInteraction: ConnectionIntentInteraction = {- id: "interaction-connection-intent-default",- companyId: issueThreadInteractionFixtureMeta.companyId,- issueId: issueThreadInteractionFixtureMeta.issueId,- kind: "connection_intent",- title: "Connect Notion",- summary: "Researcher needs this connection to continue.",- status: "pending",- continuationPolicy: "wake_assignee",- createdByAgentId: "11111111-1111-4111-8111-111111111111",- createdByUserId: null,- resolvedByAgentId: null,- resolvedByUserId: null,- addresseeUserId: issueThreadInteractionFixtureMeta.currentUserId,- createdAt: new Date("2026-04-20T15:08:00.000Z"),- updatedAt: new Date("2026-04-20T15:08:00.000Z"),- resolvedAt: null,- payload: {- version: 1,- serviceSlug: "notion",- serviceName: "Notion",- serviceLogoUrl: null,- serviceDarkLogoUrl: null,- requestingAgentId: "11111111-1111-4111-8111-111111111111",- requestingAgentName: "Researcher",- phase: "requested",- },- result: null,- resolverPolicy: "human_only",- requestedResolverPolicy: "human_only",- effectiveResolverPolicy: "human_only",- resolverPolicyProvenance: "explicit",- effectiveResolverPolicySource: "governed_action",- legacyResolverPolicyAliases: {- requested: "board_only",- effective: "board_only",- },-};-/*** Resolver-audience snapshot fields shared by every interaction fixture.*@@ -910,6 +871,105 @@ export const resolvedConnectionAuthorizationInteraction = createConnectionAuthorresult: { version: 1, outcome: "accepted" },});+function createConnectionIntentInteraction(+ overrides: Partial<ConnectionIntentInteraction> = {},+): ConnectionIntentInteraction {+ return {+ id: "interaction-connection-intent-default",+ companyId: issueThreadInteractionFixtureMeta.companyId,+ issueId: issueThreadInteractionFixtureMeta.issueId,+ kind: "connection_intent",+ title: "Connect Notion",+ summary: "Researcher needs this connection to continue.",+ status: "pending",+ continuationPolicy: "wake_assignee",+ createdByAgentId: "11111111-1111-4111-8111-111111111111",+ createdByUserId: null,+ resolvedByAgentId: null,+ resolvedByUserId: null,+ addresseeUserId: issueThreadInteractionFixtureMeta.currentUserId,+ createdAt: new Date("2026-04-20T15:08:00.000Z"),+ updatedAt: new Date("2026-04-20T15:08:00.000Z"),+ resolvedAt: null,+ payload: {+ version: 1,+ serviceSlug: "notion",+ serviceName: "Notion",+ serviceLogoUrl: null,+ requestingAgentId: "11111111-1111-4111-8111-111111111111",+ requestingAgentName: "Researcher",+ phase: "requested",+ },+ result: null,+ resolverPolicy: "human_only",+ requestedResolverPolicy: "human_only",+ effectiveResolverPolicy: "human_only",+ resolverPolicyProvenance: "explicit",+ effectiveResolverPolicySource: "governed_action",+ legacyResolverPolicyAliases: {+ requested: "board_only",+ effective: "board_only",+ },+ ...overrides,+ };+}++export const pendingConnectionIntentInteraction = createConnectionIntentInteraction();+export const retryConnectionIntentInteraction = createConnectionIntentInteraction({+ id: "interaction-connection-intent-retry",+ payload: {+ version: 1,+ serviceSlug: "notion",+ serviceName: "Notion",+ serviceLogoUrl: null,+ requestingAgentId: "11111111-1111-4111-8111-111111111111",+ requestingAgentName: "Researcher",+ phase: "needs_retry",+ },+});+export const authorizingConnectionIntentInteraction = createConnectionIntentInteraction({+ id: "interaction-connection-intent-authorizing",+ payload: {+ version: 1,+ serviceSlug: "notion",+ serviceName: "Notion",+ serviceLogoUrl: null,+ requestingAgentId: "11111111-1111-4111-8111-111111111111",+ requestingAgentName: "Researcher",+ phase: "authorizing",+ },+});+export const connectedConnectionIntentInteraction = createConnectionIntentInteraction({+ id: "interaction-connection-intent-connected",+ status: "accepted",+ result: {+ version: 1,+ outcome: "connected",+ connectionId: "22222222-2222-4222-8222-222222222222",+ },+ resolvedByUserId: issueThreadInteractionFixtureMeta.currentUserId,+ resolvedAt: new Date("2026-04-20T15:12:00.000Z"),+});+export const declinedConnectionIntentInteraction = createConnectionIntentInteraction({+ id: "interaction-connection-intent-declined",+ status: "rejected",+ result: { version: 1, outcome: "declined", reason: "Not right now" },+ resolvedByUserId: issueThreadInteractionFixtureMeta.currentUserId,+ resolvedAt: new Date("2026-04-20T15:12:00.000Z"),+});+export const supersededConnectionIntentInteraction = createConnectionIntentInteraction({+ id: "interaction-connection-intent-superseded",+ status: "expired",+ result: { version: 1, outcome: "superseded" },+ resolvedAt: new Date("2026-04-20T15:12:00.000Z"),+});+export const expiredConnectionIntentInteraction = createConnectionIntentInteraction({+ id: "interaction-connection-intent-expired",+ status: "expired",+ result: { version: 1, outcome: "expired" },+ resolvedAt: new Date("2026-04-20T15:12:00.000Z"),+});+export const executedSecretProposalInteraction = createSecretProposalConfirmationInteraction({id: "interaction-secret-proposal-executed",status: "accepted",diff --git a/ui/src/lib/app-gallery-copy.ts b/ui/src/lib/app-gallery-copy.tsindex c3960df0f2..19ff687697 100644--- a/ui/src/lib/app-gallery-copy.ts+++ b/ui/src/lib/app-gallery-copy.ts@@ -68,7 +68,7 @@ const APP_COPY: Record<string, AppCopy> = {},posthog: {tagline: "Explore product usage, errors, flags, and experiments.",- short: "Choose one project and the analytics tools your agents can use.",+ short: "Sign in with PostHog. Project pinning and access controls are optional.",},linear: {tagline: "Create, update and read tickets.",@@ -76,12 +76,40 @@ const APP_COPY: Record<string, AppCopy> = {},"google-sheets": {tagline: "Read and update selected spreadsheets.",- short: "Share each sheet with the robot email, then paste the links.",+ short: "Read spreadsheets or update the files you choose.",},gmail: {tagline: "Read mail and create drafts for your review.",short: "Read mail and create drafts for your review.",},+ "google-drive": {+ tagline: "Find, read, and create files in Drive.",+ short: "Find, read, and create files in Drive.",+ },+ "google-docs": {+ tagline: "Read and update documents.",+ short: "Read and update documents.",+ },+ "google-slides": {+ tagline: "Read and update presentations.",+ short: "Read and update presentations.",+ },+ "google-calendar": {+ tagline: "Review calendars and manage events.",+ short: "Review calendars and manage events.",+ },+ "google-chat": {+ tagline: "Read conversations and send messages.",+ short: "Read conversations and send messages.",+ },+ "google-people": {+ tagline: "Look up contacts and people in your directory.",+ short: "Look up contacts and people in your directory.",+ },+ "google-workspace-search": {+ tagline: "Search across your Google workspace.",+ short: "Search across your Google workspace.",+ },hubspot: {tagline: "Look up contacts and update deal stages.",short: "Look up contacts and update deal stages.",diff --git a/ui/src/lib/issue-chat-messages.test.ts b/ui/src/lib/issue-chat-messages.test.tsindex 68fa9c2c90..4828b7650d 100644--- a/ui/src/lib/issue-chat-messages.test.ts+++ b/ui/src/lib/issue-chat-messages.test.ts@@ -12,13 +12,71 @@ import {import type {AskUserQuestionsInteraction,AskUserQuestionsQuestion,+ ConnectionIntentInteraction,RequestConfirmationInteraction,SuggestTasksInteraction,} from "./issue-thread-interactions";+import { pendingConnectionIntentInteraction } from "../fixtures/issueThreadInteractionFixtures";import type { IssueTimelineEvent } from "./issue-timeline-events";import type { ActiveRunForIssue, LiveRunForIssue } from "../api/heartbeats";import { registerUIAdapter, unregisterUIAdapter } from "../adapters/registry";+describe("connection intents in the task feed", () => {+ it("orders the card chronologically and collapses live/polling snapshots into one updated message", () => {+ const pending = {+ ...pendingConnectionIntentInteraction,+ createdAt: new Date("2026-08-26T12:02:00.000Z"),+ updatedAt: new Date("2026-08-26T12:02:00.000Z"),+ };+ const connected: ConnectionIntentInteraction = {+ ...pending,+ status: "accepted",+ updatedAt: new Date("2026-08-26T12:04:00.000Z"),+ resolvedAt: new Date("2026-08-26T12:04:00.000Z"),+ result: {+ version: 1,+ outcome: "connected",+ connectionId: "connection-1",+ },+ };+ const messages = buildIssueChatMessages({+ comments: [+ createComment({+ id: "before",+ body: "Before",+ createdAt: new Date("2026-08-26T12:01:00.000Z"),+ }),+ createComment({+ id: "after",+ body: "After",+ createdAt: new Date("2026-08-26T12:03:00.000Z"),+ }),+ ],+ // Models the brief overlap where live invalidation and polling each+ // supplied a snapshot of the same interaction id.+ interactions: [pending, connected],+ timelineEvents: [],+ linkedRuns: [],+ liveRuns: [],+ });++ expect(messages.map((message) => message.id)).toEqual([+ "before",+ `interaction:${pending.id}`,+ "after",+ ]);+ const interactionMessages = messages.filter(+ (message) => message.id === `interaction:${pending.id}`,+ );+ expect(interactionMessages).toHaveLength(1);+ const custom = interactionMessages[0]?.metadata?.custom as {+ interaction?: ConnectionIntentInteraction;+ };+ expect(custom.interaction?.status).toBe("accepted");+ expect(custom.interaction?.result?.outcome).toBe("connected");+ });+});+function createAgent(id: string, name: string): Agent {return {id,@@ -46,7 +104,9 @@ function createAgent(id: string, name: string): Agent {} as Agent;}-function createComment(overrides: Partial<IssueChatComment> = {}): IssueChatComment {+function createComment(+ overrides: Partial<IssueChatComment> = {},+): IssueChatComment {const authorAgentId = overrides.authorAgentId ?? null;return {id: "comment-1",@@ -99,9 +159,12 @@ function createInteraction(requestedResolverPolicy: overrides.requestedResolverPolicy ?? "anyone",effectiveResolverPolicy: overrides.effectiveResolverPolicy ?? "anyone",resolverPolicyProvenance: overrides.resolverPolicyProvenance ?? "inherited",- effectiveResolverPolicySource: overrides.effectiveResolverPolicySource ?? "requested",- legacyResolverPolicyAliases: overrides.legacyResolverPolicyAliases- ?? { requested: "board_or_agents", effective: "board_or_agents" },+ effectiveResolverPolicySource:+ overrides.effectiveResolverPolicySource ?? "requested",+ legacyResolverPolicyAliases: overrides.legacyResolverPolicyAliases ?? {+ requested: "board_or_agents",+ effective: "board_or_agents",+ },};}@@ -134,18 +197,29 @@ function createRequestConfirmation(requestedResolverPolicy: overrides.requestedResolverPolicy ?? "anyone",effectiveResolverPolicy: overrides.effectiveResolverPolicy ?? "anyone",resolverPolicyProvenance: overrides.resolverPolicyProvenance ?? "inherited",- effectiveResolverPolicySource: overrides.effectiveResolverPolicySource ?? "requested",- legacyResolverPolicyAliases: overrides.legacyResolverPolicyAliases- ?? { requested: "board_or_agents", effective: "board_or_agents" },+ effectiveResolverPolicySource:+ overrides.effectiveResolverPolicySource ?? "requested",+ legacyResolverPolicyAliases: overrides.legacyResolverPolicyAliases ?? {+ requested: "board_or_agents",+ effective: "board_or_agents",+ },};}describe("buildAssistantPartsFromTranscript", () => {it("maps assistant text, reasoning, and tool activity while omitting noisy stderr", () => {const result = buildAssistantPartsFromTranscript([- { kind: "assistant", ts: "2026-04-06T12:00:00.000Z", text: "Working on it. " },+ {+ kind: "assistant",+ ts: "2026-04-06T12:00:00.000Z",+ text: "Working on it. ",+ },{ kind: "assistant", ts: "2026-04-06T12:00:01.000Z", text: "Done." },- { kind: "thinking", ts: "2026-04-06T12:00:02.000Z", text: "Need to inspect files." },+ {+ kind: "thinking",+ ts: "2026-04-06T12:00:02.000Z",+ text: "Need to inspect files.",+ },{kind: "tool_call",ts: "2026-04-06T12:00:03.000Z",@@ -160,12 +234,22 @@ describe("buildAssistantPartsFromTranscript", () => {content: "file contents",isError: false,},- { kind: "stderr", ts: "2026-04-06T12:00:05.000Z", text: "warn: noisy setup output" },+ {+ kind: "stderr",+ ts: "2026-04-06T12:00:05.000Z",+ text: "warn: noisy setup output",+ },]);expect(result.parts).toHaveLength(3);- expect(result.parts[0]).toMatchObject({ type: "text", text: "Working on it. Done." });- expect(result.parts[1]).toMatchObject({ type: "reasoning", text: "Need to inspect files." });+ expect(result.parts[0]).toMatchObject({+ type: "text",+ text: "Working on it. Done.",+ });+ expect(result.parts[1]).toMatchObject({+ type: "reasoning",+ text: "Need to inspect files.",+ });expect(result.parts[2]).toMatchObject({type: "tool-call",toolCallId: "tool-1",@@ -194,7 +278,11 @@ describe("buildAssistantPartsFromTranscript", () => {content: "ok",isError: false,},- { kind: "thinking", ts: "2026-04-06T12:00:04.000Z", text: "Need one more check." },+ {+ kind: "thinking",+ ts: "2026-04-06T12:00:04.000Z",+ text: "Need one more check.",+ },{kind: "tool_call",ts: "2026-04-06T12:00:05.000Z",@@ -213,16 +301,30 @@ describe("buildAssistantPartsFromTranscript", () => {expect(result.parts).toMatchObject([{ type: "text", text: "First." },- { type: "tool-call", toolCallId: "tool-1", toolName: "read_file", result: "ok" },+ {+ type: "tool-call",+ toolCallId: "tool-1",+ toolName: "read_file",+ result: "ok",+ },{ type: "text", text: "Second." },{ type: "reasoning", text: "Need one more check." },- { type: "tool-call", toolCallId: "tool-2", toolName: "write_file", result: "saved" },+ {+ type: "tool-call",+ toolCallId: "tool-2",+ toolName: "write_file",+ result: "saved",+ },]);});it("treats a completed tool-only segment as resolved once a tool_result arrives", () => {const result = buildAssistantPartsFromTranscript([- { kind: "thinking", ts: "2026-04-06T12:00:00.000Z", text: "Checking the task." },+ {+ kind: "thinking",+ ts: "2026-04-06T12:00:00.000Z",+ text: "Checking the task.",+ },{kind: "tool_call",ts: "2026-04-06T12:00:01.000Z",@@ -237,7 +339,11 @@ describe("buildAssistantPartsFromTranscript", () => {content: "search completed",isError: false,},- { kind: "assistant", ts: "2026-04-06T12:00:03.000Z", text: "Found the relevant code." },+ {+ kind: "assistant",+ ts: "2026-04-06T12:00:03.000Z",+ text: "Found the relevant code.",+ },]);expect(result.parts).toMatchObject([@@ -251,28 +357,36 @@ describe("buildAssistantPartsFromTranscript", () => {},{ type: "text", text: "Found the relevant code." },]);- expect(result.segments).toEqual([{- startMs: new Date("2026-04-06T12:00:00.000Z").getTime(),- endMs: new Date("2026-04-06T12:00:02.000Z").getTime(),- }]);+ expect(result.segments).toEqual([+ {+ startMs: new Date("2026-04-06T12:00:00.000Z").getTime(),+ endMs: new Date("2026-04-06T12:00:02.000Z").getTime(),+ },+ ]);});it("marks only the latest chain-of-thought segment active while a run is live", () => {- expect(isCoTSegmentActive({- isMessageRunning: true,- segmentIndex: 0,- segmentCount: 2,- })).toBe(false);- expect(isCoTSegmentActive({- isMessageRunning: true,- segmentIndex: 1,- segmentCount: 2,- })).toBe(true);- expect(isCoTSegmentActive({- isMessageRunning: false,- segmentIndex: 1,- segmentCount: 2,- })).toBe(false);+ expect(+ isCoTSegmentActive({+ isMessageRunning: true,+ segmentIndex: 0,+ segmentCount: 2,+ }),+ ).toBe(false);+ expect(+ isCoTSegmentActive({+ isMessageRunning: true,+ segmentIndex: 1,+ segmentCount: 2,+ }),+ ).toBe(true);+ expect(+ isCoTSegmentActive({+ isMessageRunning: false,+ segmentIndex: 1,+ segmentCount: 2,+ }),+ ).toBe(false);});it("keeps run errors while suppressing init and system transcript noise", () => {@@ -318,10 +432,29 @@ describe("buildAssistantPartsFromTranscript", () => {it("preserves diff transcript output as a fenced diff block", () => {const result = buildAssistantPartsFromTranscript([- { kind: "assistant", ts: "2026-04-06T12:00:00.000Z", text: "Applied the patch." },- { kind: "diff", ts: "2026-04-06T12:00:01.000Z", changeType: "file_header", text: "ui/src/lib/issue-chat-messages.ts" },- { kind: "diff", ts: "2026-04-06T12:00:02.000Z", changeType: "add", text: "+function formatDiffBlock(lines: string[]) {" },- { kind: "diff", ts: "2026-04-06T12:00:03.000Z", changeType: "add", text: "+ return ````diff`;" },+ {+ kind: "assistant",+ ts: "2026-04-06T12:00:00.000Z",+ text: "Applied the patch.",+ },+ {+ kind: "diff",+ ts: "2026-04-06T12:00:01.000Z",+ changeType: "file_header",+ text: "ui/src/lib/issue-chat-messages.ts",+ },+ {+ kind: "diff",+ ts: "2026-04-06T12:00:02.000Z",+ changeType: "add",+ text: "+function formatDiffBlock(lines: string[]) {",+ },+ {+ kind: "diff",+ ts: "2026-04-06T12:00:03.000Z",+ changeType: "add",+ text: "+ return ````diff`;",+ },]);expect(result.parts).toMatchObject([@@ -374,7 +507,10 @@ describe("buildIssueChatMessages", () => {createdAt: new Date("2026-04-06T12:01:00.000Z"),startedAt: new Date("2026-04-06T12:01:00.000Z"),finishedAt: new Date("2026-04-06T12:02:00.000Z"),- resultJson: { operatorInterrupted: true, interruptionSource: "issue_comment_interrupt" },+ resultJson: {+ operatorInterrupted: true,+ interruptionSource: "issue_comment_interrupt",+ },},{runId: "run-plain",@@ -389,10 +525,18 @@ describe("buildIssueChatMessages", () => {liveRuns: [],});- const interrupted = messages.find((message) => message.id === "run-assistant:run-int");- const plain = messages.find((message) => message.id === "run-assistant:run-plain");- expect(interrupted?.metadata?.custom).toMatchObject({ runOperatorInterrupted: true });- expect(plain?.metadata?.custom).toMatchObject({ runOperatorInterrupted: false });+ const interrupted = messages.find(+ (message) => message.id === "run-assistant:run-int",+ );+ const plain = messages.find(+ (message) => message.id === "run-assistant:run-plain",+ );+ expect(interrupted?.metadata?.custom).toMatchObject({+ runOperatorInterrupted: true,+ });+ expect(plain?.metadata?.custom).toMatchObject({+ runOperatorInterrupted: false,+ });});it("redacts deleted comment bodies while preserving tombstone metadata", () => {@@ -437,7 +581,9 @@ describe("buildIssueChatMessages", () => {timelineEvents: [],linkedRuns: [],liveRuns: [],- agentMap: new Map([["agent-1", createAgent("agent-1", "Low Trust Reviewer")]]),+ agentMap: new Map([+ ["agent-1", createAgent("agent-1", "Low Trust Reviewer")],+ ]),});expect(messages[0]?.metadata.custom.sourceTrust).toMatchObject({@@ -448,7 +594,9 @@ describe("buildIssueChatMessages", () => {});it("prefers derived agent attribution when a board-authored comment is proven to come from a run", () => {- const agentMap = new Map<string, Agent>([["agent-1", createAgent("agent-1", "Claude")]]);+ const agentMap = new Map<string, Agent>([+ ["agent-1", createAgent("agent-1", "Claude")],+ ]);const messages = buildIssueChatMessages({comments: [createComment({@@ -481,7 +629,9 @@ describe("buildIssueChatMessages", () => {});it("does not reattribute a genuine board/user comment that has no derived agent", () => {- const agentMap = new Map<string, Agent>([["agent-1", createAgent("agent-1", "Claude")]]);+ const agentMap = new Map<string, Agent>([+ ["agent-1", createAgent("agent-1", "Claude")],+ ]);const messages = buildIssueChatMessages({comments: [createComment({@@ -515,7 +665,9 @@ describe("buildIssueChatMessages", () => {});it("renders a comment as agent-authored when runAgentId is set from activity log", () => {- const agentMap = new Map<string, Agent>([["agent-1", createAgent("agent-1", "Claude")]]);+ const agentMap = new Map<string, Agent>([+ ["agent-1", createAgent("agent-1", "Claude")],+ ]);const messages = buildIssueChatMessages({comments: [createComment({@@ -548,7 +700,9 @@ describe("buildIssueChatMessages", () => {});it("orders events before comments and appends active live runs as running assistant messages", () => {- const agentMap = new Map<string, Agent>([["agent-1", createAgent("agent-1", "CodexCoder")]]);+ const agentMap = new Map<string, Agent>([+ ["agent-1", createAgent("agent-1", "CodexCoder")],+ ]);const comments = [createComment(),createComment({@@ -607,7 +761,13 @@ describe("buildIssueChatMessages", () => {transcriptsByRunId: new Map([["run-live-1",- [{ kind: "assistant", ts: "2026-04-06T12:04:01.000Z", text: "Streaming reply" }],+ [+ {+ kind: "assistant",+ ts: "2026-04-06T12:04:01.000Z",+ text: "Streaming reply",+ },+ ],],]),hasOutputForRun: (runId) => runId === "run-live-1",@@ -666,8 +826,16 @@ describe("buildIssueChatMessages", () => {currentUserId: "user-1",});- expect(terminalMessages.find((message) => message.id === "run-assistant:run-live-terminal")).toBeUndefined();- expect(liveMessages.find((message) => message.id === "run-assistant:run-live-terminal")).toMatchObject({+ expect(+ terminalMessages.find(+ (message) => message.id === "run-assistant:run-live-terminal",+ ),+ ).toBeUndefined();+ expect(+ liveMessages.find(+ (message) => message.id === "run-assistant:run-live-terminal",+ ),+ ).toMatchObject({status: { type: "running" },metadata: { custom: { waitingText: "Working..." } },});@@ -708,7 +876,13 @@ describe("buildIssueChatMessages", () => {transcriptsByRunId: new Map([["run-live-1",- [{ kind: "assistant", ts: "2026-04-06T12:03:01.000Z", text: "Working on it." }],+ [+ {+ kind: "assistant",+ ts: "2026-04-06T12:03:01.000Z",+ text: "Working on it.",+ },+ ],],]),hasOutputForRun: (runId) => runId === "run-live-1",@@ -756,7 +930,10 @@ describe("buildIssueChatMessages", () => {effectiveResolverPolicy: "anyone",resolverPolicyProvenance: "inherited",effectiveResolverPolicySource: "requested",- legacyResolverPolicyAliases: { requested: "board_or_agents", effective: "board_or_agents" },+ legacyResolverPolicyAliases: {+ requested: "board_or_agents",+ effective: "board_or_agents",+ },payload: { version: 1, questions },result: null,} as AskUserQuestionsInteraction;@@ -774,7 +951,12 @@ describe("buildIssueChatMessages", () => {// A truly unanswerable card (no options, no free-text) — must be// filtered out entirely.askInteraction("interaction-degenerate", [- { id: "q1", prompt: "Anything?", selectionMode: "single", options: [] },+ {+ id: "q1",+ prompt: "Anything?",+ selectionMode: "single",+ options: [],+ },]),// A legitimate yes/no question survives.askInteraction("interaction-legit", [@@ -797,7 +979,10 @@ describe("buildIssueChatMessages", () => {const ids = messages.map((message) => `${message.role}:${message.id}`);// The legit card is present; the degenerate one leaves no message at all.- expect(ids).toEqual(["user:comment-1", "system:interaction:interaction-legit"]);+ expect(ids).toEqual([+ "user:comment-1",+ "system:interaction:interaction-legit",+ ]);expect(ids).not.toContain("system:interaction:interaction-degenerate");});@@ -972,7 +1157,9 @@ describe("buildIssueChatMessages", () => {});it("keeps succeeded runs as assistant messages when transcript output exists", () => {- const agentMap = new Map<string, Agent>([["agent-1", createAgent("agent-1", "CodexCoder")]]);+ const agentMap = new Map<string, Agent>([+ ["agent-1", createAgent("agent-1", "CodexCoder")],+ ]);const messages = buildIssueChatMessages({comments: [],timelineEvents: [],@@ -991,8 +1178,16 @@ describe("buildIssueChatMessages", () => {["run-history-1",[- { kind: "thinking", ts: "2026-04-06T12:01:10.000Z", text: "Checking the current issue thread." },- { kind: "assistant", ts: "2026-04-06T12:02:30.000Z", text: "Updated the thread renderer." },+ {+ kind: "thinking",+ ts: "2026-04-06T12:01:10.000Z",+ text: "Checking the current issue thread.",+ },+ {+ kind: "assistant",+ ts: "2026-04-06T12:02:30.000Z",+ text: "Updated the thread renderer.",+ },],],]),@@ -1072,16 +1267,22 @@ describe("buildIssueChatMessages", () => {});expect(messages).toHaveLength(1);- const textParts = messages[0]?.content- .filter((part): part is { type: "text"; text: string } => part.type === "text")- .map((part) => part.text) ?? [];+ const textParts =+ messages[0]?.content+ .filter(+ (part): part is { type: "text"; text: string } =>+ part.type === "text",+ )+ .map((part) => part.text) ?? [];expect(textParts.join("\n")).not.toContain("Older update 1");- expect(messages[0]?.content).toContainEqual(expect.objectContaining({- type: "tool-call",- toolCallId: "tool-keep",- toolName: "search",- result: "search completed",- }));+ expect(messages[0]?.content).toContainEqual(+ expect.objectContaining({+ type: "tool-call",+ toolCallId: "tool-keep",+ toolName: "search",+ result: "search completed",+ }),+ );});it("honors a wider transcript window declared by an adapter's UI module", () => {@@ -1096,7 +1297,10 @@ describe("buildIssueChatMessages", () => {parseStdoutLine: () => [],ConfigFields: () => null,buildAdapterConfig: () => ({}),- transcriptPresentation: { maxVisibleEntries: 400, liveReasoningView: "scrollLog" },+ transcriptPresentation: {+ maxVisibleEntries: 400,+ liveReasoningView: "scrollLog",+ },});try {@@ -1154,9 +1358,13 @@ describe("buildIssueChatMessages", () => {});expect(messages).toHaveLength(1);- const textParts = messages[0]?.content- .filter((part): part is { type: "text"; text: string } => part.type === "text")- .map((part) => part.text) ?? [];+ const textParts =+ messages[0]?.content+ .filter(+ (part): part is { type: "text"; text: string } =>+ part.type === "text",+ )+ .map((part) => part.text) ?? [];expect(textParts.join("\n")).toContain("Older update 1");expect(textParts.join("\n")).toContain("Recent update 79");} finally {@@ -1184,7 +1392,16 @@ describe("buildIssueChatMessages", () => {},],transcriptsByRunId: new Map([- ["run-1", [{ kind: "assistant", ts: "2026-04-06T12:01:05.000Z", text: "Working on it." }]],+ [+ "run-1",+ [+ {+ kind: "assistant",+ ts: "2026-04-06T12:01:05.000Z",+ text: "Working on it.",+ },+ ],+ ],]),hasOutputForRun: (runId) => runId === "run-1",currentUserId: "user-1",@@ -1206,7 +1423,16 @@ describe("buildIssueChatMessages", () => {],liveRuns: [],transcriptsByRunId: new Map([- ["run-1", [{ kind: "assistant", ts: "2026-04-06T12:01:05.000Z", text: "Working on it." }]],+ [+ "run-1",+ [+ {+ kind: "assistant",+ ts: "2026-04-06T12:01:05.000Z",+ text: "Working on it.",+ },+ ],+ ],]),hasOutputForRun: (runId) => runId === "run-1",currentUserId: "user-1",@@ -1214,7 +1440,10 @@ describe("buildIssueChatMessages", () => {expect(liveMessages).toHaveLength(1);expect(cancelledMessages).toHaveLength(1);- expect(liveMessages[0]).toMatchObject({ id: "run-assistant:run-1", status: { type: "running" } });+ expect(liveMessages[0]).toMatchObject({+ id: "run-assistant:run-1",+ status: { type: "running" },+ });expect(cancelledMessages[0]).toMatchObject({id: "run-assistant:run-1",status: { type: "complete", reason: "stop" },@@ -1240,7 +1469,16 @@ describe("buildIssueChatMessages", () => {],liveRuns: [],transcriptsByRunId: new Map([- ["run-paused", [{ kind: "assistant", ts: "2026-04-06T12:01:05.000Z", text: "Working on it." }]],+ [+ "run-paused",+ [+ {+ kind: "assistant",+ ts: "2026-04-06T12:01:05.000Z",+ text: "Working on it.",+ },+ ],+ ],]),hasOutputForRun: (runId) => runId === "run-paused",currentUserId: "user-1",@@ -1272,7 +1510,16 @@ describe("buildIssueChatMessages", () => {],liveRuns: [],transcriptsByRunId: new Map([- ["run-interrupted", [{ kind: "assistant", ts: "2026-04-06T12:01:05.000Z", text: "Working on it." }]],+ [+ "run-interrupted",+ [+ {+ kind: "assistant",+ ts: "2026-04-06T12:01:05.000Z",+ text: "Working on it.",+ },+ ],+ ],]),hasOutputForRun: (runId) => runId === "run-interrupted",currentUserId: "user-1",@@ -1324,56 +1571,66 @@ describe("buildIssueChatMessages", () => {describe("stabilizeThreadMessages", () => {it("reveals live streamed additions at word boundaries instead of character boundaries", () => {- expect(preserveReadableStreamingRetraction(- "Writing ",- "Writing the pla",- )).toBe("Writing the ");- expect(preserveReadableStreamingRetraction(- "Writing ",- "Writing the plan ",- )).toBe("Writing the plan ");- expect(preserveReadableStreamingRetraction(- "Writing ",- "Writing the plan.",- )).toBe("Writing the plan.");- expect(preserveReadableStreamingRetraction(- "Writing ",- "Writing draft",- )).toBe("Writing draft");+ expect(+ preserveReadableStreamingRetraction("Writing ", "Writing the pla"),+ ).toBe("Writing the ");+ expect(+ preserveReadableStreamingRetraction("Writing ", "Writing the plan "),+ ).toBe("Writing the plan ");+ expect(+ preserveReadableStreamingRetraction("Writing ", "Writing the plan."),+ ).toBe("Writing the plan.");+ expect(+ preserveReadableStreamingRetraction("Writing ", "Writing draft"),+ ).toBe("Writing draft");});it("holds sliding-window removals until an older paragraph or group boundary drops", () => {- expect(preserveReadableStreamingRetraction(- "First sentence. Second sentence is visible",- "irst sentence. Second sentence is visible now ",- )).toBe("irst sentence. Second sentence is visible now ");- expect(preserveReadableStreamingRetraction(- "First sentence. Second sentence is visible",- "Second sentence is visible now ",- )).toBe("Second sentence is visible now ");- expect(preserveReadableStreamingRetraction(- "Paragraph one.\n\nParagraph two is visible",- "Paragraph two is visible now ",- )).toBe("Paragraph two is visible now ");- expect(preserveReadableStreamingRetraction(- "The answer is 42",- "42 is the answer",- )).toBe("42 is the answer");- expect(preserveReadableStreamingRetraction(- "The quick brown fox jumps over the lazy dog",- "quick brown fox jumps over the lazy dog near the river",- )).toBe("quick brown fox jumps over the lazy dog near the river");+ expect(+ preserveReadableStreamingRetraction(+ "First sentence. Second sentence is visible",+ "irst sentence. Second sentence is visible now ",+ ),+ ).toBe("irst sentence. Second sentence is visible now ");+ expect(+ preserveReadableStreamingRetraction(+ "First sentence. Second sentence is visible",+ "Second sentence is visible now ",+ ),+ ).toBe("Second sentence is visible now ");+ expect(+ preserveReadableStreamingRetraction(+ "Paragraph one.\n\nParagraph two is visible",+ "Paragraph two is visible now ",+ ),+ ).toBe("Paragraph two is visible now ");+ expect(+ preserveReadableStreamingRetraction(+ "The answer is 42",+ "42 is the answer",+ ),+ ).toBe("42 is the answer");+ expect(+ preserveReadableStreamingRetraction(+ "The quick brown fox jumps over the lazy dog",+ "quick brown fox jumps over the lazy dog near the river",+ ),+ ).toBe("quick brown fox jumps over the lazy dog near the river");});it("keeps live streamed retractions readable until a whole line disappears", () => {- expect(preserveReadableStreamingRetraction(- "First line\nSecond line\nThird line is complete",- "First line\nSecond line\nThird line",- )).toBe("First line\nSecond line\nThird line is complete");- expect(preserveReadableStreamingRetraction(- "First line\nSecond line\nThird line is complete",- "First line\nSecond line",- )).toBe("First line\nSecond line");+ expect(+ preserveReadableStreamingRetraction(+ "First line\nSecond line\nThird line is complete",+ "First line\nSecond line\nThird line",+ ),+ ).toBe("First line\nSecond line\nThird line is complete");+ expect(+ preserveReadableStreamingRetraction(+ "First line\nSecond line\nThird line is complete",+ "First line\nSecond line",+ ),+ ).toBe("First line\nSecond line");const liveRun: LiveRunForIssue = {id: "run-live-retract",@@ -1387,20 +1644,28 @@ describe("stabilizeThreadMessages", () => {agentName: "CodexCoder",adapterType: "codex_local",};- const buildLiveMessages = (text: string) => buildIssueChatMessages({- comments: [],- timelineEvents: [],- linkedRuns: [],- liveRuns: [liveRun],- transcriptsByRunId: new Map([- ["run-live-retract", [{ kind: "assistant", ts: "2026-04-06T12:04:01.000Z", text }]],- ]),- hasOutputForRun: (runId) => runId === "run-live-retract",- currentUserId: "user-1",- });+ const buildLiveMessages = (text: string) =>+ buildIssueChatMessages({+ comments: [],+ timelineEvents: [],+ linkedRuns: [],+ liveRuns: [liveRun],+ transcriptsByRunId: new Map([+ [+ "run-live-retract",+ [{ kind: "assistant", ts: "2026-04-06T12:04:01.000Z", text }],+ ],+ ]),+ hasOutputForRun: (runId) => runId === "run-live-retract",+ currentUserId: "user-1",+ });const fullText = "First line\nSecond line\nThird line is complete";- const firstStable = stabilizeThreadMessages(buildLiveMessages(fullText), [], new Map());+ const firstStable = stabilizeThreadMessages(+ buildLiveMessages(fullText),+ [],+ new Map(),+ );const partialRetractionStable = stabilizeThreadMessages(buildLiveMessages("First line\nSecond line\nThird line"),firstStable.messages,diff --git a/ui/src/lib/issue-chat-messages.ts b/ui/src/lib/issue-chat-messages.tsindex 8187c5a455..ec1eb11dd8 100644--- a/ui/src/lib/issue-chat-messages.ts+++ b/ui/src/lib/issue-chat-messages.ts@@ -274,6 +274,30 @@ function sortByCreated<T extends { createdAt: Date | string; id: string }>(items});}+function dedupeInteractionsById(+ interactions: readonly IssueThreadInteraction[],+): IssueThreadInteraction[] {+ const byId = new Map<string, IssueThreadInteraction>();+ for (const interaction of interactions) {+ const previous = byId.get(interaction.id);+ if (!previous) {+ byId.set(interaction.id, interaction);+ continue;+ }+ const previousUpdatedAt = toTimestamp(previous.updatedAt);+ const nextUpdatedAt = toTimestamp(interaction.updatedAt);+ if (+ nextUpdatedAt > previousUpdatedAt+ || (nextUpdatedAt === previousUpdatedAt+ && previous.status === "pending"+ && interaction.status !== "pending")+ ) {+ byId.set(interaction.id, interaction);+ }+ }+ return [...byId.values()];+}+export function latestSameRunHandoffTimestamp(args: {interactionCreatedAtMs: number;sourceRunId: string;@@ -1105,7 +1129,11 @@ export function buildIssueChatMessages(args: {});}- for (const interaction of sortByCreated(interactions)) {+ // A live-event cache patch and the polling response can briefly contain the+ // same interaction. Collapse by id before constructing messages, preferring+ // the newest/terminal snapshot so a resolved connection card updates in its+ // existing thread slot instead of flashing a duplicate beside itself.+ for (const interaction of sortByCreated(dedupeInteractionsById(interactions))) {// A card IssueThreadInteractionCard never renders — a degenerate// `ask_user_questions` (e.g. the onboarding `Test / A` placeholder) or a// stale sibling superseded by a newer question (PAP-437) — is skipped here sodiff --git a/ui/src/lib/issue-thread-interactions.ts b/ui/src/lib/issue-thread-interactions.tsindex f0bc055a1c..b1217bed57 100644--- a/ui/src/lib/issue-thread-interactions.ts+++ b/ui/src/lib/issue-thread-interactions.ts@@ -5,6 +5,9 @@ export type {AskUserQuestionsQuestion,AskUserQuestionsQuestionOption,AskUserQuestionsResult,+ ConnectionIntentInteraction,+ ConnectionIntentPayload,+ ConnectionIntentResult,IssueThreadInteraction,IssueThreadInteractionActorFields,IssueThreadInteractionBase,@@ -40,6 +43,7 @@ import type {AskUserQuestionsAnswer,AskUserQuestionsInteraction,AskUserQuestionsQuestion,+ ConnectionIntentInteraction,IssueThreadInteraction,RequestCheckboxConfirmationPayload,RequestCheckboxConfirmationResult,@@ -73,6 +77,7 @@ export function isIssueThreadInteraction(|| candidate.kind === "request_confirmation"|| candidate.kind === "request_checkbox_confirmation"|| candidate.kind === "request_item_verdicts"+ || candidate.kind === "connection_intent");}@@ -240,13 +245,14 @@ export function buildIssueThreadInteractionSummary(}if (interaction.kind === "connection_intent") {- const serviceName = interaction.payload.serviceName;- const outcome = interaction.result?.outcome;- if (outcome === "connected") return `Connected ${serviceName}`;- if (outcome === "declined") return `Declined ${serviceName} connection`;- if (outcome === "superseded") return `${serviceName} connection request was superseded`;- if (outcome === "expired") return `${serviceName} connection request expired`;- return `Requested a ${serviceName} connection`;+ if (interaction.status === "accepted") return `${interaction.payload.serviceName} connected`;+ if (interaction.status === "rejected") return `${interaction.payload.serviceName} declined`;+ if (interaction.status === "expired") {+ return interaction.result?.outcome === "superseded"+ ? `${interaction.payload.serviceName} request superseded`+ : `${interaction.payload.serviceName} request expired`;+ }+ return `Connect ${interaction.payload.serviceName}`;}const count = interaction.payload.questions.length;diff --git a/ui/src/lib/react-root.test.ts b/ui/src/lib/react-root.test.tsnew file mode 100644index 0000000000..1c1b83278e--- /dev/null+++ b/ui/src/lib/react-root.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it, vi } from "vitest";+import type { Root } from "react-dom/client";+import {+ getOrCreatePaperclipReactRoot,+ type PaperclipReactRootHost,+} from "./react-root";++describe("getOrCreatePaperclipReactRoot", () => {+ it("reuses the existing root when the entry module runs again", () => {+ const host: PaperclipReactRootHost = {};+ const container = {} as Parameters<typeof getOrCreatePaperclipReactRoot>[1];+ const root = { render: vi.fn(), unmount: vi.fn() } as unknown as Root;+ const createRoot = vi.fn(() => root);++ expect(getOrCreatePaperclipReactRoot(host, container, createRoot)).toBe(root);+ expect(getOrCreatePaperclipReactRoot(host, container, createRoot)).toBe(root);+ expect(createRoot).toHaveBeenCalledTimes(1);+ expect(createRoot).toHaveBeenCalledWith(container);+ });+});diff --git a/ui/src/lib/react-root.ts b/ui/src/lib/react-root.tsnew file mode 100644index 0000000000..ac7f312669--- /dev/null+++ b/ui/src/lib/react-root.ts@@ -0,0 +1,24 @@+import { createRoot, type Root } from "react-dom/client";++export interface PaperclipReactRootHost {+ __paperclipReactRoot?: Root;+}++type CreateRoot = (container: Parameters<typeof createRoot>[0]) => Root;++/**+ * Keep one React root per browser window even if Vite evaluates the entry+ * module more than once during a development reload.+ */+export function getOrCreatePaperclipReactRoot(+ host: object,+ container: Parameters<typeof createRoot>[0],+ create: CreateRoot = createRoot,+): Root {+ const rootHost = host as PaperclipReactRootHost;+ if (rootHost.__paperclipReactRoot) return rootHost.__paperclipReactRoot;++ const root = create(container);+ rootHost.__paperclipReactRoot = root;+ return root;+}diff --git a/ui/src/main.tsx b/ui/src/main.tsxindex 6496fe3558..a12e3130d7 100644--- a/ui/src/main.tsx+++ b/ui/src/main.tsx@@ -1,7 +1,6 @@import * as React from "react";import { StrictMode } from "react";import * as ReactDOM from "react-dom";-import { createRoot } from "react-dom/client";import { BrowserRouter } from "@/lib/router";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { App } from "./App";@@ -20,6 +19,7 @@ import { TooltipProvider } from "@/components/ui/tooltip";import { initPluginBridge } from "./plugins/bridge-init";import { PluginLauncherProvider } from "./plugins/launchers";import { startPerfMeasureReaper } from "./lib/perf-measure-reaper";+import { getOrCreatePaperclipReactRoot } from "./lib/react-root";import { startServiceWorkerUpdates } from "./lib/service-worker-updates";import "@mdxeditor/editor/style.css";import "./index.css";@@ -57,7 +57,10 @@ function CompanyAwareBreadcrumbProvider({ children }: { children: React.ReactNodreturn <BreadcrumbProvider companyName={selectedCompany?.name ?? null}>{children}</BreadcrumbProvider>;}-createRoot(document.getElementById("root")!).render(+const rootElement = document.getElementById("root");+if (!rootElement) throw new Error("Paperclip root element is missing");++getOrCreatePaperclipReactRoot(window, rootElement).render(<StrictMode><AppErrorBoundary><QueryClientProvider client={queryClient}>diff --git a/ui/src/pages/DesignGuide.tsx b/ui/src/pages/DesignGuide.tsxindex eb86cf7a6e..78da658a08 100644--- a/ui/src/pages/DesignGuide.tsx+++ b/ui/src/pages/DesignGuide.tsx@@ -137,10 +137,18 @@ import { FilterBar, type FilterValue } from "@/components/FilterBar";import { InlineEditor } from "@/components/InlineEditor";import { PageSkeleton } from "@/components/PageSkeleton";import { Identity } from "@/components/Identity";+import { AppLogo } from "@/pages/apps/AppLogo";import { IssueReferencePill } from "@/components/IssueReferencePill";import { MembershipAction } from "@/components/MembershipAction";import { IssueOutputSection } from "@/components/issue-output/IssueOutputSection";import { EnvironmentVariablesEditor } from "@/components/environment-variables-editor";+import { IssueThreadInteractionCard } from "@/components/IssueThreadInteractionCard";+import {+ connectedConnectionIntentInteraction,+ issueThreadInteractionFixtureMeta,+ pendingConnectionIntentInteraction,+ retryConnectionIntentInteraction,+} from "@/fixtures/issueThreadInteractionFixtures";import type { CompanySecret, EnvBinding } from "@paperclipai/shared";import {EnvInputsList,@@ -1346,6 +1354,21 @@ export function DesignGuide() {</SubSection></Section>+ <Section title="App logos">+ <SubSection title="Official marks and runtime fallback">+ <div className="flex items-center gap-3">+ <AppLogo+ name="Notion"+ logoUrl="/brands/apps/notion.svg"+ darkLogoUrl="/brands/apps/notion-dark.svg"+ size={36}+ />+ <AppLogo name="Jira" logoUrl="/brands/apps/jira.svg" darkLogoUrl="/brands/apps/jira-dark.svg" size={44} />+ <AppLogo name="Fallback" logoUrl="/brands/apps/does-not-exist.svg" size={36} />+ </div>+ </SubSection>+ </Section>+{/* ============================================================ */}{/* IDENTITY */}{/* ============================================================ */}@@ -2056,6 +2079,28 @@ export function DesignGuide() {<EnvironmentVariablesEditorShowcase /></Section>+ <Section title="Connection Intent">+ <p className="text-sm text-muted-foreground">+ The task card is the dialog host for the shared connection setup flow. Provider forms,+ validation, OAuth, access selection, and completion come from the same feature module as+ the full-page Apps setup; this card owns only audience, dialog, and task refresh behavior.+ </p>+ <div className="grid gap-4 xl:grid-cols-3">+ <IssueThreadInteractionCard+ interaction={pendingConnectionIntentInteraction}+ currentUserId={issueThreadInteractionFixtureMeta.currentUserId}+ />+ <IssueThreadInteractionCard+ interaction={retryConnectionIntentInteraction}+ currentUserId={issueThreadInteractionFixtureMeta.currentUserId}+ />+ <IssueThreadInteractionCard+ interaction={connectedConnectionIntentInteraction}+ currentUserId={issueThreadInteractionFixtureMeta.currentUserId}+ />+ </div>+ </Section>+<Section title="Resizable Panels"><p className="text-sm text-muted-foreground">Design-system wrapper over <span className="font-mono">react-resizable-panels</span>{" "}diff --git a/ui/src/pages/apps/AppDetail.test.tsx b/ui/src/pages/apps/AppDetail.test.tsxindex b02d113bbe..89d8fc0c61 100644--- a/ui/src/pages/apps/AppDetail.test.tsx+++ b/ui/src/pages/apps/AppDetail.test.tsx@@ -20,6 +20,7 @@ const listConnectionActivityMock = vi.hoisted(() => vi.fn());const listActionRequestsMock = vi.hoisted(() => vi.fn());const updateConnectionMock = vi.hoisted(() => vi.fn());const finishAppMock = vi.hoisted(() => vi.fn());+const finalizeOAuthAccessMock = vi.hoisted(() => vi.fn());const putConnectionInstallsMock = vi.hoisted(() => vi.fn());const refreshCatalogMock = vi.hoisted(() => vi.fn());const startOAuthMock = vi.hoisted(() => vi.fn());@@ -55,11 +56,15 @@ vi.mock("@/api/tools", () => ({updateConnectionMock(connectionId, input),finishApp: (companyId: string, connectionId: string, input: unknown) =>finishAppMock(companyId, connectionId, input),+ finalizeOAuthAccess: (companyId: string, connectionId: string, input: unknown) =>+ finalizeOAuthAccessMock(companyId, connectionId, input),putConnectionInstalls: (connectionId: string, installs: unknown) =>putConnectionInstallsMock(connectionId, installs),archiveConnection: vi.fn(),refreshCatalog: (connectionId: string) => refreshCatalogMock(connectionId),- startOAuth: (connectionId: string) => startOAuthMock(connectionId),+ startOAuth: (connectionId: string, input?: unknown) => input === undefined+ ? startOAuthMock(connectionId)+ : startOAuthMock(connectionId, input),listConnectionGrants: (connectionId: string) => listConnectionGrantsMock(connectionId),revokeConnectionGrant: (connectionId: string, grantId: string) =>revokeConnectionGrantMock(connectionId, grantId),@@ -365,6 +370,7 @@ describe("AppDetail", () => {listActionRequestsMock.mockResolvedValue({ actionRequests: [] });updateConnectionMock.mockResolvedValue(connection({ enabled: false }));finishAppMock.mockResolvedValue({});+ finalizeOAuthAccessMock.mockResolvedValue({});putConnectionInstallsMock.mockResolvedValue({ connectionId: "conn-1", installs: [] });refreshCatalogMock.mockResolvedValue({ discoveredCount: 0, quarantinedCount: 0, catalog: [] });startOAuthMock.mockResolvedValue({@@ -412,8 +418,8 @@ describe("AppDetail", () => {// Services (PAP-17865) sits below Test rather than above it, so the// Setup→Test adjacency this test exists to protect still holds."services",- "review","permissions",+ "review","activity",]);});@@ -421,10 +427,19 @@ describe("AppDetail", () => {it("pauses the app by flipping the connection enabled flag", async () => {await renderAppDetail();+ const dangerZone = Array.from(container.querySelectorAll("button"))+ .find((button) => button.textContent?.includes("Danger zone"));+ expect(dangerZone).toBeTruthy();+ await act(async () => {+ dangerZone!.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushReact();+const toggle = container.querySelector<HTMLButtonElement>(- 'button[role="switch"][aria-label="Pause this app"]',+ 'button[role="switch"][aria-label="Pause connection"]',);expect(toggle).toBeTruthy();+ expect(toggle?.getAttribute("aria-checked")).toBe("false");await act(async () => {toggle!.dispatchEvent(new MouseEvent("click", { bubbles: true }));@@ -486,9 +501,9 @@ describe("AppDetail", () => {});it.each([- ["setup", "Agents can use this app", false],+ ["setup", "Danger zone", false],["review", "Review 1 new action", true],- ["permissions", "Action permissions", true],+ ["permissions", "Agent access", true],["activity", "No activity yet.", false],])("renders the %s tab panel", async (tab, expectedText, showsActionCount) => {mockParams.tab = tab;@@ -512,14 +527,31 @@ describe("AppDetail", () => {});});- it("renders setup without waiting for tool discovery", async () => {+ it("renders setup while its permission summary loads", async () => {listCatalogMock.mockImplementation(() => new Promise(() => undefined));await renderAppDetail();- expect(container.textContent).toContain("Agents can use this app");+ expect(container.textContent).toContain("Danger zone");+ expect(container.textContent).toContain("Loading permissions…");expect(container.textContent).not.toContain("Loading tools");- expect(listCatalogMock).not.toHaveBeenCalled();+ expect(listCatalogMock).toHaveBeenCalledWith("conn-1");+ });++ it("shows permission totals on Setup and opens Permissions", async () => {+ await renderAppDetail();++ const summary = "Allowed for 1 action · Ask first for 1 action · Off for 0";+ expect(container.textContent).toContain(summary);++ const summaryButton = Array.from(container.querySelectorAll("button"))+ .find((button) => button.textContent?.includes(summary));+ expect(summaryButton).toBeTruthy();+ await act(async () => {+ summaryButton!.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });++ expect(mockNavigate).toHaveBeenCalledWith("/apps/conn-1/permissions");});it("shows an explicit lazy-loading state while a tool tab discovers actions", async () => {@@ -557,6 +589,24 @@ describe("AppDetail", () => {expect(mockNavigate).toHaveBeenCalledWith("/apps/conn-1/test", { replace: true });});+ it("normalizes the retired post-OAuth identity choice back to fixed Setup", async () => {+ mockParams.tab = "setup";+ mockSearchParams.value = new URLSearchParams("oauth=choose-access");+ getConnectionMock.mockResolvedValue(connection({+ name: "Notion",+ authKind: "oauth",+ credentialPolicy: "per_user",+ config: { sourceTemplateKey: "notion" },+ }));++ await renderAppDetail();++ expect(container.textContent).toContain("Only you can use this connection");+ expect(container.textContent).not.toContain("Who can use this connection?");+ expect(mockNavigate).toHaveBeenCalledWith("/apps/conn-1/setup", { replace: true });+ expect(finalizeOAuthAccessMock).not.toHaveBeenCalled();+ });+it("hides secret URL parameters in setup technical details", async () => {mockParams.tab = "setup";getConnectionMock.mockResolvedValue(@@ -568,6 +618,12 @@ describe("AppDetail", () => {);await renderAppDetail();+ await act(async () => {+ Array.from(container.querySelectorAll("button"))+ .find((button) => button.textContent?.includes("Connection details"))+ ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushReact();expect(container.textContent).toContain("https://mcp.zapier.com/api/v1/connect?token=REDACTED®ion=us",@@ -643,15 +699,38 @@ describe("AppDetail", () => {expect(finishInput.enabledCatalogEntryIds).not.toContain("catalog-quarantined-block");});- it("keeps setup focused while including technical details and the danger zone", async () => {+ it("keeps setup focused with secondary details folded away", async () => {mockParams.tab = "setup";await renderAppDetail();- expect(container.textContent).toContain("Give agents a governed way to inspect repositories and pull requests.");- expect(container.textContent).toContain("Agents can use this app");- expect(container.textContent).toContain("Technical details");+ expect(container.textContent).not.toContain("Give agents a governed way to inspect repositories and pull requests.");+ expect(container.textContent).toContain("Connection details");expect(container.textContent).toContain("Danger zone");+ expect(container.textContent).not.toContain("This connection always acts as the identity chosen during setup.");+ expect(container.textContent).not.toContain("Remote HTTP");+ expect(container.textContent).not.toContain("Pause connection");+ expect(container.textContent).not.toContain("Stored securely.");++ await act(async () => {+ Array.from(container.querySelectorAll("button"))+ .find((button) => button.textContent?.includes("Connection details"))+ ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushReact();++ expect(container.textContent).toContain("Remote HTTP");++ await act(async () => {+ Array.from(container.querySelectorAll("button"))+ .find((button) => button.textContent?.includes("Danger zone"))+ ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushReact();++ expect(container.textContent).toContain("Pause connection");+ expect(container.textContent).toContain("Reconnect");+ expect(container.textContent).toContain("Replace the stored credential.");expect(container.textContent).not.toContain("Read repo");expect(container.textContent).not.toContain("Action permissions");expect(container.querySelector("section.bg-card")).toBeNull();@@ -672,10 +751,10 @@ describe("AppDetail", () => {await renderAppDetail();- // The old generic "Connect with <provider>" block is gone: identity is now- // expressed per-identity, and a connection with no organization grant offers- // an explicit connect action instead of a single ambiguous button.- expect(container.textContent).toContain("Identities");+ // The old generic "Connect with <provider>" block is gone: the connection's+ // fixed identity type is explicit even before that identity is connected.+ expect(container.textContent).toContain("Account");+ expect(container.textContent).toContain("Anyone in your company can use this connection");expect(container.textContent).toContain("Organization identity");expect(container.textContent).toContain("Not connected");expect(@@ -734,15 +813,16 @@ describe("AppDetail", () => {await renderAppDetail();expect(container.textContent).toContain("Dotta’s Notion");- expect(container.textContent).toContain("Connected by");- expect(container.querySelector('[title="Dotta"] [data-slot="avatar"]')).toBeTruthy();- // Identity is legible per identity, and the shared one names its audience.- // "workspace authorization" is deliberately gone: it could only ever- // describe one shared identity (PAP-17835).- expect(container.textContent).toContain("Organization identity");- expect(container.textContent).toContain("Notion workspace");- expect(container.textContent).toContain("All organization members");+ expect(container.textContent).not.toContain("Connected by");+ expect(container.textContent).toContain("Anyone in your company can use this connection");expect(container.textContent).not.toContain("workspace authorization");+ expect(findButton("Reconnect")).toBeUndefined();++ await act(async () => {+ findButton("Danger zone")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushReact();+expect(Array.from(container.querySelectorAll("button")).some((button) => button.textContent?.trim() === "Reconnect",@@ -812,8 +892,8 @@ describe("AppDetail", () => {await renderAppDetail();- expect(container.textContent).toContain("Read only");- expect(container.textContent).toContain("Can make changes");+ expect(container.textContent).toContain("Read (1)");+ expect(container.textContent).toContain("Write (1)");expect(container.textContent).toContain("Read repo");expect(container.textContent).toContain("Write issue");expect(container.textContent).toContain("Review 1 new action");@@ -869,7 +949,7 @@ describe("AppDetail", () => {await renderAppDetail();- expect(container.textContent).toContain("Available to agents");+ expect(container.textContent).toContain("Agent access");await act(async () => {Array.from(container.querySelectorAll("button")).find((button) => button.textContent?.includes("Choose agents"))@@ -889,13 +969,7 @@ describe("AppDetail", () => {]);});- /**- * PAP-17859: agent availability is stated once. The tab used to stack a- * legacy "Who can use it" editor — its own Change button, per-agent remove- * buttons and Save — on top of "Available to agents", so the same fact had- * two visible editors and the reader had to guess which one won.- */- it("shows one agent-availability model on Permissions, not the legacy access editor", async () => {+ it("persists agent access independently from always-installed agents", async () => {mockParams.tab = "permissions";listProfilesMock.mockResolvedValue({profiles: [{@@ -910,12 +984,88 @@ describe("AppDetail", () => {await renderAppDetail();- expect(container.textContent).toContain("Available to agents");+ const accessGroup = container.querySelector('[role="radiogroup"][aria-label="Which agents can use this connection"]');+ const anyAgent = Array.from(accessGroup?.querySelectorAll('[role="radio"]') ?? [])+ .find((radio) => radio.textContent?.includes("Any agent"));+ expect(anyAgent).toBeTruthy();++ await act(async () => {+ anyAgent?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushReact();++ expect(finishAppMock).toHaveBeenCalledWith("company-1", "conn-1", {+ enabledCatalogEntryIds: ["catalog-read", "catalog-write"],+ askFirstCatalogEntryIds: ["catalog-write"],+ access: "all_agents",+ });+ expect(putConnectionInstallsMock).not.toHaveBeenCalled();+ });++ it("keeps always-installed agents in the access allowlist", async () => {+ mockParams.tab = "permissions";+ getConnectionInstallsMock.mockResolvedValue({+ connectionId: "conn-1",+ installs: [{+ id: "install-agent-1",+ companyId: "company-1",+ connectionId: "conn-1",+ targetType: "agent",+ targetId: "agent-1",+ createdByAgentId: null,+ createdByUserId: "user-1",+ createdAt: new Date(),+ }],+ });++ await renderAppDetail();++ const accessGroup = container.querySelector('[role="radiogroup"][aria-label="Which agents can use this connection"]');+ const pickedAgents = Array.from(accessGroup?.querySelectorAll('[role="radio"]') ?? [])+ .find((radio) => radio.textContent?.includes("Agents I pick"));+ await act(async () => {+ pickedAgents?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushReact();++ expect(finishAppMock).toHaveBeenCalledWith("company-1", "conn-1", {+ enabledCatalogEntryIds: ["catalog-read", "catalog-write"],+ askFirstCatalogEntryIds: ["catalog-write"],+ access: { agentIds: ["agent-1"] },+ });+ });++ it("separates agent access from agents that always install the app", async () => {+ mockParams.tab = "permissions";+ listProfilesMock.mockResolvedValue({+ profiles: [{+ profileKey: "app:conn-1",+ entries: [+ { effect: "include", catalogEntryId: "catalog-read" },+ { effect: "include", catalogEntryId: "catalog-write" },+ ],+ bindings: [{ targetType: "agent", targetId: "agent-1" }],+ }],+ });++ await renderAppDetail();++ expect(container.textContent).toContain("Agent access");+ expect(container.textContent).toContain("Always installed");+ expect(container.textContent).toContain("Agent access only makes it available when needed.");+ const alwaysInstalledHeading = Array.from(container.querySelectorAll("h2"))+ .find((heading) => heading.textContent === "Always installed");+ const agentAccessHeading = Array.from(container.querySelectorAll("h2"))+ .find((heading) => heading.textContent === "Agent access");+ expect(alwaysInstalledHeading).toBeTruthy();+ expect(agentAccessHeading).toBeTruthy();+ expect(+ alwaysInstalledHeading!.compareDocumentPosition(agentAccessHeading!)+ & Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();expect(container.textContent).not.toContain("Who can use it");- expect(container.textContent).not.toContain("Only specific agents");expect(container.querySelector('button[aria-label="Remove Coder access"]')).toBeNull();- // Exactly one radiogroup on the tab: the install model.- expect(container.querySelectorAll('[role="radiogroup"]').length).toBe(1);+ expect(container.querySelectorAll('[role="radiogroup"]').length).toBe(2);expect(Array.from(container.querySelectorAll("button")).filter((button) => button.textContent?.trim() === "Change",@@ -947,8 +1097,8 @@ describe("AppDetail", () => {await renderAppDetail();// State is still legible.- expect(container.textContent).toContain("Available to agents");- expect(container.textContent).toContain("Action permissions");+ expect(container.textContent).toContain("Agent access");+ expect(container.textContent).toContain("Actions");expect(container.textContent).toContain("Read repo");// Nothing to mutate: no radios, no permission selects, no refresh, no save.@@ -1130,7 +1280,7 @@ describe("AppDetail", () => {expect(container.textContent).toContain("Needs attention");expect(container.textContent).toContain("This app needs reconnecting");expect(container.textContent).toContain("Token expired.");- expect(container.textContent).toContain("Available to agents");+ expect(container.textContent).toContain("Agent access");});it("shows terminal OAuth failures as reconnect-required sign-in", async () => {@@ -1158,6 +1308,83 @@ describe("AppDetail", () => {expect(navigateTopLevelMock).toHaveBeenCalledWith("https://example.test/oauth");});+ it("reconnects an OAuth warning through the connection's existing personal identity", async () => {+ mockParams.tab = "permissions";+ getConnectionMock.mockResolvedValue(connection({+ authKind: "oauth",+ credentialPolicy: "per_user",+ createdByUserId: "user-1",+ healthStatus: "failed",+ healthMessage: "Authorization expired (invalid_grant).",+ }));++ await renderAppDetail();+ await act(async () => {+ Array.from(container.querySelectorAll("button"))+ .find((button) => button.textContent?.trim() === "Reconnect")+ ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushReact();++ expect(startOAuthMock).toHaveBeenCalledWith("conn-1", { asCurrentUser: true });+ expect(navigateTopLevelMock).toHaveBeenCalledWith("https://example.test/oauth");+ });++ it("does not offer a personal reconnect to someone other than its fixed owner", async () => {+ mockParams.tab = "permissions";+ getConnectionMock.mockResolvedValue(connection({+ authKind: "oauth",+ credentialPolicy: "per_user",+ createdByUserId: "user-2",+ healthStatus: "failed",+ healthMessage: "Authorization expired (invalid_grant).",+ }));+ listConnectionGrantsMock.mockResolvedValue({+ connection: { id: "conn-1", uid: "conn-1" },+ grants: [personalGrant({ id: "grant-other", subjectUserId: "user-2" })],+ capabilities: fullCapabilities({ canViewOtherPersonalIdentities: true }),+ currentUserId: "user-1",+ members: [{ userId: "user-2", name: "Carol", email: "[email protected]" }],+ });++ await renderAppDetail();++ expect(container.textContent).toContain("Reconnect required");+ expect(container.textContent).toContain("The person this connection belongs to must reconnect it.");+ expect(findButton("Reconnect")).toBeUndefined();+ expect(startOAuthMock).not.toHaveBeenCalled();+ });++ it("does not offer personal key replacement to someone other than its fixed owner", async () => {+ mockParams.tab = "setup";+ getConnectionMock.mockResolvedValue(connection({+ authKind: "api_key",+ credentialPolicy: "per_user",+ createdByUserId: "user-2",+ healthStatus: "failed",+ healthMessage: "The key was rejected.",+ }));+ listConnectionGrantsMock.mockResolvedValue({+ connection: { id: "conn-1", uid: "conn-1" },+ grants: [personalGrant({ id: "grant-other", subjectUserId: "user-2" })],+ capabilities: fullCapabilities({ canViewOtherPersonalIdentities: true }),+ currentUserId: "user-1",+ members: [{ userId: "user-2", name: "Carol", email: "[email protected]" }],+ });++ await renderAppDetail();+ await act(async () => {+ findButton("Danger zone")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushReact();++ expect(container.textContent).toContain("Reconnect");+ expect(container.textContent).toContain("The person this connection belongs to must reconnect it.");+ expect(Array.from(container.querySelectorAll("button")).filter(+ (button) => button.textContent?.trim() === "Reconnect",+ )).toHaveLength(0);+ });+/*** PAP-17099 — the server refuses to hand out an unsafe authorization endpoint,* but this is the boundary where one would actually execute, so the board must@@ -1214,14 +1441,15 @@ describe("AppDetail", () => {.find((button) => button.textContent?.trim() === label);}- it("answers 'who does this act as' in the header on every tab", async () => {+ it("keeps the app header concise on every tab", async () => {mockParams.tab = "permissions";getConnectionMock.mockResolvedValue(perUserConnection());await renderAppDetail();- expect(container.textContent).toContain("Acts as each person");- expect(container.textContent).toContain("Each person connects their own account.");+ expect(container.textContent).toContain("Connected");+ expect(container.textContent).not.toContain("This connection is for one person.");+ expect(container.textContent).not.toContain("Connected by");});it("lets a regular member connect their own identity and never someone else's", async () => {@@ -1232,8 +1460,12 @@ describe("AppDetail", () => {await renderAppDetail();// Missing personal identity is explicit, never a silent fallback.- expect(container.textContent).toContain("Your identity");- expect(container.textContent).toContain("You have not connected your account.");+ expect(container.textContent).toContain("Account");+ expect(container.textContent).toContain("Only you can use this connection");+ expect(container.textContent).toContain("Personal account");+ expect(container.textContent).toContain("Not connected");+ expect(container.textContent).not.toContain("Organization identity");+ expect(findButton("Connect organization identity")).toBeUndefined();await act(async () => {findButton("Connect as me")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));@@ -1249,12 +1481,12 @@ describe("AppDetail", () => {expect(navigateTopLevelMock).toHaveBeenCalledWith("https://accounts.example.test/authorize");});- it("lets the personal identity owner grant a named agent autonomous access", async () => {+ it("opens Permissions from app access instead of personal identity delegations", async () => {mockParams.tab = "setup";getConnectionMock.mockResolvedValue(perUserConnection());listConnectionGrantsMock.mockResolvedValue({connection: { id: "conn-1", uid: "conn-1" },- grants: [personalGrant({ delegations: [] })],+ grants: [personalGrant({ delegations: [{ id: "delegation-1", agentId: "agent-1" }] })],capabilities: fullCapabilities(),currentUserId: "user-1",members: [{ userId: "user-1", name: "Dotta", email: "[email protected]" }],@@ -1262,34 +1494,18 @@ describe("AppDetail", () => {await renderAppDetail();- expect(findButton("Allow autonomous access")).toBeTruthy();+ expect(findButton("Every agent")).toBeTruthy();+ expect(findButton("No agents")).toBeUndefined();await act(async () => {- findButton("Allow autonomous access")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ findButton("Every agent")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));});- await flushReact();- const agentCheckbox = document.querySelector<HTMLInputElement>('button[role="checkbox"][aria-label="Allow Coder"]');- expect(agentCheckbox).toBeTruthy();- await act(async () => {- agentCheckbox?.dispatchEvent(new MouseEvent("click", { bubbles: true }));- });- await act(async () => {- Array.from(document.querySelectorAll("button"))- .find((button) => button.textContent?.trim() === "Save")- ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));- });- await flushReact();-- expect(createConnectionGrantDelegationMock).toHaveBeenCalledWith(- "conn-1",- "grant-user",- "agent-1",- );+ expect(mockNavigate).toHaveBeenCalledWith("/apps/conn-1/permissions");});it("keeps a viewer read-only across identities and installs", async () => {mockParams.tab = "setup";- getConnectionMock.mockResolvedValue(perUserConnection());+ getConnectionMock.mockResolvedValue(connection({ credentialPolicy: "shared" }));listConnectionGrantsMock.mockResolvedValue({connection: { id: "conn-1", uid: "conn-1" },grants: [organizationGrant({ capabilities: { canRevoke: false, canEditAudience: false } })],@@ -1308,20 +1524,21 @@ describe("AppDetail", () => {await renderAppDetail();+ expect(container.textContent).toContain("Anyone in your company can use this connection");+// State stays legible...- expect(container.textContent).toContain("Organization identity");- expect(container.textContent).toContain("Connected");- expect(container.textContent).toContain("All organization members");+ expect(container.textContent).toContain("Anyone in your company can use this connection");+ expect(container.textContent).not.toContain("Personal account");// ...and every mutation control is absent rather than disabled.expect(findButton("Connect as me")).toBeUndefined();- expect(findButton("Manage audience")).toBeUndefined();+ expect(findButton("Manage access")).toBeUndefined();expect(findButton("Revoke")).toBeUndefined();expect(findButton("Connect organization identity")).toBeUndefined();});- it("gives a manager oversight of other people's identities", async () => {+ it("shows one fixed personal identity without an organization switch", async () => {mockParams.tab = "setup";- getConnectionMock.mockResolvedValue(perUserConnection());+ getConnectionMock.mockResolvedValue(perUserConnection({ createdByUserId: "user-2" }));revokeConnectionGrantMock.mockResolvedValue({ id: "grant-other", kind: "user" });listConnectionGrantsMock.mockResolvedValue({connection: { id: "conn-1", uid: "conn-1" },@@ -1339,28 +1556,22 @@ describe("AppDetail", () => {await renderAppDetail();- expect(container.textContent).toContain("Other personal identities · 1");+ expect(container.textContent).toContain("Only you can use this connection");+ expect(container.textContent).toContain("Carol");+ expect(container.textContent).not.toContain("Organization identity");+ expect(container.textContent).not.toContain("Other personal identities");+ expect(findButton("Connect organization identity")).toBeUndefined();+ expect(findButton("Agents")).toBeUndefined();+ // A manager can still revoke the displayed identity from the folded danger+ // zone, but cannot reconnect as Carol or switch the identity type.await act(async () => {- Array.from(container.querySelectorAll("button"))- .find((button) => button.textContent?.includes("Other personal identities"))- ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ findButton("Danger zone")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));});await flushReact();- expect(container.textContent).toContain("Carol");-- // Scope to Carol's own row: the organization identity also offers Revoke,- // and picking the first match would silently test the wrong grant.- const carolRow = Array.from(container.querySelectorAll("div"))- .filter((row) => row.textContent?.includes("Carol")- && Array.from(row.querySelectorAll("button")).some((b) => b.textContent?.trim() === "Revoke"))- .at(-1);- expect(carolRow).toBeTruthy();await act(async () => {- Array.from(carolRow!.querySelectorAll("button"))- .find((button) => button.textContent?.trim() === "Revoke")- ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ findButton("Revoke")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));});await flushReact();@@ -1399,10 +1610,10 @@ describe("AppDetail", () => {await renderAppDetail();- expect(container.textContent).toContain("1 selected member");+ expect(container.textContent).toContain("Anyone in your company can use this connection");await act(async () => {- findButton("Manage audience")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ findButton("Manage access")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));});await flushReact();@@ -1444,7 +1655,7 @@ describe("AppDetail", () => {await renderAppDetail();await act(async () => {- findButton("Manage audience")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ findButton("Manage access")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));});await flushReact();diff --git a/ui/src/pages/apps/AppDetail.tsx b/ui/src/pages/apps/AppDetail.tsxindex ab5c7b25d1..8b2480b30a 100644--- a/ui/src/pages/apps/AppDetail.tsx+++ b/ui/src/pages/apps/AppDetail.tsx@@ -34,19 +34,23 @@ import { UnverifiedServerBadge } from "./UnverifiedServerBadge";import {appApplicationSourceSlug,appConnectionSourceSlug,+ appDefinitionDarkLogoUrl,appDefinitionLogoUrl,appDefinitionName,appDefinitionSlug,type AppGalleryDisplayEntry,} from "./app-definition-display";import { appTabHref, appTabLabel, isAppTabKey, type AppTabKey } from "./app-tabs";-import { SetupPanel, connectionProviderName } from "./app-detail/SetupPanel";+import { SetupPanel } from "./app-detail/SetupPanel";import { ServicesPanel } from "./app-detail/ServicesPanel";-import { ComposioProvenanceChip } from "./ComposioProvenanceChip";+import { ConnectionProvenanceChip } from "./ComposioProvenanceChip";import { IdentitiesSection } from "./app-detail/IdentitiesSection";-import { actsAsSummary } from "./connection-identity";import { PermissionsPanel } from "./app-detail/PermissionsPanel";import { TestPanel } from "./app-detail/TestPanel";+import {+ formatActionPermissionSummary,+ summarizeActionPermissions,+} from "./app-detail/action-permission-summary";import { ReviewPanel } from "./app-detail/ReviewPanel";import { ActivityPanel } from "./app-detail/ActivityPanel";import {@@ -58,10 +62,8 @@ import {} from "./app-detail/AdvancedPanel";import type { AccessDraft } from "./app-detail/types";import {- ConnectionOwnerIdentity,connectionDisplayNameForOwner,connectionOwnerProfile,- type ConnectionOwnerProfile,} from "./connection-owner";export { DangerZone, connectionAddress, connectionTransportLabel };@@ -76,7 +78,7 @@ export function AppDetail() {const { setBreadcrumbs } = useBreadcrumbs();const activeTab: AppTabKey | null = isAppTabKey(tab) ? tab : null;- const needsCatalog = activeTab === "review" || activeTab === "permissions" || activeTab === "test";+ const needsCatalog = activeTab === "setup" || activeTab === "review" || activeTab === "permissions" || activeTab === "test";const connectionQuery = useQuery({queryKey: queryKeys.tools.connection(connectionId),@@ -111,12 +113,16 @@ export function AppDetail() {const profilesQuery = useQuery({queryKey: queryKeys.tools.profiles(selectedCompanyId ?? "__none__"),queryFn: () => toolsApi.listProfiles(selectedCompanyId!),- enabled: !!selectedCompanyId && (activeTab === "review" || activeTab === "permissions"),+ enabled: !!selectedCompanyId && (+ activeTab === "setup" || activeTab === "review" || activeTab === "permissions"+ ),});const policiesQuery = useQuery({queryKey: queryKeys.tools.policies(selectedCompanyId ?? "__none__"),queryFn: () => toolsApi.listPolicies(selectedCompanyId!),- enabled: !!selectedCompanyId && (activeTab === "review" || activeTab === "permissions"),+ enabled: !!selectedCompanyId && (+ activeTab === "setup" || activeTab === "review" || activeTab === "permissions"+ ),});const agentsQuery = useQuery({queryKey: queryKeys.agents.list(selectedCompanyId ?? "__none__"),@@ -141,19 +147,57 @@ export function AppDetail() {queryFn: () => authApi.getSession(),enabled: activeTab === "activity",});- // Identity grants drive the Setup tab's Identities section and the header's- // "acts as" sentence, and Permissions reads `capabilities` from the same- // response so install controls follow one server verdict (PAP-17835).+ // Identity grants drive reconnect authorization on every tab as well as the+ // Setup identities and Permissions controls. A personal reconnect belongs to+ // one fixed user, so the banner must not offer that action to anyone else.const grantsQuery = useQuery({queryKey: queryKeys.tools.connectionGrants(connectionId),queryFn: () => toolsApi.listConnectionGrants(connectionId),- enabled: !!connectionId && (activeTab === "setup" || activeTab === "permissions"),+ enabled: !!connectionId && !!activeTab,});const connection = connectionQuery.data;const application = connection? (applicationsQuery.data?.applications ?? []).find((candidate) => candidate.id === connection.applicationId): undefined;+ const grantRows = grantsQuery.data?.grants ?? [];+ const retainedPersonalGrant = connection?.credentialPolicy === "per_user"+ ? grantRows.find((grant) => (+ grant.kind === "user" && grant.subjectUserId === connection.createdByUserId+ ))+ ?? grantRows.find((grant) => grant.kind === "user" && grant.status === "active")+ ?? grantRows.find((grant) => grant.kind === "user")+ ?? null+ : null;+ const currentUserPersonalGrant = grantRows.find((grant) => (+ grant.kind === "user" && grant.subjectUserId === grantsQuery.data?.currentUserId+ )) ?? null;+ const retainedOrganizationGrant = grantRows.find((grant) => (+ grant.kind === "organization" && grant.isDefault+ )) ?? grantRows.find((grant) => grant.kind === "organization") ?? null;+ const managedIdentityGrant = connection?.credentialPolicy === "per_user"+ ? retainedPersonalGrant+ : connection?.credentialPolicy === "per_user_with_fallback"+ ? currentUserPersonalGrant ?? retainedOrganizationGrant+ : retainedOrganizationGrant;+ const managedPersonalUserId = managedIdentityGrant?.kind === "user"+ ? managedIdentityGrant.subjectUserId ?? connection?.createdByUserId ?? null+ : null;+ const canReconnect = managedIdentityGrant?.kind === "user"+ ? Boolean(+ managedPersonalUserId+ && managedPersonalUserId === grantsQuery.data?.currentUserId+ && grantsQuery.data?.capabilities.canConnectAsCurrentUser,+ )+ : grantsQuery.data?.capabilities.canConfigure === true;+ const reconnectUnavailableMessage = grantsQuery.isLoading+ ? "Checking who can reconnect this identity…"+ : grantsQuery.isError+ ? "We couldn't verify who can reconnect this identity. Reload the page to try again."+ : managedIdentityGrant?.kind === "user"+ && managedPersonalUserId !== grantsQuery.data?.currentUserId+ ? "The person this connection belongs to must reconnect it."+ : "You don't have permission to reconnect this identity.";const composioChildConnectionCount = (connectionsQuery.data?.connections ?? []).filter((candidate) => candidate.status !== "archived"&& candidate.config?.provider === "composio"@@ -179,6 +223,14 @@ export function AppDetail() {: "App";const successNoticeShownFor = useRef<string | null>(null);+ useEffect(() => {+ if (activeTab !== "setup" || searchParams.get("oauth") !== "choose-access") return;+ // Older OAuth states may still return to the retired post-authorization+ // identity screen. Identity is now selected before consent, so normalize+ // the stale URL without asking a contradictory second question.+ navigate(appTabHref(connectionId, "setup"), { replace: true });+ }, [activeTab, connectionId, navigate, searchParams]);+useEffect(() => {if (activeTab !== "test"@@ -392,49 +444,6 @@ export function AppDetail() {}),});- const replaceDelegations = useMutation({- mutationFn: async ({- grantId,- currentDelegations,- agentIds,- }: {- grantId: string;- currentDelegations: Array<{ id: string; agentId: string }>;- agentIds: string[];- }) => {- const desired = new Set(agentIds);- const existing = new Map(currentDelegations.map((delegation) => [delegation.agentId, delegation]));- await Promise.all([- ...currentDelegations- .filter((delegation) => !desired.has(delegation.agentId))- .map((delegation) => toolsApi.revokeConnectionGrantDelegation(- connectionId,- grantId,- delegation.id,- )),- ...agentIds- .filter((agentId) => !existing.has(agentId))- .map((agentId) => toolsApi.createConnectionGrantDelegation(connectionId, grantId, agentId)),- ]);- },- onSuccess: () => {- invalidateGrants();- pushToast({- title: "Autonomous access saved",- body: "Only the agents you selected can use your identity in autonomous runs.",- tone: "success",- });- },- onError: (error) => {- invalidateGrants();- pushToast({- title: "Couldn't save autonomous access",- body: error instanceof Error ? error.message : "Please try again.",- tone: "error",- });- },- });-// A denied or conflicting audience save keeps the dialog open with the// selection intact, so the error is surfaced inline rather than as a toast.const [audienceError, setAudienceError] = useState<string | null>(null);@@ -575,20 +584,32 @@ export function AppDetail() {}const status = statusFor(connection);- const providerName = connectionProviderName(logoEntry, baseAppName);const needsReconnect = status.tone === "attention" && connection.healthStatus !== "unknown";const quarantined = catalog.filter((e) => e.status === "quarantined");const active = catalog.filter((e) => e.status !== "quarantined" && e.status !== "removed");const readOnly = active.filter((e) => e.isReadOnly);const canChange = active.filter((e) => !e.isReadOnly);const actionCount = catalogQuery.data ? active.length : null;+ const setupPermissionsLoading = catalogQuery.isLoading || profilesQuery.isLoading || policiesQuery.isLoading;+ const setupPermissionsSummary = setupPermissionsLoading || catalogQuery.isError+ || profilesQuery.isError || policiesQuery.isError+ ? null+ : formatActionPermissionSummary(summarizeActionPermissions(active, enabledIds, askFirstIds));+ // Setup summarizes app access, not personal-identity delegations. Identity+ // delegation answers who an agent may act as; the profile binding below is+ // the source of truth for which agents may use the connection at all.+ const setupAgentsSummary = access.mode === "all"+ ? "Every agent"+ : access.agentIds.size === 0+ ? "No agents"+ : `${access.agentIds.size} ${access.agentIds.size === 1 ? "agent" : "agents"}`;const reviewLoading = catalogQuery.isLoading || profilesQuery.isLoading || policiesQuery.isLoading;const permissionsLoading = reviewLoading || installsQuery.isLoading || agentsQuery.isLoading;const reviewFailed = catalogQuery.isError || profilesQuery.isError || policiesQuery.isError;const permissionsFailed = reviewFailed || installsQuery.isError || agentsQuery.isError;return (- <div className="max-w-3xl space-y-6 pb-12">+ <div className="max-w-4xl space-y-10 pb-12"><AppDetailHeaderappName={appName}connection={connection}@@ -596,8 +617,7 @@ export function AppDetail() {brandKey={brandKey}allowRemoteLogo={!applicationsQuery.isPending}status={status}- actionCount={actionCount}- owner={owner}+ actionCount={activeTab === "setup" ? null : actionCount}renaming={renaming}nameDraft={nameDraft}renamePending={rename.isPending}@@ -617,6 +637,8 @@ export function AppDetail() {<ReconnectCardconnection={connection}galleryEntry={logoEntry}+ canReconnect={canReconnect}+ reconnectUnavailableMessage={reconnectUnavailableMessage}onReconnected={() => {queryClient.invalidateQueries({ queryKey: queryKeys.tools.connection(connectionId) });queryClient.invalidateQueries({ queryKey: queryKeys.tools.connections(selectedCompanyId) });@@ -626,69 +648,76 @@ export function AppDetail() {)}{activeTab === "setup" && (- <div className="space-y-8">- <SetupPanel- connection={connection}- galleryEntry={logoEntry}- appToggleDisabled={toggleEnabled.isPending || removeApp.isPending}- onToggleApp={() => toggleEnabled.mutate()}- configUpdateDisabled={updateConfig.isPending}- onUpdateConfig={(config) => updateConfig.mutate(config)}- identities={- <IdentitiesSection- appName={appName}- providerName={providerName}- credentialPolicy={connection.credentialPolicy}- grantsQuery={grantsQuery.data}- agents={agents}- agentsLoading={agentsQuery.isLoading}- agentsError={agentsQuery.isError}- loading={grantsQuery.isLoading}- error={grantsQuery.isError}- connectPending={startPersonalAuth.isPending || startOAuth.isPending}- revokePending={revokeGrant.isPending}- delegationPending={replaceDelegations.isPending}- audiencePending={replaceAudience.isPending}- audienceError={audienceError}- audienceGrantId={audienceOpenGrantId}- onOpenAudience={(grantId) => {- setAudienceError(null);- setAudienceOpenGrantId(grantId);- }}- onCloseAudience={() => {- setAudienceOpenGrantId(null);- setAudienceError(null);- }}- onConnectAsMe={() => startPersonalAuth.mutate()}- // The organization identity is a shared credential, so it goes- // through the connection-level OAuth start, not a personal one.- onConnectOrganization={() => startOAuth.mutate()}- onReconnectOrganization={() => startOAuth.mutate()}- onRevokeGrant={(grant) => revokeGrant.mutate(grant.id)}- onReplaceDelegations={(grant, agentIds) => replaceDelegations.mutate({- grantId: grant.id,- currentDelegations: grant.delegations ?? [],- agentIds,- })}- onReplaceAudience={(grant, memberUserIds) =>- replaceAudience.mutate({ grantId: grant.id, memberUserIds })}- />- }- />- <AdvancedPanel- connection={connection}- appName={appName}- galleryEntry={logoEntry}- childConnectionCount={composioChildConnectionCount}- removing={removeApp.isPending}- onRemove={() => removeApp.mutate()}- onReplaced={() => {- queryClient.invalidateQueries({ queryKey: queryKeys.tools.connection(connectionId) });- queryClient.invalidateQueries({ queryKey: queryKeys.tools.connections(selectedCompanyId) });- queryClient.invalidateQueries({ queryKey: queryKeys.apps.attention(selectedCompanyId) });- }}- />- </div>+ <div className="space-y-12">+ <SetupPanel+ connection={connection}+ galleryEntry={logoEntry}+ configUpdateDisabled={updateConfig.isPending}+ onUpdateConfig={(config) => updateConfig.mutate(config)}+ agentsSummary={setupAgentsSummary}+ permissionsSummary={setupPermissionsSummary}+ permissionsLoading={setupPermissionsLoading}+ onOpenPermissions={() => navigate(appTabHref(connectionId, "permissions"))}+ identities={+ <IdentitiesSection+ appName={appName}+ credentialPolicy={connection.credentialPolicy}+ ownerUserId={connection.createdByUserId}+ connectedUser={owner}+ grantsQuery={grantsQuery.data}+ loading={grantsQuery.isLoading}+ error={grantsQuery.isError}+ connectPending={startPersonalAuth.isPending || startOAuth.isPending}+ audiencePending={replaceAudience.isPending}+ audienceError={audienceError}+ audienceGrantId={audienceOpenGrantId}+ onOpenAudience={(grantId) => {+ setAudienceError(null);+ setAudienceOpenGrantId(grantId);+ }}+ onCloseAudience={() => {+ setAudienceOpenGrantId(null);+ setAudienceError(null);+ }}+ onConnectAsMe={() => startPersonalAuth.mutate()}+ // The organization identity is a shared credential, so it goes+ // through the connection-level OAuth start, not a personal one.+ onConnectOrganization={() => startOAuth.mutate()}+ onReplaceAudience={(grant, memberUserIds) =>+ replaceAudience.mutate({ grantId: grant.id, memberUserIds })}+ />+ }+ />+ <AdvancedPanel+ connection={connection}+ appName={appName}+ galleryEntry={logoEntry}+ childConnectionCount={composioChildConnectionCount}+ removing={removeApp.isPending}+ onRemove={() => removeApp.mutate()}+ canReplaceCredential={canReconnect}+ credentialUnavailableMessage={reconnectUnavailableMessage}+ appToggleDisabled={toggleEnabled.isPending || removeApp.isPending}+ onToggleApp={() => toggleEnabled.mutate()}+ identityGrant={managedIdentityGrant}+ identityCurrentUserId={grantsQuery.data?.currentUserId ?? null}+ identityProviderName={baseAppName}+ credentialPolicy={connection.credentialPolicy}+ identityActionPending={+ startPersonalAuth.isPending || startOAuth.isPending || revokeGrant.isPending+ }+ onReconnectIdentity={managedIdentityGrant ? () => {+ if (managedIdentityGrant.kind === "user") startPersonalAuth.mutate();+ else startOAuth.mutate();+ } : undefined}+ onRevokeIdentity={(grant) => revokeGrant.mutate(grant.id)}+ onReplaced={() => {+ queryClient.invalidateQueries({ queryKey: queryKeys.tools.connection(connectionId) });+ queryClient.invalidateQueries({ queryKey: queryKeys.tools.connections(selectedCompanyId) });+ queryClient.invalidateQueries({ queryKey: queryKeys.apps.attention(selectedCompanyId) });+ }}+ />+ </div>)}{activeTab === "services" && (<ServicesPanel connectionId={connectionId} appName={appName} />@@ -722,7 +751,9 @@ export function AppDetail() {? <ToolsLoading />: <PermissionsPanelcapabilities={grantsQuery.data?.capabilities}+ appName={appName}agents={agents}+ access={access}install={install}readOnly={readOnly}canChange={canChange}@@ -732,6 +763,7 @@ export function AppDetail() {pending={pending}installPending={persistInstall.isPending}refreshPending={refreshTools.isPending}+ onSaveAccess={(next) => apply({ access: accessIncludingInstalls(next, install) })}onSaveInstall={(next) => persistInstall.mutate(next)}onRefreshActions={() => refreshTools.mutate()}onSetActionPermission={(id, next) => apply(actionPermissionMutation(id, next, enabledIds, askFirstIds))}@@ -770,7 +802,6 @@ function AppDetailHeader({allowRemoteLogo,status,actionCount,- owner,renaming,nameDraft,renamePending,@@ -786,7 +817,6 @@ function AppDetailHeader({allowRemoteLogo: boolean;status: StatusInfo;actionCount: number | null;- owner: ConnectionOwnerProfile | null;renaming: boolean;nameDraft: string;renamePending: boolean;@@ -796,19 +826,18 @@ function AppDetailHeader({onRenameSubmit: (value: string) => void;}) {const unverifiedHost = unverifiedRemoteHost(connection);- const actsAs = actsAsSummary(connection.credentialPolicy);-return (- <header className="flex flex-wrap items-start justify-between gap-4">+ <header><div className="flex items-center gap-3"><AppLogoname={appName}brandKey={brandKey}logoUrl={appDefinitionLogoUrl(logoEntry)}+ darkLogoUrl={appDefinitionDarkLogoUrl(logoEntry)}allowRemoteFallback={allowRemoteLogo}size={44}/>- <div>+ <div className="min-w-0">{renaming ? (<formclassName="flex items-center gap-2"@@ -833,7 +862,7 @@ function AppDetailHeader({</form>) : (<div className="flex items-center gap-1.5">- <h1 className="text-2xl font-bold tracking-tight">{appName}</h1>+ <h1 className="truncate text-xl font-bold">{appName}</h1><Buttonvariant="ghost"size="icon"@@ -845,32 +874,20 @@ function AppDetailHeader({</Button></div>)}- {connectionDisplaySecondaryHint(connection) && (- <p className="text-xs text-muted-foreground">{connectionDisplaySecondaryHint(connection)}</p>- )}- {/* One sentence, not a cluster of badges: whether an agent acts as you- or as the organization is the first thing every tab has to answer- (PAP-17835). It lives in the header so it carries across tabs. */}- <p className="mt-0.5 text-xs text-muted-foreground">- <span className="font-medium text-foreground">{actsAs.title}</span>- {" · "}- {actsAs.detail}- </p>- {owner && (- <div className="mt-1 flex items-center gap-1.5 text-xs text-muted-foreground">- <span>Connected by</span>- <ConnectionOwnerIdentity owner={owner} />- </div>- )}- {unverifiedHost ? <UnverifiedServerBadge host={unverifiedHost} className="mt-1" /> : null}- <ComposioProvenanceChip connection={connection} className="mt-1" />- <div className="mt-1 flex items-center gap-2">+ <div className="mt-2 flex flex-wrap items-center gap-2"><StatusBadge status={status} />{actionCount !== null && (<span className="text-xs text-muted-foreground">{actionCount} {actionCount === 1 ? "action" : "actions"} available</span>)}+ {connectionDisplaySecondaryHint(connection) ? (+ <span className="text-xs text-muted-foreground">+ {connectionDisplaySecondaryHint(connection)}+ </span>+ ) : null}+ {unverifiedHost ? <UnverifiedServerBadge host={unverifiedHost} /> : null}+ <ConnectionProvenanceChip connection={connection} /></div></div></div>@@ -973,11 +990,10 @@ function askFirstCatalogIds(policies: ToolPolicy[], connectionId: string): Set<s* Who may use this connection, read back from the app profile's bindings.** `finishApp` replaces a profile's whole binding set, so every save from this- * page — including an action-permission toggle — has to restate this. Since- * PAP-17859 there is no user-facing editor for it: the Permissions tab shows- * agent availability once, as installs. This function therefore only ever- * *preserves* what the server already has, and falls back to the install state- * when the profile has no bindings yet.+ * page — including an action-permission toggle — has to restate this. The+ * Permissions tab exposes the bindings as Agent access, while installs remain+ * a separate "always loaded" choice. If the profile has no bindings yet, the+ * install state remains the safest legacy fallback.** That fallback is the important part. It used to return "all agents" for an* unbound profile, which turned any unrelated save into a silent company-wide@@ -1000,6 +1016,16 @@ function accessFrom(: { mode: "specific", agentIds: new Set(install.agentIds) };}+function accessIncludingInstalls(next: AccessDraft, install: InstallState): AccessDraft {+ if (install.onAll || next.mode === "all") {+ return { mode: "all", agentIds: new Set() };+ }+ return {+ mode: "specific",+ agentIds: new Set([...next.agentIds, ...install.agentIds]),+ };+}+function galleryEntryFor(apps: AppGalleryDisplayEntry[],connection: ToolConnection | undefined,diff --git a/ui/src/pages/apps/AppLogo.test.tsx b/ui/src/pages/apps/AppLogo.test.tsxnew file mode 100644index 0000000000..a45e3c71cc--- /dev/null+++ b/ui/src/pages/apps/AppLogo.test.tsx@@ -0,0 +1,71 @@+// @vitest-environment jsdom++import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { resetAppBrandManifestCacheForTests } from "@/lib/app-brand-assets";+import { AppLogo } from "./AppLogo";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++describe("AppLogo", () => {+ let container: HTMLDivElement;+ let root: ReturnType<typeof createRoot>;++ beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ resetAppBrandManifestCacheForTests();+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue({+ ok: true,+ json: async () => ({ schemaVersion: 1, providers: [] }),+ }));+ });++ afterEach(() => {+ act(() => root.unmount());+ container.remove();+ vi.unstubAllGlobals();+ });++ it("renders decorative local light and dark provider marks", async () => {+ await act(async () => {+ root.render(+ <AppLogo+ name="Notion"+ logoUrl="/brands/apps/notion.svg"+ darkLogoUrl="/brands/apps/notion-dark.svg"+ size={36}+ />,+ );+ await Promise.resolve();+ await Promise.resolve();+ });++ const images = Array.from(container.querySelectorAll("img"));+ expect(images).toHaveLength(2);+ expect(images.map((image) => image.getAttribute("src"))).toEqual([+ "/brands/apps/notion.svg",+ "/brands/apps/notion-dark.svg",+ ]);+ expect(images.every((image) => image.alt === "")).toBe(true);+ expect(images[0]?.className).toContain("dark:hidden");+ expect(images[1]?.className).toContain("dark:block");+ });++ it("uses the deterministic letter tile only after a runtime image failure", async () => {+ await act(async () => {+ root.render(<AppLogo name="Jira" logoUrl="/brands/apps/missing.svg" />);+ await Promise.resolve();+ await Promise.resolve();+ });+ const image = container.querySelector("img");+ expect(image).toBeTruthy();++ act(() => image?.dispatchEvent(new Event("error")));++ expect(container.querySelector("img")).toBeNull();+ expect(container.textContent).toBe("J");+ });+});diff --git a/ui/src/pages/apps/AppLogo.tsx b/ui/src/pages/apps/AppLogo.tsxindex 199e264a93..7165c7acb2 100644--- a/ui/src/pages/apps/AppLogo.tsx+++ b/ui/src/pages/apps/AppLogo.tsx@@ -24,19 +24,21 @@ interface AppLogoProps {brandKey?: string | null;logoUrl?: string | null;allowRemoteFallback?: boolean;+ darkLogoUrl?: string | null;size?: number;className?: string;}/*** App icon for the gallery and connected-apps surfaces. Renders the manifest- * favicon when available, falling back to a coloured letter tile (deterministic- * colour per app name) when the image is missing or fails to load.+ * official local provider mark when available, including a dark-mode variant.+ * The deterministic letter tile is reserved for runtime image failures.*/export function AppLogo({name,brandKey,logoUrl,+ darkLogoUrl,allowRemoteFallback = true,size = 36,className,@@ -57,17 +59,19 @@ export function AppLogo({const resolvedLogoUrl = localLookupComplete? localAssets?.light ?? (allowRemoteFallback ? logoUrl : null): null;- const lightLogoUrl = resolvedLogoUrl && !failedLogoUrls.has(resolvedLogoUrl)+ const resolvedDarkLogoUrl = localLookupComplete+ ? localAssets?.dark ?? (allowRemoteFallback ? darkLogoUrl : null)+ : null;+ const lightLogoUrlForRender = resolvedLogoUrl && !failedLogoUrls.has(resolvedLogoUrl)? resolvedLogoUrl: null;- const requestedDarkLogoUrl = localAssets?.dark ?? null;- const darkLogoUrl = requestedDarkLogoUrl && !failedLogoUrls.has(requestedDarkLogoUrl)- ? requestedDarkLogoUrl+ const darkLogoUrlForRender = resolvedDarkLogoUrl && !failedLogoUrls.has(resolvedDarkLogoUrl)+ ? resolvedDarkLogoUrl: null;const hasDistinctThemeLogos = Boolean(- resolvedLogoUrl && requestedDarkLogoUrl && resolvedLogoUrl !== requestedDarkLogoUrl,+ resolvedLogoUrl && resolvedDarkLogoUrl && resolvedLogoUrl !== resolvedDarkLogoUrl,);- const fallbackLogoUrl = lightLogoUrl ?? darkLogoUrl;+ const fallbackLogoUrl = lightLogoUrlForRender ?? darkLogoUrlForRender;useEffect(() => {let active = true;@@ -85,7 +89,7 @@ export function AppLogo({useEffect(() => {setFailedLogoUrls(new Set());- }, [resolvedLogoUrl, localAssets?.dark]);+ }, [resolvedDarkLogoUrl, resolvedLogoUrl]);const markLogoFailed = (url: string) => {setFailedLogoUrls((current) => new Set(current).add(url));@@ -99,19 +103,19 @@ export function AppLogo({>{hasDistinctThemeLogos ? (<>- {lightLogoUrl ? (+ {lightLogoUrlForRender ? (<img- src={lightLogoUrl}+ src={lightLogoUrlForRender}alt=""width={size}height={size}- className="h-full w-full object-contain dark:hidden"- onError={() => markLogoFailed(lightLogoUrl)}+ className="h-full w-full object-contain p-1.5 dark:hidden"+ onError={() => markLogoFailed(lightLogoUrlForRender)}/>) : (<spanclassName={cn(- "flex h-full w-full items-center justify-center font-bold text-white dark:hidden",+ "flex h-full w-full items-center justify-center text-sm font-bold text-white dark:hidden",colorFor(name),)}aria-hidden="true"@@ -119,19 +123,19 @@ export function AppLogo({{letter}</span>)}- {darkLogoUrl ? (+ {darkLogoUrlForRender ? (<img- src={darkLogoUrl}+ src={darkLogoUrlForRender}alt=""width={size}height={size}- className="hidden h-full w-full object-contain dark:block"- onError={() => markLogoFailed(darkLogoUrl)}+ className="hidden h-full w-full object-contain p-1.5 dark:block"+ onError={() => markLogoFailed(darkLogoUrlForRender)}/>) : (<spanclassName={cn(- "hidden h-full w-full items-center justify-center font-bold text-white dark:flex",+ "hidden h-full w-full items-center justify-center text-sm font-bold text-white dark:flex",colorFor(name),)}aria-hidden="true"@@ -146,7 +150,7 @@ export function AppLogo({alt=""width={size}height={size}- className="h-full w-full object-contain"+ className="h-full w-full object-contain p-1.5"onError={() => markLogoFailed(fallbackLogoUrl)}/>)}@@ -157,11 +161,11 @@ export function AppLogo({return (<spanclassName={cn(- "inline-flex shrink-0 items-center justify-center rounded-lg font-bold text-white",+ "inline-flex shrink-0 items-center justify-center rounded-lg text-sm font-bold text-white",colorFor(name),className,)}- style={{ ...dimension, fontSize: Math.round(size * 0.42) }}+ style={dimension}aria-hidden="true">{letter}diff --git a/ui/src/pages/apps/AppNotConnected.test.tsx b/ui/src/pages/apps/AppNotConnected.test.tsxindex 58ec0ce1ba..90957a8b88 100644--- a/ui/src/pages/apps/AppNotConnected.test.tsx+++ b/ui/src/pages/apps/AppNotConnected.test.tsx@@ -9,6 +9,7 @@ import { AppNotConnected } from "./AppNotConnected";const listApplicationsMock = vi.hoisted(() => vi.fn());const listConnectionsMock = vi.hoisted(() => vi.fn());const listGalleryMock = vi.hoisted(() => vi.fn());+const listConnectionGrantsMock = vi.hoisted(() => vi.fn());const listConnectionActivityMock = vi.hoisted(() => vi.fn());const listActionRequestsMock = vi.hoisted(() => vi.fn());const listUserDirectoryMock = vi.hoisted(() => vi.fn());@@ -23,6 +24,7 @@ vi.mock("@/api/tools", () => ({listApplications: (companyId: string) => listApplicationsMock(companyId),listConnections: (companyId: string) => listConnectionsMock(companyId),listGallery: (companyId: string) => listGalleryMock(companyId),+ listConnectionGrants: (connectionId: string) => listConnectionGrantsMock(connectionId),listConnectionActivity: (connectionId: string, limit: number) =>listConnectionActivityMock(connectionId, limit),listActionRequests: (companyId: string, status: string) =>@@ -122,6 +124,8 @@ function connection(overrides: Record<string, unknown> = {}) {name: "GitHub",connectionKind: "managed",transport: "mcp_remote",+ authKind: "api_key",+ credentialPolicy: "shared",status: "archived",transportConfig: { url: "https://github.example/mcp" },config: { url: "https://github.example/mcp" },@@ -156,6 +160,21 @@ describe("AppNotConnected", () => {apps: [{ key: "github", name: "GitHub", logoUrl: "https://example.test/github.png" }],});listConnectionActivityMock.mockResolvedValue({ events: [], issues: {}, actionRequests: {} });+ listConnectionGrantsMock.mockResolvedValue({+ connection: { id: "conn-old", uid: "conn-old" },+ grants: [],+ capabilities: {+ canConfigure: true,+ canCreateOrganizationGrant: true,+ canSetCompanyInstall: true,+ canConnectAsCurrentUser: true,+ canManageAgentInstalls: true,+ canViewOtherPersonalIdentities: false,+ editableAgentIds: [],+ },+ currentUserId: "user-1",+ members: [],+ });listActionRequestsMock.mockResolvedValue({ actionRequests: [] });listUserDirectoryMock.mockResolvedValue({ users: [] });mockAgentsList.mockResolvedValue([]);@@ -341,4 +360,97 @@ describe("AppNotConnected", () => {expect(container.textContent).toContain("https://github.example/mcp");expect(container.textContent).toContain("Danger zone");});++ it("carries the retained identity into the reconnect flow", async () => {+ listConnectionsMock.mockResolvedValue({+ connections: [connection({ credentialPolicy: "per_user", createdByUserId: "user-1" })],+ });++ await renderPage();+ await act(async () => {+ Array.from(container.querySelectorAll("button"))+ .find((button) => button.textContent?.trim() === "Reconnect")+ ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });++ expect(mockNavigate).toHaveBeenCalledWith(+ "/apps/connect?applicationId=app-1&name=GitHub&new=1&reconnect=conn-old&identity=user&source=github&link=https%3A%2F%2Fgithub.example%2Fmcp",+ );+ });++ it("keeps a removed Vercel-backed connection in the isolated Vercel setup", async () => {+ listConnectionsMock.mockResolvedValue({+ connections: [connection({ credentialSource: "vercel_connect" })],+ });++ await renderPage();+ await act(async () => {+ Array.from(container.querySelectorAll("button"))+ .find((button) => button.textContent?.trim() === "Reconnect")+ ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });++ expect(mockNavigate).toHaveBeenCalledWith(+ "/apps/vercel-connect?applicationId=app-1&name=GitHub&new=1&reconnect=conn-old&identity=organization&source=github&link=https%3A%2F%2Fgithub.example%2Fmcp",+ );+ });++ it("prefills a custom MCP reconnect from the stored transport URL", async () => {+ listApplicationsMock.mockResolvedValue({+ applications: [application({ applicationKey: "custom-mcp", name: "Bla", metadata: null })],+ });+ listConnectionsMock.mockResolvedValue({+ connections: [connection({+ name: "Bla",+ config: { url: "http://127.0.0.1:49287" },+ transportConfig: { url: "http://127.0.0.1:49287" },+ })],+ });+ listGalleryMock.mockResolvedValue({ apps: [] });++ await renderPage();+ await act(async () => {+ Array.from(container.querySelectorAll("button"))+ .find((button) => button.textContent?.trim() === "Reconnect")+ ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });++ expect(mockNavigate).toHaveBeenCalledWith(+ "/apps/connect?applicationId=app-1&name=Bla&new=1&reconnect=conn-old&identity=organization&byo=1&link=http%3A%2F%2F127.0.0.1%3A49287",+ );+ });++ it("does not offer a removed personal reconnect to someone other than its fixed owner", async () => {+ listConnectionsMock.mockResolvedValue({+ connections: [connection({ credentialPolicy: "per_user", createdByUserId: "user-2" })],+ });+ listConnectionGrantsMock.mockResolvedValue({+ connection: { id: "conn-old", uid: "conn-old" },+ grants: [{+ id: "grant-user-2",+ kind: "user",+ subjectUserId: "user-2",+ status: "revoked",+ credentialSecretRefs: [],+ }],+ capabilities: {+ canConfigure: true,+ canCreateOrganizationGrant: true,+ canSetCompanyInstall: true,+ canConnectAsCurrentUser: true,+ canManageAgentInstalls: true,+ canViewOtherPersonalIdentities: true,+ editableAgentIds: [],+ },+ currentUserId: "user-1",+ members: [],+ });++ await renderPage();++ expect(container.textContent).toContain("The person this connection belongs to must reconnect it.");+ expect(Array.from(container.querySelectorAll("button")).some(+ (button) => button.textContent?.trim() === "Reconnect",+ )).toBe(false);+ });});diff --git a/ui/src/pages/apps/AppNotConnected.tsx b/ui/src/pages/apps/AppNotConnected.tsxindex b8d4f42cdb..b0379a539f 100644--- a/ui/src/pages/apps/AppNotConnected.tsx+++ b/ui/src/pages/apps/AppNotConnected.tsx@@ -3,6 +3,7 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import type { ToolConnection } from "@paperclipai/shared";import {connectionDisplaySecondaryHint,+ isConnectableAppSlug,isToolConnectionAttentionHealth,} from "@paperclipai/shared";import { Navigate, useNavigate, useParams } from "@/lib/router";@@ -20,12 +21,12 @@ import { buildCompanyUserProfileMap, type CompanyUserProfile } from "@/lib/compaimport { AppLogo } from "./AppLogo";import {appApplicationSourceSlug,+ appDefinitionDarkLogoUrl,appDefinitionLogoUrl,appDefinitionName,appDefinitionSlug,type AppGalleryDisplayEntry,} from "./app-definition-display";-import { isMcpDirectOAuthConnectSlug } from "./app-connect-policy";import { connectionAddress, connectionTransportLabel, DangerZone } from "./AppDetail";import { ActivityPanel } from "./app-detail/ActivityPanel";import { ReviewPanel } from "./app-detail/ReviewPanel";@@ -99,6 +100,11 @@ export function AppNotConnected() {queryFn: () => toolsApi.listConnectionActivity(previousConnection!.id, 20),enabled: !!previousConnection && activeTab === "activity",});+ const grantsQuery = useQuery({+ queryKey: queryKeys.tools.connectionGrants(previousConnection?.id ?? "__none__"),+ queryFn: () => toolsApi.listConnectionGrants(previousConnection!.id),+ enabled: !!previousConnection && activeTab === "setup",+ });const agentsQuery = useQuery({queryKey: queryKeys.agents.list(selectedCompanyId ?? "__none__"),queryFn: () => agentsApi.list(selectedCompanyId!),@@ -164,20 +170,48 @@ export function AppNotConnected() {}const gallery = (galleryQuery.data?.apps ?? []) as AppGalleryDisplayEntry[];- const logoUrl =- (appSourceSlug- ? appDefinitionLogoUrl(gallery.find((entry) => appDefinitionSlug(entry) === appSourceSlug))- : undefined) ??- appDefinitionLogoUrl(- gallery.find((entry) => appDefinitionName(entry).toLowerCase() === application.name.toLowerCase()),+ const logoEntry = (appSourceSlug+ ? gallery.find((entry) => appDefinitionSlug(entry) === appSourceSlug)+ : undefined) ?? gallery.find(+ (entry) => appDefinitionName(entry).toLowerCase() === application.name.toLowerCase(),);+ const logoUrl = appDefinitionLogoUrl(logoEntry);+ const darkLogoUrl = appDefinitionDarkLogoUrl(logoEntry);const previousAddress = previousConnection ? connectionAddress(previousConnection) : null;+ const retainedPersonalGrant = previousConnection?.credentialPolicy === "per_user"+ ? grantsQuery.data?.grants.find((grant) => (+ grant.kind === "user" && grant.subjectUserId === previousConnection.createdByUserId+ ))+ ?? grantsQuery.data?.grants.find((grant) => grant.kind === "user" && grant.status === "active")+ ?? grantsQuery.data?.grants.find((grant) => grant.kind === "user")+ ?? null+ : null;+ const retainedPersonalUserId = previousConnection?.credentialPolicy === "per_user"+ ? previousConnection.createdByUserId ?? retainedPersonalGrant?.subjectUserId ?? null+ : null;+ const canReconnect = !previousConnection+ || (previousConnection.credentialPolicy === "per_user"+ ? Boolean(+ retainedPersonalUserId+ && retainedPersonalUserId === grantsQuery.data?.currentUserId+ && grantsQuery.data?.capabilities.canConnectAsCurrentUser,+ )+ : grantsQuery.data?.capabilities.canConfigure === true);+ const reconnectUnavailableMessage = grantsQuery.isLoading+ ? "Checking who can reconnect this identity…"+ : grantsQuery.isError+ ? "We couldn't verify who can reconnect this identity. Reload the page to try again."+ : previousConnection?.credentialPolicy === "per_user"+ && retainedPersonalUserId !== grantsQuery.data?.currentUserId+ ? "The person this connection belongs to must reconnect it."+ : "You don't have permission to reconnect this identity.";const connectHref = newConnectionHref({applicationId,appName: application.name,previousAddress,- sourceSlug: appSourceSlug,+ previousConnection,+ sourceSlug: isConnectableAppSlug(appSourceSlug) ? appSourceSlug : null,});return (@@ -186,6 +220,7 @@ export function AppNotConnected() {applicationName={application.name}description={application.description}logoUrl={logoUrl}+ darkLogoUrl={darkLogoUrl}connectedCount={activeConnections.length}/>@@ -197,6 +232,8 @@ export function AppNotConnected() {previousConnection={previousConnection}previousAddress={previousAddress}userProfileById={userProfileById}+ canReconnect={canReconnect}+ reconnectUnavailableMessage={reconnectUnavailableMessage}onConnect={() => navigate(connectHref)}onEdit={(connectionId) => navigate(appTabHref(connectionId, "setup"))}/>@@ -259,16 +296,18 @@ function ApplicationHeader({applicationName,description,logoUrl,+ darkLogoUrl,connectedCount,}: {applicationName: string;description: string | null;logoUrl: string | undefined;+ darkLogoUrl: string | undefined;connectedCount: number;}) {return (<header className="flex flex-wrap items-center gap-4">- <AppLogo name={applicationName} logoUrl={logoUrl} size={48} />+ <AppLogo name={applicationName} logoUrl={logoUrl} darkLogoUrl={darkLogoUrl} size={48} /><div className="min-w-0 flex-1"><div className="flex items-center gap-2"><h1 className="truncate text-2xl font-bold tracking-tight">{applicationName}</h1>@@ -290,6 +329,8 @@ function SetupTab({previousConnection,previousAddress,userProfileById,+ canReconnect,+ reconnectUnavailableMessage,onConnect,onEdit,}: {@@ -298,6 +339,8 @@ function SetupTab({previousConnection: ToolConnection | null;previousAddress: string | null;userProfileById: ReadonlyMap<string, CompanyUserProfile>;+ canReconnect: boolean;+ reconnectUnavailableMessage: string;onConnect: () => void;onEdit: (connectionId: string) => void;}) {@@ -368,13 +411,20 @@ function SetupTab({</h2><p className="mt-0.5 text-sm text-muted-foreground">{previousConnection- ? "We kept the previous setup. Add a working key to bring it back online."+ ? previousConnection.authKind === "oauth"+ ? "We kept the previous setup. Sign in again to bring it back online."+ : "We kept the previous setup. Add a working key to bring it back online.": "Agents can't use it until it's connected."}</p>+ {previousConnection && !canReconnect ? (+ <p className="mt-1 text-sm text-muted-foreground">{reconnectUnavailableMessage}</p>+ ) : null}</div>- <Button onClick={onConnect}>- {previousConnection ? "Reconnect" : "Connect"}- </Button>+ {!previousConnection || canReconnect ? (+ <Button onClick={onConnect}>+ {previousConnection ? "Reconnect" : "Connect"}+ </Button>+ ) : null}</div></section>@@ -465,16 +515,34 @@ function newConnectionHref({applicationId,appName,previousAddress,+ previousConnection,sourceSlug,}: {applicationId: string;appName: string;previousAddress: string | null;+ previousConnection: ToolConnection | null;sourceSlug: string | null;}): string {const params = new URLSearchParams({ applicationId, name: appName, new: "1" });+ if (previousConnection) {+ params.set("reconnect", previousConnection.id);+ params.set("identity", previousConnection.credentialPolicy === "per_user" ? "user" : "organization");+ }if (sourceSlug) params.set("source", sourceSlug);- if (!isMcpDirectOAuthConnectSlug(sourceSlug)) params.set("byo", "1");- if (previousAddress && /^https?:\/\//i.test(previousAddress)) params.set("link", previousAddress);- return `/apps/connect?${params.toString()}`;+ else params.set("byo", "1");+ const storedLink = [+ previousConnection?.config?.url,+ previousConnection?.config?.endpoint,+ previousConnection?.config?.remoteUrl,+ previousConnection?.transportConfig.url,+ previousConnection?.transportConfig.endpoint,+ previousConnection?.transportConfig.remoteUrl,+ previousAddress,+ ].find((value): value is string => typeof value === "string" && /^https?:\/\//i.test(value));+ if (storedLink) params.set("link", storedLink);+ const path = previousConnection?.credentialSource === "vercel_connect"+ ? "/apps/vercel-connect"+ : "/apps/connect";+ return `${path}?${params.toString()}`;}diff --git a/ui/src/pages/apps/AppsConnect.test.tsx b/ui/src/pages/apps/AppsConnect.test.tsxindex 55d7c2e651..e61233f1a5 100644--- a/ui/src/pages/apps/AppsConnect.test.tsx+++ b/ui/src/pages/apps/AppsConnect.test.tsx@@ -1,12 +1,13 @@// @vitest-environment jsdom-import { act } from "react";+import { act, type ReactNode } from "react";import { createRoot, type Root } from "react-dom/client";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { CONNECTABLE_APP_DEFINITIONS } from "@paperclipai/shared";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { ApiError } from "@/api/client";import { queryKeys } from "@/lib/queryKeys";+import { ConnectionSetupFlow } from "@/features/connections/ConnectionSetupFlow";import { AppsConnect } from "./AppsConnect";const listGalleryMock = vi.hoisted(() => vi.fn());@@ -16,7 +17,6 @@ const connectAppMock = vi.hoisted(() => vi.fn());const startOAuthMock = vi.hoisted(() => vi.fn());const finishAppMock = vi.hoisted(() => vi.fn());const putConnectionInstallsMock = vi.hoisted(() => vi.fn());-const completeConnectionIntentMock = vi.hoisted(() => vi.fn());const listAgentsMock = vi.hoisted(() => vi.fn());const mockNavigate = vi.hoisted(() => vi.fn());const navigateTopLevelMock = vi.hoisted(() => vi.fn());@@ -24,12 +24,13 @@ const mockSearch = vi.hoisted(() => ({ value: "" }));const mockParams = vi.hoisted(() => ({ appKey: undefined as string | undefined }));const ZAPIER = CONNECTABLE_APP_DEFINITIONS.find((app) => app.slug === "zapier")!;-const MEM0 = CONNECTABLE_APP_DEFINITIONS.find((app) => app.slug === "mem0")!;+const GITHUB = CONNECTABLE_APP_DEFINITIONS.find((app) => app.slug === "github")!;const NOTION = CONNECTABLE_APP_DEFINITIONS.find((app) => app.slug === "notion")!;+const ASANA = CONNECTABLE_APP_DEFINITIONS.find((app) => app.slug === "asana")!;const POSTHOG = CONNECTABLE_APP_DEFINITIONS.find((app) => app.slug === "posthog")!;const GOOGLE_SHEETS = CONNECTABLE_APP_DEFINITIONS.find((app) => app.slug === "google-sheets")!;+const GOOGLE_DRIVE = CONNECTABLE_APP_DEFINITIONS.find((app) => app.slug === "google-drive")!;const GMAIL = CONNECTABLE_APP_DEFINITIONS.find((app) => app.slug === "gmail")!;-const ASANA = CONNECTABLE_APP_DEFINITIONS.find((app) => app.slug === "asana")!;vi.mock("@/api/tools", () => ({toolsApi: {@@ -37,9 +38,7 @@ vi.mock("@/api/tools", () => ({listApplications: (companyId: string) => listApplicationsMock(companyId),listConnections: (companyId: string) => listConnectionsMock(companyId),connectApp: (companyId: string, input: unknown) => connectAppMock(companyId, input),- startOAuth: (connectionId: string, interactionId?: string) => interactionId- ? startOAuthMock(connectionId, interactionId)- : startOAuthMock(connectionId),+ startOAuth: (connectionId: string, input?: unknown) => startOAuthMock(connectionId, input),finishApp: (companyId: string, connectionId: string, input: unknown) =>finishAppMock(companyId, connectionId, input),putConnectionInstalls: (connectionId: string, installs: unknown) =>@@ -47,13 +46,6 @@ vi.mock("@/api/tools", () => ({},}));-vi.mock("@/api/connection-intents", () => ({- connectionIntentsApi: {- complete: (interactionId: string, connectionId: string) =>- completeConnectionIntentMock(interactionId, connectionId),- },-}));-vi.mock("@/api/agents", () => ({agentsApi: { list: (companyId: string) => listAgentsMock(companyId) },}));@@ -123,6 +115,12 @@ function buttonContaining(text: string): HTMLButtonElement | undefined {) as HTMLButtonElement | undefined;}+function radioContaining(text: string): HTMLButtonElement | undefined {+ return Array.from(document.body.querySelectorAll<HTMLButtonElement>('[role="radio"]')).find(+ (button) => button.textContent?.includes(text),+ );+}+/*** Advance past the Access step (PAP-17835), which now sits between picking a* curated app and entering its credential. Picks "Any agent" so Continue is@@ -131,11 +129,12 @@ function buttonContaining(text: string): HTMLButtonElement | undefined {async function passAccessStep() {const anyAgent = Array.from(document.body.querySelectorAll('[role="radio"]')).find((option) => option.textContent?.includes("Any agent"));- if (!anyAgent) return;- await act(async () => {- anyAgent.dispatchEvent(new MouseEvent("click", { bubbles: true }));- });- await flushReact();+ if (anyAgent) {+ await act(async () => {+ anyAgent.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushReact();+ }const submit = Array.from(document.body.querySelectorAll("button")).find((b) => b.textContent?.trim() === "Save and continue"|| b.textContent?.trim().startsWith("Continue to"),@@ -146,6 +145,23 @@ async function passAccessStep() {await flushReact();}+/** Submit the curated setup screen after Access for OAuth methods that also+ * expose customer-owned client details. Browser sign-in remains the default+ * when the optional client ID is left empty. */+async function submitCuratedOAuthSetup() {+ const submit = buttonByText("Continue to sign in");+ // Automatic OAuth definitions hand off directly from Access. Definitions+ // with required provider configuration still render the setup submit.+ if (!submit) {+ await flushReact();+ return;+ }+ await act(async () => {+ submit.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushReact();+}+async function gotoLinkFrame(container: HTMLDivElement, url: string) {const linkInput = Array.from(container.querySelectorAll<HTMLInputElement>("input"),@@ -164,6 +180,7 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {let mountedRoot: Root | null;beforeEach(() => {+ vi.resetAllMocks();mockSearch.value = "";mockParams.appKey = undefined;container = document.createElement("div");@@ -172,6 +189,7 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {listGalleryMock.mockResolvedValue({apps: [ZAPIER,+ GITHUB,],capabilities: {canSetCompanyInstall: true,@@ -187,7 +205,6 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {expiresAt: "2099-01-01T00:00:00.000Z",});finishAppMock.mockResolvedValue({});- completeConnectionIntentMock.mockResolvedValue({ status: "accepted" });putConnectionInstallsMock.mockResolvedValue({ connectionId: "conn-1", installs: [] });connectAppMock.mockResolvedValue({connectionId: "conn-1",@@ -211,14 +228,14 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {vi.clearAllMocks();});- async function render(queryClient?: QueryClient, byoOnly = false) {+ async function render(queryClient?: QueryClient, byoOnly = false, content?: ReactNode) {const root = createRoot(container);mountedRoot = root;const client = queryClient ?? new QueryClient({ defaultOptions: { queries: { retry: false } } });await act(async () => {root.render(<QueryClientProvider client={client}>- <AppsConnect byoOnly={byoOnly} />+ {content ?? <AppsConnect byoOnly={byoOnly} />}</QueryClientProvider>,);});@@ -269,52 +286,49 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {// credential is entered.// -------------------------------------------------------------------------- it("asks both access questions before the credential and defaults per auth kind", async () => {- mockParams.appKey = "mem0";- listGalleryMock.mockResolvedValueOnce({ apps: [MEM0] });+ it("asks both access questions and defaults to company-wide access", async () => {+ mockParams.appKey = "github";await render();expect(container.textContent).toContain("Access");expect(container.textContent).toContain("Who is this credential for?");expect(container.textContent).toContain("Which agents can use this connection?");- // Nothing about the credential is on screen yet.- expect(container.textContent).not.toContain("Connect Mem0");+ // Nothing about the credential itself is on screen yet.+ expect(container.querySelector('input[type="password"]')).toBeNull();const radios = Array.from(document.body.querySelectorAll('[role="radio"]'));const justMe = radios.find((r) => r.textContent?.includes("Just me"));- const wholeOrg = radios.find((r) => r.textContent?.includes("The whole organization"));+ const wholeOrg = radios.find((r) => r.textContent?.includes("Everyone in the company"));const agentsIPick = radios.find((r) => r.textContent?.includes("Agents I pick"));expect(justMe).toBeTruthy();expect(wholeOrg).toBeTruthy();- // A key-based app is a shared service credential by default...+ // A flexible connection method defaults to the company identity...expect(wholeOrg?.getAttribute("aria-checked")).toBe("true");expect(justMe?.getAttribute("aria-checked")).toBe("false");- // ...and the safer agent default is a picked set, not every agent.- expect(agentsIPick?.getAttribute("aria-checked")).toBe("true");+ // ...and every agent is the product default for both access and install.+ expect(agentsIPick?.getAttribute("aria-checked")).toBe("false");+ expect(radios.find((r) => r.textContent?.includes("Any agent"))?.getAttribute("aria-checked"))+ .toBe("true");});- it("blocks Continue until Agents I pick has at least one agent", async () => {- mockParams.appKey = "mem0";- listGalleryMock.mockResolvedValueOnce({ apps: [MEM0] });+ it("defaults to every agent and only blocks an empty explicit selection", async () => {+ mockParams.appKey = "github";await render();- // "Agents I pick" with nothing picked is not a usable connection, so the- // primary action stays disabled rather than failing at submit.- expect(buttonByText("Save and continue")?.disabled).toBe(true);+ expect(buttonByText("Save and continue")?.disabled).toBe(false);await act(async () => {Array.from(document.body.querySelectorAll('[role="radio"]'))- .find((r) => r.textContent?.includes("Any agent"))+ .find((r) => r.textContent?.includes("Agents I pick"))?.dispatchEvent(new MouseEvent("click", { bubbles: true }));});await flushReact();- expect(buttonByText("Save and continue")?.disabled).toBe(false);+ expect(buttonByText("Save and continue")?.disabled).toBe(true);});it("keeps the access selections when the wizard moves backward", async () => {- mockParams.appKey = "mem0";- listGalleryMock.mockResolvedValueOnce({ apps: [MEM0] });+ mockParams.appKey = "github";await render();await act(async () => {@@ -334,7 +348,7 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {buttonByText("Save and continue")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));});await flushReact();- expect(container.textContent).toContain("Connect Mem0");+ expect(container.textContent).toContain("Connect GitHub");await act(async () => {buttonByText("Back")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));@@ -350,21 +364,11 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {});/**- * The identity question is answered per connection method, not per auth kind.- *- * A homogeneous fixture cannot tell those two apart: if every app on screen- * is API-key-only, a blanket rule and a per-method predicate produce exactly- * the same DOM. So both live in one gallery here — Mem0, whose only method- * is an API key, and PostHog, whose methods are identity-bearing sign-in plus- * a key its own label calls *personal*. The two mounts must disagree about- * the default, which no blanket rule can do.- *- * "Just me" also has to stay live for the API-key-only app, not disabled with- * a reason: the personal key path completes and lands on the caller's own- * grant, so disabling it would describe the product wrongly.+ * Company-wide is a default, not a restriction. Flexible API-key and OAuth+ * methods must still let the operator deliberately choose a personal identity.*/- it("decides the identity default per method, and keeps a personal key submittable", async () => {- listGalleryMock.mockResolvedValue({ apps: [MEM0, POSTHOG] });+ it("defaults flexible methods to company identity and keeps personal credentials submittable", async () => {+ listGalleryMock.mockResolvedValue({ apps: [GITHUB, POSTHOG] });const identityChoices = () => {const radios = Array.from(@@ -372,29 +376,29 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {);return {justMe: radios.find((r) => r.textContent?.includes("Just me")),- wholeOrg: radios.find((r) => r.textContent?.includes("The whole organization")),+ wholeOrg: radios.find((r) => r.textContent?.includes("Everyone in the company")),};};// --- API-key-only method: shared by default, personal still offered ------let root = await render();await act(async () => {- buttonContaining("Mem0")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ buttonContaining("GitHub")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));});await flushReact();- const mem0 = identityChoices();- expect(mem0.wholeOrg?.getAttribute("aria-checked")).toBe("true");- expect(mem0.justMe?.getAttribute("aria-checked")).toBe("false");+ const github = identityChoices();+ expect(github.wholeOrg?.getAttribute("aria-checked")).toBe("true");+ expect(github.justMe?.getAttribute("aria-checked")).toBe("false");// Present, and genuinely selectable — not the disabled-with-reason state.- expect(mem0.justMe).toBeTruthy();- expect(mem0.justMe?.disabled).toBe(false);+ expect(github.justMe).toBeTruthy();+ expect(github.justMe?.disabled).toBe(false);expect(document.body.textContent).not.toContain("This connection method supports a shared organization credential only.",);await act(async () => {- mem0.justMe?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ github.justMe?.dispatchEvent(new MouseEvent("click", { bubbles: true }));});await flushReact();await act(async () => {@@ -409,7 +413,7 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {await flushReact();const keyField = container.querySelector<HTMLInputElement>("input[type=password]");- await act(async () => setInputValue(keyField!, "mem0-personal-token"));+ await act(async () => setInputValue(keyField!, "github-personal-token"));await flushReact();await act(async () => {buttonByText("Connect")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));@@ -420,11 +424,11 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {// a personal grant. A disabled "Just me" would make this unreachable.expect(connectAppMock).toHaveBeenCalledTimes(1);expect(connectAppMock.mock.calls[0]?.[1]).toMatchObject({- galleryKey: "mem0",+ galleryKey: "github",grantKind: "user",});- // --- Same gallery, identity-bearing method: personal by default ----------+ // --- Same gallery, identity-bearing method: company by default -----------await act(async () => root.unmount());document.body.innerHTML = "";container = document.createElement("div");@@ -433,24 +437,75 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {root = await render();const posthog = identityChoices();- expect(posthog.justMe?.getAttribute("aria-checked")).toBe("true");- expect(posthog.wholeOrg?.getAttribute("aria-checked")).toBe("false");+ expect(posthog.justMe?.getAttribute("aria-checked")).toBe("false");+ expect(posthog.wholeOrg?.getAttribute("aria-checked")).toBe("true");expect(posthog.justMe?.disabled).toBe(false);expect(posthog.wholeOrg?.disabled).toBe(false);});- it("shows Gmail as a personal-only identity", async () => {- listGalleryMock.mockResolvedValue({ apps: [GMAIL] });+ it("shows Gmail's instance configuration notice instead of a dead connect path", async () => {+ const reason = "Configure Paperclip ID before connecting Gmail.";+ listGalleryMock.mockResolvedValue({+ apps: [{ ...GMAIL, availability: { available: false, reason } }],+ });+ await render();++ const gmail = buttonContaining("Gmail");+ expect(gmail?.disabled).toBe(true);+ expect(gmail?.textContent).toContain(reason);+ expect(gmail?.textContent).not.toContain("Coming soon");+ });++ it("collects customer-owned OAuth client details for a curated manual OAuth app", async () => {+ listGalleryMock.mockResolvedValue({ apps: [ASANA] });+ mockParams.appKey = "asana";await render();+ await passAccessStep();++ expect(container.textContent).toContain("Your OAuth app");+ expect(container.textContent).toContain("Open Asana app settings");+ expect(container.textContent).toContain("Create an Asana MCP OAuth app");+ expect(container.textContent).toContain("Paperclip callback URL");+ expect(container.textContent).toContain(+ "http://localhost:3000/api/tools/oauth/callback",+ );+ expect(buttonByText("Continue to sign in")?.disabled).toBe(true);+ const clientId = container.querySelector<HTMLInputElement>("#curated-oauth-client-id")!;+ const clientSecret = container.querySelector<HTMLInputElement>("#curated-oauth-client-secret")!;await act(async () => {- buttonContaining("Gmail")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ setInputValue(clientId, "asana-client-id");+ setInputValue(clientSecret, "asana-client-secret");});await flushReact();+ expect(buttonByText("Continue to sign in")?.disabled).toBe(false);- expect(document.body.textContent).toContain("Just me.");- expect(document.body.textContent).toContain("Agents use this Gmail identity only when work runs for you.");- expect(document.body.textContent).not.toContain("The whole organization");+ await act(async () => {+ buttonByText("Continue to sign in")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushReact();++ expect(connectAppMock).toHaveBeenCalledWith("company-1", expect.objectContaining({+ galleryKey: "asana",+ connectionMethodKey: "mcp-own-oauth",+ oauthClient: {+ clientId: "asana-client-id",+ clientSecret: "asana-client-secret",+ },+ }));+ });++ it("opens a manual OAuth app from the same source deep link Browse uses", async () => {+ listGalleryMock.mockResolvedValue({ apps: [ASANA] });+ mockParams.appKey = undefined;+ mockSearch.value = "source=asana";++ await render();++ expect(document.body.textContent).toContain("Who is this credential for?");+ expect(document.body.textContent).toContain("Which agents can use this connection?");+ expect(document.body.textContent).not.toContain("Pick the app you want your agents to use.");+ expect(mockNavigate).not.toHaveBeenCalledWith("/apps/connect", { replace: true });});it("opens a brokered Gmail deep link at the access step", async () => {@@ -465,6 +520,28 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {expect(mockNavigate).not.toHaveBeenCalledWith("/apps/connect", { replace: true });});+ it("defaults Google Drive setup to its write-capable connection method", async () => {+ mockParams.appKey = "google-drive";+ listGalleryMock.mockResolvedValue({ apps: [GOOGLE_DRIVE] });++ await render();++ expect(container.textContent).toContain("Google Developer Preview access required");+ expect(container.textContent).toContain("does not enable unrelated Paperclip customers");+ expect(container.textContent).toContain("final project-registration email");+ expect(+ Array.from(container.querySelectorAll<HTMLAnchorElement>("a")).find((link) =>+ link.textContent?.includes("Apply or verify Developer Preview enrollment"),+ )?.href,+ ).toBe("https://developers.google.com/workspace/preview");+ await passAccessStep();++ expect(radioContaining("Read & create")?.getAttribute("aria-checked")).toBe("true");+ expect(radioContaining("Read only")?.getAttribute("aria-checked")).toBe("false");+ expect(container.textContent).toContain("Before connecting, enroll the signed-in Workspace account");+ expect(container.textContent).toContain("Your OAuth app");+ });+/*** Design §"Question 2": a member who may create a personal grant but cannot* configure a company-wide install sees **Any agent** disabled with the@@ -475,9 +552,9 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {* returned with the gallery reaches the real create flow.*/it("disables Any agent and blocks Continue when the member cannot install company-wide", async () => {- mockParams.appKey = "zapier";+ mockParams.appKey = "github";listGalleryMock.mockResolvedValueOnce({- apps: [ZAPIER],+ apps: [GITHUB],capabilities: {canSetCompanyInstall: false,companyInstallReason: "Your company policy limits this choice to connection managers.",@@ -505,7 +582,7 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {});it("opens the selected app directly on its setup route", async () => {- mockParams.appKey = "zapier";+ mockParams.appKey = "github";await render();// A deep-linked app lands on Access first: identity and reach are chosen@@ -513,11 +590,11 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {expect(container.textContent).toContain("Who is this credential for?");await passAccessStep();- expect(container.textContent).toContain("Connect Zapier");+ expect(container.textContent).toContain("Connect GitHub");expect(container.textContent).not.toContain("Pick the app you want your agents to use.");});- it("requires a PostHog method and submits the selected project scope", async () => {+ it("connects PostHog without a project ID and keeps optional controls advanced", async () => {mockParams.appKey = "posthog";listGalleryMock.mockResolvedValueOnce({ apps: [POSTHOG] });await render();@@ -527,22 +604,25 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {await passAccessStep();expect(container.textContent).toContain("How do you want to connect?");- expect(buttonByText("Sign in with PostHog")?.getAttribute("aria-pressed")).toBe("false");- expect(buttonByText("Use a personal API key")?.getAttribute("aria-pressed")).toBe("false");+ expect(radioContaining("Sign in with PostHog")?.getAttribute("aria-checked")).toBe("false");+ expect(radioContaining("Use a personal API key")?.getAttribute("aria-checked")).toBe("false");expect(buttonByText("Connect")?.disabled).toBe(true);await act(async () => {- buttonByText("Use a personal API key")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ radioContaining("Use a personal API key")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));});await flushReact();+ expect(container.textContent).not.toContain("Where are credentials managed?");+ expect(container.textContent).not.toContain("Vercel Connect");+const keyInput = container.querySelector<HTMLInputElement>('input[type="password"]');const advanced = buttonByText("Advanced");expect(keyInput).toBeTruthy();- expect(container.querySelector<HTMLInputElement>('input[placeholder="Optional numeric project ID"]'))- .toBeNull();+ expect(container.querySelector<HTMLInputElement>('input[placeholder="Optional numeric project ID"]')).toBeNull();expect(container.querySelector('[role="switch"]')).toBeNull();expect(advanced?.getAttribute("aria-expanded")).toBe("false");+ expect(container.textContent).not.toContain("Pin to project ID");expect(container.textContent).not.toContain("Feature groups");expect(container.textContent).not.toContain("Individual tools");expect(container.textContent).not.toContain("Tool response mode");@@ -553,44 +633,270 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {await flushReact();expect(advanced?.getAttribute("aria-expanded")).toBe("true");+ expect(container.textContent).toContain("Pin to project ID");+ expect(container.querySelector<HTMLInputElement>('input[placeholder="Optional numeric project ID"]')).toBeTruthy();+ expect(container.querySelector('[role="switch"]')?.getAttribute("aria-checked")).toBe("false");expect(container.textContent).toContain("Feature groups");expect(container.textContent).toContain("Individual tools");expect(container.textContent).not.toContain("Tool response mode");- const projectInput = container.querySelector<HTMLInputElement>(- 'input[placeholder="Optional numeric project ID"]',- );- expect(projectInput).toBeTruthy();- expect(container.querySelector('[role="switch"]')?.getAttribute("aria-checked")).toBe("false");await act(async () => {- setInputValue(projectInput!, "12345");setInputValue(keyInput!, "phx_test-key");});await flushReact();+ const submit = buttonByText("Connect");+ expect(submit).toBeTruthy();+ expect(submit?.disabled).toBe(false);await act(async () => {- buttonByText("Connect")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ submit?.dispatchEvent(new MouseEvent("click", { bubbles: true }));});await flushReact();expect(connectAppMock).toHaveBeenCalledWith("company-1", {galleryKey: "posthog",connectionMethodKey: "mcp-api-key",- name: "PostHog",+ name: "PostHog for the company",+ credentialSource: "paperclip_vault",credentialValues: { "credentials.authorization": "phx_test-key" },configValues: {- projectId: "12345",readOnly: false,mode: "tools",},applicationId: undefined,- // PostHog's Access step defaults to "Just me" because its primary method- // is identity-bearing sign-in, and a personal API key is personal too.- // The choice was on screen and accepted, so it reaches the server.- grantKind: "user",+ // Flexible methods default to a company identity, represented by omitting+ // the optional personal grantKind from the request.+ });+ });++ it("hands reviewed PostHog credentials to Vercel and submits only the connector reference", async () => {+ mockParams.appKey = "posthog";+ listGalleryMock.mockResolvedValueOnce({+ apps: [POSTHOG],+ credentialSources: {+ vercelConnect: {+ available: true,+ enabled: true,+ authentication: "access_token",+ manageUrl: "https://vercel.com/connect",+ reason: null,+ },+ },+ });+ await render(undefined, false, <AppsConnect credentialSource="vercel_connect" />);+ await passAccessStep();+ await act(async () => {+ radioContaining("Use a personal API key")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushReact();++ expect(container.textContent).toContain("Create or attach the connector in Vercel");+ expect(container.querySelector('a[href="https://vercel.com/connect"]')).toBeTruthy();+ expect(container.querySelector<HTMLInputElement>('input[type="password"]')).toBeNull();+ const connectorInput = container.querySelector<HTMLInputElement>('#vercel-connect-connector');+ expect(connectorInput).toBeTruthy();+ await act(async () => {+ setInputValue(connectorInput!, "posthog/paperclip");+ });+ await flushReact();+ const vercelSubmit = buttonByText("Validate and connect");+ expect(vercelSubmit).toBeTruthy();+ expect(vercelSubmit?.disabled).toBe(false);+ await act(async () => {+ vercelSubmit?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushReact();++ expect(connectAppMock).toHaveBeenCalledWith("company-1", {+ galleryKey: "posthog",+ connectionMethodKey: "mcp-api-key",+ name: "PostHog for the company",+ credentialSource: "vercel_connect",+ vercelConnect: { connector: "posthog/paperclip" },+ configValues: { readOnly: false, mode: "tools" },+ applicationId: undefined,});+ expect(JSON.stringify(connectAppMock.mock.calls[0])).not.toContain("credentialValues");});- it("auto-starts the allowlisted Notion source deep link and opens provider sign-in", async () => {+ it("folds optional customer-owned OAuth details under Advanced", async () => {+ mockParams.appKey = "posthog";+ listGalleryMock.mockResolvedValueOnce({ apps: [POSTHOG] });+ await render();+ await passAccessStep();++ await act(async () => {+ radioContaining("Sign in with PostHog")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushReact();++ const advanced = buttonByText("Advanced");+ expect(advanced?.getAttribute("aria-expanded")).toBe("false");+ expect(container.textContent).not.toContain("Use your own OAuth app");+ expect(container.querySelector("#curated-oauth-client-id")).toBeNull();+ expect(buttonByText("Continue to sign in")?.disabled).toBe(false);++ await act(async () => {+ advanced?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushReact();++ expect(container.textContent).toContain("Use your own OAuth app");+ expect(container.querySelector("#curated-oauth-client-id")).toBeTruthy();+ expect(container.textContent).toContain("Paperclip callback URL");+ });++ it("shows unavailable Vercel configuration only inside the isolated Vercel entry point", async () => {+ listGalleryMock.mockResolvedValueOnce({+ apps: [POSTHOG],+ credentialSources: {+ vercelConnect: {+ available: false,+ enabled: true,+ authentication: null,+ manageUrl: "https://vercel.com/connect",+ reason: "Vercel Connect needs workload OIDC or an instance access token.",+ },+ },+ });+ await render(undefined, false, <AppsConnect credentialSource="vercel_connect" />);++ expect(container.textContent).toContain("Connect through Vercel");+ expect(container.textContent).toContain("Vercel Connect needs workload OIDC or an instance access token.");+ expect(buttonContaining("PostHog")?.disabled).toBe(true);+ expect(container.textContent).not.toContain("Where are credentials managed?");+ });++ it("renders the same PostHog method choices in page and task-dialog hosts", async () => {+ const methodState = () => ({+ oauth: buttonByText("Sign in with PostHog")?.getAttribute("aria-pressed"),+ apiKey: buttonByText("Use a personal API key")?.getAttribute("aria-pressed"),+ connectDisabled: buttonByText("Connect")?.disabled,+ });++ mockParams.appKey = "posthog";+ listGalleryMock.mockResolvedValue({ apps: [POSTHOG] });+ const pageRoot = await render();+ await passAccessStep();+ const pageMethods = methodState();+ await act(async () => pageRoot.unmount());+ container.innerHTML = "";++ mockParams.appKey = undefined;+ const dialogRoot = await render(undefined, false, (+ <ConnectionSetupFlow+ host="dialog"+ serviceSlug="posthog"+ requestedAgentId="agent-1"+ />+ ));+ expect(container.textContent).toContain("This task grants access only to Ada");+ const continueButton = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent?.trim() === "Save and continue",+ );+ expect(continueButton).toBeTruthy();+ expect(continueButton?.disabled).toBe(false);+ await act(async () => {+ continueButton?.click();+ });+ await flushReact();++ expect(methodState()).toEqual(pageMethods);+ await act(async () => dialogRoot.unmount());+ });++ it("reserves the task-dialog OAuth popup before awaiting connection setup and assigns only the validated URL", async () => {+ listGalleryMock.mockResolvedValue({ apps: [NOTION] });+ let resolveConnect!: (value: unknown) => void;+ connectAppMock.mockReturnValue(new Promise((resolve) => { resolveConnect = resolve; }));+ const assign = vi.fn();+ const focus = vi.fn();+ const openSpy = vi.spyOn(window, "open").mockReturnValue({+ closed: false,+ location: { assign },+ focus,+ } as unknown as Window);++ const dialogRoot = await render(undefined, false, (+ <ConnectionSetupFlow+ host="dialog"+ serviceSlug="notion"+ requestedAgentId="agent-1"+ interactionId="interaction-1"+ />+ ));+ await passAccessStep();+ await submitCuratedOAuthSetup();++ expect(connectAppMock).toHaveBeenCalledTimes(1);+ expect(openSpy).toHaveBeenCalledWith(+ "about:blank",+ "paperclip-connection-oauth",+ "popup,width=720,height=760,resizable=yes,scrollbars=yes",+ );+ expect(openSpy.mock.invocationCallOrder[0]).toBeLessThan(connectAppMock.mock.invocationCallOrder[0]!);+ expect(assign).not.toHaveBeenCalled();++ resolveConnect({+ connectionId: "conn-notion",+ application: { id: "app-notion", name: "Notion" },+ connection: { id: "conn-notion", credentialPolicy: "per_user" },+ actions: { readOnly: [], canMakeChanges: [] },+ catalog: [],+ suggestedDefaults: {},+ auth: { kind: "oauth", startUrl: "https://untrusted-return-value.test/ignored" },+ });+ await flushReact();+ await flushReact();++ expect(startOAuthMock).toHaveBeenCalledWith("conn-notion", {+ asCurrentUser: true,+ interactionId: "interaction-1",+ });+ expect(assign).toHaveBeenCalledWith("https://mcp.notion.com/authorize?state=resumed");+ expect(assign).not.toHaveBeenCalledWith("https://untrusted-return-value.test/ignored");+ expect(focus).toHaveBeenCalled();++ openSpy.mockRestore();+ await act(async () => dialogRoot.unmount());+ });++ it("keeps the task dialog recoverable when the browser blocks its reserved OAuth popup", async () => {+ listGalleryMock.mockResolvedValue({ apps: [NOTION] });+ connectAppMock.mockResolvedValue({+ connectionId: "conn-notion",+ application: { id: "app-notion", name: "Notion" },+ connection: { id: "conn-notion", credentialPolicy: "per_user" },+ actions: { readOnly: [], canMakeChanges: [] },+ catalog: [],+ suggestedDefaults: {},+ auth: { kind: "oauth", startUrl: null },+ });+ const openSpy = vi.spyOn(window, "open").mockReturnValue(null);+ const onPhaseChange = vi.fn();++ const dialogRoot = await render(undefined, false, (+ <ConnectionSetupFlow+ host="dialog"+ serviceSlug="notion"+ requestedAgentId="agent-1"+ interactionId="interaction-1"+ onPhaseChange={onPhaseChange}+ />+ ));+ await passAccessStep();+ await submitCuratedOAuthSetup();+ await flushReact();+ await flushReact();++ expect(container.textContent).toContain("Allow popups for this site and try again");+ expect(container.textContent).toContain("Try again");+ expect(onPhaseChange).toHaveBeenCalledWith("needs_retry");++ openSpy.mockRestore();+ await act(async () => dialogRoot.unmount());+ });++ it("chooses identity before the Notion source deep link opens provider sign-in", async () => {mockSearch.value = "source=notion";listGalleryMock.mockResolvedValueOnce({ apps: [NOTION] });connectAppMock.mockResolvedValueOnce({@@ -605,10 +911,22 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {await render();+ expect(connectAppMock).not.toHaveBeenCalled();+ expect(navigateTopLevelMock).not.toHaveBeenCalled();+ expect(container.textContent).toContain("Choose access before sign-in");+ const identityRadios = Array.from(document.body.querySelectorAll('[role="radio"]'));+ expect(identityRadios.find((radio) => radio.textContent?.includes("Everyone in the company"))?.getAttribute("aria-checked"))+ .toBe("true");++ await passAccessStep();+ await submitCuratedOAuthSetup();+expect(connectAppMock).toHaveBeenCalledTimes(1);expect(connectAppMock).toHaveBeenCalledWith("company-1", {galleryKey: "notion",- name: "Notion",+ connectionMethodKey: "mcp-oauth",+ name: "Notion for the company",+ credentialSource: "paperclip_vault",credentialValues: {},configValues: undefined,applicationId: undefined,@@ -624,6 +942,8 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {connectAppMock.mockReturnValueOnce(new Promise(() => {}));await render();+ await passAccessStep();+ await submitCuratedOAuthSetup();expect(container.textContent).toContain("Connect Notion");expect(container.textContent).toContain("Preparing secure sign-in");@@ -647,6 +967,7 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {id: "conn-existing",applicationId: "app-notion",authKind: "oauth",+ credentialPolicy: "per_user",status: "draft",config: { sourceTemplateKey: "notion" },transportConfig: {},@@ -660,14 +981,309 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {});await render();+ expect(container.textContent).toContain("Reconnect keeps this identity type");+ expect(startOAuthMock).not.toHaveBeenCalled();+ await passAccessStep();+ await submitCuratedOAuthSetup();expect(connectAppMock).not.toHaveBeenCalled();- expect(startOAuthMock).toHaveBeenCalledWith("conn-existing", interactionId);+ expect(startOAuthMock).toHaveBeenCalledWith("conn-existing", {+ asCurrentUser: true,+ interactionId,+ });expect(navigateTopLevelMock).toHaveBeenCalledWith("https://mcp.notion.com/authorize?state=existing",);});+ it("resumes the exact draft selected by Finish setup", async () => {+ mockSearch.value = "source=notion&resume=22222222-2222-4222-8222-222222222222";+ listGalleryMock.mockResolvedValueOnce({ apps: [NOTION] });+ listApplicationsMock.mockResolvedValueOnce({+ applications: [{+ id: "app-notion",+ status: "active",+ metadata: { sourceTemplateKey: "notion" },+ }],+ });+ listConnectionsMock.mockResolvedValueOnce({+ connections: [+ {+ id: "11111111-1111-4111-8111-111111111111",+ applicationId: "app-notion",+ authKind: "oauth",+ credentialPolicy: "shared",+ status: "draft",+ config: { sourceTemplateKey: "notion" },+ transportConfig: {},+ },+ {+ id: "22222222-2222-4222-8222-222222222222",+ applicationId: "app-notion",+ authKind: "oauth",+ credentialPolicy: "per_user",+ status: "draft",+ config: { sourceTemplateKey: "notion" },+ transportConfig: {},+ },+ ],+ });++ await render();+ await vi.waitFor(() => {+ expect(container.textContent).toContain("Finish connecting Notion");+ });+ expect(container.textContent).toContain("identity and agent access will stay the same");+ expect(container.textContent).not.toContain("Choose access before sign-in");+ expect(buttonByText("Continue to sign in")).toBeUndefined();+ await act(async () => {+ buttonByText("Finish with Notion")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushReact();++ expect(connectAppMock).not.toHaveBeenCalled();+ expect(startOAuthMock).toHaveBeenCalledWith(+ "22222222-2222-4222-8222-222222222222",+ { asCurrentUser: true },+ );+ expect(navigateTopLevelMock).toHaveBeenCalledWith(+ "https://mcp.notion.com/authorize?state=resumed",+ );+ });++ it("returns a declined OAuth draft to the same one-action resume checkpoint", async () => {+ mockSearch.value = "source=notion&resume=22222222-2222-4222-8222-222222222222&oauth=denied&code=oauth_authorization_denied";+ listGalleryMock.mockResolvedValueOnce({ apps: [NOTION] });+ listApplicationsMock.mockResolvedValueOnce({+ applications: [{+ id: "app-notion",+ status: "draft",+ metadata: { sourceTemplateKey: "notion" },+ }],+ });+ listConnectionsMock.mockResolvedValueOnce({+ connections: [{+ id: "22222222-2222-4222-8222-222222222222",+ applicationId: "app-notion",+ authKind: "oauth",+ credentialPolicy: "shared",+ status: "draft",+ config: { sourceTemplateKey: "notion", connectionMethodKey: "mcp-oauth" },+ transportConfig: {},+ }],+ });++ await render();+ await flushReact();+ expect(container.textContent).toContain("Notion couldn’t connect");+ expect(container.textContent).toContain("Your saved connection was not changed");+ expect(buttonByText("Try again")).toBeTruthy();++ await act(async () => {+ buttonByText("Try again")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushReact();+ expect(startOAuthMock).toHaveBeenCalledWith(+ "22222222-2222-4222-8222-222222222222",+ { asCurrentUser: false },+ );+ });++ it.each([+ ["personal", "per_user", true],+ ["organization", "shared", false],+ ] as const)("preserves an active %s identity when reconnecting Notion", async (+ _label,+ credentialPolicy,+ asCurrentUser,+ ) => {+ mockSearch.value = "source=notion";+ listGalleryMock.mockResolvedValueOnce({ apps: [NOTION] });+ listApplicationsMock.mockResolvedValueOnce({+ applications: [{+ id: "app-notion",+ status: "active",+ metadata: { sourceTemplateKey: "notion" },+ }],+ });+ listConnectionsMock.mockResolvedValueOnce({+ connections: [{+ id: "conn-existing",+ applicationId: "app-notion",+ authKind: "oauth",+ credentialPolicy,+ status: "active",+ config: { sourceTemplateKey: "notion" },+ transportConfig: {},+ }],+ });+ startOAuthMock.mockResolvedValueOnce({+ connectionId: "conn-existing",+ provider: "notion",+ authorizationUrl: "https://mcp.notion.com/authorize?state=existing",+ expiresAt: "2099-01-01T00:00:00.000Z",+ });++ await render();+ expect(container.textContent).toContain(+ credentialPolicy === "per_user" ? "Just me." : "Everyone in the company",+ );+ expect(container.textContent).toContain("Existing agent access stays the same");+ await passAccessStep();+ await submitCuratedOAuthSetup();++ expect(startOAuthMock).toHaveBeenCalledWith("conn-existing", {+ asCurrentUser,+ });+ });++ it("revives an archived Notion connection without reopening its organization identity choice", async () => {+ mockSearch.value = "source=notion&applicationId=app-notion&new=1&reconnect=conn-archived&identity=organization";+ listGalleryMock.mockResolvedValueOnce({ apps: [NOTION] });+ listApplicationsMock.mockResolvedValueOnce({+ applications: [{+ id: "app-notion",+ status: "archived",+ metadata: { sourceTemplateKey: "notion" },+ }],+ });+ listConnectionsMock.mockResolvedValueOnce({+ connections: [{+ id: "conn-archived",+ applicationId: "app-notion",+ authKind: "oauth",+ credentialPolicy: "shared",+ status: "archived",+ config: { sourceTemplateKey: "notion" },+ transportConfig: {},+ }],+ });+ connectAppMock.mockResolvedValueOnce({+ connectionId: "conn-archived",+ application: { id: "app-notion", name: "Notion" },+ connection: {+ id: "conn-archived",+ credentialPolicy: "shared",+ status: "draft",+ },+ actions: { readOnly: [], canMakeChanges: [] },+ catalog: [],+ suggestedDefaults: {},+ auth: { kind: "oauth", startUrl: null },+ });+ startOAuthMock.mockResolvedValueOnce({+ connectionId: "conn-archived",+ provider: "notion",+ authorizationUrl: "https://mcp.notion.com/authorize?state=revived",+ expiresAt: "2099-01-01T00:00:00.000Z",+ });++ await render();+ expect(container.textContent).toContain("Everyone in the company");+ await passAccessStep();+ await submitCuratedOAuthSetup();++ expect(connectAppMock).toHaveBeenCalledWith("company-1", expect.objectContaining({+ galleryKey: "notion",+ applicationId: "app-notion",+ }));+ expect(connectAppMock.mock.calls[0]?.[1]).not.toHaveProperty("grantKind");+ expect(startOAuthMock).toHaveBeenCalledWith("conn-archived", {+ asCurrentUser: false,+ });+ });++ it("offers recovery when provider details fail during an exact retained reconnect", async () => {+ mockSearch.value = "source=notion&applicationId=app-notion&new=1&reconnect=conn-archived&identity=organization";+ listGalleryMock.mockRejectedValueOnce(new Error("Gallery unavailable"));+ listApplicationsMock.mockResolvedValueOnce({+ applications: [{+ id: "app-notion",+ status: "archived",+ metadata: { sourceTemplateKey: "notion" },+ }],+ });+ listConnectionsMock.mockResolvedValueOnce({+ connections: [{+ id: "conn-archived",+ applicationId: "app-notion",+ authKind: "oauth",+ credentialPolicy: "shared",+ status: "archived",+ config: { sourceTemplateKey: "notion" },+ transportConfig: {},+ }],+ });++ await render();++ expect(container.textContent).toContain("Couldn’t load connection setup");+ expect(container.textContent).toContain("The retained connection was not changed");+ expect(container.querySelector('[aria-label="Loading retained connection setup"]')).toBeNull();++ await act(async () => {+ buttonByText("Try again")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushReact();++ expect(listGalleryMock).toHaveBeenCalledTimes(2);+ expect(container.textContent).not.toContain("Couldn’t load connection setup");+ });++ it.each(["connection", "application"] as const)(+ "keeps an exact retained reconnect retryable when the %s lookup fails",+ async (failedLookup) => {+ mockSearch.value = "source=notion&applicationId=app-notion&new=1&reconnect=conn-archived&identity=organization";+ listGalleryMock.mockResolvedValueOnce({ apps: [NOTION] });+ const applications = {+ applications: [{+ id: "app-notion",+ status: "archived",+ metadata: { sourceTemplateKey: "notion" },+ }],+ };+ const connections = {+ connections: [{+ id: "conn-archived",+ applicationId: "app-notion",+ authKind: "oauth",+ credentialPolicy: "shared",+ status: "archived",+ config: { sourceTemplateKey: "notion" },+ transportConfig: {},+ }],+ };+ if (failedLookup === "connection") {+ listConnectionsMock+ .mockRejectedValueOnce(new Error("Connection lookup unavailable"))+ .mockResolvedValueOnce(connections);+ listApplicationsMock.mockResolvedValue(applications);+ } else {+ listApplicationsMock+ .mockRejectedValueOnce(new Error("Application lookup unavailable"))+ .mockResolvedValueOnce(applications);+ listConnectionsMock.mockResolvedValue(connections);+ }++ await render();++ expect(container.textContent).toContain("Couldn’t load connection setup");+ expect(container.textContent).toContain("The retained connection was not changed");+ expect(container.textContent).not.toContain("This connection can’t be reconnected");++ await act(async () => {+ buttonByText("Try again")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushReact();+ await flushReact();++ expect(listConnectionsMock).toHaveBeenCalledTimes(2);+ expect(listApplicationsMock).toHaveBeenCalledTimes(2);+ expect(container.textContent).not.toContain("Couldn’t load connection setup");+ expect(container.textContent).toContain("Connect Notion to Paperclip");+ },+ );+it("creates a fresh Notion OAuth connection when the provider landing requests another", async () => {mockSearch.value = "source=notion&applicationId=app-notion&new=1";listGalleryMock.mockResolvedValueOnce({ apps: [NOTION] });@@ -706,11 +1322,16 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {});await render();+ expect(connectAppMock).not.toHaveBeenCalled();+ await passAccessStep();+ await submitCuratedOAuthSetup();- expect(startOAuthMock).not.toHaveBeenCalledWith("conn-existing");+ expect(startOAuthMock).not.toHaveBeenCalled();expect(connectAppMock).toHaveBeenCalledWith("company-1", {galleryKey: "notion",- name: "Notion",+ connectionMethodKey: "mcp-oauth",+ name: "Notion for the company",+ credentialSource: "paperclip_vault",credentialValues: {},configValues: undefined,applicationId: "app-notion",@@ -753,6 +1374,7 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {id: "conn-refreshed",applicationId: "app-notion",authKind: "oauth",+ credentialPolicy: "per_user",status: "draft",config: { sourceTemplateKey: "notion" },transportConfig: {},@@ -762,7 +1384,13 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {await flushReact();expect(connectAppMock).not.toHaveBeenCalled();- expect(startOAuthMock).toHaveBeenCalledWith("conn-refreshed");+ expect(startOAuthMock).not.toHaveBeenCalled();+ expect(container.textContent).toContain("Reconnect keeps this identity type");+ await passAccessStep();+ await submitCuratedOAuthSetup();+ expect(startOAuthMock).toHaveBeenCalledWith("conn-refreshed", {+ asCurrentUser: true,+ });});it("resumes Notion OAuth after a failed connection lookup is retried", async () => {@@ -784,6 +1412,7 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {id: "conn-after-retry",applicationId: "app-notion",authKind: "oauth",+ credentialPolicy: "per_user",status: "draft",config: { sourceTemplateKey: "notion" },transportConfig: {},@@ -800,7 +1429,13 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {await flushReact();expect(connectAppMock).not.toHaveBeenCalled();- expect(startOAuthMock).toHaveBeenCalledWith("conn-after-retry");+ expect(startOAuthMock).not.toHaveBeenCalled();+ expect(container.textContent).toContain("Reconnect keeps this identity type");+ await passAccessStep();+ await submitCuratedOAuthSetup();+ expect(startOAuthMock).toHaveBeenCalledWith("conn-after-retry", {+ asCurrentUser: true,+ });expect(navigateTopLevelMock).toHaveBeenCalledWith("https://mcp.notion.com/authorize?state=resumed",);@@ -812,6 +1447,7 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {listApplicationsMock.mockRejectedValue(new Error("Lookup unavailable"));await render();+ await passAccessStep();await act(async () => {buttonByText("Try again")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));@@ -831,7 +1467,7 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {connectAppMock.mockResolvedValueOnce({connectionId: "conn-prepared",application: { id: "app-notion", name: "Notion" },- connection: { id: "conn-prepared" },+ connection: { id: "conn-prepared", credentialPolicy: "per_user", status: "draft" },actions: { readOnly: [], canMakeChanges: [] },catalog: [],suggestedDefaults: {},@@ -847,6 +1483,8 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {});await render();+ await passAccessStep();+ await submitCuratedOAuthSetup();expect(container.textContent).toContain("Provider unavailable");await act(async () => {@@ -856,7 +1494,9 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {expect(connectAppMock).toHaveBeenCalledTimes(1);expect(startOAuthMock).toHaveBeenCalledTimes(2);- expect(startOAuthMock).toHaveBeenLastCalledWith("conn-prepared");+ expect(startOAuthMock).toHaveBeenLastCalledWith("conn-prepared", {+ asCurrentUser: true,+ });expect(navigateTopLevelMock).toHaveBeenCalledWith("https://mcp.notion.com/authorize?state=retry",);@@ -881,6 +1521,7 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {id: "conn-response-lost",applicationId: "app-response-lost",authKind: "oauth",+ credentialPolicy: "per_user",status: "draft",config: { sourceTemplateKey: "notion" },transportConfig: {},@@ -895,6 +1536,8 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {});await render();+ await passAccessStep();+ await submitCuratedOAuthSetup();expect(container.textContent).toContain("Response lost");await act(async () => {@@ -904,13 +1547,15 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {await flushReact();expect(connectAppMock).toHaveBeenCalledTimes(1);- expect(startOAuthMock).toHaveBeenCalledWith("conn-response-lost");+ expect(startOAuthMock).toHaveBeenCalledWith("conn-response-lost", {+ asCurrentUser: true,+ });expect(navigateTopLevelMock).toHaveBeenCalledWith("https://mcp.notion.com/authorize?state=recovered",);});- it("opens customer-client OAuth apps in branded setup", async () => {+ it("opens customer-owned OAuth apps instead of blocking them by slug", async () => {const slack = CONNECTABLE_APP_DEFINITIONS.find((app) => app.slug === "slack")!;mockParams.appKey = "slack";listGalleryMock.mockResolvedValueOnce({ apps: [slack] });@@ -944,10 +1589,14 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {buttonByText("Check link")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));});await flushReact();+ await flushReact();expect(connectAppMock).toHaveBeenCalledTimes(1);const [, input] = connectAppMock.mock.calls[0];- expect(input).toMatchObject({ link: "https://www.example.com/actions", name: "example.com/actions" });+ expect(input).toMatchObject({+ link: "https://www.example.com/actions",+ name: "example.com/actions for the company",+ });expect(input.credentialValues).toBeUndefined();});@@ -997,6 +1646,8 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {await flushReact();expect(container.textContent).toContain("This looks like Zapier.");+ expect(linkInput?.type).toBe("password");+ expect(linkInput?.autocomplete).toBe("off");await act(async () => {buttonByText("Continue")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));@@ -1004,7 +1655,8 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {await flushReact();expect(container.textContent).toContain("Connect your own MCP server");- expect(container.textContent).toContain(zapierUrl);+ expect(container.textContent).not.toContain(zapierUrl);+ expect(container.textContent).toContain("token=REDACTED");expect(nameInputFrom(container)?.value).toBe("Zapier");expect(container.querySelector('input[type="password"]')).toBeNull();@@ -1014,12 +1666,17 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {await flushReact();expect(connectAppMock).toHaveBeenCalledTimes(1);- expect(connectAppMock.mock.calls[0]?.[1]).toMatchObject({ link: zapierUrl, name: "Zapier" });+ expect(connectAppMock.mock.calls[0]?.[1]).toMatchObject({+ link: zapierUrl,+ name: "Zapier for the company",+ galleryKey: "zapier",+ connectionMethodKey: "generated-url",+ });expect(connectAppMock.mock.calls[0]?.[1].credentialValues).toBeUndefined();});it("keeps Zapier visible and finishes without a separate access or install step", async () => {- mockSearch.value = "byo=1&source=zapier&intent=11111111-1111-4111-8111-111111111111";+ mockSearch.value = "byo=1&source=zapier";listGalleryMock.mockResolvedValueOnce({apps: [{ ...ZAPIER, branding: { ...ZAPIER.branding, logoUrl: "https://example.com/zapier.png" } },@@ -1038,10 +1695,18 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {riskLevel: "read",},],- canMakeChanges: [],+ canMakeChanges: [+ {+ catalogEntryId: "action-2",+ toolName: "create_record",+ title: "Create record",+ description: "Create a record.",+ riskLevel: "write",+ },+ ],},catalog: [],- suggestedDefaults: {},+ suggestedDefaults: { askFirstRiskLevels: [] },});await render();@@ -1057,6 +1722,8 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {const linkInput = container.querySelector<HTMLInputElement>('input[placeholder^="https://mcp.zapier.com"]',);+ expect(linkInput?.type).toBe("password");+ expect(linkInput?.autocomplete).toBe("off");const zapierUrl = "https://mcp.zapier.com/api/v1/connect?token=secret-token";await act(async () => setInputValue(linkInput!, zapierUrl));await flushReact();@@ -1069,25 +1736,22 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {expect(connectAppMock).toHaveBeenCalledTimes(1);expect(connectAppMock.mock.calls[0]?.[1]).toMatchObject({link: zapierUrl,- name: "Zapier",- interactionId: "11111111-1111-4111-8111-111111111111",+ name: "Zapier for the company",+ galleryKey: "zapier",+ connectionMethodKey: "generated-url",});// No grantKind is sent: the pasted-URL path never offered the choice, and// sending "user" without asking would mis-scope the credential.expect(connectAppMock.mock.calls[0]?.[1]).not.toHaveProperty("grantKind");expect(finishAppMock).toHaveBeenCalledWith("company-1", "conn-1", {- enabledCatalogEntryIds: ["action-1"],+ enabledCatalogEntryIds: ["action-1", "action-2"],askFirstCatalogEntryIds: [],access: "all_agents",});expect(putConnectionInstallsMock).toHaveBeenCalledWith("conn-1", [{ targetType: "company", targetId: "company-1" },]);- expect(completeConnectionIntentMock).toHaveBeenCalledWith(- "11111111-1111-4111-8111-111111111111",- "conn-1",- );});// PAP-10922: "Run your own" / "Paste a config" moved from the sidebar to rows@@ -1154,7 +1818,7 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {const [, input] = connectAppMock.mock.calls[0];expect(input).toMatchObject({link: "https://www.example.com/actions",- name: "Bla",+ name: "Bla for the company",applicationId: "app-77",});});@@ -1172,6 +1836,10 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {});await flushReact();await passAccessStep();+ await act(async () => {+ buttonContaining("Share selected sheets")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushReact();expect(container.textContent).toContain("Share each sheet with this email");expect(container.textContent).toContain("[email protected]");@@ -1194,6 +1862,10 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {});await flushReact();await passAccessStep();+ await act(async () => {+ buttonContaining("Share selected sheets")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushReact();const textarea = container.querySelector<HTMLTextAreaElement>("textarea");await act(async () => setTextareaValue(textarea!, "https://example.com/not-a-sheet"));await flushReact();@@ -1218,14 +1890,14 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {await render();await act(async () => {- buttonContaining("Zapier")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ buttonContaining("GitHub")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));});await flushReact();await passAccessStep();- expect(container.textContent).toContain("Connect Zapier");- expect(nameInputFrom(container)?.value).toBe("Zapier");- expect(mockNavigate).toHaveBeenCalledWith("/apps/connect?byo=1&appKey=zapier&stage=setup");+ expect(container.textContent).toContain("Connect GitHub");+ expect(nameInputFrom(container)?.value).toBe("GitHub");+ expect(mockNavigate).toHaveBeenCalledWith("/apps/connect?source=github&stage=setup");});it("keeps the originating connection intent in wizard URLs", async () => {@@ -1234,51 +1906,25 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {await render();await act(async () => {- buttonContaining("Zapier")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ buttonContaining("GitHub")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));});await flushReact();expect(mockNavigate).toHaveBeenCalledWith(- `/apps/connect?byo=1&appKey=zapier&stage=access&intent=${interactionId}`,- );-- await passAccessStep();- expect(mockNavigate).toHaveBeenCalledWith(- `/apps/connect?byo=1&appKey=zapier&stage=setup&intent=${interactionId}`,- );- });-- it("keeps an intent on its requested manual OAuth provider", async () => {- const interactionId = "11111111-1111-4111-8111-111111111111";- mockSearch.value = `byo=1&appKey=asana&intent=${interactionId}`;- listGalleryMock.mockResolvedValueOnce({- apps: [ASANA],- capabilities: {- canSetCompanyInstall: true,- companyInstallReason: null,- },- });-- await render();-- expect(container.textContent).toContain("Who is this credential for?");- expect(mockNavigate).not.toHaveBeenCalledWith(- `/apps/connect?byo=1&intent=${interactionId}`,- { replace: true },+ `/apps/connect?source=github&intent=${interactionId}`,);await passAccessStep();- expect(container.textContent).toContain("Connect Asana");expect(mockNavigate).toHaveBeenCalledWith(- `/apps/connect?byo=1&appKey=asana&stage=setup&intent=${interactionId}`,+ `/apps/connect?source=github&stage=setup&intent=${interactionId}`,);});it("steps back from the key step to Access, and from Access to the BYO gallery", async () => {mockSearch.value = "byo=1";- mockParams.appKey = "zapier";+ mockParams.appKey = "github";await render();await passAccessStep();- expect(container.textContent).toContain("Connect Zapier");+ expect(container.textContent).toContain("Connect GitHub");// Back from the credential goes to Access, not all the way out: the// selections made there have to survive (PAP-17835).@@ -1296,11 +1942,10 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {});it("leaving the default name connects with the app name", async () => {- listGalleryMock.mockResolvedValueOnce({ apps: [MEM0] });await render();await act(async () => {- buttonContaining("Mem0")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ buttonContaining("GitHub")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));});await flushReact();await passAccessStep();@@ -1314,22 +1959,62 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {await flushReact();expect(connectAppMock).toHaveBeenCalledTimes(1);- expect(mockNavigate).toHaveBeenCalledWith("/apps/connect?byo=1&appKey=mem0&stage=access");+ expect(mockNavigate).toHaveBeenCalledWith("/apps/connect?source=github");const [, input] = connectAppMock.mock.calls[0];- expect(input).toMatchObject({ galleryKey: "mem0", name: "Mem0" });+ expect(input).toMatchObject({ galleryKey: "github", name: "GitHub for the company" });+ });++ it("continues an exact credential-based draft instead of creating a replacement", async () => {+ const connectionId = "33333333-3333-4333-8333-333333333333";+ mockSearch.value = `source=github&resume=${connectionId}`;+ listGalleryMock.mockResolvedValueOnce({ apps: [GITHUB] });+ listApplicationsMock.mockResolvedValueOnce({+ applications: [{ id: "app-github", status: "active", metadata: { sourceTemplateKey: "github" } }],+ });+ listConnectionsMock.mockResolvedValueOnce({+ connections: [{+ id: connectionId,+ applicationId: "app-github",+ name: "Engineering GitHub for the company",+ authKind: "api_key",+ credentialPolicy: "shared",+ status: "draft",+ config: { sourceTemplateKey: "github", connectionMethodKey: "mcp-key" },+ transportConfig: {},+ }],+ });++ await render();+ await passAccessStep();+ expect(nameInputFrom(container)?.value).toBe("Engineering GitHub for the company");+ const keyField = container.querySelector<HTMLInputElement>("input[type=password]");+ await act(async () => setInputValue(keyField!, "replacement-key"));+ await flushReact();+ await act(async () => {+ buttonByText("Connect")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushReact();++ expect(connectAppMock).toHaveBeenCalledTimes(1);+ expect(connectAppMock.mock.calls[0]?.[1]).toMatchObject({+ galleryKey: "github",+ connectionMethodKey: "mcp-key",+ resumeConnectionId: connectionId,+ name: "Engineering GitHub for the company",+ credentialValues: { "credentials.authorization": "replacement-key" },+ });});it("a custom name in the gallery step is sent to the connect mutation", async () => {- listGalleryMock.mockResolvedValueOnce({ apps: [MEM0] });await render();await act(async () => {- buttonContaining("Mem0")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ buttonContaining("GitHub")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));});await flushReact();await passAccessStep();- await act(async () => setInputValue(nameInputFrom(container)!, "Mem0 (stdio smoke)"));+ await act(async () => setInputValue(nameInputFrom(container)!, "GitHub (stdio smoke)"));const keyField = container.querySelector<HTMLInputElement>("input[type=password]");await act(async () => setInputValue(keyField!, "secret-key"));await flushReact();@@ -1340,7 +2025,10 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {expect(connectAppMock).toHaveBeenCalledTimes(1);const [, input] = connectAppMock.mock.calls[0];- expect(input).toMatchObject({ galleryKey: "mem0", name: "Mem0 (stdio smoke)" });+ expect(input).toMatchObject({+ galleryKey: "github",+ name: "GitHub (stdio smoke) for the company",+ });});it("a custom name on the Google Sheets step is sent to the connect mutation", async () => {@@ -1356,6 +2044,10 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {});await flushReact();await passAccessStep();+ await act(async () => {+ buttonContaining("Share selected sheets")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushReact();// Default is the app name.expect(nameInputFrom(container)?.value).toBe("Google Sheets");@@ -1374,7 +2066,7 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {const [, input] = connectAppMock.mock.calls[0];expect(input).toMatchObject({galleryKey: "google-sheets",- name: "Google Sheets (stdio smoke)",+ name: "Google Sheets (stdio smoke) for the company",configValues: { allowedSpreadsheetIds: ["sheet_123"] },});});@@ -1392,6 +2084,10 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {});await flushReact();await passAccessStep();+ await act(async () => {+ buttonContaining("Share selected sheets")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+ await flushReact();const textarea = container.querySelector<HTMLTextAreaElement>("textarea");await act(async () =>setTextareaValue(@@ -1543,7 +2239,7 @@ describe("AppsConnect — guided generic MCP flow (PAP-17087)", () => {}],},catalog: [],- suggestedDefaults: { askFirstRiskLevels: ["write", "destructive"] },+ suggestedDefaults: { askFirstRiskLevels: [] },});await act(async () => {buttonByText("Check link")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));@@ -1693,6 +2389,7 @@ describe("AppsConnect — guided generic MCP flow (PAP-17087)", () => {connectAppMock.mockResolvedValue({connectionId: "conn-1",application: { id: "app-1", name: "mcp.example.test" },+ connection: { id: "conn-1", credentialPolicy: "shared", status: "draft" },actions: { readOnly: [], canMakeChanges: [] },catalog: [],suggestedDefaults: {},@@ -1717,6 +2414,7 @@ describe("AppsConnect — guided generic MCP flow (PAP-17087)", () => {connectAppMock.mockResolvedValue({connectionId: "conn-1",application: { id: "app-1", name: "mcp.example.test" },+ connection: { id: "conn-1", credentialPolicy: "shared", status: "draft" },actions: { readOnly: [], canMakeChanges: [] },catalog: [],suggestedDefaults: {},@@ -1736,7 +2434,9 @@ describe("AppsConnect — guided generic MCP flow (PAP-17087)", () => {await flushReact();await flushReact();- expect(startOAuthMock).toHaveBeenCalledWith("conn-1");+ expect(startOAuthMock).toHaveBeenCalledWith("conn-1", {+ asCurrentUser: false,+ });expect(navigateTopLevelMock).not.toHaveBeenCalled();expect(container.textContent).toContain("couldn’t connect");expect(container.textContent).not.toContain(authorizationUrl);diff --git a/ui/src/pages/apps/AppsConnect.tsx b/ui/src/pages/apps/AppsConnect.tsxindex dba0424d63..1e25e76b7d 100644--- a/ui/src/pages/apps/AppsConnect.tsx+++ b/ui/src/pages/apps/AppsConnect.tsx@@ -1,2461 +1,29 @@-import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { useMutation, useQuery } from "@tanstack/react-query";-import {- ArrowUpRight,- Check,- ChevronDown,- ChevronRight,- Copy,- ClipboardPaste,- Link2,- Loader2,- Lock,- Search,- TerminalSquare,-} from "lucide-react";-import type { LucideIcon } from "lucide-react";-import type {- Agent,- AppDefinition,- ConnectionGrantKind,- ConnectionMethodDef,- ConnectToolAppResult,- FieldDef,- ToolApplication,- ToolConnection,- ToolConnectionAuthKind,- ToolConnectionCreateCapabilities,-} from "@paperclipai/shared";-import {- connectionMethodAcceptsCustomerOAuthClient,- connectionMethodSupportsAutomaticOAuth,- credentialConfigPath,- getAppDefinitionForUrl,- getAvailableConnectionMethod,- getAvailableConnectionMethods,-} from "@paperclipai/shared";-import { useNavigate, useParams, useSearchParams } from "@/lib/router";-import { useCompany } from "@/context/CompanyContext";-import { useBreadcrumbs } from "@/context/BreadcrumbContext";-import { useToast } from "@/context/ToastContext";-import { queryKeys } from "@/lib/queryKeys";-import { RadioCardGroup } from "@/components/ui/radio-card";-import { ApiError } from "@/api/client";-import { connectionIntentsApi } from "@/api/connection-intents";-import { toolsApi } from "@/api/tools";-import { agentsApi } from "@/api/agents";-import { appCopyFor, credentialFieldLabel } from "@/lib/app-gallery-copy";-import { advancedTabHref } from "@/pages/tools/tool-tabs";-import { AgentIcon } from "@/components/AgentIconPicker";-import { AgentMultiSelect } from "@/components/AgentMultiSelect";-import { InlineBanner } from "@/components/InlineBanner";-import { Button } from "@/components/ui/button";-import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";-import { Input } from "@/components/ui/input";-import { Textarea } from "@/components/ui/textarea";-import { ToggleSwitch } from "@/components/ui/toggle-switch";-import { Skeleton } from "@/components/ui/skeleton";-import { cn } from "@/lib/utils";-import { copyTextToClipboard } from "@/lib/clipboard";-import { resolveAuthorizationTarget } from "@/lib/authorizationUrl";-import { navigateTopLevel } from "@/lib/browserNavigation";-import { AppLogo } from "./AppLogo";-import { UnverifiedServerBadge } from "./UnverifiedServerBadge";-import { appSourceConnectHref, isMcpDirectOAuthConnectSlug } from "./app-connect-policy";-import { parseGoogleSheetIds } from "./google-sheets";-import {- canSubmitGenericConnect,- customHeaderError,- defaultGenericMcpName,- endpointHost,- genericConnectGuidance,- genericConnectPayload,- newCustomHeaderRow,- type CustomHeaderRow,- type GenericConnectDraft,- type GenericConnectGuidance,- type GenericMcpAuthMode,-} from "./generic-mcp-connect";-import { autoExtendNotice, INSTALL_ALL_WARNING, installInfoNotice, installPayload } from "@/lib/tool-installs";--type Step = "gallery" | "access" | "key" | "success";-export type OAuthConnectPhase = "entry" | "starting" | "redirecting" | "error";--const ROUTE_STAGE_BY_STEP: Partial<Record<Step, string>> = {- access: "access",- key: "setup",- success: "complete",-};--function appConnectHref(appKey: string, step: Step, interactionId?: string | null): string {- const stage = ROUTE_STAGE_BY_STEP[step] ?? "setup";- const params = new URLSearchParams({ byo: "1", appKey, stage });- if (interactionId) params.set("intent", interactionId);- return `/apps/connect?${params.toString()}`;-}--function appsConnectGalleryHref(byoOnly: boolean, interactionId?: string | null): string {- const path = byoOnly ? "/apps/byo" : "/apps/connect";- const params = new URLSearchParams();- if (!byoOnly) params.set("byo", "1");- if (interactionId) params.set("intent", interactionId);- const query = params.toString();- return query ? `${path}?${query}` : path;-}--type AppAccessSelection = "all_agents" | { agentIds: string[] };--// Access comes before credentials so the reader knows what identity and reach-// the secret is about to get before they share it (PAP-17835).-const STEP_LABELS = ["Pick app", "Access", "Add your key"];-const STEP_INDEX: Record<Exclude<Step, "success">, number> = {- gallery: 0,- access: 1,- key: 2,-};-const ZAPIER_STEP_INDEX: Record<Exclude<Step, "gallery" | "success">, number> = {- key: 0,- access: 1,-};-const ZAPIER_STEP_LABELS = ["Add MCP URL"];--/**- * Which identity a fresh connection should default to (PAP-17835).- *- * An identity-bearing OAuth app (Gmail, Notion) is almost always personal — the- * whole point is that the agent acts as you. A service credential like an API- * key is almost always shared. Defaulting per auth kind keeps the common path a- * single Continue click without ever guessing silently: the choice is on screen.- */-function defaultGrantKindFor(- entry: AppDefinition | null,- method: ConnectionMethodDef | null,-): ConnectionGrantKind {- if (method?.grantKinds?.length === 1) return method.grantKinds[0]!;- const auth = method?.auth ?? (entry ? getAvailableConnectionMethod(entry)?.auth : null);- return auth === "oauth" ? "user" : "organization";-}--function isGoogleSheetsEntry(entry: AppDefinition | null): boolean {- return entry?.slug === "google-sheets";-}--function defaultMethodConfig(method: ConnectionMethodDef | null): Record<string, string | boolean> {- if (!method) return {};- return Object.fromEntries(- [...(method.tenantFields ?? []), ...(method.extensionFields ?? [])]- .filter((field) => field.defaultValue !== undefined)- .map((field) => [field.key, field.defaultValue!]),- );-}--function appSourceSlug(application: ToolApplication): string | null {- const metadata = application.metadata;- if (!metadata) return null;- const source = metadata.sourceTemplateKey ?? metadata.galleryKey;- return typeof source === "string" ? source : null;-}--function connectionSourceSlug(connection: ToolConnection): string | null {- const source = connection.config?.sourceTemplateKey ?? connection.transportConfig.sourceTemplateKey;- return typeof source === "string" ? source : null;-}--function reusableOAuthConnection(- sourceSlug: string | null,- applications: ToolApplication[],- connections: ToolConnection[],- options: { applicationId?: string; draftOnly?: boolean } = {},-): ToolConnection | null {- if (!sourceSlug) return null;- const matchingApplicationIds = new Set(- applications- .filter((application) =>- application.status !== "archived" &&- appSourceSlug(application) === sourceSlug &&- (!options.applicationId || application.id === options.applicationId)- )- .map((application) => application.id),- );- return connections.find((connection) => {- const matchesApplication = options.applicationId- ? connection.applicationId === options.applicationId- : matchingApplicationIds.has(connection.applicationId) || connectionSourceSlug(connection) === sourceSlug;- return connection.status !== "archived" &&- (!options.draftOnly || connection.status === "draft") &&- connection.authKind === "oauth" &&- matchesApplication;- }) ?? null;-}--export function AppsConnect({ byoOnly = false }: { byoOnly?: boolean } = {}) {- const navigate = useNavigate();- const routeParams = useParams<{ appKey?: string }>();- const { selectedCompany, selectedCompanyId } = useCompany();- const { setBreadcrumbs } = useBreadcrumbs();- const { pushToast } = useToast();- const [searchParams] = useSearchParams();- const appKey = routeParams.appKey ?? searchParams.get("appKey") ?? undefined;- const sourceSlug = searchParams.get("source")?.trim() || null;- // The wizard rewrites its own URL while moving between steps, so retain the- // originating request for the full setup instead of rereading the query.- const [connectionIntentId] = useState(() => searchParams.get("intent")?.trim() || null);- const createNewConnection = searchParams.get("new") === "1";- const directOAuthSource = isMcpDirectOAuthConnectSlug(sourceSlug) ? sourceSlug : null;- const requestedAppKey = appKey ?? directOAuthSource ?? undefined;- const zapierSource = sourceSlug === "zapier";- const byo = byoOnly || searchParams.get("byo") === "1";-- // Prefill arrives from the app page for reconnects; read once so later- // wizard navigation doesn't fight the URL.- const [prefill] = useState(() => {- const rawLink = searchParams.get("link")?.trim() ?? "";- return {- link: /^https?:\/\//i.test(rawLink) ? rawLink : "",- name: searchParams.get("name")?.trim() ?? "",- applicationId: searchParams.get("applicationId")?.trim() || undefined,- };- });-- const [step, setStep] = useState<Step>(requestedAppKey || prefill.link || zapierSource ? "key" : "gallery");- const [entry, setEntry] = useState<AppDefinition | null>(null);- const [galleryName, setGalleryName] = useState("");- const [linkUrl, setLinkUrl] = useState(prefill.link);- const [linkName, setLinkName] = useState(prefill.name || (zapierSource ? "Zapier" : ""));- const [linkNeedsKey, setLinkNeedsKey] = useState(false);- const [linkKey, setLinkKey] = useState("");- // Generic ("connect your own MCP server") flow state. `authMode: auto` is the- // simple path: Paperclip probes the endpoint and branches on what it finds.- const [linkAuthMode, setLinkAuthMode] = useState<GenericMcpAuthMode>("auto");- const [linkHeaders, setLinkHeaders] = useState<CustomHeaderRow[]>(() => [newCustomHeaderRow()]);- const [linkOAuthClientId, setLinkOAuthClientId] = useState("");- const [linkOAuthClientSecret, setLinkOAuthClientSecret] = useState("");- const [linkAdvancedOpen, setLinkAdvancedOpen] = useState(false);- const [linkGuidance, setLinkGuidance] = useState<GenericConnectGuidance | null>(null);- const [genericOAuthPending, setGenericOAuthPending] = useState(false);- const [credentials, setCredentials] = useState<Record<string, string>>({});- const [connectionMethodKey, setConnectionMethodKey] = useState("");- const [configValues, setConfigValues] = useState<Record<string, string | boolean>>({});- const [googleSheetsLinks, setGoogleSheetsLinks] = useState("");- const [googleSheetsError, setGoogleSheetsError] = useState<string | null>(null);- const [connectResult, setConnectResult] = useState<ConnectToolAppResult | null>(null);- const [enabled, setEnabled] = useState<Record<string, boolean>>({});- const [access, setAccess] = useState<"all" | "specific">("all");- const [agentIds, setAgentIds] = useState<Set<string>>(new Set());- const [installAgentIds, setInstallAgentIds] = useState<Set<string>>(new Set());- /**- * Access-step selections (PAP-17835). These are chosen before the credential- * and committed with it, so they must survive a failed submit and a trip- * backwards through the wizard.- */- const [grantKind, setGrantKind] = useState<ConnectionGrantKind>("organization");- const [installChoice, setInstallChoice] = useState<"specific" | "all">("all");- const [oauthPhase, setOAuthPhase] = useState<OAuthConnectPhase>("entry");- const [oauthError, setOAuthError] = useState<string | null>(null);- /** Host of the page the operator is about to be sent to, shown while redirecting. */- const [authorizationHost, setAuthorizationHost] = useState<string | null>(null);- const directOAuthStartedRef = useRef(false);- const directOAuthRetryingRef = useRef(false);-- const resetGenericAuthState = () => {- setLinkAuthMode("auto");- setLinkHeaders([newCustomHeaderRow()]);- setLinkOAuthClientId("");- setLinkOAuthClientSecret("");- setLinkAdvancedOpen(false);- setLinkGuidance(null);- setGenericOAuthPending(false);- };-- /**- * Switch to a curated app's branded setup. Reached from the gallery grid and, as- * a convenience, from the guided generic flow when the pasted endpoint matches a- * definition — the generic path stays available either way.- */- const useMatchedGalleryEntry = (picked: AppDefinition) => {- if (- getAvailableConnectionMethod(picked)?.auth === "oauth" &&- isMcpDirectOAuthConnectSlug(picked.slug)- ) {- navigate(appSourceConnectHref(picked.slug, connectionIntentId));- return;- }- setEntry(picked);- setGalleryName(picked.name);- setLinkUrl("");- setLinkName("");- setLinkNeedsKey(false);- setLinkKey("");- resetGenericAuthState();- setCredentials({});- const methods = getAvailableConnectionMethods(picked);- const initialMethod = methods.length === 1 ? methods[0]! : null;- setConnectionMethodKey(initialMethod?.key ?? "");- setConfigValues(defaultMethodConfig(initialMethod));- setGoogleSheetsLinks("");- setGoogleSheetsError(null);- setConnectResult(null);- setInstallAgentIds(new Set());- setInstallChoice("specific");- setGrantKind(defaultGrantKindFor(picked, initialMethod));- setStep("access");- navigate(appConnectHref(picked.slug, "access", connectionIntentId));- };-- const openGallery = () => {- setEntry(null);- setGalleryName("");- setLinkUrl("");- setLinkName("");- setLinkNeedsKey(false);- setLinkKey("");- resetGenericAuthState();- setCredentials({});- setConnectionMethodKey("");- setConfigValues({});- setGoogleSheetsLinks("");- setGoogleSheetsError(null);- setConnectResult(null);- setInstallAgentIds(new Set());- setInstallChoice("all");- setGrantKind("organization");- setStep("gallery");- navigate(appsConnectGalleryHref(byoOnly, connectionIntentId));- };-- useEffect(() => {- setBreadcrumbs([- { label: selectedCompany?.name ?? "Organization", href: "/dashboard" },- { label: "Apps", href: "/apps" },- { label: byoOnly ? "Connect your own tool" : "Connect an app" },- ]);- return () => setBreadcrumbs([]);- }, [byoOnly, setBreadcrumbs, selectedCompany?.name]);-- const galleryQuery = useQuery({- queryKey: queryKeys.apps.gallery(selectedCompanyId ?? "__none__"),- queryFn: () => toolsApi.listGallery(selectedCompanyId!),- enabled: !!selectedCompanyId,- });- const applicationsQuery = useQuery({- queryKey: queryKeys.tools.applications(selectedCompanyId ?? "__none__"),- queryFn: () => toolsApi.listApplications(selectedCompanyId!),- enabled: !!selectedCompanyId && !!directOAuthSource,- refetchOnMount: "always",- });- const connectionsQuery = useQuery({- queryKey: queryKeys.tools.connections(selectedCompanyId ?? "__none__"),- queryFn: () => toolsApi.listConnections(selectedCompanyId!),- enabled: !!selectedCompanyId && !!directOAuthSource,- refetchOnMount: "always",- });- const existingOAuthConnection = useMemo(- () => reusableOAuthConnection(- directOAuthSource,- applicationsQuery.data?.applications ?? [],- connectionsQuery.data?.connections ?? [],- createNewConnection- ? { applicationId: prefill.applicationId, draftOnly: true }- : {},- ),- [applicationsQuery.data, connectionsQuery.data, createNewConnection, directOAuthSource, prefill.applicationId],- );-- // A curated definition covering the pasted endpoint is offered as a branded- // convenience only; the generic flow remains the default and stays complete.- const linkMatchedEntry = useMemo(- () => (linkUrl && !entry ? getAppDefinitionForUrl(linkUrl, galleryQuery.data?.apps ?? []) : null),- [entry, galleryQuery.data, linkUrl],- );-- const directOAuthEntry = entry &&- getAvailableConnectionMethod(entry)?.auth === "oauth" &&- isMcpDirectOAuthConnectSlug(entry.slug)- ? entry- : null;-- const setAppStep = (nextStep: Step) => {- setStep(nextStep);- if (entry) navigate(appConnectHref(entry.slug, nextStep, connectionIntentId));- };-- const oauthStartMutation = useMutation({- mutationFn: ({ connectionId, interactionId }: { connectionId: string; interactionId?: string }) =>- toolsApi.startOAuth(connectionId, interactionId),- onSuccess: ({ authorizationUrl }) => {- // The endpoint chose this address, so it is checked here too — this is the- // line where an unsafe scheme would actually run (PAP-17099).- const target = resolveAuthorizationTarget(authorizationUrl);- if (!target.ok) {- setOAuthPhase("error");- setOAuthError(target.message);- return;- }- setAuthorizationHost(target.host);- setOAuthPhase("redirecting");- navigateTopLevel(target.url);- },- onError: (error) => {- const details = error instanceof ApiError && error.body && typeof error.body === "object"- ? (error.body as { details?: { code?: unknown } }).details- : null;- setOAuthPhase("error");- setOAuthError(- details?.code === "invalid_grant"- ? "Your authorization expired or was revoked. Reconnect to continue."- : error instanceof Error- ? error.message- : "Paperclip couldn’t start secure sign-in. Try again.",- );- },- });- const startOAuthMutation = oauthStartMutation.mutate;- const startOAuth = useCallback((connectionId: string, interactionId = connectionIntentId ?? undefined) => {- startOAuthMutation({ connectionId, interactionId });- }, [connectionIntentId, startOAuthMutation]);-- /**- * Commit the Access step's agent reach for a connection. Shared by the- * key-path finish and the OAuth redirect, so both routes through the wizard- * apply the same selection.- */- const applyAccessInstalls = async (connectionId: string) => {- const installState = installChoice === "all"- ? { onAll: true, agentIds: new Set<string>() }- : { onAll: false, agentIds: installAgentIds };- await toolsApi.putConnectionInstalls(connectionId, installPayload(selectedCompanyId!, installState));- };-- const connectMutation = useMutation({- mutationFn: (entryOverride?: AppDefinition) => {- const connectEntry = entryOverride ?? entry;- if (connectEntry) {- const sheetIds = isGoogleSheetsEntry(connectEntry) ? parseGoogleSheetIds(googleSheetsLinks).ids : [];- const trimmedGalleryName = galleryName.trim();- return toolsApi.connectApp(selectedCompanyId!, {- galleryKey: connectEntry.slug,- ...(connectionMethodKey ? { connectionMethodKey } : {}),- name: trimmedGalleryName || connectEntry.name,- credentialValues: credentials,- configValues: isGoogleSheetsEntry(connectEntry)- ? { allowedSpreadsheetIds: sheetIds }- : Object.keys(configValues).length > 0- ? configValues- : undefined,- applicationId: prefill.applicationId,- ...(connectionIntentId ? { interactionId: connectionIntentId } : {}),- ...(grantKind === "user" ? { grantKind } : {}),- });- }- return toolsApi.connectApp(selectedCompanyId!, {- ...genericConnectPayload({- link: linkUrl,- name: linkName,- authMode: linkAuthMode,- needsKey: linkNeedsKey,- keyValue: linkKey,- headers: linkHeaders,- oauthClientId: linkOAuthClientId,- oauthClientSecret: linkOAuthClientSecret,- }),- applicationId: prefill.applicationId,- ...(connectionIntentId ? { interactionId: connectionIntentId } : {}),- ...(grantKind === "user" ? { grantKind } : {}),- });- },- onSuccess: (result) => {- if (result.auth?.kind === "oauth") {- setConnectResult(result);- // The redirect takes the operator out of the wizard, so the Access- // step's agent reach is committed now rather than after the callback.- // Best-effort: a failure here must not block the sign-in they asked for,- // and Permissions still shows the real state when they land.- void applyAccessInstalls(result.connectionId);- // Discovery worked but this authorization server insists on a client the- // operator registers themselves. Keep the draft and ask for it in place- // rather than sending them back to the start.- if (result.auth.manualClientRequired) {- setLinkGuidance(genericConnectGuidance("oauth_manual_client_required", null));- setLinkAuthMode("oauth");- setLinkAdvancedOpen(true);- setGenericOAuthPending(false);- return;- }- const startUrl = result.auth.startUrl?.trim();- if (!startUrl) {- setOAuthPhase("starting");- setGenericOAuthPending(true);- startOAuth(result.connectionId);- return;- }- const target = resolveAuthorizationTarget(startUrl);- if (!target.ok) {- setGenericOAuthPending(true);- setOAuthPhase("error");- setOAuthError(target.message);- return;- }- setAuthorizationHost(target.host);- setOAuthPhase("redirecting");- setGenericOAuthPending(true);- navigateTopLevel(target.url);- return;- }- setLinkGuidance(null);- setConnectResult(result);- const defaults: Record<string, boolean> = {};- for (const a of result.actions.readOnly) defaults[a.catalogEntryId] = true;- for (const a of result.actions.canMakeChanges) defaults[a.catalogEntryId] = true;- setEnabled(defaults);- finishMutation.mutate({ result, enabled: defaults });- },- onError: (error) => {- const details = error instanceof ApiError && error.body && typeof error.body === "object"- ? (error.body as { details?: { code?: unknown } }).details- : null;- if (isMcpDirectOAuthConnectSlug(requestedAppKey)) {- setOAuthPhase("error");- setOAuthError(- details?.code === "invalid_grant"- ? "Your authorization expired or was revoked. Reconnect to continue."- : error instanceof Error- ? error.message- : "Paperclip couldn’t start secure sign-in. Try again.",- );- return;- }- // The generic URL path explains the specific corrective action inline,- // beside the fields the operator has to change. A toast can't do that, and- // for a pasted address "check your key" is usually the wrong advice.- if (!entry && linkUrl) {- const code = typeof details?.code === "string" ? details.code : null;- const guidance = genericConnectGuidance(code, error instanceof Error ? error.message : null);- setLinkGuidance(guidance);- setGenericOAuthPending(false);- if (guidance.focus === "credentials") setLinkAdvancedOpen(true);- return;- }- pushToast({- title: "Couldn’t connect",- body: error instanceof Error ? error.message : "Please check your key and try again.",- tone: "error",- });- },- });- const connectApp = connectMutation.mutate;-- useEffect(() => {- if (!requestedAppKey || galleryQuery.isLoading || !galleryQuery.data) return;-- const requestedEntry = galleryQuery.data.apps.find((candidate) => candidate.slug === requestedAppKey);- const method = requestedEntry ? getAvailableConnectionMethod(requestedEntry) : null;- const methods = requestedEntry ? getAvailableConnectionMethods(requestedEntry) : [];- const directOAuth = method?.auth === "oauth" && isMcpDirectOAuthConnectSlug(requestedEntry?.slug);- const unsupportedOAuth = methods.length === 1- && method?.auth === "oauth"- && !connectionMethodSupportsAutomaticOAuth(method)- && !connectionMethodAcceptsCustomerOAuthClient(method);- if (!requestedEntry || unsupportedOAuth || requestedEntry.availability?.available === false) {- setEntry(null);- setStep("gallery");- navigate(- connectionIntentId ? appsConnectGalleryHref(false, connectionIntentId) : "/apps/connect",- { replace: true },- );- return;- }-- if (entry?.slug !== requestedEntry.slug) {- setEntry(requestedEntry);- setGalleryName(requestedEntry.name);- setLinkUrl("");- setLinkName("");- setLinkNeedsKey(false);- setLinkKey("");- setCredentials({});- const methods = getAvailableConnectionMethods(requestedEntry);- const initialMethod = methods.length === 1 ? methods[0]! : null;- setConnectionMethodKey(initialMethod?.key ?? "");- setConfigValues(defaultMethodConfig(initialMethod));- setGoogleSheetsLinks("");- setGoogleSheetsError(null);- setConnectResult(null);- setGrantKind(defaultGrantKindFor(requestedEntry, initialMethod));- if (!directOAuth) setInstallChoice("specific");- }- // A direct-OAuth deep link is an express reconnect: it redirects on arrival,- // so there is no credential entry for an Access step to precede.- setStep(directOAuth ? "key" : "access");-- if (directOAuth && (- !applicationsQuery.isFetchedAfterMount ||- !connectionsQuery.isFetchedAfterMount- )) return;- if (directOAuth && directOAuthRetryingRef.current) return;- if (directOAuth && (applicationsQuery.isError || connectionsQuery.isError)) {- setOAuthPhase("error");- setOAuthError("Paperclip couldn’t check for an existing connection. Try again.");- return;- }-- if (directOAuth && !directOAuthStartedRef.current) {- directOAuthStartedRef.current = true;- setOAuthError(null);- setOAuthPhase("starting");- if (existingOAuthConnection) {- startOAuth(existingOAuthConnection.id, connectionIntentId ?? undefined);- } else {- connectApp(requestedEntry);- }- }- }, [- applicationsQuery.isError,- applicationsQuery.isFetchedAfterMount,- connectApp,- connectionsQuery.isError,- connectionsQuery.isFetchedAfterMount,- connectionIntentId,- entry?.slug,- existingOAuthConnection,- galleryQuery.data,- galleryQuery.isLoading,- navigate,- requestedAppKey,- startOAuth,- ]);-- /**- * Commit the connection: action defaults, agent reach, and installs.- *- * Takes the connect result and the enabled set as arguments rather than- * reading them from state. The Access step removed the separate who/install- * screens, so this now runs in the same tick as the `setConnectResult` /- * `setEnabled` that precede it, where that state has not been applied yet.- */- const finishMutation = useMutation({- mutationFn: async (input: { result: ConnectToolAppResult; enabled: Record<string, boolean> }) => {- const { result: connected, enabled: enabledMap } = input;- const enabledIds = Object.entries(enabledMap)- .filter(([, on]) => on)- .map(([id]) => id);- const askFirstRiskLevels = new Set(- Array.isArray(connected.suggestedDefaults.askFirstRiskLevels)- ? connected.suggestedDefaults.askFirstRiskLevels.filter(- (riskLevel): riskLevel is string => typeof riskLevel === "string",- )- : [],- );- const askFirstIds = connected.actions.canMakeChanges- .filter((action) => enabledMap[action.catalogEntryId] && askFirstRiskLevels.has(action.riskLevel))- .map((action) => action.catalogEntryId);- // The Access step asks one question about agent reach, so profile access- // and installs are committed to the same target set instead of drifting- // apart behind two separate wizard screens.- const selection: AppAccessSelection = installChoice === "all"- ? "all_agents"- : { agentIds: Array.from(installAgentIds) };- const finished = await toolsApi.finishApp(selectedCompanyId!, connected.connectionId, {- enabledCatalogEntryIds: enabledIds,- askFirstCatalogEntryIds: askFirstIds,- access: selection,- });- await applyAccessInstalls(connected.connectionId);- if (connectionIntentId) {- await connectionIntentsApi.complete(connectionIntentId, connected.connectionId);- }- return finished;- },- onSuccess: () => setAppStep("success"),- onError: (error) => {- // Creation must feel transactional: a failed commit returns the operator- // to Access with their identity and agent selections intact rather than- // stranding them on a half-made connection.- setAppStep("access");- pushToast({- title: "Couldn’t finish setup",- body: error instanceof Error ? error.message : "Please try again.",- tone: "error",- });- },- });-- if (!selectedCompanyId) {- return <div className="p-6 text-sm text-muted-foreground">Select an organization to connect apps.</div>;- }-- if (directOAuthEntry && step === "key") {- return (- <OAuthConnectStateScreen- entry={directOAuthEntry}- phase={oauthPhase}- error={oauthError}- authorizationHost={authorizationHost}- onRetry={async () => {- setOAuthError(null);- setOAuthPhase("starting");- const connectionId = connectResult?.connectionId ?? existingOAuthConnection?.id;- if (connectionId) {- startOAuth(connectionId);- return;- }-- // The create request may have reached the server even when its- // response did not reach the browser. Re-read both resources before- // creating again so Retry resumes that durable draft instead of- // duplicating it.- directOAuthRetryingRef.current = true;- try {- const [applicationsResult, connectionsResult] = await Promise.all([- applicationsQuery.refetch(),- connectionsQuery.refetch(),- ]);- if (applicationsResult.isError || connectionsResult.isError) {- setOAuthPhase("error");- setOAuthError("Paperclip couldn’t check for an existing connection. Try again.");- return;- }- const refreshedConnection = reusableOAuthConnection(- directOAuthSource,- applicationsResult.data?.applications ?? [],- connectionsResult.data?.connections ?? [],- createNewConnection- ? { applicationId: prefill.applicationId, draftOnly: true }- : {},- );- if (refreshedConnection) {- startOAuth(refreshedConnection.id);- } else {- connectMutation.mutate(directOAuthEntry);- }- } finally {- directOAuthRetryingRef.current = false;- }- }}- onCancel={() => navigate("/apps/browse")}- />- );- }-- // A pasted endpoint that needs browser sign-in gets the same waiting/retry- // screen a curated OAuth app does, minus the branding it doesn't have.- if (genericOAuthPending && !entry && linkUrl && step === "key") {- return (- <OAuthConnectStateScreen- identity={{- name: linkName.trim() || endpointHost(linkUrl) || "this server",- unverifiedHost: endpointHost(linkUrl),- }}- phase={oauthPhase}- error={oauthError}- authorizationHost={authorizationHost}- onRetry={() => {- setOAuthError(null);- const connectionId = connectResult?.connectionId;- if (connectionId) {- setOAuthPhase("starting");- startOAuth(connectionId);- return;- }- // No draft to resume, so fall back to the setup screen rather than- // creating a second connection for the same endpoint.- setGenericOAuthPending(false);- setOAuthPhase("entry");- }}- onCancel={() => {- setGenericOAuthPending(false);- setOAuthPhase("entry");- setOAuthError(null);- }}- />- );- }-- const appName =- connectResult?.application.name ??- entry?.name ??- (linkName.trim() || defaultGenericMcpName(linkUrl) || "this app");- const zapierEntry = zapierSource- ? galleryQuery.data?.apps.find((app) => app.slug === "zapier") ?? null- : null;- const stepLabels = zapierSource- ? ZAPIER_STEP_LABELS- : entry && getAvailableConnectionMethods(entry).length > 1- ? ["Pick app", "Access", "Choose connection"]- : isGoogleSheetsEntry(entry)- ? ["Pick app", "Access", "Share sheet"]- : STEP_LABELS;- // The Access step's identity question only makes sense when there *is* a- // credential, so it reads the selected method's auth kind.- const accessStepMethod = entry- ? (connectionMethodKey- ? getAvailableConnectionMethods(entry).find((m) => m.key === connectionMethodKey) ?? null- : getAvailableConnectionMethod(entry))- : null;- const accessStepAuthKind: ToolConnectionAuthKind = entry- ? accessStepMethod?.auth ?? "none"- : linkAuthMode === "none"- ? "none"- : linkAuthMode === "oauth"- ? "oauth"- : "api_key";- // The primary label names the next effect, so an OAuth handoff never arrives- // unannounced.- const accessMethodIsKnown = !entry- || Boolean(connectionMethodKey)- || getAvailableConnectionMethods(entry).length === 1;- const accessSubmitLabel = accessStepAuthKind === "oauth" && accessMethodIsKnown- ? `Continue to ${entry?.name ?? "sign-in"}`- : "Save and continue";-- const stepIndex = zapierSource && step !== "gallery" && step !== "success"- ? ZAPIER_STEP_INDEX[step]- : step === "success"- ? stepLabels.length- : STEP_INDEX[step];-- return (- <div className="max-w-5xl">- {step !== "success" && (- !(byoOnly && step === "gallery") && (- <StepHeader- subtitle={- step === "gallery"- ? "Pick the app you want your agents to use."- : `Step ${stepIndex + 1} of ${stepLabels.length}`- }- step={step}- activeIndex={stepIndex}- labels={stepLabels}- appIdentity={- zapierSource- ? { name: "Zapier", logoUrl: zapierEntry?.branding.logoUrl ?? null }- : undefined- }- unverifiedHost={!entry && !zapierSource && step !== "gallery" ? endpointHost(linkUrl) : null}- onCancel={() => navigate("/apps")}- />- )- )}-- {step === "gallery" && (- <GalleryStep- loading={galleryQuery.isLoading}- apps={galleryQuery.data?.apps ?? []}- byo={byo}- byoOnly={byoOnly}- source={searchParams.get("source")}- onPick={useMatchedGalleryEntry}- onUseLink={(url) => {- const matchedEntry = getAppDefinitionForUrl(url, galleryQuery.data?.apps ?? []);- setEntry(null);- setGalleryName("");- setLinkUrl(url);- setLinkName(matchedEntry?.name ?? defaultGenericMcpName(url) ?? "");- setLinkNeedsKey(false);- setLinkKey("");- setCredentials({});- setGoogleSheetsLinks("");- setGoogleSheetsError(null);- setInstallAgentIds(new Set());- setInstallChoice("all");- setGrantKind("organization");- setStep("key");- }}- onRunYourOwn={() => navigate(advancedTabHref("run-your-own"))}- onPasteConfig={() => navigate(advancedTabHref("paste-config"))}- />- )}-- {step === "key" && entry && (- <KeyStep- entry={entry}- name={galleryName}- onNameChange={setGalleryName}- values={credentials}- onChange={setCredentials}- methodKey={connectionMethodKey}- onMethodChange={(nextMethod) => {- setConnectionMethodKey(nextMethod.key);- if (nextMethod.grantKinds?.length === 1) setGrantKind(nextMethod.grantKinds[0]!);- setCredentials({});- setConfigValues(defaultMethodConfig(nextMethod));- }}- configValues={configValues}- onConfigChange={setConfigValues}- googleSheetsLinks={googleSheetsLinks}- googleSheetsError={googleSheetsError}- onGoogleSheetsLinksChange={(next) => {- setGoogleSheetsLinks(next);- setGoogleSheetsError(null);- }}- submitting={connectMutation.isPending}- // Back returns to Access, not to the gallery: the design requires the- // identity and agent selections to survive moving backward, and- // `openGallery` resets them.- onBack={() => setAppStep("access")}- onConnect={() => {- if (isGoogleSheetsEntry(entry)) {- const parsed = parseGoogleSheetIds(googleSheetsLinks);- if (parsed.invalidCount > 0) {- setGoogleSheetsError("That doesn't look like a Google Sheets link.");- return;- }- if (parsed.ids.length === 0) {- setGoogleSheetsError("Paste at least one Google Sheets link.");- return;- }- }- connectMutation.mutate(undefined);- }}- />- )}-- {step === "key" && !entry && linkUrl && !zapierSource && (- <LinkConnectStep- link={linkUrl}- name={linkName}- onNameChange={setLinkName}- needsKey={linkNeedsKey}- onNeedsKeyChange={(next) => {- setLinkNeedsKey(next);- if (!next) setLinkKey("");- }}- keyValue={linkKey}- onKeyChange={setLinkKey}- authMode={linkAuthMode}- onAuthModeChange={(next) => {- setLinkAuthMode(next);- setLinkGuidance(null);- // Leaving the simple path means the explicit choice governs; drop the- // "does it need a key?" answer so the two can't disagree.- if (next !== "auto") setLinkNeedsKey(false);- if (next !== "bearer" && next !== "auto") setLinkKey("");- }}- headers={linkHeaders}- onHeadersChange={(next) => {- setLinkHeaders(next);- setLinkGuidance(null);- }}- oauthClientId={linkOAuthClientId}- onOAuthClientIdChange={setLinkOAuthClientId}- oauthClientSecret={linkOAuthClientSecret}- onOAuthClientSecretChange={setLinkOAuthClientSecret}- advancedOpen={linkAdvancedOpen}- onAdvancedOpenChange={setLinkAdvancedOpen}- guidance={linkGuidance}- matchedEntry={linkMatchedEntry}- onUseMatchedEntry={linkMatchedEntry ? () => useMatchedGalleryEntry(linkMatchedEntry) : undefined}- submitting={connectMutation.isPending || genericOAuthPending}- onBack={() => setStep("gallery")}- onConnect={() => {- setLinkGuidance(null);- connectMutation.mutate(undefined);- }}- />- )}-- {step === "key" && !entry && zapierSource && (- <ZapierConnectStep- link={linkUrl}- onLinkChange={setLinkUrl}- submitting={connectMutation.isPending}- onBack={() => navigate("/apps")}- onConnect={() => connectMutation.mutate(undefined)}- />- )}-- {step === "access" && (- <AccessStep- appName={appName}- providerName={entry?.name ?? appName}- companyId={selectedCompanyId}- authKind={accessStepAuthKind}- grantKinds={accessStepMethod?.grantKinds}- grantKind={grantKind}- setGrantKind={setGrantKind}- installChoice={installChoice}- setInstallChoice={setInstallChoice}- installAgentIds={installAgentIds}- setInstallAgentIds={setInstallAgentIds}- capabilities={galleryQuery.data?.capabilities}- submitLabel={accessSubmitLabel}- // Leaving Access abandons the app choice entirely, so this resets the- // draft and returns to the gallery the operator came from.- onBack={() => (entry || linkUrl ? openGallery() : navigate("/apps"))}- onContinue={() => (entry ? setAppStep("key") : setStep("key"))}- />- )}-- {step === "success" && (- <SuccessStep- appName={appName}- logoUrl={entry?.branding.logoUrl}- summary={accessSummaryLines({- grantKind,- authKind: accessStepAuthKind,- installChoice,- installCount: installAgentIds.size,- enabledCount: Object.values(enabled).filter(Boolean).length,- })}- onDone={() => navigate("/apps/connections")}- />- )}- </div>- );-}--function StepHeader({- subtitle,- step,- activeIndex,- labels,- appIdentity,- unverifiedHost,- onCancel,-}: {- subtitle: string;- step: Step;- activeIndex: number;- labels: string[];- appIdentity?: { name: string; logoUrl: string | null };- /**- * Host of an unknown remote MCP server. Present for the whole generic flow so- * the operator can see whose server they are configuring at every step, not- * just on the screen where they pasted the address.- */- unverifiedHost?: string | null;- onCancel: () => void;-}) {- return (- <div className="mb-6">- <div className="flex items-start justify-between gap-4">- <div className="flex items-center gap-3">- {appIdentity ? (- <AppLogo name={appIdentity.name} logoUrl={appIdentity.logoUrl} size={44} />- ) : null}- <div>- <h1 className="text-2xl font-bold tracking-tight">- {appIdentity ? `Connect ${appIdentity.name}` : "Connect an app"}- </h1>- <p className="mt-1 text-sm text-muted-foreground">{subtitle}</p>- {unverifiedHost ? <UnverifiedServerBadge host={unverifiedHost} className="mt-2" /> : null}- </div>- </div>- <Button variant="ghost" size="sm" onClick={onCancel}>- Cancel- </Button>- </div>- {step !== "gallery" && (- <div className="mt-4">- <div className="flex gap-2">- {labels.map((label, i) => (- <div- key={label}- className={cn("h-1 w-20 rounded-full", i <= activeIndex ? "bg-foreground" : "bg-border")}- />- ))}- </div>- <div className="mt-2 text-xs text-muted-foreground">{labels.join(" · ")}</div>- </div>- )}- </div>- );-}--export function OAuthConnectStateScreen({- entry,- identity,- phase,- error,- authorizationHost,- onRetry,- onCancel,-}: {- /** A curated app. Omit for a generic endpoint and pass `identity` instead. */- entry?: AppDefinition | null;- /** Identity for an unknown remote MCP server: its own name plus its host. */- identity?: { name: string; unverifiedHost: string | null };- phase: OAuthConnectPhase;- error?: string | null;- /**- * Host of the authorization page being opened. A valid HTTPS authorization- * page can still be a phishing page, so the operator sees exactly which host- * they are being handed to (PAP-17099).- */- authorizationHost?: string | null;- onRetry: () => void;- onCancel: () => void;-}) {- const serverName = entry?.name ?? identity?.name ?? "this server";- const unverifiedHost = entry ? null : identity?.unverifiedHost ?? null;- const status = phase === "entry"- ? {- title: `Connect ${serverName} to Paperclip`,- body: `Paperclip will open ${serverName} so you can choose a workspace and approve access.`,- }- : phase === "starting"- ? {- title: "Preparing secure sign-in",- body: `Paperclip is creating a secure ${serverName} connection.`,- }- : phase === "redirecting"- ? {- title: `Opening ${serverName}`,- body: authorizationHost- ? `Continue at ${authorizationHost} to choose a workspace and approve access. Only approve access if you recognize that address.`- : `Continue in ${serverName} to choose a workspace and approve access.`,- }- : {- title: `${serverName} couldn’t connect`,- body: error ?? "Paperclip couldn’t start secure sign-in. Try again.",- };-- return (- <div className="max-w-5xl">- <StepHeader- subtitle="Secure MCP sign-in"- step="key"- activeIndex={0}- labels={["Connect", "Choose access", "Install tools"]}- appIdentity={entry ? { name: entry.name, logoUrl: entry.branding.logoUrl } : undefined}- unverifiedHost={unverifiedHost}- onCancel={onCancel}- />- <div className="mx-auto max-w-xl rounded-2xl border border-border bg-card p-8">- <div className="flex items-start gap-3">- <span className="mt-1 inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border border-border bg-background">- {phase === "error" ? (- <Link2 className="h-5 w-5 text-destructive" />- ) : phase === "entry" ? (- <Lock className="h-5 w-5 text-muted-foreground" />- ) : (- <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />- )}- </span>- <div className="min-w-0">- <h2 className="text-xl font-bold tracking-tight">{status.title}</h2>- <p className="mt-1 text-sm text-muted-foreground">{status.body}</p>- {unverifiedHost ? <UnverifiedServerBadge host={unverifiedHost} className="mt-2" /> : null}- </div>- </div>-- <div className="mt-6 flex items-center gap-2">- {phase === "error" ? (- <Button type="button" onClick={onRetry}>Try again</Button>- ) : (- <Button type="button" disabled>- {phase === "redirecting" ? `Opening ${serverName}…` : "Preparing…"}- </Button>- )}- <Button type="button" variant="ghost" onClick={onCancel}>Back to apps</Button>- </div>- <p className="mt-5 flex items-center gap-1.5 text-xs text-muted-foreground">- <Lock className="h-3.5 w-3.5" />- Your authorization stays in Paperclip’s encrypted secret store.- </p>- </div>- </div>- );-}--function ZapierConnectStep({- link,- onLinkChange,- submitting,- onBack,- onConnect,-}: {- link: string;- onLinkChange: (next: string) => void;- submitting: boolean;- onBack: () => void;- onConnect: () => void;-}) {- const normalizedLink = normalizeAppLink(link);- const zapierHostname = normalizedLink ? new URL(normalizedLink).hostname : "";- const isZapierLink = zapierHostname === "zapier.com" || zapierHostname.endsWith(".zapier.com");-- return (- <div className="mx-auto max-w-xl rounded-2xl border border-border bg-card p-8">- <div className="flex items-start gap-3">- <span className="mt-1 inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border border-border bg-background">- <Link2 className="h-5 w-5 text-muted-foreground" />- </span>- <div className="min-w-0">- <h2 className="text-xl font-bold tracking-tight">Connect Zapier</h2>- <p className="mt-1 text-sm text-muted-foreground">- Paste the complete MCP URL Zapier gives you, including its token.- </p>- </div>- </div>-- <div className="mt-8">- <label className="text-sm font-medium text-foreground">Zapier MCP URL</label>- <Input- value={link}- onChange={(event) => onLinkChange(event.target.value)}- onKeyDown={(event) => {- if (event.key === "Enter" && isZapierLink && !submitting) onConnect();- }}- placeholder="https://mcp.zapier.com/api/v1/connect?token=…"- className="mt-2 h-11"- autoFocus- />- <p className="mt-2 text-xs text-muted-foreground">- The token is part of the URL. Paperclip stores it securely and checks the connection before enabling actions.- </p>- {link.trim() && !isZapierLink && (- <p className="mt-2 text-xs text-destructive">Paste a valid Zapier URL to continue.</p>- )}- </div>-- <div className="mt-8 flex items-center justify-between">- <Button variant="ghost" onClick={onBack} disabled={submitting}>- Back- </Button>- <Button onClick={onConnect} disabled={submitting || !isZapierLink}>- {submitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}- {submitting ? "Checking…" : "Check link"}- </Button>- </div>- </div>- );-}--function GalleryStep({- loading,- apps,- byo = false,+import { ConnectionSetupFlow } from "@/features/connections/ConnectionSetupFlow";+import { useSearchParams } from "@/lib/router";+import type { ToolConnectionCredentialSource } from "@paperclipai/shared";++export {+ AccessStep,+ OAuthConnectStateScreen,+ type OAuthConnectPhase,+} from "@/features/connections/ConnectionSetupFlow";++/** Full-page host for the shared connection setup implementation. */+export function AppsConnect({byoOnly = false,- source = null,- onPick,- onUseLink,- onRunYourOwn,- onPasteConfig,+ credentialSource = "paperclip_vault",}: {- loading: boolean;- apps: AppDefinition[];- /** Entered via the "Connect your own MCP server" card (PAP-12371, Finding C): focus the link path. */- byo?: boolean;- /** Canonical BYO page: keep the URL path and alternate methods, without the app gallery. */byoOnly?: boolean;- source?: string | null;- onPick: (entry: AppDefinition) => void;- onUseLink: (link: string) => void;- onRunYourOwn: () => void;- onPasteConfig: () => void;-}) {- const [search, setSearch] = useState("");- const [linkInput, setLinkInput] = useState("");- const [linkError, setLinkError] = useState<string | null>(null);- const linkSectionRef = useRef<HTMLDivElement>(null);- const linkInputRef = useRef<HTMLInputElement>(null);- const linkInputSelectedRef = useRef(false);-- // Arriving from the BYO card: scroll the URL section into view and select its- // input so the operator can paste immediately.- useEffect(() => {- if (!byo || (loading && !byoOnly) || linkInputSelectedRef.current) return;- if (!byoOnly) linkSectionRef.current?.scrollIntoView?.({ block: "center" });- linkInputRef.current?.focus();- linkInputRef.current?.select();- linkInputSelectedRef.current = true;- }, [byo, byoOnly, loading]);- const filtered = useMemo(() => {- const q = search.trim().toLowerCase();- if (!q) return apps;- return apps.filter((a) => a.name.toLowerCase().includes(q));- }, [apps, search]);- const normalizedLink = normalizeAppLink(linkInput);- const matchedEntry = normalizedLink ? getAppDefinitionForUrl(normalizedLink, apps) : null;- const zapierSource = source === "zapier";-- const continueWithLink = () => {- const next = normalizeAppLink(linkInput);- if (!next) {- setLinkError("Paste a full http or https link.");- return;- }- setLinkError(null);- onUseLink(next);- };-- if (loading && !byoOnly) {- return (- <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">- {Array.from({ length: 8 }).map((_, i) => (- <Skeleton key={i} className="h-32 w-full rounded-xl" />- ))}- </div>- );- }-- return (- <div className="space-y-6">- {!byoOnly && (- <>- <div className="relative">- <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />- <Input- value={search}- onChange={(e) => setSearch(e.target.value)}- placeholder="Search apps…"- className="h-11 pl-9"- />- </div>-- <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">- {filtered.map((app) => {- const copy = appCopyFor(app.slug, app.description);- const methods = getAvailableConnectionMethods(app);- const oauth = methods[0]?.auth === "oauth";- const brokeredOAuth = methods[0]?.oauthStrategy === "paperclip_id_connector";- const oauthBlocked = methods.length === 1 && oauth && !brokeredOAuth && !isMcpDirectOAuthConnectSlug(app.slug);- const unavailable = app.availability?.available === false;- return (- <button- key={app.slug}- type="button"- disabled={oauthBlocked || unavailable}- title={- unavailable- ? `${app.name} isn't configured on this instance yet. Ask your Paperclip admin.`- : undefined- }- onClick={() => onPick(app)}- className={cn(- "flex flex-col rounded-xl border border-border bg-card p-4 text-left transition-colors",- oauthBlocked || unavailable ? "cursor-not-allowed opacity-60" : "hover:border-foreground/30 hover:bg-accent/40",- )}- >- <AppLogo name={app.name} logoUrl={app.branding.logoUrl} size={36} />- <div className="mt-3 text-sm font-bold text-foreground">{app.name}</div>- <div className="mt-1 line-clamp-2 text-xs text-muted-foreground">{copy.tagline}</div>- <div className="mt-3 text-xs font-semibold text-foreground">- {unavailable ? (- <span className="text-muted-foreground">Not available on this instance - ask your admin.</span>- ) : oauthBlocked ? (- <span className="text-muted-foreground">Sign-in coming soon</span>- ) : (- <span>Connect →</span>- )}- </div>- </button>- );- })}- </div>-- {filtered.length === 0 && (- <div className="py-10 text-center text-sm text-muted-foreground">No apps match “{search}”.</div>- )}- </>- )}-- <div- ref={linkSectionRef}- className={cn(- "grid gap-4 border-t border-border pt-5 md:grid-cols-(--gtc-13)",- byo && "-mx-3 rounded-xl border border-primary/40 bg-primary/[0.04] px-3 pb-4 md:mx-0",- )}- >- <div>- <div className="flex items-center gap-2 text-sm font-semibold text-foreground">- <Link2 className="h-4 w-4 text-muted-foreground" />- {zapierSource ? "Connect Zapier" : byo ? "Connect your own MCP server" : "Connect with a link"}- </div>- <p className="mt-1 text-xs text-muted-foreground">- {zapierSource- ? "Paste the complete MCP URL Zapier gives you, including its token."- : byo- ? "Paste your MCP server’s URL and every discovered tool will be available immediately."- : "Paste a setup link from an app that is not listed here."}- </p>- {!zapierSource && (- <p className="mt-1 text-xs text-muted-foreground">- Any remote tool URL works here — including a local MCP server like{" "}- <code className="rounded bg-muted px-1 py-0.5 text-xs">http://127.0.0.1:8848/mcp</code>.- </p>- )}- {matchedEntry && (- <div className="mt-3 flex items-center justify-between gap-3 rounded-lg border border-border bg-muted/40 px-3 py-2">- <div className="flex min-w-0 items-center gap-2 text-sm">- <AppLogo name={matchedEntry.name} logoUrl={matchedEntry.branding.logoUrl} size={24} />- <span className="truncate">This looks like {matchedEntry.name}.</span>- </div>- <Button- type="button"- size="sm"- variant="outline"- disabled={matchedEntry.availability?.available === false}- onClick={() => {- setLinkError(null);- if (matchedEntry.slug === "zapier") {- continueWithLink();- return;- }- onPick(matchedEntry);- }}- >- {matchedEntry.availability?.available === false- ? "Not available"- : matchedEntry.slug === "zapier"- ? "Continue"- : `Use ${matchedEntry.name}`}- </Button>- </div>- )}- </div>- <div className="flex min-w-0 flex-col gap-2 sm:min-w-(--sz-360px)">- <div className="flex gap-2">- <Input- ref={linkInputRef}- aria-label="MCP server URL"- value={linkInput}- onChange={(e) => {- setLinkInput(e.target.value);- setLinkError(null);- }}- onKeyDown={(e) => {- if (e.key === "Enter") continueWithLink();- }}- placeholder={zapierSource ? "https://mcp.zapier.com/api/v1/connect?token=…" : "https://example.com/actions"}- className="h-10"- />- <Button type="button" variant="outline" onClick={continueWithLink}>- Continue- </Button>- </div>- {linkError && <div className="text-xs text-destructive">{linkError}</div>}- </div>- </div>-- <div className="border-t border-border pt-5">- <div className="text-sm font-semibold text-foreground">More ways to connect</div>- <p className="mt-1 text-xs text-muted-foreground">- For tools that aren’t in the gallery. You’ll need details from the tool’s docs.- </p>- <div className="mt-3 flex flex-col gap-2">- <ConnectMethodRow- icon={TerminalSquare}- title="Run your own"- description="Register a command Paperclip runs in your workspace for a tool that isn’t listed."- onClick={onRunYourOwn}- />- <ConnectMethodRow- icon={ClipboardPaste}- title="Paste a config"- description="Already have a setup snippet from a README? Paste it and we’ll connect it."- onClick={onPasteConfig}- />- </div>- </div>- </div>- );-}--function ConnectMethodRow({- icon: Icon,- title,- description,- onClick,-}: {- icon: LucideIcon;- title: string;- description: string;- onClick: () => void;-}) {- return (- <button- type="button"- onClick={onClick}- className="flex w-full items-center gap-3 rounded-lg border border-border bg-card px-4 py-3 text-left transition-colors hover:border-foreground/30 hover:bg-accent/40"- >- <span className="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-border bg-background">- <Icon className="h-4 w-4 text-muted-foreground" />- </span>- <div className="min-w-0 flex-1">- <div className="text-sm font-semibold text-foreground">{title}</div>- <div className="truncate text-xs text-muted-foreground">{description}</div>- </div>- <ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground" />- </button>- );-}--function normalizeAppLink(value: string): string | null {- try {- const parsed = new URL(value.trim());- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;- return parsed.toString();- } catch {- return null;- }-}--/**- * The guided universal flow for an unknown remote MCP server (PAP-17087, plan 2).- *- * The simple path stays exactly as short as it was — URL, name, "does it need a- * key?" — because that is all most servers need. Everything protocol-shaped lives- * behind "Advanced authentication", and no OAuth/DCR/CIMD jargon appears on the- * consumer path: the operator picks how the server authenticates, not which RFC- * Paperclip will use to satisfy it.- *- * The endpoint host and the "Unverified server" label stay visible the whole way- * through, so the operator can always see whose server they are about to let- * agents call.- */-function LinkConnectStep({- link,- name,- onNameChange,- needsKey,- onNeedsKeyChange,- keyValue,- onKeyChange,- authMode,- onAuthModeChange,- headers,- onHeadersChange,- oauthClientId,- onOAuthClientIdChange,- oauthClientSecret,- onOAuthClientSecretChange,- advancedOpen,- onAdvancedOpenChange,- guidance,- matchedEntry,- onUseMatchedEntry,- submitting,- onBack,- onConnect,-}: {- link: string;- name: string;- onNameChange: (next: string) => void;- needsKey: boolean;- onNeedsKeyChange: (next: boolean) => void;- keyValue: string;- onKeyChange: (next: string) => void;- authMode: GenericMcpAuthMode;- onAuthModeChange: (next: GenericMcpAuthMode) => void;- headers: CustomHeaderRow[];- onHeadersChange: (next: CustomHeaderRow[]) => void;- oauthClientId: string;- onOAuthClientIdChange: (next: string) => void;- oauthClientSecret: string;- onOAuthClientSecretChange: (next: string) => void;- advancedOpen: boolean;- onAdvancedOpenChange: (next: boolean) => void;- guidance: GenericConnectGuidance | null;- /** A curated app whose endpoint matches, offered as a convenience only. */- matchedEntry?: AppDefinition | null;- onUseMatchedEntry?: () => void;- submitting: boolean;- onBack: () => void;- onConnect: () => void;-}) {- const host = endpointHost(link);- const headerError = authMode === "custom_headers" ? customHeaderError(headers) : null;- const draft: GenericConnectDraft = {- link,- name,- authMode,- needsKey,- keyValue,- headers,- oauthClientId,- oauthClientSecret,- };- const canSubmit = canSubmitGenericConnect(draft);- const showSimpleKeyQuestion = authMode === "auto";- const nameInputRef = useRef<HTMLInputElement>(null);-- useEffect(() => {- if (guidance?.focus === "name") nameInputRef.current?.focus();- }, [guidance]);-- const updateHeader = (id: string, patch: Partial<CustomHeaderRow>) => {- onHeadersChange(headers.map((row) => (row.id === id ? { ...row, ...patch } : row)));- };-- return (- <div className="mx-auto max-w-xl rounded-2xl border border-border bg-card p-8">- <div className="flex items-start gap-3">- <span className="mt-1 inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border border-border bg-background">- <Link2 className="h-5 w-5 text-muted-foreground" />- </span>- <div className="min-w-0">- <h2 className="text-xl font-bold tracking-tight">Connect your own MCP server</h2>- <p className="mt-1 truncate font-mono text-sm text-muted-foreground" title={link}>{link}</p>- <UnverifiedServerBadge host={host} className="mt-2" />- </div>- </div>-- {matchedEntry && onUseMatchedEntry ? (- <div className="mt-6 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border bg-muted/40 px-3 py-2">- <div className="flex min-w-0 items-center gap-2 text-sm">- <AppLogo name={matchedEntry.name} logoUrl={matchedEntry.branding.logoUrl} size={24} />- <span className="truncate">Paperclip has a guided setup for {matchedEntry.name}.</span>- </div>- <Button type="button" size="sm" variant="outline" onClick={onUseMatchedEntry}>- Use {matchedEntry.name}- </Button>- </div>- ) : null}-- {guidance ? (- <div className="mt-6">- <InlineBanner tone="warning" title={guidance.title}>- {guidance.body}- </InlineBanner>- </div>- ) : null}-- <div className="mt-8 space-y-6">- <div>- <label className="text-sm font-medium text-foreground" htmlFor="generic-mcp-name">Name</label>- <Input- ref={nameInputRef}- id="generic-mcp-name"- value={name}- onChange={(e) => onNameChange(e.target.value)}- placeholder="My app"- className="mt-2 h-11"- />- <p className="mt-2 text-xs text-muted-foreground">- We filled this in from the address. Change it if you'd like.- </p>- </div>-- {showSimpleKeyQuestion && (- <div>- <label className="mr-2 text-sm font-medium text-foreground">Does it need a key?</label>- <div className="mt-2 inline-flex rounded-lg border border-border bg-muted/50 p-1">- <SegmentedOption- label="No"- selected={!needsKey}- onClick={() => onNeedsKeyChange(false)}- />- <SegmentedOption- label="Yes"- selected={needsKey}- onClick={() => onNeedsKeyChange(true)}- />- </div>- <p className="mt-2 text-xs text-muted-foreground">- {needsKey- ? "Paste the key this app gave you."- : "Most servers just work from the address — pick Yes only if the server gave you a key, or if it asks you to sign in."}- </p>- </div>- )}-- {(showSimpleKeyQuestion && needsKey) || authMode === "bearer" ? (- <div className="space-y-4">- <div>- <label className="text-sm font-medium text-foreground" htmlFor="generic-mcp-key">App key</label>- <Input- id="generic-mcp-key"- type="password"- autoComplete="off"- value={keyValue}- onChange={(e) => onKeyChange(e.target.value)}- placeholder="••••••••••••••••"- className="mt-2 h-11 font-mono"- />- </div>- <StoredSecurelyNote />- </div>- ) : null}-- <Collapsible open={advancedOpen} onOpenChange={onAdvancedOpenChange}>- <CollapsibleTrigger className="flex w-full items-center justify-between rounded-lg border border-border bg-background px-3 py-2 text-left text-sm font-medium text-foreground hover:bg-accent/40">- Advanced authentication- <ChevronDown className={cn("h-4 w-4 text-muted-foreground transition-transform", advancedOpen && "rotate-180")} />- </CollapsibleTrigger>- <CollapsibleContent className="space-y-5 pt-4">- <p className="text-xs text-muted-foreground">- Only needed when the server's docs are specific about how to authenticate.- </p>- <div className="flex flex-wrap gap-2">- {GENERIC_AUTH_MODE_OPTIONS.map((option) => (- <SegmentedOption- key={option.mode}- label={option.label}- selected={authMode === option.mode}- onClick={() => onAuthModeChange(option.mode)}- />- ))}- </div>- <p className="text-xs text-muted-foreground">- {GENERIC_AUTH_MODE_OPTIONS.find((option) => option.mode === authMode)?.hint}- </p>-- {authMode === "custom_headers" ? (- <div className="space-y-3">- {headers.map((row) => (- <div key={row.id} className="flex items-start gap-2">- <Input- value={row.name}- onChange={(e) => updateHeader(row.id, { name: e.target.value })}- placeholder="Header name"- aria-label="Header name"- className="h-10 font-mono"- />- <Input- type="password"- autoComplete="off"- value={row.value}- onChange={(e) => updateHeader(row.id, { value: e.target.value })}- placeholder="Value"- aria-label={row.name.trim() ? `Value for ${row.name.trim()}` : "Header value"}- className="h-10 font-mono"- />- <Button- type="button"- variant="ghost"- size="sm"- className="h-10 shrink-0"- onClick={() => onHeadersChange(headers.filter((candidate) => candidate.id !== row.id))}- disabled={headers.length === 1}- >- Remove- </Button>- </div>- ))}- <Button- type="button"- variant="outline"- size="sm"- onClick={() => onHeadersChange([...headers, newCustomHeaderRow()])}- >- Add another header- </Button>- {headerError ? <p className="text-xs text-destructive">{headerError}</p> : null}- <StoredSecurelyNote />- </div>- ) : null}-- {authMode === "oauth" ? (- <div className="space-y-4">- <p className="text-xs text-muted-foreground">- Paperclip sets sign-in up on its own whenever the server allows it. Only fill these in when the- server's docs tell you to register Paperclip yourself first.- </p>- <div>- <label className="text-sm font-medium text-foreground" htmlFor="generic-mcp-client-id">- Client ID- </label>- <Input- id="generic-mcp-client-id"- value={oauthClientId}- onChange={(e) => onOAuthClientIdChange(e.target.value)}- autoComplete="off"- placeholder="Optional"- className="mt-2 h-11 font-mono"- />- </div>- <div>- <label className="text-sm font-medium text-foreground" htmlFor="generic-mcp-client-secret">- Client secret- </label>- <Input- id="generic-mcp-client-secret"- type="password"- autoComplete="off"- value={oauthClientSecret}- onChange={(e) => onOAuthClientSecretChange(e.target.value)}- placeholder="Optional"- className="mt-2 h-11 font-mono"- />- </div>- <StoredSecurelyNote />- </div>- ) : null}- </CollapsibleContent>- </Collapsible>- </div>-- <div className="mt-8 flex items-center justify-between">- <Button variant="ghost" onClick={onBack} disabled={submitting}>- Back- </Button>- <div className="flex items-center gap-3">- <span className="hidden text-xs text-muted-foreground sm:inline">- We'll check the server before turning anything on.- </span>- <Button onClick={onConnect} disabled={submitting || !canSubmit || Boolean(headerError)}>- {submitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}- {submitting ? "Checking…" : "Check link"}- </Button>- </div>- </div>- </div>- );-}--/**- * What the operator is choosing is how the *server* authenticates, in its own- * terms. Paperclip decides internally whether that means a preconfigured client,- * a client ID metadata document, dynamic registration, or the credentials pasted- * below — none of which belongs on this screen.- */-const GENERIC_AUTH_MODE_OPTIONS: Array<{ mode: GenericMcpAuthMode; label: string; hint: string }> = [- {- mode: "auto",- label: "Let Paperclip check",- hint: "Paperclip asks the server what it needs and walks you through it. Start here.",- },- {- mode: "none",- label: "No sign-in needed",- hint: "The server is open to anyone with the address.",- },- {- mode: "bearer",- label: "Key or token",- hint: "Paperclip sends your key as an Authorization header.",- },- {- mode: "custom_headers",- label: "Custom headers",- hint: "For servers that name their own headers. Values are stored as Paperclip secrets and can\u2019t be read back.",- },- {- mode: "oauth",- label: "Browser sign-in",- hint: "You\u2019ll sign in at the provider. Add a client ID and secret only if the provider requires you to register Paperclip first.",- },-];--function StoredSecurelyNote() {- return (- <div className="flex items-start gap-3 rounded-lg bg-muted/50 p-4">- <Lock className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />- <div>- <div className="text-sm font-medium text-foreground">Stored securely.</div>- <div className="text-xs text-muted-foreground">- Paperclip keeps this in its encrypted secret store. You can replace it anytime from this app's page,- but it can't be read back.- </div>- </div>- </div>- );-}--function SegmentedOption({- label,- selected,- onClick,-}: {- label: string;- selected: boolean;- onClick: () => void;-}) {- return (- <button- type="button"- onClick={onClick}- aria-pressed={selected}- className={cn(- "min-w-(--sz-64px) rounded-md px-4 py-1.5 text-sm font-medium transition-colors",- selected- ? "bg-background text-foreground shadow-sm"- : "text-muted-foreground hover:text-foreground",- )}- >- {label}- </button>- );-}--function ConnectionNameField({- name,- onNameChange,-}: {- name: string;- onNameChange: (next: string) => void;-}) {- return (- <div>- <label className="text-sm font-medium text-foreground">Name</label>- <Input- value={name}- onChange={(e) => onNameChange(e.target.value)}- placeholder="My app"- className="mt-2 h-11"- />- <p className="mt-2 text-xs text-muted-foreground">- We filled this in from the app. Change it to tell connections apart.- </p>- </div>- );-}--function KeyStep({- entry,- name,- onNameChange,- values,- onChange,- methodKey,- onMethodChange,- configValues,- onConfigChange,- googleSheetsLinks,- googleSheetsError,- onGoogleSheetsLinksChange,- submitting,- onBack,- onConnect,-}: {- entry: AppDefinition;- name: string;- onNameChange: (next: string) => void;- values: Record<string, string>;- onChange: (next: Record<string, string>) => void;- methodKey: string;- onMethodChange: (method: ConnectionMethodDef) => void;- configValues: Record<string, string | boolean>;- onConfigChange: (next: Record<string, string | boolean>) => void;- googleSheetsLinks: string;- googleSheetsError: string | null;- onGoogleSheetsLinksChange: (next: string) => void;- submitting: boolean;- onBack: () => void;- onConnect: () => void;-}) {- const copy = appCopyFor(entry.slug, entry.description);- const methods = getAvailableConnectionMethods(entry);- const method = methods.length > 1 && !methodKey- ? null- : getAvailableConnectionMethod(entry, methodKey || null);- const fields = (method?.credentialFields ?? []).map((field) => ({- ...field,- configPath: credentialConfigPath(field),- helpUrl: method?.consoleLinks?.keys ?? method?.consoleLinks?.docs ?? "",- }));- const allFilled = fields.every(- (f) => f.required === false || (values[f.configPath]?.trim().length ?? 0) > 0,- );- const configFields = [...(method?.tenantFields ?? []), ...(method?.extensionFields ?? [])];- const standardConfigFields = configFields.filter(- (field) => field.hidden !== true && field.advanced !== true,- );- const advancedConfigFields = configFields.filter(- (field) => field.hidden !== true && field.advanced === true,- );- const [advancedOpen, setAdvancedOpen] = useState(false);- const configFilled = configFields.every((field) => {- if (!field.required) return true;- const value = configValues[field.key];- return typeof value === "boolean" || (typeof value === "string" && value.trim().length > 0);- });- const alternativeKeys = method?.configRequirements?.atLeastOneOf ?? [];- const configRequirementMet = alternativeKeys.length === 0 || alternativeKeys.some((key) => {- const value = configValues[key];- return typeof value === "string" && value.trim().length > 0;- });- const hasMethodSelection = methods.length <= 1 || Boolean(methodKey);- const robotEmail = entry.availability?.robotEmail ?? null;- const unavailable = entry.availability?.available === false;-- if (isGoogleSheetsEntry(entry)) {- const parsed = parseGoogleSheetIds(googleSheetsLinks);- const canConnect = !unavailable && Boolean(robotEmail) && googleSheetsLinks.trim().length > 0;- return (- <div className="mx-auto max-w-xl rounded-2xl border border-border bg-card p-8">- <div className="flex items-center gap-3">- <AppLogo name={entry.name} logoUrl={entry.branding.logoUrl} size={48} />- <div>- <h2 className="text-lg font-bold tracking-tight sm:text-xl">Connect Google Sheets</h2>- <p className="text-sm text-muted-foreground">{copy.short}</p>- </div>- </div>-- <div className="mt-8 space-y-6">- <ConnectionNameField name={name} onNameChange={onNameChange} />-- {robotEmail ? (- <div>- <label className="text-sm font-medium text-foreground">Share each sheet with this email</label>- <div className="mt-2 flex min-w-0 flex-col gap-2 sm:flex-row">- <div- title={robotEmail}- className="min-h-11 min-w-0 flex-1 rounded-md border border-input bg-muted/40 px-3 py-2.5 font-mono text-xs leading-tight text-foreground break-all"- >- {robotEmail}- </div>- <Button- type="button"- variant="outline"- className="shrink-0"- onClick={() => void copyTextToClipboard(robotEmail).catch(() => {})}- >- <Copy className="mr-2 h-4 w-4" />- Copy- </Button>- </div>- <p className="mt-2 text-xs text-muted-foreground">- In Google Sheets, click Share and add this email as an Editor. Then paste the sheet links below.- </p>- </div>- ) : (- <div className="rounded-lg bg-muted/50 p-4 text-sm text-muted-foreground">- Google Sheets is not available on this instance yet.- </div>- )}-- <div>- <label className="text-sm font-medium text-foreground">Paste links to the sheets you shared</label>- <Textarea- value={googleSheetsLinks}- onChange={(e) => onGoogleSheetsLinksChange(e.target.value)}- placeholder="https://docs.google.com/spreadsheets/d/..."- className="mt-2 min-h-28"- />- <div className="mt-2 text-xs text-muted-foreground">- {parsed.ids.length > 0- ? `${parsed.ids.length} ${parsed.ids.length === 1 ? "sheet" : "sheets"} ready to connect.`- : "Paste one link per line. Both .../edit and .../edit#gid=... links work."}- </div>- {googleSheetsError && <div className="mt-2 text-xs text-destructive">{googleSheetsError}</div>}- </div>- </div>-- <div className="mt-8 flex items-center justify-between">- <Button variant="ghost" onClick={onBack} disabled={submitting}>- Back- </Button>- <Button onClick={onConnect} disabled={submitting || !canConnect}>- {submitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}- {submitting ? "Checking…" : "Connect"}- </Button>- </div>- </div>- );- }-- return (- <div className="mx-auto max-w-xl rounded-2xl border border-border bg-card p-8">- <div className="flex items-center gap-3">- <AppLogo name={entry.name} logoUrl={entry.branding.logoUrl} size={48} />- <div>- <h2 className="text-xl font-bold tracking-tight">Connect {entry.name}</h2>- <p className="text-sm text-muted-foreground">{copy.short}</p>- </div>- </div>-- <div className="mt-8 space-y-6">- {methods.length > 1 && (- <div>- <label className="text-sm font-medium text-foreground">How do you want to connect?</label>- <div className="mt-2 inline-flex rounded-lg bg-muted p-1">- {methods.map((candidate) => (- <SegmentedOption- key={candidate.key}- label={candidate.label ?? (candidate.auth === "oauth" ? `Sign in with ${entry.name}` : "Use an API key")}- selected={candidate.key === methodKey}- onClick={() => onMethodChange(candidate)}- />- ))}- </div>- {!method && <p className="mt-2 text-xs text-muted-foreground">Choose a method to continue.</p>}- </div>- )}-- <ConnectionNameField name={name} onNameChange={onNameChange} />-- {standardConfigFields.map((field) => (- <MethodConfigField- key={field.key}- field={field}- value={configValues[field.key]}- onChange={(value) => onConfigChange({ ...configValues, [field.key]: value })}- />- ))}-- {advancedConfigFields.length > 0 && (- <Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen}>- <CollapsibleTrigger className="flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground">- <ChevronDown className={cn("h-4 w-4 transition-transform", advancedOpen && "rotate-180")} />- Advanced- </CollapsibleTrigger>- <CollapsibleContent className="pt-4">- <div className="space-y-6">- {advancedConfigFields.map((field) => (- <MethodConfigField- key={field.key}- field={field}- value={configValues[field.key]}- onChange={(value) => onConfigChange({ ...configValues, [field.key]: value })}- />- ))}- </div>- </CollapsibleContent>- </Collapsible>- )}-- {method && fields.length === 0 ? (- <p className="text-sm text-muted-foreground">- {method.auth === "oauth"- ? `You’ll continue to ${entry.name} to sign in securely.`- : "This app doesn’t need a key. Just connect to continue."}- </p>- ) : (- fields.map((field) => (- <div key={field.configPath}>- <label className="text-sm font-medium text-foreground">- {credentialFieldLabel(entry.name, field.label, fields.length)}- </label>- <Input- type="password"- autoComplete="off"- value={values[field.configPath] ?? ""}- onChange={(e) => onChange({ ...values, [field.configPath]: e.target.value })}- placeholder="••••••••••••••••"- className="mt-2 h-11 font-mono"- />- {field.helpUrl && (- <a- href={field.helpUrl}- target="_blank"- rel="noreferrer"- className="mt-2 inline-flex items-center gap-1 text-xs font-semibold text-foreground underline underline-offset-2"- >- Where do I find this?- <ArrowUpRight className="h-3 w-3" />- </a>- )}- </div>- ))- )}-- {method?.auth === "api_key" && (- <div className="flex items-start gap-3 rounded-lg bg-muted/50 p-4">- <Lock className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />- <div>- <div className="text-sm font-medium text-foreground">Your key is stored securely.</div>- <div className="text-xs text-muted-foreground">- You can replace it anytime from this app’s page.- </div>- </div>- </div>- )}- </div>-- <div className="mt-8 flex items-center justify-between">- <Button variant="ghost" onClick={onBack} disabled={submitting}>- Back- </Button>- <div className="flex items-center gap-3">- <span className="hidden text-xs text-muted-foreground sm:inline">- {method?.auth === "oauth"- ? "You’ll sign in before anything turns on."- : "We’ll check the key before turning anything on."}- </span>- <Button onClick={onConnect} disabled={submitting || !hasMethodSelection || !allFilled || !configFilled || !configRequirementMet}>- {submitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}- {submitting ? "Checking…" : method?.auth === "oauth" ? "Continue to sign in" : "Connect"}- </Button>- </div>- </div>- </div>- );-}--function MethodConfigField({- field,- value,- onChange,-}: {- field: FieldDef;- value: string | boolean | undefined;- onChange: (value: string | boolean) => void;-}) {- if (field.type === "checkbox") {- return (- <div className="flex items-start justify-between gap-4 rounded-lg border border-border p-4">- <div>- <div className="text-sm font-medium text-foreground">{field.label}</div>- {field.helperMd && <div className="mt-1 text-xs text-muted-foreground">{field.helperMd}</div>}- </div>- <ToggleSwitch checked={value === true} onCheckedChange={onChange} />- </div>- );- }- return (- <div>- <label className="text-sm font-medium text-foreground">{field.label}</label>- {field.type === "textarea" ? (- <Textarea- value={typeof value === "string" ? value : ""}- onChange={(event) => onChange(event.target.value)}- placeholder={field.placeholder}- className="mt-2 min-h-24"- />- ) : field.type === "select" ? (- <select- value={typeof value === "string" ? value : ""}- onChange={(event) => onChange(event.target.value)}- className="mt-2 h-11 w-full rounded-md border border-input bg-background px-3 text-sm text-foreground outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/30"- >- <option value="" disabled>Select an option</option>- {(field.options ?? []).map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}- </select>- ) : (- <Input- value={typeof value === "string" ? value : ""}- onChange={(event) => onChange(event.target.value)}- placeholder={field.placeholder}- className="mt-2 h-11"- />- )}- {field.helperMd && <p className="mt-2 text-xs text-muted-foreground">{field.helperMd}</p>}- </div>- );-}--/**- * Access step (PAP-17835 Surface A).- *- * Two binary questions, asked together and *before* any credential is entered,- * so the reader understands the identity and the reach the secret is about to- * get. Hick's Law: two choices, not a matrix. Both use full-row radio targets.- */-export function AccessStep({- appName,- providerName,- companyId,- authKind,- grantKinds,- grantKind,- setGrantKind,- installChoice,- setInstallChoice,- installAgentIds,- setInstallAgentIds,- capabilities,- submitLabel,- onBack,- onContinue,-}: {- appName: string;- providerName: string;- companyId: string;- authKind: ToolConnectionAuthKind;- grantKinds?: ConnectionGrantKind[];- grantKind: ConnectionGrantKind;- setGrantKind: (kind: ConnectionGrantKind) => void;- installChoice: "specific" | "all";- setInstallChoice: (choice: "specific" | "all") => void;- installAgentIds: Set<string>;- setInstallAgentIds: (ids: Set<string>) => void;- capabilities?: Pick<ToolConnectionCreateCapabilities, "canSetCompanyInstall"> & {- companyInstallReason?: string | null;- editableAgentIds?: string[];- } | null;- submitLabel: string;- onBack: () => void;- onContinue: () => void;-}) {- const agentsQuery = useQuery({- queryKey: queryKeys.agents.list(companyId),- queryFn: () => agentsApi.list(companyId),- });- const allAgents: Agent[] = (agentsQuery.data ?? []).filter((a) => a.status !== "terminated");- // "Agents I pick" means agents this person may actually edit. When the server- // has not told us, fall back to every live agent rather than an empty list —- // an empty picker would read as "you have no agents".- const editableAgentIds = capabilities?.editableAgentIds;- const agents = editableAgentIds- ? allAgents.filter((agent) => editableAgentIds.includes(agent.id))- : allAgents;- // Company-wide install is the connection creator's to give. When it is not- // available the option stays visible and disabled with the reason, so the- // scope stays legible instead of quietly disappearing.- const canSetCompanyInstall = capabilities?.canSetCompanyInstall ?? true;- const needsIdentityChoice = authKind !== "none";- const allowedGrantKinds = grantKinds ?? (["user", "organization"] satisfies ConnectionGrantKind[]);- const canContinue = installChoice === "all"- ? canSetCompanyInstall- : installAgentIds.size > 0;-- return (- <div className="mx-auto max-w-xl">- <div className="rounded-2xl border border-border bg-card p-8">- <h2 className="text-xl font-bold tracking-tight">Access</h2>- <p className="mt-1 text-sm text-muted-foreground">- Choose who this credential represents and where agents can use it.- </p>-- <div className="mt-6 space-y-6">- <div>- <h3 className="text-sm font-semibold text-foreground">Who is this credential for?</h3>- {needsIdentityChoice && allowedGrantKinds.length === 1 ? (- <p className="mt-2 text-sm text-muted-foreground">- <span className="font-medium text-foreground">Just me.</span>{" "}- Agents use this {appName} identity only when work runs for you.- </p>- ) : needsIdentityChoice ? (- <RadioCardGroup- ariaLabel="Who is this credential for?"- className="mt-2 sm:grid-cols-2"- value={grantKind}- onValueChange={(next) => setGrantKind(next as ConnectionGrantKind)}- options={[- {- value: "user",- title: "Just me",- description: "Agents use this identity only when work runs for you.",- },- {- value: "organization",- title: "The whole organization",- description: "Agents use one shared identity for eligible organization members.",- },- ].filter((option) => allowedGrantKinds.includes(option.value as ConnectionGrantKind))}- />- ) : (- // A connection with no credential has no identity to choose, so- // asking would be a meaningless decision.- <p className="mt-2 text-sm text-muted-foreground">No identity required</p>- )}- </div>-- <div>- <h3 className="text-sm font-semibold text-foreground">- Which agents can use this connection?- </h3>- <RadioCardGroup- ariaLabel="Which agents can use this connection?"- className="mt-2 sm:grid-cols-2"- value={installChoice}- onValueChange={(next) => setInstallChoice(next as "specific" | "all")}- options={[- {- value: "specific",- title: "Agents I pick",- description: "Choose one or more agents you can edit.",- },- {- value: "all",- title: "Any agent",- description: canSetCompanyInstall- ? "Make this connection available to every agent."- : capabilities?.companyInstallReason ??- "Only someone who can configure this connection can choose this.",- disabled: !canSetCompanyInstall,- },- ]}- />- {installChoice === "specific" ? (- <div className="mt-2">- <AgentMultiSelect- agents={agents}- selectedAgentIds={installAgentIds}- onChange={setInstallAgentIds}- loading={agentsQuery.isLoading}- emptyMessage="You cannot edit any agents yet."- showSelectionPreview={false}- />- </div>- ) : null}- </div>- </div>- </div>-- {/* Mobile stacks actions full-width with the primary action first in- reading order; desktop keeps Back on the left. */}- <div className="mt-6 flex flex-col-reverse gap-2 sm:flex-row sm:items-center sm:justify-between">- <Button variant="ghost" className="w-full sm:w-auto" onClick={onBack}>- Back- </Button>- <Button className="w-full sm:w-auto" onClick={onContinue} disabled={!canContinue}>- {submitLabel}- </Button>- </div>- </div>- );-}--/**- * Summary of what the Access step committed. Three lines, not badges: identity,- * reach, and the existing action summary each said once.- */-export function accessSummaryLines(input: {- grantKind: ConnectionGrantKind;- authKind: ToolConnectionAuthKind;- installChoice: "specific" | "all";- installCount: number;- enabledCount: number;-}): Array<{ label: string; value: string }> {- const identity = input.authKind === "none"- ? "No identity required"- : input.grantKind === "user"- ? "Your identity"- : "Organization identity";- const availableTo = input.installChoice === "all"- ? "Any agent"- : `${input.installCount} selected ${input.installCount === 1 ? "agent" : "agents"}`;- return [- { label: "Identity", value: identity },- { label: "Available to", value: availableTo },- {- label: "Actions",- value: `${input.enabledCount} ${input.enabledCount === 1 ? "action" : "actions"} on`,- },- ];-}--function Radio({ selected }: { selected: boolean }) {- return (- <span- className={cn(- "mt-0.5 inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-2",- selected ? "border-foreground" : "border-muted-foreground/40",- )}- >- {selected && <span className="h-2 w-2 rounded-full bg-foreground" />}- </span>- );-}--function SuccessStep({- appName,- logoUrl,- summary,- onDone,-}: {- appName: string;- logoUrl?: string | null;- /** Identity / Available to / Actions, as three lines rather than badges. */- summary: Array<{ label: string; value: string }>;- onDone: () => void;-}) {- return (- <div className="mx-auto max-w-md py-10 text-center">- <div className="mx-auto flex h-20 w-20 items-center justify-center rounded-full border-2 border-emerald-500 bg-emerald-500/10">- <Check className="h-9 w-9 text-emerald-600 dark:text-emerald-400" />- </div>- <div className="mt-6 flex items-center justify-center gap-2">- <AppLogo name={appName} logoUrl={logoUrl} size={28} />- <h2 className="text-2xl font-bold tracking-tight">{appName} is ready.</h2>- </div>- <dl className="mx-auto mt-6 max-w-xs space-y-1 text-left">- {summary.map((line) => (- <div key={line.label} className="flex items-baseline justify-between gap-4">- <dt className="text-xs font-medium text-muted-foreground">{line.label}</dt>- <dd className="text-sm text-foreground">{line.value}</dd>- </div>- ))}- </dl>- <div className="mt-8">- <Button size="lg" className="px-10" onClick={onDone}>- View connection- </Button>- </div>- </div>+ credentialSource?: ToolConnectionCredentialSource;+} = {}) {+ const [searchParams] = useSearchParams();+ const interactionId = searchParams.get("intent")?.trim() || undefined;+ return (+ <ConnectionSetupFlow+ byoOnly={byoOnly}+ credentialSource={credentialSource}+ host="page"+ interactionId={interactionId}+ />);}diff --git a/ui/src/pages/apps/Browse.test.tsx b/ui/src/pages/apps/Browse.test.tsxindex 32045c9092..d19d57461b 100644--- a/ui/src/pages/apps/Browse.test.tsx+++ b/ui/src/pages/apps/Browse.test.tsx@@ -27,7 +27,9 @@ vi.mock("@/api/access", () => ({}));vi.mock("@/lib/router", () => ({- Link: ({ children, to }: { children: React.ReactNode; to: string }) => <a href={to}>{children}</a>,+ Link: ({ children, to }: { children: React.ReactNode; to: string }) => (+ <a href={to}>{children}</a>+ ),useNavigate: () => navigateMock,}));@@ -69,7 +71,10 @@ function galleryEntry(overrides: Record<string, unknown>) {logoUrl: "https://example.com/github.png",tagline: "Let agents open PRs and issues.",authKind: "oauth",- transportTemplate: { transport: "mcp_remote", url: "https://api.github.com/mcp" },+ transportTemplate: {+ transport: "mcp_remote",+ url: "https://api.github.com/mcp",+ },credentialFields: [],recommendedDefaults: {},urlPatterns: [],@@ -84,13 +89,40 @@ describe("Browse store door (PAP-13254 door 1)", () => {beforeEach(() => {listGalleryMock.mockResolvedValue({apps: [- galleryEntry({ key: "zapier", name: "Zapier", tagline: "Connect automations." }),- galleryEntry({ key: "github", name: "GitHub", tagline: "Open PRs and issues." }),- galleryEntry({ key: "slack", name: "Slack", tagline: "Post messages to channels." }),- galleryEntry({ key: "notion", name: "Notion", tagline: "Read and update workspace content." }),- galleryEntry({ key: "composio", name: "Composio", tagline: "Connect hosted toolkits." }),- galleryEntry({ key: "gmail", name: "Gmail", tagline: "Search and draft email." }),- galleryEntry({ key: "acme", name: "Acme CRM", tagline: "Sync deals and contacts." }),+ galleryEntry({+ key: "zapier",+ name: "Zapier",+ tagline: "Connect automations.",+ }),+ galleryEntry({+ key: "jira",+ name: "Jira",+ tagline: "Track projects and issues.",+ }),+ galleryEntry({+ key: "cloudflare",+ name: "Cloudflare",+ tagline: "Manage Cloudflare resources.",+ }),+ galleryEntry({+ key: "notion",+ name: "Notion",+ tagline: "Read and update workspace content.",+ }),+ galleryEntry({+ key: "gmail",+ name: "Gmail",+ tagline: "Search and draft email.",+ availability: {+ available: false,+ reason: "Gmail is not available on this Paperclip instance yet.",+ },+ }),+ galleryEntry({+ key: "acme",+ name: "Acme CRM",+ tagline: "Sync deals and contacts.",+ }),],});listApplicationsMock.mockResolvedValue({ applications: [] });@@ -107,7 +139,9 @@ describe("Browse store door (PAP-13254 door 1)", () => {});async function renderBrowse() {- const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });root = createRoot(container);await act(async () => {root.render(@@ -129,58 +163,97 @@ describe("Browse store door (PAP-13254 door 1)", () => {expect(text).not.toContain("Other integrations are previews.");expect(text).toContain("Popular");expect(text).toContain("All apps");- expect(text).toContain("GitHub");- expect(text).toContain("Slack");+ expect(text).toContain("Jira");+ expect(text).toContain("Cloudflare");expect(text).toContain("Acme CRM");+ expect(+ Array.from(+ container.querySelectorAll<HTMLElement>(+ '[aria-label="All apps"] > [data-app-slug]',+ ),+ ).map((tile) => tile.dataset.appSlug),+ ).toEqual(["acme", "cloudflare", "gmail", "jira", "notion", "zapier"]);// Bring-your-own is a first-class row in the store.expect(text).toContain("Connect your own tool");expect(text).toContain("All discovered actions are enabled automatically.");expect(text).not.toContain("review its actions before enabling it");+ expect(text).not.toContain("Vercel Connect");+ expect(text).not.toContain("Composio");+ });++ it("does not surface Vercel Connect even when the backend capability is enabled", async () => {+ listGalleryMock.mockResolvedValueOnce({+ apps: [+ galleryEntry({+ key: "posthog",+ name: "PostHog",+ tagline: "Analyze product usage.",+ }),+ ],+ credentialSources: {+ vercelConnect: {+ available: true,+ enabled: true,+ authentication: "access_token",+ manageUrl: "https://vercel.com/connect",+ reason: null,+ },+ },+ });+ await renderBrowse();++ expect(container.textContent).not.toContain("Vercel Connect");+ expect(navigateMock).not.toHaveBeenCalledWith("/apps/vercel-connect");});- it("enables Notion, Zapier, Gmail, and custom URLs while fading unfinished integrations", async () => {+ it("routes every capability-backed app and explains instance-disabled apps", async () => {await renderBrowse();const zapierTiles = Array.from(- container.querySelectorAll<HTMLButtonElement>('button[aria-label="Connect for Zapier"]'),+ container.querySelectorAll<HTMLButtonElement>(+ 'button[aria-label="Connect for Zapier"]',+ ),);- const githubTiles = Array.from(- container.querySelectorAll<HTMLButtonElement>('button[aria-label="Connect for GitHub"]'),+ const jiraTiles = Array.from(+ container.querySelectorAll<HTMLButtonElement>(+ 'button[aria-label="Connect for Jira"]',+ ),);const notionTiles = Array.from(- container.querySelectorAll<HTMLButtonElement>('button[aria-label="Connect for Notion"]'),- );- const composioTiles = Array.from(- container.querySelectorAll<HTMLButtonElement>('button[aria-label="Connect for Composio"]'),+ container.querySelectorAll<HTMLButtonElement>(+ 'button[aria-label="Connect for Notion"]',+ ),);- const gmailTiles = Array.from(- container.querySelectorAll<HTMLButtonElement>('button[aria-label="Connect for Gmail"]'),+ const gmailTile = container.querySelector<HTMLButtonElement>(+ 'button[aria-label="Unavailable for Gmail"]',);const tile = container.querySelector<HTMLButtonElement>(- 'button[aria-label="Coming soon for Acme CRM"]',+ 'button[aria-label="Unavailable for Acme CRM"]',);- const byoCard = Array.from(container.querySelectorAll("button")).find((button) =>- button.textContent?.includes("Connect your own tool"),+ const byoCard = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent?.includes("Connect your own tool"),);expect(zapierTiles).toHaveLength(2);expect(zapierTiles.every((button) => !button.disabled)).toBe(true);expect(notionTiles).toHaveLength(2);expect(notionTiles.every((button) => !button.disabled)).toBe(true);- expect(composioTiles).toHaveLength(1);- expect(composioTiles[0]?.disabled).toBe(false);- expect(gmailTiles).toHaveLength(1);- expect(gmailTiles[0]?.disabled).toBe(false);- expect(githubTiles.every((button) => button.disabled)).toBe(true);+ expect(jiraTiles).toHaveLength(2);+ expect(jiraTiles.every((button) => !button.disabled)).toBe(true);expect(tile?.disabled).toBe(true);+ expect(gmailTile?.disabled).toBe(true);expect(byoCard?.disabled).toBe(false);- expect(tile?.textContent).toContain("Coming soon");+ expect(tile?.textContent).toContain("Unavailable");+ expect(container.textContent).toContain(+ "Gmail is not available on this Paperclip instance yet.",+ );+ expect(container.textContent).not.toContain("Coming soon");expect(zapierTiles[0]?.textContent).toContain("Connect");await act(async () => {zapierTiles[0]?.dispatchEvent(new MouseEvent("click", { bubbles: true }));});- expect(navigateMock).toHaveBeenCalledWith("/apps/connect?byo=1&source=zapier");+ expect(navigateMock).toHaveBeenCalledWith("/apps/connect?source=zapier");await act(async () => {notionTiles[0]?.dispatchEvent(new MouseEvent("click", { bubbles: true }));@@ -188,14 +261,9 @@ describe("Browse store door (PAP-13254 door 1)", () => {expect(navigateMock).toHaveBeenCalledWith("/apps/connect?source=notion");await act(async () => {- composioTiles[0]?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ jiraTiles[0]?.dispatchEvent(new MouseEvent("click", { bubbles: true }));});- expect(navigateMock).toHaveBeenCalledWith("/apps/connect?byo=1&appKey=composio&stage=setup");-- await act(async () => {- gmailTiles[0]?.dispatchEvent(new MouseEvent("click", { bubbles: true }));- });- expect(navigateMock).toHaveBeenCalledWith("/apps/connect?byo=1&appKey=gmail&stage=access");+ expect(navigateMock).toHaveBeenCalledWith("/apps/connect?source=jira");await act(async () => {byoCard?.dispatchEvent(new MouseEvent("click", { bubbles: true }));@@ -206,21 +274,23 @@ describe("Browse store door (PAP-13254 door 1)", () => {it("filters the gallery by the search query", async () => {await renderBrowse();- const input = container.querySelector<HTMLInputElement>('input[type="search"]');+ const input = container.querySelector<HTMLInputElement>(+ 'input[type="search"]',+ );expect(input).toBeTruthy();const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value",)?.set;await act(async () => {- setter?.call(input, "slack");+ setter?.call(input, "cloudflare");input?.dispatchEvent(new Event("input", { bubbles: true }));});await flushReact();const text = container.textContent ?? "";expect(text).toContain("Results (1)");- expect(text).toContain("Slack");+ expect(text).toContain("Cloudflare");expect(text).not.toContain("Acme CRM");// Popular grid is hidden while searching.expect(text).not.toContain("Popular");@@ -229,7 +299,13 @@ describe("Browse store door (PAP-13254 door 1)", () => {it("shows the connected owner, edits existing connections, and offers a deliberate second account", async () => {listApplicationsMock.mockResolvedValue({applications: [- { id: "app-notion", name: "Legacy integration", status: "active", applicationKey: "legacy:notion", metadata: {} },+ {+ id: "app-notion",+ name: "Legacy integration",+ status: "active",+ applicationKey: "legacy:notion",+ metadata: {},+ },],});listConnectionsMock.mockResolvedValue({@@ -248,16 +324,18 @@ describe("Browse store door (PAP-13254 door 1)", () => {],});listUserDirectoryMock.mockResolvedValue({- users: [{- principalId: "user-1",- status: "active",- user: {- id: "user-1",- name: "Dotta",- email: "[email protected]",- image: "https://example.com/dotta.png",+ users: [+ {+ principalId: "user-1",+ status: "active",+ user: {+ id: "user-1",+ name: "Dotta",+ email: "[email protected]",+ image: "https://example.com/dotta.png",+ },},- }],+ ],});await renderBrowse();@@ -267,12 +345,112 @@ describe("Browse store door (PAP-13254 door 1)", () => {'button[aria-label="Edit connections for Notion"]',),);- expect(editButtons).toHaveLength(2);- expect(editButtons.every((button) => button.textContent?.includes("Edit connections"))).toBe(true);- // draft connections count toward the total (they are real, pending-setup connections)- expect(container.textContent).toContain("3 connected");+ expect(editButtons).toHaveLength(3);+ expect(+ editButtons.every((button) =>+ button.textContent?.includes("Edit connections"),+ ),+ ).toBe(true);+ // Interrupted setup remains resumable but is not represented as a+ // successful provider connection.+ expect(container.textContent).toContain("2 connected");expect(container.textContent).toContain("Dotta’s Notion");- expect(container.querySelector('[title="Dotta"] [data-slot="avatar"]')).toBeTruthy();+ expect(+ container.querySelector('[title="Dotta"] [data-slot="avatar"]'),+ ).toBeTruthy();+ const connectedAppTiles = Array.from(+ container.querySelectorAll<HTMLElement>(+ '[aria-label="Connected apps"] > [data-app-slug]',+ ),+ );+ expect(connectedAppTiles).toHaveLength(1);+ expect(connectedAppTiles[0]?.dataset.appSlug).toBe("notion");+ const pageText = container.textContent ?? "";+ expect(pageText.indexOf("Popular")).toBeLessThan(+ pageText.indexOf("Connected"),+ );+ expect(pageText.indexOf("Connected")).toBeLessThan(+ pageText.indexOf("All apps"),+ );+ const popularAppTiles = Array.from(+ container.querySelectorAll<HTMLElement>(+ '[aria-label="Popular apps"] > [data-app-slug]',+ ),+ );+ const popularGrid = container.querySelector<HTMLElement>(+ '[aria-label="Popular apps"]',+ );+ const connectedGrid = container.querySelector<HTMLElement>(+ '[aria-label="Connected apps"]',+ );+ for (const grid of [popularGrid, connectedGrid]) {+ expect(grid?.className).toContain("lg:grid-cols-4");+ expect(grid?.className).toContain("xl:grid-cols-6");+ }+ for (const tile of popularAppTiles) {+ expect(tile.className).toContain("min-w-0");+ expect(+ tile.querySelector('[data-slot="app-tile-status"]')?.className,+ ).toContain("min-h-4");+ expect(+ tile.querySelector('[data-slot="app-tile-primary-action"]')?.className,+ ).toContain("w-full");+ expect(+ tile.querySelector('[data-slot="app-tile-primary-action"] button')+ ?.className,+ ).toContain("max-w-full");+ expect(+ tile.querySelector('[data-slot="app-tile-secondary-action"]')+ ?.className,+ ).toContain("min-h-5");+ }+ const allAppTiles = Array.from(+ container.querySelectorAll<HTMLElement>(+ '[aria-label="All apps"] > [data-app-slug]',+ ),+ );+ const notionAllAppsTile = allAppTiles.find(+ (tile) => tile.dataset.appSlug === "notion",+ );+ expect(notionAllAppsTile?.dataset.connected).toBe("true");+ expect(notionAllAppsTile?.textContent).toContain("Dotta’s Notion");+ expect(+ notionAllAppsTile?.querySelector('[data-slot="app-tile-title"]')+ ?.className,+ ).toContain("break-words");+ expect(+ notionAllAppsTile?.querySelector('[data-slot="app-tile-title"]')+ ?.className,+ ).not.toContain("truncate");+ expect(+ notionAllAppsTile?.querySelector('[data-slot="app-tile-header-status"]')+ ?.className,+ ).toContain("min-h-5");+ expect(+ notionAllAppsTile?.querySelector('[data-slot="app-tile-connection-name"]')+ ?.className,+ ).toContain("break-words");+ expect(+ notionAllAppsTile?.querySelector('[data-slot="app-tile-connection-name"]')+ ?.className,+ ).not.toContain("truncate");+ expect(+ notionAllAppsTile?.querySelector('[data-slot="app-tile-details"]')+ ?.className,+ ).toContain("mt-auto");+ expect(+ notionAllAppsTile?.querySelector('[data-slot="app-tile-actions"]'),+ ).toBeTruthy();+ expect(+ notionAllAppsTile?.querySelector(+ 'button[aria-label="Add another Notion account"]',+ ),+ ).toBeTruthy();+ expect(+ notionAllAppsTile?.querySelector(+ 'button[aria-label="Edit connections for Notion"]',+ ),+ ).toBeTruthy();await act(async () => {editButtons[0]?.dispatchEvent(new MouseEvent("click", { bubbles: true }));@@ -291,7 +469,55 @@ describe("Browse store door (PAP-13254 door 1)", () => {);});- it("treats an existing draft-only Notion connection as editable", async () => {+ it("associates a legacy generic Zapier URL connection with the curated Zapier card", async () => {+ listGalleryMock.mockResolvedValueOnce({+ apps: [+ galleryEntry({+ key: "zapier",+ name: "Zapier",+ tagline: "Connect automations.",+ urlPatterns: ["https://mcp.zapier.com/*"],+ }),+ ],+ });+ listApplicationsMock.mockResolvedValueOnce({+ applications: [+ {+ id: "app-zapier-link",+ name: "Zapier for the company",+ status: "active",+ applicationKey: "app-gallery:link:legacy",+ metadata: { source: "link" },+ },+ ],+ });+ listConnectionsMock.mockResolvedValueOnce({+ connections: [+ {+ id: "conn-zapier",+ applicationId: "app-zapier-link",+ name: "Zapier for the company",+ status: "active",+ config: { url: "https://mcp.zapier.com/api/v1/connect" },+ transportConfig: { url: "https://mcp.zapier.com/api/v1/connect" },+ },+ ],+ });++ await renderBrowse();++ expect(+ container.querySelector('button[aria-label="Connect for Zapier"]'),+ ).toBeNull();+ expect(+ container.querySelector(+ 'button[aria-label="Edit connection for Zapier"]',+ ),+ ).toBeTruthy();+ expect(container.textContent).toContain("1 connected");+ });++ it("keeps an existing draft-only Notion connection resumable without calling it connected", async () => {const applicationId = "057a2df6-175f-4dde-b246-743706444122";const connectionId = "46dc23c1-ecfa-46f7-8e60-34a7cdbd661e";listApplicationsMock.mockResolvedValue({@@ -320,28 +546,50 @@ describe("Browse store door (PAP-13254 door 1)", () => {await renderBrowse();- const editButtons = Array.from(+ const finishButtons = Array.from(container.querySelectorAll<HTMLButtonElement>(- 'button[aria-label="Edit connection for Notion"]',+ 'button[aria-label="Finish setup for Notion"]',),);- expect(editButtons).toHaveLength(2);- expect(container.querySelector('button[aria-label="Connect for Notion"]')).toBeNull();- expect(container.textContent).toContain("1 connected");+ expect(finishButtons).toHaveLength(2);+ expect(+ container.querySelector('button[aria-label="Connect for Notion"]'),+ ).toBeNull();+ expect(container.textContent).toContain("Setup incomplete");+ expect(container.textContent).not.toContain("1 connected");+ expect(container.querySelector('[aria-label="Connected apps"]')).toBeNull();expect(- container.querySelector('button[aria-label="Add another Notion account"]')?.textContent,- ).toContain("Add new");+ container.querySelector(+ 'button[aria-label="Add another Notion account"]',+ ),+ ).toBeNull();+ const allAppTiles = Array.from(+ container.querySelectorAll<HTMLElement>(+ '[aria-label="All apps"] > [data-app-slug]',+ ),+ );+ const notionAllAppsTile = allAppTiles.find(+ (tile) => tile.dataset.appSlug === "notion",+ );+ expect(notionAllAppsTile?.dataset.connected).toBe("false");+ expect(notionAllAppsTile?.dataset.setupPending).toBe("true");await act(async () => {- editButtons[0]?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ finishButtons[0]?.dispatchEvent(+ new MouseEvent("click", { bubbles: true }),+ );});- expect(navigateMock).toHaveBeenCalledWith(`/apps/${connectionId}/setup`);+ expect(navigateMock).toHaveBeenCalledWith(+ `/apps/connect?source=notion&resume=${connectionId}`,+ );});it("keeps the custom URL option available when gallery search has no matches", async () => {await renderBrowse();- const input = container.querySelector<HTMLInputElement>('input[type="search"]');+ const input = container.querySelector<HTMLInputElement>(+ 'input[type="search"]',+ );const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value",diff --git a/ui/src/pages/apps/Browse.tsx b/ui/src/pages/apps/Browse.tsxindex 57e4f5020e..e1782731ba 100644--- a/ui/src/pages/apps/Browse.tsx+++ b/ui/src/pages/apps/Browse.tsx@@ -1,7 +1,13 @@import { useEffect, useMemo, useState } from "react";import { useQuery } from "@tanstack/react-query";import { Check, Link2, Search } from "lucide-react";+import {+ appSupportsCatalogSetup,+ getAppDefinitionForUrl,+ getAppStoreDefinition,+} from "@paperclipai/shared";import { useNavigate } from "@/lib/router";+import { cn } from "@/lib/utils";import { useCompany } from "@/context/CompanyContext";import { useBreadcrumbs } from "@/context/BreadcrumbContext";import { queryKeys } from "@/lib/queryKeys";@@ -13,6 +19,7 @@ import { buildCompanyUserProfileMap } from "@/lib/company-members";import { AppLogo } from "./AppLogo";import {appApplicationSourceSlug,+ appDefinitionDarkLogoUrl,appDefinitionDescription,appDefinitionLogoUrl,appDefinitionName,@@ -23,10 +30,12 @@ import {AdvancedToolsLink,BYO_CONNECT_HREF,ByoConnectCard,- NOTION_CONNECT_HREF,POPULAR_KEYS,- ZAPIER_CONNECT_HREF,} from "./store-cards";+import {+ appSourceConnectHref,+ appSourceResumeHref,+} from "./app-connect-policy";import {ConnectionOwnerIdentity,connectionDisplayNameForOwner,@@ -36,12 +45,10 @@ import {function connectHrefFor(entry: AppGalleryDisplayEntry): string | null {const slug = appDefinitionSlug(entry);- if (slug === "notion") return NOTION_CONNECT_HREF;- if (slug === "zapier") return ZAPIER_CONNECT_HREF;- if (slug === "posthog") return "/apps/connect?byo=1&appKey=posthog&stage=setup";- if (slug === "composio") return "/apps/connect?byo=1&appKey=composio&stage=setup";- if (slug === "gmail") return "/apps/connect?byo=1&appKey=gmail&stage=access";- return null;+ const definition = getAppStoreDefinition(slug);+ return appSupportsCatalogSetup(definition)+ ? appSourceConnectHref(slug)+ : null;}function additionalConnectionHref(@@ -61,10 +68,11 @@ function additionalConnectionHref(/*** Door 1 — Browse (the store) (PAP-13254 / U3 §4).*- * A persistent, browsable storefront: search + a Popular grid + the full- * gallery + a first-class bring-your-own card + a labelled Developer link.- * Browse remains the single discoverability surface. Notion uses MCP-direct- * OAuth, while Zapier and bring-your-own MCP servers use the URL flow.+ * A persistent, browsable storefront: search + Popular and Connected grids ++ * the full gallery + a first-class bring-your-own card + a labelled Developer+ * link.+ * Browse remains the single discoverability surface. Capability-backed apps+ * share the curated setup route; Zapier branches to its generated-URL screen.*/export function Browse() {const navigate = useNavigate();@@ -96,7 +104,9 @@ export function Browse() {enabled: !!selectedCompanyId,});const userDirectoryQuery = useQuery({- queryKey: queryKeys.access.companyUserDirectory(selectedCompanyId ?? "__none__"),+ queryKey: queryKeys.access.companyUserDirectory(+ selectedCompanyId ?? "__none__",+ ),queryFn: () => accessApi.listUserDirectory(selectedCompanyId!),enabled: !!selectedCompanyId,});@@ -104,9 +114,9 @@ export function Browse() {const gallery = (galleryQuery.data?.apps ?? []) as AppGalleryDisplayEntry[];const popular = useMemo(() =>- POPULAR_KEYS.map((key) => gallery.find((entry) => appDefinitionSlug(entry) === key)).filter(- (entry): entry is AppGalleryDisplayEntry => Boolean(entry),- ),+ POPULAR_KEYS.map((key) =>+ gallery.find((entry) => appDefinitionSlug(entry) === key),+ ).filter((entry): entry is AppGalleryDisplayEntry => Boolean(entry)),[gallery],);@@ -121,42 +131,92 @@ export function Browse() {}, [gallery, trimmed]);const connectionSummaryBySlug = useMemo(() => {const connections = connectionsQuery.data?.connections ?? [];- const gallerySlugs = new Set(gallery.map((entry) => appDefinitionSlug(entry)));+ const gallerySlugs = new Set(+ gallery.map((entry) => appDefinitionSlug(entry)),+ );const gallerySlugByName = new Map(- gallery.map((entry) => [appDefinitionName(entry).trim().toLowerCase(), appDefinitionSlug(entry)]),+ gallery.map((entry) => [+ appDefinitionName(entry).trim().toLowerCase(),+ appDefinitionSlug(entry),+ ]),);const connectionsByApplicationId = new Map<string, typeof connections>();for (const connection of connections) {if (connection.status === "archived") continue;- connectionsByApplicationId.set(- connection.applicationId,- [...(connectionsByApplicationId.get(connection.applicationId) ?? []), connection],- );+ connectionsByApplicationId.set(connection.applicationId, [+ ...(connectionsByApplicationId.get(connection.applicationId) ?? []),+ connection,+ ]);}- const summaries = new Map<string, {- applicationId: string;- count: number;- primaryConnection: (typeof connections)[number] | null;- }>();+ const summaries = new Map<+ string,+ {+ applicationId: string;+ connectedCount: number;+ draftCount: number;+ primaryConnection: (typeof connections)[number] | null;+ }+ >();for (const application of applicationsQuery.data?.applications ?? []) {if (application.status === "archived") continue;- const appConnections = connectionsByApplicationId.get(application.id) ?? [];+ const appConnections =+ connectionsByApplicationId.get(application.id) ?? [];const configuredConnectionSlug = appConnections- .map((connection) => connection.config?.sourceTemplateKey ?? connection.transportConfig?.sourceTemplateKey)- .find((value): value is string => typeof value === "string" && gallerySlugs.has(value));+ .map(+ (connection) =>+ connection.config?.sourceTemplateKey ??+ connection.transportConfig?.sourceTemplateKey,+ )+ .find(+ (value): value is string =>+ typeof value === "string" && gallerySlugs.has(value),+ );+ // Older branded URL flows (notably Zapier) were persisted as generic+ // `link` applications even though their public endpoint matched a curated+ // provider. Keep those already-working connections attached to the store+ // card without rewriting credentials or relying on a display-name guess.+ const endpointMatchedSlug = appConnections+ .flatMap((connection) => [+ connection.config?.url,+ connection.transportConfig?.url,+ ])+ .map((value) =>+ typeof value === "string"+ ? appDefinitionSlug(getAppDefinitionForUrl(value, gallery)) || null+ : null,+ )+ .find((value): value is string => Boolean(value));const applicationSlug = appApplicationSourceSlug(application);- const slug = applicationSlug && gallerySlugs.has(applicationSlug)- ? applicationSlug- : configuredConnectionSlug- ?? gallerySlugByName.get(application.name.trim().toLowerCase())- ?? null;+ const slug =+ applicationSlug &&+ applicationSlug !== "link" &&+ gallerySlugs.has(applicationSlug)+ ? applicationSlug+ : (configuredConnectionSlug ??+ endpointMatchedSlug ??+ gallerySlugByName.get(application.name.trim().toLowerCase()) ??+ null);if (!slug) continue;const current = summaries.get(slug);+ const connectedConnections = appConnections.filter(+ (connection) => connection.status !== "draft",+ );+ const draftConnections = appConnections.filter(+ (connection) => connection.status === "draft",+ );summaries.set(slug, {applicationId: current?.applicationId ?? application.id,- count: (current?.count ?? 0) + appConnections.length,- primaryConnection: current?.primaryConnection ?? appConnections[0] ?? null,+ connectedCount:+ (current?.connectedCount ?? 0) + connectedConnections.length,+ draftCount: (current?.draftCount ?? 0) + draftConnections.length,+ // Interrupted OAuth attempts remain resumable, but are not successful+ // connections and must not receive the green Connected treatment.+ primaryConnection:+ current?.primaryConnection ??+ connectedConnections[0] ??+ draftConnections[0] ??+ null,});}return summaries;@@ -165,32 +225,108 @@ export function Browse() {() => buildCompanyUserProfileMap(userDirectoryQuery.data?.users),[userDirectoryQuery.data],);+ const sortedPopular = useMemo(+ () =>+ popular+ .map((entry, index) => ({ entry, index }))+ .sort((left, right) => {+ const leftSummary = connectionSummaryBySlug.get(+ appDefinitionSlug(left.entry),+ );+ const rightSummary = connectionSummaryBySlug.get(+ appDefinitionSlug(right.entry),+ );+ const leftRank =+ (leftSummary?.connectedCount ?? 0) > 0+ ? 2+ : (leftSummary?.draftCount ?? 0) > 0+ ? 1+ : 0;+ const rightRank =+ (rightSummary?.connectedCount ?? 0) > 0+ ? 2+ : (rightSummary?.draftCount ?? 0) > 0+ ? 1+ : 0;+ return rightRank - leftRank || left.index - right.index;+ })+ .map(({ entry }) => entry),+ [connectionSummaryBySlug, popular],+ );+ const connectedApps = useMemo(+ () =>+ gallery.filter(+ (entry) =>+ (connectionSummaryBySlug.get(appDefinitionSlug(entry))+ ?.connectedCount ?? 0) > 0,+ ),+ [connectionSummaryBySlug, gallery],+ );+ const sortedFiltered = useMemo(+ () =>+ [...filtered].sort(+ (left, right) =>+ appDefinitionName(left).localeCompare(+ appDefinitionName(right),+ undefined,+ {+ sensitivity: "base",+ },+ ) || appDefinitionSlug(left).localeCompare(appDefinitionSlug(right)),+ ),+ [filtered],+ );if (!selectedCompanyId) {- return <div className="p-6 text-sm text-muted-foreground">Select an organization to browse apps.</div>;+ return (+ <div className="p-6 text-sm text-muted-foreground">+ Select an organization to browse apps.+ </div>+ );}- const loading = galleryQuery.isLoading || applicationsQuery.isLoading || connectionsQuery.isLoading;+ const loading =+ galleryQuery.isLoading ||+ applicationsQuery.isLoading ||+ connectionsQuery.isLoading;const tileProps = (entry: AppGalleryDisplayEntry) => {const summary = connectionSummaryBySlug.get(appDefinitionSlug(entry));const connectHref = connectHrefFor(entry);const available = entry.availability?.available !== false;const primaryConnection = summary?.primaryConnection ?? null;- const owner = primaryConnection ? connectionOwnerProfile(primaryConnection, userProfileById) : null;- const addAnotherHref = summary- ? additionalConnectionHref(entry, summary.applicationId)+ const owner = primaryConnection+ ? connectionOwnerProfile(primaryConnection, userProfileById): null;+ const addAnotherHref =+ summary && summary.connectedCount > 0+ ? additionalConnectionHref(entry, summary.applicationId)+ : null;+ const setupPending =+ (summary?.connectedCount ?? 0) === 0 && (summary?.draftCount ?? 0) > 0;return {- connectedCount: summary?.count ?? 0,+ connectedCount: summary?.connectedCount ?? 0,+ setupPending,connectionName: primaryConnection- ? connectionDisplayNameForOwner(primaryConnection, appDefinitionName(entry), owner)+ ? connectionDisplayNameForOwner(+ primaryConnection,+ appDefinitionName(entry),+ owner,+ ): null,owner,onPrimary: primaryConnection- ? () => navigate(summary && summary.count > 1- ? `/apps/app/${summary.applicationId}/setup`- : `/apps/${primaryConnection.id}/setup`)+ ? () =>+ navigate(+ setupPending+ ? appSourceResumeHref(+ appDefinitionSlug(entry),+ primaryConnection.id,+ )+ : summary && summary.connectedCount > 1+ ? `/apps/app/${summary.applicationId}/setup`+ : `/apps/${primaryConnection.id}/setup`,+ ): available && connectHref? () => navigate(connectHref): undefined,@@ -227,13 +363,37 @@ export function Browse() {</div>) : (<>- {!trimmed && popular.length > 0 && (+ {!trimmed && sortedPopular.length > 0 && (<section className="space-y-3"><div className="text-(length:--text-micro) font-semibold uppercase tracking-wide text-muted-foreground">Popular</div>- <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">- {popular.map((entry) => (+ <div+ className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6"+ aria-label="Popular apps"+ >+ {sortedPopular.map((entry) => (+ <AppTile+ key={appDefinitionSlug(entry)}+ entry={entry}+ {...tileProps(entry)}+ compact+ />+ ))}+ </div>+ </section>+ )}++ {!trimmed && connectedApps.length > 0 && (+ <section className="space-y-3">+ <div className="text-(length:--text-micro) font-semibold uppercase tracking-wide text-muted-foreground">+ Connected+ </div>+ <div+ className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6"+ aria-label="Connected apps"+ >+ {connectedApps.map((entry) => (<AppTilekey={appDefinitionSlug(entry)}entry={entry}@@ -247,16 +407,19 @@ export function Browse() {<section className="space-y-3"><div className="text-(length:--text-micro) font-semibold uppercase tracking-wide text-muted-foreground">- {trimmed ? `Results (${filtered.length})` : "All apps"}+ {trimmed ? `Results (${sortedFiltered.length})` : "All apps"}</div>- {filtered.length === 0 ? (+ {sortedFiltered.length === 0 ? (<p className="flex items-center gap-1.5 rounded-xl border border-dashed border-border bg-card px-4 py-6 text-sm text-muted-foreground"><Link2 className="h-4 w-4" />No planned apps match “{query.trim()}”.</p>) : (- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">- {filtered.map((entry) => (+ <div+ className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3"+ aria-label={trimmed ? "App search results" : "All apps"}+ >+ {sortedFiltered.map((entry) => (<AppTilekey={appDefinitionSlug(entry)}entry={entry}@@ -283,6 +446,7 @@ function AppTile({onPrimary,onAddAnother,connectedCount,+ setupPending,connectionName,owner,compact = false,@@ -291,99 +455,220 @@ function AppTile({onPrimary?: () => void;onAddAnother?: () => void;connectedCount: number;+ setupPending: boolean;connectionName: string | null;owner: ConnectionOwnerProfile | null;compact?: boolean;}) {const disabled = !onPrimary;+ const unavailableReason =+ entry.availability?.available === false+ ? (entry.availability.reason ?? "This app is disabled on this instance.")+ : null;const connected = connectedCount > 0;const appName = appDefinitionName(entry);const actionLabel = connected- ? connectedCount > 1 ? "Edit connections" : "Edit connection"- : disabled ? "Coming soon" : "Connect";+ ? connectedCount > 1+ ? "Edit connections"+ : "Edit connection"+ : setupPending+ ? "Finish setup"+ : disabled+ ? "Unavailable"+ : "Connect";const connectedActionClass = connected? "border-emerald-500/50 text-emerald-700 hover:bg-emerald-500/10 dark:text-emerald-300": undefined;if (compact) {return (<div- className={disabled- ? "flex cursor-not-allowed flex-col items-center gap-2 rounded-xl border border-border bg-background px-3 py-4 text-center opacity-60"- : "flex flex-col items-center gap-2 rounded-xl border border-border bg-background px-3 py-4 text-center"}+ data-app-slug={appDefinitionSlug(entry)}+ data-connected={connected ? "true" : "false"}+ data-setup-pending={setupPending ? "true" : "false"}+ className={+ disabled+ ? "flex h-full min-w-0 cursor-not-allowed flex-col items-center gap-2 rounded-xl border border-border bg-background px-3 py-4 text-center opacity-60"+ : "flex h-full min-w-0 flex-col items-center gap-2 rounded-xl border border-border bg-background px-3 py-4 text-center"+ }>- <AppLogo name={appName} logoUrl={appDefinitionLogoUrl(entry)} size={36} />+ <AppLogo+ name={appName}+ logoUrl={appDefinitionLogoUrl(entry)}+ darkLogoUrl={appDefinitionDarkLogoUrl(entry)}+ size={36}+ /><span className="text-xs font-medium text-foreground">{appName}</span>- {connected && (- <span className="inline-flex items-center gap-1 text-xs font-medium text-emerald-700 dark:text-emerald-300">- <Check className="h-3 w-3" /> {connectedCount} connected- </span>- )}- <Button- type="button"- size="sm"- variant="outline"- disabled={disabled}- onClick={onPrimary}- className={connectedActionClass}- aria-label={`${actionLabel} for ${appName}`}+ <div+ data-slot="app-tile-status"+ className="flex min-h-4 max-w-full items-center justify-center">- {actionLabel}- </Button>- {connected && onAddAnother && (- <button+ {connected ? (+ <span className="inline-flex items-center gap-1 text-xs font-medium text-emerald-700 dark:text-emerald-300">+ <Check className="h-3 w-3" /> {connectedCount} connected+ </span>+ ) : setupPending ? (+ <span className="text-xs font-medium text-muted-foreground">+ Setup incomplete+ </span>+ ) : unavailableReason ? (+ <span+ className="truncate text-xs text-muted-foreground"+ title={unavailableReason}+ >+ {unavailableReason}+ </span>+ ) : null}+ </div>+ <div data-slot="app-tile-primary-action" className="w-full min-w-0">+ <Buttontype="button"- onClick={onAddAnother}- className="text-xs text-muted-foreground transition-colors hover:text-foreground"- aria-label={`Add another ${appName} account`}+ size="sm"+ variant="outline"+ disabled={disabled}+ onClick={onPrimary}+ className={cn(+ "w-full max-w-full overflow-hidden text-ellipsis",+ connectedActionClass,+ )}+ aria-label={`${actionLabel} for ${appName}`}>- Add new- </button>- )}+ {actionLabel}+ </Button>+ </div>+ <div+ data-slot="app-tile-secondary-action"+ className="flex min-h-5 items-center justify-center"+ >+ {connected && onAddAnother ? (+ <button+ type="button"+ onClick={onAddAnother}+ className="text-xs text-muted-foreground transition-colors hover:text-foreground"+ aria-label={`Add another ${appName} account`}+ >+ Add new+ </button>+ ) : null}+ </div></div>);}return (<div- className={disabled- ? "flex h-full cursor-not-allowed items-start gap-3 rounded-xl border border-border bg-card px-4 py-4 text-left opacity-60"- : "flex h-full items-start gap-3 rounded-xl border border-border bg-card px-4 py-4 text-left"}+ data-app-slug={appDefinitionSlug(entry)}+ data-connected={connected ? "true" : "false"}+ data-setup-pending={setupPending ? "true" : "false"}+ className={+ disabled+ ? "flex h-full cursor-not-allowed flex-col rounded-xl border border-border bg-card px-4 py-4 text-left opacity-60"+ : "flex h-full flex-col rounded-xl border border-border bg-card px-4 py-4 text-left"+ }>- <AppLogo name={appName} logoUrl={appDefinitionLogoUrl(entry)} size={36} />- <div className="min-w-0 flex-1">- <div className="text-sm font-semibold text-foreground">{appName}</div>- <div className="mt-0.5 line-clamp-2 text-xs text-muted-foreground">{appDefinitionDescription(entry)}</div>- {connected && owner && (- <div className="mt-2">- <ConnectionOwnerIdentity owner={owner} />+ <div className="flex items-start gap-3">+ <AppLogo+ name={appName}+ logoUrl={appDefinitionLogoUrl(entry)}+ darkLogoUrl={appDefinitionDarkLogoUrl(entry)}+ size={36}+ />+ <div className="min-w-0 flex-1">+ <div+ data-slot="app-tile-title"+ className="break-words text-sm font-semibold leading-tight text-foreground"+ >+ {appName}+ </div>+ <div+ data-slot="app-tile-header-status"+ className="mt-1 flex min-h-5 items-center"+ >+ {connected && (+ <span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-2 py-0.5 text-xs font-medium text-emerald-700 dark:text-emerald-300">+ <Check className="h-3 w-3" />+ {connectedCount > 1+ ? `${connectedCount} connected`+ : "Connected"}+ </span>+ )}+ {setupPending && (+ <span className="rounded-full bg-muted px-2 py-0.5 text-xs font-medium text-muted-foreground">+ Setup incomplete+ </span>+ )}</div>- )}+ </div>+ </div>+ <div className="mt-2 line-clamp-2 text-xs text-muted-foreground">+ {appDefinitionDescription(entry)}</div>- <div className="flex shrink-0 flex-col items-end gap-1.5">- {connected && connectionName && (- <span className="max-w-40 truncate text-xs text-muted-foreground">{connectionName}</span>- )}- <Button- type="button"- size="sm"- variant="outline"- disabled={disabled}- onClick={onPrimary}- className={connectedActionClass}- aria-label={`${actionLabel} for ${appName}`}+ {unavailableReason ? (+ <div className="mt-2 text-xs text-muted-foreground">+ {unavailableReason}+ </div>+ ) : null}+ {connected || setupPending ? (+ <div+ data-slot="app-tile-details"+ className="mt-auto border-t border-border pt-3">- {actionLabel}- </Button>- {connected && onAddAnother && (- <button+ {connectionName && (+ <div+ data-slot="app-tile-connection-name"+ className="break-words text-sm font-medium text-foreground"+ >+ {connectionName}+ </div>+ )}+ {owner ? (+ <div className="mt-2 min-w-0">+ <ConnectionOwnerIdentity owner={owner} />+ </div>+ ) : null}+ <div+ data-slot="app-tile-actions"+ className="mt-3 flex items-center justify-end gap-2"+ >+ {onAddAnother && (+ <Button+ type="button"+ size="sm"+ variant="ghost"+ onClick={onAddAnother}+ aria-label={`Add another ${appName} account`}+ >+ Add new+ </Button>+ )}+ <Button+ type="button"+ size="sm"+ variant="outline"+ disabled={disabled}+ onClick={onPrimary}+ className={connectedActionClass}+ aria-label={`${actionLabel} for ${appName}`}+ >+ {actionLabel}+ </Button>+ </div>+ </div>+ ) : (+ <div+ data-slot="app-tile-actions"+ className="mt-auto flex justify-end pt-3"+ >+ <Buttontype="button"- onClick={onAddAnother}- className="text-xs text-muted-foreground transition-colors hover:text-foreground"- aria-label={`Add another ${appName} account`}+ size="sm"+ variant="outline"+ disabled={disabled}+ onClick={onPrimary}+ aria-label={`${actionLabel} for ${appName}`}>- Add new- </button>- )}- </div>+ {actionLabel}+ </Button>+ </div>+ )}</div>);}diff --git a/ui/src/pages/apps/ComposioProvenanceChip.tsx b/ui/src/pages/apps/ComposioProvenanceChip.tsxindex 4db5a41219..3196b7f37c 100644--- a/ui/src/pages/apps/ComposioProvenanceChip.tsx+++ b/ui/src/pages/apps/ComposioProvenanceChip.tsx@@ -13,21 +13,37 @@ import { composioChildParentConnectionId, composioChildToolkitSlug } from "./com* relationship wherever the child appears, and links to the broker's Services tab* so the parent is one click away.*/-export function ComposioProvenanceChip({+export function ConnectionProvenanceChip({connection,className,}: {- connection: { config?: Record<string, unknown> | null } | null | undefined;+ connection: {+ config?: Record<string, unknown> | null;+ credentialSource?: string;+ externalCredential?: { connectorUid?: string } | null;+ } | null | undefined;className?: string;}) {- const toolkitSlug = composioChildToolkitSlug(connection);- if (!toolkitSlug) return null;- const parentConnectionId = composioChildParentConnectionId(connection);-const chipClass = cn("inline-flex items-center gap-1 rounded-full border border-border bg-muted px-2 py-0.5 text-xs font-medium text-muted-foreground",className,);+ if (connection?.credentialSource === "vercel_connect") {+ const connectorUid = connection.externalCredential?.connectorUid;+ return (+ <span+ className={chipClass}+ title={connectorUid ? `Credentials managed by Vercel Connect (${connectorUid})` : "Credentials managed by Vercel Connect"}+ >+ <Blocks className="h-3 w-3" />+ via Vercel Connect+ </span>+ );+ }++ const toolkitSlug = composioChildToolkitSlug(connection);+ if (!toolkitSlug) return null;+ const parentConnectionId = composioChildParentConnectionId(connection);const label = (<><Blocks className="h-3 w-3" />@@ -52,3 +68,6 @@ export function ComposioProvenanceChip({</Link>);}++/** Backward-compatible name for callers outside the Apps v2 surfaces. */+export const ComposioProvenanceChip = ConnectionProvenanceChip;diff --git a/ui/src/pages/apps/Connections.test.tsx b/ui/src/pages/apps/Connections.test.tsxindex 2659cad206..b3e7159179 100644--- a/ui/src/pages/apps/Connections.test.tsx+++ b/ui/src/pages/apps/Connections.test.tsx@@ -111,6 +111,7 @@ function connection(overrides: Record<string, unknown>) {healthStatus: "healthy",healthCheckedAt: null,lastError: null,+ credentialPolicy: "shared",enabled: true,lastUsedAt: null,createdByAgentId: null,@@ -231,6 +232,7 @@ describe("Connections table (M1b / PAP-13254 door 2)", () => {name: "GitHub",healthStatus: "healthy",createdByUserId: "user-1",+ credentialPolicy: "per_user",}),connection({id: "c-attention",@@ -295,7 +297,9 @@ describe("Connections table (M1b / PAP-13254 door 2)", () => {expect(text).toContain("1 connection needs attention");// 3. New header columns are present.const headers = Array.from(container.querySelectorAll("th")).map((th) => th.textContent?.trim());- expect(headers).toEqual(["Connection", "Connected by", "Status", "Actions", "Last used", ""]);+ expect(headers).toEqual(["Connection", "Type", "Connected by", "Status", "Actions", "Last used", ""]);+ expect(text).toContain("Personal");+ expect(text).toContain("Company");// 4. Actions column reflects enabled catalog entries per account; missing profile => 0 on.expect(text).toContain("3 on");expect(text).toContain("0 on");@@ -318,6 +322,8 @@ describe("Connections table (M1b / PAP-13254 door 2)", () => {expect(rowButtonLabel("Notion")).toBe("Edit");// 8. Generic connection names inherit the originating user's first name.expect(text).toContain("Dotta’s GitHub");+ expect(text).toContain("Slack for the company");+ expect(text).toContain("Slack Team for the company");expect(container.querySelector('[title="Dotta"] [data-slot="avatar"]')).toBeTruthy();// Custom account labels remain untouched.expect(text).toContain("Slack Team");@@ -374,7 +380,7 @@ describe("Connections table (M1b / PAP-13254 door 2)", () => {await renderApps();const deleteButton = container.querySelector<HTMLButtonElement>(- 'button[aria-label="Delete GitHub connection"]',+ 'button[aria-label="Delete GitHub for the company connection"]',);expect(deleteButton).toBeTruthy();@@ -431,7 +437,7 @@ describe("Connections table (M1b / PAP-13254 door 2)", () => {await renderApps();const deleteButton = container.querySelector<HTMLButtonElement>(- 'button[aria-label="Delete Composio connection"]',+ 'button[aria-label="Delete Composio for the company connection"]',);await act(async () => {deleteButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));@@ -465,7 +471,7 @@ describe("Connections table (M1b / PAP-13254 door 2)", () => {await renderApps();const deleteButton = container.querySelector<HTMLButtonElement>(- 'button[aria-label="Delete GitHub connection"]',+ 'button[aria-label="Delete GitHub for the company connection"]',);await act(async () => {deleteButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));@@ -515,7 +521,7 @@ describe("Connections table (M1b / PAP-13254 door 2)", () => {await renderApps();const deleteButton = container.querySelector<HTMLButtonElement>(- 'button[aria-label="Delete GitHub connection"]',+ 'button[aria-label="Delete GitHub for the company connection"]',);await act(async () => {deleteButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));diff --git a/ui/src/pages/apps/Connections.tsx b/ui/src/pages/apps/Connections.tsxindex 1460e796df..000064feb4 100644--- a/ui/src/pages/apps/Connections.tsx+++ b/ui/src/pages/apps/Connections.tsx@@ -33,10 +33,11 @@ import { Skeleton } from "@/components/ui/skeleton";import { cn } from "@/lib/utils";import { timeAgo } from "@/lib/timeAgo";import { AppLogo } from "./AppLogo";-import { ComposioProvenanceChip } from "./ComposioProvenanceChip";+import { ConnectionProvenanceChip } from "./ComposioProvenanceChip";import { composioChildParentConnectionId } from "./composio-services";import {appApplicationSourceSlug,+ appDefinitionDarkLogoUrl,appDefinitionLogoUrl,appDefinitionName,appDefinitionSlug,@@ -44,6 +45,7 @@ import {} from "./app-definition-display";import { useReviewCount } from "./useReviewCount";import { AdvancedToolsLink } from "./store-cards";+import { connectionNameForCredentialPolicy, connectionTypeLabel } from "./connection-identity";import {ConnectionOwnerIdentity,connectionDisplayNameForOwner,@@ -71,6 +73,7 @@ type AppRow = {actionCount: number;lastUsedAt: Date | string | null;logoUrl?: string | null;+ darkLogoUrl?: string | null;};/**@@ -232,10 +235,11 @@ export function Connections() {return applications.flatMap((application): AppRow[] => {const appConnections = connectionsByApplication.get(application.id) ?? [];const appSourceSlug = appApplicationSourceSlug(application);- const galleryEntry = logoByKey.get(appSourceSlug ?? "") ??+ const resolvedGalleryEntry = logoByKey.get(appSourceSlug ?? "") ??logoByName.get(application.name.toLowerCase());- const logoUrl = appDefinitionLogoUrl(galleryEntry);+ const logoUrl = appDefinitionLogoUrl(resolvedGalleryEntry);const brandKey = appSourceSlug ?? application.name;+ const darkLogoUrl = appDefinitionDarkLogoUrl(resolvedGalleryEntry);const agentAvailableConnectionCount = appConnections.filter((connection) => connection.status === "active" && connection.enabled,).length;@@ -251,14 +255,22 @@ export function Connections() {actionCount: 0,lastUsedAt: null,logoUrl,+ darkLogoUrl,}];}return appConnections.map((connection) => {const owner = connectionOwnerProfile(connection, userProfileById);+ const type = connectionTypeLabel(connection.credentialPolicy);+ const displayName = type === "Company"+ ? connectionNameForCredentialPolicy(+ humanizeConnectionDisplayName(connection),+ connection.credentialPolicy,+ )+ : connectionDisplayNameForOwner(connection, application.name, owner);return {application,connection,- displayName: connectionDisplayNameForOwner(connection, application.name, owner),+ displayName,brandKey,owner,remainingAgentAvailableConnectionCount: Math.max(@@ -270,6 +282,7 @@ export function Connections() {actionCount: actionCountByConnection.get(`app:${connection.id}`) ?? 0,lastUsedAt: connection.lastUsedAt ?? null,logoUrl,+ darkLogoUrl,};});});@@ -362,6 +375,7 @@ export function Connections() {<thead><tr className="border-b border-border bg-muted/40 text-left text-(length:--text-micro) font-semibold uppercase tracking-wide text-muted-foreground"><th className="px-4 py-2.5">Connection</th>+ <th className="px-4 py-2.5">Type</th><th className="px-4 py-2.5">Connected by</th><th className="px-4 py-2.5">Status</th><th className="px-4 py-2.5">Actions</th>@@ -408,12 +422,13 @@ export function Connections() {name={row.displayName}brandKey={row.brandKey}logoUrl={row.logoUrl}+ darkLogoUrl={row.darkLogoUrl}size={32}/><div className="min-w-0"><div className="flex flex-wrap items-center gap-2"><span className="font-medium text-foreground">{row.displayName}</span>- <ComposioProvenanceChip connection={row.connection} />+ <ConnectionProvenanceChip connection={row.connection} /></div>{hint && (<div className="truncate text-xs text-muted-foreground">{hint}</div>@@ -421,6 +436,11 @@ export function Connections() {</div></div></td>+ <td className="px-4 py-3">+ <span className="text-xs font-medium text-foreground">+ {connection ? connectionTypeLabel(connection.credentialPolicy) : "—"}+ </span>+ </td><td className="px-4 py-3"><ConnectionOwnerIdentity owner={row.owner} /></td>diff --git a/ui/src/pages/apps/agent-selector-contract.test.ts b/ui/src/pages/apps/agent-selector-contract.test.tsindex a6ae2a577f..de0e9f64b6 100644--- a/ui/src/pages/apps/agent-selector-contract.test.ts+++ b/ui/src/pages/apps/agent-selector-contract.test.ts@@ -8,12 +8,14 @@ function source(relativePath: string) {describe("Apps agent selector contract", () => {it("keeps every agent chooser under /apps searchable", () => {const appConnect = source("./AppsConnect.tsx");+ const connectionSetupFlow = source("../../features/connections/ConnectionSetupFlow.tsx");const permissions = source("./app-detail/PermissionsPanel.tsx");const tester = source("./app-detail/TestPanel.tsx");const profiles = source("../tools/ProfilesTab.tsx");const audit = source("../tools/AuditTab.tsx");- expect(appConnect).toContain("<AgentMultiSelect");+ expect(appConnect).toContain("<ConnectionSetupFlow");+ expect(connectionSetupFlow).toContain("<AgentMultiSelect");expect(permissions).toContain("<AgentMultiSelect");expect(tester).toContain('placeholder="Search agents…"');diff --git a/ui/src/pages/apps/app-connect-policy.test.ts b/ui/src/pages/apps/app-connect-policy.test.tsindex 0c7d0b9ebd..1b9f11175e 100644--- a/ui/src/pages/apps/app-connect-policy.test.ts+++ b/ui/src/pages/apps/app-connect-policy.test.ts@@ -1,30 +1,73 @@+import { APP_STORE_DEFINITIONS, appSupportsCatalogSetup } from "@paperclipai/shared";import { describe, expect, it } from "vitest";import {MCP_DIRECT_OAUTH_CONNECT_SLUGS,appSourceConnectHref,+ appSourceResumeHref,canEnterAppsConnect,isMcpDirectOAuthConnectSlug,+ resolveAppsConnectRouteKey,+ vercelConnectSourceHref,} from "./app-connect-policy";describe("app connect policy", () => {- it("allowlists exactly Notion for MCP-direct OAuth", () => {- expect(MCP_DIRECT_OAUTH_CONNECT_SLUGS).toEqual(["notion"]);+ it("derives automatic OAuth entry points from app capabilities", () => {+ expect(MCP_DIRECT_OAUTH_CONNECT_SLUGS).toEqual(expect.arrayContaining(["jira", "notion", "sentry"]));expect(isMcpDirectOAuthConnectSlug("notion")).toBe(true);+ expect(isMcpDirectOAuthConnectSlug("jira")).toBe(true);+ expect(isMcpDirectOAuthConnectSlug("asana")).toBe(false);expect(isMcpDirectOAuthConnectSlug("github")).toBe(false);expect(isMcpDirectOAuthConnectSlug("slack")).toBe(false);expect(isMcpDirectOAuthConnectSlug(null)).toBe(false);});- it("admits the Notion deep link without opening other source slugs", () => {+ it("admits every capability-backed catalog deep link", () => {expect(canEnterAppsConnect(new URLSearchParams("source=notion"))).toBe(true);+ expect(canEnterAppsConnect(new URLSearchParams("source=jira"))).toBe(true);+ expect(canEnterAppsConnect(new URLSearchParams("source=asana"))).toBe(true);expect(canEnterAppsConnect(new URLSearchParams("source=github"))).toBe(false);- expect(canEnterAppsConnect(new URLSearchParams("source=zapier"))).toBe(false);+ expect(canEnterAppsConnect(new URLSearchParams("source=context7"))).toBe(false);+ expect(canEnterAppsConnect(new URLSearchParams("source=zapier"))).toBe(true);+ expect(canEnterAppsConnect(new URLSearchParams("source=unknown"))).toBe(false);expect(canEnterAppsConnect(new URLSearchParams("byo=1&source=zapier"))).toBe(true);});+ it("admits retained hidden-provider reconnects without opening fresh setup", () => {+ expect(canEnterAppsConnect(new URLSearchParams("source=github"))).toBe(false);+ expect(canEnterAppsConnect(new URLSearchParams("source=github&reconnect=connection-1"))).toBe(true);+ expect(canEnterAppsConnect(new URLSearchParams("source=unknown&reconnect=connection-1"))).toBe(false);+ });+it("builds a generic source deep link", () => {expect(appSourceConnectHref("notion")).toBe("/apps/connect?source=notion");expect(appSourceConnectHref("notion", "intent-1")).toBe("/apps/connect?source=notion&intent=intent-1");+ expect(appSourceResumeHref("notion", "11111111-1111-4111-8111-111111111111")).toBe(+ "/apps/connect?source=notion&resume=11111111-1111-4111-8111-111111111111",+ );+ expect(vercelConnectSourceHref()).toBe("/apps/vercel-connect");+ expect(vercelConnectSourceHref("notion")).toBe("/apps/vercel-connect?source=notion");+ });++ it("routes every capability-backed catalog definition through its source deep link", () => {+ const connectableApps = APP_STORE_DEFINITIONS.filter(appSupportsCatalogSetup);++ expect(connectableApps.length).toBeGreaterThan(0);+ for (const app of connectableApps) {+ const href = appSourceConnectHref(app.slug);+ const searchParams = new URL(href, "http://paperclip.test").searchParams;++ expect(canEnterAppsConnect(searchParams), app.slug).toBe(true);+ expect(resolveAppsConnectRouteKey({ sourceSlug: searchParams.get("source") }), app.slug).toBe(app.slug);+ }+ });++ it("preserves explicit route precedence while accepting every authentication mode", () => {+ expect(resolveAppsConnectRouteKey({ serviceSlug: "jira", appKey: "asana", sourceSlug: "mem0" })).toBe("jira");+ expect(resolveAppsConnectRouteKey({ appKey: "asana", sourceSlug: "mem0" })).toBe("asana");+ expect(resolveAppsConnectRouteKey({ sourceSlug: "mem0" })).toBe("mem0");+ expect(resolveAppsConnectRouteKey({ sourceSlug: "context7" })).toBe("context7");+ expect(resolveAppsConnectRouteKey({ sourceSlug: "supabase" })).toBe("supabase");+ expect(resolveAppsConnectRouteKey({})).toBeUndefined();});});diff --git a/ui/src/pages/apps/app-connect-policy.ts b/ui/src/pages/apps/app-connect-policy.tsindex 643378cc46..70a7403534 100644--- a/ui/src/pages/apps/app-connect-policy.ts+++ b/ui/src/pages/apps/app-connect-policy.ts@@ -1,5 +1,17 @@-/** OAuth apps that are safe to connect directly through the MCP OAuth broker. */-export const MCP_DIRECT_OAUTH_CONNECT_SLUGS = ["notion"] as const;+import {+ APP_STORE_DEFINITIONS,+ appSupportsCatalogSetup,+ connectionMethodSupportsAutomaticOAuth,+ getAvailableConnectionMethods,+ getAppStoreDefinition,+ getConnectableAppDefinition,+} from "@paperclipai/shared";++export const MCP_DIRECT_OAUTH_CONNECT_SLUGS = APP_STORE_DEFINITIONS+ .filter((app) => getAvailableConnectionMethods(app).some((method) =>+ connectionMethodSupportsAutomaticOAuth(method)+ ))+ .map((app) => app.slug);export function isMcpDirectOAuthConnectSlug(slug: string | null | undefined): boolean {return MCP_DIRECT_OAUTH_CONNECT_SLUGS.some((allowedSlug) => allowedSlug === slug);@@ -11,6 +23,31 @@ export function appSourceConnectHref(slug: string, interactionId?: string | nullreturn `/apps/connect?${params.toString()}`;}+/** Resume one exact draft through the same setup wizard used for a new app. */+export function appSourceResumeHref(slug: string, connectionId: string): string {+ return `/apps/connect?${new URLSearchParams({ source: slug, resume: connectionId }).toString()}`;+}++export function vercelConnectSourceHref(slug?: string): string {+ if (!slug) return "/apps/vercel-connect";+ return `/apps/vercel-connect?${new URLSearchParams({ source: slug }).toString()}`;+}++export function resolveAppsConnectRouteKey(input: {+ serviceSlug?: string | null;+ appKey?: string | null;+ sourceSlug?: string | null;+}): string | undefined {+ return input.serviceSlug ?? input.appKey ?? input.sourceSlug ?? undefined;+}+export function canEnterAppsConnect(searchParams: URLSearchParams): boolean {- return searchParams.get("byo") === "1" || isMcpDirectOAuthConnectSlug(searchParams.get("source"));+ if (searchParams.get("byo") === "1") return true;+ const source = searchParams.get("source") ?? "";+ const entry = getAppStoreDefinition(source);+ // A retained connection may belong to a provider hidden from fresh catalog+ // setup. Admit only known providers here; the setup flow then proves the+ // exact reconnect target is visible to the selected company before rendering.+ if (getConnectableAppDefinition(source) && searchParams.get("reconnect")?.trim()) return true;+ return appSupportsCatalogSetup(entry);}diff --git a/ui/src/pages/apps/app-definition-display.ts b/ui/src/pages/apps/app-definition-display.tsindex 44cf627e63..77740ad910 100644--- a/ui/src/pages/apps/app-definition-display.ts+++ b/ui/src/pages/apps/app-definition-display.ts@@ -23,6 +23,10 @@ export function appDefinitionLogoUrl(entry: AppGalleryDisplayEntry | null | undereturn entry?.branding?.logoUrl ?? entry?.logoUrl;}+export function appDefinitionDarkLogoUrl(entry: AppGalleryDisplayEntry | null | undefined): string | undefined {+ return entry?.branding?.darkLogoUrl;+}+export function appApplicationSourceSlug(application: ToolApplication | null | undefined): string | null {if (!application) return null;const metadata = application.metadata;diff --git a/ui/src/pages/apps/app-detail/ActivityPanel.tsx b/ui/src/pages/apps/app-detail/ActivityPanel.tsxindex ae28488ba5..350e5a2248 100644--- a/ui/src/pages/apps/app-detail/ActivityPanel.tsx+++ b/ui/src/pages/apps/app-detail/ActivityPanel.tsx@@ -74,9 +74,9 @@ function RecentActivity({}, [events, lifecycleEvents, issues, actionRequests, nameById, connectionId, appName, userLabelById]);return (- <section className="space-y-2">+ <section className="space-y-5"><div>- <h2 className="text-sm font-bold text-foreground">Recent activity</h2>+ <h2 className="text-lg font-semibold text-foreground">Recent activity</h2></div>{loading ? (<div className="space-y-2 py-4">diff --git a/ui/src/pages/apps/app-detail/AdvancedPanel.render.test.tsx b/ui/src/pages/apps/app-detail/AdvancedPanel.render.test.tsxindex 8e2f6b6ec8..1253193821 100644--- a/ui/src/pages/apps/app-detail/AdvancedPanel.render.test.tsx+++ b/ui/src/pages/apps/app-detail/AdvancedPanel.render.test.tsx@@ -37,24 +37,40 @@ function renderComposioDangerZone() {return container;}+function expandDangerZone(node: HTMLDivElement) {+ const trigger = Array.from(node.querySelectorAll("button"))+ .find((button) => button.textContent?.includes("Danger zone"));+ expect(trigger).toBeTruthy();+ act(() => trigger!.dispatchEvent(new MouseEvent("click", { bubbles: true })));+}+/*** Remove app deletes the operator's credentials and revokes agent access- * (PAP-17119). The confirmation has to say so before the operator commits — a- * "you can connect it again later" reassurance implies the pasted key survives,- * so these assertions exist to stop that copy coming back.+ * (PAP-17119). The compact confirmation still names both effects before the+ * operator commits.*/describe("DangerZone", () => {+ it("keeps dangerous actions folded by default", () => {+ const node = renderDangerZone();++ expect(node.textContent).toContain("Danger zone");+ expect(node.textContent).not.toContain("Remove app");+ expect(node.textContent).not.toContain("Deletes credentials");+ });+it("promises credential deletion and re-authentication before the operator confirms", () => {- const text = renderDangerZone().textContent ?? "";+ const node = renderDangerZone();+ expandDangerZone(node);+ const text = node.textContent ?? "";- expect(text).toContain("Deletes the saved credentials for PostHog");- expect(text).toContain("takes agent access away right away");- expect(text).toContain("needs a new sign-in or key");- expect(text).not.toContain("You can connect it again later");+ expect(text).toContain("Deletes credentials for PostHog");+ expect(text).toContain("removes agent access");+ expect(text).toContain("requires a new sign-in or key");});it("keeps the warning visible in the confirming state", () => {const node = renderDangerZone();+ expandDangerZone(node);const trigger = Array.from(node.querySelectorAll("button")).find((button) => button.textContent?.trim() === "Remove app");expect(trigger).toBeTruthy();@@ -63,13 +79,13 @@ describe("DangerZone", () => {const text = node.textContent ?? "";expect(text).toContain("Yes, remove it");- expect(text).toContain("Deletes the saved credentials for PostHog");- expect(text).toContain("needs a new sign-in or key");+ expect(text).toContain("Deletes credentials for PostHog");+ expect(text).toContain("requires a new sign-in or key");});it("names every child service that parent removal will take down", () => {const node = renderComposioDangerZone();- expect(node.textContent).toContain("removes 2 connected services");- expect(node.textContent).toContain("Agents lose access to all of them right away");+ expandDangerZone(node);+ expect(node.textContent).toContain("2 connected services");});});diff --git a/ui/src/pages/apps/app-detail/AdvancedPanel.tsx b/ui/src/pages/apps/app-detail/AdvancedPanel.tsxindex 36ea3ae9d3..280a809be3 100644--- a/ui/src/pages/apps/app-detail/AdvancedPanel.tsx+++ b/ui/src/pages/apps/app-detail/AdvancedPanel.tsx@@ -1,16 +1,29 @@import { useState } from "react";import { useMutation } from "@tanstack/react-query";-import { ArrowUpRight, Loader2, Lock } from "lucide-react";-import type { AppDefinition, ToolConnection } from "@paperclipai/shared";+import { ArrowUpRight, ChevronRight, Loader2, Lock } from "lucide-react";+import type {+ AppDefinition,+ ConnectionGrant,+ ToolConnection,+ ToolConnectionCredentialPolicy,+} from "@paperclipai/shared";import { credentialConfigPath, getAvailableConnectionMethod, humanizeConnectionDisplayName } from "@paperclipai/shared";import { toolsApi } from "@/api/tools";import { Button } from "@/components/ui/button";+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from "@/components/ui/collapsible";import { Input } from "@/components/ui/input";+import { ToggleSwitch } from "@/components/ui/toggle-switch";import { useToast } from "@/context/ToastContext";import { redactUrlSecrets } from "@/lib/redact-url-secrets";import { resolveAuthorizationTarget } from "@/lib/authorizationUrl";import { navigateTopLevel } from "@/lib/browserNavigation";+import { cn } from "@/lib/utils";import type { AppDetailSectionProps } from "./types";+import { RevokeGrantDialog } from "./IdentitiesSection";export function AdvancedPanel({connection,@@ -20,21 +33,56 @@ export function AdvancedPanel({removing,onRemove,onReplaced,+ canReplaceCredential = true,+ credentialUnavailableMessage = "You don't have permission to replace this identity's credential.",+ appToggleDisabled,+ onToggleApp,+ identityGrant = null,+ identityCurrentUserId = null,+ identityProviderName,+ credentialPolicy,+ identityActionPending = false,+ onReconnectIdentity,+ onRevokeIdentity,}: Pick<AppDetailSectionProps, "connection" | "appName" | "galleryEntry"> & {removing: boolean;childConnectionCount?: number;onRemove: () => void;onReplaced: () => void;+ canReplaceCredential?: boolean;+ credentialUnavailableMessage?: string;+ appToggleDisabled: boolean;+ onToggleApp: () => void;+ identityGrant?: ConnectionGrant | null;+ identityCurrentUserId?: string | null;+ identityProviderName?: string;+ credentialPolicy?: ToolConnectionCredentialPolicy;+ identityActionPending?: boolean;+ onReconnectIdentity?: () => void;+ onRevokeIdentity?: (grant: ConnectionGrant) => void;}) {return (- <div className="space-y-6">- <KeySection connection={connection} galleryEntry={galleryEntry} onReplaced={onReplaced} />+ <div className="space-y-4 border-t border-border pt-8"><TechnicalDetails connection={connection} /><DangerZoneappName={appName}+ connection={connection}+ galleryEntry={galleryEntry}childConnectionCount={childConnectionCount}removing={removing}onRemove={onRemove}+ onReplaced={onReplaced}+ canReplaceCredential={canReplaceCredential}+ credentialUnavailableMessage={credentialUnavailableMessage}+ toggleDisabled={appToggleDisabled}+ onToggleConnection={onToggleApp}+ identityGrant={identityGrant}+ identityCurrentUserId={identityCurrentUserId}+ identityProviderName={identityProviderName ?? appName}+ credentialPolicy={credentialPolicy}+ identityActionPending={identityActionPending}+ onReconnectIdentity={onReconnectIdentity}+ onRevokeIdentity={onRevokeIdentity}/></div>);@@ -44,10 +92,14 @@ function KeySection({connection,galleryEntry,onReplaced,+ canReplace,+ unavailableMessage,}: {connection: ToolConnection;galleryEntry: AppDefinition | null;onReplaced: () => void;+ canReplace: boolean;+ unavailableMessage: string;}) {const [open, setOpen] = useState(false);return (@@ -56,15 +108,15 @@ function KeySection({<div className="flex items-start gap-3"><Lock className="mt-0.5 h-4 w-4 text-muted-foreground" /><div>- <h2 className="text-sm font-bold text-foreground">Key</h2>- <p className="mt-0.5 text-sm text-muted-foreground">- Your key is stored securely. Replace it if it stopped working or you rotated it.+ <h2 className="text-sm font-medium text-foreground">Reconnect</h2>+ <p className="mt-0.5 text-xs text-muted-foreground">+ {canReplace ? "Replace the stored credential." : unavailableMessage}</p></div></div>- {!open && (+ {canReplace && !open && (<Button size="sm" variant="outline" onClick={() => setOpen(true)}>- Replace key+ Reconnect</Button>)}</div>@@ -89,14 +141,23 @@ export function ReconnectCard({connection,galleryEntry,onReconnected,+ canReconnect = true,+ reconnectUnavailableMessage,}: {connection: ToolConnection;galleryEntry: AppDefinition | null;onReconnected: () => void;+ canReconnect?: boolean;+ reconnectUnavailableMessage?: string;}) {const { pushToast } = useToast();const reconnectOAuth = useMutation({- mutationFn: () => toolsApi.startOAuth(connection.id),+ // Reconnect is not a new identity choice. Personal-only connections must+ // put the replacement token back on the signed-in user's existing grant;+ // shared and legacy fallback connections keep using the organization slot.+ mutationFn: () => connection.credentialPolicy === "per_user"+ ? toolsApi.startOAuth(connection.id, { asCurrentUser: true })+ : toolsApi.startOAuth(connection.id),onSuccess: ({ authorizationUrl }) => {// Reconnect navigates to the same discovered address a fresh connect does,// so it goes through the same gate (PAP-17099).@@ -114,20 +175,60 @@ export function ReconnectCard({tone: "error",}),});+ const verifyVercel = useMutation({+ mutationFn: () => toolsApi.checkConnectionHealth(connection.id),+ onSuccess: () => {+ pushToast({+ title: "Vercel credential verified",+ body: `${humanizeConnectionDisplayName(connection)} is back online.`,+ tone: "success",+ });+ onReconnected();+ },+ onError: (error) => pushToast({+ title: "Credential still needs attention",+ body: error instanceof Error ? error.message : "Review the connector in Vercel Connect and try again.",+ tone: "error",+ }),+ });const oauth = connection.authKind === "oauth";+ const managedByVercel = connection.credentialSource === "vercel_connect";return (- <div className="rounded-xl border border-amber-500/50 bg-amber-500/10 p-5">- <h2 className="text-sm font-bold text-amber-900 dark:text-amber-100">- {oauth ? "Reconnect required" : "This app needs reconnecting"}- </h2>- <p className="mt-1 text-sm text-amber-800 dark:text-amber-200">- {connection.healthMessage?.trim() || (oauth- ? "Authorization expired or was revoked. Sign in again to restore access."- : "The key stopped working. Paste a new one to get it back online.")}- </p>- <div className="mt-3">- {oauth ? (+ <div className="flex flex-col gap-4 rounded-lg border border-amber-500/50 bg-amber-500/10 px-4 py-3 sm:flex-row sm:items-center sm:justify-between">+ <div className="min-w-0">+ <h2 className="text-sm font-semibold text-amber-900 dark:text-amber-100">+ {oauth ? "Reconnect required" : "This app needs reconnecting"}+ </h2>+ <p className="mt-0.5 text-sm text-amber-800 dark:text-amber-200">+ {connection.healthMessage?.trim() || (oauth+ ? "Authorization expired or was revoked. Sign in again to restore access."+ : "The key stopped working. Paste a new one to get it back online.")}+ </p>+ </div>+ <div className="shrink-0">+ {!canReconnect ? (+ <p className="text-sm text-amber-800 dark:text-amber-200">+ {reconnectUnavailableMessage ?? "You don't have permission to reconnect this identity."}+ </p>+ ) : managedByVercel && !oauth ? (+ <div className="flex items-center gap-2">+ <Button type="button" size="sm" variant="outline" asChild>+ <a href="https://vercel.com/connect" target="_blank" rel="noreferrer">+ Manage in Vercel <ArrowUpRight className="ml-1.5 h-3.5 w-3.5" />+ </a>+ </Button>+ <Button+ type="button"+ size="sm"+ disabled={verifyVercel.isPending}+ onClick={() => verifyVercel.mutate()}+ >+ {verifyVercel.isPending && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}+ Check again+ </Button>+ </div>+ ) : oauth ? (<Buttontype="button"size="sm"@@ -209,6 +310,14 @@ function ReconnectForm({? fields.every((f) => f.required === false || (values[f.configPath]?.trim().length ?? 0) > 0): single.trim().length > 0;+ if (connection.credentialSource === "vercel_connect") {+ return (+ <p className="text-sm text-muted-foreground">+ Credentials for this connection are managed in Vercel Connect.+ </p>+ );+ }+return (<div className="space-y-3">{usesGallery ? (@@ -261,62 +370,214 @@ function ReconnectForm({}function TechnicalDetails({ connection }: { connection: ToolConnection }) {+ const [open, setOpen] = useState(false);return (- <section>- <h2 className="text-sm font-bold text-foreground">Technical details</h2>- <dl className="mt-3 grid gap-2 text-xs sm:grid-cols-(--gtc-59)">- <dt className="text-muted-foreground">Address</dt>- <dd className="break-all font-mono text-foreground">{connectionAddress(connection)}</dd>- <dt className="text-muted-foreground">Connection type</dt>- <dd className="text-foreground">{connectionTransportLabel(connection.transport)}</dd>- </dl>- </section>+ <Collapsible open={open} onOpenChange={setOpen} asChild>+ <section>+ <CollapsibleTrigger asChild>+ <button type="button" className="flex w-full items-center gap-3 py-1 text-left">+ <span className="min-w-0 flex-1 text-sm font-medium text-foreground">Connection details</span>+ <ChevronRight+ className={cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform", open && "rotate-90")}+ />+ </button>+ </CollapsibleTrigger>+ <CollapsibleContent>+ <dl className="mt-4 grid gap-2 pb-2 text-xs sm:grid-cols-(--gtc-59)">+ <dt className="text-muted-foreground">Address</dt>+ <dd className="break-all font-mono text-foreground">{connectionAddress(connection)}</dd>+ <dt className="text-muted-foreground">Type</dt>+ <dd className="text-foreground">{connectionTransportLabel(connection.transport)}</dd>+ </dl>+ </CollapsibleContent>+ </section>+ </Collapsible>);}export function DangerZone({appName,+ connection,+ galleryEntry = null,childConnectionCount = 0,removing,onRemove,+ onReplaced,+ canReplaceCredential = true,+ credentialUnavailableMessage = "You don't have permission to replace this identity's credential.",+ toggleDisabled = false,+ onToggleConnection,+ identityGrant = null,+ identityCurrentUserId = null,+ identityProviderName = appName,+ credentialPolicy,+ identityActionPending = false,+ onReconnectIdentity,+ onRevokeIdentity,}: {appName: string;+ connection?: ToolConnection;+ galleryEntry?: AppDefinition | null;childConnectionCount?: number;removing: boolean;onRemove: () => void;+ onReplaced?: () => void;+ canReplaceCredential?: boolean;+ credentialUnavailableMessage?: string;+ toggleDisabled?: boolean;+ onToggleConnection?: () => void;+ identityGrant?: ConnectionGrant | null;+ identityCurrentUserId?: string | null;+ identityProviderName?: string;+ credentialPolicy?: ToolConnectionCredentialPolicy;+ identityActionPending?: boolean;+ onReconnectIdentity?: () => void;+ onRevokeIdentity?: (grant: ConnectionGrant) => void;}) {+ const [open, setOpen] = useState(false);const [confirming, setConfirming] = useState(false);+ const [revokeTarget, setRevokeTarget] = useState<ConnectionGrant | null>(null);+ const paused = connection+ ? connection.enabled === false || connection.status === "disabled"+ : false;+return (- <section className="space-y-3">- <div className="text-sm font-bold text-destructive">- Danger zone- </div>- <div className="flex flex-wrap items-center justify-between gap-3">- <div>- <p className="text-sm font-medium text-foreground">Remove this app</p>- <p className="text-xs text-muted-foreground">- {childConnectionCount > 0- ? `Deletes the saved credentials for ${appName} and removes ${childConnectionCount} connected ${childConnectionCount === 1 ? "service" : "services"}. Agents lose access to all of them right away.`- : `Deletes the saved credentials for ${appName} and takes agent access away right away. Connecting it again later needs a new sign-in or key.`}- </p>- </div>- {confirming ? (- <div className="flex items-center gap-2">- <Button variant="ghost" size="sm" onClick={() => setConfirming(false)} disabled={removing}>- Cancel- </Button>- <Button variant="destructive" size="sm" onClick={onRemove} disabled={removing}>- {removing && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}- Yes, remove it- </Button>+ <Collapsible+ open={open}+ onOpenChange={(nextOpen) => {+ setOpen(nextOpen);+ if (!nextOpen) setConfirming(false);+ }}+ asChild+ >+ <section>+ <CollapsibleTrigger asChild>+ <button+ type="button"+ className="flex w-full items-center gap-3 py-1 text-left"+ >+ <span className="min-w-0 flex-1 text-sm font-medium text-destructive">Danger zone</span>+ <ChevronRight+ className={cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform", open && "rotate-90")}+ />+ </button>+ </CollapsibleTrigger>++ <CollapsibleContent>+ <div className="mt-3 divide-y divide-border border-t border-border">+ {connection && onToggleConnection ? (+ <div className="flex items-center justify-between gap-4 py-4">+ <h2 className="text-sm font-medium text-foreground">Pause connection</h2>+ <ToggleSwitch+ aria-label="Pause connection"+ checked={paused}+ disabled={toggleDisabled}+ onCheckedChange={onToggleConnection}+ size="lg"+ />+ </div>+ ) : null}++ {connection && connection.authKind !== "oauth" ? (+ <div className="py-4">+ <KeySection+ connection={connection}+ galleryEntry={galleryEntry}+ onReplaced={onReplaced ?? (() => undefined)}+ canReplace={canReplaceCredential}+ unavailableMessage={credentialUnavailableMessage}+ />+ </div>+ ) : null}++ {connection?.authKind === "oauth" && (onReconnectIdentity || !canReplaceCredential) ? (+ <div className="flex flex-wrap items-center justify-between gap-3 py-4">+ <div>+ <p className="text-sm font-medium text-foreground">Reconnect</p>+ <p className="text-xs text-muted-foreground">+ {canReplaceCredential+ ? `Sign in to ${identityProviderName} again.`+ : credentialUnavailableMessage}+ </p>+ </div>+ {canReplaceCredential && onReconnectIdentity ? (+ <Button+ size="sm"+ variant="outline"+ disabled={identityActionPending}+ onClick={onReconnectIdentity}+ >+ {identityActionPending ? <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" /> : null}+ Reconnect+ </Button>+ ) : null}+ </div>+ ) : null}++ {identityGrant?.capabilities?.canRevoke+ && identityGrant.status !== "revoked"+ && onRevokeIdentity ? (+ <div className="flex flex-wrap items-center justify-between gap-3 py-4">+ <div>+ <p className="text-sm font-medium text-foreground">Revoke identity</p>+ <p className="text-xs text-muted-foreground">+ Disconnect the identity currently used by this app.+ </p>+ </div>+ <Button+ variant="destructive"+ size="sm"+ onClick={() => setRevokeTarget(identityGrant)}+ >+ Revoke+ </Button>+ </div>+ ) : null}++ <div className="flex flex-wrap items-center justify-between gap-3 py-4">+ <div>+ <p className="text-sm font-medium text-foreground">Remove this app</p>+ <p className="text-xs text-muted-foreground">+ {childConnectionCount > 0+ ? `Deletes credentials for ${appName} and ${childConnectionCount} connected ${childConnectionCount === 1 ? "service" : "services"}.`+ : `Deletes credentials for ${appName} and removes agent access. Reconnecting requires a new sign-in or key.`}+ </p>+ </div>+ {confirming ? (+ <div className="flex items-center gap-2">+ <Button variant="ghost" size="sm" onClick={() => setConfirming(false)} disabled={removing}>+ Cancel+ </Button>+ <Button variant="destructive" size="sm" onClick={onRemove} disabled={removing}>+ {removing && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}+ Yes, remove it+ </Button>+ </div>+ ) : (+ <Button variant="destructive" size="sm" onClick={() => setConfirming(true)}>+ Remove app+ </Button>+ )}+ </div></div>- ) : (- <Button variant="destructive" size="sm" onClick={() => setConfirming(true)}>- Remove app- </Button>- )}- </div>- </section>+ </CollapsibleContent>++ {revokeTarget && credentialPolicy ? (+ <RevokeGrantDialog+ grant={revokeTarget}+ providerName={identityProviderName}+ pending={identityActionPending}+ credentialPolicy={credentialPolicy}+ isOwnIdentity={revokeTarget.kind === "user" && revokeTarget.subjectUserId === identityCurrentUserId}+ onCancel={() => setRevokeTarget(null)}+ onConfirm={() => {+ onRevokeIdentity?.(revokeTarget);+ setRevokeTarget(null);+ }}+ />+ ) : null}+ </section>+ </Collapsible>);}diff --git a/ui/src/pages/apps/app-detail/IdentitiesSection.tsx b/ui/src/pages/apps/app-detail/IdentitiesSection.tsxindex 9d20e456a6..ea31e022ce 100644--- a/ui/src/pages/apps/app-detail/IdentitiesSection.tsx+++ b/ui/src/pages/apps/app-detail/IdentitiesSection.tsx@@ -1,5 +1,5 @@import { useEffect, useMemo, useState, type ReactNode } from "react";-import { ChevronRight, Loader2 } from "lucide-react";+import { Building2, Loader2, UserRound } from "lucide-react";import type {ConnectionAudienceMember,ConnectionGrant,@@ -7,10 +7,10 @@ import type {ToolConnectionCredentialPolicy,} from "@paperclipai/shared";import { Button } from "@/components/ui/button";+import { Identity } from "@/components/Identity";import { Skeleton } from "@/components/ui/skeleton";import { InlineBanner } from "@/components/InlineBanner";import { MemberMultiSelect } from "@/components/MemberMultiSelect";-import { AgentMultiSelect } from "@/components/AgentMultiSelect";import { RadioCardGroup } from "@/components/ui/radio-card";import {Dialog,@@ -33,14 +33,12 @@ import {import { cn } from "@/lib/utils";import { brandChipBadge } from "@/lib/status-colors";import {- audienceSummary,audienceUserIds,grantAccountLabel,grantStatusLabel,grantStatusTone,memberLabel,organizationGrant,- otherPersonalGrants,personalGrantFor,type GrantStatusTone,} from "../connection-identity";@@ -66,69 +64,43 @@ function StatusText({ status }: { status: ConnectionGrant["status"] | null }) {);}-function formatLastUsed(value: ConnectionGrant["lastUsedAt"]): string | null {- if (!value) return null;- const parsed = value instanceof Date ? value : new Date(value);- if (Number.isNaN(parsed.getTime())) return null;- return `Last used ${parsed.toLocaleDateString(undefined, { month: "short", day: "numeric" })}`;-}-/**- * Identity rows for the connection Setup tab (PAP-17835 Surface B).+ * Fixed identity for the connection Setup tab.*- * Rows are separated by space and a rule, not wrapped in one card each: "space- * separates; lines contain". Every action here is rendered from a server- * capability — a policy-forbidden action is absent rather than disabled, so a- * viewer sees the same legible state with no controls at all.+ * The chosen personal/organization type comes from the connection policy and+ * the alternative is not rendered after setup. Every action is rendered from+ * a server capability — a policy-forbidden action is absent rather than+ * disabled, so a viewer sees the same legible state with no controls at all.*/export function IdentitiesSection({appName,- providerName,credentialPolicy,+ ownerUserId,+ connectedUser,grantsQuery,- agents,- agentsLoading,- agentsError,loading,error,onConnectAsMe,onConnectOrganization,- onReconnectOrganization,- onRevokeGrant,onReplaceAudience,connectPending,- revokePending,- delegationPending,audiencePending,audienceError,audienceGrantId,onOpenAudience,onCloseAudience,- onReplaceDelegations,}: {appName: string;- providerName: string;credentialPolicy: ToolConnectionCredentialPolicy;+ ownerUserId: string | null;+ connectedUser: { label: string; image: string | null } | null;grantsQuery: ConnectionGrantsResponse | undefined;- agents: Array<{- id: string;- name: string;- title?: string | null;- icon?: string | null;- status: string;- }>;- agentsLoading: boolean;- agentsError: boolean;loading: boolean;error: boolean;onConnectAsMe: () => void;onConnectOrganization: () => void;- onReconnectOrganization: () => void;- onRevokeGrant: (grant: ConnectionGrant) => void;onReplaceAudience: (grant: ConnectionGrant, memberUserIds: string[]) => void;connectPending: boolean;- revokePending: boolean;- delegationPending: boolean;audiencePending: boolean;audienceError: string | null;/**@@ -139,36 +111,43 @@ export function IdentitiesSection({audienceGrantId: string | null;onOpenAudience: (grantId: string) => void;onCloseAudience: () => void;- onReplaceDelegations: (grant: ConnectionGrant, agentIds: string[]) => void;}) {- const [revokeTarget, setRevokeTarget] = useState<ConnectionGrant | null>(null);- const [othersExpanded, setOthersExpanded] = useState(false);-const grants = grantsQuery?.grants ?? [];const capabilities = grantsQuery?.capabilities;const currentUserId = grantsQuery?.currentUserId ?? null;const members = grantsQuery?.members ?? [];const orgGrant = useMemo(() => organizationGrant(grants), [grants]);const myGrant = useMemo(() => personalGrantFor(grants, currentUserId), [grants, currentUserId]);- const others = useMemo(() => otherPersonalGrants(grants, currentUserId), [grants, currentUserId]);- const myLabel = memberLabel(members, currentUserId);+ const personalGrant = useMemo(() => {+ const personalGrants = grants.filter((grant) => grant.kind === "user");+ return personalGrants.find((grant) => grant.subjectUserId === ownerUserId)+ ?? myGrant+ ?? personalGrants.find((grant) => grant.status === "active")+ ?? personalGrants[0]+ ?? null;+ }, [grants, myGrant, ownerUserId]);+ const personalSubjectLabel = memberLabel(+ members,+ personalGrant?.subjectUserId ?? ownerUserId ?? currentUserId,+ );+ const usesPersonalIdentity = credentialPolicy === "per_user"+ || (credentialPolicy === "per_user_with_fallback" && Boolean(myGrant));const audienceGrant = audienceGrantId? grants.find((grant) => grant.id === audienceGrantId) ?? null: null;if (loading) {return (- <section className="space-y-3" aria-busy="true">+ <section className="space-y-5" aria-busy="true"><IdentitiesHeading /><Skeleton className="h-14 w-full" />- <Skeleton className="h-14 w-full" /></section>);}if (error) {return (- <section className="space-y-3">+ <section className="space-y-5"><IdentitiesHeading /><InlineBanner tone="warning" compact>We couldn't load who this connection acts as. Reload the page to try again.@@ -178,157 +157,55 @@ export function IdentitiesSection({}return (- <section>+ <section className="space-y-5"><IdentitiesHeading />- {agentsError ? (- <div className="mt-3">- <InlineBanner tone="warning" compact>- We couldn't load agents for autonomous access. Reload the page to try again.- </InlineBanner>- </div>- ) : null}-- <div className="mt-4 divide-y divide-border">- {/* Organization identity — always visible, including when missing, so the- shared-vs-personal distinction never has to be inferred from absence. */}- <IdentityRow- title="Organization identity"- secondary={grantAccountLabel(orgGrant)}- status={orgGrant?.status ?? null}- detail={orgGrant- ? audienceSummary(orgGrant)- : "Used when the connection policy allows a shared identity."}- actions={- <>- {orgGrant?.capabilities?.canEditAudience ? (- <Button size="sm" variant="outline" onClick={() => onOpenAudience(orgGrant.id)}>- Manage audience- </Button>- ) : null}- {orgGrant && capabilities?.canConfigure ? (- <Button- size="sm"- variant="outline"- disabled={connectPending}- onClick={onReconnectOrganization}- >- Reconnect- </Button>- ) : null}- {orgGrant?.capabilities?.canRevoke && orgGrant.status !== "revoked" ? (- <Button size="sm" variant="outline" onClick={() => setRevokeTarget(orgGrant)}>- Revoke- </Button>- ) : null}- {!orgGrant && capabilities?.canCreateOrganizationGrant ? (- <Button size="sm" disabled={connectPending} onClick={onConnectOrganization}>- Connect organization identity- </Button>- ) : null}- </>- }- />+ <ConnectionAudienceCallout+ personal={usesPersonalIdentity}+ connectedName={usesPersonalIdentity ? personalSubjectLabel ?? connectedUser?.label ?? null : null}+ connectedImage={usesPersonalIdentity ? connectedUser?.image ?? null : null}+ status={(usesPersonalIdentity ? personalGrant : orgGrant)?.status ?? null}+ />- {/* Your identity — the signed-in user only. Audience is never shown here:- a personal identity is consent-bound to the person who granted it. */}- {capabilities?.canConnectAsCurrentUser || myGrant ? (- <IdentityRow- id="personal-identity"- title="Your identity"- secondary={myGrant ? grantAccountLabel(myGrant, { subjectLabel: myLabel }) : null}- status={myGrant?.status ?? null}- detail={myGrant- ? formatLastUsed(myGrant.lastUsedAt) ?? "Only work running for you can use this identity."- : "You have not connected your account."}- actions={- <>- {myGrant && myGrant.status !== "revoked" ? (- <>- <Button size="sm" variant="outline" disabled={connectPending} onClick={onConnectAsMe}>- Reconnect- </Button>- {myGrant.capabilities?.canRevoke ? (- <Button size="sm" variant="outline" onClick={() => setRevokeTarget(myGrant)}>- Revoke- </Button>- ) : null}- {myGrant.status === "active" ? (- <AgentMultiSelect- agents={agents.filter((agent) => agent.status !== "terminated")}- loading={agentsLoading}- selectedAgentIds={new Set(- (myGrant.delegations ?? []).map((delegation) => delegation.agentId),- )}- pending={delegationPending}- triggerLabel={(myGrant.delegations?.length ?? 0) === 0- ? "Allow autonomous access"- : `${myGrant.delegations?.length ?? 0} ${myGrant.delegations?.length === 1 ? "agent" : "agents"} allowed for autonomous runs`}- triggerSize="sm"- triggerFullWidth={false}- showSelectionPreview={false}- headerContent={(- <p className="mt-2 text-xs text-muted-foreground">- Select the named agents that may use your identity in autonomous runs.- </p>- )}- onSave={(agentIds) => onReplaceDelegations(myGrant, [...agentIds])}- />- ) : null}- </>- ) : capabilities?.canConnectAsCurrentUser ? (+ <div>+ {usesPersonalIdentity ? (+ personalGrant ? null : (+ <IdentityRow+ id="personal-identity"+ title="Personal account"+ status={null}+ detail="Personal identity"+ actions={capabilities?.canConnectAsCurrentUser ? (<Button size="sm" disabled={connectPending} onClick={onConnectAsMe}>{connectPending ? <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" /> : null}Connect as me</Button>) : null}- </>- }- />- ) : null}- </div>-- {/* Manager oversight. A regular member never sees this list — the server- omits the grants entirely, so there is nothing to hide client-side. */}- {capabilities?.canViewOtherPersonalIdentities && others.length > 0 ? (- <div className="mt-4 border-t border-border pt-3">- <button- type="button"- className="flex w-full items-center gap-1.5 text-left text-sm text-muted-foreground hover:text-foreground"- aria-expanded={othersExpanded}- onClick={() => setOthersExpanded((open) => !open)}- >- <span className="flex-1">Other personal identities · {others.length}</span>- <ChevronRight- className={cn("h-4 w-4 transition-transform", othersExpanded && "rotate-90")}/>- </button>- {othersExpanded ? (- <div className="mt-2 divide-y divide-border">- {others.map((grant) => (- <div key={grant.id} className="flex flex-wrap items-center gap-3 py-2">- <div className="min-w-0 flex-1">- <div className="truncate text-sm text-foreground">- {grantAccountLabel(grant, {- subjectLabel: memberLabel(members, grant.subjectUserId),- })}- </div>- {formatLastUsed(grant.lastUsedAt) ? (- <div className="text-xs text-muted-foreground">{formatLastUsed(grant.lastUsedAt)}</div>- ) : null}- </div>- <StatusText status={grant.status} />- {grant.capabilities?.canRevoke && grant.status !== "revoked" ? (- <Button size="sm" variant="outline" onClick={() => setRevokeTarget(grant)}>- Revoke- </Button>- ) : null}- </div>- ))}- </div>- ) : null}- </div>- ) : null}+ )+ ) : (+ orgGrant ? (+ orgGrant.capabilities?.canEditAudience ? (+ <div className="flex justify-end">+ <Button size="sm" variant="outline" onClick={() => onOpenAudience(orgGrant.id)}>+ Manage access+ </Button>+ </div>+ ) : null+ ) : (+ <IdentityRow+ title="Organization account"+ status={null}+ detail="Organization identity"+ actions={capabilities?.canCreateOrganizationGrant ? (+ <Button size="sm" disabled={connectPending} onClick={onConnectOrganization}>+ Connect organization identity+ </Button>+ ) : null}+ />+ )+ )}+ </div>{audienceGrant ? (<AudienceDialog@@ -342,31 +219,44 @@ export function IdentitiesSection({/>) : null}- {revokeTarget ? (- <RevokeGrantDialog- grant={revokeTarget}- providerName={providerName}- pending={revokePending}- credentialPolicy={credentialPolicy}- isOwnIdentity={revokeTarget.kind === "user" && revokeTarget.subjectUserId === currentUserId}- onCancel={() => setRevokeTarget(null)}- onConfirm={() => {- onRevokeGrant(revokeTarget);- setRevokeTarget(null);- }}- />- ) : null}</section>);}function IdentitiesHeading() {+ return <h2 className="text-sm font-semibold text-foreground">Account</h2>;+}++function ConnectionAudienceCallout({+ personal,+ connectedName,+ connectedImage,+ status,+}: {+ personal: boolean;+ connectedName: string | null;+ connectedImage: string | null;+ status: ConnectionGrant["status"] | null;+}) {+ const Icon = personal ? UserRound : Building2;return (- <div>- <h2 className="text-sm font-bold text-foreground">Identities</h2>- <p className="mt-0.5 text-sm text-muted-foreground">- Who agents act as when they use this connection.- </p>+ <div className="flex items-start gap-4 rounded-lg border border-border bg-card p-5">+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-muted text-foreground">+ <Icon className="h-5 w-5" />+ </div>+ <div className="min-w-0 space-y-3">+ <p className="text-lg font-semibold text-foreground">+ {personal+ ? "Only you can use this connection"+ : "Anyone in your company can use this connection"}+ </p>+ {connectedName && status !== null ? (+ <div className="flex flex-wrap items-center gap-2">+ <Identity name={connectedName} avatarUrl={connectedImage} />+ {status === "active" ? null : <StatusText status={status} />}+ </div>+ ) : null}+ </div></div>);}@@ -374,26 +264,23 @@ function IdentitiesHeading() {function IdentityRow({id,title,- secondary,status,detail,actions,}: {id?: string;title: string;- secondary: string | null;status: ConnectionGrant["status"] | null;detail: string | null;actions: ReactNode;}) {return (- <div id={id} className="flex flex-col gap-2 py-3 sm:flex-row sm:items-start sm:justify-between sm:gap-4">+ <div id={id} className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between sm:gap-8"><div className="min-w-0"><div className="flex flex-wrap items-center gap-2"><span className="text-sm font-semibold text-foreground">{title}</span>- <StatusText status={status} />+ {status === "active" ? null : <StatusText status={status} />}</div>- {secondary ? <div className="mt-0.5 truncate text-sm text-foreground">{secondary}</div> : null}{detail ? <div className="mt-0.5 text-xs text-muted-foreground">{detail}</div> : null}</div><div className="flex flex-wrap items-center gap-2">{actions}</div>diff --git a/ui/src/pages/apps/app-detail/PermissionsPanel.tsx b/ui/src/pages/apps/app-detail/PermissionsPanel.tsxindex c2d6e1cb1b..f53982d19f 100644--- a/ui/src/pages/apps/app-detail/PermissionsPanel.tsx+++ b/ui/src/pages/apps/app-detail/PermissionsPanel.tsx@@ -9,27 +9,26 @@ import { RadioCardGroup } from "@/components/ui/radio-card";import { cn } from "@/lib/utils";import { type InstallState } from "@/lib/tool-installs";import { QuarantinedActionsReview } from "./SetupPanel";-import type { AppDetailSectionProps } from "./types";+import {+ formatActionPermissionSummary,+ summarizeActionPermissions,+} from "./action-permission-summary";+import type { AccessDraft, AppDetailSectionProps } from "./types";type ActionPermission = "off" | "allowed" | "ask";/*** Permissions tab.*- * Agent availability is expressed **once** (PAP-17859). This panel used to- * stack a legacy "Who can use it" editor on top of "Available to agents",- * asking the reader to hold two overlapping models of the same fact and to- * guess which one wins. The install model — *Agents I pick / Any agent* — is- * now the single visible source of truth.- *- * The runtime distinction survives untouched: an install still authorizes its- * target server-side (`putConnectionInstalls` extends the app profile's- * bindings), so "installed ⊆ permitted" holds without a second editor. What is- * gone is the *user-facing* duplicate, and with it the hidden path that could- * widen access from a control the reader could not see.+ * Agent access and installs answer two different questions. Access decides who+ * may use the app when work needs it. Installs decide which agents load the app+ * on every run. Keeping the sections adjacent makes that distinction explicit+ * while preserving the server invariant that installed agents are permitted.*/export function PermissionsPanel({+ appName,agents,+ access,install,readOnly,canChange,@@ -38,6 +37,7 @@ export function PermissionsPanel({askFirstIds,pending,installPending,+ onSaveAccess,onSaveInstall,onSetActionPermission,onReviewQuarantined,@@ -46,10 +46,19 @@ export function PermissionsPanel({capabilities,}: Pick<AppDetailSectionProps,- "agents" | "readOnly" | "canChange" | "quarantined" | "enabledIds" | "askFirstIds" | "pending"+ | "appName"+ | "agents"+ | "access"+ | "readOnly"+ | "canChange"+ | "quarantined"+ | "enabledIds"+ | "askFirstIds"+ | "pending"> & {install: InstallState;installPending: boolean;+ onSaveAccess: (next: AccessDraft) => void;onSaveInstall: (next: InstallState) => void;onSetActionPermission: (id: string, next: ActionPermission) => void;onReviewQuarantined: (enabledIds: string[]) => void;@@ -63,14 +72,24 @@ export function PermissionsPanel({const [searchParams] = useSearchParams();const focusId = searchParams.get("focus");return (- <div className="space-y-6">- <AvailableToAgentsSection+ <div className="space-y-10">+ <AlwaysInstalledSection+ appName={appName}agents={agents}install={install}capabilities={capabilities}disabled={installPending}onSave={onSaveInstall}/>+ <AgentAccessSection+ appName={appName}+ agents={agents}+ access={access}+ install={install}+ capabilities={capabilities}+ disabled={pending}+ onSave={onSaveAccess}+ /><ActionsSectionreadOnly={readOnly}canChange={canChange}@@ -89,55 +108,168 @@ export function PermissionsPanel({);}-/**- * "Available to agents" (PAP-17835 Surface E).- *- * The old section exposed the runtime's own vocabulary — "permitted only",- * "installed", an auto-extend warning — which asked the reader to hold two- * overlapping concepts to answer one question. It is now the same two-choice- * model the create flow uses: pick agents, or any agent. The runtime- * distinction still exists in code; it just stopped being the user's problem.- *- * Every control is gated on a server capability. A viewer, or a member who may- * not configure this connection, sees the summary and the agent list with no- * controls at all rather than disabled ones.- */-function AvailableToAgentsSection({+function AgentAccessSection({+ appName,agents,+ access,install,capabilities,disabled,onSave,}: {+ appName: string;agents: Agent[];+ access: AccessDraft;install: InstallState;capabilities: ToolConnectionCapabilities | undefined;disabled: boolean;- onSave: (next: InstallState) => void;+ onSave: (next: AccessDraft) => void;}) {const liveAgents = agents.filter((a) => a.status !== "terminated");+ const canManage = capabilities?.canConfigure ?? false;+ const editableAgentIds = capabilities?.editableAgentIds;+ const selectableAgents = editableAgentIds+ ? liveAgents.filter((agent) => editableAgentIds.includes(agent.id))+ : liveAgents;+ const selectedAgents = liveAgents.filter((agent) => access.agentIds.has(agent.id));+ const requiredAgentIds = install.agentIds;+ const summary = access.mode === "all"+ ? "Any agent"+ : access.agentIds.size === 0+ ? "No agents"+ : `${access.agentIds.size} ${access.agentIds.size === 1 ? "agent" : "agents"}`;++ return (+ <section className="border-t border-border pt-8">+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div>+ <h2 className="text-lg font-semibold text-foreground">Agent access</h2>+ <p className="mt-1 text-sm text-muted-foreground">{summary}</p>+ <p className="mt-2 text-sm text-muted-foreground">+ Agents that may use {appName} when work needs it.+ </p>+ </div>+ {disabled && <span className="text-xs text-muted-foreground">Saving…</span>}+ </div>++ {canManage ? (+ <div className="space-y-3 pt-4">+ <RadioCardGroup+ ariaLabel="Which agents can use this connection"+ value={access.mode}+ disabled={disabled}+ className="sm:grid-cols-2"+ onValueChange={(next) => {+ if (next === "all") onSave({ mode: "all", agentIds: new Set() });+ else onSave({+ mode: "specific",+ agentIds: new Set([...access.agentIds, ...requiredAgentIds]),+ });+ }}+ options={[+ {+ value: "specific",+ title: "Agents I pick",+ description: install.onAll+ ? "Unavailable while installed for every agent."+ : "Only selected agents.",+ disabled: install.onAll,+ },+ {+ value: "all",+ title: "Any agent",+ description: "Available across your company.",+ },+ ]}+ />++ {access.mode === "specific" ? (+ <AgentMultiSelect+ agents={selectableAgents}+ selectedAgentIds={access.agentIds}+ disabled={disabled}+ triggerLabel={+ access.agentIds.size === 0+ ? "Choose agents"+ : `${access.agentIds.size} ${access.agentIds.size === 1 ? "agent" : "agents"} selected`+ }+ emptyMessage="You cannot edit any agents yet."+ isAgentDisabled={(agent) => requiredAgentIds.has(agent.id)}+ getDescription={(agent) => requiredAgentIds.has(agent.id) ? "Always installed" : agent.title}+ headerContent={requiredAgentIds.size > 0 ? (+ <p className="mt-2 text-xs text-muted-foreground">+ Always-installed agents keep access.+ </p>+ ) : null}+ onChange={(agentIds) => onSave({+ mode: "specific",+ agentIds: new Set([...agentIds, ...requiredAgentIds]),+ })}+ />+ ) : null}+ </div>+ ) : (+ // Read-only: the state is still fully legible, just not editable.+ <div className="pt-3">+ {access.mode === "all" ? (+ <p className="text-sm text-muted-foreground">Every agent can use this connection.</p>+ ) : selectedAgents.length === 0 ? (+ <p className="text-sm text-muted-foreground">No agents can use this connection.</p>+ ) : (+ <div className="space-y-0.5">+ {selectedAgents.map((agent) => (+ <div key={agent.id} className="flex items-center gap-2 px-1.5 py-1 text-sm">+ <AgentIcon icon={agent.icon ?? null} className="h-4 w-4 shrink-0 text-muted-foreground" />+ <span className="min-w-0 flex-1 truncate text-foreground">{agent.name}</span>+ </div>+ ))}+ </div>+ )}+ </div>+ )}+ </section>+ );+}++function AlwaysInstalledSection({+ appName,+ agents,+ install,+ capabilities,+ disabled,+ onSave,+}: {+ appName: string;+ agents: Agent[];+ install: InstallState;+ capabilities: ToolConnectionCapabilities | undefined;+ disabled: boolean;+ onSave: (next: InstallState) => void;+}) {+ const liveAgents = agents.filter((agent) => agent.status !== "terminated");const canManage = capabilities?.canManageAgentInstalls ?? false;const canSetCompanyWide = capabilities?.canSetCompanyInstall ?? false;- // "Agents I pick" is scoped to the agents this person may actually edit. The- // server decides that set; the client never infers it from a role string.const editableAgentIds = capabilities?.editableAgentIds;const selectableAgents = editableAgentIds? liveAgents.filter((agent) => editableAgentIds.includes(agent.id)): liveAgents;- const mode: "all" | "specific" = install.onAll ? "all" : "specific";const selectedAgents = liveAgents.filter((agent) => install.agentIds.has(agent.id));+ const mode: "all" | "specific" = install.onAll ? "all" : "specific";const summary = install.onAll- ? "Any agent"+ ? "Every agent": install.agentIds.size === 0- ? "No agents yet"+ ? "No agents": `${install.agentIds.size} ${install.agentIds.size === 1 ? "agent" : "agents"}`;return (<section><div className="flex flex-wrap items-start justify-between gap-3"><div>- <h2 className="text-sm font-bold text-foreground">Available to agents</h2>- <p className="mt-0.5 text-sm text-muted-foreground">{summary}</p>+ <h2 className="text-lg font-semibold text-foreground">Always installed</h2>+ <p className="mt-1 text-sm text-muted-foreground">{summary}</p>+ <p className="mt-2 text-sm text-muted-foreground">+ Loads {appName} on every run. Agent access only makes it available when needed.+ </p></div>{disabled && <span className="text-xs text-muted-foreground">Saving…</span>}</div>@@ -145,7 +277,7 @@ function AvailableToAgentsSection({{canManage ? (<div className="space-y-3 pt-4"><RadioCardGroup- ariaLabel="Which agents can use this connection"+ ariaLabel="Which agents always load this connection"value={mode}disabled={disabled}className="sm:grid-cols-2"@@ -157,14 +289,14 @@ function AvailableToAgentsSection({{value: "specific",title: "Agents I pick",- description: "Choose one or more agents you can edit.",+ description: "Always loaded for selected agents.",},{value: "all",- title: "Any agent",+ title: "Every agent",description: canSetCompanyWide- ? "Make this connection available to every agent."- : "Only someone who can configure this connection can choose this.",+ ? "Always loaded for current and future agents."+ : "Only a connection manager can choose this.",},].filter((option) => option.value !== "all" || canSetCompanyWide || install.onAll)}/>@@ -174,23 +306,20 @@ function AvailableToAgentsSection({agents={selectableAgents}selectedAgentIds={install.agentIds}disabled={disabled}- triggerLabel={- install.agentIds.size === 0- ? "Choose agents"- : `${install.agentIds.size} ${install.agentIds.size === 1 ? "agent" : "agents"} selected`- }+ triggerLabel={install.agentIds.size === 0+ ? "Choose agents"+ : `${install.agentIds.size} ${install.agentIds.size === 1 ? "agent" : "agents"} selected`}emptyMessage="You cannot edit any agents yet."onChange={(agentIds) => onSave({ onAll: false, agentIds })}/>) : null}</div>) : (- // Read-only: the state is still fully legible, just not editable.<div className="pt-3">{install.onAll ? (- <p className="text-sm text-muted-foreground">Every agent can use this connection.</p>+ <p className="text-sm text-muted-foreground">This connection is always loaded for every agent.</p>) : selectedAgents.length === 0 ? (- <p className="text-sm text-muted-foreground">No agents have this connection yet.</p>+ <p className="text-sm text-muted-foreground">This connection is not always loaded for any agent.</p>) : (<div className="space-y-0.5">{selectedAgents.map((agent) => (@@ -236,14 +365,16 @@ function ActionsSection({onRefreshActions: () => void;}) {return (- <section className="space-y-3">+ <section className="space-y-10 border-t border-border pt-8"><div className="flex flex-wrap items-center justify-between gap-2"><div>- <h2 className="text-sm font-bold text-foreground">Action permissions</h2>- <p className="mt-0.5 text-sm text-muted-foreground">- {canConfigure- ? "Choose what agents can do and what needs a human first."- : "What agents can do, and what needs a human first."}+ <h2 className="text-lg font-semibold text-foreground">Actions</h2>+ <p className="mt-1 text-sm text-muted-foreground">+ {formatActionPermissionSummary(summarizeActionPermissions(+ [...readOnly, ...canChange],+ enabledIds,+ askFirstIds,+ ))}</p></div>{/* Viewer rule D4: a forbidden action is omitted, not rendered disabled.@@ -278,8 +409,8 @@ function ActionsSection({)}<ActionGroup- title="Read only"- hint="Can look up context without changing anything."+ title={`Read (${readOnly.length})`}+ hint="Views data without changing it."actions={readOnly}enabledIds={enabledIds}askFirstIds={askFirstIds}@@ -289,8 +420,8 @@ function ActionsSection({onSetPermission={onSetPermission}/><ActionGroup- title="Can make changes"- hint="Can change something in another app."+ title={`Write (${canChange.length})`}+ hint="Creates or changes data."actions={canChange}enabledIds={enabledIds}askFirstIds={askFirstIds}@@ -339,9 +470,9 @@ function ActionGroup({if (actions.length === 0) return null;return (<div>- <div className="pb-2 text-sm">- <span className="font-bold text-foreground">{title}</span>- <span className="ml-2 text-muted-foreground">- {hint}</span>+ <div className="pb-4">+ <div className="text-lg font-semibold text-foreground">{title}</div>+ <div className="mt-1 text-sm text-muted-foreground">{hint}</div></div><div className="divide-y divide-border">{actions.map((action) => {diff --git a/ui/src/pages/apps/app-detail/ReviewPanel.tsx b/ui/src/pages/apps/app-detail/ReviewPanel.tsxindex 93c247e875..b93b35b04c 100644--- a/ui/src/pages/apps/app-detail/ReviewPanel.tsx+++ b/ui/src/pages/apps/app-detail/ReviewPanel.tsx@@ -14,7 +14,8 @@ export function ReviewPanel({const showsQuarantinedActions = quarantined.length > 0 && !!onReviewQuarantined;return (- <div className="space-y-4">+ <div className="space-y-6">+ <h2 className="text-lg font-semibold text-foreground">Review</h2>{showsQuarantinedActions ? (<QuarantinedActionsReviewentries={quarantined}diff --git a/ui/src/pages/apps/app-detail/SetupPanel.tsx b/ui/src/pages/apps/app-detail/SetupPanel.tsxindex 58e0406bd7..399fe9014d 100644--- a/ui/src/pages/apps/app-detail/SetupPanel.tsx+++ b/ui/src/pages/apps/app-detail/SetupPanel.tsx@@ -1,4 +1,5 @@import { useState, type ReactNode } from "react";+import { ChevronRight } from "lucide-react";import type { ToolCatalogEntry, ToolConnection } from "@paperclipai/shared";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";@@ -10,33 +11,38 @@ import { googleSheetsConfigWithAllowlist, parseGoogleSheetIds } from "../google-export function SetupPanel({connection,galleryEntry,- onToggleApp,- appToggleDisabled,onUpdateConfig,configUpdateDisabled,identities,+ agentsSummary,+ permissionsSummary,+ permissionsLoading,+ onOpenPermissions,}: Pick<AppDetailSectionProps,"connection" | "galleryEntry"> & {- onToggleApp: () => void;- appToggleDisabled: boolean;onUpdateConfig: (config: Record<string, unknown>) => void;configUpdateDisabled: boolean;/**- * The Identities section (PAP-17835). It replaces the old generic OAuth- * "workspace authorization" block, because that block could only ever describe- * one shared identity and this connection may act as each person instead.+ * The fixed Identity section. It replaces the old generic OAuth "workspace+ * authorization" block and shows the identity type chosen during setup.*/identities?: ReactNode;+ agentsSummary: string;+ permissionsSummary: string | null;+ permissionsLoading: boolean;+ onOpenPermissions: () => void;}) {- const description = galleryEntry?.description ?? null;return (- <div className="space-y-6">- {description && (- <p className="max-w-2xl text-sm leading-6 text-muted-foreground">{description}</p>- )}+ <div className="space-y-10">{identities}+ <SetupLinkSection title="Agents" summary={agentsSummary} onClick={onOpenPermissions} />+ <SetupLinkSection+ title="Actions"+ summary={permissionsLoading ? "Loading permissions…" : permissionsSummary ?? "Manage permissions"}+ onClick={onOpenPermissions}+ />{appDefinitionSlug(galleryEntry) === "google-sheets" && (<GoogleSheetsAllowlistSectionconnection={connection}@@ -47,11 +53,34 @@ export function SetupPanel({{appDefinitionSlug(galleryEntry) === "posthog" && (<PostHogConfigurationSection connection={connection} />)}- <AppLifecycleSection connection={connection} disabled={appToggleDisabled} onToggle={onToggleApp} /></div>);}+function SetupLinkSection({+ title,+ summary,+ onClick,+}: {+ title: string;+ summary: string;+ onClick: () => void;+}) {+ return (+ <section className="space-y-3">+ <h2 className="text-sm font-semibold text-foreground">{title}</h2>+ <button+ type="button"+ onClick={onClick}+ className="flex w-full items-center justify-between gap-4 rounded-lg border border-border px-4 py-3 text-left transition-colors hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <span className="min-w-0 text-sm text-muted-foreground">{summary}</span>+ <ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground" />+ </button>+ </section>+ );+}+/*** Provider label used in identity and revoke copy. Falls back to the app's own* display name so a pasted server never reads as a generic "OAuth".@@ -84,7 +113,7 @@ function PostHogConfigurationSection({ connection }: { connection: ToolConnectioconst tools = typeof config.tools === "string" && config.tools ? config.tools : "None";const rows = [["Connection method", method],- ["Project ID", typeof config.projectId === "string" ? config.projectId : "Not set"],+ ["Project pin", typeof config.projectId === "string" ? config.projectId : "Use active project"],["Read-only mode", config.readOnly === true ? "On" : "Off"],["Feature groups", features],["Individual tools", tools],@@ -94,7 +123,7 @@ function PostHogConfigurationSection({ connection }: { connection: ToolConnectio<section><h2 className="text-sm font-bold text-foreground">PostHog access scope</h2><p className="mt-0.5 text-sm text-muted-foreground">- This connection is pinned to the project and analytics surface below.+ PostHog uses its normal account defaults unless you narrow the optional controls below.</p><dl className="mt-4 divide-y divide-border">{rows.map(([label, value]) => (@@ -215,41 +244,6 @@ function GoogleSheetsAllowlistSection({);}-export function AppLifecycleSection({- connection,- disabled,- onToggle,-}: {- connection: ToolConnection;- disabled: boolean;- onToggle: () => void;-}) {- const enabled = connection.enabled !== false && connection.status !== "disabled";- return (- <section>- <div className="flex items-center justify-between gap-4">- <div>- <h2 className="text-sm font-bold text-foreground">- {enabled ? "Agents can use this app" : "This app is paused"}- </h2>- <p className="mt-0.5 text-sm text-muted-foreground">- {enabled- ? "Pause it to stop every agent from using its actions."- : "Resume it when agents should be able to use its actions again."}- </p>- </div>- <ToggleSwitch- aria-label={enabled ? "Pause this app" : "Resume this app"}- checked={enabled}- disabled={disabled}- onCheckedChange={onToggle}- size="lg"- />- </div>- </section>- );-}-export function QuarantinedActionsReview({entries,disabled,diff --git a/ui/src/pages/apps/app-detail/TestPanel.test.tsx b/ui/src/pages/apps/app-detail/TestPanel.test.tsxindex 3afccd0505..a194f0b2ce 100644--- a/ui/src/pages/apps/app-detail/TestPanel.test.tsx+++ b/ui/src/pages/apps/app-detail/TestPanel.test.tsx@@ -229,11 +229,12 @@ describe("TestPanel", () => {expect(container.querySelectorAll('[data-slot="skeleton"]')).not.toHaveLength(0);});- it("renders the Test-as header and grouped actions with access badges", async () => {+ it("renders the test hierarchy and grouped actions with access badges", async () => {await act(async () => renderPanel());await flushReact();- expect(container.textContent).toContain("Test as");+ expect(container.textContent).toContain("Test an action");+ expect(container.textContent).toContain("Agent");expect(container.textContent).toContain("ClaudeCoder");expect(container.textContent).toContain("Allowed for 1 action · Ask first for 1 action · Off for 1 action");expect(container.textContent).toContain("Read (1)");diff --git a/ui/src/pages/apps/app-detail/TestPanel.tsx b/ui/src/pages/apps/app-detail/TestPanel.tsxindex 8dbf102cc0..89eda462ee 100644--- a/ui/src/pages/apps/app-detail/TestPanel.tsx+++ b/ui/src/pages/apps/app-detail/TestPanel.tsx@@ -14,7 +14,6 @@ import {} from "lucide-react";import type {ToolCatalogEntry,- ToolConnectionAccessSummary,ToolConnectionTestAgent,ToolConnectionTestCallResult,ToolConnectionTestCallStatus,@@ -41,6 +40,7 @@ import {} from "@/components/JsonSchemaForm";import { cn, relativeTime } from "@/lib/utils";import { appTabHref } from "../app-tabs";+import { formatActionPermissionSummary } from "./action-permission-summary";// ---------------------------------------------------------------------------// Small format helpers@@ -99,19 +99,6 @@ function DecisionBadge({ decision }: { decision: ToolConnectionTestDecision }) {);}-/** "Allowed for 1 action · Ask first for 2 · Off for 1" — singular gets " action". */-function summaryCount(label: string, n: number): string {- return `${label} ${n}${n === 1 ? " action" : ""}`;-}--function accessSummaryLine(summary: ToolConnectionAccessSummary): string {- return [- summaryCount("Allowed for", summary.allowedCount),- summaryCount("Ask first for", summary.askFirstCount),- summaryCount("Off for", summary.offCount),- ].join(" · ");-}-// ---------------------------------------------------------------------------// Panel// ---------------------------------------------------------------------------@@ -152,9 +139,6 @@ export function TestPanel({setAgentId(agents[0].id);}, [agents, agentId]);- // Switches the header from "TEST AS" card to the compact "Testing as …" line.- const [hasInteracted, setHasInteracted] = useState(false);-const selectedAgent = agents.find((a) => a.id === agentId) ?? null;// Per-action decision for the selected agent, keyed by both the upstream and@@ -236,11 +220,10 @@ export function TestPanel({appName,allAgents: agents,onSelectAgent: setAgentId,- onInteract: () => setHasInteracted(true),};return (- <div className="space-y-5">+ <div className="space-y-8">{selectedAgent && (<TestAsHeaderappName={appName}@@ -248,11 +231,11 @@ export function TestPanel({selectedAgent={selectedAgent}onSelect={setAgentId}connectionId={connectionId}- compact={hasInteracted}/>)}- <div className="space-y-3">+ <section className="space-y-4 border-t border-border pt-8">+ <h2 className="text-lg font-semibold text-foreground">Actions</h2><div className="flex flex-wrap items-center gap-2"><div className="relative min-w-(--sz-12rem) flex-1"><Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />@@ -269,7 +252,7 @@ export function TestPanel({<FilterChip label={`Write ${writeActions.length}`} active={kindFilter === "write"} onClick={() => setKindFilter("write")} /></div><p className="text-xs text-muted-foreground">{visibleCount} matches · sorted A–Z</p>- </div>+ </section>{visibleCount === 0 ? (<div className="py-6 text-center text-sm text-muted-foreground">@@ -339,38 +322,24 @@ function TestAsHeader({selectedAgent,onSelect,connectionId,- compact,}: {appName: string;agents: ToolConnectionTestAgent[];selectedAgent: ToolConnectionTestAgent;onSelect: (agentId: string) => void;connectionId: string;- compact: boolean;}) {- if (compact) {- return (- <div className="flex flex-wrap items-center justify-between gap-3 pb-3">- <p className="text-sm text-muted-foreground">- Testing as{" "}- <AgentPicker- agents={agents}- selectedAgent={selectedAgent}- onSelect={onSelect}- connectionId={connectionId}- appName={appName}- inline- />+ return (+ <section className="space-y-5">+ <div>+ <h2 className="text-lg font-semibold text-foreground">Test an action</h2>+ <p className="mt-1 text-sm text-muted-foreground">+ Run a real action as an agent.</p>- <p className="text-xs text-muted-foreground">{accessSummaryLine(selectedAgent.effectiveAccess)}</p></div>- );- }- return (- <div><div className="flex flex-wrap items-center justify-between gap-3"><div className="min-w-0">- <p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">Test as</p>+ <p className="text-xs font-medium text-muted-foreground">Agent</p><AgentPickeragents={agents}selectedAgent={selectedAgent}@@ -379,12 +348,14 @@ function TestAsHeader({appName={appName}/></div>- <p className="text-sm text-muted-foreground">{accessSummaryLine(selectedAgent.effectiveAccess)}</p>+ <Link+ className="text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline"+ to={appTabHref(connectionId, "permissions")}+ >+ {formatActionPermissionSummary(selectedAgent.effectiveAccess)}+ </Link></div>- <p className="mt-2 text-xs text-muted-foreground">- Runs real actions in {appName}, exactly as this agent would.- </p>- </div>+ </section>);}@@ -531,7 +502,6 @@ type RowSharedProps = {appName: string;allAgents: ToolConnectionTestAgent[];onSelectAgent: (agentId: string) => void;- onInteract: () => void;};function ActionGroup({@@ -693,7 +663,6 @@ function ActionTester({agent,allAgents,onSelectAgent,- onInteract,}: {entry: ToolCatalogEntry;decision: ToolConnectionTestDecision;@@ -761,7 +730,6 @@ function ActionTester({const validationErrors = validateJsonSchemaForm(rawSchema, values);setErrors(validationErrors);if (Object.keys(validationErrors).length > 0) return;- onInteract();cancelledRef.current = false;startedAtRef.current = Date.now();setElapsedMs(0);diff --git a/ui/src/pages/apps/app-detail/action-permission-summary.ts b/ui/src/pages/apps/app-detail/action-permission-summary.tsnew file mode 100644index 0000000000..27d3f92f1a--- /dev/null+++ b/ui/src/pages/apps/app-detail/action-permission-summary.ts@@ -0,0 +1,41 @@+import type { ToolCatalogEntry } from "@paperclipai/shared";++export type ActionPermissionSummary = {+ allowedCount: number;+ askFirstCount: number;+ offCount: number;+};++export function summarizeActionPermissions(+ entries: ToolCatalogEntry[],+ enabledIds: Set<string>,+ askFirstIds: Set<string>,+): ActionPermissionSummary {+ let allowedCount = 0;+ let askFirstCount = 0;+ let offCount = 0;++ for (const entry of entries) {+ if (!enabledIds.has(entry.id)) {+ offCount += 1;+ } else if (askFirstIds.has(entry.id)) {+ askFirstCount += 1;+ } else {+ allowedCount += 1;+ }+ }++ return { allowedCount, askFirstCount, offCount };+}++function summaryCount(label: string, count: number): string {+ return `${label} ${count}${count === 1 ? " action" : ""}`;+}++export function formatActionPermissionSummary(summary: ActionPermissionSummary): string {+ return [+ summaryCount("Allowed for", summary.allowedCount),+ summaryCount("Ask first for", summary.askFirstCount),+ summaryCount("Off for", summary.offCount),+ ].join(" · ");+}diff --git a/ui/src/pages/apps/app-tabs.ts b/ui/src/pages/apps/app-tabs.tsindex d92dcc4fe5..da7f992e52 100644--- a/ui/src/pages/apps/app-tabs.ts+++ b/ui/src/pages/apps/app-tabs.ts@@ -4,8 +4,8 @@ export const APP_TABS = [{ key: "setup", label: "Setup", icon: Settings2 },{ key: "test", label: "Test", icon: Beaker },{ key: "services", label: "Services", icon: Blocks },- { key: "review", label: "Review", icon: Inbox },{ key: "permissions", label: "Permissions", icon: ShieldCheck },+ { key: "review", label: "Review", icon: Inbox },{ key: "activity", label: "Activity", icon: Activity },] as const;diff --git a/ui/src/pages/apps/connection-identity.ts b/ui/src/pages/apps/connection-identity.tsindex e907c56dd4..bf105247d7 100644--- a/ui/src/pages/apps/connection-identity.ts+++ b/ui/src/pages/apps/connection-identity.ts@@ -1,4 +1,5 @@import type {+ ConnectionGrantKind,ConnectionAudienceMember,ConnectionGrant,ConnectionGrantStatus,@@ -14,24 +15,34 @@ import type {* card cannot drift into three different names for the same thing.*/-export interface ActsAsSummary {- title: string;- detail: string;+export type ConnectionTypeLabel = "Personal" | "Company";++/** The two connection types shown throughout the product. */+export function connectionTypeLabel(+ credentialPolicy: ToolConnectionCredentialPolicy,+): ConnectionTypeLabel {+ return credentialPolicy === "per_user" ? "Personal" : "Company";}-export function actsAsSummary(credentialPolicy: ToolConnectionCredentialPolicy): ActsAsSummary {- switch (credentialPolicy) {- case "per_user":- return { title: "Acts as each person", detail: "Each person connects their own account." };- case "per_user_with_fallback":- return {- title: "Uses a personal identity with organization fallback",- detail: "Agents use your account when you have one, and the organization account otherwise.",- };- case "shared":- default:- return { title: "Acts as the organization", detail: "Agents share the organization identity." };+const COMPANY_NAME_SUFFIX = " for the company";++/** Keep company-owned connections unmistakable anywhere their name appears. */+export function connectionNameForGrantKind(name: string, grantKind: ConnectionGrantKind): string {+ const trimmed = name.trim();+ if (grantKind !== "organization" || trimmed.toLocaleLowerCase().endsWith(COMPANY_NAME_SUFFIX)) {+ return trimmed;}+ return `${trimmed}${COMPANY_NAME_SUFFIX}`;+}++export function connectionNameForCredentialPolicy(+ name: string,+ credentialPolicy: ToolConnectionCredentialPolicy,+): string {+ return connectionNameForGrantKind(+ name,+ connectionTypeLabel(credentialPolicy) === "Company" ? "organization" : "user",+ );}/**diff --git a/ui/src/pages/apps/generic-mcp-connect.test.ts b/ui/src/pages/apps/generic-mcp-connect.test.tsindex ca6952b0a6..f13192eae8 100644--- a/ui/src/pages/apps/generic-mcp-connect.test.ts+++ b/ui/src/pages/apps/generic-mcp-connect.test.ts@@ -7,6 +7,7 @@ import {genericConnectGuidance,genericConnectPayload,newCustomHeaderRow,+ oauthCallbackUrlForBrowser,type GenericConnectDraft,} from "./generic-mcp-connect";@@ -36,6 +37,23 @@ describe("endpointHost", () => {});});+describe("oauthCallbackUrlForBrowser", () => {+ it("uses localhost for local HTTP callbacks to match the API authorization request", () => {+ expect(oauthCallbackUrlForBrowser("http://127.0.0.1:3200")).toBe(+ "http://localhost:3200/api/tools/oauth/callback",+ );+ expect(oauthCallbackUrlForBrowser("http://[::1]:3200")).toBe(+ "http://localhost:3200/api/tools/oauth/callback",+ );+ });++ it("preserves public HTTPS origins", () => {+ expect(oauthCallbackUrlForBrowser("https://paperclip.example.test")).toBe(+ "https://paperclip.example.test/api/tools/oauth/callback",+ );+ });+});+describe("defaultGenericMcpName", () => {it("keeps the port and path so endpoints on one host get distinct names", () => {expect(defaultGenericMcpName("http://127.0.0.1:47399/mcp"))diff --git a/ui/src/pages/apps/generic-mcp-connect.ts b/ui/src/pages/apps/generic-mcp-connect.tsindex 075c21fc52..98ea9dcaec 100644--- a/ui/src/pages/apps/generic-mcp-connect.ts+++ b/ui/src/pages/apps/generic-mcp-connect.ts@@ -35,6 +35,25 @@ export function endpointHost(url: string): string | null {}}+/**+ * The callback URI shown to operators must exactly match the URI the API sends.+ *+ * Xero and a few other OAuth providers reject numeric loopback hosts even though+ * they point at the same machine. The API therefore uses `localhost` for local+ * HTTP OAuth, so the setup form must advertise that same canonical spelling.+ */+export function oauthCallbackUrlForBrowser(origin: string = window.location.origin): string {+ const callbackUrl = new URL("/api/tools/oauth/callback", origin);+ const hostname = callbackUrl.hostname.toLowerCase().replace(/^\[|\]$/g, "");+ if (+ callbackUrl.protocol === "http:"+ && (hostname === "127.0.0.1" || hostname === "::1")+ ) {+ callbackUrl.hostname = "localhost";+ }+ return callbackUrl.toString();+}+/*** A useful, non-secret default label for an arbitrary endpoint.*diff --git a/ui/src/pages/apps/store-cards.tsx b/ui/src/pages/apps/store-cards.tsxindex 0a500823dd..fd27dd58c1 100644--- a/ui/src/pages/apps/store-cards.tsx+++ b/ui/src/pages/apps/store-cards.tsx@@ -4,7 +4,7 @@ import { advancedTabHref } from "@/pages/tools/tool-tabs";import { appSourceConnectHref } from "./app-connect-policy";/** Popular gallery keys surfaced first in the Browse store (PAP-13254, door 1). */-export const POPULAR_KEYS = ["zapier", "github", "slack", "notion", "posthog", "linear"];+export const POPULAR_KEYS = ["zapier", "notion", "posthog", "linear", "jira", "cloudflare"];/** Deep-link into the Connect wizard's bring-your-own-tool URL flow. */export const BYO_CONNECT_HREF = "/apps/connect?byo=1";diff --git a/ui/src/pages/tools/PasteConfigTab.test.tsx b/ui/src/pages/tools/PasteConfigTab.test.tsxindex 23ee9f7912..e997528759 100644--- a/ui/src/pages/tools/PasteConfigTab.test.tsx+++ b/ui/src/pages/tools/PasteConfigTab.test.tsx@@ -90,8 +90,8 @@ function connectResult(overrides: Partial<ConnectToolAppResult> = {}): ConnectToownership: "customer",transport: "mcp_remote",authKind: "none",- credentialPolicy: "shared",credentialSource: "paperclip_vault",+ credentialPolicy: "shared",status: "draft",enabled: false,config: { url: "http://127.0.0.1:8848/mcp" },@@ -124,7 +124,7 @@ function connectResult(overrides: Partial<ConnectToolAppResult> = {}): ConnectTo}],canMakeChanges: [],},- suggestedDefaults: { access: "all_agents", askFirstRiskLevels: ["write", "destructive"] },+ suggestedDefaults: { access: "all_agents", askFirstRiskLevels: [] },...overrides,};}diff --git a/ui/src/pages/tools/PasteConfigTab.tsx b/ui/src/pages/tools/PasteConfigTab.tsxindex e62e6df52e..803ad79360 100644--- a/ui/src/pages/tools/PasteConfigTab.tsx+++ b/ui/src/pages/tools/PasteConfigTab.tsx@@ -19,7 +19,7 @@ import { useNavigate } from "@/lib/router";import {OAuthConnectStateScreen,type OAuthConnectPhase,-} from "@/pages/apps/AppsConnect";+} from "@/features/connections/ConnectionSetupFlow";import { endpointHost } from "@/pages/apps/generic-mcp-connect";import { McpConfigHelpDialog } from "./McpConfigHelpDialog";import { ErrorState } from "./shared";diff --git a/ui/storybook/.storybook/preview.tsx b/ui/storybook/.storybook/preview.tsxindex b4a1b93276..537b1d6328 100644--- a/ui/storybook/.storybook/preview.tsx+++ b/ui/storybook/.storybook/preview.tsx@@ -1,7 +1,10 @@import { useEffect, useState, type ReactNode } from "react";import type { Preview } from "@storybook/react-vite";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import type { WorkTimelineResult } from "@paperclipai/shared";+import {+ CONNECTABLE_APP_DEFINITIONS,+ type WorkTimelineResult,+} from "@paperclipai/shared";import { MemoryRouter } from "@/lib/router";import { ONBOARDING_STORAGE_KEY } from "@/components/OnboardingWizard";import { BreadcrumbProvider } from "@/context/BreadcrumbContext";@@ -39,12 +42,16 @@ import "./styles.css";const STORYBOOK_USER_AVATAR ="https://images.unsplash.com/photo-1494790108377-be9c29b29330?auto=format&fit=crop&w=96&q=80";-function withStorybookTimelineDetails(data: WorkTimelineResult): WorkTimelineResult {+function withStorybookTimelineDetails(+ data: WorkTimelineResult,+): WorkTimelineResult {return {...data,- actors: data.actors.map((actor) => (- actor.type === "user" ? { ...actor, avatar: STORYBOOK_USER_AVATAR } : actor- )),+ actors: data.actors.map((actor) =>+ actor.type === "user"+ ? { ...actor, avatar: STORYBOOK_USER_AVATAR }+ : actor,+ ),spans: data.spans.map((span, index) => {const inputTokens = 42_000 + index * 137;const cachedInputTokens = index % 3 === 0 ? 8_000 : 0;@@ -62,7 +69,9 @@ function withStorybookTimelineDetails(data: WorkTimelineResult): WorkTimelineRes};}-const storybookTimelineSample = withStorybookTimelineDetails(timelineSample as WorkTimelineResult);+const storybookTimelineSample = withStorybookTimelineDetails(+ timelineSample as WorkTimelineResult,+);// Install fetch monkeypatch eagerly so any module-load-time fetches (e.g. schema// caches in adapter config renderers) hit our fixtures before they reach the@@ -148,6 +157,66 @@ function installStorybookApiFixtures() {return Response.json([]);}+ if (+ url.pathname ===+ "/api/connection-intents/interaction-connection-intent-default/setup-options"+ ) {+ return Response.json({+ version: 1,+ interaction: null,+ service: {+ service: "notion",+ name: "Notion",+ description: "Search and update a Notion workspace.",+ logoUrl: null,+ methods: [+ { key: "mcp-oauth", label: "Sign in with Notion", auth: "oauth" },+ ],+ state: "needs_user_action",+ connectionId: null,+ },+ requestedAgentId: "11111111-1111-4111-8111-111111111111",+ existingConnections: [+ {+ id: "connection-storybook-notion",+ companyId: "company-storybook",+ applicationId: "application-storybook-notion",+ name: "Board Operator’s Notion",+ uid: "notion/storybook",+ transport: "mcp_remote",+ authKind: "oauth",+ credentialPolicy: "per_user",+ status: "active",+ enabled: true,+ config: { sourceTemplateKey: "notion" },+ transportConfig: { sourceTemplateKey: "notion" },+ credentialRefs: [],+ credentialSecretRefs: [],+ },+ ],+ });+ }++ if (url.pathname === "/api/companies/company-storybook/tools/gallery") {+ return Response.json({+ apps: CONNECTABLE_APP_DEFINITIONS.filter(+ (app) => app.slug === "notion",+ ),+ capabilities: {+ canSetCompanyInstall: true,+ companyInstallReason: null,+ },+ });+ }+ if (+ url.pathname === "/api/companies/company-storybook/tools/applications"+ ) {+ return Response.json({ applications: [] });+ }+ if (url.pathname === "/api/companies/company-storybook/tools/connections") {+ return Response.json({ connections: [] });+ }+if (url.pathname === "/api/adapters") {return Response.json([{@@ -209,23 +278,33 @@ function installStorybookApiFixtures() {return Response.json([]);}- const adapterSchemaMatch = url.pathname.match(/^\/api\/adapters\/([^/]+)\/config-schema$/);+ const adapterSchemaMatch = url.pathname.match(+ /^\/api\/adapters\/([^/]+)\/config-schema$/,+ );if (adapterSchemaMatch) {const [, adapterType] = adapterSchemaMatch;- const schemas = (window as typeof window & {- __paperclipStorybookAdapterSchemas?: Record<string, unknown>;- }).__paperclipStorybookAdapterSchemas;+ const schemas = (+ window as typeof window & {+ __paperclipStorybookAdapterSchemas?: Record<string, unknown>;+ }+ ).__paperclipStorybookAdapterSchemas;const schema = schemas?.[adapterType];if (schema) return Response.json(schema);}- const secretsListMatch = url.pathname.match(/^\/api\/companies\/([^/]+)\/secrets$/);+ const secretsListMatch = url.pathname.match(+ /^\/api\/companies\/([^/]+)\/secrets$/,+ );if (secretsListMatch) {const [, companyId] = secretsListMatch;- return Response.json(companyId === "company-storybook" ? storybookSecrets : []);+ return Response.json(+ companyId === "company-storybook" ? storybookSecrets : [],+ );}- const secretProvidersMatch = url.pathname.match(/^\/api\/companies\/([^/]+)\/secret-providers$/);+ const secretProvidersMatch = url.pathname.match(+ /^\/api\/companies\/([^/]+)\/secret-providers$/,+ );if (secretProvidersMatch) {return Response.json(storybookSecretProviders);}@@ -247,36 +326,57 @@ function installStorybookApiFixtures() {const secretProviderConfigDiscoveryPreviewMatch = url.pathname.match(/^\/api\/companies\/([^/]+)\/secret-provider-configs\/discovery\/preview$/,);- if (secretProviderConfigDiscoveryPreviewMatch && init?.method?.toUpperCase() === "POST") {+ if (+ secretProviderConfigDiscoveryPreviewMatch &&+ init?.method?.toUpperCase() === "POST"+ ) {return Response.json(storybookSecretProviderDiscoveryPreview);}- const secretUsageMatch = url.pathname.match(/^\/api\/secrets\/([^/]+)\/usage$/);+ const secretUsageMatch = url.pathname.match(+ /^\/api\/secrets\/([^/]+)\/usage$/,+ );if (secretUsageMatch) {const [, secretId] = secretUsageMatch;return Response.json({secretId,- bindings: storybookSecretBindings.filter((binding) => binding.secretId === secretId),+ bindings: storybookSecretBindings.filter(+ (binding) => binding.secretId === secretId,+ ),});}- const secretEventsMatch = url.pathname.match(/^\/api\/secrets\/([^/]+)\/access-events$/);+ const secretEventsMatch = url.pathname.match(+ /^\/api\/secrets\/([^/]+)\/access-events$/,+ );if (secretEventsMatch) {const [, secretId] = secretEventsMatch;- return Response.json(storybookSecretAccessEvents.filter((event) => event.secretId === secretId));+ return Response.json(+ storybookSecretAccessEvents.filter(+ (event) => event.secretId === secretId,+ ),+ );}- const companyResourceMatch = url.pathname.match(/^\/api\/companies\/([^/]+)\/([^/]+)$/);+ const companyResourceMatch = url.pathname.match(+ /^\/api\/companies\/([^/]+)\/([^/]+)$/,+ );if (companyResourceMatch) {const [, companyId, resource] = companyResourceMatch;if (resource === "agents") {- return Response.json(companyId === "company-storybook" ? storybookAgents : []);+ return Response.json(+ companyId === "company-storybook" ? storybookAgents : [],+ );}if (resource === "projects") {- return Response.json(companyId === "company-storybook" ? storybookProjects : []);+ return Response.json(+ companyId === "company-storybook" ? storybookProjects : [],+ );}if (resource === "approvals") {- return Response.json(companyId === "company-storybook" ? storybookApprovals : []);+ return Response.json(+ companyId === "company-storybook" ? storybookApprovals : [],+ );}if (resource === "dashboard") {return Response.json({@@ -293,9 +393,15 @@ function installStorybookApiFixtures() {spans: [],events: [],edges: [],- pagination: { limit: 100, offset: 0, totalIssues: 0, hasMore: false },+ pagination: {+ limit: 100,+ offset: 0,+ totalIssues: 0,+ hasMore: false,+ },window: {- from: url.searchParams.get("from") ?? new Date(0).toISOString(),+ from:+ url.searchParams.get("from") ?? new Date(0).toISOString(),to: url.searchParams.get("to") ?? new Date(0).toISOString(),capped: false,},@@ -306,7 +412,9 @@ function installStorybookApiFixtures() {return Response.json([]);}if (resource === "live-runs") {- return Response.json(companyId === "company-storybook" ? storybookLiveRuns : []);+ return Response.json(+ companyId === "company-storybook" ? storybookLiveRuns : [],+ );}if (resource === "inbox-dismissals") {return Response.json([]);@@ -327,14 +435,19 @@ function installStorybookApiFixtures() {return Response.json(query? issues.filter((issue) =>- `${issue.identifier ?? ""} ${issue.title} ${issue.description ?? ""}`.toLowerCase().includes(query),+ `${issue.identifier ?? ""} ${issue.title} ${issue.description ?? ""}`+ .toLowerCase()+ .includes(query),): issues,);}}- if (url.pathname.startsWith("/api/invites/") && url.pathname.endsWith("/logo")) {+ if (+ url.pathname.startsWith("/api/invites/") &&+ url.pathname.endsWith("/logo")+ ) {return new Response(null, { status: 204 });}diff --git a/ui/storybook/stories/access-profiles.stories.tsx b/ui/storybook/stories/access-profiles.stories.tsxindex 9f33a3a6b8..59a0af777f 100644--- a/ui/storybook/stories/access-profiles.stories.tsx+++ b/ui/storybook/stories/access-profiles.stories.tsx@@ -275,8 +275,8 @@ const CONNECTIONS: ToolConnection[] = [ownership: "customer",transport: "mcp_remote",authKind: "oauth",- credentialPolicy: "per_user",credentialSource: "paperclip_vault",+ credentialPolicy: "per_user",status: "active",transportConfig: {},credentialSecretRefs: [],@@ -311,8 +311,8 @@ const CONNECTIONS: ToolConnection[] = [ownership: "customer",transport: "mcp_remote",authKind: "oauth",- credentialPolicy: "per_user",credentialSource: "paperclip_vault",+ credentialPolicy: "per_user",status: "active",transportConfig: {},credentialSecretRefs: [],diff --git a/ui/storybook/stories/issue-thread-interactions.stories.tsx b/ui/storybook/stories/issue-thread-interactions.stories.tsxindex 428e2dd1c1..571dc7269d 100644--- a/ui/storybook/stories/issue-thread-interactions.stories.tsx+++ b/ui/storybook/stories/issue-thread-interactions.stories.tsx@@ -2,7 +2,13 @@ import { useEffect, useRef, useState } from "react";import type { Meta, StoryObj } from "@storybook/react-vite";import { IssueChatThread } from "@/components/IssueChatThread";import { IssueThreadInteractionCard } from "@/components/IssueThreadInteractionCard";-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";+import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+} from "@/components/ui/card";import {acceptedManyRequestCheckboxConfirmationInteraction,acceptedRequestCheckboxConfirmationInteraction,@@ -55,6 +61,13 @@ import {rejectedSuggestedTasksInteraction,staleTargetRequestCheckboxConfirmationInteraction,staleTargetRequestConfirmationInteraction,+ pendingConnectionIntentInteraction,+ authorizingConnectionIntentInteraction,+ retryConnectionIntentInteraction,+ connectedConnectionIntentInteraction,+ declinedConnectionIntentInteraction,+ supersededConnectionIntentInteraction,+ expiredConnectionIntentInteraction,} from "@/fixtures/issueThreadInteractionFixtures";import type {AskUserQuestionsAnswer,@@ -123,7 +136,37 @@ function ScenarioCard({);}-function AudienceCard({ interaction }: { interaction: RequestConfirmationInteraction }) {+function OpenConnectionIntentDialogStory() {+ const hostRef = useRef<HTMLDivElement>(null);+ useEffect(() => {+ const frame = window.requestAnimationFrame(() => {+ const trigger = Array.from(+ hostRef.current?.querySelectorAll("button") ?? [],+ ).find((candidate) =>+ candidate.textContent?.includes("Connect / Use existing"),+ );+ trigger?.click();+ });+ return () => window.cancelAnimationFrame(frame);+ }, []);++ return (+ <div ref={hostRef}>+ <IssueThreadInteractionCard+ interaction={pendingConnectionIntentInteraction}+ agentMap={storybookAgentMap}+ currentUserId={issueThreadInteractionFixtureMeta.currentUserId}+ userLabelMap={boardUserLabels}+ />+ </div>+ );+}++function AudienceCard({+ interaction,+}: {+ interaction: RequestConfirmationInteraction;+}) {return (<IssueThreadInteractionCardinteraction={interaction}@@ -152,13 +195,20 @@ function InteractiveSuggestedTasksCard() {...acceptedSuggestedTasksInteraction,result: {version: 1,- createdTasks: (acceptedSuggestedTasksInteraction.result?.createdTasks ?? []).filter((task) =>- selectedClientKeys?.includes(task.clientKey) ?? true),+ createdTasks: (+ acceptedSuggestedTasksInteraction.result?.createdTasks ?? []+ ).filter(+ (task) => selectedClientKeys?.includes(task.clientKey) ?? true,+ ),skippedClientKeys: pendingSuggestedTasksInteraction.payload.tasks.map((task) => task.clientKey)- .filter((clientKey) => !(selectedClientKeys?.includes(clientKey) ?? true)),+ .filter(+ (clientKey) =>+ !(selectedClientKeys?.includes(clientKey) ?? true),+ ),},- })}+ })+ }onRejectInteraction={(_interaction, reason) =>setInteraction({...rejectedSuggestedTasksInteraction,@@ -166,11 +216,12 @@ function InteractiveSuggestedTasksCard() {version: 1,...(rejectedSuggestedTasksInteraction.result ?? {}),rejectionReason:- reason- || rejectedSuggestedTasksInteraction.result?.rejectionReason- || null,+ reason ||+ rejectedSuggestedTasksInteraction.result?.rejectionReason ||+ null,},- })}+ })+ }/>);}@@ -178,13 +229,15 @@ function InteractiveSuggestedTasksCard() {function buildAnsweredInteraction(answers: AskUserQuestionsAnswer[],): AskUserQuestionsInteraction {- const labels = pendingAskUserQuestionsInteraction.payload.questions.flatMap((question) => {- const answer = answers.find((entry) => entry.questionId === question.id);- if (!answer) return [];- return question.options- .filter((option) => answer.optionIds.includes(option.id))- .map((option) => option.label);- });+ const labels = pendingAskUserQuestionsInteraction.payload.questions.flatMap(+ (question) => {+ const answer = answers.find((entry) => entry.questionId === question.id);+ if (!answer) return [];+ return question.options+ .filter((option) => answer.optionIds.includes(option.id))+ .map((option) => option.label);+ },+ );return {...answeredAskUserQuestionsInteraction,@@ -208,15 +261,17 @@ function InteractiveAskUserQuestionsCard() {currentUserId={issueThreadInteractionFixtureMeta.currentUserId}userLabelMap={boardUserLabels}onSubmitInteractionAnswers={(_interaction, answers) =>- setInteraction(buildAnsweredInteraction(answers))}+ setInteraction(buildAnsweredInteraction(answers))+ }/>);}function InteractiveRequestConfirmationCard() {- const [interaction, setInteraction] = useState<RequestConfirmationInteraction>(- pendingRequestConfirmationInteraction,- );+ const [interaction, setInteraction] =+ useState<RequestConfirmationInteraction>(+ pendingRequestConfirmationInteraction,+ );return (<IssueThreadInteractionCard@@ -224,16 +279,22 @@ function InteractiveRequestConfirmationCard() {agentMap={storybookAgentMap}currentUserId={issueThreadInteractionFixtureMeta.currentUserId}userLabelMap={boardUserLabels}- onAcceptInteraction={() => setInteraction(acceptedRequestConfirmationInteraction)}+ onAcceptInteraction={() =>+ setInteraction(acceptedRequestConfirmationInteraction)+ }onRejectInteraction={(_interaction, reason) =>setInteraction({...rejectedRequestConfirmationInteraction,result: {version: 1,outcome: "rejected",- reason: reason || rejectedRequestConfirmationInteraction.result?.reason || null,+ reason:+ reason ||+ rejectedRequestConfirmationInteraction.result?.reason ||+ null,},- })}+ })+ }/>);}@@ -247,7 +308,8 @@ function InteractiveRequestCheckboxConfirmationCard({accepted: RequestCheckboxConfirmationInteraction;rejected: RequestCheckboxConfirmationInteraction;}) {- const [interaction, setInteraction] = useState<RequestCheckboxConfirmationInteraction>(pending);+ const [interaction, setInteraction] =+ useState<RequestCheckboxConfirmationInteraction>(pending);return (<IssueThreadInteractionCard@@ -255,7 +317,11 @@ function InteractiveRequestCheckboxConfirmationCard({agentMap={storybookAgentMap}currentUserId={issueThreadInteractionFixtureMeta.currentUserId}userLabelMap={boardUserLabels}- onAcceptInteraction={(_interaction, _selectedClientKeys, selectedOptionIds) =>+ onAcceptInteraction={(+ _interaction,+ _selectedClientKeys,+ selectedOptionIds,+ ) =>setInteraction({...accepted,payload: pending.payload,@@ -264,7 +330,8 @@ function InteractiveRequestCheckboxConfirmationCard({outcome: "accepted",selectedOptionIds: selectedOptionIds ?? [],},- })}+ })+ }onRejectInteraction={(_interaction, reason) =>setInteraction({...rejected,@@ -274,7 +341,8 @@ function InteractiveRequestCheckboxConfirmationCard({outcome: "rejected",reason: reason || rejected.result?.reason || null,},- })}+ })+ }/>);}@@ -284,7 +352,8 @@ function InteractiveRequestItemVerdictsCard({}: {initial?: RequestItemVerdictsInteraction;}) {- const [interaction, setInteraction] = useState<RequestItemVerdictsInteraction>(initial);+ const [interaction, setInteraction] =+ useState<RequestItemVerdictsInteraction>(initial);return (<IssueThreadInteractionCard@@ -304,7 +373,8 @@ function InteractiveRequestItemVerdictsCard({id: verdict.id,verdict: verdict.verdict as RequestItemVerdictValue,reason: verdict.reason ?? null,- resolvedByUserId: issueThreadInteractionFixtureMeta.currentUserId,+ resolvedByUserId:+ issueThreadInteractionFixtureMeta.currentUserId,resolvedAt: new Date("2026-04-20T15:20:00.000Z"),})),];@@ -313,7 +383,9 @@ function InteractiveRequestItemVerdictsCard({...current,status: complete ? "answered" : "pending",resolvedAt: complete ? new Date("2026-04-20T15:20:00.000Z") : null,- resolvedByUserId: complete ? issueThreadInteractionFixtureMeta.currentUserId : null,+ resolvedByUserId: complete+ ? issueThreadInteractionFixtureMeta.currentUserId+ : null,result: {version: 1,outcome: "resolved",@@ -321,7 +393,8 @@ function InteractiveRequestItemVerdictsCard({items: merged,},};- })}+ })+ }/>);}@@ -334,8 +407,13 @@ function AutoOpenDeclineRequestConfirmationCard({const ref = useRef<HTMLDivElement | null>(null);useEffect(() => {- const declineButton = Array.from(ref.current?.querySelectorAll("button") ?? [])- .find((button) => button.textContent?.includes(interaction.payload.rejectLabel ?? "Decline"));+ const declineButton = Array.from(+ ref.current?.querySelectorAll("button") ?? [],+ ).find((button) =>+ button.textContent?.includes(+ interaction.payload.rejectLabel ?? "Decline",+ ),+ );declineButton?.click();}, [interaction]);@@ -675,7 +753,128 @@ export const RequestConfirmationFailed: Story = {};export const RequestConfirmationAccepted = RequestConfirmationConfirmed;-export const RequestConfirmationRejected = RequestConfirmationDeclinedWithReason;+export const RequestConfirmationRejected =+ RequestConfirmationDeclinedWithReason;++export const ConnectionIntentStates: Story = {+ render: () => (+ <StoryFrame>+ <Section eyebrow="Connection intent" title="Inline setup request states">+ <div className="grid gap-6 xl:grid-cols-2">+ <ScenarioCard+ title="Addressed user"+ description="The responsible user can launch the shared connection setup flow or decline in place."+ >+ <IssueThreadInteractionCard+ interaction={pendingConnectionIntentInteraction}+ agentMap={storybookAgentMap}+ currentUserId={issueThreadInteractionFixtureMeta.currentUserId}+ userLabelMap={boardUserLabels}+ />+ </ScenarioCard>+ <ScenarioCard+ title="Other viewer"+ description="Other viewers see who Paperclip is waiting for and receive no connection controls."+ >+ <IssueThreadInteractionCard+ interaction={pendingConnectionIntentInteraction}+ agentMap={storybookAgentMap}+ currentUserId="user-product"+ userLabelMap={boardUserLabels}+ />+ </ScenarioCard>+ <ScenarioCard+ title="Authorizing"+ description="The in-flight state prevents duplicate authorization or decline actions."+ >+ <IssueThreadInteractionCard+ interaction={authorizingConnectionIntentInteraction}+ agentMap={storybookAgentMap}+ currentUserId={issueThreadInteractionFixtureMeta.currentUserId}+ userLabelMap={boardUserLabels}+ />+ </ScenarioCard>+ <ScenarioCard+ title="Retry needed"+ description="A failed popup or provider callback keeps the intent pending with a safe retry path."+ >+ <IssueThreadInteractionCard+ interaction={retryConnectionIntentInteraction}+ agentMap={storybookAgentMap}+ currentUserId={issueThreadInteractionFixtureMeta.currentUserId}+ userLabelMap={boardUserLabels}+ />+ </ScenarioCard>+ <ScenarioCard+ title="Connected"+ description="The terminal card records that the requesting agent receives the connection on continuation."+ >+ <IssueThreadInteractionCard+ interaction={connectedConnectionIntentInteraction}+ agentMap={storybookAgentMap}+ currentUserId={issueThreadInteractionFixtureMeta.currentUserId}+ userLabelMap={boardUserLabels}+ />+ </ScenarioCard>+ <ScenarioCard+ title="Declined"+ description="Decline is terminal and wakes the requesting agent without exposing setup controls."+ >+ <IssueThreadInteractionCard+ interaction={declinedConnectionIntentInteraction}+ agentMap={storybookAgentMap}+ currentUserId={issueThreadInteractionFixtureMeta.currentUserId}+ userLabelMap={boardUserLabels}+ />+ </ScenarioCard>+ <ScenarioCard+ title="Superseded"+ description="A newer run owns the active request, so the stale card points at the latest one."+ >+ <IssueThreadInteractionCard+ interaction={supersededConnectionIntentInteraction}+ agentMap={storybookAgentMap}+ currentUserId={issueThreadInteractionFixtureMeta.currentUserId}+ userLabelMap={boardUserLabels}+ />+ </ScenarioCard>+ <ScenarioCard+ title="Expired"+ description="Closed tasks and expired requests have a quiet terminal state with no authorization controls."+ >+ <IssueThreadInteractionCard+ interaction={expiredConnectionIntentInteraction}+ agentMap={storybookAgentMap}+ currentUserId={issueThreadInteractionFixtureMeta.currentUserId}+ userLabelMap={boardUserLabels}+ />+ </ScenarioCard>+ </div>+ </Section>+ </StoryFrame>+ ),+};++export const ConnectionIntentSetupDialog: Story = {+ render: () => (+ <StoryFrame>+ <Section eyebrow="Connection intent" title="Shared setup dialog">+ <OpenConnectionIntentDialogStory />+ </Section>+ </StoryFrame>+ ),+};++export const ConnectionIntentSetupDialogMobile: Story = {+ render: () => (+ <StoryFrame>+ <OpenConnectionIntentDialogStory />+ </StoryFrame>+ ),+ parameters: {+ viewport: { defaultViewport: "mobile" },+ },+};// ---------------------------------------------------------------------------// MCP tool-approval card (PAP-13745). A `request_confirmation` carrying a@@ -710,7 +909,10 @@ export const ToolActionPendingWrite: Story = {title="Pending · write"description="A write tool call awaits approval: identity header, WRITE risk badge, humanized preview, collapsible technical details, expiry countdown, and an Approve & run CTA.">- <ToolActionCard interaction={pendingToolActionWriteInteraction} interactive />+ <ToolActionCard+ interaction={pendingToolActionWriteInteraction}+ interactive+ /></ScenarioCard></StoryFrame>),@@ -723,7 +925,10 @@ export const ToolActionPendingDestructive: Story = {title="Pending · destructive"description="A destructive call takes the red risk badge and a destructive primary button; the countdown sits inside the sub-5-minute urgent window.">- <ToolActionCard interaction={pendingToolActionDestructiveInteraction} interactive />+ <ToolActionCard+ interaction={pendingToolActionDestructiveInteraction}+ interactive+ /></ScenarioCard></StoryFrame>),@@ -801,7 +1006,10 @@ export const ToolActionLegacyGeneric: Story = {title="Legacy · no toolAction"description="A confirmation without a toolAction payload keeps the existing generic rendering unchanged — the tool-approval surface is strictly additive.">- <ToolActionCard interaction={genericPendingRequestConfirmationInteraction} interactive />+ <ToolActionCard+ interaction={genericPendingRequestConfirmationInteraction}+ interactive+ /></ScenarioCard></StoryFrame>),@@ -833,7 +1041,10 @@ export const SecretProposalPending: Story = {title="Pending secret binding"description="A human reviews safe binding metadata, the agent-authored reason, and expiry before approving the real write.">- <SecretProposalCard interaction={pendingSecretProposalInteraction} interactive />+ <SecretProposalCard+ interaction={pendingSecretProposalInteraction}+ interactive+ /></ScenarioCard></StoryFrame>),@@ -896,20 +1107,44 @@ export const SecretProposalAllStates: Story = {<StoryFrame><Section eyebrow="Secret binding proposal" title="All lifecycle states"><div className="grid gap-6 xl:grid-cols-2">- <ScenarioCard title="1 · Pending" description="Safe metadata and approval actions.">- <SecretProposalCard interaction={pendingSecretProposalInteraction} interactive />+ <ScenarioCard+ title="1 · Pending"+ description="Safe metadata and approval actions."+ >+ <SecretProposalCard+ interaction={pendingSecretProposalInteraction}+ interactive+ /></ScenarioCard>- <ScenarioCard title="2 · Executed" description="The binding was created.">- <SecretProposalCard interaction={executedSecretProposalInteraction} />+ <ScenarioCard+ title="2 · Executed"+ description="The binding was created."+ >+ <SecretProposalCard+ interaction={executedSecretProposalInteraction}+ /></ScenarioCard>- <ScenarioCard title="3 · FAILED" description="Accepted, then failed closed.">+ <ScenarioCard+ title="3 · FAILED"+ description="Accepted, then failed closed."+ ><SecretProposalCard interaction={failedSecretProposalInteraction} /></ScenarioCard>- <ScenarioCard title="4 · Rejected" description="The binding was not created.">- <SecretProposalCard interaction={rejectedSecretProposalInteraction} />+ <ScenarioCard+ title="4 · Rejected"+ description="The binding was not created."+ >+ <SecretProposalCard+ interaction={rejectedSecretProposalInteraction}+ /></ScenarioCard>- <ScenarioCard title="5 · Expired" description="A fresh proposal is required.">- <SecretProposalCard interaction={expiredSecretProposalInteraction} />+ <ScenarioCard+ title="5 · Expired"+ description="A fresh proposal is required."+ >+ <SecretProposalCard+ interaction={expiredSecretProposalInteraction}+ /></ScenarioCard></div></Section>@@ -937,31 +1172,41 @@ export const ResolverAudienceStates: Story = {title="Anyone except creator"description="Requested on purpose when the answer has to be independent of the agent that asked.">- <AudienceCard interaction={notCreatorRequestConfirmationInteraction} />+ <AudienceCard+ interaction={notCreatorRequestConfirmationInteraction}+ /></ScenarioCard><ScenarioCardtitle="Human only"description="Reserved for a person: agents are turned away by the server, and the copy says so.">- <AudienceCard interaction={humanOnlyRequestConfirmationInteraction} />+ <AudienceCard+ interaction={humanOnlyRequestConfirmationInteraction}+ /></ScenarioCard><ScenarioCardtitle="Named addressee"description="One agent owns the response; the card stays out of the open attention feed.">- <AudienceCard interaction={agentAddressedRequestConfirmationInteraction} />+ <AudienceCard+ interaction={agentAddressedRequestConfirmationInteraction}+ /></ScenarioCard><ScenarioCardtitle="Narrowed by a company cap"description="The request asked for Anyone; company interaction governance capped the kind, and the card explains the narrowing.">- <AudienceCard interaction={companyCappedRequestConfirmationInteraction} />+ <AudienceCard+ interaction={companyCappedRequestConfirmationInteraction}+ /></ScenarioCard><ScenarioCardtitle="Legacy restricted card"description="Created before Anyone became the default. Migration keeps it restricted fail-closed and the card says a new card would be open.">- <AudienceCard interaction={legacyRestrictedRequestConfirmationInteraction} />+ <AudienceCard+ interaction={legacyRestrictedRequestConfirmationInteraction}+ /></ScenarioCard></div></Section>@@ -972,31 +1217,67 @@ export const ResolverAudienceStates: Story = {export const ToolActionAllStates: Story = {render: () => (<StoryFrame>- <Section eyebrow="MCP Tool Approval" title="All six lifecycle states (PAP-13745)">+ <Section+ eyebrow="MCP Tool Approval"+ title="All six lifecycle states (PAP-13745)"+ ><div className="grid gap-6 xl:grid-cols-2">- <ScenarioCard title="1 · Pending (write)" description="Awaiting approval — Approve & run.">- <ToolActionCard interaction={pendingToolActionWriteInteraction} interactive />+ <ScenarioCard+ title="1 · Pending (write)"+ description="Awaiting approval — Approve & run."+ >+ <ToolActionCard+ interaction={pendingToolActionWriteInteraction}+ interactive+ /></ScenarioCard>- <ScenarioCard title="1b · Pending (destructive)" description="Red risk badge, urgent countdown.">- <ToolActionCard interaction={pendingToolActionDestructiveInteraction} interactive />+ <ScenarioCard+ title="1b · Pending (destructive)"+ description="Red risk badge, urgent countdown."+ >+ <ToolActionCard+ interaction={pendingToolActionDestructiveInteraction}+ interactive+ /></ScenarioCard>- <ScenarioCard title="2 · Approved — running…" description="Transient, self-resolving spinner.">+ <ScenarioCard+ title="2 · Approved — running…"+ description="Transient, self-resolving spinner."+ ><ToolActionCard interaction={runningToolActionInteraction} /></ScenarioCard>- <ScenarioCard title="3 · Executed" description="Green, with a result summary.">+ <ScenarioCard+ title="3 · Executed"+ description="Green, with a result summary."+ ><ToolActionCard interaction={executedToolActionInteraction} /></ScenarioCard>- <ScenarioCard title="4 · Failed" description="Ran, but the connector errored.">+ <ScenarioCard+ title="4 · Failed"+ description="Ran, but the connector errored."+ ><ToolActionCard interaction={failedToolActionInteraction} /></ScenarioCard>- <ScenarioCard title="5 · Declined" description="Rejected — nothing ran.">+ <ScenarioCard+ title="5 · Declined"+ description="Rejected — nothing ran."+ ><ToolActionCard interaction={declinedToolActionInteraction} /></ScenarioCard>- <ScenarioCard title="6 · Expired" description="No response in 60 min.">+ <ScenarioCard+ title="6 · Expired"+ description="No response in 60 min."+ ><ToolActionCard interaction={expiredToolActionInteraction} /></ScenarioCard>- <ScenarioCard title="Legacy · no toolAction" description="Unchanged generic rendering.">- <ToolActionCard interaction={genericPendingRequestConfirmationInteraction} interactive />+ <ScenarioCard+ title="Legacy · no toolAction"+ description="Unchanged generic rendering."+ >+ <ToolActionCard+ interaction={genericPendingRequestConfirmationInteraction}+ interactive+ /></ScenarioCard></div></Section>@@ -1012,7 +1293,10 @@ export const ToolActionMobile: Story = {description="Single column: risk badge wraps under the tool name, actions stack full-width, the technical drawer stays collapsed."><div className="mx-auto max-w-[358px]">- <ToolActionCard interaction={pendingToolActionWriteInteraction} interactive />+ <ToolActionCard+ interaction={pendingToolActionWriteInteraction}+ interactive+ /></div></ScenarioCard></StoryFrame>@@ -1165,7 +1449,9 @@ export const ItemVerdictsPartial: Story = {title="S3 / S4 — partial progress"description="Two items already applied (one approved, one rejected with its reason echoed); three remain actionable. The card stays alive and shows 2 of 5 decided.">- <InteractiveRequestItemVerdictsCard initial={partialRequestItemVerdictsInteraction} />+ <InteractiveRequestItemVerdictsCard+ initial={partialRequestItemVerdictsInteraction}+ /></ScenarioCard></StoryFrame>),@@ -1214,7 +1500,9 @@ export const ItemVerdictsManyItems: Story = {title="S7 — long list"description="24 items decided in passes; the expanded list scrolls in a bounded region and reuses the 200-item cap.">- <InteractiveRequestItemVerdictsCard initial={manyItemsRequestItemVerdictsInteraction} />+ <InteractiveRequestItemVerdictsCard+ initial={manyItemsRequestItemVerdictsInteraction}+ /></ScenarioCard></StoryFrame>),@@ -1226,14 +1514,17 @@ export const ReviewSurface: Story = {<section className="paperclip-story__frame p-6"><div className="paperclip-story__label">Thread interactions</div><div className="mt-2 max-w-3xl text-sm leading-6 text-muted-foreground">- This review surface pressure-tests the thread interaction kinds directly inside the issue- chat surface. The card language leans closer to- annotated review sheets than generic admin widgets so the objects feel like first-class work- artifacts in the thread.+ This review surface pressure-tests the thread interaction kinds+ directly inside the issue chat surface. The card language leans closer+ to annotated review sheets than generic admin widgets so the objects+ feel like first-class work artifacts in the thread.</div></section>- <Section eyebrow="Suggested Tasks" title="Pending, accepted, and rejected task-tree cards">+ <Section+ eyebrow="Suggested Tasks"+ title="Pending, accepted, and rejected task-tree cards"+ ><div className="grid gap-6 xl:grid-cols-3"><ScenarioCardtitle="Pending"@@ -1266,7 +1557,10 @@ export const ReviewSurface: Story = {</div></Section>- <Section eyebrow="Ask User Questions" title="Pending multi-question form and answered summary">+ <Section+ eyebrow="Ask User Questions"+ title="Pending multi-question form and answered summary"+ ><div className="grid gap-6 xl:grid-cols-2"><ScenarioCardtitle="Pending"@@ -1288,7 +1582,10 @@ export const ReviewSurface: Story = {</div></Section>- <Section eyebrow="Request Confirmation" title="Plan approval and compact resolution states">+ <Section+ eyebrow="Request Confirmation"+ title="Plan approval and compact resolution states"+ ><div className="grid gap-6 xl:grid-cols-2"><ScenarioCardtitle="Plan approval"@@ -1340,7 +1637,10 @@ export const ReviewSurface: Story = {</div></Section>- <Section eyebrow="Mixed Feed" title="Interaction cards in the real issue thread">+ <Section+ eyebrow="Mixed Feed"+ title="Interaction cards in the real issue thread"+ ><ScenarioCardtitle="IssueChatThread composition"description="Comments, timeline events, accepted task suggestions, a pending confirmation, a pending question form, and an active run share the same feed."diff --git a/ui/storybook/stories/notion-connect-flow.stories.tsx b/ui/storybook/stories/notion-connect-flow.stories.tsxindex df5a449ed2..c90c3acd98 100644--- a/ui/storybook/stories/notion-connect-flow.stories.tsx+++ b/ui/storybook/stories/notion-connect-flow.stories.tsx@@ -4,6 +4,8 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import {CONNECTABLE_APP_DEFINITIONS,type AppDefinition,+ type ConnectionGrant,+ type ConnectionGrantsResponse,type ToolConnection,} from "@paperclipai/shared";import { queryKeys } from "@/lib/queryKeys";@@ -14,20 +16,75 @@ import {type OAuthConnectPhase,} from "@/pages/apps/AppsConnect";import { SetupPanel } from "@/pages/apps/app-detail/SetupPanel";-import { ReconnectCard } from "@/pages/apps/app-detail/AdvancedPanel";+import {+ AdvancedPanel,+ ReconnectCard,+} from "@/pages/apps/app-detail/AdvancedPanel";+import { IdentitiesSection } from "@/pages/apps/app-detail/IdentitiesSection";const COMPANY_ID = "company-storybook";-const NOTION = CONNECTABLE_APP_DEFINITIONS.find((app) => app.slug === "notion") as AppDefinition;-const ZAPIER = CONNECTABLE_APP_DEFINITIONS.find((app) => app.slug === "zapier") as AppDefinition;-const GITHUB = CONNECTABLE_APP_DEFINITIONS.find((app) => app.slug === "github") as AppDefinition;+const NOTION = CONNECTABLE_APP_DEFINITIONS.find(+ (app) => app.slug === "notion",+) as AppDefinition;+const ZAPIER = CONNECTABLE_APP_DEFINITIONS.find(+ (app) => app.slug === "zapier",+) as AppDefinition;+const GITHUB = CONNECTABLE_APP_DEFINITIONS.find(+ (app) => app.slug === "github",+) as AppDefinition;function seededClient() {const client = new QueryClient({defaultOptions: {- queries: { staleTime: Infinity, gcTime: Infinity, retry: false, refetchOnMount: false },+ queries: {+ staleTime: Infinity,+ gcTime: Infinity,+ retry: false,+ refetchOnMount: false,+ },+ },+ });+ client.setQueryData(queryKeys.apps.gallery(COMPANY_ID), {+ apps: [NOTION, ZAPIER, GITHUB],+ credentialSources: {+ vercelConnect: {+ available: true,+ enabled: true,+ authentication: "access_token",+ manageUrl: "https://vercel.com/connect",+ reason: null,+ },},});- client.setQueryData(queryKeys.apps.gallery(COMPANY_ID), { apps: [NOTION, ZAPIER, GITHUB] });+ client.setQueryData(queryKeys.tools.applications(COMPANY_ID), {+ applications: [+ {+ id: "application-notion",+ companyId: COMPANY_ID,+ name: "Notion",+ applicationKey: "notion",+ status: "active",+ metadata: {},+ },+ ],+ });+ client.setQueryData(queryKeys.tools.connections(COMPANY_ID), {+ connections: [notionConnection()],+ });+ client.setQueryData(queryKeys.access.companyUserDirectory(COMPANY_ID), {+ users: [+ {+ principalId: "board-user",+ status: "active",+ user: {+ id: "board-user",+ name: "Dotta",+ email: "[email protected]",+ image: null,+ },+ },+ ],+ });return client;}@@ -42,7 +99,13 @@ function BrowseHost() {);}-function OAuthStateHost({ phase, error }: { phase: OAuthConnectPhase; error?: string }) {+function OAuthStateHost({+ phase,+ error,+}: {+ phase: OAuthConnectPhase;+ error?: string;+}) {return (<div className="mx-auto max-w-5xl p-6"><OAuthConnectStateScreen@@ -56,7 +119,9 @@ function OAuthStateHost({ phase, error }: { phase: OAuthConnectPhase; error?: st);}-function notionConnection(overrides: Partial<ToolConnection> = {}): ToolConnection {+function notionConnection(+ overrides: Partial<ToolConnection> = {},+): ToolConnection {return {id: "connection-notion",companyId: COMPANY_ID,@@ -67,8 +132,8 @@ function notionConnection(overrides: Partial<ToolConnection> = {}): ToolConnectiownership: "dcr",transport: "mcp_remote",authKind: "oauth",- credentialPolicy: "per_user",credentialSource: "paperclip_vault",+ credentialPolicy: "per_user",status: "active",transportConfig: { url: "https://mcp.notion.com/mcp" },config: {@@ -91,25 +156,131 @@ function notionConnection(overrides: Partial<ToolConnection> = {}): ToolConnecti};}+function personalGrant(): ConnectionGrant {+ return {+ id: "grant-notion-personal",+ companyId: COMPANY_ID,+ connectionId: "connection-notion",+ kind: "user",+ subjectUserId: "board-user",+ providerTenant: { name: "Dotta" },+ credentialSecretRefs: [],+ status: "active",+ isDefault: true,+ createdByAgentId: null,+ createdByUserId: "board-user",+ revokedAt: null,+ revokedByAgentId: null,+ revokedByUserId: null,+ lastUsedAt: new Date("2026-08-06T19:00:00.000Z"),+ createdAt: new Date("2026-08-06T18:55:00.000Z"),+ updatedAt: new Date("2026-08-06T19:00:00.000Z"),+ delegations: [+ {+ id: "delegation-1",+ companyId: COMPANY_ID,+ grantId: "grant-notion-personal",+ agentId: "agent-1",+ createdByUserId: "board-user",+ createdAt: new Date("2026-08-06T19:00:00.000Z"),+ },+ ],+ capabilities: { canRevoke: true, canEditAudience: false },+ };+}++function personalGrantsResponse(+ grant: ConnectionGrant,+): ConnectionGrantsResponse {+ return {+ connection: { id: "connection-notion", uid: "notion-storybook" },+ grants: [grant],+ capabilities: {+ canConfigure: true,+ canCreateOrganizationGrant: false,+ canSetCompanyInstall: true,+ canConnectAsCurrentUser: true,+ canManageAgentInstalls: true,+ canViewOtherPersonalIdentities: false,+ editableAgentIds: ["agent-1"],+ },+ currentUserId: "board-user",+ members: [+ { userId: "board-user", name: "Dotta", email: "[email protected]" },+ ],+ };+}+function ConnectedHost() {+ const client = useMemo(() => seededClient(), []);+ const connection = notionConnection();+ const grant = personalGrant();return (- <div className="mx-auto max-w-3xl p-6">- <header className="mb-6 flex items-center gap-3">- <AppLogo name={NOTION.name} logoUrl={NOTION.branding.logoUrl} size={44} />- <div>- <h1 className="text-2xl font-bold tracking-tight">Notion</h1>- <p className="mt-1 text-sm text-muted-foreground">Connected app setup</p>+ <QueryClientProvider client={client}>+ <div className="mx-auto w-screen max-w-3xl p-6">+ <header className="mb-6 flex items-center gap-3">+ <AppLogo+ name={NOTION.name}+ logoUrl={NOTION.branding.logoUrl}+ size={44}+ />+ <div>+ <h1 className="text-2xl font-bold tracking-tight">Notion</h1>+ <p className="mt-1 text-sm text-muted-foreground">+ Connected app setup+ </p>+ </div>+ </header>+ <div className="space-y-8">+ <SetupPanel+ connection={connection}+ galleryEntry={NOTION}+ onUpdateConfig={() => undefined}+ configUpdateDisabled={false}+ agentsSummary="1 agent"+ permissionsSummary="Allowed for 28 · Ask first for 0 · Off for 0"+ permissionsLoading={false}+ onOpenPermissions={() => undefined}+ identities={+ <IdentitiesSection+ appName="Notion"+ credentialPolicy="per_user"+ ownerUserId="board-user"+ connectedUser={{ label: "Dotta", image: null }}+ grantsQuery={personalGrantsResponse(grant)}+ loading={false}+ error={false}+ onConnectAsMe={() => undefined}+ onConnectOrganization={() => undefined}+ onReplaceAudience={() => undefined}+ connectPending={false}+ audiencePending={false}+ audienceError={null}+ audienceGrantId={null}+ onOpenAudience={() => undefined}+ onCloseAudience={() => undefined}+ />+ }+ />+ <AdvancedPanel+ connection={connection}+ appName="Notion"+ galleryEntry={NOTION}+ removing={false}+ onRemove={() => undefined}+ onReplaced={() => undefined}+ appToggleDisabled={false}+ onToggleApp={() => undefined}+ identityGrant={grant}+ identityCurrentUserId="board-user"+ identityProviderName="Notion"+ credentialPolicy="per_user"+ onReconnectIdentity={() => undefined}+ onRevokeIdentity={() => undefined}+ /></div>- </header>- <SetupPanel- connection={notionConnection()}- galleryEntry={NOTION}- onToggleApp={() => undefined}- appToggleDisabled={false}- onUpdateConfig={() => undefined}- configUpdateDisabled={false}- />- </div>+ </div>+ </QueryClientProvider>);}@@ -118,12 +289,15 @@ function ReconnectRequiredHost() {<div className="mx-auto max-w-3xl p-6"><header className="mb-6"><h1 className="text-2xl font-bold tracking-tight">Notion</h1>- <p className="mt-1 text-sm text-muted-foreground">Connection needs attention</p>+ <p className="mt-1 text-sm text-muted-foreground">+ Connection needs attention+ </p></header><ReconnectCardconnection={notionConnection({healthStatus: "failed",- healthMessage: "Notion authorization expired or was revoked (invalid_grant).",+ healthMessage:+ "Notion authorization expired or was revoked (invalid_grant).",lastError: "invalid_grant",})}galleryEntry={NOTION}@@ -133,6 +307,33 @@ function ReconnectRequiredHost() {);}+function VercelConnectProvenanceHost() {+ return (+ <div className="mx-auto max-w-3xl p-6">+ <ReconnectCard+ connection={notionConnection({+ credentialSource: "vercel_connect",+ externalCredential: {+ provider: "vercel_connect",+ connectorId: "scl_storybook",+ connectorUid: "notion-paperclip",+ service: "notion",+ connectorType: "oauth",+ principalMode: "user",+ headerName: "Authorization",+ headerPrefix: "Bearer ",+ scopes: ["*"],+ },+ healthStatus: "failed",+ healthMessage: "This Vercel Connect identity needs authorization.",+ })}+ galleryEntry={NOTION}+ onReconnected={() => undefined}+ />+ </div>+ );+}+const meta: Meta = {title: "Apps/Notion MCP connect flow (PAP-16650)",parameters: { layout: "fullscreen" },@@ -175,3 +376,8 @@ export const ReconnectRequired: Story = {name: "6 — Reconnect required",render: () => <ReconnectRequiredHost />,};++export const VercelConnectReconnect: Story = {+ name: "7 — Vercel Connect reconnect",+ render: () => <VercelConnectProvenanceHost />,+};diff --git a/ui/storybook/stories/permitted-vs-installed.stories.tsx b/ui/storybook/stories/permitted-vs-installed.stories.tsxindex 9a1cd1fb35..dc9fbe7bec 100644--- a/ui/storybook/stories/permitted-vs-installed.stories.tsx+++ b/ui/storybook/stories/permitted-vs-installed.stories.tsx@@ -17,6 +17,7 @@ import type { RequestConfirmationInteraction } from "@/lib/issue-thread-interactimport { queryKeys } from "@/lib/queryKeys";import { AgentToolsTab } from "@/pages/AgentToolsTab";import { PermissionsPanel } from "@/pages/apps/app-detail/PermissionsPanel";+import type { AccessDraft } from "@/pages/apps/app-detail/types";import { AccessStep } from "@/pages/apps/AppsConnect";import type { InstallState } from "@/lib/tool-installs";@@ -137,11 +138,14 @@ function PanelHarness({capabilities?: ToolConnectionCapabilities;}) {const [state, setState] = useState(install);+ const [access, setAccess] = useState<AccessDraft>({ mode: "all", agentIds: new Set() });return (<div className="mx-auto max-w-3xl bg-background p-6"><PermissionsPanelcapabilities={capabilities}+ appName="Gmail"agents={AGENTS}+ access={access}install={state}readOnly={GMAIL_TOOLS.filter((t) => t.isReadOnly)}canChange={GMAIL_TOOLS.filter((t) => !t.isReadOnly)}@@ -151,6 +155,7 @@ function PanelHarness({pending={false}installPending={false}refreshPending={false}+ onSaveAccess={setAccess}onSaveInstall={setState}onSetActionPermission={() => {}}onReviewQuarantined={() => {}}diff --git a/ui/storybook/stories/personal-connection-identity.stories.tsx b/ui/storybook/stories/personal-connection-identity.stories.tsxindex 063454adf1..d9a16a444d 100644--- a/ui/storybook/stories/personal-connection-identity.stories.tsx+++ b/ui/storybook/stories/personal-connection-identity.stories.tsx@@ -7,7 +7,6 @@ import type {ToolConnectionCredentialPolicy,} from "@paperclipai/shared";import { IdentitiesSection } from "@/pages/apps/app-detail/IdentitiesSection";-import { actsAsSummary } from "@/pages/apps/connection-identity";// ---------------------------------------------------------------------------// PAP-17835 — personal connection identity UX review harness.@@ -100,11 +99,7 @@ function personalGrant(overrides: Partial<ConnectionGrant> = {}): ConnectionGran});}-/**- * Renders the identity surface the way the Setup tab does, including the header- * "acts as" sentence — that sentence is the at-a-glance answer the design- * requires, so a screenshot of the rows alone would not show the whole state.- */+/** Renders the fixed account surface used on the Setup tab. */function IdentitiesHarness({credentialPolicy = "per_user",grants,@@ -130,30 +125,17 @@ function IdentitiesHarness({currentUserId: CURRENT_USER,members: MEMBERS,};- const actsAs = actsAsSummary(credentialPolicy);return (- <div className="mx-auto max-w-3xl bg-background p-6">- <header className="mb-6">- <h1 className="text-2xl font-bold tracking-tight">Gmail</h1>- <p className="mt-0.5 text-xs text-muted-foreground">- <span className="font-medium text-foreground">{actsAs.title}</span>- {" · "}- {actsAs.detail}- </p>- </header>+ <div className="mx-auto max-w-4xl bg-background p-8"><IdentitiesSectionappName="Gmail"- providerName="Gmail"credentialPolicy={credentialPolicy}+ ownerUserId={CURRENT_USER}+ connectedUser={{ label: "Carol", image: null }}grantsQuery={loading || error ? undefined : response}- agents={[{ id: "agent-1", name: "Outreach agent", title: "Growth", status: "active" }]}- agentsLoading={false}- agentsError={false}loading={loading}error={error}connectPending={false}- revokePending={false}- delegationPending={false}audiencePending={false}audienceError={audienceError}audienceGrantId={openAudience}@@ -161,9 +143,6 @@ function IdentitiesHarness({onCloseAudience={() => setOpenAudience(null)}onConnectAsMe={() => {}}onConnectOrganization={() => {}}- onReconnectOrganization={() => {}}- onRevokeGrant={() => {}}- onReplaceDelegations={() => {}}onReplaceAudience={() => {}}/></div>@@ -177,10 +156,10 @@ const meta: Meta = {export default meta;type Story = StoryObj;-// --- Gate 3: personal connected, organization missing ----------------------+// --- Gate 3: fixed personal identity ----------------------------------------export const SetupPersonalConnectedOrganizationMissing: Story = {- name: "3 · Setup — your identity connected, organization missing",+export const SetupPersonalConnectedOrganizationHidden: Story = {+ name: "3 · Setup — your identity connected, organization hidden",render: () => (<IdentitiesHarnessgrants={[personalGrant({ providerTenant: { name: "[email protected]" } })]}@@ -193,10 +172,10 @@ export const SetupPersonalNotConnected: Story = {render: () => <IdentitiesHarness grants={[]} />,};-// --- Gate 4: organization identity with a selected audience, manager view ---+// --- Gate 4: legacy alternates stay hidden after setup ----------------------export const SetupManagerOversight: Story = {- name: "4 · Setup — selected audience + manager oversight",+export const SetupFixedPersonalIdentity: Story = {+ name: "4 · Setup — fixed personal identity",render: () => (<IdentitiesHarnesscredentialPolicy="per_user_with_fallback"@@ -273,6 +252,7 @@ export const SetupViewerReadOnly: Story = {name: "7 · Setup — viewer read-only",render: () => (<IdentitiesHarness+ credentialPolicy="shared"capabilities={VIEWER_CAPABILITIES}grants={[grant({