Files
PaperClipAI/ui/src/pages/tools/PasteConfigTab.tsx
T
DottaandClaude Opus 5.5 8de6686739 fix(apps): save action choices when the provider no longer offers some actions (#22877)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Connections give agents actions in other apps, and the Permissions
page controls which actions agents can use
> - A managed Google Workspace connection moved from Paperclip's REST
tools to Google's MCP servers (#22815)
> - Google's MCP servers do not list two Gmail actions, so the catalog
refresh marked them as removed (`disabled`, `mcp_tool_removed`)
> - The Permissions page still sent these two actions as enabled, and
the server refused every save that contained them, except on remote MCP
aggregators
> - An admin could not release the 34 held actions, so the connection
stayed unusable
> - This pull request makes the server accept a removed action for every
connection kind, and makes the UI stop sending disabled or removed
actions
> - The benefit is that an admin can always save the review after a
provider removes actions, and a disabled action still cannot be turned
on

## Linked Issues or Issue Description

Refs #22815

**What happened?**

On a managed Google Workspace connection that runs on Google's MCP
servers, the Permissions page showed "Review 34 new actions". After
"Turn all on" and "Save choices", the save failed with the message
"Couldn't save that — Disabled actions cannot be enabled". The held
actions stayed held.

**What did you expect to happen?**

The save releases the reviewed actions. Actions that Google no longer
offers stay off and do not block the save.

**Steps to reproduce**

1. Connect Google Workspace with the managed method while the transport
is Paperclip REST. Keep all actions on.
2. Move the connection to Google's MCP servers (#22815). The refresh
holds the actions for review, and Google's listing does not include
`gmail__list_threads` and `gmail__search_messages`.
3. Open the connection's Permissions page. Select "Review 34 new
actions", then "Turn all on", then "Save choices".
4. See the error "Disabled actions cannot be enabled".

**Cause**

- `useConnectionPermissionSave.ts` sent `enabledCatalogEntryIds:
[...next.enabled]`. This set came from the saved profile and still
contained the two removed actions.
- `finishGalleryAppConnection` in `server/src/services/tool-access.ts`
refused an enabled row with `status === "disabled"`. It accepted a
removed row (`quarantineReason === "mcp_tool_removed"`) only for remote
MCP aggregators (`isRemoteMcpConnectorMethod`). The catalog refresh
writes `mcp_tool_removed` also for Google Workspace and plugin
connections, so these connections did not get the same exception.

## What Changed

- Server: `finishGalleryAppConnection` accepts a row that the provider's
listing removed (`mcp_tool_removed`) for every connection kind. Only the
catalog refresh writes this marker, and only when the provider's listing
no longer has the action. This is the same behavior that remote MCP
aggregators already had. Any other disabled row is still refused with
"Disabled actions cannot be enabled". A removed row is not active, so
the gateway does not offer it to agents.
- Shared: `@paperclipai/shared` has three named predicates in
`tool-catalog-availability.ts`. `isCatalogEntryOffered` is true for
active and held actions. `isCatalogEntryRemovedByProvider` is true for
`removed` rows and for `disabled` rows with `mcp_tool_removed`.
`isCatalogEntryBlocked` is true for every other disabled row. The server
and the UI use these predicates, so the rule is in one place.
- Server: the review coverage check ignores a reviewed id that the
provider removed after the page loaded. Before this change, that save
failed with "Action review decisions must cover every currently
quarantined action exactly once".
- Server: a save no longer sets a `removed` row back to active.
- UI: a new `withoutUnavailableActions` helper drops catalog entries
that are not offered (`isCatalogEntryOffered` is false) from an enabled
list.
- UI: the Permissions page save (`finishAppPermissions` in
`useConnectionPermissionSave.ts`) sends only available actions as
enabled or Ask first. The page already showed and counted only active
and held actions, so the removed actions do not show, count, or toggle.
The page has no existing pattern for removed actions, so this change
adds no new text.
- UI: the setup flow (`ConnectionSetupFlow.tsx`, which also serves
task-hosted setup) and the pasted-config flow (`PasteConfigTab.tsx`)
also drop disabled actions before they finish a connection. Before this
change, a provider-blocked action (for example a Gmail write action on a
read-only method) could make the first save fail the same way.
`RemoteMcpProductionSetup.tsx` already sends only active actions.
`QuarantinedActionsReview` in `SetupPanel.tsx` selects only from held
actions.

## Verification

- Red, then green:
`server/src/__tests__/google-workspace-mcp-transport.test.ts` → "saves
the review when Google no longer offers actions that were on, and still
refuses a disabled action". The test saves a managed Google Workspace
connection on REST, moves it to Google's MCP servers while Google does
not list `list_threads` and `search_messages`, then saves the review
with the removed actions in the enabled list. Before the fix it failed
with "Disabled actions cannot be enabled". After the fix it passes. The
same test makes sure that a disabled action without the removal marker
is still refused, and that agents are not offered the removed actions.
- Red, then green:
`ui/src/pages/apps/app-detail/action-permissions.test.ts` →
"finishAppPermissions never asks to turn on an action Google no longer
offers or a disabled action". Without the filter, the test fails.
- `packages/shared/src/tool-catalog-availability.test.ts` covers the
three predicates.
- The transport test also sends the removed ids in
`reviewedCatalogEntryIds`. Without the coverage fix it fails with
"Action review decisions must cover every currently quarantined action
exactly once". It also makes sure that the removed rows stay disabled
after the save.
- Local runs: `google-workspace-mcp-transport.test.ts` and
`tool-access-service.test.ts` (542 passed). UI tests in `app-detail`,
`features/connections` and `pages/tools` (143 passed).
- `pnpm verify` selected the full server suite (1520 files) because
`tool-access.ts` is a shared service. On this machine, under load from
other sessions, 31 of 33876 tests failed. The run output did not keep
the names of the failed tests. The touched test files pass when run
alone, and the CI server shards run the full suite on the final head.
- `tsc --noEmit` for `server` and for `ui/src`.

## Risks

- Low risk. The security rule stays: a disabled action that the provider
did not remove cannot be turned on.
- Behavior change: Google Workspace and plugin connections now accept a
removed action in the enabled list, as remote MCP aggregators already
did. The UI no longer sends removed actions, so after a save from the
page a removed action stays off if the provider lists it again.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edits, test runs).

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [ ] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 04:32:26 -06:00

616 lines
24 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useEffect, useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { useMutation } from "@tanstack/react-query";
import { CheckCircle2, KeyRound, Loader2, ShieldCheck } from "lucide-react";
import type {
ConnectToolAppResult,
McpJsonImportDraft,
McpJsonImportPreview,
ToolAppConnectionActionSummary,
ToolOAuthStartResult,
} from "@paperclipai/shared";
import { QueryErrorState } from "@/components/QueryView";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { ToggleSwitch } from "@/components/ui/toggle-switch";
import { toolsApi } from "@/api/tools";
import { useAuthorizationWindow } from "@/hooks/useAuthorizationWindow";
import { readOAuthWindowOutcome } from "@/lib/oauthWindowOutcome";
import { useNavigate } from "@/lib/router";
import {
OAuthConnectStateScreen,
type OAuthConnectPhase,
} from "@/features/connections/ConnectionSetupFlow";
import { endpointHost } from "@/pages/apps/generic-mcp-connect";
import { withoutUnavailableActions } from "@/pages/apps/app-detail/action-permissions";
import { McpConfigHelpDialog } from "./McpConfigHelpDialog";
import { describeError } from "@/api/errors";
const SAMPLE_CONFIG = `{
"mcpServers": {
"github": {
"command": "npx -y @modelcontextprotocol/server-github",
"env": { "GITHUB_TOKEN": "ghp_..." }
}
}
}`;
/** Turn an env/header key (e.g. `GITHUB_TOKEN`) into a friendly field label. */
function humanizeKey(raw: string): string {
const cleaned = raw.replace(/[_-]+/g, " ").trim().toLowerCase();
if (!cleaned) return "Key";
return cleaned.charAt(0).toUpperCase() + cleaned.slice(1);
}
function draftSummary(draft: McpJsonImportDraft): string {
const keyCount = draft.credentialFields.length || draft.credentialRefs.length;
const where = draft.transport === "local_stdio" ? "Runs in your workspace" : "Connects over the web";
if (keyCount === 0) return `${where} · no keys needed`;
return `${where} · needs ${keyCount} ${keyCount === 1 ? "key" : "keys"}`;
}
/**
* A draft is connectable when it's a remote server with a real http(s) URL — that
* is exactly what the "Connect with a link" wizard step needs to land an active
* `tool_connection`. Imported stdio commands stay draft-only (they require an
* approved Paperclip template), so they get no hand-off here.
*/
function draftConnectUrl(draft: McpJsonImportDraft): string | null {
if (draft.transport !== "mcp_remote") return null;
const raw = draft.config?.url;
if (typeof raw !== "string") return null;
try {
const parsed = new URL(raw.trim());
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
return parsed.toString();
} catch {
return null;
}
}
function credentialValueKey(draft: McpJsonImportDraft, configPath: string): string {
return `${draft.name}::${configPath}`;
}
function credentialValuesForDraft(draft: McpJsonImportDraft, values: Record<string, string>): Record<string, string> {
const out: Record<string, string> = {};
for (const field of draft.credentialFields) {
const value = values[credentialValueKey(draft, field.configPath)]?.trim();
if (value) out[field.configPath] = value;
}
return out;
}
function missingCredentialFields(draft: McpJsonImportDraft, values: Record<string, string>): string[] {
return draft.credentialFields
.filter((field) => field.required)
.filter((field) => !values[credentialValueKey(draft, field.configPath)]?.trim())
.map((field) => field.configPath);
}
function askFirstLevelsFrom(result: ConnectToolAppResult): string[] {
const raw = (result.suggestedDefaults as { askFirstRiskLevels?: unknown })?.askFirstRiskLevels;
return Array.isArray(raw) ? raw.filter((x): x is string => typeof x === "string") : [];
}
/**
* M8a — "Paste a config" tab on the Advanced door (PAP-10862, plan D8).
*
* A thin, honest surface over `POST /companies/:id/tools/mcp/import-json`: paste
* the snippet a README tells you to copy, and we parse it into a friendly
* preview (humanized field labels, never the raw transport jargon). This is one
* of the two M8 screens where "MCP" vocabulary is allowed (PAP-10827 vocab map).
*/
export function PasteConfigTab({ companyId }: { companyId: string }) {
const navigate = useNavigate();
const [draftText, setDraftText] = useState("");
const [preview, setPreview] = useState<McpJsonImportPreview | null>(null);
const [connectionNames, setConnectionNames] = useState<Record<string, string>>({});
const [credentialValues, setCredentialValues] = useState<Record<string, string>>({});
const [connectResult, setConnectResult] = useState<ConnectToolAppResult | null>(null);
const [enabled, setEnabled] = useState<Record<string, boolean>>({});
const [activatedName, setActivatedName] = useState<string | null>(null);
const [oauthPhase, setOAuthPhase] = useState<OAuthConnectPhase>("entry");
const [oauthError, setOAuthError] = useState<string | null>(null);
const [authorizationHost, setAuthorizationHost] = useState<string | null>(null);
const authorization = useAuthorizationWindow();
const importMutation = useMutation({
mutationFn: (mcpJson: string) => toolsApi.importMcpJson(companyId, { mcpJson }),
onSuccess: (result) => {
setPreview(result);
setConnectionNames(Object.fromEntries(result.drafts.map((draft) => [draft.name, draft.name])));
setConnectResult(null);
setActivatedName(null);
},
});
const openAuthorizationPage = async (
authorizationUrl: string,
handoff?: ToolOAuthStartResult["handoff"],
) => {
try {
const target = await authorization.open({ authorizationUrl, handoff });
setAuthorizationHost(target.host);
setOAuthPhase("redirecting");
} catch (error) {
setOAuthPhase("error");
setOAuthError(describeError(error).body);
}
};
const { windowRef: authorizationWindow, cancel: closeAuthorization } = authorization;
const oauthConnectionId = connectResult?.connectionId;
useEffect(() => {
if (oauthPhase !== "redirecting" || !oauthConnectionId) return;
let cancelled = false;
let checking = false;
const check = async () => {
if (cancelled || checking) return;
const outcome = readOAuthWindowOutcome(authorizationWindow.current, oauthConnectionId);
if (outcome === "waiting") return;
if (outcome !== "connected") {
closeAuthorization();
setOAuthPhase("error");
setOAuthError(outcome === "closed" ? "The sign-in window closed. Try again to finish connecting."
: outcome === "denied" ? "Sign-in was cancelled. Try again when you’re ready."
: "Sign-in failed. Try again to finish connecting.");
return;
}
checking = true;
try {
const saved = await toolsApi.getConnection(oauthConnectionId);
if (!cancelled && saved.status === "active") {
cancelled = true;
closeAuthorization();
navigate(`/apps/${oauthConnectionId}/permissions`);
}
} catch { /* A later focus or poll can retry verification. */ }
finally { checking = false; }
};
const timer = window.setInterval(() => void check(), 1000);
window.addEventListener("focus", check);
return () => { cancelled = true; window.clearInterval(timer); window.removeEventListener("focus", check); };
}, [oauthPhase, oauthConnectionId, authorizationWindow, closeAuthorization, navigate]);
const oauthStartMutation = useMutation({
mutationFn: (connectionId: string) => toolsApi.startOAuth(connectionId),
onSuccess: (start) => void openAuthorizationPage(start.authorizationUrl, start.handoff),
onError: (error) => {
authorization.cancel();
setOAuthPhase("error");
setOAuthError(
describeError(error).body,
);
},
});
const connectMutation = useMutation({
mutationFn: (draft: McpJsonImportDraft) => {
const url = draftConnectUrl(draft);
if (!url) throw new Error("Only remote HTTP drafts can be checked and activated from pasted config.");
return toolsApi.connectApp(companyId, {
link: url,
name: connectionNames[draft.name]?.trim() || draft.name,
credentialValues: credentialValuesForDraft(draft, credentialValues),
});
},
onSuccess: (result) => {
setConnectResult(result);
if (result.auth?.kind === "oauth") {
setActivatedName(null);
setAuthorizationHost(null);
setOAuthError(null);
if (result.auth.manualClientRequired) {
authorization.cancel();
setOAuthPhase("error");
setOAuthError(
result.auth.manualClientReason
?? "This server requires OAuth client details from its provider settings. Continue in setup to add them.",
);
return;
}
const startUrl = result.auth.startUrl?.trim();
if (startUrl) {
void openAuthorizationPage(startUrl, result.auth.handoff);
} else {
setOAuthPhase("starting");
oauthStartMutation.mutate(result.connectionId);
}
return;
}
authorization.cancel();
const defaults: Record<string, boolean> = {};
for (const action of result.actions.readOnly) defaults[action.catalogEntryId] = true;
for (const action of result.actions.canMakeChanges) defaults[action.catalogEntryId] = true;
setEnabled(defaults);
setActivatedName(null);
},
onError: () => authorization.cancel(),
});
const finishMutation = useMutation({
mutationFn: () => {
const askFirstLevels = connectResult ? askFirstLevelsFrom(connectResult) : [];
const enabledIds = withoutUnavailableActions(
Object.entries(enabled).filter(([, on]) => on).map(([id]) => id),
connectResult?.catalog ?? [],
);
const askFirstIds = (connectResult?.actions.canMakeChanges ?? [])
.filter((action) => enabledIds.includes(action.catalogEntryId) && askFirstLevels.includes(action.riskLevel))
.map((action) => action.catalogEntryId);
return toolsApi.finishApp(companyId, connectResult!.connectionId, {
enabledCatalogEntryIds: enabledIds,
askFirstCatalogEntryIds: askFirstIds,
access: "all_agents",
});
},
onSuccess: () => setActivatedName(connectResult?.application.name ?? "Imported app"),
});
const drafts = preview?.drafts ?? [];
const canSubmit = draftText.trim().length > 0 && !importMutation.isPending;
const localParseError = useMemo(() => {
const trimmed = draftText.trim();
if (!trimmed) return null;
try {
JSON.parse(trimmed);
return null;
} catch {
return "That doesn't look like valid JSON yet — paste the whole snippet, including the outer braces.";
}
}, [draftText]);
if (connectResult?.auth?.kind === "oauth") {
const connectionUrl = typeof connectResult.connection.config?.url === "string"
? connectResult.connection.config.url
: typeof connectResult.connection.transportConfig?.url === "string"
? connectResult.connection.transportConfig.url
: "";
return (<>
{authorization.fallback}
<OAuthConnectStateScreen
identity={{
name: connectResult.application.name,
unverifiedHost: endpointHost(connectionUrl),
}}
phase={oauthPhase}
error={oauthError}
authorizationHost={authorizationHost}
onRetry={() => {
authorization.reserve();
setOAuthError(null);
setAuthorizationHost(null);
setOAuthPhase("starting");
oauthStartMutation.mutate(connectResult.connectionId);
}}
onBack={() => navigate(`/apps/${connectResult.connectionId}/permissions`)}
onCancel={() => navigate("/apps")}
/>
</>);
}
return (
<div className="space-y-5">
<div className="flex max-w-2xl items-start gap-1.5">
<p className="text-sm text-muted-foreground">
Paste the MCP config snippet from the tool's README and we'll turn it into a friendly setup.
</p>
<McpConfigHelpDialog />
</div>
<p className="text-xs text-muted-foreground">
Just a URL?{" "}
<Link to="/apps" className="text-primary hover:underline">
Browse planned app connections
</Link>{" "}
instead.
</p>
<div className="space-y-2">
<Textarea
value={draftText}
onChange={(event) => {
setDraftText(event.target.value);
if (preview) setPreview(null);
setConnectResult(null);
setActivatedName(null);
}}
spellCheck={false}
rows={10}
placeholder={SAMPLE_CONFIG}
className="min-h-(--sz-220px) bg-slate-900 font-mono text-(length:--text-compact) leading-relaxed text-slate-100 placeholder:text-slate-500 focus-visible:ring-slate-400"
/>
{localParseError ? (
<p className="text-xs text-amber-600">{localParseError}</p>
) : (
<p className="text-xs text-muted-foreground">
Paste an MCP config — the snippet a README tells you to copy.
</p>
)}
</div>
<div className="flex flex-wrap items-center gap-3">
<Button
onClick={() => importMutation.mutate(draftText)}
disabled={!canSubmit || Boolean(localParseError)}
>
{importMutation.isPending ? "Checking…" : "Check config"}
</Button>
<span className="text-xs text-muted-foreground">
We'll read it and show what we found before anything is saved.
</span>
</div>
{importMutation.error ? <QueryErrorState error={importMutation.error} action="check the config" /> : null}
{preview ? (
drafts.length === 0 ? (
<div className="rounded-lg border border-dashed border-border p-6 text-sm text-muted-foreground">
We couldn't find an app in that config. Double-check you pasted the whole snippet.
</div>
) : (
<div className="space-y-3">
<h3 className="flex items-center gap-2 text-sm font-semibold text-foreground">
<CheckCircle2 className="h-4 w-4 text-emerald-600" />
We found {drafts.length} {drafts.length === 1 ? "app" : "apps"} in that config
</h3>
{drafts.map((draft, index) => {
const url = draftConnectUrl(draft);
const missingFields = missingCredentialFields(draft, credentialValues);
return (
<DraftCard
key={`${draft.name}-${index}`}
draft={draft}
connectionName={connectionNames[draft.name] ?? draft.name}
onConnectionNameChange={(value) =>
setConnectionNames((previous) => ({ ...previous, [draft.name]: value }))
}
credentialValues={credentialValues}
onCredentialChange={(configPath, value) =>
setCredentialValues((prev) => ({ ...prev, [credentialValueKey(draft, configPath)]: value }))
}
checking={connectMutation.isPending && connectMutation.variables?.name === draft.name}
canCheck={Boolean(url) && missingFields.length === 0}
onCheck={url ? () => { authorization.reserve(); connectMutation.mutate(draft); } : undefined}
/>
);
})}
{drafts.some((d) => draftConnectUrl(d)) ? (
<p className="text-xs text-muted-foreground">
Checking a remote app creates a draft connection, stores any header replacements as Paperclip secrets,
and runs health/catalog discovery before activation.
</p>
) : (
<p className="text-xs text-muted-foreground">
We humanized the field names from the config. These run-in-your-workspace tools stay as drafts until an
admin maps them to an approved template.
</p>
)}
</div>
)
) : null}
{connectMutation.error ? <QueryErrorState error={connectMutation.error} action="check the app" /> : null}
{connectResult ? (
<CatalogReview
result={connectResult}
enabled={enabled}
onToggle={(id, on) => setEnabled((prev) => ({ ...prev, [id]: on }))}
onBulk={(ids, on) =>
setEnabled((prev) => {
const next = { ...prev };
for (const id of ids) next[id] = on;
return next;
})
}
finishing={finishMutation.isPending}
activatedName={activatedName}
onFinish={() => finishMutation.mutate()}
/>
) : null}
{finishMutation.error ? <QueryErrorState error={finishMutation.error} action="finish setup" /> : null}
</div>
);
}
function DraftCard({
draft,
connectionName,
onConnectionNameChange,
credentialValues,
onCredentialChange,
checking,
canCheck,
onCheck,
}: {
draft: McpJsonImportDraft;
connectionName: string;
onConnectionNameChange: (value: string) => void;
credentialValues: Record<string, string>;
onCredentialChange: (configPath: string, value: string) => void;
checking: boolean;
canCheck: boolean;
onCheck?: () => void;
}) {
return (
<div className="rounded-lg border border-border bg-card p-4">
<div className="flex items-center justify-between gap-3">
<div className="min-w-0">
<div className="font-semibold text-foreground">{draft.name}</div>
<div className="text-xs text-muted-foreground">{draftSummary(draft)}</div>
</div>
{onCheck ? (
<Button size="sm" className="shrink-0" onClick={onCheck} disabled={checking || !canCheck}>
{checking ? <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" /> : null}
Check actions
</Button>
) : null}
</div>
{onCheck ? (
<label className="mt-4 block max-w-sm space-y-1 text-xs font-medium text-foreground">
Connection name
<Input
value={connectionName}
onChange={(event) => onConnectionNameChange(event.target.value)}
placeholder={draft.name}
className="h-8 text-xs"
/>
</label>
) : null}
{draft.credentialFields.length > 0 ? (
<div className="mt-4 space-y-3">
{draft.credentialFields.map((field) => (
<div key={`${field.configPath}-${field.key}`} className="space-y-1">
<div className="flex items-center gap-1.5 text-xs font-medium text-foreground">
<KeyRound className="h-3.5 w-3.5 text-muted-foreground" />
{humanizeKey(field.label || field.key)}
</div>
<div className="flex items-center gap-2">
<code className="rounded border border-border bg-muted/40 px-2 py-1 font-mono text-(length:--text-micro) text-muted-foreground">
{field.key}
</code>
<Input
type="password"
value={credentialValues[credentialValueKey(draft, field.configPath)] ?? ""}
onChange={(event) => onCredentialChange(field.configPath, event.target.value)}
placeholder="Paste replacement value"
className="h-8 max-w-sm text-xs"
/>
</div>
</div>
))}
</div>
) : draft.credentialRefs.length > 0 ? (
<p className="mt-3 text-xs text-muted-foreground">
Keys from this config stay draft-only until an admin maps them to an approved template.
</p>
) : (
<p className="mt-3 text-xs text-muted-foreground">No keys needed for this one.</p>
)}
{draft.warnings.length > 0 ? (
<ul className="mt-4 space-y-1 border-t border-border pt-3">
{draft.warnings.map((warning, i) => (
<li key={i} className="text-xs text-amber-600">
{warning}
</li>
))}
</ul>
) : null}
</div>
);
}
function CatalogReview({
result,
enabled,
onToggle,
onBulk,
finishing,
activatedName,
onFinish,
}: {
result: ConnectToolAppResult;
enabled: Record<string, boolean>;
onToggle: (id: string, on: boolean) => void;
onBulk: (ids: string[], on: boolean) => void;
finishing: boolean;
activatedName: string | null;
onFinish: () => void;
}) {
const askFirstLevels = askFirstLevelsFrom(result);
const enabledCount = Object.values(enabled).filter(Boolean).length;
const total = result.actions.readOnly.length + result.actions.canMakeChanges.length;
return (
<div className="space-y-4 border-t border-border pt-5">
<div className="flex items-start justify-between gap-4">
<div>
<h3 className="flex items-center gap-2 text-sm font-semibold text-foreground">
<ShieldCheck className="h-4 w-4 text-emerald-600" />
Review actions for {result.application.name}
</h3>
<p className="mt-1 text-xs text-muted-foreground">
Health and catalog checks passed. Every discovered action starts allowed; you can narrow access after activation.
</p>
</div>
<Button size="sm" onClick={onFinish} disabled={finishing || enabledCount === 0 || Boolean(activatedName)}>
{finishing ? <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" /> : null}
Activate {enabledCount} of {total}
</Button>
</div>
<ActionGroup
title="Read-only"
actions={result.actions.readOnly}
enabled={enabled}
onToggle={onToggle}
onBulk={(on) => onBulk(result.actions.readOnly.map((action) => action.catalogEntryId), on)}
askFirstLevels={askFirstLevels}
/>
<ActionGroup
title="Can make changes"
actions={result.actions.canMakeChanges}
enabled={enabled}
onToggle={onToggle}
onBulk={(on) => onBulk(result.actions.canMakeChanges.map((action) => action.catalogEntryId), on)}
askFirstLevels={askFirstLevels}
/>
{activatedName ? (
<p className="text-xs font-medium text-emerald-700">{activatedName} is active for all agents.</p>
) : null}
</div>
);
}
function ActionGroup({
title,
actions,
enabled,
onToggle,
onBulk,
askFirstLevels,
}: {
title: string;
actions: ToolAppConnectionActionSummary[];
enabled: Record<string, boolean>;
onToggle: (id: string, on: boolean) => void;
onBulk: (on: boolean) => void;
askFirstLevels: string[];
}) {
if (actions.length === 0) return null;
return (
<div className="space-y-1">
<div className="flex items-center justify-between gap-3">
<div className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">{title}</div>
<div className="flex gap-2">
<Button type="button" size="sm" variant="ghost" className="h-7 px-2 text-xs" onClick={() => onBulk(true)}>
Turn all on
</Button>
<Button type="button" size="sm" variant="ghost" className="h-7 px-2 text-xs" onClick={() => onBulk(false)}>
Turn all off
</Button>
</div>
</div>
<div className="divide-y divide-border rounded-lg border border-border">
{actions.map((action) => {
const on = enabled[action.catalogEntryId] ?? false;
return (
<div key={action.catalogEntryId} className="flex items-center gap-3 px-3 py-2">
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-medium text-foreground">{action.title || action.toolName}</div>
<div className="truncate text-xs text-muted-foreground">
{askFirstLevels.includes(action.riskLevel) ? "Ask first when enabled" : action.riskLevel}
</div>
</div>
<ToggleSwitch checked={on} onCheckedChange={(next) => onToggle(action.catalogEntryId, next)} />
</div>
);
})}
</div>
</div>
);
}