Files
PaperClipAI/ui/src/pages/apps/chat/ChatEndpointDetail.tsx
T
DottaandPaperclip a10702a878 feat(slack): add governed tools for Slack-origin tasks (#13828)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Chat connectors let people start and continue agent tasks from other
services.
> - A Slack conversation needs access to its surrounding discussion and
Slack collaboration tools.
> - The agent must use the linked requester's access and keep private
material within its permitted audience.
> - This pull request adds Slack tools through the existing connector
contribution and approval framework.
> - People can ask an invited bot to read a discussion, create follow-up
tasks, and collaborate in Slack.

## Linked Issues or Issue Description

**Subsystem affected**

Chat connectors, connector runtime, tool gateway, and connection
Settings/Access.

**Problem or motivation**

Slack-origin tasks can receive messages but cannot inspect the rest of a
channel or act through the originating bot. People must paste context or
configure a separate integration.

**Proposed solution**

Supply typed Slack tools and a bundled skill only to the originating
task and assigned agent. Resolve the linked requester on the server.
Check bot and requester access before reads and writes. Use existing
durable actions and approvals. Retrieved messages remain source
material.

**Alternatives considered**

Slack's user-OAuth MCP server does not replace the customer-created chat
bot. An unrestricted Web API proxy would not provide suitable permission
or publication boundaries.

**Roadmap alignment**

This extends the existing MCP Tool Gateway & Apps work with a provider
contribution. It does not add a task dispatcher or a separate Slack task
lifecycle. Related: #11144 covers generic per-user MCP grant execution;
this change binds Slack bot operations to chat-origin tasks.

## What Changed

- Add 39 typed Slack tools, a method/scope matrix, a bundled skill, and
shared native/HTTP execution.
- Bind tools to company, endpoint, task, run, assigned agent, and
admitted linked requester. Check membership and revocation on each call
and before queued writes.
- Add paginated reads, bounded history search, source links, messages,
file uploads, reactions, pins, bookmarks, topics, canvases, lists, and
approved channel operations.
- Restrict private-source publication, including automatic replies and
uploaded deliverables. Keep other people's bot DMs inaccessible.
- Reuse action receipts, idempotency, approvals, and reconciliation.
Suppress an identical explicit-send/final-reply duplicate. Return
governed results through their verified originating conversation.
- Add endpoint-bound personal search OAuth storage and lifecycle. Keep
native real-time search disabled until a runtime meets Slack's
transient-result requirements. Current runtimes use bounded history
search.
- Show capabilities, scope upgrades, and personal search authorization
in Settings/Access and Storybook. Document provider and runtime limits.

## Verification

- Current head `0eb21cba4`: CI checks pass and Greptile is 5/5 with no
unresolved findings. One unchanged rapid-callback timing test passed on
a single CI retry.
- Approval presentation regressions cover board-comment precedence and
exact Slack publication; the expanded database assertion passed in CI.
The local PostgreSQL startup probe later became unavailable, so that
final assertion was verified in CI. Slack setup and failed-run retry
browser tests also passed locally.

- Full workspace typecheck and build passed. Server typecheck/build
passed again after the approval routing fix.
- Broad local suites passed in separate groups: server 12,958 tests, UI
6,555, shared 770, skills catalog 20, and other workspace packages
2,652. CLI and serialized server checks passed after environment/timeout
retries. These are composite results, not one uninterrupted green
full-suite invocation.
- PostgreSQL authority regression covers admitted identity,
cross-company/task/agent rejection, recovery, retained-session
revocation, OAuth refresh/disconnect races, approval execution, exact
publication lineage, retries, uncertain sends, and duplicate
suppression.
- Gateway/response regressions cover separate-origin approval batches
and durable continuation. Focused provider, access, search, native
runtime, route, and AgentMail regressions pass.
- Storybook capability, missing-scope, OAuth configuration,
authorization, and disconnect states were inspected in the browser.
- Live staging: read a channel decision and full thread, create exactly
two assigned backlog tasks, add a reaction, paginate discovery to
exhaustion, and return bounded search matches with source links and
coverage.
- Live staging: create/edit/read a canvas and list, inspect the canvas
in Slack, post/edit one message, and create a channel only after
approval. New channels remain disabled for responses.
- Live staging: read a response-disabled channel from the requester's
DM; writes to that channel were denied. The test setting was restored.
- Final live retest passed: explicit file upload and exact content
read-back; approved deletion of only the disposable bot message;
continuation confirmation returned to the original Slack thread without
repeating the action.
- Optional OAuth, private multi-user boundaries, native RTS, and CLI
provider execution are not fully live-qualified. The staging agent
initially supplied malformed tool arguments; valid arguments succeeded,
and the tool/skill descriptions now emphasize UUID write keys.

## Risks

- Existing Slack apps must add scopes and reinstall for new
capabilities. Provider plans and document permissions can still restrict
operations.
- Instances need an independent `PAPERCLIP_TOOL_ACTION_SIGNING_SECRET`
for governed tool actions. The staging instance was configured with
explicit operator approval; fleet provisioning is a separate gap.
- Native RTS is not exposed on current transcript-retaining runtimes.
Bounded history scans are deliberately reported as incomplete. Inline
file reads support text/canvas content up to 256 KiB; other types return
metadata.
- Private document edits fail closed when the full audience cannot be
verified. Uncertain effects other than posts/uploads require inspection
instead of blind retries.
- Shared approval-delivery code now separates outcomes by source run to
preserve origin boundaries. No database migration is required.
- A separate completion-validator gap remains when the agent cites a
prior run's registered artifact during finalization. It asked for
registration again even though Slack delivery was confirmed. This change
does not add a connector-specific task-completion policy.

## Model Used

OpenAI GPT-6 through Codex, with repository tools, code execution, and
browser testing. The exact deployed model identifier and context-window
size were not exposed in the session.

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-09-22 15:29:07 -05:00

1286 lines
53 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 { SlackToolsSettings, SlackSearchAccess } from "./SlackToolSettings";
import { defaultSlackAppName } from "./slack-app-name";
import { ChatCommunicationInstructions } from "./ChatCommunicationInstructions";
import { SlackAvatarSettings } from "./SlackAvatarStep";
import { agentsApi } from "@/api/agents";
import { agentAvatarUrl } from "@/lib/agent-avatar-url";
import { resolveAgentAppearance } from "@paperclipai/shared";
import { GitHubBotManagement, GitHubReviews } from "./GitHubBotManagement";
import { EmailEndpointSettings } from "./EmailEndpointSetup";
import { useEffect, useMemo, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
AlertTriangle,
ArrowDownLeft,
ArrowUpRight,
ChevronDown,
Check,
Activity as ActivityIcon,
Copy,
ExternalLink,
Loader2,
Pause,
Play,
RefreshCw,
Trash2,
Unlink,
} from "lucide-react";
import {
chatEndpointsApi,
type ChatActivityItem,
type ChatEndpoint,
type ChatEndpointResource,
type ChatProvider,
} from "@/api/chatEndpoints";
import { Button } from "@/components/ui/button";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { ToggleSwitch } from "@/components/ui/toggle-switch";
import { AppLogo } from "../AppLogo";
import { StatusBadge } from "@/components/StatusBadge";
import { useBreadcrumbs } from "@/context/BreadcrumbContext";
import { useToast } from "@/context/ToastContext";
import { formatDateTime } from "@/lib/utils";
import { queryKeys } from "@/lib/queryKeys";
import { copyTextToClipboard } from "@/lib/clipboard";
import { Link, Navigate, useNavigate, useParams } from "@/lib/router";
const tabs = ["settings", "access", "reviews", "conversations", "activity"] as const;
type ChatTab = (typeof tabs)[number];
const tabItems = tabs.map((value) => ({
value,
label: value[0].toUpperCase() + value.slice(1),
}));
const providerNames: Record<ChatProvider, string> = {
agentmail: "AgentMail",
slack: "Slack",
github: "GitHub",
discord: "Discord",
"microsoft-teams": "Microsoft Teams",
telegram: "Telegram",
"imessage-photon": "iMessage Photon",
};
const providerLifecycleGuidance: Record<
ChatProvider,
{ reconnect: string; remove: string }
> = {
agentmail: { reconnect: "Reconnect the same email inbox.", remove: "Disconnect email and retain task history." },
slack: {
reconnect:
"Reconnect verifies or replaces credentials for this same Slack app. It does not reinstall the app or change its workspace or channel membership.",
remove:
"Paperclip archives the endpoint, stops new ingress, and retires its saved Slack credentials. It does not uninstall the Slack app: the app remains installed, and its bot remains in channels, until you remove them in Slack.",
},
github: {
reconnect:
"Reconnect verifies this same App and installation, then updates its webhook URL, secret, and secure delivery settings. It does not reinstall the App or change repository access.",
remove:
"Paperclip archives the endpoint, stops new ingress, and retires its saved App key and webhook secret. It does not uninstall the GitHub App: the App, its installations, and its webhook settings remain until you remove or update them on GitHub.",
},
discord: {
reconnect:
"Reconnect verifies this same Discord application and server installation. It does not add or remove the bot from the server.",
remove:
"Paperclip archives the endpoint, stops its Paperclip Gateway connection, and retires its saved bot token. It does not uninstall the bot: the bot remains in the Discord server, and the application remains in the Developer Portal, until you remove them there.",
},
"microsoft-teams": {
reconnect:
"Reconnect verifies this same Microsoft app, tenant, and bot identity. It does not upload or reinstall the Teams app.",
remove:
"Paperclip archives the endpoint, stops new ingress, and retires its saved client secret. It does not uninstall the Teams app: the Entra app registration, Azure Bot, custom Teams app, and Teams installations remain until you remove them in Microsoft.",
},
"imessage-photon": {
reconnect: "Reconnect verifies the same Photon project and line allocation, then recovers eligible missed messages.",
remove: "Disconnect archives this channel and removes its saved secret. Your Photon project, number, subscription, and Messages history remain in Photon.",
},
telegram: {
reconnect:
"Reconnect verifies this same BotFather bot and automatically refreshes its Paperclip webhook and command menu.",
remove:
"Paperclip archives the endpoint and queues durable removal of its Telegram webhook and command menu. After Telegram confirms that cleanup, Paperclip retires the saved token. The BotFather bot and its chat memberships remain until you remove them in Telegram.",
},
};
const activityKindLabels: Record<ChatActivityItem["kind"], string> = {
delivery: "Inbound delivery",
publication: "Outbound publication",
action: "Provider action",
health: "Connection health",
repair: "Connection repair",
};
const replayableFailureStates = new Set(["failed"]);
// Provider callbacks do not necessarily emit a Board activity event. Refresh
// only mounted operational views, and stop polling when the browser is hidden.
const liveChatQueryOptions = {
staleTime: 0,
refetchInterval: 5_000,
refetchIntervalInBackground: false,
} as const;
export function isReplayEligible(item: ChatActivityItem): boolean {
if (
item.fileTransfer ||
!item.replayable ||
!replayableFailureStates.has(item.status)
) {
return false;
}
if (item.kind === "delivery") return item.status === "failed";
return item.kind === "publication";
}
export function activityResolutionActions(item: ChatActivityItem) {
const offered = item.resolutionActions ?? [];
if (!item.fileTransfer) return offered;
if (
item.kind !== "publication" ||
!Number.isSafeInteger(item.fileTransfer.version) ||
item.fileTransfer.version < 1
)
return [];
if (
![
"consent_unknown",
"upload_unknown",
"file_info_unknown",
"conflict",
].includes(item.fileTransfer.phase)
)
return [];
// Only the file-info stage can use ordinary visible-delivery resolution.
// Earlier consent/upload evidence must not be fabricated by these buttons.
return item.fileTransfer.phase === "file_info_unknown"
? offered
: offered.filter((action) => action === "cancel");
}
export function activityResolutionDescription(item: ChatActivityItem): string {
const phase = item.fileTransfer?.phase;
if (phase === "file_info_unknown")
return "The file upload was confirmed, but its Teams notification was not. Check Teams first. Retrying sends only that notification, not the file bytes, and may create a duplicate card.";
if (phase === "consent_unknown")
return "The consent card may have reached Teams. File delivery is not confirmed. Cancelling here does not remove any card already sent.";
if (phase)
return "The file may already exist in OneDrive. Cancelling stops this Paperclip transfer; it does not delete remote bytes. Uploads cannot be marked delivered or retried from this uncertain state.";
return "Paperclip lost confirmation after sending. Check the provider conversation first. Retrying can create a duplicate message.";
}
export function isResolutionEligible(item: ChatActivityItem): boolean {
return (
(item.kind === "publication" || item.kind === "action") &&
item.status === "delivery_unknown" &&
activityResolutionActions(item).length > 0
);
}
export function isIndividuallyToggleableResource(
provider: ChatProvider,
resourceType: string,
): boolean {
return !(
provider === "microsoft-teams" &&
(resourceType === "direct_message" || resourceType === "group_chat")
);
}
function activityDetailLabel(item: ChatActivityItem): string {
return replayableFailureStates.has(item.status) ? "Reason" : "Details";
}
export function connectionHealthPresentation(
endpoint: Pick<ChatEndpoint, "status" | "healthMessage" | "lastError">,
) {
// Health events outlive pause/removal. They are history, not lifecycle state.
const lifecycleMessages = {
draft: "Connection setup is incomplete.",
verifying: "Connection verification is in progress.",
paused: "Connection is paused. Resume it to receive new messages.",
attention: "Connection needs attention.",
revoked: "Connection access is revoked. Reconnect to verify access.",
archived: "Connection has been removed from Paperclip.",
};
const lifecycleMessage =
endpoint.status === "active" ? null : lifecycleMessages[endpoint.status];
return {
message: lifecycleMessage ?? endpoint.healthMessage ?? null,
previousHealth: lifecycleMessage ? (endpoint.healthMessage ?? null) : null,
error: endpoint.lastError ?? null,
errorLabel: ["active", "attention", "revoked"].includes(endpoint.status)
? "Reason"
: "Last reported error",
};
}
export function ChatEndpointDetail() {
const { endpointId = "", tab = "settings" } = useParams<{
endpointId: string;
tab?: string;
}>();
const activeTab = tabs.includes(tab as ChatTab) ? (tab as ChatTab) : null;
const navigate = useNavigate();
const { setBreadcrumbs } = useBreadcrumbs();
const endpointQuery = useQuery({
queryKey: queryKeys.chatEndpoints.detail(endpointId),
queryFn: () => chatEndpointsApi.get(endpointId),
enabled: Boolean(endpointId && activeTab),
...liveChatQueryOptions,
refetchInterval:
activeTab === "activity" || activeTab === "conversations"
? liveChatQueryOptions.refetchInterval
: false,
});
const endpoint = endpointQuery.data;
const [copyStatus, setCopyStatus] = useState<string | null>(null);
useEffect(() => {
if (!endpoint || !activeTab) return;
setBreadcrumbs([
{ label: "Connectors", href: "/apps" },
{
label: `${endpoint.assignedAgentName} · ${providerNames[endpoint.provider]}`,
href: `/apps/chat/${endpoint.id}/settings`,
},
{
label:
tabItems.find((item) => item.value === activeTab)?.label ??
"Settings",
},
]);
return () => setBreadcrumbs([]);
}, [activeTab, endpoint, setBreadcrumbs]);
if (!activeTab)
return <Navigate replace to={`/apps/chat/${endpointId}/settings`} />;
if (endpointQuery.isLoading)
return (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
Loading connection…
</div>
);
if (endpointQuery.isError || !endpoint)
return (
<div className="space-y-3">
<p className="text-sm text-destructive">
This chat connection could not be loaded.
</p>
<Button variant="outline" onClick={() => endpointQuery.refetch()}>
Try again
</Button>
</div>
);
if (endpoint.provider === "agentmail") return <EmailEndpointSettings endpointId={endpoint.id} companyId={endpoint.companyId} />;
const setupIncomplete =
endpoint.setup?.step !== "complete" &&
["draft", "verifying", "attention", "revoked"].includes(endpoint.status);
return (
<div className="max-w-5xl space-y-6 pb-12">
<header className="flex flex-wrap items-start justify-between gap-4">
<div>
<h1 className="text-xl font-bold">
{endpoint.assignedAgentName} in {providerNames[endpoint.provider]}
</h1>
<p className="mt-1 text-sm text-muted-foreground">
{endpoint.providerAccountLabel ?? "Chat connection"}
</p>
{endpoint.provider === "imessage-photon" && endpoint.botExternalId && endpoint.photonAllocation !== "shared" && (
<div className="mt-2 flex flex-wrap items-center gap-2 text-sm">
<span>{endpoint.botExternalId}</span>
<Button variant="ghost" size="sm" aria-label="Copy dedicated number" onClick={async () => {
try { await copyTextToClipboard(endpoint.botExternalId!); setCopyStatus("Number copied"); }
catch { setCopyStatus("Could not copy the number. Select and copy it manually."); }
}}><Copy className="size-4" />Copy number</Button>
<span role="status" className="text-muted-foreground">{copyStatus}</span>
</div>
)}
</div>
<div className="flex items-center gap-2">
{setupIncomplete ? (
<Button
variant="outline"
onClick={() =>
navigate(
`/apps/chat/connect?provider=${endpoint.provider}&purpose=chat&resume=${endpoint.id}`,
)
}
>
Continue setup
</Button>
) : null}
{endpoint.status !== "active" && <StatusBadge status={endpoint.status} />}
</div>
</header>
{activeTab === "settings" && (
<>
{endpoint.provider === "github" && <GitHubBotManagement endpoint={endpoint} view="settings" />}
{endpoint.provider !== "github" && <Settings endpointId={endpoint.id} endpoint={endpoint} />}
</>
)}
{activeTab === "reviews" && endpoint.provider === "github" && <GitHubReviews endpointId={endpoint.id} />}
{activeTab === "access" && endpoint.provider === "github" && <GitHubBotManagement endpoint={endpoint} view="access" />}
{activeTab === "access" && endpoint.provider !== "github" && (
<Access
endpointId={endpoint.id}
allowUnlinked={endpoint.allowUnlinkedPeople}
endpoint={endpoint}
/>
)}
{activeTab === "conversations" && (
<Conversations endpointId={endpoint.id} provider={endpoint.provider} />
)}
{activeTab === "activity" && (
<Activity endpointId={endpoint.id} endpoint={endpoint} />
)}
</div>
);
}
function Settings({
endpointId,
endpoint,
}: {
endpointId: string;
endpoint: Awaited<ReturnType<typeof chatEndpointsApi.get>>;
}) {
const queryClient = useQueryClient();
const { pushToast } = useToast();
const [messageCopied, setMessageCopied] = useState(false);
const avatarAgent = useQuery({
queryKey: queryKeys.agents.detail(endpoint.assignedAgentId),
queryFn: () => agentsApi.get(endpoint.assignedAgentId, endpoint.companyId),
enabled: endpoint.provider === "slack",
});
const mentionMessage = `@${(endpoint.botUsername ?? endpoint.botLabel ?? endpoint.assignedAgentName).replace(/^@/, "")} you there?`;
const resourcesQuery = useQuery({
queryKey: queryKeys.chatEndpoints.resources(endpointId),
queryFn: () => chatEndpointsApi.listResources(endpointId),
});
const saveResources = useMutation({
mutationFn: (resource: Pick<ChatEndpointResource, "id" | "enabled">) =>
chatEndpointsApi.updateResources(endpointId, [resource]),
onSuccess: (resources) =>
queryClient.setQueryData(
queryKeys.chatEndpoints.resources(endpointId),
resources,
),
onError: (error) =>
pushToast({
title: "Couldn't update destination",
body: error instanceof Error ? error.message : "Try again.",
tone: "error",
}),
});
const updateEndpoint = useMutation({
mutationFn: chatEndpointsApi.update.bind(null, endpointId),
onSuccess: (next) =>
queryClient.setQueryData(
queryKeys.chatEndpoints.detail(endpointId),
next,
),
onError: (error) =>
pushToast({
title: "Couldn't update settings",
body: error instanceof Error ? error.message : "Try again.",
tone: "error",
}),
});
const resources = resourcesQuery.data ?? [];
const destinationResources = resources.filter((resource) =>
isIndividuallyToggleableResource(endpoint.provider, resource.type),
);
const toggleResource = (resource: ChatEndpointResource, enabled: boolean) =>
// A cached inventory must not overwrite another operator's unrelated edits.
saveResources.mutate({ id: resource.id, enabled });
return (
<section className="max-w-3xl space-y-7">
{endpoint.provider === "imessage-photon" && <p className="text-sm text-muted-foreground">{endpoint.photonAllocation === "shared" ? "Shared Photon project · direct messages only. Enroll senders in Photon and link their Messages identities in Access. Groups cannot be enabled." : "Enable each group individually. Agent replies are visible to everyone in that group; only authorized senders can start work."}</p>}
{endpoint.provider === "slack" && (
<div className="space-y-2 text-sm">
<h2 className="text-lg font-semibold">Chat in Slack</h2>
<p>Invite the bot to a channel, then mention it to start a conversation.</p>
<div className="flex items-center justify-between gap-3 rounded-lg border border-border p-3">
<code>{mentionMessage}</code>
<Button size="icon" variant="ghost" aria-label={messageCopied ? "Message copied" : "Copy message"} onClick={() => {
void copyTextToClipboard(mentionMessage).then(() => setMessageCopied(true), () => pushToast({ title: "Couldn’t copy the message", body: "Select and copy it manually.", tone: "error" }));
}}>{messageCopied ? <Check className="size-4" /> : <Copy className="size-4" />}</Button>
</div>
</div>
)}
{endpoint.provider === "slack" && (
avatarAgent.isPending ? <p role="status" className="text-sm text-muted-foreground">Loading agent avatar…</p>
: avatarAgent.isError ? <p role="alert" className="text-sm text-destructive">Couldn’t load the agent’s avatar. <button className="underline" onClick={() => void avatarAgent.refetch()}>Try again</button></p>
: <SlackAvatarSettings
agentName={avatarAgent.data?.name ?? endpoint.assignedAgentName}
appName={endpoint.setup?.slackApp?.appName ?? defaultSlackAppName(avatarAgent.data?.name ?? endpoint.assignedAgentName)}
avatarUrl={agentAvatarUrl(resolveAgentAppearance(avatarAgent.data?.appearance, endpoint.assignedAgentId), 512, 1, "rest")}
/>
)}
{endpoint.provider === "slack" && <SlackToolsSettings companyId={endpoint.companyId} endpointId={endpointId} connectionId={endpoint.connectionId} />}
{endpoint.provider === "slack" && <ChatCommunicationInstructions
key={endpoint.id}
value={endpoint.communicationInstructions ?? ""}
onSave={async (communicationInstructions) => {
const next = await chatEndpointsApi.update(endpointId, { communicationInstructions });
queryClient.setQueryData(queryKeys.chatEndpoints.detail(endpointId), next);
}}
/>}
{endpoint.provider === "telegram" && (
<div className="space-y-2">
<h2 className="text-lg font-semibold">Telegram group command</h2>
<div className="rounded-lg border border-border p-3 text-sm">
<code>
/task@
{endpoint.botUsername?.replace(/^@/, "") ?? "bot_username"}{" "}
&lt;request&gt;
</code>
<p className="mt-2 text-muted-foreground">
Telegram&apos;s default privacy mode does not deliver ordinary
mentions to bots. Use this command to start or continue group
work, or reply directly to a message from the bot.
</p>
</div>
</div>
)}
<div>
<h2 className="text-lg font-semibold">Where this agent can work</h2>
</div>
<div className="space-y-2">
<h3 className="text-sm font-semibold">{endpoint.provider === "slack" ? "Allowed Channels" : "Destinations"}</h3>
{resourcesQuery.isLoading ? (
<p className="text-sm text-muted-foreground">Loading destinations…</p>
) : destinationResources.length === 0 ? (
<p className="rounded-lg border border-dashed border-border p-4 text-sm text-muted-foreground">
No provider destinations have been discovered yet.
</p>
) : (
<div className="divide-y divide-border border-y border-border">
{destinationResources.map((resource) => (
<div key={resource.id} className="flex items-center gap-3 py-3">
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">
{resource.label}
</p>
<p className="text-xs text-muted-foreground">
{resource.availability === "available"
? (resource.detail ?? resource.type)
: "Unavailable at the provider"}
</p>
{resource.participants?.length ? <p className="mt-1 break-words text-xs text-muted-foreground">Participants: {resource.participants.join(", ")}</p> : null}
</div>
<ToggleSwitch
aria-label={`Enable ${resource.label}`}
checked={resource.enabled}
disabled={
endpoint.photonAllocation === "shared" ||
resource.availability !== "available" ||
saveResources.isPending
}
onCheckedChange={(enabled) =>
toggleResource(resource, enabled)
}
/>
</div>
))}
</div>
)}
</div>
{endpoint.provider !== "github" && (
<div className="space-y-3">
<h3 className="text-sm font-semibold">Private conversations</h3>
<SettingToggle
label="Allow direct messages"
detail={
endpoint.provider === "discord"
? "People must also enable Direct Messages in their shared Discord server’s Privacy Settings."
: "People can start or continue a task in a direct conversation."
}
checked={endpoint.allowDirectMessages ?? false}
pending={updateEndpoint.isPending}
onChange={(allowDirectMessages) =>
updateEndpoint.mutate({ allowDirectMessages })
}
/>
{endpoint.provider === "microsoft-teams" && (
<SettingToggle
label="Allow group chats"
detail="The bot may participate in group chats where it is installed."
checked={endpoint.allowGroupChats ?? false}
pending={updateEndpoint.isPending}
onChange={(allowGroupChats) =>
updateEndpoint.mutate({ allowGroupChats })
}
/>
)}
</div>
)}
</section>
);
}
function SettingToggle({
label,
detail,
checked,
pending,
onChange,
}: {
label: string;
detail: string;
checked: boolean;
pending: boolean;
onChange: (value: boolean) => void;
}) {
return (
<div className="flex items-center gap-3 border-y border-border py-3">
<div className="min-w-0 flex-1">
<p className="text-sm font-medium">{label}</p>
<p className="text-xs text-muted-foreground">{detail}</p>
</div>
<ToggleSwitch
aria-label={label}
checked={checked}
disabled={pending}
onCheckedChange={onChange}
/>
</div>
);
}
function Access({
endpointId,
allowUnlinked,
endpoint,
}: {
endpointId: string;
allowUnlinked: boolean;
endpoint: ChatEndpoint;
}) {
const queryClient = useQueryClient();
const { pushToast } = useToast();
const [confirmationUrl, setConfirmationUrl] = useState<string | null>(null);
const [joinCommandCopied, setJoinCommandCopied] = useState(false);
const joinCommand = `${endpoint.setup?.slackApp?.command ?? endpoint.setup?.command ?? "/paperclip"} connect`;
const linksQuery = useQuery({
queryKey: queryKeys.chatEndpoints.principals(endpointId),
queryFn: () => chatEndpointsApi.listPrincipals(endpointId),
});
const updatePolicy = useMutation({
mutationFn: (value: boolean) =>
chatEndpointsApi.update(endpointId, { allowUnlinkedPeople: value }),
onSuccess: (next) =>
queryClient.setQueryData(
queryKeys.chatEndpoints.detail(endpointId),
next,
),
onError: (error) => pushToast({ title: "Couldn’t update access", body: error instanceof Error ? error.message : "Try again.", tone: "error" }),
});
const createIntent = useMutation({
mutationFn: (principalId: string) =>
chatEndpointsApi.createLinkIntent(endpointId, principalId),
onSuccess: ({ confirmationUrl }) => {
setConfirmationUrl(
new URL(confirmationUrl, window.location.origin).toString(),
);
pushToast({
title: "Private identity-link URL created",
body: "Send it only to the person whose provider identity is shown.",
tone: "success",
});
},
onError: (error) =>
pushToast({
title: "Couldn't create identity link",
body: error instanceof Error ? error.message : "Try again.",
tone: "error",
}),
});
const revoke = useMutation({
mutationFn: (principalId: string) =>
chatEndpointsApi.revokeLink(endpointId, principalId),
onSuccess: () =>
queryClient.invalidateQueries({
queryKey: queryKeys.chatEndpoints.principals(endpointId),
}),
});
const links = linksQuery.data ?? [];
return (
<section className="max-w-3xl space-y-7">
<div>
<h2 className="text-lg font-semibold">External identity access</h2>
</div>
{endpoint.provider === "slack" && <SlackSearchAccess companyId={endpoint.companyId} endpointId={endpointId} />}
{endpoint.provider === "slack" && (
<div className="space-y-3">
<h3 className="text-sm font-semibold">Invite others to connect their Slack accounts</h3>
<ol className="list-decimal space-y-3 pl-5 text-sm">
<li>
Ask them to send this command in your Slack workspace:
<div className="mt-2 flex items-center justify-between gap-3 rounded-lg border border-border p-3">
<code>{joinCommand}</code>
<Button size="sm" variant="ghost" onClick={() => {
void copyTextToClipboard(joinCommand).then(() => setJoinCommandCopied(true), () => pushToast({ title: "Couldn't copy the command", body: "Select and copy it manually.", tone: "error" }));
}}><Copy className="size-4" />{joinCommandCopied ? "Copied" : "Copy command"}</Button>
</div>
</li>
<li>Open the private link from the bot, sign into Paperclip, and confirm their Slack account. The link expires in 15 minutes and works once.</li>
<li>If they aren’t a member of this organization, choose <strong>Request access</strong>. An admin must approve their request before they can link their account.</li>
</ol>
<p className="text-sm text-muted-foreground">Each person links their own account and uses their own Paperclip permissions. They don’t need to create another Slack app or share credentials.</p>
</div>
)}
<SettingToggle
label="Allow unlinked people"
detail="They are restricted guests. Their tasks run only with an isolated workspace and sandbox environment; otherwise Paperclip safely refuses the request. They cannot approve, hire, spend, manage access, or reassign agents."
checked={allowUnlinked}
pending={updatePolicy.isPending}
onChange={(value) => updatePolicy.mutate(value)}
/>
{confirmationUrl && (
<div className="space-y-2 border-y border-border py-3">
<p className="text-sm font-medium">Private confirmation link</p>
<p className="break-all text-xs text-muted-foreground">
{confirmationUrl}
</p>
<Button
size="sm"
variant="outline"
onClick={() => {
void copyTextToClipboard(confirmationUrl).then(
() =>
pushToast({
title: "Confirmation link copied",
tone: "success",
}),
() =>
pushToast({
title: "Couldn't copy the link",
body: "Select and copy it manually.",
tone: "error",
}),
);
}}
>
<Copy />
Copy link
</Button>
</div>
)}
<div className="space-y-2">
<h3 className="text-sm font-semibold">Identity links</h3>
{links.length === 0 ? (
<p className="rounded-lg border border-dashed border-border p-4 text-sm text-muted-foreground">
External people appear here after they message the agent.
</p>
) : (
<div className="divide-y divide-border border-y border-border">
{links.map((link) => (
<div
key={link.id}
className="flex flex-wrap items-center gap-3 py-3"
>
<div className="min-w-0 flex-1">
<p className="text-sm font-medium">{link.externalLabel}</p>
<p className="text-xs text-muted-foreground">
{link.paperclipUserLabel
? `Linked to ${link.paperclipUserLabel}`
: (link.externalDetail ?? "Not linked")}
</p>
</div>
{link.status === "linked" ? (
<Button
size="sm"
variant="ghost"
disabled={revoke.isPending}
onClick={() => revoke.mutate(link.principalId)}
>
<Unlink />
Revoke
</Button>
) : (
<Button
size="sm"
variant="outline"
disabled={createIntent.isPending}
onClick={() => createIntent.mutate(link.principalId)}
>
Create private link
</Button>
)}
</div>
))}
</div>
)}
</div>
</section>
);
}
function Conversations({
endpointId,
provider,
}: {
endpointId: string;
provider: ChatProvider;
}) {
const query = useQuery({
queryKey: queryKeys.chatEndpoints.conversations(endpointId),
queryFn: () => chatEndpointsApi.listConversations(endpointId),
...liveChatQueryOptions,
});
const rows = query.data ?? [];
return (
<section className="space-y-4">
<div>
<h2 className="text-lg font-semibold">Conversations</h2>
</div>
{rows.length === 0 ? (
<p className="rounded-lg border border-dashed border-border p-4 text-sm text-muted-foreground">
No conversations yet. Address the agent in an enabled destination to
start one.
</p>
) : (
<ul aria-label="Conversations" className="divide-y divide-border overflow-x-auto border-y border-border">
{rows.map((row) => (
<li key={row.id} className="flex min-w-xl items-center gap-3 px-2 py-3 text-sm transition-colors hover:bg-accent/50">
<AppLogo name={providerNames[provider]} brandKey={provider} compact className="size-5! rounded-sm bg-transparent" />
<div className="flex min-w-0 max-w-56 items-center gap-2">
<span className="truncate font-medium" title={row.externalLabel}>{row.externalLabel}</span>
{row.externalUrl && <a href={row.externalUrl} target="_blank" rel="noreferrer" className="inline-flex shrink-0 items-center gap-1 text-xs text-muted-foreground hover:text-foreground hover:underline">Open {providerNames[provider]}<ExternalLink className="size-3" /></a>}
</div>
<span aria-hidden="true" className="text-muted-foreground">·</span>
<div className="flex min-w-0 flex-1 items-center gap-2">
<span className="truncate" title={row.issueTitle ?? undefined}>{row.issueTitle ?? "Waiting for task"}</span>
{row.issueId && <Link to={`/issues/${row.issueId}`} className="inline-flex shrink-0 items-center gap-1 text-xs text-muted-foreground hover:text-foreground hover:underline">Open task<ExternalLink className="size-3" /></Link>}
</div>
<span className="hidden shrink-0 text-xs text-muted-foreground xl:inline">{row.issueIdentifier}</span>
{row.state !== "active" && <StatusBadge status={row.state} />}
</li>
))}
</ul>
)}
</section>
);
}
function Activity({
endpointId,
endpoint,
}: {
endpointId: string;
endpoint: Awaited<ReturnType<typeof chatEndpointsApi.get>>;
}) {
const queryClient = useQueryClient();
const navigate = useNavigate();
const { pushToast } = useToast();
const [removeOpen, setRemoveOpen] = useState(false);
const [resolutionItem, setResolutionItem] = useState<ChatActivityItem | null>(
null,
);
const [cursors, setCursors] = useState<Array<string | undefined>>([undefined]);
const cursor = cursors[cursors.length - 1];
useEffect(() => setCursors([undefined]), [endpointId]);
const query = useQuery({
queryKey: [...queryKeys.chatEndpoints.activity(endpointId), cursor ?? null],
queryFn: () => chatEndpointsApi.listActivityPage(endpointId, cursor),
...liveChatQueryOptions,
refetchInterval: cursor ? false : liveChatQueryOptions.refetchInterval,
});
const replay = useMutation({
mutationFn: (item: ChatActivityItem) =>
item.kind === "publication"
? chatEndpointsApi.replayPublication(endpointId, item.id)
: chatEndpointsApi.replayDelivery(endpointId, item.id),
onSuccess: async (_result, item) => {
await queryClient.invalidateQueries({
queryKey: queryKeys.chatEndpoints.activity(endpointId),
});
pushToast({
title: `${item.kind === "publication" ? "Publication" : "Delivery"} queued for replay`,
tone: "success",
});
},
onError: (error) =>
pushToast({
title: "Couldn't replay activity",
body: error instanceof Error ? error.message : "Try again.",
tone: "error",
}),
});
const resolveActivity = useMutation({
mutationFn: (input: {
item: ChatActivityItem;
action: "mark_delivered" | "retry_anyway" | "cancel";
}) => {
if (input.item.kind === "publication") {
return chatEndpointsApi.resolvePublication(
endpointId,
input.item.id,
input.action,
input.item.fileTransfer
? {
phase: input.item.fileTransfer.phase,
version: input.item.fileTransfer.version,
}
: undefined,
);
}
return chatEndpointsApi.resolveAction(
endpointId,
input.item.id,
input.action,
);
},
onSuccess: async (_result, input) => {
setResolutionItem(null);
await queryClient.invalidateQueries({
queryKey: queryKeys.chatEndpoints.activity(endpointId),
});
pushToast({
title:
input.item.actionType === "slash_task_start" &&
input.action === "retry_anyway"
? "Task start retried"
: input.item.actionType === "slash_task_start"
? "Task start cancelled"
: input.item.actionType === "provider_effect" &&
input.action === "mark_delivered"
? "Provider reply marked delivered"
: input.item.actionType === "provider_effect" &&
input.action === "retry_anyway"
? "Provider reply retried"
: input.item.actionType === "provider_effect"
? "Provider reply cancelled"
: input.action === "mark_delivered"
? "Publication marked delivered"
: input.action === "retry_anyway"
? "Publication queued for retry"
: "Publication cancelled",
tone: "success",
});
},
onError: (error) =>
pushToast({
title: "Couldn't resolve activity",
body: error instanceof Error ? error.message : "Try again.",
tone: "error",
}),
});
const lifecycle = useMutation({
mutationFn: (action: "pause" | "resume" | "remove") =>
chatEndpointsApi.setup(endpointId, { action }),
onSuccess: async (next, action) => {
await queryClient.invalidateQueries({
queryKey: queryKeys.chatEndpoints.list(next.companyId),
});
if (action === "remove") {
navigate("/apps");
return;
}
queryClient.setQueryData(
queryKeys.chatEndpoints.detail(endpointId),
next,
);
pushToast({
title: action === "pause" ? "Connection paused" : "Connection resumed",
tone: "success",
});
},
onError: (error) =>
pushToast({
title: "Couldn't update connection",
body: error instanceof Error ? error.message : "Try again.",
tone: "error",
}),
});
const rows = query.data?.items ?? [];
const { status } = endpoint;
const health = connectionHealthPresentation(endpoint);
const lifecycleAction = lifecycle.variables;
const callbackSurfaceRows = endpoint.setup?.callbackSurfaces
? ([
["Events API", endpoint.setup.callbackSurfaces.events],
["Interactivity", endpoint.setup.callbackSurfaces.interactivity],
["Slash command", endpoint.setup.callbackSurfaces.slashCommands],
] as const)
: [];
return (
<section className="space-y-5">
<h2 className="text-lg font-semibold">Connection activity</h2>
{((status !== "active" && health.message) || health.error) && (
<div
className={`flex items-start gap-2 rounded-lg border p-3 text-sm ${status === "attention" || status === "revoked" ? "border-destructive/40 bg-destructive/5 text-destructive" : "border-border bg-muted/30 text-foreground"}`}
>
{(status === "attention" || status === "revoked") && (
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
)}
<div>
{health.message && <p>{health.message}</p>}
{health.previousHealth && (
<p className="mt-1 text-xs opacity-80">
<span className="font-medium">Last reported health:</span>{" "}
{health.previousHealth}
</p>
)}
{health.error && (
<p className="mt-1 text-xs opacity-80">
<span className="font-medium">{health.errorLabel}:</span>{" "}
{health.error}
</p>
)}
</div>
</div>
)}
<details className="group rounded-lg border border-border">
<summary className="flex cursor-pointer list-none items-center justify-between gap-3 p-4 text-sm font-medium chat-connection-health-summary">
<span>Connection health and controls</span>
<span className="flex items-center gap-2">
{endpoint.setup?.callbacksNeedUpdate && <span className="text-xs text-(--status-task-blocked)">Callback URLs need attention</span>}
<ChevronDown className="size-4 text-muted-foreground transition-transform group-open:rotate-180" />
</span>
</summary>
<div className="space-y-5 border-t border-border p-4">
{endpoint.provider === "slack" && callbackSurfaceRows.length > 0 && (
<div
className="space-y-3 text-sm"
>
<p className="font-medium">Slack callback health</p>
<p className="text-xs text-muted-foreground">
{endpoint.setup?.callbacksNeedUpdate
? "Slack callback URLs need an update. Save the current App Manifest, then exercise Events, Interactivity, and the registered command again."
: "Paperclip records each callback surface independently after Slack successfully calls it."}
</p>
<div className="divide-y divide-border border-y border-border">
{callbackSurfaceRows.map(([label, surface]) => (
<div key={label} className="flex flex-wrap items-center justify-between gap-3 py-2">
<p className="text-xs font-medium">{label}</p>
<p className="text-xs text-muted-foreground">
{surface.status === "current"
? "Current"
: surface.status === "stale"
? "Stale URL"
: "Not observed"}
</p>
{surface.observedAt && (
<p className="text-xs text-muted-foreground">
Last observed{" "}
<time
dateTime={surface.observedAt}
title={surface.observedAt}
className="font-mono"
>
{formatDateTime(surface.observedAt, {
includeSeconds: true,
})}
</time>
</p>
)}
</div>
))}
</div>
</div>
)}
{status !== "archived" && (
<div className="space-y-3 pt-2">
<div className="flex flex-wrap items-center gap-2">
{status === "active" && (
<Button
variant="outline"
disabled={lifecycle.isPending}
onClick={() => lifecycle.mutate("pause")}
>
{lifecycle.isPending && lifecycleAction === "pause" ? (
<Loader2 className="animate-spin" />
) : (
<Pause />
)}
Pause
</Button>
)}
{status === "paused" && (
<Button
variant="outline"
disabled={lifecycle.isPending}
onClick={() => lifecycle.mutate("resume")}
>
{lifecycle.isPending && lifecycleAction === "resume" ? (
<Loader2 className="animate-spin" />
) : (
<Play />
)}
Resume
</Button>
)}
{[
"active",
"paused",
"attention",
"revoked",
"draft",
"verifying",
].includes(status) && (
<Button
variant="outline"
disabled={lifecycle.isPending}
onClick={() =>
navigate(
`/apps/chat/connect?provider=${endpoint.provider}&purpose=chat&resume=${endpoint.id}${status === "draft" || status === "verifying" ? "" : "&reconnect=1"}`,
)
}
>
<RefreshCw />
{status === "draft" || status === "verifying"
? "Finish setup"
: "Reconnect"}
</Button>
)}
<Button
variant="ghost"
className="text-destructive hover:text-destructive"
disabled={lifecycle.isPending}
onClick={() => setRemoveOpen(true)}
>
<Trash2 />
Remove connection
</Button>
</div>
{status !== "draft" && status !== "verifying" && (
<p className="text-xs text-muted-foreground">
{providerLifecycleGuidance[endpoint.provider].reconnect}
</p>
)}
</div>
)}
</div>
</details>
<div className="space-y-2">
<h3 className="text-sm font-semibold">
Recent activity
</h3>
<div className="divide-y divide-border border-y border-border">
{query.isLoading && (
<div className="flex items-center gap-2 py-5 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
Loading activity…
</div>
)}
{query.isError && (
<div className="flex flex-wrap items-center justify-between gap-3 py-4">
<p className="text-sm text-destructive" role="alert">
Connection activity could not be loaded.
</p>
<Button
size="sm"
variant="outline"
onClick={() => query.refetch()}
>
Try again
</Button>
</div>
)}
{!query.isLoading &&
!query.isError &&
rows.map((item) => (
<div
key={item.id}
className="flex items-start gap-3 px-2 py-3 transition-colors hover:bg-accent/50"
>
<span className="mt-0.5 text-muted-foreground" aria-hidden="true">
{item.kind === "delivery" ? <ArrowDownLeft className="size-4" /> : item.kind === "publication" ? <ArrowUpRight className="size-4" /> : <ActivityIcon className="size-4" />}
</span>
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
<p className="min-w-0 flex-1 text-sm font-medium">{item.summary}</p>
<StatusBadge status={item.status} />
<time dateTime={item.createdAt} title={item.createdAt} className="shrink-0 text-xs tabular-nums text-muted-foreground">
{formatDateTime(item.createdAt, { includeSeconds: true })}
</time>
</div>
<p className="mt-1 text-xs text-muted-foreground">{activityKindLabels[item.kind]}</p>
{item.fileTransfer && (
<p className="mt-1 text-xs text-muted-foreground">
{item.fileTransfer.filename} —{" "}
{item.fileTransfer.phase.replaceAll("_", " ")}
</p>
)}
{item.detail && (
<p className="mt-1 text-xs text-muted-foreground">
<span className="font-medium text-foreground">
{activityDetailLabel(item)}:
</span>{" "}
{item.detail}
</p>
)}
</div>
{isReplayEligible(item) && (
<Button
size="sm"
variant="outline"
aria-label={`Replay failed ${item.kind}`}
disabled={replay.isPending}
onClick={() => replay.mutate(item)}
>
{replay.isPending && replay.variables?.id === item.id ? (
<Loader2 className="animate-spin" />
) : (
<RefreshCw />
)}
Replay
</Button>
)}
{isResolutionEligible(item) && (
<Button
size="sm"
variant="outline"
onClick={() => setResolutionItem(item)}
>
Resolve
</Button>
)}
</div>
))}
{!query.isLoading && !query.isError && rows.length === 0 && (
<p className="py-5 text-sm text-muted-foreground">
No connection activity yet.
</p>
)}
</div>
</div>
<nav aria-label="Activity pagination" className="flex items-center justify-between gap-3">
<span className="text-xs text-muted-foreground">Page {cursors.length}</span>
<div className="flex items-center gap-2">
<Button size="sm" variant="outline" disabled={cursors.length === 1 || query.isFetching} onClick={() => setCursors((pages) => pages.slice(0, -1))}>Previous</Button>
<Button size="sm" variant="outline" disabled={!query.data?.nextCursor || query.isFetching || query.isError} onClick={() => { if (query.data?.nextCursor) setCursors((pages) => [...pages, query.data.nextCursor!]); }}>Next</Button>
</div>
</nav>
<AlertDialog
open={resolutionItem !== null}
onOpenChange={(open) => !open && setResolutionItem(null)}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{resolutionItem?.actionType === "slash_task_start"
? "Resolve unconfirmed task start"
: resolutionItem?.actionType === "provider_effect"
? "Resolve unconfirmed provider reply"
: "Resolve unconfirmed delivery"}
</AlertDialogTitle>
<AlertDialogDescription>
{resolutionItem?.actionType === "slash_task_start"
? "Paperclip lost confirmation after asking Slack to start the task. Check Slack first. Retrying can create a duplicate starter message and task."
: resolutionItem?.actionType === "provider_effect"
? "Paperclip lost confirmation after sending this provider reply. Check the provider first. Marking it delivered applies any pending Paperclip state change; retrying can create a duplicate message."
: resolutionItem
? activityResolutionDescription(resolutionItem)
: ""}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter className="sm:flex-wrap">
<AlertDialogCancel disabled={resolveActivity.isPending}>
Keep unresolved
</AlertDialogCancel>
{resolutionItem &&
activityResolutionActions(resolutionItem).includes("cancel") && (
<Button
variant="outline"
disabled={resolveActivity.isPending}
onClick={() =>
resolutionItem &&
resolveActivity.mutate({
item: resolutionItem,
action: "cancel",
})
}
>
{resolutionItem.actionType === "slash_task_start"
? "Cancel task start"
: resolutionItem.actionType === "provider_effect"
? "Cancel provider reply"
: resolutionItem.fileTransfer
? "Cancel file transfer"
: "Cancel publication"}
</Button>
)}
{resolutionItem &&
activityResolutionActions(resolutionItem).includes(
"retry_anyway",
) && (
<Button
variant="outline"
disabled={resolveActivity.isPending}
onClick={() =>
resolutionItem &&
resolveActivity.mutate({
item: resolutionItem,
action: "retry_anyway",
})
}
>
{resolutionItem.fileTransfer
? "Retry file notification"
: "Retry anyway"}
</Button>
)}
{resolutionItem &&
activityResolutionActions(resolutionItem).includes(
"mark_delivered",
) && (
<AlertDialogAction
disabled={resolveActivity.isPending}
onClick={(event) => {
event.preventDefault();
if (resolutionItem) {
resolveActivity.mutate({
item: resolutionItem,
action: "mark_delivered",
});
}
}}
>
Mark delivered
</AlertDialogAction>
)}
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<AlertDialog open={removeOpen} onOpenChange={setRemoveOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Remove this connection?</AlertDialogTitle>
<AlertDialogDescription>
{endpoint.assignedAgentName} will stop receiving new work from
{` ${providerNames[endpoint.provider]}`}. Existing Paperclip tasks
remain available.{" "}
{providerLifecycleGuidance[endpoint.provider].remove}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
disabled={lifecycle.isPending}
onClick={() => lifecycle.mutate("remove")}
>
{lifecycle.isPending && (
<Loader2 className="h-4 w-4 animate-spin" />
)}
Remove connection
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</section>
);
}