mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 15:52:36 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Hosted Paperclip Cloud records browser sessions with PostHog session replay > - Replay masked all text and showed only an allowlist of chrome, so most replays showed only stars > - The team cannot see how people use the board, and the allowlist needed a review for each new label > - The owner decided to show text by default and mask only marked customer content, the way PostHog normally works > - This pull request flips the default, removes the allowlist, and marks every surface that can show connected-account content > - The benefit is readable replays, while Google user data and Slack data stay masked ## Linked Issues or Issue Description **Subsystem affected** Hosted Cloud browser analytics: PostHog session replay in the board UI (`ui/src/lib/analytics/`). **Problem or motivation** Replay masked every text node. Only sidebar items and opt-in components showed text. Replays were almost unreadable. Each new label needed an `analyticsChrome` opt-in and an allowlist review. **Proposed solution** Record text as it is. Mask text only inside `ph-mask` (customer content), `ph-no-capture` (secrets, blocked) and editable content. Add `ANALYTICS_MASK_CLASS` to every surface that can show connected-account content (Gmail, Calendar, Drive and Docs, Slack) or other free-form text from agents or customers. **Alternatives considered** Keep "mask all" and grow the allowlist. This needs a review for each label and still hides most of the board. ## What Changed - `privacy.ts`: `ANALYTICS_MASK_TEXT_SELECTOR` is now `.ph-mask, .ph-no-capture, [contenteditable]:not([contenteditable="false"])`. rrweb masks a text node only when its parent or an ancestor matches the selector. Removed `maskReplayText`, `isReplayTextRevealed`, `ANALYTICS_UNMASK_ATTRIBUTE` and `ANALYTICS_UNMASK_PROPS`. - `product-analytics.ts`: removed `maskTextFn`, so rrweb uses its default star masking. `maskAllInputs`, `blockClass`, `maskAttributeFn`, `mask_all_text` and `mask_all_element_attributes` do not change. - Removed the `analyticsChrome` prop from `Button`, `Label`, `TabsTrigger`, `EmptyState` and `SidebarNavItem`, and from all sidebar call sites. - Added `ANALYTICS_MASK_CLASS` to the content element (not the chrome) of these surfaces: - Link preview cards, task quicklook description, external object pills and rows, related-work titles. - Email message cards and email send intents. - Connected account names and email addresses (Browse, Connections, app detail headers, app sidebar, connection choice list, connection access and repair cards), GitHub login and repositories, Slack workspace names, chat channel and linked user labels. - Inbox and decision rows (subject and detail), obligation evidence, Needs You notes and receipts, decision options and result summaries, and the interaction card roots (questions, options, answers, tool action requests, suggested tasks). - Approval payloads, action card input and reason, recovery card headline, evidence and options, run ledger retry detail, interrupt handoff previews. - Run transcripts, run failure details and run events on the agent page. - Search result snippets, toast bodies, voice and call transcripts, case summary, files and fields, attachment previews, artifact previews (text, tables, patches and documents). - Replaced `unmask-allowlist.test.ts` with `replay-masking.test.tsx`. It checks that unmarked chrome records as it is, that each marker masks, that a rendered voice transcript and run transcript mask, that each surface above has the class, and that autocapture records no element text. Updated `privacy.test.ts`, `shared-chrome.test.tsx` and `product-analytics.test.ts`. - Updated `doc/cloud-browser-analytics.md`: new default, marker classes, masked surfaces, and residual risk. ## Verification - `pnpm exec vitest run src/lib/analytics` in `ui/`: 83 tests pass. - Vitest for the 48 test files next to the changed components: 994 tests pass. - `tsc --noEmit -p ui/tsconfig.json`: no new errors (only the existing generated Storybook catalog errors). - `pnpm verify` exits 2 because a doc is a global CI input. Required CI supplies the broad coverage. - Manual: I ran an isolated local instance with a Cloud-like browser analytics config. `PAPERCLIP_POSTHOG_HOST` pointed to a local capture server, not PostHog. I opened a task page in headless Chromium, hovered a GitHub pull request link, and decoded the captured `/s/` replay payloads: - Clear text: sidebar (`New task`, `Chat`, `Tasks`, `Inbox`, `More`), breadcrumb, task title `Quarterly launch checklist`, `REP-1`, the Connectors promo heading and button. - Masked (stars only): the markdown task body, the chat comment, the link preview card (pull request title, author, URL, status), and the company menu. - Marker strings in the body, comment and preview never appeared in clear text in any payload. - The page `<title>` (task title and company name) is in the replay head. This is accepted residual risk. ## Risks - Text that is not marked is now recorded. Task titles, agent names, project names, company names, routine names, artifact and document titles, and activity rows are visible in replays. The owner accepted this. An agent can copy email or Slack text into a task title. - A new surface that shows connected-account content without `ANALYTICS_MASK_CLASS` is recorded until somebody marks it. `replay-masking.test.tsx` and the doc list the marked surfaces. - The masking options in `posthog.init` take precedence over the PostHog project masking settings (posthog-js 1.450), so a dashboard change cannot unmask content. Keep the project settings empty to avoid a console warning. - Some masked areas also mask nearby fixed labels (for example the interaction card buttons). This is safe. - Analytics is off on self-hosted and local installs, so they see no change. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (claude-opus-5-5), Anthropic, with tool use and code execution in Claude Code. ## 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 - [x] 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>
1442 lines
67 KiB
TypeScript
1442 lines
67 KiB
TypeScript
import { SpekoPhoneLine } from "@/components/voice/SpekoPhoneLine";
|
||
import { SpekoIncomingCalls } from "@/components/voice/SpekoIncomingCalls";
|
||
import { SpekoCallActivityItem, SpekoUnapprovedCallActivityItem, useSpekoCallHistory } from "@/components/voice/SpekoCallHistory";
|
||
import { SpekoPhoneCallback } from "@/components/voice/SpekoPhoneCallback";
|
||
import { deriveInitials } from "@/components/Identity";
|
||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||
import { agentAvatarUrl } from "@/lib/agent-avatar-url";
|
||
import { resolveAgentAppearance } from "@paperclipai/shared";
|
||
import { SlackTestMessageButton } from "./SlackTestMessageButton";
|
||
import { slackConversationUrl } from "./slack/conversation-url";
|
||
import { useAccountIdentity } from "@/api/companies-query";
|
||
import { AgentAvatar } from "@/components/AgentAvatar";
|
||
import { SlackSetupAdvanced } from "./SlackAppDetails";
|
||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
|
||
import { SlackToolsSettings, SlackSearchAccess } from "./SlackToolSettings";
|
||
import { ChatCommunicationInstructions } from "./ChatCommunicationInstructions";
|
||
import { ChatExecutionDefaults } from "./ChatExecutionDefaults";
|
||
import { agentsApi } from "@/api/agents";
|
||
import { ChatConversationList } from "./ChatConversationList";
|
||
import { GitHubConnectionRecoveryNotice } from "./GitHubConnectionRecovery";
|
||
import { GitHubBotManagement, GitHubReviews } from "./GitHubBotManagement";
|
||
import { GitHubBotMention, GitHubAppIdentityActions } from "./GitHubAppIdentity";
|
||
import { GitHubConnectionComplete, type GitHubConnectionCompleteLocationState } from "./GitHubConnectionComplete";
|
||
import { EmailEndpointSettings } from "./EmailEndpointSetup";
|
||
import { EmailConnectionAccess } from "@/components/EmailConnectionAccess";
|
||
import { emailApi } from "@/api/email";
|
||
import { toolsApi } from "@/api/tools";
|
||
import { useEffect, useMemo, useRef, 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 { QueryErrorState, useQueryView } from "@/components/QueryView";
|
||
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, useLocation, useNavigate, useParams } from "@/lib/router";
|
||
import { describeError } from "@/api/errors";
|
||
import { ANALYTICS_MASK_CLASS, ANALYTICS_NO_CAPTURE_CLASS } from "@/lib/analytics/privacy";
|
||
import { cn } from "@/lib/utils";
|
||
|
||
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> = {
|
||
speko: "Speko",
|
||
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 }
|
||
> = {
|
||
speko: {
|
||
reconnect: "Reverify this voice persona and update its signed session tools. Existing task assignments stay attached to their history.",
|
||
remove: "Stop this connection from accepting voice requests. Accepted work and task history remain in Paperclip.",
|
||
},
|
||
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 { userId, settled: identitySettled } = useAccountIdentity();
|
||
const { endpointId = "", tab: routeTab, reviewId } = useParams<{
|
||
endpointId: string;
|
||
tab?: string;
|
||
reviewId?: string;
|
||
}>();
|
||
const tab = reviewId ? "reviews" : (routeTab ?? "settings");
|
||
const activeTab = tabs.includes(tab as ChatTab) ? (tab as ChatTab) : null;
|
||
const navigate = useNavigate();
|
||
const location = useLocation();
|
||
const heading = useRef<HTMLHeadingElement>(null);
|
||
const completion = (location.state as GitHubConnectionCompleteLocationState | null)?.githubConnectionComplete;
|
||
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 endpointView = useQueryView(endpointQuery);
|
||
const avatarAgent = useQuery({
|
||
queryKey: queryKeys.agents.detail(endpoint?.assignedAgentId ?? ""),
|
||
queryFn: () => agentsApi.get(endpoint!.assignedAgentId),
|
||
enabled: endpoint?.provider === "github",
|
||
});
|
||
const [copyStatus, setCopyStatus] = useState<string | null>(null);
|
||
const agentQuery = useQuery({
|
||
queryKey: queryKeys.agents.detail(endpoint?.assignedAgentId ?? ""),
|
||
queryFn: () => agentsApi.get(endpoint!.assignedAgentId, endpoint!.companyId),
|
||
enabled: Boolean(endpoint?.assignedAgentId),
|
||
});
|
||
|
||
useEffect(() => {
|
||
if (!endpoint || !activeTab) return;
|
||
setBreadcrumbs([
|
||
{ label: "Connectors", href: "/apps" },
|
||
{
|
||
label: `${endpoint.assignedAgentName} · ${providerNames[endpoint.provider]}`,
|
||
href: `/apps/chat/${endpoint.id}/settings`,
|
||
},
|
||
...(reviewId ? [{ label: "Reviews", href: `/apps/chat/${endpoint.id}/reviews` }, { label: "Review" }] : [{
|
||
label:
|
||
tabItems.find((item) => item.value === activeTab)?.label ??
|
||
"Settings",
|
||
}]),
|
||
]);
|
||
return () => setBreadcrumbs([]);
|
||
}, [activeTab, endpoint, reviewId, setBreadcrumbs]);
|
||
|
||
if (!activeTab)
|
||
return <Navigate replace to={`/apps/chat/${endpointId}/settings`} />;
|
||
if (endpointQuery.isLoading || endpointView.kind === "reconnecting")
|
||
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 (endpointView.kind === "error" || !endpoint)
|
||
return (
|
||
<QueryErrorState
|
||
size="page"
|
||
error={endpointQuery.error}
|
||
action="load the connection"
|
||
onRetry={endpointView.retry}
|
||
retrying={endpointView.isFetching}
|
||
/>
|
||
);
|
||
if (endpoint.provider === "agentmail" && activeTab === "settings")
|
||
return <div className="space-y-7"><EmailEndpointSettings key={endpoint.id} endpointId={endpoint.id} companyId={endpoint.companyId} assignedAgentName={endpoint.assignedAgentName} /><EndpointExecutionDefaults endpoint={endpoint} /></div>;
|
||
const setupIncomplete =
|
||
endpoint.setup?.step !== "complete" &&
|
||
!(endpoint.provider === "slack" && endpoint.setup?.step === "test") &&
|
||
["draft", "verifying", "attention", "revoked"].includes(endpoint.status);
|
||
const slackAppId = endpoint.setup?.slackRegistration?.appId;
|
||
const slackUrl = endpoint.provider === "slack"
|
||
? slackAppId ? `https://api.slack.com/apps/${encodeURIComponent(slackAppId)}/oauth` : "https://api.slack.com/apps"
|
||
: null;
|
||
|
||
return (
|
||
<div className="max-w-5xl space-y-6 pb-12">
|
||
<header className="flex flex-wrap items-start justify-between gap-4">
|
||
<div className="flex min-w-0 items-center gap-3">
|
||
<AgentAvatar agent={agentQuery.data ?? { id: endpoint.assignedAgentId, name: endpoint.assignedAgentName }} size={endpoint.provider === "github" ? 64 : 48} />
|
||
<div className="min-w-0">
|
||
<h1 ref={heading} tabIndex={-1} className={endpoint.provider === "speko" ? "flex items-center gap-3 text-xl font-bold" : "text-xl font-bold"}>
|
||
{endpoint.provider === "speko" && <AppLogo name="Speko" brandKey="speko" size={36} />}
|
||
{endpoint.provider === "github" ? (endpoint.botLabel ?? endpoint.assignedAgentName) : endpoint.assignedAgentName}{endpoint.provider === "speko" ? " in Speko" : ""}
|
||
</h1>
|
||
<p className={cn("mt-1 flex flex-wrap items-center gap-2 text-sm text-muted-foreground", ANALYTICS_MASK_CLASS)}>
|
||
{endpoint.provider === "github" ? <><AppLogo name="GitHub" brandKey="github" compact className="size-4! rounded-sm bg-transparent" /><Link to={`/agents/${endpoint.assignedAgentId}`} className="hover:underline">{endpoint.assignedAgentName}</Link>{endpoint.providerAccountLabel && <span>· {endpoint.providerAccountLabel}</span>}</> : endpoint.providerAccountLabel ?? (endpoint.provider === "agentmail" ? endpoint.botExternalId ?? "Email connection" : "Chat connection")}
|
||
</p>
|
||
{endpoint.provider === "github" && <div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1">
|
||
<GitHubBotMention endpoint={endpoint} />
|
||
<GitHubAppIdentityActions endpoint={endpoint} avatarUrl={avatarAgent.data ? agentAvatarUrl(resolveAgentAppearance(avatarAgent.data.appearance, endpoint.assignedAgentId), 512, 1, "rest") : undefined} />
|
||
</div>}
|
||
{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>
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
{endpoint.provider === "speko" && <a href="https://platform.speko.ai/agents" target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-sm text-primary underline">Open Speko<ExternalLink className="size-3.5" aria-hidden="true" /></a>}
|
||
{endpoint.provider === "slack" && !setupIncomplete && <Button asChild variant="outline"><a href={slackConversationUrl(endpoint, identitySettled ? userId : null)} target="_blank" rel="noopener noreferrer">Open Slack <ExternalLink className="size-4" /></a></Button>}
|
||
{slackUrl && <Button asChild variant="outline"><a href={slackUrl} target="_blank" rel="noopener noreferrer">Open Slack configuration <ExternalLink className="size-4" /></a></Button>}
|
||
{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} className={endpoint.provider === "speko" ? "text-foreground" : undefined} />}
|
||
</div>
|
||
</header>
|
||
<div className={cn("space-y-6", ANALYTICS_MASK_CLASS)}>
|
||
{endpoint.provider === "github" && <GitHubConnectionRecoveryNotice endpoint={endpoint} />}
|
||
{activeTab === "settings" && endpoint.provider === "speko" && endpoint.status === "active" && <div className="space-y-6"><SpekoPhoneCallback companyId={endpoint.companyId} endpointId={endpoint.id} /><SpekoPhoneLine companyId={endpoint.companyId} endpointId={endpoint.id} /><SpekoIncomingCalls companyId={endpoint.companyId} endpointId={endpoint.id} agentId={endpoint.assignedAgentId} /></div>}
|
||
{endpoint.provider === "slack" && <SlackTestMessageButton key={endpoint.id} endpointId={endpoint.id} />}
|
||
{endpoint.provider === "github" && <div hidden={activeTab !== "settings" && activeTab !== "access"}>
|
||
<GitHubBotManagement key={endpoint.id} endpoint={endpoint} view={activeTab === "access" ? "access" : "settings"} />
|
||
</div>}
|
||
{activeTab === "settings" && endpoint.provider !== "github" && <Settings endpointId={endpoint.id} endpoint={endpoint} />}
|
||
{activeTab === "settings" && <EndpointExecutionDefaults endpoint={endpoint} />}
|
||
{activeTab === "reviews" && endpoint.provider === "github" && <GitHubReviews endpointId={endpoint.id} reviewId={reviewId} />}
|
||
{activeTab === "access" && endpoint.provider === "speko" && (
|
||
<section className="max-w-3xl space-y-3">
|
||
<h2 className="text-lg font-semibold">Private voice access</h2>
|
||
<p className="text-sm text-muted-foreground">Browser calls use the signed-in Paperclip user’s current company access. Each call stays bound to its selected agent and task.</p>
|
||
<p className="text-sm text-muted-foreground">Outgoing calls use your saved callback number and opt-in. For a private incoming call, enter the code spoken on the phone in signed-in Paperclip and select a task to approve that live call. Incoming calls can start a new conversation task without sign-in, under a task-scoped low-trust policy. Private mode is optional and requires approval before accessing existing tasks.</p>
|
||
</section>
|
||
)}
|
||
{activeTab === "access" && endpoint.provider === "agentmail" && <EmailAccess endpoint={endpoint} />}
|
||
{activeTab === "access" && endpoint.provider !== "speko" && endpoint.provider !== "github" && endpoint.provider !== "agentmail" && (
|
||
<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} />
|
||
)}
|
||
{endpoint.provider === "github" && activeTab === "settings" && endpoint.status === "active" &&
|
||
endpoint.setup?.step === "complete" && completion?.endpointId === endpoint.id && (
|
||
<GitHubConnectionComplete
|
||
endpoint={endpoint}
|
||
agent={avatarAgent.data}
|
||
runtimeChecks={completion.runtimeChecks}
|
||
onClose={() => {
|
||
const { githubConnectionComplete: _complete, ...rest } = location.state as GitHubConnectionCompleteLocationState;
|
||
navigate({ pathname: location.pathname, search: location.search, hash: location.hash }, { replace: true, state: rest });
|
||
}}
|
||
onCloseAutoFocus={() => heading.current?.focus()}
|
||
/>
|
||
)}
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function EndpointExecutionDefaults({ endpoint }: { endpoint: ChatEndpoint }) {
|
||
const queryClient = useQueryClient();
|
||
return <section className="max-w-3xl py-5"><ChatExecutionDefaults
|
||
key={endpoint.id}
|
||
companyId={endpoint.companyId}
|
||
value={endpoint.executionDefaults}
|
||
onSave={async (executionDefaults) => {
|
||
const next = await chatEndpointsApi.update(endpoint.id, { executionDefaults });
|
||
queryClient.setQueryData(queryKeys.chatEndpoints.detail(endpoint.id), next);
|
||
}}
|
||
/></section>;
|
||
}
|
||
|
||
function EmailAccess({ endpoint }: { endpoint: ChatEndpoint }) {
|
||
const connection = useQuery({
|
||
queryKey: queryKeys.tools.connection(endpoint.connectionId ?? ""),
|
||
queryFn: () => toolsApi.getConnection(endpoint.connectionId!),
|
||
enabled: Boolean(endpoint.connectionId),
|
||
});
|
||
const agents = useQuery({
|
||
queryKey: queryKeys.agents.list(endpoint.companyId),
|
||
queryFn: () => agentsApi.list(endpoint.companyId),
|
||
});
|
||
const agentsView = useQueryView(agents);
|
||
const connectionView = useQueryView(connection);
|
||
if (!endpoint.connectionId) return <p role="alert" className="text-sm text-destructive">Connection access could not be loaded.</p>;
|
||
if (agentsView.kind === "error" || connectionView.kind === "error") return (
|
||
<QueryErrorState
|
||
error={agentsView.kind === "error" ? agents.error : connection.error}
|
||
action="load connection access"
|
||
onRetry={() => { agentsView.retry(); connectionView.retry(); }}
|
||
retrying={agents.isFetching || connection.isFetching}
|
||
/>
|
||
);
|
||
if (agents.isPending || connection.isPending || agentsView.kind === "reconnecting" || connectionView.kind === "reconnecting") {
|
||
return <p role="status" className="text-sm text-muted-foreground">Loading access…</p>;
|
||
}
|
||
const sourceId = connection.data?.config?.credentialConnectionId;
|
||
const credentialId = typeof sourceId === "string" ? sourceId : endpoint.connectionId;
|
||
return <section className="max-w-3xl space-y-4">
|
||
<h2 className="text-lg font-semibold">Access</h2>
|
||
{credentialId !== endpoint.connectionId && <p className="text-sm text-muted-foreground">These settings apply to the saved AgentMail account and all inboxes using it.</p>}
|
||
<EmailConnectionAccess key={credentialId} companyId={endpoint.companyId} connectionId={credentialId} agents={agents.data ?? []} />
|
||
</section>;
|
||
}
|
||
|
||
function Settings({
|
||
endpointId,
|
||
endpoint,
|
||
}: {
|
||
endpointId: string;
|
||
endpoint: Awaited<ReturnType<typeof chatEndpointsApi.get>>;
|
||
}) {
|
||
const queryClient = useQueryClient();
|
||
const { pushToast } = useToast();
|
||
const resourcesQuery = useQuery({
|
||
queryKey: queryKeys.chatEndpoints.resources(endpointId),
|
||
queryFn: () => chatEndpointsApi.listResources(endpointId),
|
||
enabled: endpoint.provider !== "speko",
|
||
...(endpoint.provider === "slack" ? liveChatQueryOptions : {}),
|
||
});
|
||
const resourcesView = useQueryView(resourcesQuery);
|
||
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: describeError(error).body,
|
||
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: describeError(error).body,
|
||
tone: "error",
|
||
}),
|
||
});
|
||
if (endpoint.provider === "speko") return null;
|
||
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 === "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"}{" "}
|
||
<request>
|
||
</code>
|
||
<p className="mt-2 text-muted-foreground">
|
||
Telegram'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 className="space-y-2">
|
||
<h3 className="text-sm font-semibold">{endpoint.provider === "slack" ? "Allowed Channels" : "Destinations"}</h3>
|
||
{resourcesView.kind === "error" ? <QueryErrorState size="inline" error={resourcesQuery.error} action={endpoint.provider === "slack" ? "load the channels" : "load the destinations"} onRetry={resourcesView.retry} retrying={resourcesView.isFetching} /> : resourcesQuery.isLoading || resourcesView.kind === "reconnecting" ? (
|
||
<p className="text-sm text-muted-foreground">Loading destinations…</p>
|
||
) : destinationResources.length === 0 && endpoint.provider !== "slack" ? (
|
||
<p className="rounded-lg border border-dashed border-border p-4 text-sm text-muted-foreground">
|
||
No destinations yet.
|
||
</p>
|
||
) : (
|
||
<div className={endpoint.provider === "slack" ? "space-y-1" : "divide-y divide-border border-y border-border"}>
|
||
{destinationResources.map((resource) => (
|
||
<div key={resource.id} className="py-3 space-y-3">
|
||
<div className="flex items-center gap-3">
|
||
<div className={cn("min-w-0 flex-1", ANALYTICS_MASK_CLASS)}>
|
||
<p className="truncate text-sm font-medium">
|
||
{resource.label}
|
||
</p>
|
||
{(resource.availability !== "available" || resource.detail) && <p className="text-xs text-muted-foreground">
|
||
{resource.availability === "available"
|
||
? resource.detail
|
||
: "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>
|
||
<details className="text-sm">
|
||
<summary className="cursor-pointer text-muted-foreground">Task defaults</summary>
|
||
<div className="pt-3"><ChatExecutionDefaults
|
||
companyId={endpoint.companyId}
|
||
value={resource.executionDefaults}
|
||
resource
|
||
onSave={async (executionDefaults) => {
|
||
const next = await chatEndpointsApi.updateResources(endpointId, [{ id: resource.id, executionDefaults }]);
|
||
queryClient.setQueryData(queryKeys.chatEndpoints.resources(endpointId), next);
|
||
}}
|
||
/></div>
|
||
</details>
|
||
</div>
|
||
))}
|
||
{endpoint.provider === "slack" && (
|
||
<p className="py-3 text-sm text-muted-foreground">
|
||
Invite {endpoint.assignedAgentName} to a channel to add it
|
||
</p>
|
||
)}
|
||
</div>
|
||
)}
|
||
</div>
|
||
{endpoint.provider !== "github" && (
|
||
<div className="space-y-3">
|
||
<SettingToggle
|
||
label="Allow direct messages"
|
||
detail={
|
||
endpoint.provider === "discord"
|
||
? "People must also enable Direct Messages in their shared Discord server’s Privacy Settings."
|
||
: undefined
|
||
}
|
||
checked={endpoint.allowDirectMessages ?? false}
|
||
pending={updateEndpoint.isPending}
|
||
onChange={(allowDirectMessages) =>
|
||
updateEndpoint.mutate({ allowDirectMessages })
|
||
}
|
||
/>
|
||
{endpoint.provider === "slack" && (
|
||
<SettingToggle
|
||
label="Require at-mention in channels"
|
||
detail="In channels, require an @mention to start a conversation with this bot. Replies in existing threads and direct messages do not require an @mention. Direct messages must be allowed above."
|
||
checked={endpoint.requireAtMention ?? false}
|
||
pending={updateEndpoint.isPending}
|
||
onChange={(requireAtMention) =>
|
||
updateEndpoint.mutate({ requireAtMention })
|
||
}
|
||
/>
|
||
)}
|
||
{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>
|
||
)}
|
||
{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 === "slack" && <SlackSetupAdvanced label="Slack tools"><SlackToolsSettings companyId={endpoint.companyId} endpointId={endpointId} /></SlackSetupAdvanced>}
|
||
</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 py-3">
|
||
<div className="min-w-0 flex-1">
|
||
<p className="text-sm font-medium">{label}</p>
|
||
{detail && <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 [inviteCopied, setInviteCopied] = useState(false);
|
||
const [confirmationFor, setConfirmationFor] = useState<string | null>(null);
|
||
const joinCommand = `${endpoint.setup?.slackApp?.command ?? endpoint.setup?.command ?? "/paperclip"} connect`;
|
||
const linksQuery = useQuery({
|
||
queryKey: queryKeys.chatEndpoints.principals(endpointId),
|
||
queryFn: () => chatEndpointsApi.listPrincipals(endpointId),
|
||
refetchInterval: 5000,
|
||
});
|
||
const linksView = useQueryView(linksQuery);
|
||
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: describeError(error).body, tone: "error" }),
|
||
});
|
||
const createIntent = useMutation({
|
||
mutationFn: (principalId: string) =>
|
||
chatEndpointsApi.createLinkIntent(endpointId, principalId),
|
||
onSuccess: ({ confirmationUrl }) => {
|
||
setConfirmationUrl(
|
||
new URL(confirmationUrl, window.location.origin).toString(),
|
||
);
|
||
|
||
},
|
||
onError: (error) =>
|
||
pushToast({
|
||
title: "Couldn't create identity link",
|
||
body: describeError(error).body,
|
||
tone: "error",
|
||
}),
|
||
});
|
||
const revoke = useMutation({
|
||
mutationFn: (principalId: string) =>
|
||
chatEndpointsApi.revokeLink(endpointId, principalId),
|
||
onSuccess: () => queryClient.invalidateQueries({ queryKey: queryKeys.chatEndpoints.principals(endpointId) }),
|
||
onError: (error) => pushToast({ title: "Couldn't disconnect account", body: describeError(error).body, tone: "error" }),
|
||
});
|
||
const links = linksQuery.data ?? [];
|
||
return (
|
||
<section className="max-w-3xl space-y-7">
|
||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||
<h2 className="text-lg font-semibold">People</h2>
|
||
{endpoint.provider === "slack" && <Dialog>
|
||
<DialogTrigger asChild><Button>Invite people</Button></DialogTrigger>
|
||
<DialogContent className={ANALYTICS_MASK_CLASS}>
|
||
<DialogHeader>
|
||
<DialogTitle>Invite people to talk to {endpoint.assignedAgentName}</DialogTitle>
|
||
<DialogDescription>Share these instructions with someone in your Slack workspace.</DialogDescription>
|
||
</DialogHeader>
|
||
<div className="space-y-4 text-sm">
|
||
<ol className="list-decimal space-y-3 pl-5">
|
||
<li>Send <code className="font-mono">{joinCommand}</code> in Slack.</li>
|
||
<li>Open the bot’s private link and sign in to Paperclip to confirm your Slack account.</li>
|
||
<li>If you’re new to this organization, request access and wait for an admin to approve.</li>
|
||
</ol>
|
||
<p className="text-muted-foreground">The confirmation link is personal and expires after 15 minutes.</p>
|
||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||
<Button variant="ghost" onClick={() => {
|
||
void copyTextToClipboard(joinCommand).then(() => setJoinCommandCopied(true), () => pushToast({ title: "Couldn't copy the command", tone: "error" }));
|
||
}}>{joinCommandCopied ? <Check className="size-4" /> : <Copy className="size-4" />}{joinCommandCopied ? "Copied" : "Copy command"}</Button>
|
||
<Button onClick={() => {
|
||
const workspace = endpoint.providerAccountId ? `https://app.slack.com/client/${encodeURIComponent(endpoint.providerAccountId)}` : "https://app.slack.com/";
|
||
void copyTextToClipboard(`Talk to ${endpoint.assignedAgentName} in Slack: ${workspace}\nSend ${joinCommand}, then open the bot’s private link and sign in to Paperclip to confirm your account. If you’re new to the organization, request access for an admin to approve.`).then(() => setInviteCopied(true), () => pushToast({ title: "Couldn't copy invitation", tone: "error" }));
|
||
}}>{inviteCopied ? <Check className="size-4" /> : <Copy className="size-4" />}{inviteCopied ? "Invitation copied" : "Copy invitation"}</Button>
|
||
</div>
|
||
</div>
|
||
</DialogContent>
|
||
</Dialog>}
|
||
</div>
|
||
<p className="text-sm text-muted-foreground">People with linked accounts use their own Paperclip permissions. <Link className="underline underline-offset-4" to="/company/settings/members">Manage members</Link></p>
|
||
{confirmationUrl && (
|
||
<div className="space-y-2 border-y border-border py-3">
|
||
<p className={cn("text-sm font-medium", ANALYTICS_MASK_CLASS)}>Confirm {confirmationFor ?? "this account"}</p>
|
||
<p className="text-xs text-muted-foreground">Share only with this person. They must sign in and confirm their own account.</p>
|
||
<p className={cn("break-all text-xs text-muted-foreground", ANALYTICS_NO_CAPTURE_CLASS)}>
|
||
{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">
|
||
{linksQuery.isPending || linksView.kind === "reconnecting" ? <p role="status" className="text-sm text-muted-foreground">Loading people…</p> : linksView.kind === "error" ? <QueryErrorState size="inline" error={linksQuery.error} action="load people" onRetry={linksView.retry} retrying={linksView.isFetching} /> : links.length === 0 ? (
|
||
<p className="rounded-lg border border-dashed border-border p-4 text-sm text-muted-foreground">
|
||
No linked accounts yet. Invite someone to connect.
|
||
</p>
|
||
) : (
|
||
<div role="list" aria-label="People" className="divide-y divide-border border-y border-border">
|
||
{links.map((link) => (
|
||
<div
|
||
key={link.id}
|
||
role="listitem"
|
||
className="flex flex-wrap items-center gap-3 py-3"
|
||
>
|
||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
||
<Avatar aria-hidden="true">
|
||
{link.paperclipUserImage && <AvatarImage src={link.paperclipUserImage} alt="" />}
|
||
<AvatarFallback>{deriveInitials(link.paperclipUserLabel ?? link.externalLabel)}</AvatarFallback>
|
||
</Avatar>
|
||
<div className={cn("min-w-0", ANALYTICS_MASK_CLASS)}>
|
||
<p className="truncate text-sm" title={link.paperclipUserLabel ?? link.externalLabel}>{link.paperclipUserLabel ?? link.externalLabel}</p>
|
||
{(link.status !== "linked" || link.externalLabel !== link.paperclipUserLabel) && <p className="text-xs text-muted-foreground">
|
||
{link.status === "revoked" ? "Disconnected" : link.status === "linked"
|
||
? link.externalLabel
|
||
: "Waiting for account confirmation"}
|
||
</p>}
|
||
</div>
|
||
</div>
|
||
{link.status === "linked" ? (
|
||
<Button
|
||
size="sm"
|
||
variant="ghost"
|
||
disabled={revoke.isPending}
|
||
onClick={() => revoke.mutate(link.principalId)}
|
||
>
|
||
<Unlink />
|
||
Disconnect
|
||
</Button>
|
||
) : (
|
||
<Button
|
||
size="sm"
|
||
variant="outline"
|
||
disabled={createIntent.isPending}
|
||
onClick={() => { setConfirmationUrl(null); setConfirmationFor(link.externalLabel); createIntent.mutate(link.principalId); }}
|
||
>
|
||
Create confirmation link
|
||
</Button>
|
||
)}
|
||
</div>
|
||
))}
|
||
</div>
|
||
)}
|
||
</div>
|
||
<SlackSetupAdvanced label="Guest access">
|
||
<SettingToggle label="Allow unlinked people"
|
||
detail="People without linked accounts can start isolated tasks. They cannot approve actions, spend, or manage access. Requests are refused when isolation is unavailable."
|
||
checked={allowUnlinked} pending={updatePolicy.isPending} onChange={value => updatePolicy.mutate(value)} />
|
||
</SlackSetupAdvanced>
|
||
{endpoint.provider === "slack" && <SlackSetupAdvanced label="Personal Slack search"><SlackSearchAccess companyId={endpoint.companyId} endpointId={endpointId} /></SlackSetupAdvanced>}
|
||
</section>
|
||
);
|
||
}
|
||
|
||
function Conversations({
|
||
endpointId,
|
||
provider,
|
||
}: {
|
||
endpointId: string;
|
||
provider: ChatProvider;
|
||
}) {
|
||
const query = useQuery({
|
||
queryKey: queryKeys.chatEndpoints.conversations(endpointId),
|
||
queryFn: () => chatEndpointsApi.listConversations(endpointId),
|
||
...liveChatQueryOptions,
|
||
});
|
||
const view = useQueryView(query);
|
||
return (
|
||
<section className="space-y-4">
|
||
{query.isPending || view.kind === "reconnecting" ? <p role="status" className="text-sm text-muted-foreground">Loading conversations…</p> : view.kind === "error" ? (
|
||
<QueryErrorState error={query.error} action="load the conversations" onRetry={view.retry} retrying={view.isFetching} />
|
||
) : <ChatConversationList rows={query.data ?? []} provider={provider} />}
|
||
</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 view = useQueryView(query);
|
||
const activityLoaded = view.kind === "ready" || view.kind === "stale";
|
||
const calls = useSpekoCallHistory(endpoint.companyId, endpointId, endpoint.provider === "speko" && !cursor);
|
||
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: describeError(error).body,
|
||
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: describeError(error).body,
|
||
tone: "error",
|
||
}),
|
||
});
|
||
const lifecycle = useMutation({
|
||
mutationFn: async (action: "pause" | "resume" | "remove") =>
|
||
endpoint.provider === "agentmail"
|
||
? emailApi.control(endpointId, action)
|
||
: chatEndpointsApi.setup(endpointId, { action }),
|
||
onSuccess: async (next, action) => {
|
||
await queryClient.invalidateQueries({
|
||
queryKey: queryKeys.chatEndpoints.list(next.companyId),
|
||
});
|
||
if (endpoint.provider === "agentmail") {
|
||
await Promise.all([
|
||
queryClient.invalidateQueries({ queryKey: ["email-inboxes", next.companyId] }),
|
||
queryClient.invalidateQueries({ queryKey: queryKeys.chatEndpoints.detail(endpointId) }),
|
||
]);
|
||
}
|
||
if (action === "remove") {
|
||
navigate("/apps");
|
||
return;
|
||
}
|
||
if (endpoint.provider !== "agentmail") 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: describeError(error).body,
|
||
tone: "error",
|
||
}),
|
||
});
|
||
const rows = query.data?.items ?? [];
|
||
// Calls use their own caller-authorized API and appear once in recent activity.
|
||
// Older connection-event pages retain the existing cursor contract.
|
||
const activityEntries = [
|
||
...(view.kind !== "error" ? rows.map(item => ({ kind: "connection" as const, id: `connection:${item.id}`, createdAt: item.createdAt, item })) : []),
|
||
...(!cursor && !calls.error ? calls.entries.map(entry => ({ kind: "call" as const, id: `call:${entry.session.id}`, createdAt: entry.session.createdAt, entry })) : []),
|
||
...(!cursor && !calls.incomingError ? calls.unapprovedCalls.map(call => ({ kind: "unapproved_call" as const, id: `unapproved:${call.id}`, createdAt: call.createdAt, call })) : []),
|
||
].sort((a, b) => b.createdAt.localeCompare(a.createdAt) || a.id.localeCompare(b.id));
|
||
|
||
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" aria-label="Connection activity">
|
||
<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(
|
||
endpoint.provider === "agentmail" && status !== "draft" && status !== "verifying"
|
||
? `/apps/chat/${endpoint.id}/settings`
|
||
: `/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">
|
||
<div className="flex items-center justify-between gap-3">
|
||
<h3 className="text-sm font-semibold">Recent activity</h3>
|
||
{endpoint.provider === "speko" && !cursor && <Button size="sm" variant="ghost" onClick={() => { void query.refetch(); calls.onRetry(); }} disabled={query.isFetching || calls.loading}>Refresh</Button>}
|
||
</div>
|
||
{endpoint.provider === "agentmail" && rows.some((item) => item.kind === "publication" && item.status === "delivery_unknown") && (
|
||
<p className="text-sm text-muted-foreground">
|
||
Review unconfirmed email delivery in the{" "}
|
||
<Link to={`/apps/chat/${endpointId}/conversations`} className="underline underline-offset-4">conversation’s task</Link>.
|
||
</p>
|
||
)}
|
||
<div className="divide-y divide-border border-y border-border">
|
||
{(query.isLoading || view.kind === "reconnecting" || calls.loading) && (
|
||
<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>
|
||
)}
|
||
{view.kind === "error" && (
|
||
<div className="py-4">
|
||
<QueryErrorState
|
||
error={query.error}
|
||
action="load the connection activity"
|
||
onRetry={view.retry}
|
||
retrying={view.isFetching}
|
||
/>
|
||
</div>
|
||
)}
|
||
{endpoint.provider === "speko" && !cursor && [
|
||
calls.error && `Call activity could not be loaded. ${calls.error}`,
|
||
calls.incomingError && `Unapproved calls could not be loaded. ${calls.incomingError}`,
|
||
calls.endError && `The call could not be ended. ${calls.endError}`,
|
||
].filter(Boolean).map((message) => <div key={String(message)} className="flex flex-wrap items-center justify-between gap-3 py-4"><p role="alert" className="text-sm text-destructive">{message}</p><Button size="sm" variant="outline" onClick={calls.onRetry}>Retry calls</Button></div>)}
|
||
{activityEntries.map(entry => {
|
||
if (entry.kind === "call") return <SpekoCallActivityItem key={entry.id} entry={entry.entry} presentation="activity" onEnd={calls.onEnd} ending={calls.endingSessionId === entry.entry.session.id} />;
|
||
if (entry.kind === "unapproved_call") return <SpekoUnapprovedCallActivityItem key={entry.id} call={entry.call} presentation="activity" />;
|
||
const item = entry.item;
|
||
return (
|
||
<div
|
||
key={entry.id}
|
||
data-activity-kind="connection"
|
||
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>
|
||
{endpoint.provider !== "agentmail" && 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>
|
||
)}
|
||
{endpoint.provider !== "agentmail" && isResolutionEligible(item) && (
|
||
<Button
|
||
size="sm"
|
||
variant="outline"
|
||
onClick={() => setResolutionItem(item)}
|
||
>
|
||
Resolve
|
||
</Button>
|
||
)}
|
||
</div>
|
||
);
|
||
})}
|
||
{activityLoaded && !calls.loading && !calls.error && !calls.incomingError && activityEntries.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 || view.kind === "error"} 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 className={ANALYTICS_MASK_CLASS}>
|
||
<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 className={ANALYTICS_MASK_CLASS}>
|
||
<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}
|
||
{endpoint.provider === "slack" && (
|
||
<> <a
|
||
href={endpoint.setup?.slackRegistration?.managementUrl ?? "https://api.slack.com/apps"}
|
||
target="_blank"
|
||
rel="noopener noreferrer"
|
||
className="underline underline-offset-4"
|
||
>Open Slack app settings</a> to manage or delete the Slack app.</>
|
||
)}
|
||
</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>
|
||
);
|
||
}
|