Files
PaperClipAI/ui/src/pages/apps/chat/ChatEndpointDetail.tsx
T
a3313f6944 fix(ui): complete read recovery and enforce query error rendering (#18822)
## Thinking Path

> - Paperclip lets people manage agent work through the board.
> - The board reads task, agent, settings, plugin, and run data from the
server.
> - A deploy can interrupt those reads after content is already visible.
> - Local error branches can replace that content with an error or show
raw codes.
> - This pull request moves the remaining reads to the shared recovery
behavior.
> - The query-error guard prevents new local error patterns from
returning.

## Linked Issues or Issue Description

**What happened?**
Loaded lists, settings, task panels, and manual reads could clear their
content or show errors during a server restart. Some reads also disabled
the shared retry policy.

**Expected behavior**
Keep loaded content during a temporary failure. Show the shared
connection banner. Retry reads after recovery. Replace content after a
real access denial or missing resource, with readable copy.

**Steps to reproduce**
Open a task, settings page, or run log. Return 503 with
`tenant_app_unavailable` from the API. Restore the API and check that
content refreshes. Repeat with 403 and 404 to check the failure state.

Related merged work: Refs #15754, Refs #15772, Refs #17960. This change
covers remaining reads and enforcement. Browser persistence and the
outage browser suite follow separately.

## What Changed

- Repair an existing PostgreSQL deadline fixture at UTC boundaries. A
daily cap defers a heartbeat until both its original interval and the
next UTC day allow it. Keep the counted run in its seeded day and cover
noon, just before midnight and the first second after midnight with
explicit clocks and real PostgreSQL. Production scheduling is unchanged.

- Integrate the saved list, settings, shell, task, and manual-read
recovery changes against current master. Preserve the current task,
Inbox, and run-log structure.
- Add `useResilientFetch` for component-local reads. Preserve loaded
data, cancel stale requests, and retry through the shared connectivity
policy. Keep browser and pairing capabilities in memory.
- Retain run log chunks across stream changes and catch up after
recovery without duplicate chunks or stalled requests.
- Keep genuine authorization and missing-resource failures visible.
Translate known single-word codes such as `forbidden`. Show known skills
and disconnected-app failures before sibling loading states. Keep Retry
bound to its failed request.
- Make the query-error guard enforce by default and run it in the CI
policy job. Document the narrow exceptions and the read recovery
contract.
- Invalidate pending OAuth discovery when the operator leaves setup or
its context changes. Keep reserved-popup cleanup bound to the current
attempt.

## Verification

- Current read head `09d1db29dea` is merge-ready: all 59 check runs are
completed (54 successful, three skipped, two neutral), the legacy Snyk
status is successful, and both required `ci / verify` and `ci / e2e`
gates pass. Greptile Apex reviewed this exact head at 5/5 with no
unresolved threads; the branch has no merge conflicts. The current CI
run is `41748339602`.
- Current read head `09d1db29dea` includes master `683fa4725e9`. The
latest change touches only the existing server deadline test fixture.
Application source remains the previously verified `86376fa751e`
revision: all 60 affected skills/disconnected-app tests and both
application UI typechecks passed, along with token gates and the
enforcing query-error guard. Those UI suites were not repeated for this
test-only repair.
- The fixture repair passes all seven deadline integration cases and the
complete server typecheck, including the server test layer. The old
assertion deterministically fails at 23:59:06.888 UTC; its
one-second-old run also fails the first-second-of-day probe. The
corrected fixture passes noon and both midnight probes. The permanent
three-case coverage uses seeded 2099 clocks.
- Twelve new regressions fail against the previous implementation. Both
skills variants and disconnected-app pages show either request's 403 or
429 while the sibling pauses or remains fetching. Permission failures
stay visible. Retry stays usable for its failed request and recovers
independently. An initial test-fixture query-key typo was corrected
before the passing run. The finding is replied to and resolved. Greptile
reviewed prior application revision `86376fa751e` at 5/5 with no new
actionable findings or unresolved threads. The current test-only head
has now received its own Apex 5/5 review with no unresolved threads, and
its CI is successful as recorded above.
- The preceding OAuth fix passed all 237 setup tests on both application
branches. Its ten regressions prove that Back, Cancel, unmount, or
context changes retire initial discovery without creating a connection,
caching old identities, navigating an abandoned popup, or closing a
newer attempt.
- Earlier master integration `e992f770339` passed all 309 tests across
eight affected Slack, recovery, retry, submission and task files, plus
UI typecheck, token gates, enforcing query-error scan and seven guard
tests. The integration preserves Slack workspace reconnect and shared
recovery, readable execution errors, source-inspection company scoping,
and current submission behavior. Newly inherited retained-file recovery
controls keep cached data through transient failures and hide it after
definitive denial.
- The preceding cache head `97c0bc3966f` passed 1,038 focused
cache/write/editor/account/task/API tests. All 22 built-UI
outage/write/loading cases passed in 4.7 minutes on exact browser head
`b7deaaee5da`, with strict checking of all three specs. The latest
skills/app rendering fix is covered by its affected component suites;
those broader cases were not repeated for this separate read path.
- Historical broader UI, CLI and build results and unresolved aggregate
server/DB/adapter failures remain in the PR discussion. Interrupted CI
runs were audited and recorded separately; they are not counted as
passes. Controlled local outages do not prove hosted authentication or a
real Cloud restart/deploy. Real hosted acceptance remains required after
merge and deployment.

Commands for the latest fix:

```sh
pnpm --filter @paperclipai/ui exec vitest run src/pages/CompanySkills.test.tsx src/pages/apps/AppNotConnected.test.tsx
pnpm --filter @paperclipai/ui typecheck
pnpm check:token-gates
node scripts/check-query-error-rendering.mjs --enforce --summary
```

## Risks

This migration touches many read surfaces. The main risks are initial
loading, request cancellation, retained authorization state, and run-log
paging. The tests cover those states. There are no server, schema,
dependency, or API contract changes. The follow-up browser suite and
hosted deploy acceptance are required before release acceptance.

Recovered commits retain their original authors. If squash-merging,
preserve `Co-Authored-By: Bender (Fable) <bender@agents.paperclip.ing>`
and the Paperclip trailer.

## Model Used

OpenAI `gpt-6.1-sol` through Codex, with xhigh reasoning effort, tool
use, and code execution. The context window size is not exposed. Saved
source commits keep their original authorship.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have described the issue in-PR following the bug report template
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [x] My branch name describes the change and contains no internal
ticket id
- [x] The affected local tests pass; broader limitations are recorded
above
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Bender (Fable) <bender@agents.paperclip.ing>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-04 14:07:18 -08:00

1438 lines
67 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { 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<ChatProvider, string> = {
speko: "Speko",
agentmail: "AgentMail",
slack: "Slack",
github: "GitHub",
discord: "Discord",
"microsoft-teams": "Microsoft Teams",
telegram: "Telegram",
"imessage-photon": "iMessage Photon",
};
const providerLifecycleGuidance: Record<
ChatProvider,
{ reconnect: string; remove: string }
> = {
speko: {
reconnect: "Reverify this voice persona and update its signed session tools. Existing task assignments stay attached to their history.",
remove: "Stop this connection from accepting voice requests. Accepted work and task history remain in Paperclip.",
},
agentmail: { reconnect: "Reconnect the same email inbox.", remove: "Disconnect email and retain task history." },
slack: {
reconnect:
"Reconnect verifies or replaces credentials for this same Slack app. It does not reinstall the app or change its workspace or channel membership.",
remove:
"Paperclip archives the endpoint, stops new ingress, and retires its saved Slack credentials. It does not uninstall the Slack app: the app remains installed, and its bot remains in channels, until you remove them in Slack.",
},
github: {
reconnect:
"Reconnect verifies this same App and installation, then updates its webhook URL, secret, and secure delivery settings. It does not reinstall the App or change repository access.",
remove:
"Paperclip archives the endpoint, stops new ingress, and retires its saved App key and webhook secret. It does not uninstall the GitHub App: the App, its installations, and its webhook settings remain until you remove or update them on GitHub.",
},
discord: {
reconnect:
"Reconnect verifies this same Discord application and server installation. It does not add or remove the bot from the server.",
remove:
"Paperclip archives the endpoint, stops its Paperclip Gateway connection, and retires its saved bot token. It does not uninstall the bot: the bot remains in the Discord server, and the application remains in the Developer Portal, until you remove them there.",
},
"microsoft-teams": {
reconnect:
"Reconnect verifies this same Microsoft app, tenant, and bot identity. It does not upload or reinstall the Teams app.",
remove:
"Paperclip archives the endpoint, stops new ingress, and retires its saved client secret. It does not uninstall the Teams app: the Entra app registration, Azure Bot, custom Teams app, and Teams installations remain until you remove them in Microsoft.",
},
"imessage-photon": {
reconnect: "Reconnect verifies the same Photon project and line allocation, then recovers eligible missed messages.",
remove: "Disconnect archives this channel and removes its saved secret. Your Photon project, number, subscription, and Messages history remain in Photon.",
},
telegram: {
reconnect:
"Reconnect verifies this same BotFather bot and automatically refreshes its Paperclip webhook and command menu.",
remove:
"Paperclip archives the endpoint and queues durable removal of its Telegram webhook and command menu. After Telegram confirms that cleanup, Paperclip retires the saved token. The BotFather bot and its chat memberships remain until you remove them in Telegram.",
},
};
const activityKindLabels: Record<ChatActivityItem["kind"], string> = {
delivery: "Inbound delivery",
publication: "Outbound publication",
action: "Provider action",
health: "Connection health",
repair: "Connection repair",
};
const replayableFailureStates = new Set(["failed"]);
// Provider callbacks do not necessarily emit a Board activity event. Refresh
// only mounted operational views, and stop polling when the browser is hidden.
const liveChatQueryOptions = {
staleTime: 0,
refetchInterval: 5_000,
refetchIntervalInBackground: false,
} as const;
export function isReplayEligible(item: ChatActivityItem): boolean {
if (
item.fileTransfer ||
!item.replayable ||
!replayableFailureStates.has(item.status)
) {
return false;
}
if (item.kind === "delivery") return item.status === "failed";
return item.kind === "publication";
}
export function activityResolutionActions(item: ChatActivityItem) {
const offered = item.resolutionActions ?? [];
if (!item.fileTransfer) return offered;
if (
item.kind !== "publication" ||
!Number.isSafeInteger(item.fileTransfer.version) ||
item.fileTransfer.version < 1
)
return [];
if (
![
"consent_unknown",
"upload_unknown",
"file_info_unknown",
"conflict",
].includes(item.fileTransfer.phase)
)
return [];
// Only the file-info stage can use ordinary visible-delivery resolution.
// Earlier consent/upload evidence must not be fabricated by these buttons.
return item.fileTransfer.phase === "file_info_unknown"
? offered
: offered.filter((action) => action === "cancel");
}
export function activityResolutionDescription(item: ChatActivityItem): string {
const phase = item.fileTransfer?.phase;
if (phase === "file_info_unknown")
return "The file upload was confirmed, but its Teams notification was not. Check Teams first. Retrying sends only that notification, not the file bytes, and may create a duplicate card.";
if (phase === "consent_unknown")
return "The consent card may have reached Teams. File delivery is not confirmed. Cancelling here does not remove any card already sent.";
if (phase)
return "The file may already exist in OneDrive. Cancelling stops this Paperclip transfer; it does not delete remote bytes. Uploads cannot be marked delivered or retried from this uncertain state.";
return "Paperclip lost confirmation after sending. Check the provider conversation first. Retrying can create a duplicate message.";
}
export function isResolutionEligible(item: ChatActivityItem): boolean {
return (
(item.kind === "publication" || item.kind === "action") &&
item.status === "delivery_unknown" &&
activityResolutionActions(item).length > 0
);
}
export function isIndividuallyToggleableResource(
provider: ChatProvider,
resourceType: string,
): boolean {
return !(
provider === "microsoft-teams" &&
(resourceType === "direct_message" || resourceType === "group_chat")
);
}
function activityDetailLabel(item: ChatActivityItem): string {
return replayableFailureStates.has(item.status) ? "Reason" : "Details";
}
export function connectionHealthPresentation(
endpoint: Pick<ChatEndpoint, "status" | "healthMessage" | "lastError">,
) {
// Health events outlive pause/removal. They are history, not lifecycle state.
const lifecycleMessages = {
draft: "Connection setup is incomplete.",
verifying: "Connection verification is in progress.",
paused: "Connection is paused. Resume it to receive new messages.",
attention: "Connection needs attention.",
revoked: "Connection access is revoked. Reconnect to verify access.",
archived: "Connection has been removed from Paperclip.",
};
const lifecycleMessage =
endpoint.status === "active" ? null : lifecycleMessages[endpoint.status];
return {
message: lifecycleMessage ?? endpoint.healthMessage ?? null,
previousHealth: lifecycleMessage ? (endpoint.healthMessage ?? null) : null,
error: endpoint.lastError ?? null,
errorLabel: ["active", "attention", "revoked"].includes(endpoint.status)
? "Reason"
: "Last reported error",
};
}
export function ChatEndpointDetail() {
const { userId, settled: identitySettled } = useAccountIdentity();
const { endpointId = "", tab: routeTab, reviewId } = useParams<{
endpointId: string;
tab?: string;
reviewId?: string;
}>();
const tab = reviewId ? "reviews" : (routeTab ?? "settings");
const activeTab = tabs.includes(tab as ChatTab) ? (tab as ChatTab) : null;
const navigate = useNavigate();
const location = useLocation();
const heading = useRef<HTMLHeadingElement>(null);
const completion = (location.state as GitHubConnectionCompleteLocationState | null)?.githubConnectionComplete;
const { setBreadcrumbs } = useBreadcrumbs();
const endpointQuery = useQuery({
queryKey: queryKeys.chatEndpoints.detail(endpointId),
queryFn: () => chatEndpointsApi.get(endpointId),
enabled: Boolean(endpointId && activeTab),
...liveChatQueryOptions,
refetchInterval:
activeTab === "activity" || activeTab === "conversations"
? liveChatQueryOptions.refetchInterval
: false,
});
const endpoint = endpointQuery.data;
const endpointView = useQueryView(endpointQuery);
const avatarAgent = useQuery({
queryKey: queryKeys.agents.detail(endpoint?.assignedAgentId ?? ""),
queryFn: () => agentsApi.get(endpoint!.assignedAgentId),
enabled: endpoint?.provider === "github",
});
const [copyStatus, setCopyStatus] = useState<string | null>(null);
const agentQuery = useQuery({
queryKey: queryKeys.agents.detail(endpoint?.assignedAgentId ?? ""),
queryFn: () => agentsApi.get(endpoint!.assignedAgentId, endpoint!.companyId),
enabled: Boolean(endpoint?.assignedAgentId),
});
useEffect(() => {
if (!endpoint || !activeTab) return;
setBreadcrumbs([
{ label: "Connectors", href: "/apps" },
{
label: `${endpoint.assignedAgentName} · ${providerNames[endpoint.provider]}`,
href: `/apps/chat/${endpoint.id}/settings`,
},
...(reviewId ? [{ label: "Reviews", href: `/apps/chat/${endpoint.id}/reviews` }, { label: "Review" }] : [{
label:
tabItems.find((item) => item.value === activeTab)?.label ??
"Settings",
}]),
]);
return () => setBreadcrumbs([]);
}, [activeTab, endpoint, reviewId, setBreadcrumbs]);
if (!activeTab)
return <Navigate replace to={`/apps/chat/${endpointId}/settings`} />;
if (endpointQuery.isLoading || endpointView.kind === "reconnecting")
return (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
Loading connection…
</div>
);
if (endpointView.kind === "error" || !endpoint)
return (
<QueryErrorState
size="page"
error={endpointQuery.error}
action="load the connection"
onRetry={endpointView.retry}
retrying={endpointView.isFetching}
/>
);
if (endpoint.provider === "agentmail" && activeTab === "settings")
return <div className="space-y-7"><EmailEndpointSettings key={endpoint.id} endpointId={endpoint.id} companyId={endpoint.companyId} assignedAgentName={endpoint.assignedAgentName} /><EndpointExecutionDefaults endpoint={endpoint} /></div>;
const setupIncomplete =
endpoint.setup?.step !== "complete" &&
!(endpoint.provider === "slack" && endpoint.setup?.step === "test") &&
["draft", "verifying", "attention", "revoked"].includes(endpoint.status);
const slackAppId = endpoint.setup?.slackRegistration?.appId;
const slackUrl = endpoint.provider === "slack"
? slackAppId ? `https://api.slack.com/apps/${encodeURIComponent(slackAppId)}/oauth` : "https://api.slack.com/apps"
: null;
return (
<div className="max-w-5xl space-y-6 pb-12">
<header className="flex flex-wrap items-start justify-between gap-4">
<div className="flex min-w-0 items-center gap-3">
<AgentAvatar agent={agentQuery.data ?? { id: endpoint.assignedAgentId, name: endpoint.assignedAgentName }} size={endpoint.provider === "github" ? 64 : 48} />
<div className="min-w-0">
<h1 ref={heading} tabIndex={-1} className={endpoint.provider === "speko" ? "flex items-center gap-3 text-xl font-bold" : "text-xl font-bold"}>
{endpoint.provider === "speko" && <AppLogo name="Speko" brandKey="speko" size={36} />}
{endpoint.provider === "github" ? (endpoint.botLabel ?? endpoint.assignedAgentName) : endpoint.assignedAgentName}{endpoint.provider === "speko" ? " in Speko" : ""}
</h1>
<p className="mt-1 flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
{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>
{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>
);
}
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"}{" "}
&lt;request&gt;
</code>
<p className="mt-2 text-muted-foreground">
Telegram&apos;s default privacy mode does not deliver ordinary
mentions to bots. Use this command to start or continue group
work, or reply directly to a message from the bot.
</p>
</div>
</div>
)}
<div 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="min-w-0 flex-1">
<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"
detail="In channels, only respond to messages that @mention this bot, including thread replies. Direct messages never require an @mention and 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>
<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="text-sm font-medium">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="break-all text-xs text-muted-foreground">
{confirmationUrl}
</p>
<Button
size="sm"
variant="outline"
onClick={() => {
void copyTextToClipboard(confirmationUrl).then(
() =>
pushToast({
title: "Confirmation link copied",
tone: "success",
}),
() =>
pushToast({
title: "Couldn't copy the link",
body: "Select and copy it manually.",
tone: "error",
}),
);
}}
>
<Copy />
Copy link
</Button>
</div>
)}
<div className="space-y-2">
{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="min-w-0">
<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>
<AlertDialogHeader>
<AlertDialogTitle>
{resolutionItem?.actionType === "slash_task_start"
? "Resolve unconfirmed task start"
: resolutionItem?.actionType === "provider_effect"
? "Resolve unconfirmed provider reply"
: "Resolve unconfirmed delivery"}
</AlertDialogTitle>
<AlertDialogDescription>
{resolutionItem?.actionType === "slash_task_start"
? "Paperclip lost confirmation after asking Slack to start the task. Check Slack first. Retrying can create a duplicate starter message and task."
: resolutionItem?.actionType === "provider_effect"
? "Paperclip lost confirmation after sending this provider reply. Check the provider first. Marking it delivered applies any pending Paperclip state change; retrying can create a duplicate message."
: resolutionItem
? activityResolutionDescription(resolutionItem)
: ""}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter className="sm:flex-wrap">
<AlertDialogCancel disabled={resolveActivity.isPending}>
Keep unresolved
</AlertDialogCancel>
{resolutionItem &&
activityResolutionActions(resolutionItem).includes("cancel") && (
<Button
variant="outline"
disabled={resolveActivity.isPending}
onClick={() =>
resolutionItem &&
resolveActivity.mutate({
item: resolutionItem,
action: "cancel",
})
}
>
{resolutionItem.actionType === "slash_task_start"
? "Cancel task start"
: resolutionItem.actionType === "provider_effect"
? "Cancel provider reply"
: resolutionItem.fileTransfer
? "Cancel file transfer"
: "Cancel publication"}
</Button>
)}
{resolutionItem &&
activityResolutionActions(resolutionItem).includes(
"retry_anyway",
) && (
<Button
variant="outline"
disabled={resolveActivity.isPending}
onClick={() =>
resolutionItem &&
resolveActivity.mutate({
item: resolutionItem,
action: "retry_anyway",
})
}
>
{resolutionItem.fileTransfer
? "Retry file notification"
: "Retry anyway"}
</Button>
)}
{resolutionItem &&
activityResolutionActions(resolutionItem).includes(
"mark_delivered",
) && (
<AlertDialogAction
disabled={resolveActivity.isPending}
onClick={(event) => {
event.preventDefault();
if (resolutionItem) {
resolveActivity.mutate({
item: resolutionItem,
action: "mark_delivered",
});
}
}}
>
Mark delivered
</AlertDialogAction>
)}
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<AlertDialog open={removeOpen} onOpenChange={setRemoveOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Remove this connection?</AlertDialogTitle>
<AlertDialogDescription>
{endpoint.assignedAgentName} will stop receiving new work from
{` ${providerNames[endpoint.provider]}`}. Existing Paperclip tasks
remain available.{" "}
{providerLifecycleGuidance[endpoint.provider].remove}
{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>
);
}