mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-04 04:29:01 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agents reach outside tools through connectors, which people add on the Connectors page > - That page is one long list. Each row mixes the catalog entry with its accounts, so it is hard to scan and hard to tell what is installed > - Some connectors also bring skills, but the page does not show them > - This pull request renames the page to Plugins and changes the browse view into a marketplace of small cards grouped by category. Each card opens a plugin page that holds the accounts, the skills and the tool permissions > - The benefit is a catalog that people can scan fast, with one place per connector for its accounts and its skills. Connector behavior does not change ## Linked Issues or Issue Description **Subsystem affected** UI: the Connectors (Apps catalog) pages under `ui/src/pages/apps/` and the navigation labels that point to them. **Problem or motivation** The Connectors browse page is a vertical list of large rows. A row shows the catalog entry and every account under it. People must expand rows to see what is connected. The page does not show which skills come with a connector. **Proposed solution** - Rename the page from Connectors to Plugins in the navigation, the breadcrumbs, and the page titles. A single app is still called a connector. - Remove the Browse / Review rail. The page header carries the title, a Review shortcut, and an Add menu for a custom MCP server, a pasted config, or an assistant connection. - Show the catalog as a marketplace under one "All" tab: "Most used" and "New and noteworthy" for first-party connectors, then one block per category. Composio and Arcade connectors sit in the same blocks. A block shows at most nine plugins, its total, and a "See all" link to a category page at `/apps/category/:categoryId`. - Use a compact card: logo, name, description, and one corner control. The control is a plus to connect, a check when connected, or a warning when an account needs attention. - Open a plugin page at `/apps/plugin/:pluginKey` from each card. The page has Connect in its header and groups Accounts, Connector, Skills, Tool permissions, and Information as blocks. Tool permissions shows a connected account's actions as Reads and Writes, each with a group policy and per-action policies. - Start sign-in straight from the card for a one-click connector: one OAuth method that Paperclip can start itself, with nothing to fill in and no warning to read. The success screen states who can use the connection and links to where that changes. - Search reads plugin titles only. - Keep the account list on the Installed filter. **Related pull requests** A search of open and closed pull requests for the Connectors browse page, a plugins or connectors marketplace, connector categories, and one-click sign-in found no duplicate. #22863 compresses connector logo files and does not overlap with these pages. **Alternatives considered** - An experimental setting that keeps the old page. The product owner chose to replace the page for everyone. - A new backend link between connectors and catalog skills. This pull request stays in the front end. The pairing for GitHub is a constant in `PluginSkills.tsx`. - Real categories for Composio apps. Its public catalog file has names only, so those apps are sorted by keywords in the name and the rest go to "Other". Arcade's catalog states a category, which is now carried through `AggregatorAppCatalogEntry.category`. ## What Changed - `Browse.tsx`: keeps all data loading, connect logic, and dialogs. The render now has five views: marketplace, category page, flat results grid, Installed list, and plugin page. The default source is `all`; the `paperclip` source is removed. - `PluginMarketplace.tsx` (new): `PluginTile`, `PluginShelf` (count and "See all"), `PluginCategories`, and the category labels. - `PluginsHeader.tsx` (new): page title, Review shortcut with the pending count, and the Add menu. - `PluginPageSections.tsx` (new): plugin page header, Connector row, and Information facts read from the app definition. - `PluginPermissions.tsx` (new): Reads and Writes blocks for a connected account. Saves go through `useConnectionPermissionSave` and restate agent access exactly as the per-connection page does. The four helpers it shares with that page moved from `AppDetail.tsx` to `app-detail/saved-permissions.ts` with no behavior change. - `PluginSkills.tsx` (new): lists built-in connector skills, skills that a connected server publishes, and paired catalog skills. "Add skill" calls the existing catalog install endpoint. - `plugin-categories.ts` (new): maps Arcade categories onto the Plugins categories and guesses a category from the name for apps that state none. - `features/connections/one-click-oauth.ts` (new): the one-click rule and the hand-over of the sign-in window from the card's click to the connect flow. A browser only opens that window during a click, so the card opens it and `ConnectionSetupFlow` takes it over. If the window is blocked, or the page is reloaded, the ordinary confirmation screen shows. - `ConnectionSetupFlow.tsx`: takes the handed-over window, starts sign-in when the app qualifies, and adds a "Change" link beside the stated default on the success screen. - `apps-rail.ts` (new), `AppsSidebar*.tsx`, `Layout*.tsx`: the marketplace pages have no second rail. Chat setup and detail keep theirs, and the developer pages keep one while a developer tab is on. - `ConnectorCard`: new `variant="page"` that renders the accounts as one block with "Add account" at the bottom. - `ConnectorsToolbar.tsx`: source filters first, a wider "Search plugins" field on the right. - `App.tsx`, `Layout.tsx`, `Layout.production.tsx`: new `apps/plugin/:pluginKey` and `apps/category/:categoryId` routes and reserved subpaths. - Navigation and breadcrumb labels: "Connectors" becomes "Plugins" in 19 files, and the instance plugin system becomes "System plugins". - `packages/shared/src/aggregator-app-catalog.ts`: optional `category` on a catalog entry, set from Arcade's catalog. - `ui/storybook/prototypes/ConnectorCatalogNavigation.tsx`: keeps its own five-source list so the older prototype still builds. - Tests: label renames in the specs and stories that named Connectors or "Search connectors". Seven specs now reach the custom-server setup through the Add menu. New specs: `one-click-connect`, `plugins-browse`. `apps-prosumer-mcp-flow` also covers the plugin page permissions and the success-screen link. Kept on purpose, so current flows and specs continue to work: the `Connector list` list label, `data-app-slug` and `data-connected` on each card, and the `<Verb> <App name>` button names. ## Verification - `cd ui && pnpm typecheck`: pass. - `pnpm run check:token-gates`: pass. - `cd ui && npx vitest run`: 564 files, 7,059 tests pass, 1 skipped. - `cd packages/shared && npx vitest run src/aggregator-app-catalog.test.ts`: 9 tests pass. - `PAPERCLIP_RUNNER_BINARY=/usr/bin/true npx playwright test --config tests/e2e/playwright.config.ts` for the 15 spec files under `tests/e2e/*.spec.ts` that touch the Plugins pages, plus `one-click-connect` and `plugins-browse`: all pass (3 skipped by their own conditions). - Storybook: built this branch and master and ran the interaction tests of the 253 stories in the files that mount the browse page. Master passes 230; this branch passes the same 230. The 23 that fail do so on master too. - Manual: opened Plugins, a category page, a plugin page, the Installed filter, and Review on a local instance. - Not run locally: `execution-recovery/recovery.spec.ts`, `in-feed-native/connections.spec.ts`, the runner e2e tests, and the repo-wide typecheck (it needs the Rust toolchain). A real provider sign-in was not completed; the one-click test stops at the point the flow starts. `pnpm verify` exits 2 and names CI as the source of broad coverage. ## Risks - The page changes for every user. People who know the old list must learn the new layout. The Installed filter keeps the old account list. - The instance plugin system is renamed "System plugins" in the settings navigation, breadcrumbs, and its management page, so the two areas no longer share a name. URLs and lower-case mentions of "plugin" inside sentences are unchanged. - One-click connect skips the screen that states the access default ("Connects for everyone in your organization, available to all agents") and offers Change. The default is applied without being shown first; the success screen states it and links to the permissions page. - Most Composio apps (about 1,100 of 1,583) land in "Other", and the keyword guess is sometimes wrong. Correct categories need category data in the catalog file. - The plugin page can now save action permissions. It uses the same save path and access derivation as the per-connection page and waits for all four reads before it enables the controls. The account picker for several accounts and the read-only view have no test. - The Smoke Lab developer page has no link from the browse page; it is reachable by URL. - e2e specs that this pull request did not run locally can fail on selectors. CI must confirm them. - "New and noteworthy" is a fixed list in code. The catalog has no date to sort by. - Skill pairing is a front-end constant. Nothing records that a skill came from a connector, so removing a connector does not remove the skill. - The per-connection permissions page is not restyled in this pull request. > 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 Fable 5.2 (`claude-fable-5-2`) through Claude Code, with tool use, code execution, and subagents for read-only code search. ## 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) - [ ] 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 - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5.2 <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: "Plugins", 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>
|
||
);
|
||
}
|