mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-15 20:53:23 +02:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Connections give agents access to external services. > - AgentMail needs both a saved key and an inbox assigned to the agent. > - Chat requests offered a setup link instead of an inline card and could treat a saved key as complete. > - Inbox setup also hid address conflicts behind a generic server error and a separate review step. > - This pull request makes AgentMail a default connection, adds the inline card, reduces setup to two steps, and shows conflicts beside the address. > - Shared native dropdown styles also give every caret a consistent inset. ## Linked Issues or Issue Description **What happened?** AgentMail requests in chat did not show a usable inline connection card. Manual setup required extra screens, ignored saved account keys, and could trap new-address setup in a locked inbox dropdown. Agent selectors omitted the avatar from the selected value. A taken address could produce an HTTP 403 from AgentMail and appear as an internal server error. Native dropdown arrows also touched the right edge of their fields. **Expected behavior** Make AgentMail available as a default connection. Ask for the API key inline, with a direct link to its provider page. Default human access to the company and agent access to the requesting agent. Resume the agent only after an assigned inbox is active. Manual setup should ask for an agent and email address, then finish. Address checks should run as the user types. Taken addresses should show clickable alternatives. A domain dropdown beside the name should prefer a verified custom domain. Setup should suggest authorized saved AgentMail keys and show agent avatars in the picker and selected value. **Steps to reproduce** 1. Ask an agent to connect AgentMail when it has no assigned inbox. 2. Check that an inline API-key card appears and links to the provider's API-key page. 3. Open AgentMail setup, choose an agent, and request an address that is already taken. 4. Correct the inline error, refresh, and finish setup with the same request ID. 5. Inspect native dropdown carets in light, dark, disabled, and right-to-left states. Uses the bounded provider-error parser merged in #14768. Related work: #13256 introduced AgentMail; #14725 expanded connection search. ## What Changed - Stop recurring email queries for tasks that have no email thread. Share the query between the thread provider and activity view. Keep email-task updates and invalidation-based discovery. - Make AgentMail available without the experimental chat setting. Keep the catalog, setup and management routes, agent Channels tab, task email feed, receiving worker, and agent tools available by default. Other experimental chat providers stay gated. - Make the email address and copy icon a single clickable action with the shared Copied! confirmation. Add View inbox linking directly to the matching AgentMail console inbox, with the address encoded as one URL path segment. - Reorganize inbox Settings around the copyable email address, usage instructions, and receiving status. Move reconnect credentials into a disclosure and separate the Disconnect action. Add production Settings stories for active, paused, unassigned-address, revoked, webhook, long-address, mobile, and reconnect states. Show repair controls when the inbox has an error. Keep usage instructions tied to an active inbox with an address. - Add AgentMail channel intents and an inline key field with the direct API-key URL. - Keep setup and retry state tied to the interaction. Require an active inbox for completion. Preserve company and agent access checks. - Reduce manual setup to agent selection and email selection. Put the domain dropdown beside the address and default to a verified custom domain. Preserve explicit choices across reloads. Keep receiving settings under Advanced options. - Check the initial address and edits after a 350 ms pause. Abort superseded requests and ignore stale responses. Show clickable suggestions and retain known creation conflicts across reloads. - Add a company-scoped, manager-only address check using the saved credential. Search the visible inbox list instead of fetching an uncreated inbox: live AgentMail retains negative lookups that can break subsequent access-key creation. Unlisted addresses remain unknown; creation is authoritative. - Suggest labeled saved AgentMail keys in both manual setup and the inline card. Filter by company, provider, active credential, and current-user grants on the server. Prefer an account key and preserve the selected key or an explicit new-key choice across refresh. Use verified scope metadata and bounded concurrent checks for legacy keys. Never return secret values. - Catch an inbox-only key before the email step. Allow its existing inbox only after an explicit choice. Recover old locked drafts at the key picker. Save the replacement key before retiring an empty draft, then use a new setup URL so refresh preserves the switched account; stop if cleanup fails. Preserve already allocated addresses and their original accounts. - Use the shared AgentSelect in email setup. Show the canonical agent avatar in each option and the selected value, including other consumers of the shared component. Add regression coverage for legacy and current Lucide agent-mention icon formats. - Start each catalog Add connection with a fresh setup identity. Honor Finish setup's exact draft/account/address instead of resuming an unrelated browser draft. Return Cancel and Done to Connectors and Email settings to the inbox. Group the task/thread explanation in a How it Works card. - Route AgentMail catalog removal through the email inbox control API, including unfinished drafts. Refresh both the catalog and inbox views. - Render each inbox management tab separately. Access uses the saved account grants and agent controls; Conversations and Activity use the shared persisted email feed. Activity lifecycle actions use the email API. Reconnect returns to inbox Settings. Conversation failures show a retry instead of a false empty state. Email delivery recovery stays in the task. - Map documented provider address conflicts to a field error. Preserve actionable messages for other failures. - Preserve non-secret draft fields across refresh, scoped to the requested agent. Never save API keys in browser storage. Resume partial inbox creation with the original agent, address, and request ID. - Show an already-created address with explicit retry and new-address recovery instead of locked inputs. Preserve the original inbox and resumable draft when choosing another address. Distinguish runtime-key 404 errors and log safe provider status/operation/code. - Apply final agent access once within email setup authorization for a new account whose original installs are unchanged. Preserve later permission edits and reused account installs. Support in-place retry of progress loading. - Let a failed inline setup change keys after retiring an empty draft. Persist its replacement setup identity without storing secrets. Recover a server-saved account when refresh interrupts the save response, while preserving intentional account changes. - Render the production setup in Storybook and add error, recovery, and mobile states. - Inset native select carets in shared CSS. Preserve custom icons, listboxes, keyboard behavior, and forced-color controls. - Add browser regression coverage and an AgentMail Product E2E case with persisted-state and rendered-card evidence. ## Verification - Full `pnpm -r typecheck`, `pnpm build`, `pnpm check:token-gates`, and `git diff --check` passed after the default-availability change. - All 485 focused tests passed. These cover setup, management, catalog and route gates, connection intents, email authorization, Cursor execution, and the OpenAPI contract. All 39 email integration tests run with the experimental chat setting off. - The shared polling change passed four behavioral tests, UI typecheck and build, and token gates. - `tests/e2e/agentmail.spec.ts` passed with the actual server setting off. This full-stack browser test uses simulated provider responses. It covers catalog entry, saved keys, editable address and domain controls, creation, conflicts, retry, all management tabs, clipboard feedback, the provider link, and task email rendering. - In the live local browser, Add connection reached the editable email step with the saved account key. The verified custom domain was selected by default. Both domain choices worked. The existing inbox Settings page remained available. Both active inboxes completed new mail checks with the setting off. No new provider inbox or email message was created for this pass. - Earlier live provider acceptance covered creation on a verified custom domain, Finish connecting on the reported draft, successful mail checks after refresh, and catalog removal of disposable draft and active connections. Clicking the email address copied the exact address and showed Copied!. View inbox opened the same inbox in AgentMail’s console. No email messages were sent. - Production setup and Settings Storybook builds and interactions passed. Settings states include active, paused, unassigned, revoked, webhook, long-address, mobile, and reconnect. Receiving and revoked-access stories had zero accessibility violations. - Full local `pnpm test:run` on an earlier revision completed with 14,709 passing, 87 skipped, and four transient failures. All four failed cases passed in focused reruns without product changes. That serial full local command was not repeated after each follow-up. The latest-head full CI suite is the final test gate. - CI found an obsolete browser assertion that hid every channel when the flag was off. Updated it to keep AgentMail and the Channels surface visible while preserving the GitHub chat route gates. All 11 provider browser tests passed locally after scoping the Channels selector to the agent sidebar. Two initial local attempts stopped at temporary Postgres initialization. The passing run used a separate disposable database on the existing local Postgres server; it was removed after the test. - Updated the remaining sidebar and aggregator discovery assertions for default AgentMail availability. Ordinary task fixtures now return no email thread. All 128 sidebar/task-page tests and all 42 aggregator tests passed locally. - Latest head `b42bb4cd5cc9f2d01a99ab8026832d5a956ea85f`: full CI passed, with 54 successful checks including Snyk and two intentional Storybook skips. The CI run is https://github.com/paperclipai/paperclip/actions/runs/37020833647. A fresh Greptile review scored 5/5 with no unresolved threads. Live model evaluations and inbound/outbound email delivery were not run. ## Risks - AgentMail no longer needs experimental opt-in. Setup still requires a human to connect an account and assign an inbox. Inline setup creates an inbox after a human submits a new or saved key. Company access, agent access, inbox assignment, and completion checks remain enforced. - AgentMail read APIs cannot prove global address availability. The visible-list check is bounded to 100 entries and cannot see inboxes outside the key’s scope. The UI reports this limitation, suggests alternatives without claiming they are free, and keeps final creation conflicts inline. Lookup outages show an error without preventing the authoritative creation attempt. - Native select CSS affects the whole app. Custom-icon selects and multi-row lists are excluded. Forced-color mode keeps the browser caret. - Saved-key discovery uses stored verified scope metadata and checks authorized legacy credentials concurrently within a shared three-second deadline. Provider outages mark legacy choices unavailable; users can still enter another key. Final use rechecks authorization and provider access. - No database migration or transport default change. Live connection remains the default. ## Model Used OpenAI Codex, GPT-6, with reasoning, tool use, and code execution. The exact served model ID and context-window size are not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass (focused suites; full-suite limitation documented 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 any risks above - [x] All Paperclip CI gates are green (latest head `b42bb4cd5cc9f2d01a99ab8026832d5a956ea85f`) - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups (latest head `b42bb4cd5cc9f2d01a99ab8026832d5a956ea85f`) - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
750 lines
40 KiB
TypeScript
750 lines
40 KiB
TypeScript
import { isUuidLike } from "@paperclipai/shared";
|
||
import { ApiError } from "@/api/client";
|
||
import { AgentMailCredentialField } from "@/features/connections/AgentMailCredentialField";
|
||
import { AgentMailApiKeyField } from "@/features/connections/AgentMailApiKeyField";
|
||
import { useEmailAddressCheck } from "@/features/connections/useEmailAddressCheck";
|
||
import { ChatSetupNavigation } from "@/components/chat/ChatSetupNavigation";
|
||
import { useEffect, useRef, useState } from "react";
|
||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||
import {
|
||
ArrowLeft,
|
||
ArrowRight,
|
||
Check,
|
||
Copy,
|
||
ExternalLink,
|
||
Mail,
|
||
} from "lucide-react";
|
||
import { useCompany } from "@/context/CompanyContext";
|
||
import { useNavigate, useSearchParams, Link } from "@/lib/router";
|
||
import { agentsApi } from "@/api/agents";
|
||
import { issuesApi } from "@/api/issues";
|
||
import { projectsApi } from "@/api/projects";
|
||
import { toolsApi } from "@/api/tools";
|
||
import { emailApi } from "@/api/email";
|
||
import { Button } from "@/components/ui/button";
|
||
import { Input } from "@/components/ui/input";
|
||
import { Label } from "@/components/ui/label";
|
||
import { Card, CardHeader, CardDescription } from "@/components/ui/card";
|
||
import { CopyText } from "@/components/CopyText";
|
||
import { StatusBadge } from "@/components/StatusBadge";
|
||
import { formatDateTime } from "@/lib/utils";
|
||
import { AgentSelect } from "@/components/AgentMultiSelect";
|
||
import { TrustPresetSection } from "@/components/TrustPresetSection";
|
||
import { EmailSafetyNotice } from "@/components/EmailSafetyNotice";
|
||
import {
|
||
Dialog,
|
||
DialogContent,
|
||
DialogHeader,
|
||
DialogTitle,
|
||
DialogDescription,
|
||
DialogFooter,
|
||
} from "@/components/ui/dialog";
|
||
import {
|
||
getTrustPreset,
|
||
getLowTrustBoundary,
|
||
lowTrustBoundaryHasScope,
|
||
} from "@/lib/trust-policy-ui";
|
||
import { queryKeys } from "@/lib/queryKeys";
|
||
import type {
|
||
AgentPermissions,
|
||
EmailEndpointSummary,
|
||
} from "@paperclipai/shared";
|
||
const selectClass =
|
||
"w-full rounded-md border border-input bg-background px-3 py-2 text-sm";
|
||
|
||
interface EmailSetupDraft {
|
||
connectionId: string; step: 0 | 1; agentId: string; requestId: string;
|
||
addressMode: "new" | "existing"; inboxId: string; username: string; domain: string;
|
||
mode: "websocket" | "webhook";
|
||
domainSelected: boolean;
|
||
takenAddresses: string[];
|
||
allowInboxKey: boolean;
|
||
selectedCredentialId: string | null;
|
||
}
|
||
function readEmailSetupDraft(key: string): Partial<EmailSetupDraft> {
|
||
try {
|
||
const value = JSON.parse(sessionStorage.getItem(key) ?? "{}");
|
||
if (!value || typeof value !== "object") return {};
|
||
const draft: Partial<EmailSetupDraft> = {};
|
||
for (const field of ["connectionId", "agentId", "inboxId", "username", "domain"] as const) {
|
||
if (typeof value[field] === "string") draft[field] = value[field];
|
||
}
|
||
if (value.step === 0 || value.step === 1) draft.step = value.step;
|
||
if (typeof value.requestId === "string" && isUuidLike(value.requestId)) draft.requestId = value.requestId;
|
||
if (value.addressMode === "new" || value.addressMode === "existing") draft.addressMode = value.addressMode;
|
||
if (value.mode === "websocket" || value.mode === "webhook") draft.mode = value.mode;
|
||
if (value.selectedCredentialId === null || typeof value.selectedCredentialId === "string") draft.selectedCredentialId = value.selectedCredentialId;
|
||
if (typeof value.allowInboxKey === "boolean") draft.allowInboxKey = value.allowInboxKey;
|
||
if (typeof value.domainSelected === "boolean") draft.domainSelected = value.domainSelected;
|
||
if (Array.isArray(value.takenAddresses)) draft.takenAddresses = value.takenAddresses
|
||
.filter((address: unknown): address is string => typeof address === "string" && address.length <= 320).slice(-20);
|
||
return draft;
|
||
} catch { return {}; }
|
||
}
|
||
|
||
export function EmailEndpointSetup() {
|
||
const { selectedCompanyId } = useCompany();
|
||
const [params] = useSearchParams();
|
||
if (!selectedCompanyId) return <p role="status" className="p-6 text-sm text-muted-foreground">Loading email setup…</p>;
|
||
return <EmailEndpointSetupForm key={`${selectedCompanyId}:${params.get("resume") ?? params.get("setupId") ?? params.get("connectionId") ?? "new"}:${params.get("agentId") ?? "choose"}`} companyId={selectedCompanyId} />;
|
||
}
|
||
|
||
function EmailEndpointSetupForm({ companyId }: { companyId: string }) {
|
||
const [params] = useSearchParams();
|
||
const navigate = useNavigate();
|
||
const cache = useQueryClient();
|
||
const resumeId = params.get("resume");
|
||
const setupId = params.get("setupId");
|
||
const draftKey = `paperclip.agentmail-setup:${companyId}:${resumeId ?? setupId ?? params.get("connectionId") ?? "new"}:${params.get("agentId") ?? "choose"}`;
|
||
const [draft] = useState(() => {
|
||
const saved = readEmailSetupDraft(draftKey);
|
||
// A Finish setup link always names its original inbox, including when an
|
||
// older client accidentally stored a replacement under that resume key.
|
||
return resumeId && saved.requestId && saved.requestId !== resumeId ? {} : saved;
|
||
});
|
||
const [connectionId, setConnectionId] = useState(draft.connectionId ?? params.get("connectionId") ?? "");
|
||
const [step, setStep] = useState<0 | 1 | 2>(draft.step ?? (resumeId ? 1 : 0));
|
||
const [agentId, setAgentId] = useState(draft.agentId ?? params.get("agentId") ?? "");
|
||
const [apiKey, setApiKey] = useState("");
|
||
const [selectedCredentialId, setSelectedCredentialId] = useState<string | null>(draft.selectedCredentialId !== undefined ? draft.selectedCredentialId : connectionId || null);
|
||
const [restrictedInbox, setRestrictedInbox] = useState("");
|
||
const [allowInboxKey, setAllowInboxKey] = useState(draft.allowInboxKey ?? false);
|
||
const [requestId] = useState(() => draft.requestId ?? resumeId ?? (setupId && isUuidLike(setupId) ? setupId : crypto.randomUUID()));
|
||
const [addressMode, setAddressMode] = useState<"new" | "existing">(draft.addressMode ?? "new");
|
||
const [inboxId, setInboxId] = useState(draft.inboxId ?? "");
|
||
const [username, setUsername] = useState(draft.username ?? "");
|
||
const [domain, setDomain] = useState(draft.domain ?? "agentmail.to");
|
||
const [domainSelected, setDomainSelected] = useState(draft.domainSelected ?? (!!draft.domain && draft.domain !== "agentmail.to"));
|
||
const [takenAddresses, setTakenAddresses] = useState<string[]>(draft.takenAddresses ?? []);
|
||
const [mode, setMode] = useState<"websocket" | "webhook">(draft.mode ?? "websocket");
|
||
const [trustOpen, setTrustOpen] = useState(false);
|
||
const [permissions, setPermissions] = useState<Partial<AgentPermissions>>({});
|
||
const suggestedUsername = useRef(false);
|
||
useEffect(() => {
|
||
if (!companyId) return;
|
||
// Save progress, never the API key. The same request ID resumes partial setup.
|
||
try {
|
||
if (step === 2) sessionStorage.removeItem(draftKey);
|
||
else sessionStorage.setItem(draftKey, JSON.stringify({ connectionId, step, agentId,
|
||
requestId, addressMode, inboxId, username, domain, domainSelected, takenAddresses, mode, allowInboxKey, selectedCredentialId }));
|
||
} catch { /* Setup remains usable when browser storage is unavailable. */ }
|
||
}, [companyId, draftKey, connectionId, step, agentId, requestId, addressMode, inboxId, username, domain, domainSelected, takenAddresses, mode, allowInboxKey, selectedCredentialId]);
|
||
const agents = useQuery({ queryKey: queryKeys.agents.list(companyId),
|
||
queryFn: () => agentsApi.list(companyId), enabled: !!companyId });
|
||
const projects = useQuery({ queryKey: queryKeys.projects.list(companyId),
|
||
queryFn: () => projectsApi.list(companyId), enabled: !!companyId && trustOpen });
|
||
const boundaryIssues = useQuery({ queryKey: ["email-boundary-issues", companyId],
|
||
queryFn: () => issuesApi.list(companyId), enabled: !!companyId && trustOpen });
|
||
const chosen = agents.data?.find(a => a.id === agentId);
|
||
const lowTrust = getTrustPreset(chosen?.permissions) === "low_trust_review";
|
||
const scoped = lowTrustBoundaryHasScope(getLowTrustBoundary(chosen?.permissions));
|
||
const inspected = useQuery({ queryKey: ["email-credential-inspect", companyId, connectionId],
|
||
queryFn: () => emailApi.inspectSaved(companyId, connectionId),
|
||
enabled: !!companyId && !!connectionId, retry: false });
|
||
const inboxes = useQuery({ queryKey: ["email-inboxes", companyId],
|
||
queryFn: () => emailApi.list(companyId), enabled: !!companyId });
|
||
// A provider failure can leave an inbox allocated under this request. Resume
|
||
// that exact endpoint; its agent and address are already fixed server-side.
|
||
const pendingEndpoint = inboxes.data?.find(i => i.id === requestId && i.status !== "archived");
|
||
const pendingAddress = pendingEndpoint?.address;
|
||
const resumeAccount = useQuery({
|
||
queryKey: ["email-resume-account", companyId, pendingEndpoint?.connectionId],
|
||
queryFn: () => toolsApi.getConnection(pendingEndpoint!.connectionId),
|
||
enabled: !!resumeId && requestId === resumeId && !!pendingEndpoint && !connectionId,
|
||
retry: false,
|
||
});
|
||
useEffect(() => {
|
||
if (!resumeId || !pendingEndpoint || connectionId || !resumeAccount.isSuccess) return;
|
||
const savedAccount = resumeAccount.data?.config?.credentialConnectionId;
|
||
if (typeof savedAccount === "string") setConnectionId(savedAccount);
|
||
else setStep(0);
|
||
setMode(pendingEndpoint.receiveMode);
|
||
}, [resumeId, pendingEndpoint, connectionId, resumeAccount.isSuccess, resumeAccount.data]);
|
||
useEffect(() => {
|
||
if (pendingEndpoint) setAgentId(pendingEndpoint.assignedAgentId);
|
||
}, [pendingEndpoint]);
|
||
const scopedKey = inspected.data?.scope.scope_type === "inbox";
|
||
const customDomains = [...new Set(inspected.data?.domains
|
||
.filter(d => d.status === "VERIFIED" && d.domain.toLowerCase() !== "agentmail.to")
|
||
.map(d => d.domain.toLowerCase()) ?? [])];
|
||
const defaultDomain = customDomains[0] ?? "agentmail.to";
|
||
useEffect(() => {
|
||
if (inspected.isSuccess && !domainSelected && !pendingAddress) setDomain(defaultDomain);
|
||
}, [inspected.isSuccess, domainSelected, pendingAddress, defaultDomain]);
|
||
useEffect(() => {
|
||
if (!scopedKey || !inboxes.isSuccess) return;
|
||
if (pendingAddress || allowInboxKey) {
|
||
setAddressMode("existing");
|
||
setInboxId(inspected.data?.inboxes[0]?.inbox_id ?? "");
|
||
} else if (step === 1) {
|
||
// Old drafts must recover at the key choice, not return to a locked form.
|
||
setRestrictedInbox(inspected.data?.inboxes[0]?.inbox_id ?? "this inbox");
|
||
setSelectedCredentialId(null);
|
||
setStep(0);
|
||
}
|
||
}, [scopedKey, inspected.data, inboxes.isSuccess, pendingAddress, allowInboxKey, step]);
|
||
useEffect(() => {
|
||
if (chosen && !suggestedUsername.current) {
|
||
suggestedUsername.current = true;
|
||
if (!username) setUsername(chosen.name.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").slice(0, 64));
|
||
}
|
||
}, [chosen, username]);
|
||
const connect = useMutation({
|
||
mutationFn: async () => {
|
||
if (pendingAddress) return true;
|
||
const details = selectedCredentialId
|
||
? await emailApi.inspectSaved(companyId, selectedCredentialId)
|
||
: await emailApi.inspect(companyId, apiKey.trim());
|
||
if (details.scope.scope_type === "inbox" && !allowInboxKey) {
|
||
setRestrictedInbox(details.inboxes[0]?.inbox_id ?? "this inbox");
|
||
return false;
|
||
}
|
||
const changingAccount = !!connectionId && selectedCredentialId !== connectionId;
|
||
const nextRequestId = changingAccount ? crypto.randomUUID() : requestId;
|
||
let id = selectedCredentialId;
|
||
if (!id) {
|
||
const result = await emailApi.connect(companyId, {
|
||
apiKey: apiKey.trim(), grantKind: "organization", allAgents: false,
|
||
agentIds: [agentId], idempotencyKey: nextRequestId,
|
||
});
|
||
id = result.id;
|
||
}
|
||
cache.setQueryData(["email-credential-inspect", companyId, id], details);
|
||
setSelectedCredentialId(id);
|
||
setApiKey("");
|
||
void cache.invalidateQueries({ queryKey: ["email-credentials", companyId] });
|
||
void cache.invalidateQueries({ queryKey: queryKeys.tools.connections(companyId) });
|
||
if (changingAccount) {
|
||
// Save the replacement credential before retiring the original draft.
|
||
// A failed save/cleanup leaves the original URL recoverable; a completed
|
||
// switch gets its own URL so refreshing cannot revive an archived draft.
|
||
if (pendingEndpoint) {
|
||
await emailApi.control(pendingEndpoint.id, "remove");
|
||
await cache.invalidateQueries({ queryKey: ["email-inboxes", companyId] });
|
||
}
|
||
openDraft({
|
||
connectionId: id, selectedCredentialId: id, agentId, step: 1,
|
||
requestId: nextRequestId, addressMode: details.scope.scope_type === "inbox" ? "existing" : "new",
|
||
inboxId: details.scope.scope_type === "inbox" ? details.inboxes[0]?.inbox_id ?? "" : "",
|
||
username, domain: "agentmail.to", domainSelected: false, takenAddresses: [], mode, allowInboxKey,
|
||
});
|
||
return false;
|
||
}
|
||
setConnectionId(id);
|
||
setRestrictedInbox("");
|
||
setAddressMode(details.scope.scope_type === "inbox" ? "existing" : "new");
|
||
if (details.scope.scope_type === "inbox") setInboxId(details.inboxes[0]?.inbox_id ?? "");
|
||
return true;
|
||
},
|
||
onSuccess: ready => { if (ready) setStep(1); },
|
||
});
|
||
function selectCredential(id: string) {
|
||
setSelectedCredentialId(id);
|
||
setApiKey("");
|
||
setRestrictedInbox("");
|
||
setAllowInboxKey(false);
|
||
setDomainSelected(false);
|
||
setTakenAddresses([]);
|
||
connect.reset();
|
||
}
|
||
const agentDetail = useQuery({ queryKey: queryKeys.agents.detail(agentId),
|
||
queryFn: () => agentsApi.get(agentId), enabled: !!agentId && trustOpen });
|
||
const trust = useMutation({
|
||
mutationFn: () => agentsApi.updatePermissions(agentId, {
|
||
...permissions,
|
||
canCreateAgents: permissions.canCreateAgents ?? false,
|
||
canCreateSkills: permissions.canCreateSkills ?? true,
|
||
canAssignTasks: agentDetail.data?.access?.canAssignTasks ?? false,
|
||
}, companyId),
|
||
onSuccess: () => {
|
||
setTrustOpen(false);
|
||
void cache.invalidateQueries({ queryKey: queryKeys.agents.list(companyId) });
|
||
},
|
||
});
|
||
const setup = useMutation({
|
||
mutationFn: () => emailApi.setup(companyId, {
|
||
assignedAgentId: agentId, credentialConnectionId: connectionId,
|
||
...(pendingAddress ? { inboxId: pendingAddress } : addressMode === "existing" ? { inboxId } : { username, domain }),
|
||
receiveMode: mode, idempotencyKey: requestId,
|
||
}),
|
||
onError: async (error) => {
|
||
if (error instanceof ApiError && (error.body as { code?: string } | null)?.code === "agentmail_address_taken") {
|
||
setTakenAddresses(previous => [...new Set([...previous, `${username}@${domain}`.toLowerCase()])].slice(-20));
|
||
}
|
||
await cache.invalidateQueries({ queryKey: ["email-inboxes", companyId] });
|
||
},
|
||
onSuccess: () => {
|
||
void cache.invalidateQueries({ queryKey: ["email-inboxes", companyId] });
|
||
void cache.invalidateQueries({ queryKey: queryKeys.chatEndpoints.list(companyId) });
|
||
void cache.invalidateQueries({ queryKey: queryKeys.tools.connections(companyId) });
|
||
void cache.invalidateQueries({ queryKey: queryKeys.tools.connectionInstalls(connectionId) });
|
||
setStep(2);
|
||
},
|
||
});
|
||
const address = pendingAddress ?? (addressMode === "existing" ? inboxId : `${username}@${domain}`);
|
||
const knownAddresses = new Set([...takenAddresses, ...(inspected.data?.inboxes.map(i => i.inbox_id.toLowerCase()) ?? [])]);
|
||
const checkingNewAddress = step === 1 && addressMode === "new" && !pendingAddress && !scopedKey;
|
||
const knownAddress = checkingNewAddress && knownAddresses.has(address.toLowerCase());
|
||
const validUsername = /^[a-z0-9][a-z0-9._-]*$/.test(username) && username.length <= 64;
|
||
const addressCheck = useEmailAddressCheck(companyId, connectionId, username, domain,
|
||
checkingNewAddress && validUsername && !!inspected.data && !knownAddress);
|
||
const addressTaken = knownAddress || addressCheck.result?.status === "taken";
|
||
const suggestions = checkingNewAddress && validUsername && (addressTaken || addressCheck.result?.status === "unknown")
|
||
? ["-agent", "-team", `-${requestId.slice(0, 6)}`]
|
||
.map(suffix => `${username.slice(0, 64 - suffix.length)}${suffix}`)
|
||
.filter(name => !knownAddresses.has(`${name}@${domain}`)) : [];
|
||
const assignedInbox = addressMode === "existing" && inboxes.data?.some(i => i.id !== requestId && i.address === address && i.status !== "archived");
|
||
const addressError = addressTaken ? "This email address is already in use. Choose a different address."
|
||
: assignedInbox ? "This inbox is already assigned to an agent." : null;
|
||
const error = connect.error ?? (!addressTaken ? setup.error : null) ?? resumeAccount.error ?? inspected.error ?? agents.error;
|
||
const busy = connect.isPending || setup.isPending;
|
||
const identityReady = inboxes.isSuccess && (!resumeId || requestId !== resumeId || !!pendingEndpoint) && (!pendingEndpoint || pendingEndpoint.assignedAgentId === agentId);
|
||
const canContinue = identityReady && !!chosen && !busy && !(lowTrust && !scoped) && (!!pendingAddress || !!selectedCredentialId || !!apiKey.trim());
|
||
const canCreate = identityReady && !!chosen && !busy && !!inspected.data && !(lowTrust && !scoped) && !addressError && !addressCheck.checking
|
||
&& (!!pendingAddress || (addressMode === "existing" ? !!inboxId : validUsername));
|
||
const openTrust = () => { if (chosen) { setPermissions(chosen.permissions); setTrustOpen(true); } };
|
||
const leave = () => navigate(`/apps/chat/${setup.data?.id ?? pendingEndpoint?.id}/settings`);
|
||
const cancel = () => { try { sessionStorage.removeItem(draftKey); } catch {} navigate("/apps"); };
|
||
function openDraft(nextDraft: EmailSetupDraft & { requestId: string; connectionId: string }) {
|
||
try {
|
||
sessionStorage.setItem(`paperclip.agentmail-setup:${companyId}:${nextDraft.requestId}:${agentId}`, JSON.stringify(nextDraft));
|
||
} catch { /* The new link still restores the agent and saved account. */ }
|
||
navigate(`/apps/chat/connect?${new URLSearchParams({ provider: "agentmail", purpose: "chat", setupId: nextDraft.requestId, agentId, connectionId: nextDraft.connectionId })}`);
|
||
}
|
||
const chooseAnotherAddress = () => {
|
||
// Preserve the allocated inbox and its resumable setup. A different address
|
||
// must use a new provider client_id, never silently rename a retry.
|
||
const nextRequestId = crypto.randomUUID();
|
||
openDraft({
|
||
connectionId, selectedCredentialId: connectionId, agentId, step: 1,
|
||
requestId: nextRequestId, addressMode: "new", username: "", inboxId: "",
|
||
domain: pendingAddress?.slice(pendingAddress.lastIndexOf("@") + 1) ?? domain,
|
||
domainSelected: true, takenAddresses, mode, allowInboxKey: false,
|
||
});
|
||
};
|
||
return <div className="mx-auto max-w-xl space-y-6 p-6">
|
||
<header className="space-y-2">
|
||
<h1 className="text-xl font-bold">{step === 2 ? "Your agent’s email is ready" : "Give an agent an email address"}</h1>
|
||
</header>
|
||
{step < 2 && inboxes.isError && <div role="alert" className="space-y-2 text-sm">
|
||
<p className="text-destructive">Could not load email setup progress. {inboxes.error.message}</p>
|
||
<Button type="button" variant="outline" size="sm" disabled={busy || inboxes.isFetching} onClick={() => { void inboxes.refetch(); }}>
|
||
{inboxes.isFetching ? "Loading…" : "Retry loading inboxes"}
|
||
</Button>
|
||
</div>}
|
||
{step < 2 && resumeId === requestId && inboxes.isSuccess && !pendingEndpoint && <p role="alert" className="text-sm text-destructive">This email setup could not be found. Return to Connectors and start a new connection.</p>}
|
||
{step < 2 && <ChatSetupNavigation labels={["Agent", "Email address"]} step={step}
|
||
availableStep={step} disabled={busy} onSelect={index => { setup.reset(); setStep(index as 0 | 1); }} />}
|
||
{step === 0 && <form className="space-y-6" onSubmit={event => { event.preventDefault(); if (canContinue) connect.mutate(); }}>
|
||
<div className="space-y-2">
|
||
<Label htmlFor="email-agent">Agent</Label>
|
||
<AgentSelect id="email-agent" value={agentId} disabled={busy || agents.isPending || !inboxes.isSuccess || !!pendingEndpoint}
|
||
placeholder="Choose an agent" emptyMessage="No agents found." triggerClassName="h-10"
|
||
agents={(agents.data ?? []).filter(a => !["terminated", "pending_approval"].includes(a.status))}
|
||
onChange={id => { setAgentId(id); setUsername((agents.data?.find(a => a.id === id)?.name ?? "").toLowerCase().replace(/[^a-z0-9._-]+/g, "-").slice(0, 64)); }} />
|
||
</div>
|
||
{!pendingAddress && <AgentMailCredentialField companyId={companyId} connectionId={selectedCredentialId}
|
||
onConnectionChange={selectCredential} value={apiKey} onChange={value => { setApiKey(value); connect.reset(); }} disabled={busy} />}
|
||
{restrictedInbox && <div className="space-y-2 text-sm">
|
||
<p className="text-muted-foreground">That key only connects {restrictedInbox}. Choose a saved account key or enter one to create a new address.</p>
|
||
<Button type="button" variant="link" size="sm" className="h-auto p-0" disabled={busy || !(selectedCredentialId || apiKey.trim())}
|
||
onClick={() => { setAllowInboxKey(true); setRestrictedInbox(""); connect.reset(); }}>Use the existing inbox instead</Button>
|
||
</div>}
|
||
{lowTrust && !scoped && <div role="alert" className="space-y-2 text-sm">
|
||
<p>This agent needs a work boundary before it can receive email.</p>
|
||
<Button type="button" variant="outline" size="sm" onClick={openTrust}>Configure work boundary</Button>
|
||
</div>}
|
||
{error && <p role="alert" className="text-sm text-destructive">{error.message}</p>}
|
||
<div className="flex items-center justify-between gap-3 border-t border-border pt-5">
|
||
<Button type="button" variant="ghost" disabled={busy} onClick={cancel}>Cancel</Button>
|
||
<Button disabled={!canContinue}>{connect.isPending ? "Connecting…" : "Continue"}<ArrowRight className="size-4" /></Button>
|
||
</div>
|
||
</form>}
|
||
{step === 1 && <form className="space-y-6" onSubmit={event => { event.preventDefault(); if (canCreate) setup.mutate(); }}>
|
||
<div className="space-y-2">
|
||
<Label htmlFor={addressMode === "new" ? "email-name" : "email-existing"}>{chosen?.name}’s email address</Label>
|
||
{pendingAddress ? <>
|
||
<p className="text-sm font-medium">{pendingAddress}</p>
|
||
<p className="text-sm text-muted-foreground">This address was created in AgentMail. Finish connecting it to {chosen?.name}{scopedKey ? "." : ", or choose a different address. The original inbox will stay in AgentMail."}</p>
|
||
{!scopedKey && <Button type="button" variant="link" size="sm" className="h-auto p-0" disabled={busy} onClick={chooseAnotherAddress}>Choose a different address</Button>}
|
||
</> : addressMode === "new" ? <>
|
||
<div className="flex items-center gap-2">
|
||
<Input id="email-name" className="min-w-0" value={username} maxLength={64} autoComplete="off" spellCheck={false} disabled={busy}
|
||
aria-invalid={!!addressError} aria-describedby={addressError ? "email-address-error" : "email-address-status"}
|
||
onChange={event => { setUsername(event.target.value.toLowerCase()); setup.reset(); }} />
|
||
<select id="email-domain" aria-label="Email domain" className={`${selectClass} max-w-1/2 shrink-0`} value={domain}
|
||
disabled={busy || !inspected.data} onChange={event => { setDomainSelected(true); setDomain(event.target.value); setup.reset(); }}>
|
||
{[...new Set([...customDomains, "agentmail.to", domain])]
|
||
.map(value => <option key={value} value={value}>@{value}</option>)}
|
||
</select>
|
||
</div>
|
||
</> : <select id="email-existing" className={selectClass} value={pendingAddress ?? inboxId} disabled={busy || scopedKey || !!pendingAddress}
|
||
aria-invalid={!!addressError} aria-describedby={addressError ? "email-address-error" : undefined}
|
||
onChange={event => { setInboxId(event.target.value); setup.reset(); }}>
|
||
<option value="">Choose an inbox</option>
|
||
{inspected.data?.inboxes.map(i => {
|
||
const assigned = inboxes.data?.some(e => e.id !== requestId && e.address === i.inbox_id && e.status !== "archived");
|
||
return <option key={i.inbox_id} value={i.inbox_id} disabled={assigned}>{i.inbox_id}{assigned ? " — already assigned" : ""}</option>;
|
||
})}
|
||
</select>}
|
||
{scopedKey && !pendingAddress && <Button type="button" variant="link" size="sm" className="h-auto p-0" disabled={busy}
|
||
onClick={() => { setAllowInboxKey(false); setStep(0); }}>Choose a key for a new address</Button>}
|
||
{addressError && <p id="email-address-error" role="alert" className="text-sm text-destructive">{addressError}</p>}
|
||
{checkingNewAddress && !addressError && <p id="email-address-status" role="status" className="text-sm text-muted-foreground">
|
||
{addressCheck.checking ? "Checking address…" : addressCheck.error ? `Could not check this address. ${addressCheck.error}`
|
||
: addressCheck.result?.status === "unknown" ? "AgentMail confirms availability when you create the address." : null}
|
||
</p>}
|
||
{suggestions.length > 0 && <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-sm" aria-label="Suggested email addresses">
|
||
<span className="text-muted-foreground">Try:</span>
|
||
{suggestions.map(name => <Button key={name} type="button" variant="link" size="sm" className="h-auto p-0" disabled={busy}
|
||
onClick={() => { setUsername(name); setup.reset(); }}>{name}@{domain}</Button>)}
|
||
</div>}
|
||
{!scopedKey && !pendingAddress && <Button type="button" variant="link" size="sm" className="h-auto p-0" disabled={busy}
|
||
onClick={() => { setAddressMode(addressMode === "new" ? "existing" : "new"); setup.reset(); }}>
|
||
{addressMode === "new" ? "Use an existing inbox" : "Create a new address"}
|
||
</Button>}
|
||
</div>
|
||
<Card className="py-4">
|
||
<CardHeader className="px-4">
|
||
<h2 className="text-sm font-medium">How it Works</h2>
|
||
<CardDescription>Incoming email creates tasks for {chosen?.name}. Replies stay in the same task.</CardDescription>
|
||
</CardHeader>
|
||
</Card>
|
||
<details className="space-y-4">
|
||
<summary className="cursor-pointer text-sm text-muted-foreground">Advanced options</summary>
|
||
<div className="space-y-4">
|
||
{addressMode === "new" && <div className="space-y-2">
|
||
<a className="text-sm underline" href="https://docs.agentmail.to/custom-domains" target="_blank" rel="noreferrer">Set up a custom domain ↗</a>
|
||
</div>}
|
||
<div className="space-y-2">
|
||
<Label htmlFor="email-mode">Receiving</Label>
|
||
<select id="email-mode" value={mode} disabled={busy} className={selectClass} onChange={event => setMode(event.target.value as typeof mode)}>
|
||
<option value="websocket">Live connection</option><option value="webhook">Webhook</option>
|
||
</select>
|
||
</div>
|
||
<EmailSafetyNotice />
|
||
<div className="space-y-2 text-sm">
|
||
<p>{lowTrust && scoped ? "Low-trust review configured" : "Manage which tasks and tools this agent can access."}</p>
|
||
<Button type="button" variant="outline" size="sm" onClick={openTrust}>Review trust settings</Button>
|
||
</div>
|
||
</div>
|
||
</details>
|
||
{error && <p role="alert" className="text-sm text-destructive">{error.message}</p>}
|
||
{inspected.isPending && <p role="status" className="text-sm text-muted-foreground">Loading email options…</p>}
|
||
<div className="flex items-center justify-between gap-3 border-t border-border pt-5">
|
||
<Button type="button" variant="ghost" disabled={busy} onClick={() => { setup.reset(); setStep(0); }}><ArrowLeft className="size-4" />Back</Button>
|
||
<Button disabled={!canCreate}>
|
||
{setup.isPending ? "Connecting…" : pendingAddress ? "Finish connecting" : addressMode === "new" ? "Create email address" : "Connect email address"}<ArrowRight className="size-4" />
|
||
</Button>
|
||
</div>
|
||
</form>}
|
||
{step === 2 && <div className="space-y-6">
|
||
<div className="space-y-2"><p className="flex items-center gap-2 font-medium"><Check className="size-4" />{setup.data?.address}</p>
|
||
<p className="text-sm text-muted-foreground">{chosen?.name} can now receive email at this address.</p></div>
|
||
<div className="flex items-center justify-between gap-3 border-t border-border pt-5">
|
||
<Button variant="ghost" onClick={leave}>Email settings</Button><Button onClick={() => navigate("/apps")}>Done</Button>
|
||
</div>
|
||
</div>}
|
||
<Dialog open={trustOpen} onOpenChange={setTrustOpen}>
|
||
<DialogContent className="max-h-screen overflow-y-auto sm:max-w-2xl">
|
||
<DialogHeader>
|
||
<DialogTitle>Trust settings · {chosen?.name}</DialogTitle>
|
||
<DialogDescription>
|
||
Changes apply to all of this agent’s work. Use a dedicated email
|
||
agent if its other tasks need broader access.
|
||
</DialogDescription>
|
||
</DialogHeader>
|
||
<TrustPresetSection
|
||
permissions={permissions}
|
||
onChange={setPermissions}
|
||
companyId={companyId}
|
||
projectCandidates={(projects.data ?? []).map((p) => ({
|
||
id: p.id,
|
||
label: p.name,
|
||
}))}
|
||
issueCandidates={(boundaryIssues.data ?? []).map((issue) => ({
|
||
id: issue.id,
|
||
label: `${issue.identifier} · ${issue.title}`,
|
||
}))}
|
||
allowSingleIssue={false}
|
||
candidatesLoading={projects.isPending || boundaryIssues.isPending}
|
||
/>
|
||
<p className="text-xs text-muted-foreground">
|
||
Low trust limits Paperclip access; it does not sandbox the runtime.
|
||
Review filesystem, tool, and secret access separately.
|
||
</p>
|
||
{(trust.error || projects.error || boundaryIssues.error) && (
|
||
<p role="alert" className="text-sm text-destructive">
|
||
{(trust.error ?? projects.error ?? boundaryIssues.error)?.message}
|
||
</p>
|
||
)}
|
||
<DialogFooter>
|
||
<Button variant="ghost" onClick={() => setTrustOpen(false)}>
|
||
Cancel
|
||
</Button>
|
||
<Button
|
||
disabled={
|
||
trust.isPending ||
|
||
agentDetail.isPending ||
|
||
!!agentDetail.error ||
|
||
(getTrustPreset(permissions) === "low_trust_review" &&
|
||
!lowTrustBoundaryHasScope(getLowTrustBoundary(permissions)))
|
||
}
|
||
onClick={() => trust.mutate()}
|
||
>
|
||
Save trust settings
|
||
</Button>
|
||
</DialogFooter>
|
||
</DialogContent>
|
||
</Dialog>
|
||
</div>;
|
||
}
|
||
|
||
export function EmailConnectionInboxes({
|
||
companyId,
|
||
connectionId,
|
||
canConfigure,
|
||
}: {
|
||
companyId: string;
|
||
connectionId: string;
|
||
canConfigure: boolean;
|
||
}) {
|
||
const query = useQuery({
|
||
queryKey: ["email-inboxes", companyId],
|
||
queryFn: () => emailApi.list(companyId),
|
||
refetchInterval: 10_000,
|
||
});
|
||
const connections = useQuery({
|
||
queryKey: queryKeys.tools.connections(companyId),
|
||
queryFn: () => toolsApi.listConnections(companyId),
|
||
});
|
||
const children = new Set(
|
||
connections.data?.connections
|
||
.filter((c) => c.config?.credentialConnectionId === connectionId)
|
||
.map((c) => c.id),
|
||
);
|
||
const inboxes =
|
||
query.data?.filter(
|
||
(i) => i.connectionId === connectionId || children.has(i.connectionId),
|
||
) ?? [];
|
||
return (
|
||
<section className="space-y-4">
|
||
<div className="flex flex-wrap items-center justify-between gap-4 rounded-xl border border-border p-6">
|
||
<div className="space-y-1">
|
||
<h2 className="text-lg font-semibold">
|
||
Give an agent an email address
|
||
</h2>
|
||
<p className="text-sm text-muted-foreground">
|
||
Each email conversation becomes a task.
|
||
</p>
|
||
</div>
|
||
{canConfigure && (
|
||
<Button asChild size="lg">
|
||
<Link
|
||
to={`/apps/chat/connect?provider=agentmail&connectionId=${connectionId}`}
|
||
>
|
||
Give an agent an email address
|
||
</Link>
|
||
</Button>
|
||
)}
|
||
</div>
|
||
{inboxes.map((i) => (
|
||
<div
|
||
key={i.id}
|
||
className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border p-4"
|
||
>
|
||
<Link
|
||
className="text-sm underline"
|
||
to={`/apps/chat/${i.id}/settings`}
|
||
>
|
||
{i.address}
|
||
</Link>
|
||
<span className="text-xs text-muted-foreground">
|
||
{i.lastError ??
|
||
(i.status === "active" ? "Receiving email" : i.status)}
|
||
</span>
|
||
</div>
|
||
))}
|
||
{!!inboxes.length && <EmailSafetyNotice />}
|
||
{query.error && (
|
||
<p role="alert" className="text-sm text-destructive">
|
||
{query.error.message}
|
||
</p>
|
||
)}
|
||
</section>
|
||
);
|
||
}
|
||
export function EmailEndpointSettings({
|
||
endpointId,
|
||
companyId,
|
||
assignedAgentName,
|
||
}: {
|
||
endpointId: string;
|
||
companyId: string;
|
||
assignedAgentName: string;
|
||
}) {
|
||
const cache = useQueryClient();
|
||
const query = useQuery({
|
||
queryKey: ["email-inboxes", companyId],
|
||
queryFn: () => emailApi.list(companyId),
|
||
refetchInterval: 10_000,
|
||
});
|
||
const inbox = query.data?.find(
|
||
(row: EmailEndpointSummary) => row.id === endpointId,
|
||
);
|
||
const [removed, setRemoved] = useState(false);
|
||
const [replacementKey, setReplacementKey] = useState("");
|
||
const [reconnectOpen, setReconnectOpen] = useState(false);
|
||
useEffect(() => {
|
||
if (inbox?.lastError) setReconnectOpen(true);
|
||
}, [inbox?.lastError]);
|
||
const [receiveMode, setReceiveMode] = useState<"websocket" | "webhook" | "">(
|
||
"",
|
||
);
|
||
const reconnect = useMutation({
|
||
mutationFn: () =>
|
||
emailApi.reconnect(
|
||
endpointId,
|
||
replacementKey,
|
||
receiveMode || inbox!.receiveMode,
|
||
),
|
||
onSuccess: () => {
|
||
setReplacementKey("");
|
||
},
|
||
onSettled: () => {
|
||
void cache.invalidateQueries({ queryKey: ["email-inboxes", companyId] });
|
||
},
|
||
});
|
||
const control = useMutation({
|
||
mutationFn: (action: "pause" | "resume" | "remove") =>
|
||
emailApi.control(endpointId, action),
|
||
onSuccess: (result) => {
|
||
setRemoved(result.status === "archived");
|
||
void cache.invalidateQueries({ queryKey: ["email-inboxes", companyId] });
|
||
},
|
||
});
|
||
if (removed)
|
||
return <p>Inbox disconnected. Email history remains in its tasks.</p>;
|
||
if (!inbox)
|
||
return (
|
||
<p role={query.error ? "alert" : undefined}>
|
||
{query.error?.message ?? "Loading email inbox…"}
|
||
</p>
|
||
);
|
||
return (
|
||
<div className="max-w-2xl space-y-8 pb-8">
|
||
<header className="space-y-2">
|
||
<p className="text-sm text-muted-foreground">{assignedAgentName}’s email address</p>
|
||
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
|
||
<h1 aria-label={inbox.address ?? undefined} className="min-w-0 break-all text-xl font-bold">
|
||
{inbox.address ? (
|
||
<CopyText text={inbox.address} ariaLabel="Copy email address" title="Copy email address"
|
||
containerClassName="max-w-full" className="flex min-w-0 items-center gap-2 rounded-md text-left">
|
||
<span className="min-w-0 break-all">{inbox.address}</span>
|
||
<Copy aria-hidden="true" className="size-4 shrink-0 text-muted-foreground" />
|
||
</CopyText>
|
||
) : "Email inbox"}
|
||
</h1>
|
||
{inbox.address && (
|
||
<a href={`https://console.agentmail.to/dashboard/inboxes/${encodeURIComponent(inbox.address)}`}
|
||
target="_blank" rel="noopener noreferrer"
|
||
className="inline-flex items-center gap-1 text-sm text-muted-foreground underline underline-offset-4 hover:text-foreground">
|
||
View inbox <ExternalLink aria-hidden="true" className="size-3" />
|
||
</a>
|
||
)}
|
||
</div>
|
||
{inbox.status === "active" && inbox.address && (
|
||
<p className="text-sm text-muted-foreground">
|
||
Send an email to this address to start a task with {assignedAgentName}.
|
||
</p>
|
||
)}
|
||
</header>
|
||
|
||
<Card className="gap-2 p-4">
|
||
<h2 className="text-sm font-semibold">How it Works</h2>
|
||
<p className="text-sm text-muted-foreground">
|
||
Incoming email creates tasks for {assignedAgentName}. Replies stay in the same task.
|
||
Task comments stay internal; use Email reply to send an email.
|
||
</p>
|
||
</Card>
|
||
|
||
<section aria-labelledby="email-receiving-heading" className="space-y-4">
|
||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||
<div className="flex items-center gap-2">
|
||
<h2 id="email-receiving-heading" className="text-sm font-semibold">Receiving email</h2>
|
||
{(inbox.status !== "active" || inbox.lastError) && (
|
||
<StatusBadge status={inbox.status === "active" ? "attention" : inbox.status}
|
||
label={inbox.status === "active" ? "Needs attention" : inbox.status === "revoked" ? "Access revoked" : undefined} />
|
||
)}
|
||
</div>
|
||
{["active", "paused"].includes(inbox.status) && (
|
||
<Button variant="outline" size="sm" disabled={control.isPending}
|
||
onClick={() => control.mutate(inbox.status === "active" ? "pause" : "resume")}>
|
||
{inbox.status === "active" ? "Pause" : "Resume"}
|
||
</Button>
|
||
)}
|
||
</div>
|
||
{inbox.status === "paused" && (
|
||
<p className="text-sm text-muted-foreground">Receiving is paused. Resume to receive new email.</p>
|
||
)}
|
||
<dl className="grid gap-3 sm:grid-cols-2">
|
||
<div className="space-y-1">
|
||
<dt className="text-xs text-muted-foreground">Receiving mode</dt>
|
||
<dd className="text-sm">{inbox.receiveMode === "websocket" ? "Live connection" : "Webhook"}</dd>
|
||
</div>
|
||
<div className="space-y-1">
|
||
<dt className="text-xs text-muted-foreground">Last mail check</dt>
|
||
<dd className="font-mono text-xs">{inbox.lastSyncAt ? formatDateTime(inbox.lastSyncAt) : "Not checked yet"}</dd>
|
||
</div>
|
||
</dl>
|
||
{inbox.lastError && <p role="alert" className="text-sm text-destructive">{inbox.lastError}</p>}
|
||
{control.error && control.variables !== "remove" && (
|
||
<p role="alert" className="text-sm text-destructive">{control.error.message}</p>
|
||
)}
|
||
</section>
|
||
|
||
<details open={reconnectOpen} onToggle={(event) => setReconnectOpen(event.currentTarget.open)} className="border-t border-border pt-5">
|
||
<summary className="cursor-pointer text-sm font-medium">Reconnect inbox</summary>
|
||
<div className="space-y-4 pt-4">
|
||
<p className="text-sm text-muted-foreground">
|
||
Replace the API key or change how this inbox receives email. The email address and task history stay the same.
|
||
</p>
|
||
<AgentMailApiKeyField label="New API key" value={replacementKey} onChange={setReplacementKey} disabled={reconnect.isPending} />
|
||
<div className="space-y-2">
|
||
<Label htmlFor="email-reconnect-mode">Receiving mode</Label>
|
||
<select id="email-reconnect-mode" className={selectClass}
|
||
disabled={reconnect.isPending} value={receiveMode || inbox.receiveMode}
|
||
onChange={(e) => setReceiveMode(e.target.value as "websocket" | "webhook")}>
|
||
<option value="websocket">Live connection</option>
|
||
<option value="webhook">Webhook</option>
|
||
</select>
|
||
</div>
|
||
{reconnect.error && <p role="alert" className="text-sm text-destructive">{reconnect.error.message}</p>}
|
||
{reconnect.isSuccess && <p role="status" className="text-sm">Inbox reconnected.</p>}
|
||
<div className="flex justify-end">
|
||
<Button variant="outline" disabled={!replacementKey || reconnect.isPending} onClick={() => reconnect.mutate()}>
|
||
{reconnect.isPending ? "Reconnecting…" : "Reconnect inbox"}
|
||
</Button>
|
||
</div>
|
||
</div>
|
||
</details>
|
||
|
||
<section aria-labelledby="email-disconnect-heading" className="space-y-3 border-t border-border pt-5">
|
||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||
<div className="space-y-1">
|
||
<h2 id="email-disconnect-heading" className="text-sm font-semibold">Disconnect inbox</h2>
|
||
<p className="text-sm text-muted-foreground">Stop receiving email in Paperclip. The inbox stays in AgentMail.</p>
|
||
</div>
|
||
<Button variant="outline" size="sm" disabled={control.isPending}
|
||
onClick={() => control.mutate("remove")}>
|
||
Disconnect inbox
|
||
</Button>
|
||
</div>
|
||
{control.error && control.variables === "remove" && (
|
||
<p role="alert" className="text-sm text-destructive">{control.error.message}</p>
|
||
)}
|
||
</section>
|
||
</div>
|
||
);
|
||
}
|