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"; 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 = { 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 = { 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, ) { // 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(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(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 ; if (endpointQuery.isLoading || endpointView.kind === "reconnecting") return (
Loading connection…
); if (endpointView.kind === "error" || !endpoint) return ( ); if (endpoint.provider === "agentmail" && activeTab === "settings") return
; 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 (

{endpoint.provider === "speko" && } {endpoint.provider === "github" ? (endpoint.botLabel ?? endpoint.assignedAgentName) : endpoint.assignedAgentName}{endpoint.provider === "speko" ? " in Speko" : ""}

{endpoint.provider === "github" ? <>{endpoint.assignedAgentName}{endpoint.providerAccountLabel && · {endpoint.providerAccountLabel}} : endpoint.providerAccountLabel ?? (endpoint.provider === "agentmail" ? endpoint.botExternalId ?? "Email connection" : "Chat connection")}

{endpoint.provider === "github" &&
} {endpoint.provider === "imessage-photon" && endpoint.botExternalId && endpoint.photonAllocation !== "shared" && (
{endpoint.botExternalId} {copyStatus}
)}
{endpoint.provider === "speko" && Open Speko} {endpoint.provider === "slack" && !setupIncomplete && } {slackUrl && } {setupIncomplete ? ( ) : null} {endpoint.status !== "active" && }
{endpoint.provider === "github" && } {activeTab === "settings" && endpoint.provider === "speko" && endpoint.status === "active" &&
} {endpoint.provider === "slack" && } {endpoint.provider === "github" && } {activeTab === "settings" && endpoint.provider !== "github" && } {activeTab === "settings" && } {activeTab === "reviews" && endpoint.provider === "github" && } {activeTab === "access" && endpoint.provider === "speko" && (

Private voice access

Browser calls use the signed-in Paperclip user’s current company access. Each call stays bound to its selected agent and task.

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.

)} {activeTab === "access" && endpoint.provider === "agentmail" && } {activeTab === "access" && endpoint.provider !== "speko" && endpoint.provider !== "github" && endpoint.provider !== "agentmail" && ( )} {activeTab === "conversations" && ( )} {activeTab === "activity" && ( )} {endpoint.provider === "github" && activeTab === "settings" && endpoint.status === "active" && endpoint.setup?.step === "complete" && completion?.endpointId === endpoint.id && ( { 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()} /> )}
); } function EndpointExecutionDefaults({ endpoint }: { endpoint: ChatEndpoint }) { const queryClient = useQueryClient(); return
{ const next = await chatEndpointsApi.update(endpoint.id, { executionDefaults }); queryClient.setQueryData(queryKeys.chatEndpoints.detail(endpoint.id), next); }} />
; } 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

Connection access could not be loaded.

; if (agentsView.kind === "error" || connectionView.kind === "error") return ( { agentsView.retry(); connectionView.retry(); }} retrying={agents.isFetching || connection.isFetching} /> ); if (agents.isPending || connection.isPending || agentsView.kind === "reconnecting" || connectionView.kind === "reconnecting") { return

Loading access…

; } const sourceId = connection.data?.config?.credentialConnectionId; const credentialId = typeof sourceId === "string" ? sourceId : endpoint.connectionId; return

Access

{credentialId !== endpoint.connectionId &&

These settings apply to the saved AgentMail account and all inboxes using it.

}
; } function Settings({ endpointId, endpoint, }: { endpointId: string; endpoint: Awaited>; }) { 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) => 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 (
{endpoint.provider === "imessage-photon" &&

{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."}

} {endpoint.provider === "telegram" && (

Telegram group command

/task@ {endpoint.botUsername?.replace(/^@/, "") ?? "bot_username"}{" "} <request>

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.

)}

{endpoint.provider === "slack" ? "Allowed Channels" : "Destinations"}

{resourcesView.kind === "error" ? : resourcesQuery.isLoading || resourcesView.kind === "reconnecting" ? (

Loading destinations…

) : destinationResources.length === 0 && endpoint.provider !== "slack" ? (

No destinations yet.

) : (
{destinationResources.map((resource) => (

{resource.label}

{(resource.availability !== "available" || resource.detail) &&

{resource.availability === "available" ? resource.detail : "Unavailable at the provider"}

} {resource.participants?.length ?

Participants: {resource.participants.join(", ")}

: null}
toggleResource(resource, enabled) } />
Task defaults
{ const next = await chatEndpointsApi.updateResources(endpointId, [{ id: resource.id, executionDefaults }]); queryClient.setQueryData(queryKeys.chatEndpoints.resources(endpointId), next); }} />
))} {endpoint.provider === "slack" && (

Invite {endpoint.assignedAgentName} to a channel to add it

)}
)}
{endpoint.provider !== "github" && (
updateEndpoint.mutate({ allowDirectMessages }) } /> {endpoint.provider === "slack" && ( updateEndpoint.mutate({ requireAtMention }) } /> )} {endpoint.provider === "microsoft-teams" && ( updateEndpoint.mutate({ allowGroupChats }) } /> )}
)} {endpoint.provider === "slack" && { const next = await chatEndpointsApi.update(endpointId, { communicationInstructions }); queryClient.setQueryData(queryKeys.chatEndpoints.detail(endpointId), next); }} />} {endpoint.provider === "slack" && }
); } function SettingToggle({ label, detail, checked, pending, onChange, }: { label: string; detail?: string; checked: boolean; pending: boolean; onChange: (value: boolean) => void; }) { return (

{label}

{detail &&

{detail}

}
); } function Access({ endpointId, allowUnlinked, endpoint, }: { endpointId: string; allowUnlinked: boolean; endpoint: ChatEndpoint; }) { const queryClient = useQueryClient(); const { pushToast } = useToast(); const [confirmationUrl, setConfirmationUrl] = useState(null); const [joinCommandCopied, setJoinCommandCopied] = useState(false); const [inviteCopied, setInviteCopied] = useState(false); const [confirmationFor, setConfirmationFor] = useState(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 (

People

{endpoint.provider === "slack" && Invite people to talk to {endpoint.assignedAgentName} Share these instructions with someone in your Slack workspace.
  1. Send {joinCommand} in Slack.
  2. Open the bot’s private link and sign in to Paperclip to confirm your Slack account.
  3. If you’re new to this organization, request access and wait for an admin to approve.

The confirmation link is personal and expires after 15 minutes.

}

People with linked accounts use their own Paperclip permissions. Manage members

{confirmationUrl && (

Confirm {confirmationFor ?? "this account"}

Share only with this person. They must sign in and confirm their own account.

{confirmationUrl}

)}
{linksQuery.isPending || linksView.kind === "reconnecting" ?

Loading people…

: linksView.kind === "error" ? : links.length === 0 ? (

No linked accounts yet. Invite someone to connect.

) : (
{links.map((link) => (

{link.paperclipUserLabel ?? link.externalLabel}

{(link.status !== "linked" || link.externalLabel !== link.paperclipUserLabel) &&

{link.status === "revoked" ? "Disconnected" : link.status === "linked" ? link.externalLabel : "Waiting for account confirmation"}

}
{link.status === "linked" ? ( ) : ( )}
))}
)}
updatePolicy.mutate(value)} /> {endpoint.provider === "slack" && }
); } 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 (
{query.isPending || view.kind === "reconnecting" ?

Loading conversations…

: view.kind === "error" ? ( ) : }
); } function Activity({ endpointId, endpoint, }: { endpointId: string; endpoint: Awaited>; }) { const queryClient = useQueryClient(); const navigate = useNavigate(); const { pushToast } = useToast(); const [removeOpen, setRemoveOpen] = useState(false); const [resolutionItem, setResolutionItem] = useState( null, ); const [cursors, setCursors] = useState>([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 (

Connection activity

{((status !== "active" && health.message) || health.error) && (
{(status === "attention" || status === "revoked") && ( )}
{health.message &&

{health.message}

} {health.previousHealth && (

Last reported health:{" "} {health.previousHealth}

)} {health.error && (

{health.errorLabel}:{" "} {health.error}

)}
)}
Connection health and controls {endpoint.setup?.callbacksNeedUpdate && Callback URLs need attention}
{endpoint.provider === "slack" && callbackSurfaceRows.length > 0 && (

Slack callback health

{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."}

{callbackSurfaceRows.map(([label, surface]) => (

{label}

{surface.status === "current" ? "Current" : surface.status === "stale" ? "Stale URL" : "Not observed"}

{surface.observedAt && (

Last observed{" "}

)}
))}
)} {status !== "archived" && (
{status === "active" && ( )} {status === "paused" && ( )} {[ "active", "paused", "attention", "revoked", "draft", "verifying", ].includes(status) && ( )}
{status !== "draft" && status !== "verifying" && (

{providerLifecycleGuidance[endpoint.provider].reconnect}

)}
)}

Recent activity

{endpoint.provider === "speko" && !cursor && }
{endpoint.provider === "agentmail" && rows.some((item) => item.kind === "publication" && item.status === "delivery_unknown") && (

Review unconfirmed email delivery in the{" "} conversation’s task.

)}
{(query.isLoading || view.kind === "reconnecting" || calls.loading) && (
Loading activity…
)} {view.kind === "error" && (
)} {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) =>

{message}

)} {activityEntries.map(entry => { if (entry.kind === "call") return ; if (entry.kind === "unapproved_call") return ; const item = entry.item; return (

{item.summary}

{activityKindLabels[item.kind]}

{item.fileTransfer && (

{item.fileTransfer.filename} —{" "} {item.fileTransfer.phase.replaceAll("_", " ")}

)} {item.detail && (

{activityDetailLabel(item)}: {" "} {item.detail}

)}
{endpoint.provider !== "agentmail" && isReplayEligible(item) && ( )} {endpoint.provider !== "agentmail" && isResolutionEligible(item) && ( )}
); })} {activityLoaded && !calls.loading && !calls.error && !calls.incomingError && activityEntries.length === 0 && (

No connection activity yet.

)}
!open && setResolutionItem(null)} > {resolutionItem?.actionType === "slash_task_start" ? "Resolve unconfirmed task start" : resolutionItem?.actionType === "provider_effect" ? "Resolve unconfirmed provider reply" : "Resolve unconfirmed delivery"} {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) : ""} Keep unresolved {resolutionItem && activityResolutionActions(resolutionItem).includes("cancel") && ( )} {resolutionItem && activityResolutionActions(resolutionItem).includes( "retry_anyway", ) && ( )} {resolutionItem && activityResolutionActions(resolutionItem).includes( "mark_delivered", ) && ( { event.preventDefault(); if (resolutionItem) { resolveActivity.mutate({ item: resolutionItem, action: "mark_delivered", }); } }} > Mark delivered )} Remove this connection? {endpoint.assignedAgentName} will stop receiving new work from {` ${providerNames[endpoint.provider]}`}. Existing Paperclip tasks remain available.{" "} {providerLifecycleGuidance[endpoint.provider].remove} {endpoint.provider === "slack" && ( <> Open Slack app settings to manage or delete the Slack app. )} Cancel lifecycle.mutate("remove")} > {lifecycle.isPending && ( )} Remove connection
); }