The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
feat(connections): make AgentMail a default connection with inline setup (#14772)
Dotta6c1a75da4989
diff --git a/doc/SPEC-implementation.md b/doc/SPEC-implementation.mdindex 8a5d7fdd01..f980ee7ca0 100644--- a/doc/SPEC-implementation.md+++ b/doc/SPEC-implementation.md@@ -1724,10 +1724,10 @@ when the run fails, before generic recovery retries. Reconnect preserves accountidentity and permissions. Compatible legacy agents may explicitly adopt avalidated connection inline; late failures must not invalidate newer credentials.-### Experimental task-bound email+### Task-bound email-AgentMail channel connections extend the experimental conversation/task pipeline-with explicit email publication. Each owned inbox/provider thread binds one task;+AgentMail is a default connection and does not require the experimental chat+setting. It extends the conversation/task pipeline with explicit email publication. Each owned inbox/provider thread binds one task;external email senders do not gain board authority. Incoming correspondence usesthe assigned agent's normal execution controls. Internal task activity neverimplicitly sends email. New outgoing conversations create child tasks and durablediff --git a/doc/connections/AGENTMAIL.md b/doc/connections/AGENTMAIL.mdindex 8310cbe846..717c3fc9e2 100644--- a/doc/connections/AGENTMAIL.md+++ b/doc/connections/AGENTMAIL.md@@ -1,13 +1,38 @@# AgentMail email connections-AgentMail is an experimental **channel** connection. Enable experimental chat-connections, open Apps → AgentMail, select which humans and agents may use the-credential, then enter an API key. In the saved connection’s Permissions page,-choose **Give an agent an email address**. The three-step wizard selects an agent,-creates or attaches an address, and reviews the setup. Selecting an agent outside-the current allowed list adds that agent when setup completes. Every provider thread in that inbox has one Paperclip task. Subjects are-not identifiers. The same email delivered to two connected inboxes creates two-independent tasks.+AgentMail is a default **channel** connection. Open Connectors → AgentMail;+no experimental setting is required. Setup has two steps: pick the agent, then+pick its email address and create it. For a new connection, the first step also+suggests an accessible saved AgentMail account key, or asks for a new API key.+New credentials default to company-wide human access and only the selected agent.+Reusing a key preserves its grants and other agent installs. The domain dropdown sits+beside the email name and defaults to the first verified custom domain, falling+back to `agentmail.to`. An explicit choice is preserved across reloads. Receiving+mode, sender guidance, and trust settings are under **Advanced options**; an+existing low-trust agent still needs its required work boundary and runtime.+There is no separate review or Permissions detour. Each provider thread in the+inbox becomes one Paperclip task. Subjects are not identifiers. The same email+delivered to two connected inboxes creates two independent tasks.++**Add connection** starts a fresh setup identity, so an earlier unfinished key+or address cannot silently replace the new form. **Finish setup** on a draft row+resumes that exact inbox with its saved account and request ID, including an+address already allocated before a later provider failure. Cancel and Done+return to Connectors; Email settings opens the inbox settings. The email step+groups the task/thread explanation under **How it Works**.++After allocation, the address is shown as text with **Finish connecting**.+**Choose a different address** restores the editable name and domain fields with+a new setup identity. The previous inbox stays in AgentMail, and its draft can+still be resumed from Connectors. Retrying never silently creates a replacement.+Changing accounts also opens a new setup URL after saving the replacement key+and retiring the empty draft, so refresh preserves the new account and request.++Get API keys from [AgentMail's API-key page](https://console.agentmail.to/dashboard/api-keys).+When an agent requests AgentMail in a chat or task, an inline card asks only for+the key. It defaults to company-wide human access and this agent only, then+creates an address (or connects the existing address for an inbox-scoped key).+The agent resumes only after its inbox is usable. Access can be adjusted later on the saved connection’s Permissions page.Setup accepts an AgentMail API key or the saved company credential from anotherAgentMail connection. Organization and pod keys create an inbox-scoped runtime@@ -15,10 +40,37 @@ key. An existing inbox-scoped key can connect only its own inbox. Credentialsare vaulted and resolved by the server; they are not passed to agents. An inboxcan have only one non-archived Paperclip endpoint across the instance.+The shared API-key field offers labeled saved credentials and an explicit new-key+choice. The server filters suggestions by company, provider, active secret, and+current-user grants. Scope metadata is saved during key validation; legacy keys+are checked with bounded concurrency under a shared three-second deadline.+No secret values are returned. Use still rechecks authorization and the key.+Organization/pod keys are preferred over inbox-only keys. The same picker is used+by the inline card. Unrelated or unbound secrets are not suggested.++An inbox-only key is caught on the agent/key step before the email form. Choose+an account key to type a new name and pick a domain, or explicitly choose+**Use the existing inbox instead**. Old locked drafts recover at this key choice.+The selected credential or explicit new-key choice survives refresh without+storing the key text. Failed inline setup offers **Change API key** before any+address is allocated; it retires an empty draft and preserves the replacement+request identity across refresh.+Switching preserves the agent and starts a new setup request. Agent dropdowns+use the shared avatar-aware selector for both options and the selected value.+An already allocated inbox must finish its original setup before changing accounts.+Verified custom domains are selectable after checking the API key. Complete DNSsetup in [AgentMail](https://docs.agentmail.to/custom-domains). Paperclip does notregister domains or manage DNS.+Debounced address checks search the account's visible inbox list (up to 100+entries), rather than requesting a not-yet-created inbox by ID. Live testing+found that AgentMail retains negative inbox lookups: an address checked before+creation could return 404 during access-key creation even after the inbox was+created successfully. Listing avoids this failure. A match is taken; absence is+unknown because the address may be outside the returned page or credential scope.+Final creation still handles global address conflicts.+Failed provider requests retain their HTTP status, a fixed operation name, andan allowlisted [AgentMail error code](https://docs.agentmail.to/errors). Forexample, `create_inbox` with `missing_permission` differs from `limit_exceeded`.@@ -28,11 +80,11 @@ malformed, larger, or stalled responses keep the original HTTP failure. Providermessages, suggested fixes, URLs, inbox identifiers, and credentials are excludedfrom these diagnostics. These diagnostics do not retry or suppress failures.-The setup and Permissions page warn that an unrestricted inbox can receive mail-from anyone. Configure sender allowlists in AgentMail; Paperclip does not manage+Advanced options and the Permissions page explain that an unrestricted inbox can+receive mail from anyone. Configure sender allowlists in AgentMail; Paperclip does not manageor verify them. AgentMail controls new-message and reply lists separately. The-wizard recommends Paperclip’s existing **Low-trust review** preset and lets the-operator configure a project or root-task boundary. Incoming tasks are placed+setup lets the operator review the agent’s trust settings and configure a project+or root-task boundary for **Low-trust review**. Incoming tasks are placedinside that boundary. Low-trust execution also requires isolated workspaces and an active sandboxenvironment selected for the agent; setup rejects an unavailable runtime. Newinbound tasks request isolated execution. The trust preset itself does not@@ -45,6 +97,21 @@ An explicitly configured workspace strategy still applies and must be usable.Removing the assigned agent’s saved-connection access or revoking its credentialgrant stops receiving and sending. Connection creation saves the vaulted binding,human grants, and agent access in one database transaction.+The catalog's **Remove connection** action uses the email inbox control API for+AgentMail, including unfinished drafts. It preserves provider inboxes and task+history while disconnecting Paperclip and removing its owned runtime credentials.++Each inbox has distinct **Settings**, **Access**, **Conversations**, and+**Activity** views. Access reuses the saved account's credential and agent controls,+so changes apply to every inbox using that account. Conversations links email+threads to their tasks; Activity shows the shared delivery and publication feed.+Settings leads with the agent’s email address: click it to copy with confirmation,+or use **View inbox** to open that inbox in AgentMail’s console. It also explains+how email becomes tasks.+Receiving mode, last mail check, and Pause/Resume are grouped below. Reconnect+credentials live in an expandable section, followed by a separate Disconnect+action. Inbox lifecycle controls use the email API, and reconnect opens inbox Settings.+Unconfirmed email delivery is resolved in its task rather than through chat replay.## Receiving and task lifecycle@@ -111,6 +178,7 @@ All paths below are relative to `/api`:| --- | --- || Save credential and human/agent access | `POST /companies/:companyId/email/connections` || Inspect a saved credential | `POST /companies/:companyId/email/connections/:connectionId/inspect` |+| Check an address without creating an inbox (connection manager) | `POST /companies/:companyId/email/connections/:connectionId/check-address` || List authorized inboxes | `GET /companies/:companyId/email/inboxes` || Inspect setup credentials (connection manager) | `POST /companies/:companyId/email/inspect` || Create or attach an inbox (connection manager) | `POST /companies/:companyId/email/inboxes` |@@ -191,9 +259,44 @@ show publication failures and uncertain delivery resolution. Delivery admission,message processing and agent wakeup are separate from provider delivery and modelstartup; live latency measurements must distinguish those stages.+Setup reads only allowlisted, documented provider error codes from a bounded+response body. An inbox-creation `resource_taken` or `already_exists` error,+including HTTP 403, appears beside the email field as “This email address is+already in use.” Other 403 errors retain permission guidance. Provider messages,+fixes, and links are never forwarded. Existing addresses visible to the saved+account are flagged before submission. The initial name and subsequent edits+trigger a read-only check after a 350 ms pause; changing the name or domain+aborts the previous request and ignores its result. Checks use the saved credential+behind the same company, connection-management, and connector-feature gates.+Taken addresses show clickable alternatives, excluding known conflicts. A failed+creation also remembers that address in the non-secret setup draft.++[AgentMail's `not_found` response](https://docs.agentmail.to/errors#not_found)+also hides inboxes outside the credential's scope, so a lookup cannot prove+global availability. Missing addresses show that availability is confirmed on+creation and offer alternatives without claiming they are free. Lookup failures+are visible and leave creation available for its authoritative check; known+conflicts and pending checks disable creation. Other taken addresses are reported+when creation is attempted, without leaving the address step.++Browser refresh preserves non-secret draft fields and the setup request ID;+API keys are never saved in browser storage. Retrying the same setup resumes any+inbox already created before the failure. Drafts are scoped to the agent requested+by the setup link. Once an inbox has been allocated, its agent and address stay+fixed during recovery. A failed progress lookup can be retried in place.++When the account and inbox share a setup request ID, completion replaces the+account’s untouched initial agent access with the final selected agent. That+default applies only once and only while the original install rows are unchanged.+Later permission edits and retries preserve existing agent or company installs.+Reusing an account from another setup also preserves its existing installs. Both paths use the email+setup permission (`tools:manage_connections`), without an additional agent-edit+permission.+## Verification and live qualificationDeterministic coverage lives in `server/src/__tests__/agentmail-api.test.ts`,+`server/src/__tests__/email-routes-provider-errors.test.ts`,`server/src/__tests__/email-channels.integration.test.ts`, and`tests/e2e/agentmail.spec.ts`. It exercises real database transactions with a fakeprovider, plus browser setup and explicit task email actions.diff --git a/doc/connections/CONNECTION-SEARCH.md b/doc/connections/CONNECTION-SEARCH.mdindex dbcb31c816..9c0630e21e 100644--- a/doc/connections/CONNECTION-SEARCH.md+++ b/doc/connections/CONNECTION-SEARCH.md@@ -12,9 +12,16 @@ is shared across the catalog scan.Discovery includes tool, channel/email, and AI methods. Channel methods followthe instance's Chat connectors experimental setting. Each catalog method namesits `purpose`. Channel and AI methods include a company-scoped `setupPath` to-their existing setup flow. `connection_request` still creates tool setup cards;-channel discovery does not turn an email inbox into an executable MCP tool or-add channel setup to that card.+their existing setup flow. AgentMail also supports `connection_request`: it+creates an inline API-key card addressed to the responsible user. Search guidance+prefers this card over a setup link or asking for credentials in chat. Other+channel methods continue to use their setup path.++The AgentMail card grants company-wide human access and installs access only for+the requesting agent. It saves the credential, provisions or connects an inbox,+and completes only after the server verifies that the assigned inbox is usable.+A saved key alone does not make the search result ready. Partial setup can resume+after reload using the same request ID, without duplicating the account or inbox.The agent chooses the relevant match using descriptions and method purposes.It should clarify only when the task remains ambiguous. A search match does notdiff --git a/doc/connections/CONNECTOR-PLAYBOOK.md b/doc/connections/CONNECTOR-PLAYBOOK.mdindex facfb02001..cd2db9348c 100644--- a/doc/connections/CONNECTOR-PLAYBOOK.md+++ b/doc/connections/CONNECTOR-PLAYBOOK.md@@ -569,10 +569,10 @@ they do not need a duplicate native wrapper just to supply a skill.**Resolve eligibility from current assignments and access.** An AgentMail accountcredential alone does not give an agent email capabilities. An active inboxassigned to that agent does, provided both the inbox connection and saved-credential access remain authorized and the experimental chat-connector flag is-on. Other connectors must define an equally concrete assignment rule. Keep every+credential access remain authorized. AgentMail is available by default and does+not depend on the experimental chat-connector flag. Other connectors must define an equally concrete assignment rule. Keep everylookup company-scoped. Revoked grants, disabled connections, removed assignments,-and experimental gates must remove the contribution. Fail closed on lookup errors.+and any applicable experimental gates must remove the contribution. Fail closed on lookup errors.**Install skills transparently through the existing runtime skill path.** Mergesystem-managed contributions with the agent's chosen skills for each run, withoutdiff --git a/packages/shared/src/app-definitions/agentmail.json b/packages/shared/src/app-definitions/agentmail.jsonindex f4e22e8122..edd0799b19 100644--- a/packages/shared/src/app-definitions/agentmail.json+++ b/packages/shared/src/app-definitions/agentmail.json@@ -37,7 +37,7 @@],"guidanceMd": "Connect an AgentMail API key, then create or select an inbox for your agent. WebSocket receiving works without a public URL.","consoleLinks": {- "keys": "https://console.agentmail.to",+ "keys": "https://console.agentmail.to/dashboard/api-keys","docs": "https://docs.agentmail.to/inboxes"},"riskTier": "S3",diff --git a/packages/shared/src/connection-intent-guidance.ts b/packages/shared/src/connection-intent-guidance.tsindex 3866243d6a..3078023901 100644--- a/packages/shared/src/connection-intent-guidance.ts+++ b/packages/shared/src/connection-intent-guidance.ts@@ -13,7 +13,7 @@ export const CONNECTION_INTENT_AGENT_GUIDANCE = ["- Do not use connection tools for arbitrary MCP URLs or unrelated work.",].join("\n");-export const CONNECTIONS_SEARCH_TOOL_DESCRIPTION = "Search connections across tool, channel/email, and AI purposes with a service name or a natural-language description (up to 4000 characters). Results tolerate extra words, split names, and small typos. Choose the relevant match using its description, method purpose, and setupPath; tool methods use connection_request. Also discovers verified external aggregator apps. Use first when the user asks to connect a service, or when usable access is uncertain; follow the returned instruction and exact providerQuestion, if any. Do not use for arbitrary MCP URLs. Search is read-only.";+export const CONNECTIONS_SEARCH_TOOL_DESCRIPTION = "Search connections across tool, channel/email, and AI purposes with a service name or a natural-language description (up to 4000 characters). Results tolerate extra words, split names, and small typos. Choose the relevant match using its description and method purpose. Follow the returned instruction to present an inline setup card with connection_request or share the method's setupPath. Also discovers verified external aggregator apps. Use first when the user asks to connect a service, or when usable access is uncertain; follow the returned instruction and exact providerQuestion, if any. Do not use for arbitrary MCP URLs. Search is read-only.";export const CONNECTION_REQUEST_TOOL_DESCRIPTION = "Request the service identifier returned by connections_search as available or needs_user_action. Follow the search instruction; aggregator routes require the saved provider-selection interaction ID. Only this tool creates the real setup card. If user action is needed, finish independent work, then yield without retrying or asking for credentials in comments.";diff --git a/packages/shared/src/feature-catalog.ts b/packages/shared/src/feature-catalog.tsindex 9660136a2e..f2c404a3bd 100644--- a/packages/shared/src/feature-catalog.ts+++ b/packages/shared/src/feature-catalog.ts@@ -111,7 +111,7 @@ export const INSTANCE_FEATURE_CATALOG: Record<InstanceFeatureKey, FeatureCatalogenableChatConnectors: {title: "Chat connectors",description:- "Show experimental chat connector setup and Board surfaces. Existing connections keep running when hidden; GitHub and other tool connectors are unaffected.",+ "Show experimental chat connector setup and Board surfaces. Existing connections keep running when hidden; AgentMail, GitHub tools, and other tool connectors are unaffected.",tier: "managed",cloudDefault: false,selfHostedDefault: false,diff --git a/packages/shared/src/types/connection-intent.ts b/packages/shared/src/types/connection-intent.tsindex 128e1bc6de..8a0dce3916 100644--- a/packages/shared/src/types/connection-intent.ts+++ b/packages/shared/src/types/connection-intent.ts@@ -28,7 +28,7 @@ export interface ConnectionSearchResultItem {key: string;label: string;auth: "oauth" | "api_key" | "none";- /** Discovery is open across purposes; connection_request creates tool cards. */+ /** AgentMail channel setup and tool methods support connection_request cards. */purpose?: "tool" | "channel" | "ai";/** Company-scoped setup destination for methods with a separate setup flow. */setupPath?: string;@@ -60,6 +60,8 @@ export interface ConnectionRequestResult {export type ConnectionIntentSetupConnection = Pick<ToolConnection, "id" | "applicationId" | "name" | "status" | "enabled">;export interface ConnectionIntentSetupOptions {+ /** Resume this request's saved AgentMail account after a partial setup. */+ emailSetup?: { credentialConnectionId: string | null; readyConnectionId: string | null };aiConnection?: import("../ai-connections.js").AiConnectionBinding;/** Legacy authentication stays unchanged until the normal validated agent update succeeds. */aiConnectionRequiresAdoption?: boolean;diff --git a/packages/shared/src/types/email.ts b/packages/shared/src/types/email.tsindex fb158df36c..556ff6a0dc 100644--- a/packages/shared/src/types/email.ts+++ b/packages/shared/src/types/email.ts@@ -52,3 +52,17 @@ export interface EmailThreadSummary {messages: EmailMessage[];publications: EmailPublicationSummary[];}+/** A missing inbox is not proof of availability: AgentMail hides other accounts. */+export interface EmailAddressCheckResult {+ address: string;+ status: "taken" | "unknown";+}++/** Metadata only, filtered by provider and the current user's credential grants. */+export interface EmailCredentialOption {+ id: string;+ label: string;+ scope: "organization" | "pod" | "inbox" | "unavailable";+ inboxId: string | null;+ createdAt: string;+}diff --git a/packages/shared/src/types/issue.ts b/packages/shared/src/types/issue.tsindex 22e5e0ae37..ef9d2962d2 100644--- a/packages/shared/src/types/issue.ts+++ b/packages/shared/src/types/issue.ts@@ -1359,8 +1359,8 @@ export type ConnectionIntentPhase = "requested" | "authorizing" | "needs_retry";export interface ConnectionIntentPayload {version: 1;upstreamService?: { slug: string; name: string; selectionInteractionId?: string };- /** Runtime authentication requests cannot be satisfied by tool credentials. */- purpose?: "ai";+ /** AI authentication and inbox setup cannot be satisfied by tool credentials. */+ purpose?: "ai" | "channel";serviceSlug: string;serviceName: string;serviceLogoUrl?: string | null;diff --git a/packages/shared/src/validators/email.ts b/packages/shared/src/validators/email.tsindex f96bf0f188..661624d121 100644--- a/packages/shared/src/validators/email.ts+++ b/packages/shared/src/validators/email.ts@@ -2,6 +2,12 @@ import { z } from "zod";const address = z.string().trim().email().max(320);const addresses = z.array(address).max(50);+export const emailAddressCheckSchema = z.object({+ username: z.string().trim().toLowerCase().regex(/^[a-z0-9][a-z0-9._-]*$/).max(64),+ domain: z.string().trim().toLowerCase().max(253).regex(/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.[a-z]{2,}$/),+}).strict();+export type EmailAddressCheckInput = z.infer<typeof emailAddressCheckSchema>;+export const emailEndpointSetupSchema = z.object({assignedAgentId: z.string().uuid(),diff --git a/packages/shared/src/validators/issue.ts b/packages/shared/src/validators/issue.tsindex c2a1795b3f..99f1c22f1e 100644--- a/packages/shared/src/validators/issue.ts+++ b/packages/shared/src/validators/issue.ts@@ -1111,7 +1111,7 @@ const connectionIntentBrandAssetSchema = zexport const connectionIntentPayloadSchema = z.object({upstreamService: z.object({ slug: z.string().min(1).max(120), name: z.string().min(1).max(160), selectionInteractionId: z.string().guid().optional() }).strict().optional(),- purpose: z.literal("ai").optional(),+ purpose: z.enum(["ai", "channel"]).optional(),version: z.literal(1),serviceSlug: z.string().trim().min(1).max(120),serviceName: z.string().trim().min(1).max(160),diff --git a/server/src/__tests__/agentmail-api.test.ts b/server/src/__tests__/agentmail-api.test.tsindex 727a11c6f8..21a17d7710 100644--- a/server/src/__tests__/agentmail-api.test.ts+++ b/server/src/__tests__/agentmail-api.test.ts@@ -24,6 +24,43 @@ const message = (extra = {}) =>...extra,});describe("AgentMail protocol boundary", () => {+ it("checks the visible inbox list without probing an uncreated address", async () => {+ const fetcher = vi.fn(async () => Response.json({ inboxes: [{ inbox_id: "[email protected]" }] }));+ await expect(agentmailApi("private-key", fetcher).checkAddress("[email protected]"))+ .resolves.toEqual({ address: "[email protected]", status: "taken" });+ expect(fetcher).toHaveBeenCalledOnce();+ expect(fetcher).toHaveBeenCalledWith("https://api.agentmail.to/v0/inboxes?limit=100", expect.objectContaining({ method: "GET", body: undefined }));+ });+ it("never treats an unlisted inbox as proof that an address is available", async () => {+ const fetcher = vi.fn(async () => Response.json({ inboxes: [], next_page_token: "more-inboxes" }));+ await expect(agentmailApi("private-key", fetcher).checkAddress("[email protected]"))+ .resolves.toEqual({ address: "[email protected]", status: "unknown" });+ });+ it("can create the checked address and its access key when the provider caches missing inbox lookups", async () => {+ let created = false;+ let negativeLookupCached = false;+ const fetcher = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {+ const path = new URL(String(url)).pathname;+ if (path === "/v0/inboxes" && init?.method === "GET") return Response.json({ inboxes: [] });+ if (path === "/v0/inboxes" && init?.method === "POST") {+ created = true;+ return Response.json({ inbox_id: "[email protected]" });+ }+ if (path === "/v0/inboxes/ralph%40agentmail.to" && !created) negativeLookupCached = true;+ if (!created || negativeLookupCached) return Response.json({ code: "not_found" }, { status: 404 });+ return Response.json({ api_key: "test-runtime-key", api_key_id: "runtime-id" });+ });+ const api = agentmailApi("test-account-key", fetcher);+ await expect(api.checkAddress("[email protected]")).resolves.toMatchObject({ status: "unknown" });+ const inbox = await api.createInbox({ username: "ralph" });+ await expect(api.createInboxKey(inbox.inbox_id)).resolves.toMatchObject({ api_key_id: "runtime-id" });+ expect(negativeLookupCached).toBe(false);+ });+ it.each([401, 403, 404, 429, 503])("preserves lookup errors (%s) rather than claiming an address is taken or free", async status => {+ const fetcher = vi.fn(async () => Response.json({ code: "missing_permission" }, { status }));+ await expect(agentmailApi("private-key", fetcher).checkAddress("[email protected]"))+ .rejects.toMatchObject({ status, operation: "list_inboxes" });+ });it("verifies the exact raw body and rejects forged or stale Svix signatures", () => {const secret = `whsec_${Buffer.from("a-test-secret-only").toString("base64")}`;const body = JSON.stringify({@@ -322,6 +359,10 @@ describe("AgentMail protocol boundary", () => {expect(send?.responses).toHaveProperty("202");const setup = operations.find(o => o.path === "/api/companies/{companyId}/email/inspect");expect(JSON.stringify(setup?.authorization)).toContain("board");+ const check = operations.find(o => o.path === "/api/companies/{companyId}/email/connections/{connectionId}/check-address");+ expect(check?.requestBody).toBeDefined();+ expect(JSON.stringify(check?.authorization)).toContain("board");+ expect(check?.responses).toHaveProperty("429");});});diff --git a/server/src/__tests__/connection-aggregator-fallback.test.ts b/server/src/__tests__/connection-aggregator-fallback.test.tsindex 689a628ae3..4ccea4c46d 100644--- a/server/src/__tests__/connection-aggregator-fallback.test.ts+++ b/server/src/__tests__/connection-aggregator-fallback.test.ts@@ -281,17 +281,24 @@ const support = await getEmbeddedPostgresTestSupport();await instanceSettingsService(db).updateExperimental({ enableChatConnectors: false });}});- it("discovers all purposes with truthful setup actions and the chat feature gate", async () => {+ it.each([false, true])("discovers AgentMail with truthful setup actions regardless of the chat setting (%s)", async (enabled) => {await resetQuestions();const service = connectionIntentService(db);- expect((await service.search(claims, "agentmail")).results.some(item => item.service === "agentmail")).toBe(false);- await instanceSettingsService(db).updateExperimental({ enableChatConnectors: true });+ await instanceSettingsService(db).updateExperimental({ enableChatConnectors: enabled });try {const result = await service.search(claims, "agentmail");expect(result.results[0]?.methods).toEqual([expect.objectContaining({key: "email-agent", purpose: "channel", setupPath: `/AGG/apps/chat/connect?provider=agentmail&purpose=chat&agentId=${claims.sub}`,})]);- expect(result.instruction).toContain("setupPath");+ expect(result.instruction).toContain("connection_request");+ const requested = await service.request(claims, "agentmail");+ expect(requested).toMatchObject({ state: "needs_user_action", interactionId: expect.any(String) });+ expect(await service.request(claims, "agentmail")).toMatchObject({ interactionId: requested.interactionId });+ const options = await service.setupOptions(requested.interactionId!);+ expect(options.interaction.payload).toMatchObject({ purpose: "channel", serviceSlug: "agentmail", requestingAgentId: claims.sub });+ expect(options.emailSetup).toEqual({ credentialConnectionId: null, readyConnectionId: null });+ await service.decline(requested.interactionId!, "responsible-user");+ await expect(service.request(claims, "agentmail")).rejects.toThrow(/already been resolved/);const browse = await service.search(claims, "");expect(browse.results.some(item => item.service === "agentmail")).toBe(true);expect(browse.results.some(item => item.service === "anthropic")).toBe(true);diff --git a/server/src/__tests__/email-address-check.test.ts b/server/src/__tests__/email-address-check.test.tsnew file mode 100644index 0000000000..08a13e0e68--- /dev/null+++ b/server/src/__tests__/email-address-check.test.ts@@ -0,0 +1,82 @@+import express from "express";+import request from "supertest";+import type { Db } from "@paperclipai/db";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { forbidden } from "../errors.js";+import { errorHandler } from "../middleware/error-handler.js";+import { emailRoutes } from "../routes/email.js";+import type { EmailChannelService } from "../services/email-channels.js";++const mocks = vi.hoisted(() => ({ credential: vi.fn(), listCredentials: vi.fn(), permission: vi.fn() }));+vi.mock("../services/email-connections.js", () => ({ emailConnectionService: () => ({ credential: mocks.credential, listCredentials: mocks.listCredentials }) }));+vi.mock("../services/access.js", () => ({ accessService: () => ({ hasPermission: mocks.permission }) }));+const companyId = "11111111-1111-4111-8111-111111111111";+const connectionId = "22222222-2222-4222-8222-222222222222";+const path = `/api/companies/${companyId}/email/connections/${connectionId}/check-address`;+const input = { username: "ralph", domain: "agentmail.to" };+function app(actor = { type: "board", source: "local_implicit", userId: "board" } as express.Request["actor"]) {+ const instance = express();+ instance.use(express.json());+ instance.use((req, _res, next) => { req.actor = actor; next(); });+ instance.use("/api", emailRoutes({} as Db, {} as EmailChannelService));+ instance.use(errorHandler);+ return instance;+}+beforeEach(() => {+ vi.resetAllMocks();+ mocks.credential.mockResolvedValue({ value: "private-key" });+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({ inboxes: [{ inbox_id: "[email protected]" }] })));+});+afterEach(() => vi.unstubAllGlobals());+describe("AgentMail address checks", () => {+ it("lists saved-key metadata with company and manager access checks", async () => {+ const listPath = `/api/companies/${companyId}/email/connections`;+ mocks.listCredentials.mockResolvedValue([{ id: connectionId, label: "AgentMail account key", scope: "organization" }]);+ const response = await request(app()).get(listPath).expect(200);+ expect(response.headers["cache-control"]).toBe("no-store");+ expect(mocks.listCredentials).toHaveBeenCalledWith(companyId, expect.objectContaining({ userId: "board" }));+ mocks.listCredentials.mockClear();+ await request(app({ type: "agent", agentId: connectionId, companyId })).get(listPath).expect(403);+ await request(app({ type: "board", source: "session", userId: "member", companyIds: [] })).get(listPath).expect(404);+ await request(app({ type: "board", source: "session", userId: "member", companyIds: [companyId] })).get(listPath).expect(403);+ expect(mocks.listCredentials).not.toHaveBeenCalled();+ });+ it("uses the company-scoped saved credential and returns only address status", async () => {+ const response = await request(app()).post(path).send({ username: "Ralph", domain: "AgentMail.to" }).expect(200);+ expect(response.body).toEqual({ address: "[email protected]", status: "taken" });+ expect(response.headers["cache-control"]).toBe("no-store");+ expect(mocks.credential).toHaveBeenCalledWith(companyId, connectionId, expect.objectContaining({ userId: "board" }));+ expect(fetch).toHaveBeenCalledWith("https://api.agentmail.to/v0/inboxes?limit=100", expect.objectContaining({ method: "GET" }));+ expect(response.text).not.toContain("private-key");+ });+ it.each([+ { username: "bad/name", domain: "agentmail.to" },+ { username: "r".repeat(65), domain: "agentmail.to" },+ { username: "ralph", domain: "https://other.test" },+ { ...input, apiKey: "unexpected" },+ ])("rejects malformed input before reading credentials (%#)", async body => {+ await request(app()).post(path).send(body).expect(400);+ expect(mocks.credential).not.toHaveBeenCalled();+ expect(fetch).not.toHaveBeenCalled();+ });+ it("does not allow agents to check addresses", async () => {+ await request(app({ type: "agent", agentId: connectionId, companyId })).post(path).send(input).expect(403);+ expect(fetch).not.toHaveBeenCalled();+ });+ it("requires company access and connection management permission", async () => {+ await request(app({ type: "board", source: "session", userId: "member", companyIds: [] })).post(path).send(input).expect(404);+ await request(app({ type: "board", source: "session", userId: "member", companyIds: [companyId] })).post(path).send(input).expect(403);+ expect(mocks.credential).not.toHaveBeenCalled();+ });+ it("preserves credential access checks", async () => {+ mocks.credential.mockRejectedValueOnce(forbidden("Credential access denied"));+ await request(app()).post(path).send(input).expect(403);+ expect(fetch).not.toHaveBeenCalled();+ });+ it("surfaces rate limits without copying provider bodies", async () => {+ vi.mocked(fetch).mockResolvedValueOnce(Response.json({ code: "rate_limit_exceeded", message: "private-key" }, { status: 429, headers: { "retry-after": "10" } }));+ const response = await request(app()).post(path).send(input).expect(429);+ expect(response.headers["retry-after"]).toBe("10");+ expect(response.text).not.toContain("private-key");+ });+});diff --git a/server/src/__tests__/email-channels.integration.test.ts b/server/src/__tests__/email-channels.integration.test.tsindex 3c969b76c6..adcdda0184 100644--- a/server/src/__tests__/email-channels.integration.test.ts+++ b/server/src/__tests__/email-channels.integration.test.ts@@ -1,3 +1,4 @@+import { connectionIntentService } from "../services/connection-intents.js";import { applyConnectorSkills, prepareConnectorSkillDelivery, resolveConnectorAssignments, annotateConnectorSkills } from "../services/connector-runtime.js";import { PaperclipRunnerToolAuthority } from "../services/native-runtime/paperclip-runner-tool-authority.js";import { renderPaperclipWakePrompt, resolvePaperclipDesiredSkillNames, resolveLegacyPaperclipDesiredSkillNames } from "@paperclipai/adapter-utils/server-utils";@@ -5,6 +6,7 @@ import express from "express";import type WebSocket from "ws";import request from "supertest";import { issueRoutes } from "../routes/issues.js";+import { emailRoutes } from "../routes/email.js";import { errorHandler } from "../middleware/index.js";import { issueRecoveryActionService } from "../services/issue-recovery-actions.js";import { randomUUID } from "node:crypto";@@ -43,6 +45,7 @@ import {issues,authUsers,companyMemberships,+ principalPermissionGrants,toolConnections,toolConnectionInstalls,connectionGrants,@@ -59,6 +62,7 @@ import {agentmailMessageSchema,type AgentmailMessage,} from "../services/agentmail-api.js";+import { accessService } from "../services/access.js";import { emailConnectionService } from "../services/email-connections.js";import { toolAccessService } from "../services/tool-access.js";import { emailSendSchema } from "@paperclipai/shared";@@ -78,7 +82,7 @@ describe("AgentMail durable email pipeline", () => {database = await startEmbeddedPostgresTestDatabase("paperclip-email-");db = createDb(database.connectionString);await instanceSettingsService(db).updateExperimental({- enableChatConnectors: true,+ enableChatConnectors: false,});await db.insert(authUsers).values({id: "email-board",@@ -178,12 +182,11 @@ describe("AgentMail durable email pipeline", () => {expect((await resolveConnectorAssignments(db, binding))[0].resources).toHaveLength(1);});- it("removes connector contributions when the experimental gate or credential access is revoked", async () => {+ it("keeps AgentMail available with chat disabled and removes contributions when credential access is revoked", async () => {const f = await fixture();const binding = { companyId: f.companyId, agentId: f.agentId };await instanceSettingsService(db).updateExperimental({ enableChatConnectors: false });- try { expect(await resolveConnectorAssignments(db, binding)).toEqual([]); }- finally { await instanceSettingsService(db).updateExperimental({ enableChatConnectors: true }); }+ expect((await resolveConnectorAssignments(db, binding)).map(item => item.key)).toEqual(["agentmail"]);const endpoint = await f.service.getEndpoint(f.endpointId);await db.update(toolConnections).set({ enabled: false }).where(eq(toolConnections.id, endpoint.connectionId));expect(await resolveConnectorAssignments(db, binding)).toEqual([]);@@ -981,6 +984,57 @@ describe("AgentMail durable email pipeline", () => {expect(f.wakeup).toHaveBeenCalledTimes(1);});+ it("suggests only same-provider active credentials authorized for this user", async () => {+ const f = await fixture();+ const svc = emailConnectionService(db, f.fetcher);+ const actor = { userId: "email-board" };+ const own = await svc.connect(f.companyId, { apiKey: "private-key", grantKind: "user", allAgents: false,+ agentIds: [], idempotencyKey: randomUUID() }, actor);+ const shared = await svc.connect(f.companyId, { apiKey: "shared-key", grantKind: "organization", allAgents: false,+ agentIds: [], idempotencyKey: randomUUID() }, actor);+ const other = await svc.connect(f.companyId, { apiKey: "other-user-key", grantKind: "user", allAgents: false,+ agentIds: [], idempotencyKey: randomUUID() }, { userId: "different-user" });+ const choices = await svc.listCredentials(f.companyId, actor);+ expect(choices.map(option => option.id).sort()).toEqual([own.id, shared.id].sort());+ expect(JSON.stringify(choices)).not.toMatch(/private-key|shared-key|other-user-key|secretId|api_key_hash/);+ expect(choices[0]).toMatchObject({ scope: "inbox", inboxId: f.address });+ expect((await svc.listCredentials(randomUUID(), actor))).toEqual([]);+ await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.connectionId, own.id));+ await db.update(toolConnections).set({ config: { provider: "different", emailCredential: true } }).where(eq(toolConnections.id, shared.id));+ expect(await svc.listCredentials(f.companyId, actor)).toEqual([]);+ expect((await svc.listCredentials(f.companyId, { userId: "different-user" })).map(option => option.id)).toEqual([other.id]);+ });++ it("bounds legacy saved-key discovery and checks slow keys concurrently", async () => {+ const f = await fixture();+ const actor = { userId: "email-board" };+ const svc = emailConnectionService(db, f.fetcher);+ const ids = [];+ for (let i = 0; i < 2; i++) {+ const row = await svc.connect(f.companyId, { apiKey: `legacy-key-${i}`, grantKind: "organization", allAgents: false,+ agentIds: [], idempotencyKey: randomUUID() }, actor);+ ids.push(row.id);+ await db.update(toolConnections).set({ config: { provider: "agentmail", emailCredential: true } }).where(eq(toolConnections.id, row.id));+ }+ let concurrent = 0, peak = 0;+ const signals: AbortSignal[] = [];+ const slowFetch = vi.fn<typeof fetch>(async (_url, init) => {+ concurrent++; peak = Math.max(peak, concurrent);+ const signal = init!.signal!; signals.push(signal);+ try {+ return await new Promise<Response>((_resolve, reject) => {+ if (signal.aborted) reject(new Error("Discovery deadline"));+ else signal.addEventListener("abort", () => reject(new Error("Discovery deadline")), { once: true });+ });+ } finally { concurrent--; }+ });+ const choices = await emailConnectionService(db, slowFetch).listCredentials(f.companyId, actor);+ expect(choices.map(option => option.id).sort()).toEqual(ids.sort());+ expect(choices.every(option => option.scope === "unavailable")).toBe(true);+ expect(peak).toBe(2);+ expect(signals.every(signal => signal.aborted)).toBe(true);+ }, 10_000);+it("saves a scoped credential before inbox setup, preserves personal ownership, and adds the chosen agent", async () => {const f = await fixture();const svc = emailConnectionService(db, f.fetcher);@@ -1060,6 +1114,214 @@ describe("AgentMail durable email pipeline", () => {).rejects.toThrow(/revoked/);});+ it.each(["new", "reused"] as const)("finishes a %s account for the final agent with only connection-management permission", async kind => {+ const f = await fixture("websocket");+ const actor = { userId: "email-board" };+ await f.service.control(f.endpointId, "remove", actor);+ const selectedAgentId = randomUUID();+ await db.insert(agents).values({ id: selectedAgentId, companyId: f.companyId, name: "Final email agent",+ role: "engineer", status: "idle", adapterType: "process", permissions: {} });+ await db.insert(principalPermissionGrants).values({ companyId: f.companyId, principalType: "user",+ principalId: actor.userId, permissionKey: "tools:manage_connections" });+ expect(await accessService(db).hasPermission(f.companyId, "user", actor.userId, "tools:manage_connections")).toBe(true);+ expect(await accessService(db).hasPermission(f.companyId, "user", actor.userId, "agent_config:update")).toBe(false);+ const requestId = randomUUID();+ const svc = emailConnectionService(db, f.fetcher);+ const connection = await svc.connect(f.companyId, { apiKey: "test-key", grantKind: "organization",+ allAgents: false, agentIds: [f.agentId], idempotencyKey: kind === "new" ? requestId : randomUUID() }, actor);+ const server = express();+ server.use(express.json());+ server.use((req, _res, next) => {+ req.actor = { type: "board", source: "session", userId: actor.userId, companyIds: [f.companyId] };+ next();+ });+ server.use("/api", emailRoutes(db, f.service));+ server.use(errorHandler);+ const input = { assignedAgentId: selectedAgentId, credentialConnectionId: connection.id,+ inboxId: f.address, receiveMode: "websocket", idempotencyKey: requestId };+ const route = `/api/companies/${f.companyId}/email/inboxes`;+ // Keep one listener for this journey instead of racing ephemeral listeners+ // against Node's HTTP keep-alive socket reuse between requests.+ const http = server.listen(0, "127.0.0.1");+ await new Promise<void>((resolve, reject) => { http.once("listening", resolve); http.once("error", reject); });+ try {+ const response = await request(http).post(route).send(input).expect(201);+ expect(response.body).toMatchObject({ assignedAgentId: selectedAgentId, status: "active", address: f.address });+ await request(http).post(route).send(input).expect(201);+ const installs = await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, connection.id));+ expect(installs.map(i => i.targetId).sort()).toEqual((kind === "new" ? [selectedAgentId] : [f.agentId, selectedAgentId]).sort());+ await expect(svc.assertAgentAccess(f.companyId, connection.id, selectedAgentId)).resolves.toBeUndefined();+ if (kind === "new") await expect(svc.assertAgentAccess(f.companyId, connection.id, f.agentId)).rejects.toThrow(/no longer has access/);+ await request(http).post(`/api/companies/${randomUUID()}/email/inboxes`).send(input).expect(404);+ } finally {+ await new Promise<void>((resolve, reject) => http.close(error => error ? reject(error) : resolve()));+ }+ });++ it.each([+ ["before setup", "company"], ["before setup", "agents"],+ ["after a failed setup", "company"], ["after a failed setup", "agents"],+ ] as const)("preserves permissions edited %s to include %s access", async (when, scope) => {+ const f = await fixture("websocket");+ const actor = { userId: "email-board" };+ await f.service.control(f.endpointId, "remove", actor);+ const selectedAgentId = randomUUID(), otherAgentId = randomUUID();+ await db.insert(agents).values([selectedAgentId, otherAgentId].map(id => ({ id, companyId: f.companyId,+ name: "Email agent", role: "engineer", status: "idle", adapterType: "process", permissions: {} })));+ const requestId = randomUUID();+ const connection = await emailConnectionService(db, f.fetcher).connect(f.companyId, {+ apiKey: "test-key", grantKind: "organization", allAgents: false, agentIds: [f.agentId], idempotencyKey: requestId,+ }, actor);+ const input = { assignedAgentId: selectedAgentId, credentialConnectionId: connection.id,+ inboxId: f.address, receiveMode: "websocket" as const, idempotencyKey: requestId };+ if (when === "after a failed setup") {+ const provider = vi.mocked(f.fetcher).getMockImplementation()!;+ vi.mocked(f.fetcher).mockImplementation(async (url, init) =>+ decodeURIComponent(new URL(String(url)).pathname) === `/v0/inboxes/${f.address}`+ ? new Response(null, { status: 403 }) : provider(url, init));+ await expect(f.service.setup(f.companyId, input, actor)).rejects.toThrow();+ vi.mocked(f.fetcher).mockImplementation(provider);+ }+ const requestedInstalls = scope === "company"+ ? [{ targetType: "company" as const, targetId: f.companyId }]+ : [f.agentId, otherAgentId].map(targetId => ({ targetType: "agent" as const, targetId }));+ await toolAccessService(db).putConnectionInstalls(connection.id, { installs: requestedInstalls }, { actorType: "user", actorId: actor.userId });+ const before = await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, connection.id));+ const result = await f.service.setup(f.companyId, input, actor);+ expect(result.status).toBe("active");+ const after = await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, connection.id));+ for (const install of before) expect(after).toContainEqual(install);+ expect(after.map(i => i.targetId).sort()).toEqual((scope === "company" ? [f.companyId] : [f.agentId, otherAgentId, selectedAgentId]).sort());+ });++ it.each(["create_inbox", "create_inbox_key", "address_taken"] as const)("reports a provider rejection during %s and resumes the same setup after correction", async (failedOperation) => {+ const f = await fixture("websocket");+ await f.service.control(f.endpointId, "remove", { userId: "email-board" });+ const provider = vi.mocked(f.fetcher).getMockImplementation()!;+ let denied = true;+ let createdInboxes = 0;+ vi.mocked(f.fetcher).mockImplementation(async (url, init) => {+ const pathname = new URL(String(url)).pathname;+ if (pathname === "/v0/auth/me" && new Headers(init?.headers).get("authorization") === "Bearer organization-test-key") {+ return Response.json({ scope_type: "organization", organization_id: "organization" });+ }+ if (pathname === "/v0/inboxes" && init?.method === "POST") {+ if (failedOperation === "address_taken") {+ const body = JSON.parse(String(init.body));+ if (body.username === "ralph") return Response.json({ code: "resource_taken", message: "private provider detail" }, { status: 403 });+ expect(body.username).toBe("ralph-team");+ }+ if (denied && failedOperation === "create_inbox") return new Response("private provider denial", { status: 403 });+ createdInboxes++;+ return Response.json({ inbox_id: f.address });+ }+ if (pathname.endsWith("/api-keys") && init?.method === "POST") {+ if (denied && failedOperation === "create_inbox_key") return new Response("private provider denial", { status: 403 });+ return Response.json({ api_key: "test-key", api_key_id: "inbox-runtime-key" });+ }+ return provider(url, init);+ });+ const account = await emailConnectionService(db, f.fetcher).connect(f.companyId, {+ apiKey: "organization-test-key", grantKind: "organization", allAgents: false,+ agentIds: [f.agentId], idempotencyKey: randomUUID(),+ }, { userId: "email-board" });+ const server = express();+ server.use(express.json());+ server.use((req, _res, next) => {+ req.actor = { type: "board", source: "local_implicit", userId: "email-board" };+ next();+ });+ server.use("/api", emailRoutes(db, f.service));+ server.use(errorHandler);+ const id = randomUUID();+ const input = { assignedAgentId: f.agentId, credentialConnectionId: account.id,+ username: "ralph", domain: "agentmail.to", receiveMode: "websocket", idempotencyKey: id };+ const route = `/api/companies/${f.companyId}/email/inboxes`;+ const failure = await request(server).post(route).send(input).expect(failedOperation === "address_taken" ? 409 : 422);+ expect(failure.body.error).toContain(failedOperation === "address_taken" ? "already in use" : "AgentMail did not allow Paperclip");+ expect(failure.body.details).toMatchObject({ providerStatus: 403, operation: failedOperation === "address_taken" ? "create_inbox" : failedOperation });+ expect(failure.text).not.toMatch(/private provider denial|organization-test-key|Internal server error/);+ const [draft] = await db.select().from(chatEndpoints).where(eq(chatEndpoints.id, id));+ expect(draft.status).toBe("draft");+ expect(draft.botExternalId).toBe(failedOperation === "create_inbox_key" ? f.address : null);+ denied = false;+ if (failedOperation === "address_taken") input.username = "ralph-team";+ const connected = await request(server).post(route).send(input).expect(201);+ expect(connected.body).toMatchObject({ id, status: "active", address: f.address });+ await request(server).post(route).send(input).expect(201);+ expect(createdInboxes).toBe(1);+ const endpoints = await db.select().from(chatEndpoints).where(and(+ eq(chatEndpoints.companyId, f.companyId), ne(chatEndpoints.status, "archived"),+ ));+ expect(endpoints.map(endpoint => endpoint.id)).toEqual([id]);+ });++ it.each(["inbox", "organization"] as const)("completes an AgentMail card with a %s key only after its assigned inbox is usable", async (scope) => {+ const f = await fixture("websocket");+ const actor = { userId: "email-board" };+ await f.service.control(f.endpointId, "remove", actor);+ const provider = vi.mocked(f.fetcher).getMockImplementation()!;+ const createdInboxes: unknown[] = [];+ vi.mocked(f.fetcher).mockImplementation(async (url, init) => {+ const pathname = new URL(String(url)).pathname;+ if (pathname === "/v0/auth/me" && new Headers(init?.headers).get("authorization") === "Bearer organization-test-key") {+ return Response.json({ scope_type: "organization", organization_id: "organization" });+ }+ if (pathname === "/v0/inboxes" && init?.method === "POST") {+ createdInboxes.push(JSON.parse(String(init.body)));+ return Response.json({ inbox_id: f.address });+ }+ if (pathname.endsWith("/api-keys") && init?.method === "POST") {+ return Response.json({ api_key: "test-key", api_key_id: "inbox-runtime-key" });+ }+ return provider(url, init);+ });+ const issue = await issueService(db).create(f.companyId, { title: "Acquire an email address", assigneeAgentId: f.agentId, status: "in_progress" });+ const runId = randomUUID();+ await db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: f.agentId,+ status: "running", responsibleUserId: "email-board", contextSnapshot: { issueId: issue.id } });+ const claims = { sub: f.agentId, company_id: f.companyId, run_id: runId, responsible_user_id: "email-board" };+ const intents = connectionIntentService(db);+ const requested = await intents.request(claims, "agentmail");+ const id = requested.interactionId!;+ const account = await emailConnectionService(db, f.fetcher).connect(f.companyId, {+ apiKey: scope === "organization" ? "organization-test-key" : "test-key", grantKind: "organization", allAgents: false, agentIds: [f.agentId], idempotencyKey: id,+ }, actor);+ expect((await intents.setupOptions(id)).emailSetup).toEqual({ credentialConnectionId: account.id, readyConnectionId: null });+ expect((await intents.search(claims, "agentmail")).results[0].state).not.toBe("ready");+ await expect(intents.complete(id, account.id, "email-board", { canManageOrganizationGrant: true })).rejects.toThrow(/active inbox/);+ const inbox = await f.service.setup(f.companyId, { assignedAgentId: f.agentId,+ credentialConnectionId: account.id, receiveMode: "websocket", idempotencyKey: id }, actor);+ expect(createdInboxes).toEqual(scope === "organization"+ ? [{ display_name: "Email agent", client_id: `paperclip-${id}` }] : []);+ const retry = await f.service.setup(f.companyId, { assignedAgentId: f.agentId,+ credentialConnectionId: account.id, receiveMode: "websocket", idempotencyKey: id }, actor);+ expect(retry.connectionId).toBe(inbox.connectionId);+ expect(createdInboxes).toHaveLength(scope === "organization" ? 1 : 0);+ expect((await intents.setupOptions(id)).emailSetup?.readyConnectionId).toBe(inbox.connectionId);+ await expect(intents.complete(id, inbox.connectionId, "someone-else", { canManageOrganizationGrant: true })).rejects.toThrow(/addressed user/);+ await expect(intents.complete(id, inbox.connectionId, "email-board")).rejects.toThrow(/connection-management/);+ const otherAgentId = randomUUID();+ await db.insert(agents).values({ id: otherAgentId, companyId: f.companyId, name: "Other agent", role: "engineer", status: "idle", adapterType: "process", adapterConfig: {}, runtimeConfig: {}, permissions: {} });+ await db.update(chatEndpoints).set({ assignedAgentId: otherAgentId }).where(eq(chatEndpoints.id, id));+ await expect(intents.complete(id, inbox.connectionId, "email-board", { canManageOrganizationGrant: true })).rejects.toThrow(/active inbox/);+ await db.update(chatEndpoints).set({ assignedAgentId: f.agentId, status: "paused" }).where(eq(chatEndpoints.id, id));+ await expect(intents.complete(id, inbox.connectionId, "email-board", { canManageOrganizationGrant: true })).rejects.toThrow(/active inbox/);+ await db.update(chatEndpoints).set({ status: "active" }).where(eq(chatEndpoints.id, id));+ const grants = await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, account.id));+ expect(grants.map(grant => grant.kind)).toEqual(["organization"]);+ const installs = await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, account.id));+ expect(installs.map(install => ({ type: install.targetType, id: install.targetId }))).toEqual([{ type: "agent", id: f.agentId }]);+ await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.connectionId, account.id));+ await expect(intents.complete(id, inbox.connectionId, "email-board", { canManageOrganizationGrant: true })).rejects.toThrow(/active inbox/);+ await db.update(connectionGrants).set({ status: "active" }).where(eq(connectionGrants.connectionId, account.id));+ const completed = await intents.complete(id, inbox.connectionId, "email-board", { canManageOrganizationGrant: true });+ expect(completed).toMatchObject({ status: "accepted", result: { outcome: "connected", connectionId: inbox.connectionId } });+ expect((await intents.complete(id, inbox.connectionId, "email-board", { canManageOrganizationGrant: true })).id).toBe(id);+ expect(await intents.request(claims, "agentmail")).toMatchObject({ state: "ready", interactionId: null, connectionId: inbox.connectionId });+ expect((await intents.search(claims, "agentmail")).results[0]).toMatchObject({ state: "ready", connectionId: inbox.connectionId });+ });+it("checks AgentMail account and inbox health without local stdio or MCP discovery", async () => {const f = await fixture();const connection = await emailConnectionService(db, f.fetcher).connect(f.companyId, {diff --git a/server/src/__tests__/email-routes-provider-errors.test.ts b/server/src/__tests__/email-routes-provider-errors.test.tsnew file mode 100644index 0000000000..742c0058ad--- /dev/null+++ b/server/src/__tests__/email-routes-provider-errors.test.ts@@ -0,0 +1,113 @@+import express from "express";+import request from "supertest";+import type { Db } from "@paperclipai/db";+import { describe, expect, it, vi } from "vitest";+import { forbidden } from "../errors.js";+import { errorHandler } from "../middleware/error-handler.js";+import { emailRoutes } from "../routes/email.js";+import { agentmailApi } from "../services/agentmail-api.js";+import type { EmailChannelService } from "../services/email-channels.js";++const companyId = "11111111-1111-4111-8111-111111111111";+const agentId = "22222222-2222-4222-8222-222222222222";+const setupPath = `/api/companies/${companyId}/email/inboxes`;+const setupInput = {+ assignedAgentId: agentId,+ apiKey: "private-api-key",+ username: "ralph",+ receiveMode: "websocket",+ idempotencyKey: "33333333-3333-4333-8333-333333333333",+};++function app(setup: () => Promise<unknown>) {+ const instance = express();+ instance.use(express.json());+ instance.use((req, _res, next) => {+ req.actor = { type: "board", source: "local_implicit", userId: "board" };+ next();+ });+ instance.use("/api", emailRoutes({} as Db, { setup, inspect: setup } as unknown as EmailChannelService));+ instance.use(errorHandler);+ return instance;+}++describe("AgentMail provider errors at the HTTP boundary", () => {+ it("explains a key-creation 404 without claiming the allocated address is missing", async () => {+ const api = agentmailApi("private-api-key", vi.fn(async () => Response.json({ code: "not_found" }, { status: 404 })));+ const response = await request(app(() => api.createInboxKey("[email protected]")))+ .post(setupPath).send(setupInput).expect(422);+ expect(response.body.error).toBe("AgentMail could not create an access key for this inbox. The email address was saved; try finishing the connection again.");+ expect(response.body.details).toMatchObject({ providerStatus: 404, operation: "create_inbox_key" });+ });++ it.each(["resource_taken", "already_exists"])("identifies %s on inbox creation even when AgentMail returns 403", async (code) => {+ const api = agentmailApi("private-api-key", vi.fn(async () => Response.json({+ code, message: "private provider message", fix: "private-api-key", docs: "https://untrusted.invalid",+ }, { status: 403 })));+ const response = await request(app(() => api.createInbox({ username: "ralph" })))+ .post(setupPath).send(setupInput).expect(409);+ expect(response.body).toMatchObject({+ code: "agentmail_address_taken", error: "This email address is already in use. Choose a different address.",+ details: { field: "username", providerStatus: 403, operation: "create_inbox" },+ });+ expect(response.text).not.toMatch(/private|untrusted/);+ });++ it("does not mislabel a taken resource during another operation as a taken address", async () => {+ const api = agentmailApi("private-api-key", vi.fn(async () => Response.json({ code: "resource_taken" }, { status: 403 })));+ const response = await request(app(() => api.createInboxKey("[email protected]")))+ .post(setupPath).send(setupInput).expect(422);+ expect(response.body.code).toBe("agentmail_request_failed");+ expect(response.body.error).not.toContain("already in use");+ });++ it.each([+ [401, 422, "AgentMail rejected the API key"],+ [403, 422, "AgentMail did not allow Paperclip to create the email address"],+ [400, 422, "Try a different address"],+ [409, 422, "Try a different address"],+ [422, 422, "Try a different address"],+ [404, 422, "could not find the requested inbox or resource"],+ [429, 429, "rate limiting"],+ [503, 502, "temporarily unavailable"],+ ])("explains provider %i without exposing the provider body", async (providerStatus, status, message) => {+ const fetcher = vi.fn(async () => new Response("private provider body and private-api-key", {+ status: providerStatus,+ headers: { "Retry-After": "12" },+ }));+ const api = agentmailApi("private-api-key", fetcher);+ const response = await request(app(() => api.createInbox({ username: "ralph" })))+ .post(setupPath).send(setupInput);+ expect(response.status).toBe(status);+ expect(response.body.error).toContain(message);+ expect(response.body.details).toEqual({+ code: "agentmail_request_failed", providerStatus, operation: "create_inbox",+ });+ expect(response.text).not.toMatch(/private|Internal server error/);+ if (providerStatus === 429) expect(response.headers["retry-after"]).toBe("12");+ });++ it("explains a denied runtime-key creation without suggesting a different address", async () => {+ const api = agentmailApi("private-api-key", vi.fn(async () => new Response(null, { status: 403 })));+ const response = await request(app(() => api.createInboxKey("[email protected]")))+ .post(setupPath).send(setupInput).expect(422);+ expect(response.body.error).toContain("create an inbox-scoped API key");+ expect(response.body.error).not.toContain("different address");+ expect(response.body.details.operation).toBe("create_inbox_key");+ });++ it("keeps a rejected provider key distinct from Paperclip session authentication", async () => {+ const api = agentmailApi("private-api-key", vi.fn(async () => new Response(null, { status: 401 })));+ const response = await request(app(() => api.whoami()))+ .post(`/api/companies/${companyId}/email/inspect`).send({ apiKey: "private-api-key" }).expect(422);+ expect(response.body.error).toContain("AgentMail rejected the API key");+ expect(response.body.details.operation).toBe("inspect_key");+ });++ it("preserves Paperclip authorization errors", async () => {+ const response = await request(app(async () => { throw forbidden("Missing permission: tools:manage_connections"); }))+ .post(setupPath).send(setupInput).expect(403);+ expect(response.body.error).toBe("Missing permission: tools:manage_connections");+ expect(response.body.details).toBeUndefined();+ });+});diff --git a/server/src/routes/email.ts b/server/src/routes/email.tsindex 937f3bc07e..8a67356eb9 100644--- a/server/src/routes/email.ts+++ b/server/src/routes/email.ts@@ -1,7 +1,8 @@-import { Router, type Request } from "express";+import { Router, type ErrorRequestHandler, type Request } from "express";import { z } from "zod";import {emailConnectionSchema,+ emailAddressCheckSchema,emailEndpointSetupSchema,emailSendSchema,isUuidLike,@@ -11,7 +12,9 @@ import { validate } from "../middleware/validate.js";import { assertBoard, assertCompanyAccess, hasCompanyAccess } from "./authz.js";import { emailConnectionService } from "../services/email-connections.js";import { accessService } from "../services/access.js";-import { badRequest, forbidden, notFound } from "../errors.js";+import { badRequest, forbidden, HttpError, notFound } from "../errors.js";+import { agentmailApi, AgentmailApiError } from "../services/agentmail-api.js";+import { logger } from "../middleware/logger.js";import type {EmailChannelService,EmailActor,@@ -25,6 +28,62 @@ function actor(req: Request): EmailActor {localImplicit: req.actor.source === "local_implicit",};}++// Provider rejections describe setup/account problems, not Paperclip crashes.+// Only local messages and operation names reach the UI; never forward a body.+const agentmailErrorHandler: ErrorRequestHandler = (error, _req, res, next) => {+ if (!(error instanceof AgentmailApiError)) return next(error);+ logger.warn({ operation: error.operation, providerStatus: error.status, providerCode: error.providerCode }, "AgentMail request rejected");+ const actions: Partial<Record<AgentmailApiError["operation"], string>> = {+ request: "complete this request",+ inspect_key: "verify the API key",+ create_inbox: "create the email address",+ create_inbox_key: "create an inbox-scoped API key",+ create_webhook: "register the email webhook",+ };+ const action = actions[error.operation] ?? "complete this request";+ let status = 422;+ let code = "agentmail_request_failed";+ let message: string;+ const addressTaken = error.operation === "create_inbox"+ && [403, 409, 422].includes(error.status)+ && (error.providerCode === "resource_taken" || error.providerCode === "already_exists");+ if (addressTaken) {+ status = 409;+ code = "agentmail_address_taken";+ message = "This email address is already in use. Choose a different address.";+ } else if (error.providerCode === "limit_exceeded") {+ message = "Your AgentMail account has reached its resource limit. Free up space or increase your plan’s limit, then try again.";+ } else if (error.providerCode === "domain_not_verified") {+ message = "Verify this domain in AgentMail before creating an email address, or choose another domain.";+ } else if (error.status === 401) {+ message = "AgentMail rejected the API key. Check that it is correct and has not been revoked, then reconnect.";+ } else if (error.status === 403) {+ message = `AgentMail did not allow Paperclip to ${action}. Check your API key permissions and AgentMail account limits, then try again.`;+ } else if (error.status === 429) {+ status = 429;+ res.set("Retry-After", String(Math.ceil(error.retryAfterMs / 1000)));+ message = "AgentMail is rate limiting requests. Wait a moment, then try again.";+ } else if ([400, 409, 422].includes(error.status) && error.operation === "create_inbox") {+ message = "AgentMail could not create this email address. Try a different address and check that its domain is available in your AgentMail account.";+ } else if (error.status === 404) {+ message = error.operation === "create_inbox_key"+ ? "AgentMail could not create an access key for this inbox. The email address was saved; try finishing the connection again."+ : "AgentMail could not find the requested inbox or resource. Check that it still exists and that your API key can access it.";+ } else if (error.status >= 500) {+ status = 502;+ message = "AgentMail is temporarily unavailable. Try again in a moment.";+ } else {+ message = `AgentMail could not ${action}. Check your AgentMail settings, then try again.`;+ }+ next(new HttpError(status, message, {+ code,+ providerStatus: error.status,+ operation: error.operation,+ ...(addressTaken ? { field: "username" } : {}),+ }));+};+export function emailRoutes(db: Db, service: EmailChannelService) {const router = Router();async function manager(req: Request, companyId: string) {@@ -45,13 +104,19 @@ export function emailRoutes(db: Db, service: EmailChannelService) {)throw forbidden("Missing permission: tools:manage_connections");}+ router.get("/companies/:companyId/email/connections", async (req, res) => {+ const companyId = req.params.companyId as string;+ await manager(req, companyId);+ res.set("Cache-Control", "no-store").json(+ await emailConnectionService(db).listCredentials(companyId, actor(req)),+ );+ });router.post("/companies/:companyId/email/connections",validate(emailConnectionSchema),async (req, res) => {const companyId = req.params.companyId as string;await manager(req, companyId);- await service.requireEnabled();res.status(201).json(@@ -68,7 +133,6 @@ export function emailRoutes(db: Db, service: EmailChannelService) {async (req, res) => {const companyId = req.params.companyId as string;await manager(req, companyId);- await service.requireEnabled();const saved = await emailConnectionService(db).credential(companyId,req.params.connectionId as string,@@ -79,6 +143,19 @@ export function emailRoutes(db: Db, service: EmailChannelService) {.json(await service.inspect(saved.value));},);+ router.post(+ "/companies/:companyId/email/connections/:connectionId/check-address",+ validate(emailAddressCheckSchema),+ async (req, res) => {+ const companyId = req.params.companyId as string;+ await manager(req, companyId);+ const saved = await emailConnectionService(db).credential(+ companyId, req.params.connectionId as string, actor(req),+ );+ res.set("Cache-Control", "no-store").json(await agentmailApi(saved.value)+ .checkAddress(`${req.body.username}@${req.body.domain}`));+ },+ );router.get("/companies/:companyId/email/inboxes", async (req, res) => {const companyId = req.params.companyId as string;assertCompanyAccess(req, companyId);@@ -229,6 +306,7 @@ export function emailRoutes(db: Db, service: EmailChannelService) {res.json(delivery);},);+ router.use(agentmailErrorHandler);return router;}export function emailWebhookRoutes(service: EmailChannelService) {diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.tsindex d320a5c170..1ef26262c7 100644--- a/server/src/routes/openapi.ts+++ b/server/src/routes/openapi.ts@@ -12,6 +12,7 @@ import {localAiLoginStartSchema,emailEndpointSetupSchema,emailConnectionSchema,+ emailAddressCheckSchema,emailSendSchema,browserUseControlSchema,browserUseSettingsSchema,@@ -1508,8 +1509,10 @@ const BOARD_ONLY_OPERATIONS = new Set(["POST /api/tool-gateway/action-requests/{id}/decline","POST /api/companies/{companyId}/email/inspect","POST /api/companies/{companyId}/email/inboxes",+ "GET /api/companies/{companyId}/email/connections","POST /api/companies/{companyId}/email/connections","POST /api/companies/{companyId}/email/connections/{connectionId}/inspect",+ "POST /api/companies/{companyId}/email/connections/{connectionId}/check-address","POST /api/email/inboxes/{endpointId}/control","POST /api/email/inboxes/{endpointId}/reconnect","POST /api/companies/{companyId}/email/deliveries/{publicationId}/resolve",@@ -2128,7 +2131,25 @@ for (const [method, path, summary, body] of browserUseOperations) {// Explicit task-bound email. Board setup and agent actions share the same vaulted// connection, while automatic chat publication never applies to these endpoints.+registry.registerPath({+ method: "post",+ path: "/api/companies/{companyId}/email/connections/{connectionId}/check-address",+ tags: ["Email"],+ summary: "Check for an existing AgentMail address using a saved credential",+ description: "Requires a board connection manager and enabled chat connectors. Read-only: does not create or reserve an inbox. A missing inbox returns unknown because AgentMail hides resources outside the credential scope; it is never proof of availability.",+ request: {+ params: z.object({ companyId: z.string().uuid(), connectionId: z.string().uuid() }),+ body: jsonBody(emailAddressCheckSchema),+ },+ responses: {+ 200: r.ok(z.object({ address: z.string(), status: z.enum(["taken", "unknown"]) })),+ 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound,+ 422: r.unprocessable, 429: { description: "AgentMail request limit reached; retry later" },+ 502: r.serverError,+ },+});for (const [method, path, summary, body, success] of [+ ["get", "/api/companies/{companyId}/email/connections", "List accessible saved AgentMail API keys (metadata only)", undefined, 200],["post", "/api/companies/{companyId}/email/connections", "Save AgentMail credential and access", emailConnectionSchema, 201],["post", "/api/companies/{companyId}/email/connections/{connectionId}/inspect", "Inspect inboxes using a saved AgentMail credential", undefined, 200],["get", "/api/companies/{companyId}/email/inboxes", "List authorized AgentMail inboxes", undefined, 200],@@ -2142,7 +2163,7 @@ for (const [method, path, summary, body, success] of [["post", "/api/companies/{companyId}/email/deliveries/{publicationId}/resolve", "Resolve uncertain email after checking the provider", z.object({ outcome: z.enum(["sent", "failed"]), providerMessageId: z.string().min(1).max(998).optional() }).strict(), 200],] as const) {registry.registerPath({ method, path, tags: ["Email"], summary,- description: "Experimental AgentMail channel. Internal comments never send email. Agent sends require assigned inbox and task ownership, active run authority, and configured action policies. Preserve the same idempotencyKey and payload across retries. New conversations create an email child task; replies require conversationId and replyToMessageId. Reply-all is deliberate and never includes Bcc.",+ description: "AgentMail email connection. Available without the experimental chat setting. Internal comments never send email. Agent sends require assigned inbox and task ownership, active run authority, and configured action policies. Preserve the same idempotencyKey and payload across retries. New conversations create an email child task; replies require conversationId and replyToMessageId. Reply-all is deliberate and never includes Bcc.",request: { params: z.object(Object.fromEntries([...path.matchAll(/\{([^}]+)\}/g)].map(match => [match[1], z.string().uuid()]))), ...(body ? { body: jsonBody(body) } : {}) },responses: { [success]: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 409: r.conflict },});diff --git a/server/src/services/agentmail-api.ts b/server/src/services/agentmail-api.tsindex 3d95934af7..5d8ad897d8 100644--- a/server/src/services/agentmail-api.ts+++ b/server/src/services/agentmail-api.ts@@ -1,6 +1,6 @@import { z } from "zod";import { Webhook } from "svix";-import type { EmailEnvelope } from "@paperclipai/shared";+import type { EmailAddressCheckResult, EmailEnvelope } from "@paperclipai/shared";const strings = z.array(z.string());export const agentmailMessageSchema = z.object({@@ -284,6 +284,18 @@ export function agentmailApi(apiKey: string, fetchImpl: typeof fetch = fetch) {request,whoami: () => request<AgentmailScope>("/auth/me"),getInbox: (id: string) => request<AgentmailInbox>(inboxPath(id)),+ checkAddress: async (address: string): Promise<EmailAddressCheckResult> => {+ // Do not GET a speculative inbox ID. Live AgentMail caches missing inbox+ // lookups, so checking a free name can make key creation return 404 after+ // the inbox is created. Listing avoids priming that negative lookup.+ const { inboxes } = await request<{ inboxes: AgentmailInbox[] }>("/inboxes?limit=100");+ // An absent entry can be outside this page or credential's scope. Only+ // creation is authoritative; never claim an unlisted address is free.+ return {+ address,+ status: inboxes.some(inbox => inbox.inbox_id.toLowerCase() === address.toLowerCase()) ? "taken" : "unknown",+ };+ },listInboxes: () =>request<{ inboxes: AgentmailInbox[] }>("/inboxes?limit=100"),listDomains: () =>diff --git a/server/src/services/connection-intents.ts b/server/src/services/connection-intents.tsindex 1a43c5d6e2..34cec954f7 100644--- a/server/src/services/connection-intents.ts+++ b/server/src/services/connection-intents.ts@@ -1,3 +1,5 @@+import { emailChannelService } from "./email-channels.js";+import { emailConnectionService } from "./email-connections.js";import { agentService } from "./agents.js";import { logActivity } from "./activity-log.js";import { aiConnectionService } from "./ai-connections.js";@@ -237,7 +239,7 @@ export function connectionIntentService(db: Db) {agentId: string;responsibleUserId: string;serviceSlug: string;- purpose?: "ai";+ purpose?: "ai" | "channel";inventory?: Awaited<ReturnType<typeof connectionInventory>>;}) {const managed = input.purpose === "ai" ? await managedAgent(input.companyId, input.agentId, input.serviceSlug) : null;@@ -248,6 +250,11 @@ export function connectionIntentService(db: Db) {} catch (error) { if ([403, 404, 422].includes((error as { status?: number }).status ?? 0)) return null; throw error; }}if (input.purpose === "ai") return null;+ if (input.purpose === "channel") {+ if (input.serviceSlug !== "agentmail") return null;+ const inboxes = await assignedAgentmailInboxes(db, input.companyId, input.agentId);+ return inboxes[0] ? access.getConnection(inboxes[0].connectionId, input.companyId) : null;+ }const inventory = input.inventory ?? await connectionInventory(input.companyId);const matching = inventory.connections.filter((connection) =>sourceSlugForConnection(connection, inventory.applicationsById) === input.serviceSlug@@ -318,11 +325,24 @@ export function connectionIntentService(db: Db) {));}- async function resolveService(service: string, companyId: string, userId: string, agentId: string, purpose?: "ai") {+ // Readiness uses the same credential, feature and assignment checks as the+ // runtime's AgentMail tools; it never starts a worker or contacts the provider.+ function assignedAgentmailInboxes(database: Db, companyId: string, agentId: string) {+ return emailChannelService(database, { heartbeat: { wakeup: async () => {+ throw new Error("Connection discovery cannot start an email worker");+ } } }).assignedInboxes(companyId, agentId);+ }++ async function resolveService(service: string, companyId: string, userId: string, agentId: string, purpose?: "ai" | "channel") {if (!service.startsWith("connection:")) {const app = getAppStoreDefinition(service);if (!app) throw notFound("Connection service was not found");- const methods = purpose === "ai" ? getAvailableConnectionMethods(app).filter(method => method.transport === "runtime_auth") : availableToolConnectionMethods(app);+ if (purpose === "channel" && service !== "agentmail") {+ throw unprocessable("This email connection is not available");+ }+ const methods = purpose === "ai" ? getAvailableConnectionMethods(app).filter(method => method.transport === "runtime_auth")+ : purpose === "channel" ? getAvailableConnectionMethods(app).filter(method => method.purpose === "channel")+ : availableToolConnectionMethods(app);return { ...app, available: app.availability?.available !== false,searchCapabilities: methods.map((method) =>`${method.whenToUse} ${method.capabilityProfile?.label ?? ""} ${method.capabilityProfile?.description ?? ""}`).join(" "),@@ -364,7 +384,7 @@ export function connectionIntentService(db: Db) {const candidates: Array<{ item: ConnectionSearchResultItem; score: number; nameScore: number }> = [];const authorizedCatalogs = new Map<string, Awaited<ReturnType<typeof indexedCatalog>>>();const discoveryMethods = (app: (typeof APP_STORE_DEFINITIONS)[number]) => getAvailableConnectionMethods(app)- .filter(method => method.purpose !== "channel" || settings.enableChatConnectors);+ .filter(method => method.purpose !== "channel" || app.slug === "agentmail" || settings.enableChatConnectors);const services = [...APP_STORE_DEFINITIONS.filter(app => discoveryMethods(app).length).map((app) => app.slug),...inventory.connections.filter((connection) =>sourceSlugForConnection(connection, inventory.applicationsById)?.startsWith("connection:")@@ -406,7 +426,7 @@ export function connectionIntentService(db: Db) {`${app.description ?? ""} ${app.searchCapabilities} ${catalog.map(tool => `${tool.toolName} ${tool.description ?? ""}`).join(" ")}`);if (!score) continue;const ready = await usableConnectionForAgent({ companyId: run.companyId, agentId: agent.id,- responsibleUserId: run.responsibleUserId!, serviceSlug: service, purpose: aiOnly ? "ai" : undefined, inventory });+ responsibleUserId: run.responsibleUserId!, serviceSlug: service, purpose: aiOnly ? "ai" : service === "agentmail" ? "channel" : undefined, inventory });const denied = !aiOnly && !ready && matching.length > 0 && await administrativeDenial(run.companyId, agent.id, service, inventory);candidates.push({ score, nameScore, item: {service, name: app.name, description: app.description ?? null, logoUrl: app.branding.logoUrl ?? null,@@ -540,7 +560,7 @@ export function connectionIntentService(db: Db) {function discoverySuggestions(results: ConnectionSearchResultItem[]): ConnectionsSearchResult {return { version: 1, query, results: results.slice(0, 40),- instruction: "Multiple apps match this query. Choose the relevant service and method using descriptions and purposes. For available or needs_user_action results, tool methods use connection_request and channel or AI methods use setupPath. Use ready tools as installed; ready AI authentication applies to the next execution without reconnection. For an aggregator result, search its aggregator.targetService to obtain the provider-choice question and follow that instruction before requesting a connection. Respect unavailable states. Do not treat a search match as provider consent or app authorization." };+ instruction: "Multiple apps match this query. Choose the relevant service and method using descriptions and purposes. For available or needs_user_action results, tool methods and AgentMail use connection_request to show the inline setup card; other channel or AI methods use setupPath. Use ready tools as installed; ready AI authentication applies to the next execution without reconnection. For an aggregator result, search its aggregator.targetService to obtain the provider-choice question and follow that instruction before requesting a connection. Respect unavailable states. Do not treat a search match as provider consent or app authorization." };}}@@ -550,9 +570,13 @@ export function connectionIntentService(db: Db) {: !suggestions && isRemoteMcpConnectorId(results[0]!.service) && results[0]!.state !== "unavailable"? `${results[0]!.name} is an external service. When the user explicitly names this provider, disclose that it handles the connection and requests to the requested app; no additional provider-choice question is necessary. ${results[0]!.state === "ready" ? aggregatorContinuationInstruction(results[0]!.service, "The requested app") : "Call connection_request with the returned service identifier and follow its instruction. Provider setup does not yet verify underlying app access."}`: !suggestions && results[0]!.state === "unavailable" ? "This connection is unavailable or administratively restricted. Explain the reason. Do not bypass it using another provider."- : suggestions || results.length > 1 ? "These are ranked connection matches. Choose the relevant service and method using their descriptions and purposes; extra query words need not match. For available or needs_user_action tool methods, call connection_request with the service identifier to present its setup card. For available or needs_user_action channel or AI methods, share the method's setupPath. Use ready tools as installed; ready AI authentication is available for the agent's next execution and does not need reconnection. Respect unavailable states and recorded user choices. Clarify only if the intended service is still ambiguous; unrelated matches are not evidence of support."+ : suggestions || results.length > 1 ? "These are ranked connection matches. Choose the relevant service and method using their descriptions and purposes; extra query words need not match. For available or needs_user_action tool methods or AgentMail, call connection_request with the service identifier to present its setup card. For other available or needs_user_action channel or AI methods, share the method's setupPath. Use ready tools as installed; ready AI authentication is available for the agent's next execution and does not need reconnection. Respect unavailable states and recorded user choices. Clarify only if the intended service is still ambiguous; unrelated matches are not evidence of support.": results[0]!.state === "ready" && results[0]!.methods.every(method => method.purpose === "ai")? "AI authentication is available for this agent's next execution. Do not create another connection request or ask the user to reconnect."+ : results[0]!.service === "agentmail"+ ? results[0]!.state === "ready"+ ? "An active AgentMail inbox is assigned to you. Use agentmail_inboxes to read its address. Do not request another connection."+ : "Call connection_request with service agentmail to show the inline API-key card. Do not send a setup link or ask for the key in chat. The card creates an inbox for this agent; wait for completion before claiming an email address.": results[0]!.methods.every(method => method.purpose && method.purpose !== "tool")? "Choose the method relevant to the task using its purpose and label. Share its setupPath with the user to open the existing channel or AI setup flow. These methods do not use the tool connection_request card. Do not claim tools or an inbox are ready before setup finishes.": results[0]!.state === "ready" ? "Use the installed connection. Do not create another connection request."@@ -615,7 +639,7 @@ export function connectionIntentService(db: Db) {async function request(claims: ConnectionRunClaims,serviceSlug: string,- options: { purpose?: "ai"; selectionInteractionId?: string; targetService?: string } = {},+ options: { purpose?: "ai" | "channel"; selectionInteractionId?: string; targetService?: string } = {},): Promise<ConnectionRequestResult> {const context = await loadRunContext(claims);return requestWithContext(context, serviceSlug, options);@@ -624,7 +648,7 @@ export function connectionIntentService(db: Db) {async function requestWithContext(context: Awaited<ReturnType<typeof loadRunContext>>,serviceSlug: string,- options: { purpose?: "ai"; selectionInteractionId?: string; targetService?: string } = {},+ options: { purpose?: "ai" | "channel"; selectionInteractionId?: string; targetService?: string } = {},): Promise<ConnectionRequestResult> {const claims = { sub: context.agent.id, company_id: context.run.companyId, run_id: context.run.id, responsible_user_id: context.run.responsibleUserId! };const route = parseAggregatorRoute(serviceSlug);@@ -653,6 +677,9 @@ export function connectionIntentService(db: Db) {upstreamService = { slug: route.targetService, name: selected.aggregator.targetName, selectionInteractionId: options.selectionInteractionId };serviceSlug = route.provider;}+ // AgentMail has one channel method. Infer it from the server-owned catalog+ // identifier instead of asking the model to invent a new tool argument.+ if (serviceSlug === "agentmail" && !options.purpose) options = { ...options, purpose: "channel" };const app = await resolveService(serviceSlug, context.run.companyId, context.run.responsibleUserId!, context.agent.id, options.purpose);if (!app.available || app.methods.length === 0) {throw unprocessable(`Connection service ${serviceSlug} is not available`);@@ -671,10 +698,10 @@ export function connectionIntentService(db: Db) {state: "ready",connectionId: ready.id,interactionId: null,- instruction: isRemoteMcpConnectorId(app.slug) ? aggregatorContinuationInstruction(app.slug, upstreamService?.name ?? "The requested app") : options.purpose === "ai" ? `${app.name} authentication is available for the next execution.` : `${app.name} is connected. Use its installed tools; a native continuation will refresh tools if needed.`,+ instruction: isRemoteMcpConnectorId(app.slug) ? aggregatorContinuationInstruction(app.slug, upstreamService?.name ?? "The requested app") : options.purpose === "channel" ? "An active AgentMail inbox is assigned to you. Use agentmail_inboxes to read its address; do not request another connection." : options.purpose === "ai" ? `${app.name} authentication is available for the next execution.` : `${app.name} is connected. Use its installed tools; a native continuation will refresh tools if needed.`,};}- if (options.purpose !== "ai" && await administrativeDenial(context.run.companyId, context.agent.id, app.slug, await connectionInventory(context.run.companyId))) {+ if (!options.purpose && await administrativeDenial(context.run.companyId, context.agent.id, app.slug, await connectionInventory(context.run.companyId))) {throw forbidden("This agent has no permitted actions for this service. Ask an administrator to review tool permissions; reconnecting will not remove a denial.");}const outcomeId = context.run.contextSnapshot?.interactionId;@@ -702,7 +729,7 @@ export function connectionIntentService(db: Db) {sourceRunId: context.run.id,sourceIdentityContextId: context.run.activeIdentityContextId,addresseeUserId: context.run.responsibleUserId!,- idempotencyKey: `connection-intent:${context.run.id}:${context.run.responsibleUserId}:${app.slug}${upstreamService ? `:${upstreamService.slug}` : ""}${options.purpose ? ":ai" : ""}`,+ idempotencyKey: `connection-intent:${context.run.id}:${context.run.responsibleUserId}:${app.slug}${upstreamService ? `:${upstreamService.slug}` : ""}${options.purpose ? `:${options.purpose}` : ""}`,},);if (interaction.status !== "pending") throw conflict("This connection request has already been resolved. Follow its recorded outcome.");@@ -738,6 +765,25 @@ export function connectionIntentService(db: Db) {const loaded = await loadIntent(interactionId);const payload = connectionIntentPayloadSchema.parse(loaded.interaction.payload);const app = await resolveService(payload.serviceSlug, loaded.issue.companyId, loaded.interaction.addresseeUserId!, payload.requestingAgentId, payload.purpose);+ if (payload.purpose === "channel") {+ const [saved] = await db.select().from(toolConnections).where(and(+ eq(toolConnections.companyId, loaded.issue.companyId),+ eq(toolConnections.uid, `agentmail-account-${interactionId}`),+ ));+ // A retry may recover only this card's account, after checking the+ // addressed person's current access. No arbitrary connection is selected.+ const credential = saved ? await emailConnectionService(db).get(loaded.issue.companyId, saved.id, { userId: loaded.interaction.addresseeUserId! }) : null;+ const inboxes = await assignedAgentmailInboxes(db, loaded.issue.companyId, payload.requestingAgentId);+ return {+ version: 1, interaction: loaded.interaction,+ service: { service: app.slug, name: app.name, description: app.description ?? null,+ logoUrl: app.branding.logoUrl ?? null, methods: app.methods, source: app.source,+ state: "needs_user_action", connectionId: null },+ existingConnections: [], requestedAgentId: payload.requestingAgentId,+ emailSetup: { credentialConnectionId: credential?.id ?? null,+ readyConnectionId: inboxes.find(inbox => inbox.id === interactionId)?.connectionId ?? null },+ };+ }let managed = payload.purpose === "ai" ? await managedAgent(loaded.issue.companyId, payload.requestingAgentId, app.slug) : null;if (payload.purpose === "ai" && !managed) {const [source] = await db.select().from(heartbeatRuns).where(and(@@ -873,6 +919,22 @@ export function connectionIntentService(db: Db) {throw conflict("Finish and test this connection before using it for the task");}+ if (payload.purpose === "channel") {+ if (payload.serviceSlug !== "agentmail" || !options.canManageOrganizationGrant) {+ throw forbidden("AgentMail inbox setup requires connection-management authority");+ }+ const inboxes = await assignedAgentmailInboxes(txDb, loaded.issue.companyId, payload.requestingAgentId);+ const inbox = inboxes.find(inbox => inbox.connectionId === selectedConnection.id);+ if (!inbox?.address) throw conflict("Finish creating an active inbox for the requesting agent before continuing");+ const credentialId = selectedConnection.config?.credentialConnectionId;+ if (typeof credentialId !== "string") throw conflict("Use a saved AgentMail account for this inbox");+ await emailConnectionService(txDb).get(loaded.issue.companyId, credentialId, { userId });+ return txInteractions.resolveConnectionIntent(loaded.issue, interactionId, {+ version: 1, outcome: "connected", connectionId: selectedConnection.id,+ instruction: "Your AgentMail inbox is ready. Use agentmail_inboxes to read its verified address and continue the user's request.",+ }, { userId });+ }+ if (selectedConnection.connectionPurpose === "channel") throw conflict("An email inbox cannot satisfy a tool connection request");if (payload.purpose === "ai" && selectedConnection.connectionPurpose !== "ai") throw conflict("Select an AI account for this authentication request");if (selectedConnection.connectionPurpose === "ai") {if (payload.purpose !== "ai") throw conflict("AI authentication cannot satisfy a tool connection request");diff --git a/server/src/services/connectors/agentmail.ts b/server/src/services/connectors/agentmail.tsindex 8c84c6fd5c..d0ca2f379f 100644--- a/server/src/services/connectors/agentmail.ts+++ b/server/src/services/connectors/agentmail.ts@@ -3,11 +3,10 @@ import type { Db } from "@paperclipai/db";import { emailSendSchema } from "@paperclipai/shared";import { emailChannelService } from "../email-channels.js";import { forbidden, notFound } from "../../errors.js";-import { instanceSettingsService } from "../instance-settings.js";const AGENTMAIL_EMAIL_CONTRACT = {description:- "Use an assigned AgentMail inbox for this task. Internal comments and final responses never send email. List inboxes, read the current email thread, explicitly send a new email child task or reply, and inspect delivery. Requires experimental email connections. A send needs a UUID idempotencyKey; preserve it and the identical payload on retry. A reply uses conversationId and replyToMessageId from thread; replyAll defaults false and excludes Bcc. Sending does not close the task.",+ "Use an assigned AgentMail inbox for this task. Internal comments and final responses never send email. List inboxes, read the current email thread, explicitly send a new email child task or reply, and inspect delivery. A send needs a UUID idempotencyKey; preserve it and the identical payload on retry. A reply uses conversationId and replyToMessageId from thread; replyAll defaults false and excludes Bcc. Sending does not close the task.",inputSchema: {type: "object",properties: {@@ -118,10 +117,6 @@ export async function executeAgentmailTool(},value: unknown,) {- if (- !(await instanceSettingsService(db).getExperimental()).enableChatConnectors- )- throw forbidden("Experimental email connections are disabled");const input = schema.parse(value);// This facade only persists intents/reads. The app's durable email worker owns execution.const service = emailChannelService(db, {diff --git a/server/src/services/email-channels.ts b/server/src/services/email-channels.tsindex 0969fecc63..d7d8b08d4c 100644--- a/server/src/services/email-channels.ts+++ b/server/src/services/email-channels.ts@@ -129,14 +129,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) {let activeTick: Promise<void> | null = null;let timer: ReturnType<typeof setInterval> | undefined;- async function enabled() {- return (await instanceSettingsService(db).getExperimental())- .enableChatConnectors;- }- async function requireEnabled() {- if (!(await enabled()))- throw forbidden("Enable experimental chat connections first");- }async function getEndpoint(id: string) {const [row] = await db.select()@@ -620,7 +612,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) {input: EmailEndpointSetupInput,actor: EmailActor,) {- await requireEnabled();const [agent] = await db.select().from(agents)@@ -797,6 +788,7 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) {input.credentialConnectionId,agent.id,actor,+ input.idempotencyKey,);} else if (controlKey) await vault(endpoint, "controlKey", controlKey);if (!controlKey) throw badRequest("AgentMail API key required");@@ -919,7 +911,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) {}async function admit(endpoint: Endpoint, value: unknown) {- await requireEnabled();await active(endpoint);const event = normalizeAgentmailEvent(value);if (!event) return;@@ -1452,7 +1443,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) {input: EmailSendInput,actor: EmailActor,): Promise<EmailPublicationSummary> {- await requireEnabled();const endpoint = await getEndpoint(input.endpointId);if (endpoint.companyId !== companyId)throw notFound("Email inbox not found");@@ -1647,7 +1637,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) {const input = send.request;let attempted = false;try {- await requireEnabled();await active(endpoint);const sourceId = input.parentIssueId ?? pub.issueId;await authorize(endpoint, sourceId, send.actor);@@ -2064,11 +2053,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) {if (ticking || stopped) return;ticking = true;try {- if (!(await enabled())) {- for (const state of sockets.values()) state.socket.close();- sockets.clear();- return;- }const endpoints = await db.select().from(chatEndpoints)@@ -2272,7 +2256,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) {if (endpoint.status === "archived")throw conflict("This inbox is disconnected");if (action === "resume") {- await requireEnabled();if (!config.activationAt)throw conflict("Complete inbox setup before resuming");await agentmailApi(await credential(endpoint), fetchImpl).getInbox(@@ -2368,7 +2351,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) {receiveMode: "websocket" | "webhook",actor: EmailActor,) {- await requireEnabled();const endpoint = await getEndpoint(id);if (endpoint.status === "archived" || !endpoint.botExternalId)throw conflict("Create a new inbox connection");@@ -2591,7 +2573,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) {};}async function assignedInboxes(companyId: string, agentId: string) {- if (!(await enabled())) return [];const rows = await db.select().from(chatEndpoints).where(and(eq(chatEndpoints.companyId, companyId), eq(chatEndpoints.assignedAgentId, agentId),eq(chatEndpoints.provider, "agentmail"), eq(chatEndpoints.status, "active"),@@ -2610,7 +2591,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) {}return {assignedInboxes,- requireEnabled,authorizeRead,setup,getEndpoint,diff --git a/server/src/services/email-connections.ts b/server/src/services/email-connections.tsindex ca272d3b06..70a8b4b186 100644--- a/server/src/services/email-connections.ts+++ b/server/src/services/email-connections.ts@@ -8,8 +8,8 @@ import {companySecrets,toolConnectionInstalls,} from "@paperclipai/db";-import type { EmailConnectionInput } from "@paperclipai/shared";-import { badRequest, forbidden, notFound } from "../errors.js";+import type { EmailConnectionInput, EmailCredentialOption } from "@paperclipai/shared";+import { badRequest, forbidden, HttpError, notFound } from "../errors.js";import { secretService } from "./secrets.js";import { toolAccessService } from "./tool-access.js";import { agentmailApi } from "./agentmail-api.js";@@ -75,6 +75,56 @@ export function emailConnectionService(}return connection;}+ async function listCredentials(companyId: string, actor: EmailActor): Promise<EmailCredentialOption[]> {+ const connections = await db.select().from(toolConnections).where(and(+ eq(toolConnections.companyId, companyId), eq(toolConnections.status, "active"),+ eq(toolConnections.enabled, true),+ ));+ const options: EmailCredentialOption[] = [];+ const candidates = connections.filter(connection => connection.config.provider === "agentmail" && connection.config.emailCredential);+ // New credentials already have verified scope metadata. Legacy credentials+ // get a bounded discovery pass: four workers share one three-second budget.+ const deadline = AbortSignal.timeout(3_000);+ const discoveryFetch: typeof fetch = (input, init) => fetchImpl(input, {+ ...init, signal: init?.signal ? AbortSignal.any([init.signal, deadline]) : deadline,+ });+ let next = 0;+ await Promise.all(Array.from({ length: Math.min(4, candidates.length) }, async () => {+ while (next < candidates.length) {+ const connection = candidates[next++];+ try {+ await get(companyId, connection.id, actor);+ } catch (error) {+ if (error instanceof HttpError && [403, 404].includes(error.status)) continue;+ throw error;+ }+ const storedScope = connection.config.emailScope;+ let scope: EmailCredentialOption["scope"] = storedScope === "organization" || storedScope === "pod" || storedScope === "inbox"+ ? storedScope : "unavailable";+ let inboxId = typeof connection.config.emailInboxId === "string" ? connection.config.emailInboxId : null;+ if (scope === "unavailable" && !deadline.aborted) {+ try {+ const saved = await credential(companyId, connection.id, actor);+ if (!deadline.aborted) {+ const identity = await agentmailApi(saved.value, discoveryFetch).whoami();+ scope = identity.scope_type;+ inboxId = identity.inbox_id ?? null;+ }+ } catch {+ // Never expose a provider body, key, hash, or secret reference.+ }+ }+ options.push({+ id: connection.id, scope, inboxId, createdAt: connection.createdAt.toISOString(),+ label: connection.name !== "AgentMail" ? connection.name+ : scope === "inbox" ? `AgentMail inbox key${inboxId ? ` · ${inboxId}` : ""}`+ : scope === "unavailable" ? "AgentMail key · unavailable" : "AgentMail account key",+ });+ }+ }));+ return options.sort((a, b) => Number(b.scope === "organization" || b.scope === "pod")+ - Number(a.scope === "organization" || a.scope === "pod") || b.createdAt.localeCompare(a.createdAt));+ }async function assertAgentAccess(companyId: string,id: string,@@ -126,7 +176,7 @@ export function emailConnectionService(input: EmailConnectionInput,actor: EmailActor,) {- await agentmailApi(input.apiKey, fetchImpl).whoami();+ const identity = await agentmailApi(input.apiKey, fetchImpl).whoami();return db.transaction(async (tx) => {const db = tx as unknown as Db;await db.execute(@@ -166,7 +216,7 @@ export function emailConnectionService(actor,);const secret = await secrets.create(companyId, {- name: `AgentMail account ${randomUUID()}`,+ name: `AgentMail ${identity.scope_type === "inbox" ? "inbox" : "account"} API key ${randomUUID().slice(0, 8)}`,provider: "local_encrypted",value: input.apiKey,});@@ -190,7 +240,7 @@ export function emailConnectionService(credentialPolicy: "shared",enabled: true,status: "active",- config: { provider: "agentmail", emailCredential: true },+ config: { provider: "agentmail", emailCredential: true, emailScope: identity.scope_type, emailInboxId: identity.inbox_id ?? null },transportConfig: {},credentialSecretRefs: [{@@ -241,6 +291,11 @@ export function emailConnectionService(actorSource: actor.localImplicit ? "local_implicit" : "session",},);+ const initialInstalls = await db.select({ id: toolConnectionInstalls.id })+ .from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, connection.id));+ await db.update(toolConnections).set({+ config: { ...connection.config, emailSetupInitialInstallIds: initialInstalls.map(install => install.id) },+ }).where(eq(toolConnections.id, connection.id));await logActivity(db, {companyId,actorType: "user",@@ -262,6 +317,7 @@ export function emailConnectionService(id: string,agentId: string,actor: EmailActor,+ setupRequestId: string,) {return db.transaction(async (tx) => {const db = tx as unknown as Db;@@ -275,26 +331,37 @@ export function emailConnectionService(),).for("update");- await emailConnectionService(db, fetchImpl).get(companyId, id, actor);+ const connection = await emailConnectionService(db, fetchImpl).get(companyId, id, actor);const tools = toolAccessService(db);const installs = await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, id));+ // Apply the setup default once, only if nobody has edited access since+ // saving the key. Install IDs detect removal/re-addition as well as new+ // agent/company grants. Later retries always preserve those edits.+ const initialIds = connection.config.emailSetupInitialInstallIds;+ const ownsInitialAccess = connection.uid === `agentmail-account-${setupRequestId}` && Array.isArray(initialIds);+ const replaceInitialAccess = ownsInitialAccess && initialIds.length === installs.length+ && installs.every(install => initialIds.includes(install.id));+ if (ownsInitialAccess) {+ const { emailSetupInitialInstallIds: _initialIds, ...config } = connection.config;+ await db.update(toolConnections).set({ config }).where(eq(toolConnections.id, id));+ }if (- installs.some(- (i) => i.targetType === "company" || i.targetId === agentId,- )+ replaceInitialAccess+ ? installs.length === 1 && installs[0].targetType === "agent" && installs[0].targetId === agentId+ : installs.some((i) => i.targetType === "company" || i.targetId === agentId))return;await tools.putConnectionInstalls(id,{installs: [- ...installs.map((i) => ({+ ...(replaceInitialAccess ? [] : installs.map((i) => ({targetType: i.targetType,targetId: i.targetId,- })),+ }))),{ targetType: "agent", targetId: agentId },],},@@ -308,12 +375,12 @@ export function emailConnectionService(companyId,actorType: "user",actorId: actor.userId ?? "board",- action: "email.connection.agent_added",+ action: replaceInitialAccess ? "email.connection.agents_updated" : "email.connection.agent_added",entityType: "tool_connection",entityId: id,details: { agentId },});});}- return { get, credential, connect, allowAgent, assertAgentAccess };+ return { get, credential, connect, listCredentials, allowAgent, assertAgentAccess };}diff --git a/tests/e2e/agentmail.spec.ts b/tests/e2e/agentmail.spec.tsindex 9af42ffd57..8b87788bda 100644--- a/tests/e2e/agentmail.spec.ts+++ b/tests/e2e/agentmail.spec.ts@@ -12,6 +12,11 @@ test("AgentMail setup and email work through the normal task conversation", asynpage,request,}) => {+ await page.setViewportSize({ width: 1440, height: 1080 });+ const settings = await request.patch("/api/instance/settings/experimental", {+ data: { enableChatConnectors: false },+ });+ expect(settings.ok()).toBeTruthy();const created = await request.post("/api/companies", {data: { name: `AgentMail browser ${Date.now()}` },});@@ -50,7 +55,12 @@ test("AgentMail setup and email work through the normal task conversation", asynlastError: null,lastSyncAt: new Date().toISOString(),};+ const organizationConnectionId = randomUUID();let connected = false;+ let reservedInbox: typeof inbox | null = null;+ const setupRequests: { idempotencyKey: string; username?: string }[] = [];+ const addressTakenError = "This email address is already in use. Choose a different address.";+ const permissionError = "AgentMail did not allow Paperclip to create an inbox-scoped API key. Check your API key permissions and AgentMail account limits, then try again.";const sends: any[] = [];const conversationId = randomUUID();const thread = {@@ -79,11 +89,54 @@ test("AgentMail setup and email work through the normal task conversation", asynpublications: [] as any[],};await page.route("**/api/instance/settings/experimental", (route) =>- fulfill(route, { enableChatConnectors: true }),+ fulfill(route, { enableChatConnectors: false }),+ );+ await page.route(`**/api/companies/${company.id}/tools/connections`, route =>+ fulfill(route, { connections: [{+ id: organizationConnectionId, name: "AgentMail", status: "active", enabled: true,+ config: { provider: "agentmail", emailCredential: true }, createdAt: "2026-09-30T14:00:00Z",+ }] }),+ );+ await page.route(`**/api/companies/${company.id}/chat-endpoints`, route =>+ fulfill(route, reservedInbox ? [{ ...reservedInbox, provider: "agentmail", assignedAgentName: agent.name,+ providerAccountLabel: reservedInbox.address }] : []),+ );+ await page.route(`**/api/tool-connections/${inbox.connectionId}`, route =>+ fulfill(route, { config: { credentialConnectionId: organizationConnectionId } }),+ );+ await page.route(`**/api/tool-connections/${organizationConnectionId}/grants`, route =>+ fulfill(route, { grants: [{ status: "active", kind: "organization" }], capabilities: { canConfigure: true } }),+ );+ await page.route(`**/api/tool-connections/${organizationConnectionId}/installs`, route =>+ fulfill(route, { installs: [{ targetType: "agent", targetId: agent.id }] }),+ );+ await page.route(`**/api/chat-endpoints/${inbox.id}/conversations`, route =>+ fulfill(route, [{ id: conversationId, externalLabel: "Customer email", issueId: task.id,+ issueTitle: task.title, issueIdentifier: task.identifier, state: "active" }]),+ );+ await page.route(`**/api/chat-endpoints/${inbox.id}/activity?*`, route =>+ fulfill(route, { items: [{ id: randomUUID(), kind: "delivery", status: "processed",+ summary: "Email received", createdAt: new Date().toISOString() }], nextCursor: null }),);await page.route("**/api/**/email/**", async (route) => {const url = new URL(route.request().url()),method = route.request().method();+ if (url.pathname.endsWith("/connections") && method === "GET") return fulfill(route, [+ { id: organizationConnectionId, label: "AgentMail account key", scope: "organization", createdAt: "2026-09-30T14:00:00Z" },+ { id: inbox.connectionId, label: "AgentMail inbox key", scope: "inbox", createdAt: "2026-10-01T14:00:00Z" },+ ]);+ if (url.pathname.endsWith("/connections") && method === "POST") {+ expect(route.request().postDataJSON()).toMatchObject({ apiKey: "inbox-test-key", agentIds: [agent.id], allAgents: false });+ return fulfill(route, { id: inbox.connectionId }, 201);+ }+ if (url.pathname.endsWith("/check-address")) {+ const body = route.request().postDataJSON();+ return fulfill(route, { address: `${body.username}@${body.domain}`, status: body.username === "taken" ? "taken" : "unknown" });+ }+ if (url.pathname.endsWith(`/connections/${inbox.connectionId}/inspect`))+ return fulfill(route, {+ scope: { scope_type: "inbox" }, inboxes: [{ inbox_id: inbox.address }], domains: [],+ });if (url.pathname.endsWith("/inspect"))return fulfill(route, {scope: { scope_type: "organization" },@@ -97,11 +150,22 @@ test("AgentMail setup and email work through the normal task conversation", asyn],});if (url.pathname.endsWith("/inboxes") && method === "GET")- return fulfill(route, connected ? [inbox] : []);+ return fulfill(route, connected ? [inbox] : reservedInbox ? [reservedInbox] : []);if (url.pathname.endsWith("/inboxes") && method === "POST") {const body = route.request().postDataJSON();expect(body.receiveMode).toBe("websocket");expect(body.assignedAgentId).toBe(agent.id);+ expect(body.credentialConnectionId).toBe(organizationConnectionId);+ setupRequests.push(body);+ if (setupRequests.length === 1) return fulfill(route, { error: addressTakenError, code: "agentmail_address_taken",+ details: { field: "username", providerStatus: 403, operation: "create_inbox" } }, 409);+ if (setupRequests.length === 2) {+ reservedInbox = { ...inbox, id: body.idempotencyKey, address: `${body.username}@${body.domain}`, status: "draft" };+ return fulfill(route, {+ error: permissionError,+ details: { code: "agentmail_request_failed", providerStatus: 403, operation: "create_inbox_key" },+ }, 422);+ }connected = true;return fulfill(route, inbox, 201);}@@ -129,64 +193,118 @@ test("AgentMail setup and email work through the normal task conversation", asynprovider: "agentmail",setup: { step: "complete" },capabilities: {},+ assignedAgentName: agent.name,botExternalId: inbox.address,}),);- await page.goto(- `/${company.issuePrefix}/apps/chat/connect?provider=agentmail&connectionId=${inbox.connectionId}`,- );+ await page.goto(`/${company.issuePrefix}/apps`);+ await page.getByRole("button", { name: /^(Connect|Add connection) AgentMail$/ }).click();await expect(page.getByRole("heading", { name: "Give an agent an email address" }),).toBeVisible();- await page.getByRole("combobox").click();- await page.getByPlaceholder("Search all agents…").fill("Mail agent");- await page.getByRole("option", { name: "Mail agent" }).click();- await expect(- page.getByText("Mail agent is not a low-trust agent"),- ).toBeVisible();- await page.getByRole("button", { name: "Configure low trust" }).click();+ await page.getByLabel("Agent", { exact: true }).click();+ await page.getByPlaceholder("Filter agents").fill("Mail agent");+ await expect(page.getByRole("button", { name: "Select Mail agent", exact: true }).locator('[data-slot="agent-avatar"]')).toBeVisible();+ await page.getByRole("button", { name: "Select Mail agent", exact: true }).click();+ await expect(page.locator('#email-agent [data-slot="agent-avatar"]')).toBeVisible();+ await expect(page.getByLabel("API key", { exact: true })).toHaveValue(organizationConnectionId);+ // A deliberately selected restricted key stays at credentials until the user+ // chooses a usable account key or explicitly requests that existing inbox.+ await page.getByLabel("API key", { exact: true }).selectOption(inbox.connectionId);+ await page.getByRole("button", { name: "Continue", exact: true }).click();+ await expect(page.getByText(`That key only connects ${inbox.address}.`, { exact: false })).toBeVisible();+ await expect(page.getByLabel("Mail agent’s email address", { exact: true })).toHaveCount(0);+ await page.screenshot({ path: test.info().outputPath("agentmail-inbox-key-recovery.png"), fullPage: true });+ await page.getByLabel("API key", { exact: true }).selectOption(organizationConnectionId);+ await page.getByRole("button", { name: "Continue", exact: true }).click();+ const addressField = page.getByLabel("Mail agent’s email address", { exact: true });+ await expect(addressField).toBeEditable();+ await expect(page.getByRole("heading", { name: "How it Works", exact: true })).toBeVisible();+ await expect(page.getByLabel("Email domain", { exact: true })).toHaveValue("verified.example.test");+ await page.getByLabel("Email domain", { exact: true }).selectOption("agentmail.to");+ await expect(page.getByLabel("Email domain", { exact: true })).toHaveValue("agentmail.to");+ await page.getByLabel("Email domain", { exact: true }).selectOption("verified.example.test");+ await addressField.fill("taken");+ await expect(page.getByRole("alert")).toHaveText(addressTakenError);+ expect(setupRequests).toHaveLength(0);+ await page.getByRole("button", { name: "[email protected]", exact: true }).click();+ await expect(addressField).toHaveValue("taken-agent");+ await expect(page.getByRole("alert")).toHaveCount(0);+ await addressField.fill("mail-agent");+ await expect(page.getByRole("button", { name: "Review email address" })).toHaveCount(0);+ await page.getByText("Advanced options", { exact: true }).click();+ await expect(page.getByLabel("Email domain", { exact: true }).locator("option", { hasText: "verified.example.test" })).toHaveCount(1);+ await page.getByRole("button", { name: "Review trust settings" }).click();const trustDialog = page.getByRole("dialog");- await trustDialog- .getByRole("combobox")- .first()- .selectOption("low_trust_review");+ await trustDialog.getByRole("combobox").first().selectOption("low_trust_review");await trustDialog.getByRole("combobox").nth(1).selectOption("root_issue");await trustDialog.getByRole("combobox").nth(2).selectOption(task.id);- await trustDialog- .getByRole("button", { name: "Save trust settings" })- .click();+ await trustDialog.getByRole("button", { name: "Save trust settings" }).click();await expect(page.getByText("Low-trust review configured")).toBeVisible();await page.getByRole("button", { name: "Review trust settings" }).click();await page.getByRole("dialog").getByRole("combobox").first().selectOption("standard");await page.getByRole("button", { name: "Save trust settings" }).click();- await expect(page.getByText("Mail agent is not a low-trust agent")).toBeVisible();+ await expect(trustDialog).not.toBeVisible();const savedAgent = await (await request.get(`/api/agents/${agent.id}`)).json();expect(savedAgent.permissions.authorizationPolicy).toEqual({});- await page.getByRole("button", { name: "Continue", exact: true }).click();+ await expect(page.getByRole("link", { name: "Set up allowlists ↗" })).toHaveAttribute(+ "href", "https://docs.agentmail.to/knowledge-base/allowlists-blocklists");await page.getByText("Advanced options", { exact: true }).click();- await expect(- page- .getByLabel("Domain", { exact: true })- .locator("option", { hasText: "verified.example.test" }),- ).toHaveCount(1);- await page.getByRole("radio", { name: "Use an existing inbox" }).click();- await page.getByLabel("Available inbox").selectOption(inbox.address);- await page.getByRole("button", { name: "Review email address" }).click();- await expect(- page.getByText("Anyone can email an unrestricted inbox"),- ).toBeVisible();- await expect(- page.getByRole("link", { name: "Set up allowlists ↗" }),- ).toHaveAttribute(- "href",- "https://docs.agentmail.to/knowledge-base/allowlists-blocklists",- );- await page- .getByRole("button", { name: "Connect email address", exact: true })- .click();- await expect(- page.getByRole("heading", { name: "Your agent’s email is ready" }),- ).toBeVisible();+ await page.getByRole("button", { name: "Create email address", exact: true }).click();+ await expect(page.getByRole("alert")).toHaveText(addressTakenError);+ await expect(addressField).toHaveAttribute("aria-invalid", "true");+ await expect(page.getByRole("button", { name: "Create email address", exact: true })).toBeDisabled();+ await page.screenshot({ path: test.info().outputPath("agentmail-address-taken.png"), fullPage: true });+ await addressField.fill("mail-agent-free");+ await expect(page.getByRole("alert")).toHaveCount(0);+ await page.reload();+ await expect(addressField).toHaveValue("mail-agent-free");+ await page.getByRole("button", { name: "Create email address", exact: true }).click();+ await expect(page.getByText(permissionError, { exact: true })).toBeVisible();+ await expect(page.getByText("Internal server error", { exact: true })).toHaveCount(0);+ await expect(page.getByRole("heading", { name: "Your agent’s email is ready" })).toHaveCount(0);+ await page.screenshot({ path: test.info().outputPath("agentmail-permission-denied.png"), fullPage: true });+ await page.getByRole("link", { name: "Connectors", exact: true }).click();+ await page.getByRole("button", { name: "Finish setup", exact: true }).click();+ await expect(page.getByText("[email protected]", { exact: true })).toBeVisible();+ await expect(addressField).toHaveCount(0);+ await expect(page.getByRole("button", { name: "Choose a different address", exact: true })).toBeVisible();+ await page.getByRole("button", { name: "Finish connecting", exact: true }).click();+ await expect(page.getByRole("heading", { name: "Your agent’s email is ready" })).toBeVisible();+ expect(setupRequests.map(input => input.username)).toEqual(["mail-agent", "mail-agent-free", undefined]);+ expect(setupRequests[2]).toMatchObject({ inboxId: "[email protected]" });+ expect(new Set(setupRequests.map(input => input.idempotencyKey)).size).toBe(1);+ await page.getByRole("button", { name: "Email settings", exact: true }).click();+ await expect(page.getByRole("heading", { name: inbox.address, exact: true })).toBeVisible();+ const navigation = page.getByRole("navigation", { name: "Chat connection" });+ await navigation.getByRole("link", { name: "Access", exact: true }).click();+ await expect(page.getByText("Any human in the organization", { exact: true })).toBeVisible();+ await expect(page.getByRole("button", { name: "Reconnect inbox", exact: true })).toHaveCount(0);+ await navigation.getByRole("link", { name: "Conversations", exact: true }).click();+ await expect(page.getByRole("list", { name: "Conversations" })).toBeVisible();+ await expect(page.getByRole("link", { name: "Open task", exact: true })).toHaveAttribute("href", `/${company.issuePrefix}/issues/${task.id}`);+ await page.reload();+ await expect(page.getByRole("list", { name: "Conversations" })).toBeVisible();+ await navigation.getByRole("link", { name: "Activity", exact: true }).click();+ await expect(page.getByText("Email received", { exact: true })).toBeVisible();+ await expect(page.getByRole("heading", { name: "Connection activity", exact: true })).toBeVisible();+ await page.screenshot({ path: test.info().outputPath("agentmail-management-tabs.png"), fullPage: true });+ await navigation.getByRole("link", { name: "Settings", exact: true }).click();+ await expect(page.getByRole("heading", { name: "Receiving email", exact: true })).toBeVisible();+ const copyAddress = page.getByRole("button", { name: "Copy email address", exact: true });+ await expect(copyAddress).toHaveText(inbox.address);+ await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);+ await copyAddress.click();+ await expect(page.getByRole("status").filter({ hasText: "Copied!" })).toHaveCSS("opacity", "1");+ expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(inbox.address);+ await expect(page.getByRole("link", { name: "View inbox", exact: true })).toHaveAttribute(+ "href", `https://console.agentmail.to/dashboard/inboxes/${encodeURIComponent(inbox.address)}`);+ await page.screenshot({ path: test.info().outputPath("agentmail-settings-copy-inbox.png"), fullPage: true });+ await expect(page.getByLabel("New API key", { exact: true })).not.toBeVisible();+ await page.locator("summary").filter({ hasText: "Reconnect inbox" }).click();+ await expect(page.getByLabel("New API key", { exact: true })).toBeVisible();+ await expect(page.getByRole("button", { name: "Reconnect inbox", exact: true })).toBeVisible();+ await page.screenshot({ path: test.info().outputPath("agentmail-settings-reconnect.png"), fullPage: true });await page.goto(`/${company.issuePrefix}/issues/${task.identifier}`);const email = page.getByRole("article", { name: "Email received", exact: true });await expect(email).toBeVisible();diff --git a/tests/e2e/chat-adapters-ui-providers.spec.ts b/tests/e2e/chat-adapters-ui-providers.spec.tsindex 7d37d75b4b..4b8cfca57d 100644--- a/tests/e2e/chat-adapters-ui-providers.spec.ts+++ b/tests/e2e/chat-adapters-ui-providers.spec.ts@@ -165,12 +165,13 @@ test.describe.serial("native chat adapter UI", () => {).toBeVisible();await page.goto(`/${seed.prefix}/apps/chat/endpoint-github/settings`);await expect(page).toHaveURL(new RegExp(`/${seed.prefix}/apps$`));- await expect.poll(() => mock.chatEndpointListReads).toBe(0);+ await expect.poll(() => mock.chatEndpointListReads).toBeGreaterThan(0);+ await expect(page.getByRole("button", { name: "Connect AgentMail", exact: true })).toBeVisible();expect(mock.createdWithAgentId).toBeNull();});for (const enabled of [false, true]) {- test(`Agent Channels: one heading and current experiment gate (${enabled})`, async ({+ test(`Agent Channels: default email surface and experimental providers (${enabled})`, async ({page,}) => {const github = PROVIDERS.find(@@ -185,21 +186,18 @@ test.describe.serial("native chat adapter UI", () => {name: "Channels",exact: true,});- if (enabled) {- await expect(page).toHaveURL(/\/channels$/);- await expect(channelsHeading).toHaveCount(1);- await expect(channelsHeading).toBeVisible();- await expect(- page.getByRole("link", { name: "Connect a channel" }),- ).toBeVisible();- await expect.poll(() => mock.chatEndpointListReads).toBeGreaterThan(0);- } else {- await expect(page).toHaveURL(/\/overview$/);- await expect(channelsHeading).toHaveCount(0);- await expect(- page.getByRole("link", { name: "Channels", exact: true }),- ).toHaveCount(0);- expect(mock.chatEndpointListReads).toBe(0);+ await expect(page).toHaveURL(/\/channels$/);+ await expect(channelsHeading).toHaveCount(1);+ await expect(channelsHeading).toBeVisible();+ await expect(+ page.getByRole("link", { name: "Connect a channel" }),+ ).toBeVisible();+ await expect(+ page.getByRole("navigation", { name: "Maya navigation" }).getByRole("link", { name: "Channels", exact: true }),+ ).toBeVisible();+ await expect.poll(() => mock.chatEndpointListReads).toBeGreaterThan(0);+ if (!enabled) {+ await expect(page.getByText("Connect AgentMail from Connectors.", { exact: true })).toBeVisible();}});}diff --git a/tests/e2e/connection-intents.spec.ts b/tests/e2e/connection-intents.spec.tsindex c3dce4e7ff..591ea51e20 100644--- a/tests/e2e/connection-intents.spec.ts+++ b/tests/e2e/connection-intents.spec.ts@@ -1,6 +1,7 @@import { expect, test, type APIRequestContext } from "@playwright/test";import { createServer, type Server } from "node:http";import { listenOnFetchAllowedPort } from "./fetch-allowed-port";+import { send } from "./agent-chat.shared";type Json = Record<string, unknown>;type Seed = { companyId: string; prefix: string };@@ -178,6 +179,76 @@ function escapeRegExp(value: string) {return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");}+test("AgentMail request shows a durable inline key card in agent chat", async ({ page, request }, testInfo) => {+ test.setTimeout(120_000);+ const settings = await json(await request.get("/api/instance/settings/experimental"));+ try {+ await json(await request.patch("/api/instance/settings/experimental", { data: {+ enableAgentChat: true, enableChatConnectors: true, enableClassicTaskInterface: false,+ } }));+ const seed = await newCompany(request);+ const agent = await createAgent(request, seed.companyId, "Email requester");+ // Script only the agent's choice of tool; persistence, routes, and UI are real.+ const script = `+const headers = { authorization: "Bearer " + process.env.PAPERCLIP_API_KEY, "content-type": "application/json", "x-paperclip-run-id": process.env.PAPERCLIP_RUN_ID };+const runResponse = await fetch(process.env.PAPERCLIP_API_URL + "/api/heartbeat-runs/" + process.env.PAPERCLIP_RUN_ID, { headers });+if (!runResponse.ok) throw new Error(await runResponse.text());+const run = await runResponse.json();+if (run.contextSnapshot?.interactionId) process.exit(0);+const post = async (url, body) => {+ const response = await fetch(url, { method: "POST", headers: { authorization: "Bearer " + process.env.PAPERCLIP_RUNTIME_TOOLS_TOKEN, "content-type": "application/json" }, body: JSON.stringify(body) });+ if (!response.ok) throw new Error(await response.text());+ return response.json();+};+const search = await post(process.env.PAPERCLIP_RUNTIME_TOOLS_CONNECTIONS_SEARCH_URL, { query: "Get yourself an email address with AgentMail" });+if (!search.results.some(result => result.service === "agentmail") || !search.instruction.includes("connection_request")) throw new Error("AgentMail card was not advertised");+const result = await post(process.env.PAPERCLIP_RUNTIME_TOOLS_CONNECTION_REQUEST_URL, { service: "agentmail" });+if (result.state !== "needs_user_action") throw new Error("Expected an inline card");+`;+ await json(await request.patch(`/api/agents/${agent.id}`, { data: {+ adapterConfig: { command: process.execPath, args: ["--input-type=module", "-e", script] }, replaceAdapterConfig: true,+ } }));+ await page.goto(`/${seed.prefix}/chats/${agent.id}`);+ await send(page, "Get yourself an email address with AgentMail.");+ await waitForAgentRun(request, seed.companyId, agent.id);+ const chat = await json<{ id: string }>(await request.get(`/api/companies/${seed.companyId}/chats/${agent.id}`));+ const interactions = await json<Array<{ id: string; kind: string; status: string; addresseeUserId: string; payload: Json }>>(+ await request.get(`/api/issues/${chat.id}/interactions`),+ );+ expect(interactions).toHaveLength(1);+ expect(interactions[0]).toMatchObject({ kind: "connection_intent", status: "pending", addresseeUserId: "local-board",+ payload: { purpose: "channel", serviceSlug: "agentmail", requestingAgentId: agent.id } });+ await page.reload();+ const form = page.getByTestId("agentmail-inline-setup");+ await expect(form).toBeVisible();+ await expect(form.locator("input")).toHaveCount(1);+ await expect(form.getByLabel("API key")).toHaveAttribute("type", "password");+ await expect(form.getByRole("link", { name: "Get an AgentMail API key" })).toHaveAttribute("href", "https://console.agentmail.to/dashboard/api-keys");+ await expect(form.locator('[role="radiogroup"], [role="combobox"], select')).toHaveCount(0);+ await expect(page.getByRole("dialog")).toHaveCount(0);+ await expect(form.getByRole("button", { name: "Connect AgentMail" })).toBeDisabled();+ const card = page.getByTestId("connection-intent-focus-target");+ await card.screenshot({ path: testInfo.outputPath("agentmail-inline-card.png") });+ await page.setViewportSize({ width: 390, height: 844 });+ await expect(form).toBeVisible();+ await card.screenshot({ path: testInfo.outputPath("agentmail-inline-card-mobile.png") });+ await form.getByRole("button", { name: "Not now" }).click();+ await expect(form).toHaveCount(0);+ await expect.poll(async () => {+ const rows = await json<Array<{ status: string }>>(await request.get(`/api/issues/${chat.id}/interactions`));+ return rows.map(row => row.status);+ }).toEqual(["rejected"]);+ expect(await json(await request.get(`/api/companies/${seed.companyId}/email/inboxes`))).toEqual([]);+ const connections = await json<{ connections: unknown[] }>(await request.get(`/api/companies/${seed.companyId}/tools/connections`));+ expect(connections.connections).toEqual([]);+ } finally {+ await json(await request.patch("/api/instance/settings/experimental", { data: {+ enableAgentChat: settings.enableAgentChat, enableChatConnectors: settings.enableChatConnectors,+ enableClassicTaskInterface: settings.enableClassicTaskInterface,+ } }));+ }+});+async function waitForAgentRun(request: APIRequestContext,companyId: string,diff --git a/tests/runner-e2e/EVERYDAY-WORKFLOWS.md b/tests/runner-e2e/EVERYDAY-WORKFLOWS.mdindex 938647cabe..cec2fe6fb5 100644--- a/tests/runner-e2e/EVERYDAY-WORKFLOWS.md+++ b/tests/runner-e2e/EVERYDAY-WORKFLOWS.md@@ -15,6 +15,7 @@ exact execution ID explicitly.| Hire a teammate and use them again | `hire-reuse` | One Morgan QA reporting to the lead, native runner and the same encrypted connection bindings, real child execution, then a second usable delivery from that same agent. || Decide on an installed service action | `service-approve`, `service-decline` | Assign an authenticated local MCP fixture with Ask first; match its tool action and connection ID; no provider call before approval; exactly one after approval and a verified document; none after decline. || Decline a new connection | `connection-decline` | Start without service connections; match a Notion connection intent; click Not now; verify the saved rejection, no new connection or repeated request, and an explanation followed by Done. |+| Request an email address | `agentmail-setup` | Enable Chat connectors, ask for an email address, and require a durable AgentMail card for the requesting agent and user. Reload and verify one password field, the direct API-key link, and no access selectors or modal. Decline and verify no connection or repeated request. || Continue work after a controller restart | `recover-controller` | Observe saved source, persist a user message, restart the isolated controller, and independently test the delivered result. || Stop work and change direction | `stop-redirect` | Click Stop, send one new request, reload, observe exactly one stored user message and the new answer, and reach Done. || Create and edit a company skill | `create-skill-studio` | Create one skill through the runner, verify its persisted library entry and activity-feed card, open Skill Studio, save an edit, and verify the edit after returning. Local Codex, local ACPX Claude, and warm Daytona cells are explicit. |@@ -36,8 +37,8 @@ See [controlled recovery tests](../runner-recovery/README.md).## Matrix and running-The local matrix has nine cases on native Codex `gpt-5.6-sol`, native ACPX Claude-`claude-sonnet-5`, and native Codex `gpt-5.4-mini`: 27 cells. The two core profiles+The local matrix has fourteen cases on native Codex `gpt-5.6-sol`, native ACPX Claude+`claude-sonnet-5`, and native Codex `gpt-5.4-mini`: 42 cells. The two core profilesalso declare build/revise, delegation, controller-restart, and skill-creation caseson Daytona: eight cells. Remote runner-process killing is not supported. For remote controllerrestart, a verified first download supplies the persistence checkpoint; the@@ -200,7 +201,19 @@ identity check.## External-provider fallbackThree explicit local cases cover aggregator routing with the normal production-agent guidance. They add nine local cells; the suite now has 47 cells total.+agent guidance. They add nine local cells. The AgentMail setup case adds three+local cells; the suite now has 50 cells total.++The AgentMail case uses real model discovery and production interaction/UI paths,+but declines before sending credentials to AgentMail. Its independent grader is+calibrated against missing, duplicate, misaddressed, hidden, and malformed cards.+The email integration suite separately proves credential/inbox creation, access+defaults, assignment checks, and completion using a fixture provider. Neither+test qualifies live AgentMail delivery. Run a bounded local model cell with:++```sh+pnpm test:e2e:runner -- --id everyday-workflows.runner-codex-mini.local.agentmail-setup --max-automatic-retries 0+```- `provider-native`: Jira is supported natively and by aggregators. Require theJira connection card directly, decline it in the browser, and verify no providerdiff --git a/tests/runner-e2e/agentmail-setup-evidence.test.ts b/tests/runner-e2e/agentmail-setup-evidence.test.tsnew file mode 100644index 0000000000..24779c84b2--- /dev/null+++ b/tests/runner-e2e/agentmail-setup-evidence.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from "vitest";+import { gradeAgentmailSetup } from "./agentmail-setup-evidence.js";++const good = {+ interactions: [{ id: "card", kind: "connection_intent", status: "pending", addresseeUserId: "user",+ payload: { serviceSlug: "agentmail", purpose: "channel", requestingAgentId: "agent" } }],+ agentId: "agent", userId: "user", visible: true, inputTypes: ["password"],+ keyLink: "https://console.agentmail.to/dashboard/api-keys", accessSelectorCount: 0, dialogCount: 0,+};+describe("AgentMail setup oracle", () => {+ it("accepts the persisted inline credential form", () => {+ expect(gradeAgentmailSetup(good).every(check => check.passed)).toBe(true);+ });+ it.each([+ { interactions: [] }, // The original search + prose link failure.+ { interactions: [good.interactions[0], good.interactions[0]] },+ { agentId: "another-agent" },+ { userId: "another-user" },+ { visible: false },+ { inputTypes: ["text"] },+ { inputTypes: ["password", "text"] },+ { keyLink: "https://console.agentmail.to" },+ { keyLink: null },+ { accessSelectorCount: 2 },+ { dialogCount: 1 },+ ])("rejects incomplete or misleading evidence: %j", bad => {+ expect(gradeAgentmailSetup({ ...good, ...bad }).some(check => !check.passed)).toBe(true);+ });+});diff --git a/tests/runner-e2e/agentmail-setup-evidence.ts b/tests/runner-e2e/agentmail-setup-evidence.tsnew file mode 100644index 0000000000..fd31651916--- /dev/null+++ b/tests/runner-e2e/agentmail-setup-evidence.ts@@ -0,0 +1,25 @@+/** Independent browser + durable-state evidence, never the agent's claim. */+export function gradeAgentmailSetup(input: {+ interactions: Array<{ id: string; kind: string; status: string; addresseeUserId?: string | null; payload?: { serviceSlug?: string; purpose?: string; requestingAgentId?: string } }>;+ agentId: string;+ userId: string;+ visible: boolean;+ inputTypes: string[];+ keyLink: string | null;+ accessSelectorCount: number;+ dialogCount: number;+}) {+ const pending = input.interactions.filter(row => row.status === "pending");+ const card = pending[0];+ return [+ { id: "agentmail-durable-request", passed: pending.length === 1 && card?.kind === "connection_intent"+ && card.payload?.serviceSlug === "agentmail" && card.payload.purpose === "channel"+ && card.payload.requestingAgentId === input.agentId && card.addresseeUserId === input.userId,+ detail: "One saved AgentMail inbox request addresses the user for the requesting agent." },+ { id: "agentmail-inline-key-only", passed: input.visible && input.dialogCount === 0+ && input.inputTypes.length === 1 && input.inputTypes[0] === "password" && input.accessSelectorCount === 0,+ detail: "The thread shows one password field inline without an access step or modal." },+ { id: "agentmail-direct-key-link", passed: input.keyLink === "https://console.agentmail.to/dashboard/api-keys",+ detail: "Credential help opens the exact AgentMail API-key page." },+ ];+}diff --git a/tests/runner-e2e/catalog.test.ts b/tests/runner-e2e/catalog.test.tsindex 3bf098ded5..b22f2e227a 100644--- a/tests/runner-e2e/catalog.test.ts+++ b/tests/runner-e2e/catalog.test.ts@@ -136,10 +136,10 @@ describe("runner E2E catalog", () => {expect(localIntegrityTasks).toHaveLength(2);expect(openRouterBreadthTasks).toHaveLength(3);expect(runnerSuites.map((suite) => suite.expectedMatrixSize)).toEqual([- 6, 30, 3, 16, 16, 2, 6, 8, 46, 23, 47, 20, 52, 28, 18, 6, 6, 12, 10, 48, 16, 10, 2, 1, 1,+ 6, 30, 3, 16, 16, 2, 6, 8, 46, 23, 50, 20, 52, 28, 18, 6, 6, 12, 10, 48, 16, 10, 2, 1, 1,]);- expect(validateRunnerCatalog()).toHaveLength(433);- expect(new Set(runnerMatrix.map((entry) => entry.id)).size).toBe(433);+ expect(validateRunnerCatalog()).toHaveLength(436);+ expect(new Set(runnerMatrix.map((entry) => entry.id)).size).toBe(436);expect(runnerMatrix.filter((entry) => entry.suite.id === "core-compatibility"),).toHaveLength(48);diff --git a/tests/runner-e2e/catalog.ts b/tests/runner-e2e/catalog.tsindex baf0939565..b94cf60b70 100644--- a/tests/runner-e2e/catalog.ts+++ b/tests/runner-e2e/catalog.ts@@ -1186,11 +1186,11 @@ export const runnerSuites: readonly RunnerSuiteFixture[] = [id: "everyday-workflows", label: "Everyday Paperclip Work", manualOnly: true,description: "Real user requests, useful downloaded work, and durable continuation using production instructions.",groups: ["native"], profiles: everydayProfiles, environments: [localEnvironment, daytonaWarmEnvironment],- tasks: everydayTasks, expectedMatrixSize: 47,+ tasks: everydayTasks, expectedMatrixSize: 50,excludedExecutionIds: [...everydayProfiles.flatMap(profile => everydayTasks.filter(task => !["build-revise", "delegate-feedback", "recover-controller", "create-skill-studio"].includes(task.id)).map(task => `everyday-workflows.${profile.id}.daytona.${task.id}`))],- definitionMetadata: { version: 3, instructions: "production", grading: "outcome-and-invariants", scheduling: "explicit-only" },+ definitionMetadata: { version: 4, instructions: "production", grading: "outcome-and-invariants", scheduling: "explicit-only" },},{id: "context-integrity",diff --git a/tests/runner-e2e/everyday-cases.ts b/tests/runner-e2e/everyday-cases.tsindex cbc709a073..51bf0de2ee 100644--- a/tests/runner-e2e/everyday-cases.ts+++ b/tests/runner-e2e/everyday-cases.ts@@ -32,6 +32,7 @@ export const SLUGIFY_REVISION = `Add an optional --separator argument that accepexport const LATE_REQUIREMENT = `Also support --max-length as a positive integer. Truncate the final slug to that length, then remove any trailing separator. In particular, input " Queue--Ready!! " with --max-length 7 must print "queue-r". Preserve the default behavior.`;const definitions = [+ ["agentmail-setup", "Request an AgentMail inbox in the thread", "I'd like you to acquire an email address with AgentMail and tell me the address once it exists. If I choose Not now, explain that no inbox was created and finish without connecting.", 2],["provider-decline", "Decline external providers", "Connect HubSpot so you can read my recent contacts. If I choose None for now, explain that you could not retrieve the contacts and finish without connecting.", 2],["provider-second", "Choose and reuse the second external provider", "Connect HubSpot and read my recent contacts. Report the contact names and verification code returned by the service.", 2],["provider-native", "Prefer a built-in connection over external providers", "Connect Jira so you can read my recent issues. If I choose Not now, explain that you could not retrieve the issues and finish without connecting.", 2],diff --git a/tests/runner-e2e/everyday-flow.ts b/tests/runner-e2e/everyday-flow.tsindex 1fc1a11851..b9f23d1f47 100644--- a/tests/runner-e2e/everyday-flow.ts+++ b/tests/runner-e2e/everyday-flow.ts@@ -1,3 +1,4 @@+import { gradeAgentmailSetup } from "./agentmail-setup-evidence.js";import { expect, type Page } from "@playwright/test";import { runnerApiToolsEnabled } from "../../server/src/services/native-runtime/runner-api-rollout.js";import { spawn } from "node:child_process";@@ -161,7 +162,8 @@ export async function runEverydayFlow(input: Input) {const providerChoice = caseId === "provider-decline" || caseId === "provider-second";const nativeProviderCase = caseId === "provider-native";let aggregatorFixture: Awaited<ReturnType<typeof setupAggregatorFixture>> | undefined;- const decliningConnection = caseId === "connection-decline" || nativeProviderCase;+ const agentmailSetup = caseId === "agentmail-setup";+ const decliningConnection = caseId === "connection-decline" || nativeProviderCase || agentmailSetup;const declining = decliningConnection || caseId === "service-decline";let decisionId: string | undefined;let decisionResolvedAt: string | undefined;@@ -549,6 +551,7 @@ export async function runEverydayFlow(input: Input) {"everyday-decisions.ts","aggregator-fixture.ts","connection-routing-evidence.ts",+ "agentmail-setup-evidence.ts","everyday-delivery.ts","everyday-observations.ts","everyday-artifact.py",@@ -650,6 +653,7 @@ export async function runEverydayFlow(input: Input) {const state = await api.get<{connections:Row[]}>(`/api/companies/${fixtures.company.id}/tools/connections`);initialConnections = state.connections.map(c=>c.id);}+ if (agentmailSetup) await api.patch("/api/instance/settings/experimental", { enableChatConnectors: true });if (decliningConnection) {const state = await api.get<{ connections: Row[] }>(`/api/companies/${fixtures.company.id}/tools/connections`,@@ -952,7 +956,7 @@ export async function runEverydayFlow(input: Input) {interactions.interactions,review? { kind: "tool", connectionId: review.connectionId }- : { kind: "connection", serviceSlug: nativeProviderCase ? "jira" : "notion" },+ : { kind: "connection", serviceSlug: agentmailSetup ? "agentmail" : nativeProviderCase ? "jira" : "notion" },);await expect(page.getByRole("button", {@@ -971,8 +975,28 @@ export async function runEverydayFlow(input: Input) {true,review? "Tool approval belongs to the installed page service."- : `New connection request is for ${nativeProviderCase ? "Jira" : "Notion"}, without an external-provider question.`,+ : `New connection request is for ${agentmailSetup ? "AgentMail" : nativeProviderCase ? "Jira" : "Notion"}, without an external-provider question.`,);+ if (agentmailSetup) {+ // Reload proves the card is durable, rather than a transient model UI.+ await page.reload();+ const form = page.getByTestId("agentmail-inline-setup");+ await expect(form).toBeVisible();+ const card = page.getByTestId("connection-intent-focus-target").filter({ has: form });+ const rows = await api.get<Parameters<typeof gradeAgentmailSetup>[0]["interactions"]>(`/api/issues/${parent!.id}/interactions`);+ const checks = gradeAgentmailSetup({+ // This harness boots a dedicated local_trusted instance.+ interactions: rows, agentId: fixtures.agent.id, userId: "local-board",+ visible: await form.isVisible(),+ inputTypes: await card.locator("input").evaluateAll(inputs => inputs.map(input => input.getAttribute("type") ?? "text")),+ keyLink: await form.getByRole("link", { name: "Get an AgentMail API key" }).getAttribute("href"),+ accessSelectorCount: await card.locator('[role="radiogroup"], [role="combobox"], select').count(),+ dialogCount: await page.getByRole("dialog").count(),+ });+ ev.checks.push(...checks);+ await input.capture("agentmail-inline-key", "AgentMail API-key card after reload", "agentmail-inline-key.png");+ if (checks.some(result => !result.passed)) throw new Error("AgentMail inline setup evidence failed");+ }if (review)check("no-call-before-approval",diff --git a/tests/runner-e2e/everyday.test.ts b/tests/runner-e2e/everyday.test.tsindex c1322eb794..3afd8735fa 100644--- a/tests/runner-e2e/everyday.test.ts+++ b/tests/runner-e2e/everyday.test.ts@@ -212,7 +212,7 @@ describe("manual everyday workflow catalog", () => {const selected = selectRunnerExecutions(parseRunnerSelectors(["--suite", "everyday-workflows"]),);- expect(selected).toHaveLength(47);+ expect(selected).toHaveLength(50);expect(selected.every((e) => e.profile.generation === "native")).toBe(true);expect(selectRunnerExecutions(diff --git a/ui/src/api/email.ts b/ui/src/api/email.tsindex 0afe70a71f..aeeac285d3 100644--- a/ui/src/api/email.ts+++ b/ui/src/api/email.ts@@ -1,14 +1,22 @@import { api } from "./client";import type {EmailConnectionInput,+ EmailCredentialOption,ToolConnection,EmailEndpointSummary,EmailPublicationSummary,EmailThreadSummary,EmailSendInput,EmailEndpointSetupInput,+ EmailAddressCheckInput,+ EmailAddressCheckResult,} from "@paperclipai/shared";export const emailApi = {+ credentials: (companyId: string) => api.get<EmailCredentialOption[]>(`/companies/${companyId}/email/connections`),+ checkAddress: (companyId: string, connectionId: string, input: EmailAddressCheckInput, signal?: AbortSignal) =>+ api.post<EmailAddressCheckResult>(+ `/companies/${companyId}/email/connections/${connectionId}/check-address`, input, { signal },+ ),connect: (companyId: string, input: EmailConnectionInput) =>api.post<ToolConnection>(`/companies/${companyId}/email/connections`,@@ -29,6 +37,7 @@ export const emailApi = {),inspect: (companyId: string, apiKey: string) =>api.post<{+ scope: { scope_type: string };inboxes: { inbox_id: string }[];domains: { domain_id: string; domain: string; status: string }[];}>(`/companies/${companyId}/email/inspect`, { apiKey }),diff --git a/ui/src/components/AgentContextualSidebar.test.tsx b/ui/src/components/AgentContextualSidebar.test.tsxindex 0c0571b938..7b4eaa5491 100644--- a/ui/src/components/AgentContextualSidebar.test.tsx+++ b/ui/src/components/AgentContextualSidebar.test.tsx@@ -34,13 +34,13 @@ vi.mock("./SidebarNavItem", () => ({}));describe("AgentContextualSidebar", () => {- it.each([false, true])("shows agent Channels only when chat connectors are enabled (%s)", (enabled) => {+ it.each([false, true])("keeps Channels available for default email regardless of the chat setting (%s)", (enabled) => {const client = new QueryClient();client.setQueryData(queryKeys.instance.experimentalSettings, { enableChatConnectors: enabled });const markup = renderToStaticMarkup(<QueryClientProvider client={client}><MemoryRouter><AgentContextualSidebar agentRef="agent" agentId="agent-1" agentName="Agent" /></MemoryRouter></QueryClientProvider>);- expect(markup.includes('href="/agents/agent/channels"')).toBe(enabled);+ expect(markup.includes('href="/agents/agent/channels"')).toBe(true);expect(markup).toContain('href="/agents/agent/tools"');client.clear();});diff --git a/ui/src/components/AgentContextualSidebar.tsx b/ui/src/components/AgentContextualSidebar.tsxindex abddd81179..14ab6a27af 100644--- a/ui/src/components/AgentContextualSidebar.tsx+++ b/ui/src/components/AgentContextualSidebar.tsx@@ -16,7 +16,6 @@ import {} from "lucide-react";import { agentsApi } from "@/api/agents";import { useCompany } from "@/context/CompanyContext";-import { useChatConnectorsEnabled } from "@/hooks/useChatConnectorsEnabled";import { queryKeys } from "@/lib/queryKeys";import { ContextualSidebarFrame } from "./ContextualSidebarFrame";import { SidebarNavItem } from "./SidebarNavItem";@@ -60,7 +59,6 @@ export function AgentContextualSidebar({labels?: Partial<Record<AgentLocalDetailView, string>>;}) {const { selectedCompanyId } = useCompany();- const { enabled: chatConnectorsEnabled } = useChatConnectorsEnabled();const shouldResolveAgent = !agentId || !agentName;const { data: resolvedAgent } = useQuery({queryKey: [...queryKeys.agents.detail(agentRef), selectedCompanyId ?? null, "contextual-sidebar"],@@ -97,7 +95,6 @@ export function AgentContextualSidebar({</p><div data-slot="contextual-sidebar-group" className={contextualSidebarStyles.group}>{section.items- .filter((item) => item.value !== "channels" || chatConnectorsEnabled).map((item) => {const href = agentDetailHref(agentRef, item.value);return (diff --git a/ui/src/components/AgentMultiSelect.test.tsx b/ui/src/components/AgentMultiSelect.test.tsxindex 82daf82509..81353d0afa 100644--- a/ui/src/components/AgentMultiSelect.test.tsx+++ b/ui/src/components/AgentMultiSelect.test.tsx@@ -128,6 +128,18 @@ describe("AgentMultiSelect", () => {expect(document.body.querySelector('input[placeholder="Filter agents"]')).toBeNull();});+ it("uses the same agent avatar in the selected value and every option", async () => {+ const agents = [{ id: "agent-1", name: "Ralph" }, { id: "agent-2", name: "Support" }];+ root = createRoot(container);+ act(() => root?.render(<AgentSelect agents={agents} value="agent-1" onChange={vi.fn()} />));+ const selected = container.querySelector('[data-slot="agent-avatar"] img')?.getAttribute("src");+ expect(selected).toBeTruthy();+ act(() => container.querySelector("button")?.click());+ await flush();+ expect(document.querySelector('[aria-label="Select Ralph"] [data-slot="agent-avatar"] img')?.getAttribute("src")).toBe(selected);+ expect(document.querySelector('[aria-label="Select Support"] [data-slot="agent-avatar"] img')).not.toBeNull();+ });+it("previews selected agents and stages changes until save", async () => {const onSave = vi.fn();const agents = Array.from({ length: 6 }, (_, index) => ({diff --git a/ui/src/components/AgentMultiSelect.tsx b/ui/src/components/AgentMultiSelect.tsxindex 5c38fec2c3..5d14afab69 100644--- a/ui/src/components/AgentMultiSelect.tsx+++ b/ui/src/components/AgentMultiSelect.tsx@@ -1,4 +1,4 @@-import { AgentAvatar } from "@/components/AgentAvatar";+import { AgentAvatar, type AvatarAgent } from "@/components/AgentAvatar";import { useEffect, useMemo, useState, type ComponentProps, type ReactNode } from "react";import { ChevronRight } from "lucide-react";import { Button } from "@/components/ui/button";@@ -8,7 +8,7 @@ import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popoverimport { Skeleton } from "@/components/ui/skeleton";import { cn } from "@/lib/utils";-export interface AgentMultiSelectOption {+export interface AgentMultiSelectOption extends AvatarAgent {id: string;name: string;title?: string | null;@@ -63,8 +63,9 @@ export function AgentSelect({className={cn("w-full justify-between", triggerClassName)}disabled={disabled}>- <span className={cn("min-w-0 truncate", !selectedAgent && "text-muted-foreground")}>- {selectedAgent?.name ?? placeholder}+ <span className={cn("flex min-w-0 items-center gap-2", !selectedAgent && "text-muted-foreground")}>+ {selectedAgent && <AgentAvatar agent={selectedAgent} size={20} />}+ <span className="truncate">{selectedAgent?.name ?? placeholder}</span></span><ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground" /></Button>@@ -94,7 +95,7 @@ export function AgentSelect({setOpen(false);}}>- <AgentAvatar agent={agent} size={16} className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"/>+ <AgentAvatar agent={agent} size={20} className="shrink-0" /><span className="flex min-w-0 flex-col"><span className="truncate text-sm font-medium text-foreground">{agent.name}</span>{agent.title ? <span className="truncate text-xs text-muted-foreground">{agent.title}</span> : null}diff --git a/ui/src/components/ChatConnectorsExperimentalGate.test.tsx b/ui/src/components/ChatConnectorsExperimentalGate.test.tsxindex b0feae96f3..ce2741da81 100644--- a/ui/src/components/ChatConnectorsExperimentalGate.test.tsx+++ b/ui/src/components/ChatConnectorsExperimentalGate.test.tsx@@ -13,14 +13,19 @@ const api = vi.hoisted(() => ({settings: vi.fn(),list: vi.fn(),binding: vi.fn(),+ get: vi.fn(),+ provider: null as string | null,+ endpointId: undefined as string | undefined,}));vi.mock("@/api/instanceSettings", () => ({instanceSettingsApi: { getExperimental: api.settings },}));vi.mock("@/api/chatEndpoints", () => ({- chatEndpointsApi: { list: api.list, getIssueBinding: api.binding },+ chatEndpointsApi: { list: api.list, getIssueBinding: api.binding, get: api.get },}));vi.mock("@/lib/router", () => ({+ useParams: () => ({ endpointId: api.endpointId }),+ useSearchParams: () => [new URLSearchParams(api.provider ? { provider: api.provider } : {})],Navigate: ({ to }: { to: string }) => <div data-redirect={to} />,Link: ({ to, children }: { to: string; children: React.ReactNode }) => (<a href={to}>{children}</a>@@ -44,6 +49,9 @@ describe("Chat connectors visibility gate", () => {client = new QueryClient({ defaultOptions: { queries: { retry: false } } });api.settings.mockResolvedValue({ enableChatConnectors: false });api.list.mockResolvedValue([]);+ api.get.mockResolvedValue({ provider: "agentmail" });+ api.provider = null;+ api.endpointId = undefined;api.binding.mockResolvedValue(null);});afterEach(() => {@@ -82,6 +90,20 @@ describe("Chat connectors visibility gate", () => {).toBe("/apps");},);+ it("opens AgentMail setup with the experimental flag disabled", async () => {+ api.provider = "agentmail";+ await render();+ expect(container.querySelector("[data-chat-setup]")).not.toBeNull();+ expect(api.get).not.toHaveBeenCalled();+ });+ it.each(["agentmail", "slack"])("admits only default email management when chat is disabled (%s)", async (provider) => {+ api.endpointId = "endpoint-1";+ api.get.mockResolvedValue({ provider });+ await render();+ await vi.waitFor(() => expect(api.get).toHaveBeenCalledWith("endpoint-1"));+ await vi.waitFor(() => expect(Boolean(container.querySelector("[data-chat-setup]"))).toBe(provider === "agentmail"));+ if (provider !== "agentmail") expect(container.querySelector("[data-redirect]")).not.toBeNull();+ });it("waits without exposing setup, then enables the route after explicit opt-in", async () => {let resolve!: (value: unknown) => void;api.settings.mockReturnValue(@@ -127,9 +149,9 @@ describe("Chat connectors visibility gate", () => {expect(container.querySelector("[data-chat-setup]")).toBeNull();expect(api.settings).not.toHaveBeenCalled();});- it("hides cached agent channels and task bindings without fetching chat data while disabled", async () => {+ it("keeps agent email channels available but hides cached experimental chat channels and task bindings", async () => {client.setQueryData(queryKeys.chatEndpoints.list("company-1"), [- { id: "endpoint-1", assignedAgentId: "agent-1", status: "active" },+ { provider: "slack", id: "endpoint-1", assignedAgentId: "agent-1", status: "active" },]);client.setQueryData(["issue-chat-binding", "company-1", "issue-1"], {endpointId: "endpoint-1",@@ -147,8 +169,9 @@ describe("Chat connectors visibility gate", () => {),);await flushReact();- expect(container.innerHTML).toBe("");- expect(api.list).not.toHaveBeenCalled();+ expect(container.textContent).toContain("Connect AgentMail from Connectors.");+ expect(container.querySelector('a[href="/apps/chat/endpoint-1/settings"]')).toBeNull();+ expect(api.list).toHaveBeenCalledWith("company-1");expect(api.binding).not.toHaveBeenCalled();});});diff --git a/ui/src/components/ChatConnectorsExperimentalGate.tsx b/ui/src/components/ChatConnectorsExperimentalGate.tsxindex 91a8c4a3b6..e9b081c56f 100644--- a/ui/src/components/ChatConnectorsExperimentalGate.tsx+++ b/ui/src/components/ChatConnectorsExperimentalGate.tsx@@ -1,6 +1,25 @@import type { ReactNode } from "react";+import { useQuery } from "@tanstack/react-query";+import { chatEndpointsApi } from "@/api/chatEndpoints";+import { queryKeys } from "@/lib/queryKeys";+import { Button } from "@/components/ui/button";import { useChatConnectorsEnabled } from "@/hooks/useChatConnectorsEnabled";-import { Navigate } from "@/lib/router";+import { Navigate, useParams, useSearchParams } from "@/lib/router";++function DefaultEmailEndpointGate({ endpointId, children }: { endpointId: string; children: ReactNode }) {+ const endpoint = useQuery({+ queryKey: queryKeys.chatEndpoints.detail(endpointId),+ queryFn: () => chatEndpointsApi.get(endpointId),+ });+ if (endpoint.isError) return (+ <div className="space-y-3 p-6">+ <p role="alert" className="text-sm text-destructive">{endpoint.error.message}</p>+ <Button variant="outline" onClick={() => void endpoint.refetch()}>Retry</Button>+ </div>+ );+ if (!endpoint.data) return null;+ return endpoint.data.provider === "agentmail" ? <>{children}</> : <Navigate to="/apps" replace />;+}export function ChatConnectorsExperimentalGate({children,@@ -8,7 +27,12 @@ export function ChatConnectorsExperimentalGate({children: ReactNode;}) {const { enabled, loaded } = useChatConnectorsEnabled();+ const [params] = useSearchParams();+ const { endpointId } = useParams<{ endpointId: string }>();+ if (!endpointId && params.get("provider") === "agentmail") return <>{children}</>;if (!loaded) return null;- if (!enabled) return <Navigate to="/apps" replace />;+ if (!enabled) return endpointId+ ? <DefaultEmailEndpointGate endpointId={endpointId}>{children}</DefaultEmailEndpointGate>+ : <Navigate to="/apps" replace />;return <>{children}</>;}diff --git a/ui/src/components/EmailMessageCard.tsx b/ui/src/components/EmailMessageCard.tsxindex 32a4298870..be4a083e15 100644--- a/ui/src/components/EmailMessageCard.tsx+++ b/ui/src/components/EmailMessageCard.tsx@@ -6,9 +6,8 @@ import type {EmailPublicationSummary,EmailThreadSummary,} from "@paperclipai/shared";-import { emailApi } from "@/api/email";+import { useEmailThread } from "@/hooks/useEmailThread";import { issuesApi } from "@/api/issues";-import { useChatConnectorsEnabled } from "@/hooks/useChatConnectorsEnabled";const EmailContext = createContext<EmailThreadSummary | null>(null);export function EmailThreadProvider({companyId,@@ -19,13 +18,7 @@ export function EmailThreadProvider({issueId: string;children: ReactNode;}) {- const { enabled } = useChatConnectorsEnabled();- const thread = useQuery({- queryKey: ["email-thread", companyId, issueId],- queryFn: () => emailApi.thread(companyId, issueId),- enabled,- refetchInterval: enabled ? 3000 : false,- });+ const thread = useEmailThread(companyId, issueId);return (<EmailContext.Provider value={thread.data ?? null}>{children}diff --git a/ui/src/components/EmailTaskActivity.tsx b/ui/src/components/EmailTaskActivity.tsxindex 428a953085..6f442b1372 100644--- a/ui/src/components/EmailTaskActivity.tsx+++ b/ui/src/components/EmailTaskActivity.tsx@@ -1,7 +1,8 @@import { EmailMessageCard } from "./EmailMessageCard";import { useState } from "react";-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { useMutation, useQueryClient } from "@tanstack/react-query";import { emailApi } from "@/api/email";+import { useEmailThread } from "@/hooks/useEmailThread";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import type { EmailPublicationSummary } from "@paperclipai/shared";@@ -18,12 +19,7 @@ export function EmailTaskActivity({const cache = useQueryClient();const threadKey = ["email-thread", companyId, issueId];const queryEnabled = Boolean(companyId && issueId) && !issueId.startsWith("chat:");- const thread = useQuery({- queryKey: threadKey,- queryFn: () => emailApi.thread(companyId, issueId),- enabled: queryEnabled,- refetchInterval: 3000,- });+ const thread = useEmailThread(companyId, issueId);if (!queryEnabled) return null;const data = thread.data;const messages = data?.messages.filter((m) => !m.commentId) ?? [];diff --git a/ui/src/components/EmailThreadPolling.test.tsx b/ui/src/components/EmailThreadPolling.test.tsxnew file mode 100644index 0000000000..7af18bf917--- /dev/null+++ b/ui/src/components/EmailThreadPolling.test.tsx@@ -0,0 +1,75 @@+// @vitest-environment jsdom++import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { EmailThreadProvider } from "./EmailMessageCard";+import { EmailTaskActivity } from "./EmailTaskActivity";++const api = vi.hoisted(() => ({ thread: vi.fn() }));+vi.mock("@/api/email", () => ({ emailApi: { thread: api.thread } }));++const emailThread = { issueId: "task-1", messages: [], publications: [] };++describe("task email polling", () => {+ let container: HTMLDivElement;+ let root: Root;+ let client: QueryClient;+ beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ vi.useFakeTimers();+ api.thread.mockReset();+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ });+ afterEach(async () => {+ await act(async () => root.unmount());+ client.clear();+ container.remove();+ vi.useRealTimers();+ vi.unstubAllGlobals();+ });+ async function render(issueId = "task-1") {+ await act(async () => {+ root.render(<QueryClientProvider client={client}>+ <EmailThreadProvider companyId="company-1" issueId={issueId}>+ <EmailTaskActivity companyId="company-1" issueId={issueId} />+ </EmailThreadProvider>+ </QueryClientProvider>);+ });+ await advance(1);+ }+ async function advance(ms: number) {+ await act(async () => { await vi.advanceTimersByTimeAsync(ms); });+ }+ it("stops recurring requests when both task observers find no email thread", async () => {+ api.thread.mockResolvedValue(null);+ await render();+ expect(api.thread).toHaveBeenCalledTimes(1);+ await advance(10_000);+ expect(api.thread).toHaveBeenCalledTimes(1);+ });+ it("continues refreshing an email task", async () => {+ api.thread.mockResolvedValue(emailThread);+ await render();+ await advance(6_100);+ expect(api.thread.mock.calls.length).toBeGreaterThan(1);+ });+ it("can discover a thread after invalidation and resume updates", async () => {+ api.thread.mockResolvedValueOnce(null).mockResolvedValue(emailThread);+ await render();+ await act(async () => { await client.invalidateQueries({ queryKey: ["email-thread", "company-1", "task-1"] }); });+ await advance(1);+ expect(api.thread).toHaveBeenCalledTimes(2);+ await advance(3_100);+ expect(api.thread.mock.calls.length).toBeGreaterThan(2);+ });+ it("does not request email threads for chat conversations", async () => {+ await render("chat:agent-1");+ await advance(6_100);+ expect(api.thread).not.toHaveBeenCalled();+ });+});diff --git a/ui/src/components/chat/AgentChannelsPanel.tsx b/ui/src/components/chat/AgentChannelsPanel.tsxindex 216dc9bbbe..ed4ce716a2 100644--- a/ui/src/components/chat/AgentChannelsPanel.tsx+++ b/ui/src/components/chat/AgentChannelsPanel.tsx@@ -28,12 +28,11 @@ export function AgentChannelsPanel({const query = useQuery({queryKey: queryKeys.chatEndpoints.list(companyId),queryFn: () => chatEndpointsApi.list(companyId),- enabled,+ enabled: Boolean(companyId),});- if (!enabled) return null;const endpoints = (query.data ?? []).filter((endpoint) =>- endpoint.assignedAgentId === agentId && endpoint.status !== "archived",+ endpoint.assignedAgentId === agentId && endpoint.status !== "archived" && (endpoint.provider === "agentmail" || enabled),);return (<section className="max-w-3xl space-y-5">@@ -57,8 +56,7 @@ export function AgentChannelsPanel({<div className="rounded-lg border border-dashed border-border p-5"><p className="text-sm font-medium">No channels connected</p><p className="mt-1 text-sm text-muted-foreground">- Connect AgentMail, Slack, GitHub Code Review Bot, Discord, Microsoft Teams, or Telegram from- Connectors.+ {enabled ? "Connect AgentMail, Slack, GitHub Code Review Bot, Discord, Microsoft Teams, or Telegram from Connectors." : "Connect AgentMail from Connectors."}</p><Button asChild className="mt-3" variant="outline" size="sm"><Link to="/apps">Open Connectors</Link>diff --git a/ui/src/features/connections/AgentMailApiKeyField.tsx b/ui/src/features/connections/AgentMailApiKeyField.tsxnew file mode 100644index 0000000000..773664c92d--- /dev/null+++ b/ui/src/features/connections/AgentMailApiKeyField.tsx@@ -0,0 +1,15 @@+import { getAppStoreDefinition } from "@paperclipai/shared";+import { ApiKeyCredentialField } from "./ApiKeyCredentialField";++export const AGENTMAIL_API_KEYS_URL = getAppStoreDefinition("agentmail")!.methods[0]!.consoleLinks!.keys!;++export function AgentMailApiKeyField({ value, onChange, disabled = false, label = "API key" }: {+ value: string;+ onChange(value: string): void;+ disabled?: boolean;+ label?: string;+}) {+ return <ApiKeyCredentialField providerName="AgentMail" keysUrl={AGENTMAIL_API_KEYS_URL}+ options={[]} connectionId="" onConnectionChange={() => {}} value={value} onChange={onChange}+ disabled={disabled} label={label} />;+}diff --git a/ui/src/features/connections/AgentMailCredentialField.tsx b/ui/src/features/connections/AgentMailCredentialField.tsxnew file mode 100644index 0000000000..a00e8f8b42--- /dev/null+++ b/ui/src/features/connections/AgentMailCredentialField.tsx@@ -0,0 +1,30 @@+import { useEffect } from "react";+import { useQuery } from "@tanstack/react-query";+import { emailApi } from "@/api/email";+import { formatDateTime } from "@/lib/utils";+import { ApiKeyCredentialField } from "./ApiKeyCredentialField";+import { AGENTMAIL_API_KEYS_URL } from "./AgentMailApiKeyField";++export function AgentMailCredentialField({ companyId, connectionId, onConnectionChange, value, onChange, disabled }: {+ companyId: string;+ connectionId: string | null;+ onConnectionChange(id: string): void;+ value: string;+ onChange(value: string): void;+ disabled?: boolean;+}) {+ const saved = useQuery({ queryKey: ["email-credentials", companyId],+ queryFn: () => emailApi.credentials(companyId), staleTime: 60_000, retry: false });+ useEffect(() => {+ // Null means untouched; an explicit new-key choice must survive refreshes+ // and slow responses. Inbox-only keys cannot create a new email address.+ if (connectionId !== null || value || !saved.isSuccess) return;+ const preferred = saved.data.find(option => option.scope === "organization" || option.scope === "pod");+ if (preferred) onConnectionChange(preferred.id);+ }, [connectionId, value, saved.isSuccess, saved.data, onConnectionChange]);+ return <ApiKeyCredentialField providerName="AgentMail" keysUrl={AGENTMAIL_API_KEYS_URL}+ options={(saved.data ?? []).map(option => ({ id: option.id, disabled: option.scope === "unavailable",+ label: `${option.label} · saved ${formatDateTime(option.createdAt)}` }))}+ connectionId={connectionId} onConnectionChange={onConnectionChange} value={value} onChange={onChange}+ disabled={disabled} loading={saved.isFetching} error={saved.error?.message} />;+}diff --git a/ui/src/features/connections/AgentMailIntentSetup.tsx b/ui/src/features/connections/AgentMailIntentSetup.tsxnew file mode 100644index 0000000000..2b82e2f765--- /dev/null+++ b/ui/src/features/connections/AgentMailIntentSetup.tsx@@ -0,0 +1,115 @@+import { useEffect, useState } from "react";+import { useMutation } from "@tanstack/react-query";+import { isUuidLike } from "@paperclipai/shared";+import { emailApi } from "@/api/email";+import { Button } from "@/components/ui/button";+import { AgentMailCredentialField } from "./AgentMailCredentialField";++interface InlineEmailDraft {+ setupRequestId: string;+ credentialId: string | null;+ inboxConnectionId: string | null;+ selectedCredentialId: string | null;+}+function readDraft(key: string): InlineEmailDraft | null {+ try {+ const value = JSON.parse(sessionStorage.getItem(key) ?? "null");+ return value && isUuidLike(value.setupRequestId) && ["credentialId", "inboxConnectionId", "selectedCredentialId"]+ .every(field => value[field] === null || typeof value[field] === "string") ? value : null;+ } catch { return null; }+}++/** Same account and inbox APIs as Apps; task setup fixes the access defaults. */+export function AgentMailIntentSetup({ companyId, agentId, requestId, savedCredentialId, readyConnectionId, onComplete, onDecline, declining = false }: {+ companyId: string;+ agentId: string;+ requestId: string;+ savedCredentialId?: string | null;+ readyConnectionId?: string | null;+ onComplete(connectionId: string): Promise<void>;+ onDecline(): void;+ declining?: boolean;+}) {+ const draftKey = `paperclip.agentmail-inline:${companyId}:${requestId}`;+ const [draft] = useState(() => readDraft(draftKey));+ const [setupRequestId, setSetupRequestId] = useState(draft?.setupRequestId ?? requestId);+ const [apiKey, setApiKey] = useState("");+ // A refresh can interrupt the response after the server has saved the key.+ // Recover that account unless the user selected another key or started a+ // different setup after the interrupted request.+ const [credentialId, setCredentialId] = useState(draft?.credentialId+ ?? (!draft || (draft.setupRequestId === requestId && !draft.selectedCredentialId) ? savedCredentialId ?? null : null));+ const [selectedCredentialId, setSelectedCredentialId] = useState<string | null>(draft?.selectedCredentialId ?? null);+ const [inboxConnectionId, setInboxConnectionId] = useState(readyConnectionId ?? draft?.inboxConnectionId ?? null);+ useEffect(() => {+ try { sessionStorage.setItem(draftKey, JSON.stringify({ setupRequestId, credentialId, inboxConnectionId, selectedCredentialId })); }+ catch { /* Keep setup usable without browser storage. */ }+ }, [draftKey, setupRequestId, credentialId, inboxConnectionId, selectedCredentialId]);+ const changeKey = useMutation({+ mutationFn: async (pendingRequestId: string) => {+ const pending = (await emailApi.list(companyId)).find(inbox => inbox.id === pendingRequestId && inbox.status !== "archived");+ if (pending?.address) throw new Error(`The address ${pending.address} is already reserved. Finish setup with its saved key.`);+ if (pending) await emailApi.control(pending.id, "remove");+ },+ onSuccess: () => {+ setSetupRequestId(crypto.randomUUID());+ setCredentialId(null);+ setSelectedCredentialId("");+ setApiKey("");+ setup.reset();+ },+ });+ const setup = useMutation({+ mutationFn: async (submitted: { accountId: string | null; apiKey: string; requestId: string; inboxId: string | null }) => {+ let connectionId = submitted.inboxId;+ if (!connectionId) {+ let accountId = submitted.accountId;+ if (!accountId) {+ const account = await emailApi.connect(companyId, {+ apiKey: submitted.apiKey, grantKind: "organization", allAgents: false,+ agentIds: [agentId], idempotencyKey: submitted.requestId,+ });+ accountId = account.id;+ setCredentialId(accountId);+ setApiKey("");+ }+ setCredentialId(accountId);+ const inbox = await emailApi.setup(companyId, {+ assignedAgentId: agentId, credentialConnectionId: accountId,+ receiveMode: "websocket", idempotencyKey: submitted.requestId,+ });+ connectionId = inbox.connectionId;+ setInboxConnectionId(connectionId);+ }+ // Only the server's completed intent may resume the task. A saved API key+ // alone is not an inbox, and failures remain retryable in this same form.+ await onComplete(connectionId);+ try { sessionStorage.removeItem(draftKey); } catch { /* Optional draft storage. */ }+ },+ });+ return <form className="mt-4 space-y-4" data-testid="agentmail-inline-setup" onSubmit={event => {+ event.preventDefault();+ const accountId = credentialId || selectedCredentialId;+ if (!setup.isPending && !changeKey.isPending && !declining && (accountId || inboxConnectionId || apiKey.trim())) {+ setup.mutate({ accountId, apiKey: apiKey.trim(), requestId: setupRequestId, inboxId: inboxConnectionId });+ }+ }}>+ {credentialId || inboxConnectionId+ ? <p className="text-sm text-muted-foreground">{inboxConnectionId ? "Your inbox is ready. Continue to resume the chat." : "API key saved. Finish creating the inbox."}</p>+ : <AgentMailCredentialField companyId={companyId} connectionId={selectedCredentialId}+ onConnectionChange={id => { setSelectedCredentialId(id); setApiKey(""); }}+ value={apiKey} onChange={setApiKey} disabled={setup.isPending || changeKey.isPending || declining} />}+ {credentialId && !inboxConnectionId && <Button type="button" variant="link" size="sm" className="h-auto p-0"+ disabled={setup.isPending || changeKey.isPending || declining} onClick={() => changeKey.mutate(setupRequestId)}>+ {changeKey.isPending ? "Checking setup…" : "Change API key"}+ </Button>}+ {changeKey.error && <p className="text-sm text-destructive" role="alert">{changeKey.error.message}</p>}+ {setup.error && <p className="text-sm text-destructive" role="alert">{setup.error.message}</p>}+ <div className="flex items-center justify-between gap-2">+ <Button type="button" variant="ghost" disabled={setup.isPending || changeKey.isPending || declining} onClick={onDecline}>Not now</Button>+ <Button type="submit" disabled={setup.isPending || changeKey.isPending || declining || (!credentialId && !selectedCredentialId && !inboxConnectionId && !apiKey.trim())}>+ {setup.isPending ? "Connecting…" : inboxConnectionId ? "Continue" : credentialId ? "Finish setup" : "Connect AgentMail"}+ </Button>+ </div>+ </form>;+}diff --git a/ui/src/features/connections/ApiKeyCredentialField.tsx b/ui/src/features/connections/ApiKeyCredentialField.tsxnew file mode 100644index 0000000000..741ab22fd9--- /dev/null+++ b/ui/src/features/connections/ApiKeyCredentialField.tsx@@ -0,0 +1,38 @@+import { useId } from "react";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";++/** Providers supply only credentials the current user is authorized to use.+ * Values are opaque connection references, never secret values. */+export function ApiKeyCredentialField({ options, connectionId, onConnectionChange, value, onChange,+ disabled, loading, error, providerName, keysUrl, label = "API key" }: {+ options: { id: string; label: string; disabled?: boolean }[];+ connectionId: string | null;+ onConnectionChange(id: string): void;+ value: string;+ onChange(value: string): void;+ disabled?: boolean;+ loading?: boolean;+ error?: string;+ providerName: string;+ keysUrl: string;+ label?: string;+}) {+ const id = useId();+ const choices = connectionId && !options.some(option => option.id === connectionId)+ ? [{ id: connectionId, label: loading ? "Checking saved API key…" : "Previously selected key · unavailable", disabled: true }, ...options] : options;+ return <div className="space-y-2">+ <Label htmlFor={id}>{label}</Label>+ {choices.length > 0 && <select id={id} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"+ value={connectionId ?? ""} disabled={disabled} onChange={event => onConnectionChange(event.target.value)}>+ {choices.map(option => <option key={option.id} value={option.id} disabled={option.disabled}>{option.label}</option>)}+ <option value="">Enter a new API key</option>+ </select>}+ {!connectionId && <Input id={choices.length ? `${id}-new` : id} aria-label={choices.length ? "New API key" : undefined}+ type="password" autoComplete="off" value={value} disabled={disabled}+ onChange={event => { onConnectionChange(""); onChange(event.target.value); }} placeholder={`Paste your ${providerName} API key`} />}+ {loading && <p role="status" className="text-sm text-muted-foreground">Checking saved API keys…</p>}+ {error && <p role="alert" className="text-sm text-destructive">Could not load saved API keys. {error}</p>}+ <a href={keysUrl} target="_blank" rel="noreferrer" className="text-sm underline">Get an {providerName} API key ↗</a>+ </div>;+}diff --git a/ui/src/features/connections/ConnectionIntentInteractionBody.test.tsx b/ui/src/features/connections/ConnectionIntentInteractionBody.test.tsxindex a8b0a74192..e82db5ccf9 100644--- a/ui/src/features/connections/ConnectionIntentInteractionBody.test.tsx+++ b/ui/src/features/connections/ConnectionIntentInteractionBody.test.tsx@@ -16,6 +16,19 @@ import {} from "@/fixtures/issueThreadInteractionFixtures";import { ConnectionIntentInteractionBody } from "./ConnectionIntentInteractionBody";+const emailConnectMock = vi.hoisted(() => vi.fn());+const emailSetupMock = vi.hoisted(() => vi.fn());+const emailListMock = vi.hoisted(() => vi.fn());+const emailControlMock = vi.hoisted(() => vi.fn());+const emailCredentialsMock = vi.hoisted(() => vi.fn());+vi.mock("@/api/email", () => ({ emailApi: {+ credentials: (...args: unknown[]) => emailCredentialsMock(...args),+ list: (...args: unknown[]) => emailListMock(...args),+ control: (...args: unknown[]) => emailControlMock(...args),+ connect: (...args: unknown[]) => emailConnectMock(...args),+ setup: (...args: unknown[]) => emailSetupMock(...args),+} }));+const credentialRender = vi.hoisted(() => vi.fn());const setupOptionsMock = vi.hoisted(() => vi.fn());const completeMock = vi.hoisted(() => vi.fn());@@ -113,12 +126,12 @@ async function flush() {async function waitForAssertion(assertion: () => void, attempts = 20) {let lastError: unknown;for (let attempt = 0; attempt < attempts; attempt += 1) {+ await flush();try {assertion();return;} catch (error) {lastError = error;- await flush();}}throw lastError;@@ -175,6 +188,12 @@ function button(label: string) {}beforeEach(() => {+ sessionStorage.clear();+ emailCredentialsMock.mockReset().mockResolvedValue([]);+ emailListMock.mockReset().mockResolvedValue([]);+ emailControlMock.mockReset().mockResolvedValue({});+ emailConnectMock.mockReset().mockResolvedValue({ id: "email-account" });+ emailSetupMock.mockReset().mockResolvedValue({ connectionId: "email-inbox" });setDefaultMock.mockReset();getAgentMock.mockReset();updateAgentMock.mockReset();@@ -196,6 +215,8 @@ beforeEach(() => {afterEach(async () => {if (root) await act(() => root?.unmount());+ await queryClient.cancelQueries();+ queryClient.clear();host?.remove();document.body.querySelectorAll("[data-radix-focus-guard]")@@ -581,3 +602,168 @@ describe("AI repair inside the card", () => {expect(document.body.textContent).not.toContain("can continue without it");});});++describe("AgentMail inline setup", () => {+ const interaction: ConnectionIntentInteraction = {+ ...pendingConnectionIntentInteraction,+ payload: { ...pendingConnectionIntentInteraction.payload, purpose: "channel", serviceSlug: "agentmail", serviceName: "AgentMail" },+ };+ async function clickReadyButton(label: string) {+ await waitForAssertion(() => expect(button(label)?.disabled).toBe(false));+ await act(() => button(label)!.click());+ await flush();+ }+ async function enterKey() {+ await waitForAssertion(() => expect(document.querySelector('input[type="password"]')).not.toBeNull());+ const input = document.querySelector('input[type="password"]') as HTMLInputElement;+ await act(() => {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "fixture-api-key");+ input.dispatchEvent(new Event("input", { bubbles: true }));+ });+ }+ it("shows only the key inline, saves company access for this agent and completes after inbox setup", async () => {+ renderBody(interaction);+ await flush();+ expect(document.querySelector('[role="dialog"]')).toBeNull();+ await waitForAssertion(() => expect(document.querySelectorAll("input")).toHaveLength(1));+ expect(document.querySelector('a[href="https://console.agentmail.to/dashboard/api-keys"]')).not.toBeNull();+ expect(document.querySelector('[role="radiogroup"], select')).toBeNull();+ expect(button("Connect AgentMail")?.disabled).toBe(true);+ await enterKey();+ await clickReadyButton("Connect AgentMail");+ expect(emailConnectMock).toHaveBeenCalledWith(interaction.companyId, {+ apiKey: "fixture-api-key", grantKind: "organization", allAgents: false,+ agentIds: [interaction.payload.requestingAgentId], idempotencyKey: interaction.id,+ });+ expect(emailSetupMock).toHaveBeenCalledWith(interaction.companyId, {+ assignedAgentId: interaction.payload.requestingAgentId, credentialConnectionId: "email-account",+ receiveMode: "websocket", idempotencyKey: interaction.id,+ });+ expect(completeMock).toHaveBeenCalledWith(interaction.id, "email-inbox");+ });+ it("keeps invalid credentials retryable and does not create an inbox or accept the request", async () => {+ emailConnectMock.mockRejectedValueOnce(new Error("AgentMail request failed (401)"));+ renderBody(interaction); await flush(); await enterKey();+ await clickReadyButton("Connect AgentMail");+ expect(document.querySelector('[role="alert"]')?.textContent).toContain("401");+ expect(emailSetupMock).not.toHaveBeenCalled();+ expect(completeMock).not.toHaveBeenCalled();+ await clickReadyButton("Connect AgentMail");+ expect(completeMock).toHaveBeenCalledTimes(1);+ });+ it("retries inbox setup without asking for or saving the key again", async () => {+ emailSetupMock.mockRejectedValueOnce(new Error("Inbox setup unavailable"));+ renderBody(interaction); await flush(); await enterKey();+ await clickReadyButton("Connect AgentMail");+ expect(completeMock).not.toHaveBeenCalled();+ expect(document.querySelector('input[type="password"]')).toBeNull();+ await clickReadyButton("Finish setup");+ expect(emailConnectMock).toHaveBeenCalledTimes(1);+ expect(emailSetupMock).toHaveBeenCalledTimes(2);+ expect(completeMock).toHaveBeenCalledWith(interaction.id, "email-inbox");+ });+ it("can choose another key after a saved key fails, retiring an empty draft and preserving the retry identity", async () => {+ emailCredentialsMock.mockResolvedValue([{ id: "saved-account", label: "Saved key", scope: "organization", createdAt: "2026-10-01T14:00:00Z" }]);+ emailSetupMock.mockRejectedValueOnce(new Error("Inbox already assigned"))+ .mockRejectedValueOnce(new Error("Temporary provider failure"));+ emailListMock.mockResolvedValue([{ id: interaction.id, address: null, status: "draft" }]);+ renderBody(interaction); await flush();+ await waitForAssertion(() => expect(button("Connect AgentMail")?.disabled).toBe(false));+ expect((document.querySelector("select") as HTMLSelectElement)?.value).toBe("saved-account");+ expect(emailConnectMock).not.toHaveBeenCalled();+ await clickReadyButton("Connect AgentMail");+ expect(emailConnectMock).not.toHaveBeenCalled();+ await clickReadyButton("Change API key");+ expect(emailControlMock).toHaveBeenCalledWith(interaction.id, "remove");+ await enterKey();+ await clickReadyButton("Connect AgentMail");+ const next = emailSetupMock.mock.calls[1][1].idempotencyKey;+ expect(next).not.toBe(interaction.id);+ expect(emailConnectMock).toHaveBeenCalledWith(interaction.companyId, expect.objectContaining({ idempotencyKey: next }));+ expect(sessionStorage.getItem(`paperclip.agentmail-inline:${interaction.companyId}:${interaction.id}`)).not.toContain("fixture-api-key");+ await act(() => root!.unmount()); host!.remove(); queryClient.clear();+ renderBody(interaction); await flush();+ await clickReadyButton("Finish setup");+ expect(emailSetupMock.mock.calls[2][1].idempotencyKey).toBe(next);+ expect(emailConnectMock).toHaveBeenCalledTimes(1);+ expect(completeMock).toHaveBeenCalledWith(interaction.id, "email-inbox");+ });+ it("does not switch keys after an inbox address is allocated", async () => {+ setupOptionsMock.mockResolvedValue({ existingConnections: [], emailSetup: { credentialConnectionId: "saved-account", readyConnectionId: null } });+ emailListMock.mockResolvedValue([{ id: interaction.id, address: "[email protected]", status: "draft" }]);+ renderBody(interaction); await flush();+ await clickReadyButton("Change API key");+ expect(document.body.textContent).toContain("[email protected] is already reserved");+ expect(emailControlMock).not.toHaveBeenCalled();+ expect(document.querySelector('input[type="password"]')).toBeNull();+ });+ it("recovers the server-saved account when refresh interrupted its response", async () => {+ const resumedInteraction = { ...interaction, id: "a381e91e-7127-427d-9d2d-519d4deba89f" };+ sessionStorage.setItem(`paperclip.agentmail-inline:${interaction.companyId}:${resumedInteraction.id}`, JSON.stringify({+ setupRequestId: resumedInteraction.id, credentialId: null, inboxConnectionId: null, selectedCredentialId: "",+ }));+ setupOptionsMock.mockResolvedValue({ existingConnections: [], emailSetup: { credentialConnectionId: "server-saved-account", readyConnectionId: null } });+ renderBody(resumedInteraction); await flush();+ expect(document.querySelector('input[type="password"]')).toBeNull();+ await clickReadyButton("Finish setup");+ expect(emailConnectMock).not.toHaveBeenCalled();+ expect(emailSetupMock).toHaveBeenCalledWith(interaction.companyId, expect.objectContaining({+ credentialConnectionId: "server-saved-account", idempotencyKey: resumedInteraction.id,+ }));+ });+ it("keeps a different saved-key selection when recovering an interrupted save", async () => {+ const resumedInteraction = { ...interaction, id: "a381e91e-7127-427d-9d2d-519d4deba89f" };+ sessionStorage.setItem(`paperclip.agentmail-inline:${interaction.companyId}:${resumedInteraction.id}`, JSON.stringify({+ setupRequestId: resumedInteraction.id, credentialId: null, inboxConnectionId: null, selectedCredentialId: "selected-account",+ }));+ emailCredentialsMock.mockResolvedValue([{ id: "selected-account", label: "My selected key", scope: "organization", createdAt: "2026-10-01T14:00:00Z" }]);+ setupOptionsMock.mockResolvedValue({ existingConnections: [], emailSetup: { credentialConnectionId: "earlier-account", readyConnectionId: null } });+ renderBody(resumedInteraction); await flush();+ await waitForAssertion(() => expect((document.querySelector('select') as HTMLSelectElement)?.value).toBe("selected-account"));+ await clickReadyButton("Connect AgentMail");+ expect(emailConnectMock).not.toHaveBeenCalled();+ expect(emailSetupMock).toHaveBeenCalledWith(interaction.companyId, expect.objectContaining({+ credentialConnectionId: "selected-account", idempotencyKey: resumedInteraction.id,+ }));+ });+ it("does not restore an abandoned server account after the user changes keys", async () => {+ const replacementRequestId = "a381e91e-7127-427d-9d2d-519d4deba89f";+ sessionStorage.setItem(`paperclip.agentmail-inline:${interaction.companyId}:${interaction.id}`, JSON.stringify({+ setupRequestId: replacementRequestId, credentialId: null, inboxConnectionId: null, selectedCredentialId: "",+ }));+ setupOptionsMock.mockResolvedValue({ existingConnections: [], emailSetup: { credentialConnectionId: "abandoned-account", readyConnectionId: null } });+ renderBody(interaction); await flush(); await enterKey();+ await clickReadyButton("Connect AgentMail");+ expect(emailConnectMock).toHaveBeenCalledWith(interaction.companyId, expect.objectContaining({ idempotencyKey: replacementRequestId }));+ expect(emailSetupMock).toHaveBeenCalledWith(interaction.companyId, expect.objectContaining({+ credentialConnectionId: "email-account", idempotencyKey: replacementRequestId,+ }));+ });+ it("resumes a saved account after reload and retries acceptance without recreating the inbox", async () => {+ setupOptionsMock.mockResolvedValue({ existingConnections: [], emailSetup: { credentialConnectionId: "email-account", readyConnectionId: "email-inbox" } });+ completeMock.mockRejectedValueOnce(new Error("Retry completion"));+ renderBody(interaction); await flush();+ await clickReadyButton("Continue");+ await clickReadyButton("Continue");+ expect(emailConnectMock).not.toHaveBeenCalled();+ expect(emailSetupMock).not.toHaveBeenCalled();+ expect(completeMock).toHaveBeenCalledTimes(2);+ });+ it("declines without provider requests and hides credentials from other viewers", async () => {+ renderBody(interaction); await flush();+ await clickReadyButton("Not now");+ expect(declineMock).toHaveBeenCalledWith(interaction.id);+ expect(emailConnectMock).not.toHaveBeenCalled();+ expect(emailSetupMock).not.toHaveBeenCalled();+ await act(() => root!.render(<QueryClientProvider client={queryClient}><ConnectionIntentInteractionBody interaction={interaction} currentUserId="different-user" addresseeLabel="Carol" /></QueryClientProvider>));+ expect(document.querySelector('input')).toBeNull();+ });+ it("can decline even when inbox setup options fail to load", async () => {+ setupOptionsMock.mockRejectedValue(new Error("Email setup is unavailable"));+ renderBody(interaction);+ await waitForAssertion(() => expect(document.body.textContent).toContain("Email setup is unavailable"));+ await clickReadyButton("Not now");+ expect(declineMock).toHaveBeenCalledWith(interaction.id);+ expect(emailConnectMock).not.toHaveBeenCalled();+ });+});diff --git a/ui/src/features/connections/ConnectionIntentInteractionBody.tsx b/ui/src/features/connections/ConnectionIntentInteractionBody.tsxindex 17010fd026..3a7f50c9db 100644--- a/ui/src/features/connections/ConnectionIntentInteractionBody.tsx+++ b/ui/src/features/connections/ConnectionIntentInteractionBody.tsx@@ -9,6 +9,7 @@ import {XCircle,} from "lucide-react";import type { AiAuthMethod, ConnectionIntentInteraction } from "@paperclipai/shared";+import { AgentMailIntentSetup } from "./AgentMailIntentSetup";import { connectionIntentsApi } from "@/api/connection-intents";import { aiConnectionsApi } from "@/api/ai-connections";import { agentsApi } from "@/api/agents";@@ -61,6 +62,7 @@ export function ConnectionIntentInteractionBody({);const isPending = interaction.status === "pending";const isAi = interaction.payload.purpose === "ai";+ const isEmail = interaction.payload.purpose === "channel" && interaction.payload.serviceSlug === "agentmail";const focusTargetId = `connection-intent-focus-target-${interaction.id}`;const invalidateTask = async (@@ -410,6 +412,7 @@ export function ConnectionIntentInteractionBody({<p className="mt-1 text-sm text-muted-foreground">{interaction.payload.purpose === "ai"? "This task can’t run until the agent has a valid AI connection. Connect here and the task will resume automatically."+ : isEmail ? "Connect AgentMail to create an email address for this agent.": "Connect your identity or reuse an eligible connection. Access is added only for this agent."}</p></div>@@ -423,7 +426,19 @@ export function ConnectionIntentInteractionBody({</p>) : null}- <div className="mt-4 flex flex-wrap justify-end gap-2">+ {isEmail ? setupQuery.isLoading || setupQuery.isError ? <>+ {setupContent}+ <Button type="button" variant="ghost" disabled={declineMutation.isPending} onClick={() => declineMutation.mutate()}>Not now</Button>+ </> : <AgentMailIntentSetup+ companyId={interaction.companyId}+ agentId={interaction.payload.requestingAgentId}+ requestId={interaction.id}+ savedCredentialId={setupQuery.data?.emailSetup?.credentialConnectionId}+ readyConnectionId={setupQuery.data?.emailSetup?.readyConnectionId}+ onComplete={async connectionId => { await completeMutation.mutateAsync(connectionId); }}+ onDecline={() => declineMutation.mutate()}+ declining={declineMutation.isPending}+ /> : <div className="mt-4 flex flex-wrap justify-end gap-2">{!isAi && <Buttontype="button"variant="ghost"@@ -468,10 +483,10 @@ export function ConnectionIntentInteractionBody({{setupContent}</DialogContent></Dialog>}- </div>+ </div>}{isAi && open ? <div className="mt-4 border-t border-border pt-4" data-testid="ai-connection-inline-repair">{inlineContent}</div> : null}- {completeMutation.isError ||+ {(!isEmail && completeMutation.isError) ||(selectAiAccountMutation.isError && selectAiAccountMutation.variables?.generation === generation) ||adoptMutation.isError ||declineMutation.isError ||diff --git a/ui/src/features/connections/ConnectionSetupFlow.tsx b/ui/src/features/connections/ConnectionSetupFlow.tsxindex 7a01867fc7..548d4a8681 100644--- a/ui/src/features/connections/ConnectionSetupFlow.tsx+++ b/ui/src/features/connections/ConnectionSetupFlow.tsx@@ -970,7 +970,7 @@ function StandardConnectionSetupFlow({// Generic custom URLs remain usable without selecting a hidden provider.const visibleGalleryApps = useMemo(() => (galleryQuery.data?.apps ?? []).filter((app) => memoryConnectorsEnabled || !isMemoryConnectorId(app.slug)).filter((app) =>- chatConnectorsEnabled ||+ app.slug === "agentmail" || chatConnectorsEnabled ||!app.methods.some((method) => method.transport === "chat_sdk") ||appSupportsToolCatalogSetup(app),),diff --git a/ui/src/features/connections/useEmailAddressCheck.ts b/ui/src/features/connections/useEmailAddressCheck.tsnew file mode 100644index 0000000000..173b1d8459--- /dev/null+++ b/ui/src/features/connections/useEmailAddressCheck.ts@@ -0,0 +1,25 @@+import { useEffect, useState } from "react";+import type { EmailAddressCheckResult } from "@paperclipai/shared";+import { emailApi } from "@/api/email";++type Check = { key: string; result?: EmailAddressCheckResult; error?: string };++/** Debounce reads, abort superseded requests, and never display an old address's result. */+export function useEmailAddressCheck(companyId: string, connectionId: string, username: string, domain: string, enabled: boolean) {+ const key = JSON.stringify([companyId, connectionId, username, domain]);+ const [check, setCheck] = useState<Check>();+ useEffect(() => {+ if (!enabled) return;+ const controller = new AbortController();+ const timeout = setTimeout(() => {+ void emailApi.checkAddress(companyId, connectionId, { username, domain }, controller.signal)+ .then(result => { if (!controller.signal.aborted) setCheck({ key, result }); })+ .catch(error => {+ if (!controller.signal.aborted) setCheck({ key, error: error instanceof Error ? error.message : "Could not check this address." });+ });+ }, 350);+ return () => { clearTimeout(timeout); controller.abort(); };+ }, [companyId, connectionId, username, domain, key, enabled]);+ const current = enabled && check?.key === key ? check : undefined;+ return { result: current?.result, error: current?.error, checking: enabled && !current };+}diff --git a/ui/src/hooks/useEmailThread.ts b/ui/src/hooks/useEmailThread.tsnew file mode 100644index 0000000000..390a2d2d0a--- /dev/null+++ b/ui/src/hooks/useEmailThread.ts@@ -0,0 +1,13 @@+import { useQuery } from "@tanstack/react-query";+import { emailApi } from "@/api/email";++export function useEmailThread(companyId: string, issueId: string) {+ return useQuery({+ queryKey: ["email-thread", companyId, issueId],+ queryFn: () => emailApi.thread(companyId, issueId),+ enabled: Boolean(companyId && issueId) && !issueId.startsWith("chat:"),+ // A null response identifies an ordinary task. It can still refetch on+ // focus or invalidation, but only email tasks need recurring updates.+ refetchInterval: (query) => query.state.data === null ? false : 3000,+ });+}diff --git a/ui/src/index.css b/ui/src/index.cssindex bec5ab10ee..cac1eb5c35 100644--- a/ui/src/index.css+++ b/ui/src/index.css@@ -95,6 +95,10 @@--file-tree-indent-base: calc(var(--spacing) * 2);--file-tree-indent-step: calc(var(--spacing) * 6);--file-tree-indent-max: 40%;+ --native-select-caret-half: calc(var(--spacing) * 1.5);+ --native-select-caret-inset: calc(var(--spacing) * 3);+ --native-select-caret-stroke: 1.5px;+ --native-select-end-padding: calc(var(--spacing) * 9);--radius: 0.5rem;--background: oklch(1 0 0);--foreground: oklch(0.145 0 0);@@ -562,6 +566,31 @@}}+/* Native single-value dropdowns share one inset caret. Padding alone does not+ move the browser's arrow. Keep native menus/keyboard behavior and leave+ listboxes and controls with their own appearance-none icon untouched.+ This rule is outside layers so per-field px-* utilities cannot erase the+ space reserved for the caret. currentColor follows every app theme. */+select:where(:not([multiple]):not(.appearance-none)):where(:not([size]), [size="0"], [size="1"]) {+ appearance: none;+ padding-inline-end: var(--native-select-end-padding);+ background-image:+ linear-gradient(45deg, transparent calc(50% - var(--native-select-caret-stroke) / 2), currentColor calc(50% - var(--native-select-caret-stroke) / 2), currentColor calc(50% + var(--native-select-caret-stroke) / 2), transparent calc(50% + var(--native-select-caret-stroke) / 2)),+ linear-gradient(135deg, transparent calc(50% - var(--native-select-caret-stroke) / 2), currentColor calc(50% - var(--native-select-caret-stroke) / 2), currentColor calc(50% + var(--native-select-caret-stroke) / 2), transparent calc(50% + var(--native-select-caret-stroke) / 2));+ background-position: right calc(var(--native-select-caret-inset) + var(--native-select-caret-half)) center, right var(--native-select-caret-inset) center;+ background-size: var(--native-select-caret-half) var(--native-select-caret-half);+ background-repeat: no-repeat;+}+select:where(:not([multiple]):not(.appearance-none)):where(:not([size]), [size="0"], [size="1"]):dir(rtl) {+ background-position: left var(--native-select-caret-inset) center, left calc(var(--native-select-caret-inset) + var(--native-select-caret-half)) center;+}+@media (forced-colors: active) {+ select:where(:not([multiple]):not(.appearance-none)):where(:not([size]), [size="0"], [size="1"]) {+ appearance: auto;+ background-image: none;+ }+}+@media (pointer: coarse) {button,[role="button"],diff --git a/ui/src/lib/mention-chips.test.ts b/ui/src/lib/mention-chips.test.tsnew file mode 100644index 0000000000..7d138f5b27--- /dev/null+++ b/ui/src/lib/mention-chips.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it, vi } from "vitest";+import { mentionChipInlineStyle } from "./mention-chips";++const getAgentIcon = vi.hoisted(() => vi.fn());+vi.mock("./agent-icons", () => ({ getAgentIcon }));++describe("agent mention icon compatibility", () => {+ const node = [["path", { d: "m16 18 6-6-6-6", key: "code" }]];++ it.each([+ ["static", { iconNode: node }],+ ["legacy", { render: () => ({ props: { iconNode: node } }) }],+ ["icon-data", { render: () => ({ props: { icon: { name: "code", size: 24, node } } }) }],+ ])("renders an agent mention mask from Lucide's %s format", (name, icon) => {+ getAgentIcon.mockReturnValue(icon);+ const style = mentionChipInlineStyle({ kind: "agent", agentId: "agent", icon: name });+ const mask = (style as Record<string, string>)["--paperclip-mention-icon-mask"];+ expect(decodeURIComponent(mask)).toContain('<path d="m16 18 6-6-6-6"></path>');+ });+});diff --git a/ui/src/pages/AgentDetail.tsx b/ui/src/pages/AgentDetail.tsxindex 4beff8f0cb..939e482e9e 100644--- a/ui/src/pages/AgentDetail.tsx+++ b/ui/src/pages/AgentDetail.tsx@@ -96,7 +96,6 @@ import { Input } from "@/components/ui/input";import { RunTranscriptView, type TranscriptMode } from "../components/transcript/RunTranscriptView";import { AgentToolsTab } from "./AgentToolsTab";import { AgentChannelsPanel } from "../components/chat/AgentChannelsPanel";-import { useChatConnectorsEnabled } from "@/hooks/useChatConnectorsEnabled";import {appendCapped,LIVE_TRANSCRIPT_RENDER_LIMIT,@@ -769,11 +768,10 @@ export function AgentDetail() {const { setBreadcrumbs } = useBreadcrumbs();const queryClient = useQueryClient();const navigate = useNavigate();- const { enabled: chatConnectorsEnabled, loaded: chatConnectorsLoaded } = useChatConnectorsEnabled();const [actionError, setActionError] = useState<string | null>(null);const [dismissedLeftAgentIds, setDismissedLeftAgentIds] = useState<Set<string>>(() => new Set());const activeView: AgentDetailView = urlRunId ? "run-detail"- : urlTab === "channels" && !chatConnectorsEnabled ? "overview" : parseAgentDetailView(urlTab ?? null);+ : parseAgentDetailView(urlTab ?? null);const legacyAuditSection = !urlRunId ? agentLegacyAuditSection(urlTab ?? null) : null;const legacyView = urlRunId? "runs"@@ -963,13 +961,6 @@ export function AgentDetail() {useEffect(() => {if (!agent) return;- if (!urlRunId && urlTab === "channels") {- if (!chatConnectorsLoaded) return;- if (!chatConnectorsEnabled) {- navigate(agentDetailHref(canonicalAgentRef, "overview"), { replace: true });- return;- }- }if (urlRunId) {if (routeAgentRef !== canonicalAgentRef) {navigate(`/agents/${canonicalAgentRef}/runs/${urlRunId}`, { replace: true });@@ -982,7 +973,7 @@ export function AgentDetail() {navigate(agentDetailHref(canonicalAgentRef, canonicalTab), { replace: true });return;}- }, [agent, routeAgentRef, canonicalAgentRef, urlRunId, urlTab, activeView, legacyAuditSection, navigate, chatConnectorsEnabled, chatConnectorsLoaded]);+ }, [agent, routeAgentRef, canonicalAgentRef, urlRunId, urlTab, activeView, legacyAuditSection, navigate]);useEffect(() => {if (!agent?.companyId || agent.companyId === selectedCompanyId) return;diff --git a/ui/src/pages/DesignGuide.tsx b/ui/src/pages/DesignGuide.tsxindex 4002febed8..e09b59d8d8 100644--- a/ui/src/pages/DesignGuide.tsx+++ b/ui/src/pages/DesignGuide.tsx@@ -1,3 +1,4 @@+import { AgentMailApiKeyField } from "@/features/connections/AgentMailApiKeyField";import { TaskBrowserFooter } from "@/components/task-side-panel/TaskBrowserFooter";import { TaskBrowserActivity } from "@/components/task-side-panel/TaskBrowserActivity";import type { TaskBrowser } from "@paperclipai/shared";@@ -494,6 +495,7 @@ function ComposerActionsExample() {}export function DesignGuide() {+ const [agentmailDemoKey, setAgentmailDemoKey] = useState("");const [wizardStep, setWizardStep] = useState(0);const [status, setStatus] = useState("todo");const [priority, setPriority] = useState("medium");@@ -1028,6 +1030,7 @@ export function DesignGuide() {{/* SELECT */}{/* ============================================================ */}<Section title="Select">+ <p className="mb-4 text-sm text-muted-foreground">Native single-value dropdowns share an inset, theme-aware caret and reserve room for it in the base stylesheet. Multiple-selection lists and controls with a custom icon keep their own appearance.</p><div className="grid gap-6 md:grid-cols-2"><SubSection title="Default size"><Select value={selectValue} onValueChange={setSelectValue}>@@ -2297,7 +2300,8 @@ export function DesignGuide() {the full-page Apps setup; this card owns only audience, dialog, and task refresh behavior.Pending connections stay in the timeline beside a usable composer. The independentlyaddressable Connections/In-task connections stories cover access, OAuth recovery, narrow- layouts, completion, and historical outcomes.+ layouts, completion, and historical outcomes. AgentMail uses an inline API-key field+ with fixed access defaults; its field and direct key-page link are shared with Apps setup.</p><div className="grid gap-4 xl:grid-cols-3"><IssueThreadInteractionCard@@ -2315,6 +2319,14 @@ export function DesignGuide() {</div></Section>+ <Section title="AgentMail API key">+ <p className="text-sm text-muted-foreground">AgentMail setup has two steps: pick an agent, then pick an email address. Ask for the API key alongside the agent only when needed. Keep address errors beside the field and additional settings under Advanced options.</p>+ <p className="text-sm text-muted-foreground">Preview only. This field does not save or submit a credential.</p>+ <div className="max-w-md">+ <AgentMailApiKeyField value={agentmailDemoKey} onChange={setAgentmailDemoKey} />+ </div>+ </Section>+<Section title="Resizable Panels"><p className="text-sm text-muted-foreground">Design-system wrapper over <span className="font-mono">react-resizable-panels</span>{" "}diff --git a/ui/src/pages/InstanceExperimentalSettings.tsx b/ui/src/pages/InstanceExperimentalSettings.tsxindex 8fc3a2c641..0d8bd95e36 100644--- a/ui/src/pages/InstanceExperimentalSettings.tsx+++ b/ui/src/pages/InstanceExperimentalSettings.tsx@@ -342,7 +342,7 @@ export function InstanceExperimentalSettings() {<ExperimentalToggleCardtitle="Chat connectors"description="Connect agents to Slack, GitHub, Discord, Microsoft Teams, and Telegram conversations."- footnote="Turning this off hides chat setup, channels, and connected-task controls. Existing chat connections keep running. GitHub and other tool connectors stay available."+ footnote="Turning this off hides experimental chat setup and connected-task controls. Existing chat connections keep running. AgentMail, GitHub tools, and other tool connectors stay available."checked={enableChatConnectors}onCheckedChange={(checked) => toggleMutation.mutate({ enableChatConnectors: checked })}disabled={toggleMutation.isPending}diff --git a/ui/src/pages/IssueDetail.test.tsx b/ui/src/pages/IssueDetail.test.tsxindex b785be4437..a45a721f35 100644--- a/ui/src/pages/IssueDetail.test.tsx+++ b/ui/src/pages/IssueDetail.test.tsx@@ -172,6 +172,10 @@ vi.mock("../api/issues", async (importOriginal) => {return { ...actual, issuesApi: Object.assign(actual.issuesApi, mockIssuesApi) };});+vi.mock("../api/email", () => ({+ emailApi: { thread: vi.fn().mockResolvedValue(null) },+}));+vi.mock("../api/activity", () => ({activityApi: mockActivityApi,}));diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsxindex 672a89738c..be09ccbd6a 100644--- a/ui/src/pages/IssueDetail.tsx+++ b/ui/src/pages/IssueDetail.tsx@@ -7805,7 +7805,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskSonOpenSkill={handleOpenSkill}browsers={browserQuery.data}onOpenBrowser={(id) => { setOpenBrowserId(id); if (isMobile) setMobilePropsOpen(true); else openTaskSidePanel(); }}- threadHeader={<>{taskChatThreadHeader}{instanceExperimentalSettings?.enableChatConnectors && <EmailTaskActivity key={issue.id} companyId={issue.companyId} issueId={issue.id} />}</>}+ threadHeader={<>{taskChatThreadHeader}<EmailTaskActivity key={issue.id} companyId={issue.companyId} issueId={issue.id} /></>}issueBrief={// Suppress the seeded-description bubble for the onboarding first// task: its description is agent instructions, not something thediff --git a/ui/src/pages/apps/Browse.test.tsx b/ui/src/pages/apps/Browse.test.tsxindex 603078e382..35ab90ed2f 100644--- a/ui/src/pages/apps/Browse.test.tsx+++ b/ui/src/pages/apps/Browse.test.tsx@@ -18,9 +18,11 @@ const navigateMock = vi.hoisted(() => vi.fn());const setBreadcrumbsMock = vi.hoisted(() => vi.fn());const experimentalMock = vi.hoisted(() => vi.fn());const chatSetupMock = vi.hoisted(() => vi.fn());+const emailControlMock = vi.hoisted(() => vi.fn());const chatListMock = vi.hoisted(() => vi.fn());vi.mock("@/api/instanceSettings", () => ({ instanceSettingsApi: { getExperimental: experimentalMock } }));vi.mock("@/api/chatEndpoints", () => ({ chatEndpointsApi: { list: chatListMock, setup: chatSetupMock } }));+vi.mock("@/api/email", () => ({ emailApi: { control: emailControlMock } }));vi.mock("@/api/tools", () => ({toolsApi: {@@ -137,6 +139,7 @@ describe("Connectors landing page", () => {experimentalMock.mockResolvedValue({ enableChatConnectors: true });chatListMock.mockResolvedValue([]);chatSetupMock.mockReset().mockResolvedValue({ status: "archived" });+ emailControlMock.mockReset().mockResolvedValue({ status: "archived" });listGalleryMock.mockResolvedValue({apps: [galleryEntry({@@ -349,17 +352,20 @@ describe("Connectors landing page", () => {it("defaults to tools-only GitHub and hides chat-only catalog and existing chat accounts", async () => {experimentalMock.mockResolvedValue({});- listGalleryMock.mockResolvedValue({ apps: ["github", "github-code-review-bot", "discord", "telegram", "microsoft-teams"].map(getAppStoreDefinition) });+ listGalleryMock.mockResolvedValue({ apps: ["agentmail", "github", "github-code-review-bot", "discord", "telegram", "microsoft-teams"].map(getAppStoreDefinition) });listApplicationsMock.mockResolvedValue({ applications: [application({id: "chat-app", type: "chat", name: "Private bot", applicationKey: "chat:github:endpoint-1", metadata: { purpose: "channel" },})] });await renderBrowse();- expect(chatListMock).not.toHaveBeenCalled();+ expect(chatListMock).toHaveBeenCalledWith("company-1");expect(container.querySelector('[data-app-slug="github"]')).not.toBeNull();for (const slug of ["github-code-review-bot", "discord", "telegram", "microsoft-teams", "slack"]) {expect(container.querySelector(`[data-app-slug="${slug}"]`)).toBeNull();}expect(container.textContent).not.toContain("Private bot");+ expect(container.querySelector('[data-app-slug="agentmail"]')).not.toBeNull();+ await act(() => void container.querySelector<HTMLButtonElement>('button[aria-label="Connect AgentMail"]')!.click());+ expect(navigateMock.mock.lastCall?.[0]).toContain("/apps/chat/connect?provider=agentmail");expect(container.textContent).not.toContain("Chat with agents");await act(() => void container.querySelector<HTMLButtonElement>('button[aria-label="Add key GitHub"]')!.click());expect(navigateMock).toHaveBeenLastCalledWith("/apps/connect?source=github");@@ -460,6 +466,7 @@ describe("Connectors landing page", () => {),).map((row) => row.dataset.appSlug),).toEqual([+ "agentmail","discord","github-code-review-bot","imessage-photon",@@ -642,6 +649,19 @@ describe("Connectors landing page", () => {);});+ it("starts each AgentMail Add connection with a distinct setup identity", async () => {+ chatListMock.mockResolvedValue([{ id: "chat-draft", provider: "agentmail", status: "draft", assignedAgentName: "Ralph" }]);+ await renderBrowse();+ const add = container.querySelector<HTMLButtonElement>('button[aria-label="Add connection AgentMail"]')!;+ await act(() => add.click());+ const first = new URL(navigateMock.mock.lastCall![0], "http://localhost");+ expect(first.pathname).toBe("/apps/chat/connect");+ expect(first.searchParams.get("provider")).toBe("agentmail");+ expect(first.searchParams.get("setupId")).toMatch(/^[0-9a-f-]{36}$/);+ await act(() => add.click());+ expect(navigateMock.mock.lastCall![0]).not.toBe(first.pathname + first.search);+ });+it.each(["slack", "discord", "telegram", "github", "microsoft-teams", "agentmail", "imessage-photon"])("puts Manage and removal in the %s chat menu while keeping draft setup visible",async (provider) => {@@ -665,23 +685,34 @@ describe("Connectors landing page", () => {},);- it.each(["active", "draft"])("confirms chat removal for %s connections and refreshes the list", async (status) => {- chatListMock.mockResolvedValue([{ id: "chat-1", provider: "slack", status, assignedAgentName: "CEO" }]);+ it.each([+ ["slack", "Slack", "active"], ["slack", "Slack", "draft"],+ ["agentmail", "AgentMail", "active"], ["agentmail", "AgentMail", "draft"],+ ])("confirms %s removal for %s %s connections and refreshes the list", async (provider, providerName, status) => {+ chatListMock.mockResolvedValue([{ id: "chat-1", provider, status, assignedAgentName: "CEO" }]);const client = await renderBrowse();const invalidate = vi.spyOn(client, "invalidateQueries");- await act(() => void container.querySelector('button[aria-label="Manage CEO Slack connection"]')!.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true })));+ await act(() => void container.querySelector(`button[aria-label="Manage CEO ${providerName} connection"]`)!.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true })));await flushReact();const remove = Array.from(document.querySelectorAll<HTMLElement>('[role="menuitem"]')).find((item) => item.textContent?.trim() === "Remove connection");await act(() => remove!.click());await flushReact();expect(chatSetupMock).not.toHaveBeenCalled();+ expect(emailControlMock).not.toHaveBeenCalled();expect(document.body.textContent).toContain("Existing Paperclip tasks and conversation history remain available.");chatListMock.mockResolvedValue([]);await act(() => Array.from(document.querySelectorAll("button")).find((button) => button.textContent?.trim() === "Remove connection")!.click());await flushReact();- expect(chatSetupMock).toHaveBeenCalledWith("chat-1", { action: "remove" });+ if (provider === "agentmail") {+ expect(emailControlMock).toHaveBeenCalledWith("chat-1", "remove");+ expect(chatSetupMock).not.toHaveBeenCalled();+ } else {+ expect(chatSetupMock).toHaveBeenCalledWith("chat-1", { action: "remove" });+ expect(emailControlMock).not.toHaveBeenCalled();+ }expect(archiveConnectionMock).not.toHaveBeenCalled();expect(invalidate).toHaveBeenCalledWith({ queryKey: queryKeys.chatEndpoints.list("company-1") });+ expect(invalidate).toHaveBeenCalledWith({ queryKey: ["email-inboxes", "company-1"] });expect(container.textContent).not.toContain("CEO");});diff --git a/ui/src/pages/apps/Browse.tsx b/ui/src/pages/apps/Browse.tsxindex aeb71f444a..c117743324 100644--- a/ui/src/pages/apps/Browse.tsx+++ b/ui/src/pages/apps/Browse.tsx@@ -38,6 +38,7 @@ import { useBreadcrumbs } from "@/context/BreadcrumbContext";import { useToast } from "@/context/ToastContext";import { queryKeys } from "@/lib/queryKeys";import { toolsApi } from "@/api/tools";+import { emailApi } from "@/api/email";import {chatEndpointsApi,type ChatEndpoint,@@ -109,13 +110,11 @@ type ConnectionState = {};type ConnectionRemovalTarget = {- kind?: "chat";id: string;accountName: string;providerName: string;remainingConnectionCount: number;--};+} & ({ kind: "chat"; provider: ChatProvider } | { kind?: undefined });// Temporary, page-only hold until Google OAuth verification is approved.// Keep definitions, direct setup/management routes, and runtime access intact.@@ -232,7 +231,7 @@ function connectorAction(title?: string;} {const applicationId = row.applications[0]?.id ?? null;- const chatHref = chatConnectorsEnabled+ const chatHref = (row.slug === "agentmail" || chatConnectorsEnabled)? chatConnectHref(row.slug,row.entry ? connectHrefFor(row.entry) : null,@@ -331,7 +330,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conneconst chatEndpointsQuery = useQuery({queryKey: queryKeys.chatEndpoints.list(selectedCompanyId ?? "__none__"),queryFn: () => chatEndpointsApi.list(selectedCompanyId!),- enabled: !!selectedCompanyId && chatConnectorsEnabled,+ enabled: !!selectedCompanyId,});const userDirectoryQuery = useQuery({queryKey: queryKeys.access.companyUserDirectory(@@ -343,12 +342,17 @@ export function Browse({ renderAccountDetails = (connection) => connection.conneconst removeConnection = useMutation({mutationFn: async (target: ConnectionRemovalTarget) => {if (target.kind === "chat") {- await chatEndpointsApi.setup(target.id, { action: "remove" });+ if (target.provider === "agentmail") {+ await emailApi.control(target.id, "remove");+ } else {+ await chatEndpointsApi.setup(target.id, { action: "remove" });+ }} else {await toolsApi.archiveConnection(target.id);}},onSuccess: (_connection, target) => {+ queryClient.invalidateQueries({ queryKey: ["email-inboxes", selectedCompanyId!] });queryClient.invalidateQueries({queryKey: queryKeys.chatEndpoints.list(selectedCompanyId!),});@@ -387,7 +391,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conneif (!memoryConnectorsEnabled && isMemoryConnectorId(appDefinitionSlug(entry))) return false;const definition = getAppStoreDefinition(appDefinitionSlug(entry));return (- chatConnectorsEnabled ||+ appDefinitionSlug(entry) === "agentmail" || chatConnectorsEnabled ||!definition?.methods.some((method) => method.purpose === "channel") ||appSupportsToolCatalogSetup(definition));@@ -436,7 +440,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conneslug,name: appDefinitionName(entry),description:- !chatConnectorsEnabled && chatProviderForSlug(slug)+ !chatConnectorsEnabled && slug !== "agentmail" && chatProviderForSlug(slug)? appCopyFor(slug).tagline: appDefinitionDescription(entry),brandKey: slug,@@ -449,6 +453,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne});}const nativeChatApps = [+ { slug: "agentmail", name: "AgentMail", description: "Give agents email inboxes and handle each conversation as a task." },{ slug: "imessage-photon", name: "iMessage Photon", description: "Message agents and share photos from Apple Messages with a dedicated Photon number." },{slug: "slack",@@ -480,7 +485,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne"Chat with agents from Telegram direct messages, groups, and topics.",},] as const;- for (const item of chatConnectorsEnabled ? nativeChatApps : []) {+ for (const item of nativeChatApps.filter(item => item.slug === "agentmail" || chatConnectorsEnabled)) {if (rowsBySlug.has(item.slug)) continue;rowsBySlug.set(item.slug, {key: `native-chat:${item.slug}`,@@ -563,9 +568,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne});}- for (const endpoint of chatConnectorsEnabled- ? (chatEndpointsQuery.data ?? [])- : []) {+ for (const endpoint of (chatEndpointsQuery.data ?? []).filter(endpoint => endpoint.provider === "agentmail" || chatConnectorsEnabled)) {if (endpoint.status === "archived") continue;let target = [...rowsBySlug.values()].find((row) => chatProviderForSlug(row.slug) === endpoint.provider,@@ -654,12 +657,12 @@ export function Browse({ renderAccountDetails = (connection) => connection.connegalleryQuery.isLoading ||applicationsQuery.isLoading ||connectionsQuery.isLoading ||- (chatConnectorsEnabled && chatEndpointsQuery.isLoading);+ chatEndpointsQuery.isLoading;const loadFailed =galleryQuery.isError ||applicationsQuery.isError ||connectionsQuery.isError ||- (chatConnectorsEnabled && chatEndpointsQuery.isError);+ chatEndpointsQuery.isError;const nothingMatches = visibleRows.length === 0 && !showCustomConnector;return (@@ -696,7 +699,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.connevoid galleryQuery.refetch();void applicationsQuery.refetch();void connectionsQuery.refetch();- if (chatConnectorsEnabled) void chatEndpointsQuery.refetch();+ void chatEndpointsQuery.refetch();}}>Try again@@ -836,7 +839,8 @@ export function ConnectorCard({disabled={!action.href}title={action.title}onClick={() => {- if (action.href) onNavigate(action.href);+ if (action.href) onNavigate(row.slug === "agentmail"+ ? `${action.href}&setupId=${crypto.randomUUID()}` : action.href);}}aria-label={`${action.label} ${row.name}`}>@@ -932,6 +936,7 @@ export function ConnectorCard({variant="destructive"onSelect={() => onRequestRemove({kind: "chat",+ provider: endpoint.provider,id: endpoint.id,accountName: `${endpoint.assignedAgentName} · ${row.name}`,providerName: row.name,diff --git a/ui/src/pages/apps/app-connect-policy.test.ts b/ui/src/pages/apps/app-connect-policy.test.tsindex a11c224f41..5756946ae5 100644--- a/ui/src/pages/apps/app-connect-policy.test.ts+++ b/ui/src/pages/apps/app-connect-policy.test.ts@@ -87,6 +87,7 @@ describe("app connect policy", () => {it("retains GitHub tools but denies chat-only deep links while chat connectors are disabled", () => {expect(canEnterAppsConnect(new URLSearchParams("source=github"))).toBe(true);+ expect(canEnterAppsConnect(new URLSearchParams("source=agentmail"))).toBe(true);for (const source of ["discord", "telegram", "microsoft-teams"]) {expect(canEnterAppsConnect(new URLSearchParams({ source })), source).toBe(false);expect(canEnterAppsConnect(new URLSearchParams({ source, reconnect: "connection-1" })), source).toBe(false);diff --git a/ui/src/pages/apps/app-connect-policy.ts b/ui/src/pages/apps/app-connect-policy.tsindex 089ceb8b9e..60dfbea7ed 100644--- a/ui/src/pages/apps/app-connect-policy.ts+++ b/ui/src/pages/apps/app-connect-policy.ts@@ -77,5 +77,5 @@ export function canEnterAppsConnect(// setup. Admit only known providers here; the setup flow then proves the// exact reconnect target is visible to the selected company before rendering.if (getConnectableAppDefinition(source) && searchParams.get("reconnect")?.trim()) return true;- return chatConnectorsEnabled ? appSupportsCatalogSetup(entry) : appSupportsToolCatalogSetup(entry);+ return source === "agentmail" || chatConnectorsEnabled ? appSupportsCatalogSetup(entry) : appSupportsToolCatalogSetup(entry);}diff --git a/ui/src/pages/apps/chat/ChatEndpointDetail.agentmail.test.tsx b/ui/src/pages/apps/chat/ChatEndpointDetail.agentmail.test.tsxnew file mode 100644index 0000000000..16b0d1cfe9--- /dev/null+++ b/ui/src/pages/apps/chat/ChatEndpointDetail.agentmail.test.tsx@@ -0,0 +1,118 @@+// @vitest-environment jsdom+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { ChatEndpointDetail } from "./ChatEndpointDetail";+import { queryKeys } from "@/lib/queryKeys";+import { TooltipProvider } from "@/components/ui/tooltip";++const mocks = vi.hoisted(() => ({+ tab: "settings", get: vi.fn(), conversations: vi.fn(), activity: vi.fn(), setup: vi.fn(),+ control: vi.fn(), getConnection: vi.fn(), grants: vi.fn(), installs: vi.fn(), agents: vi.fn(),+ navigate: vi.fn(),+}));+vi.mock("@/api/chatEndpoints", () => ({ chatEndpointsApi: {+ get: mocks.get, listConversations: mocks.conversations, listActivityPage: mocks.activity, setup: mocks.setup,+} }));+vi.mock("@/api/email", () => ({ emailApi: { control: mocks.control } }));+vi.mock("@/api/tools", () => ({ toolsApi: {+ getConnection: mocks.getConnection, listConnectionGrants: mocks.grants, getConnectionInstalls: mocks.installs,+} }));+vi.mock("@/api/agents", () => ({ agentsApi: { list: mocks.agents } }));+vi.mock("./EmailEndpointSetup", () => ({ EmailEndpointSettings: () => <h1>Email settings</h1> }));+vi.mock("@/context/BreadcrumbContext", () => ({ useBreadcrumbs: () => ({ setBreadcrumbs: () => {} }) }));+vi.mock("@/context/ToastContext", () => ({ useToast: () => ({ pushToast: () => {} }) }));+vi.mock("@/lib/router", () => ({+ useParams: () => ({ endpointId: "inbox", tab: mocks.tab }), useNavigate: () => mocks.navigate,+ Link: ({ children, to, ...props }: React.ComponentProps<"a"> & { to: string }) => <a href={to} {...props}>{children}</a>,+ Navigate: () => null,+}));++describe("AgentMail connection management tabs", () => {+ let root: Root;+ let container: HTMLDivElement;+ let client: QueryClient;+ const endpoint = { id: "inbox", companyId: "company", connectionId: "runtime", provider: "agentmail",+ assignedAgentId: "ralph", assignedAgentName: "Ralph", botExternalId: "[email protected]",+ allowUnlinkedPeople: false, status: "active", setup: { step: "complete" } };+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.tab = "settings";+ mocks.get.mockResolvedValue(endpoint);+ mocks.getConnection.mockResolvedValue({ id: "runtime", companyId: "company", config: { credentialConnectionId: "account" } });+ mocks.grants.mockResolvedValue({ grants: [{ status: "active", kind: "organization" }], capabilities: { canConfigure: true } });+ mocks.installs.mockResolvedValue({ installs: [{ targetType: "agent", targetId: "ralph" }] });+ mocks.agents.mockResolvedValue([{ id: "ralph", name: "Ralph", status: "idle" }]);+ mocks.conversations.mockResolvedValue([]);+ mocks.activity.mockResolvedValue({ items: [], nextCursor: null });+ mocks.control.mockResolvedValue({ id: "inbox", companyId: "company", status: "paused" });+ container = document.createElement("div"); document.body.append(container); root = createRoot(container);+ client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });+ });+ afterEach(async () => { await act(async () => root.unmount()); client.clear(); container.remove(); });+ const settle = () => act(async () => { await new Promise(resolve => setTimeout(resolve, 20)); });+ async function render(tab: string) {+ mocks.tab = tab;+ await act(async () => root.render(<QueryClientProvider client={client}><TooltipProvider><ChatEndpointDetail /></TooltipProvider></QueryClientProvider>));+ await vi.waitFor(() => {+ expect(container.textContent?.trim().length).toBeGreaterThan(0);+ expect(container.textContent).not.toMatch(/Loading (connection|access|conversations|activity)…/);+ }, { timeout: 3000 });+ }+ async function click(label: string) {+ const button = [...container.querySelectorAll("button")].find(node => node.textContent?.trim() === label);+ expect(button).toBeDefined(); await act(async () => button!.click());+ await vi.waitFor(() => expect(button!.disabled).toBe(false), { timeout: 3000 });+ await settle();+ }+ it("renders settings only on Settings and loads the saved credential on Access", async () => {+ await render("settings"); expect(container.textContent).toContain("Email settings");+ await render("access");+ expect(container.textContent).not.toContain("Email settings");+ expect(container.textContent).toContain("Any human in the organization");+ expect(container.textContent).toContain("Ralph");+ expect(mocks.grants).toHaveBeenCalledWith("account"); expect(mocks.installs).toHaveBeenCalledWith("account");+ expect(mocks.grants).not.toHaveBeenCalledWith("runtime");+ });+ it("shows an access failure rather than editable controls when the credential cannot load", async () => {+ mocks.getConnection.mockRejectedValue(new Error("Offline")); await render("access");+ expect(container.querySelector('[role="alert"]')?.textContent).toContain("could not be loaded");+ expect(container.querySelector('[role="radiogroup"]')).toBeNull(); expect(mocks.grants).not.toHaveBeenCalled();+ });+ it("uses inbox-local access for a legacy inbox with no saved account", async () => {+ mocks.getConnection.mockResolvedValue({ id: "runtime", config: {} }); await render("access");+ expect(mocks.grants).toHaveBeenCalledWith("runtime");+ });+ it("loads email conversations and links their tasks", async () => {+ mocks.conversations.mockResolvedValue([{ id: "thread", externalLabel: "Customer question", issueId: "task", issueTitle: "Help customer", state: "active" }]);+ await render("conversations"); expect(container.textContent).toContain("Customer question");+ expect(container.querySelector('a[href="/issues/task"]')).not.toBeNull();+ expect(container.textContent).not.toContain("Email settings"); expect(mocks.conversations).toHaveBeenCalledWith("inbox");+ });+ it("gives an email-specific empty state and reports conversation load errors", async () => {+ await render("conversations"); expect(container.textContent).toContain("Send an email");+ client.removeQueries({ queryKey: queryKeys.chatEndpoints.conversations("inbox") });+ mocks.conversations.mockRejectedValue(new Error("Offline")); await render("conversations");+ expect(container.querySelector('[role="alert"]')?.textContent).toContain("Conversations could not be loaded");+ expect(container.textContent).not.toContain("No email conversations yet");+ mocks.conversations.mockResolvedValue([]); await click("Try again"); expect(container.textContent).toContain("Send an email");+ });+ it("loads activity and routes pause through the email API without replacing cached chat detail with an email summary", async () => {+ mocks.activity.mockImplementation(async () => {+ // Query completion can follow the initial endpoint render, especially+ // while the complete UI suite is running. Wait for data, not a short sleep.+ await new Promise(resolve => setTimeout(resolve, 100));+ return { items: [{ id: "delivery", kind: "delivery", status: "failed", summary: "Email received", createdAt: "2026-10-01T00:00:00Z", replayable: true,+ resolutionActions: ["retry_anyway"] }, { id: "publication", kind: "publication", status: "delivery_unknown", summary: "Email send unconfirmed",+ createdAt: "2026-10-01T00:00:00Z", resolutionActions: ["mark_delivered", "retry_anyway", "cancel"] }], nextCursor: null };+ });+ await render("activity"); expect(container.textContent).toContain("Email received");+ expect(container.textContent).not.toContain("Email settings"); expect(container.textContent).not.toContain("Replay");+ expect([...container.querySelectorAll("button")].some(button => button.textContent?.trim() === "Resolve")).toBe(false);+ expect(container.querySelector('a[href="/apps/chat/inbox/conversations"]')).not.toBeNull();+ await click("Pause"); expect(mocks.control).toHaveBeenCalledWith("inbox", "pause"); expect(mocks.setup).not.toHaveBeenCalled();+ expect(client.getQueryData(queryKeys.chatEndpoints.detail("inbox"))).toMatchObject({ provider: "agentmail", assignedAgentName: "Ralph" });+ await click("Reconnect"); expect(mocks.navigate).toHaveBeenCalledWith("/apps/chat/inbox/settings");+ });+});diff --git a/ui/src/pages/apps/chat/ChatEndpointDetail.tsx b/ui/src/pages/apps/chat/ChatEndpointDetail.tsxindex 245d2f26b4..3203d0207e 100644--- a/ui/src/pages/apps/chat/ChatEndpointDetail.tsx+++ b/ui/src/pages/apps/chat/ChatEndpointDetail.tsx@@ -7,6 +7,9 @@ import { agentAvatarUrl } from "@/lib/agent-avatar-url";import { resolveAgentAppearance } from "@paperclipai/shared";import { GitHubBotManagement, GitHubReviews } from "./GitHubBotManagement";import { EmailEndpointSettings } from "./EmailEndpointSetup";+import { EmailConnectionAccess } from "@/components/EmailConnectionAccess";+import { emailApi } from "@/api/email";+import { toolsApi } from "@/api/tools";import { useEffect, useMemo, useState } from "react";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import {@@ -279,7 +282,8 @@ export function ChatEndpointDetail() {</Button></div>);- if (endpoint.provider === "agentmail") return <EmailEndpointSettings endpointId={endpoint.id} companyId={endpoint.companyId} />;+ if (endpoint.provider === "agentmail" && activeTab === "settings")+ return <EmailEndpointSettings key={endpoint.id} endpointId={endpoint.id} companyId={endpoint.companyId} assignedAgentName={endpoint.assignedAgentName} />;const setupIncomplete =endpoint.setup?.step !== "complete" &&["draft", "verifying", "attention", "revoked"].includes(endpoint.status);@@ -292,7 +296,7 @@ export function ChatEndpointDetail() {{endpoint.assignedAgentName} in {providerNames[endpoint.provider]}</h1><p className="mt-1 text-sm text-muted-foreground">- {endpoint.providerAccountLabel ?? "Chat connection"}+ {endpoint.providerAccountLabel ?? (endpoint.provider === "agentmail" ? endpoint.botExternalId ?? "Email connection" : "Chat connection")}</p>{endpoint.provider === "imessage-photon" && endpoint.botExternalId && endpoint.photonAllocation !== "shared" && (<div className="mt-2 flex flex-wrap items-center gap-2 text-sm">@@ -329,7 +333,8 @@ export function ChatEndpointDetail() {)}{activeTab === "reviews" && endpoint.provider === "github" && <GitHubReviews endpointId={endpoint.id} />}{activeTab === "access" && endpoint.provider === "github" && <GitHubBotManagement endpoint={endpoint} view="access" />}-{activeTab === "access" && endpoint.provider !== "github" && (+{activeTab === "access" && endpoint.provider === "agentmail" && <EmailAccess endpoint={endpoint} />}+{activeTab === "access" && endpoint.provider !== "github" && endpoint.provider !== "agentmail" && (<AccessendpointId={endpoint.id}allowUnlinked={endpoint.allowUnlinkedPeople}@@ -346,6 +351,32 @@ export function ChatEndpointDetail() {);}+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),+ });+ if (!endpoint.connectionId || agents.isError || connection.isError) return (+ <div className="space-y-3">+ <p role="alert" className="text-sm text-destructive">Connection access could not be loaded.</p>+ <Button variant="outline" onClick={() => { void agents.refetch(); void connection.refetch(); }}>Try again</Button>+ </div>+ );+ if (agents.isPending || connection.isPending) 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,@@ -744,10 +775,16 @@ function Conversations({<div><h2 className="text-lg font-semibold">Conversations</h2></div>- {rows.length === 0 ? (+ {query.isPending ? <p role="status" className="text-sm text-muted-foreground">Loading conversations…</p> : query.isError ? (+ <div className="space-y-3">+ <p role="alert" className="text-sm text-destructive">Conversations could not be loaded.</p>+ <Button variant="outline" onClick={() => void query.refetch()}>Try again</Button>+ </div>+ ) : rows.length === 0 ? (<p className="rounded-lg border border-dashed border-border p-4 text-sm text-muted-foreground">- No conversations yet. Address the agent in an enabled destination to- start one.+ {provider === "agentmail"+ ? "No email conversations yet. Send an email to this agent’s address to start one."+ : "No conversations yet. Address the agent in an enabled destination to start one."}</p>) : (<ul aria-label="Conversations" className="divide-y divide-border overflow-x-auto border-y border-border">@@ -877,20 +914,25 @@ function Activity({}),});const lifecycle = useMutation({- mutationFn: (action: "pause" | "resume" | "remove") =>- chatEndpointsApi.setup(endpointId, { action }),+ 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;}- queryClient.setQueryData(- queryKeys.chatEndpoints.detail(endpointId),- next,- );+ if (endpoint.provider !== "agentmail") queryClient.setQueryData(queryKeys.chatEndpoints.detail(endpointId), next);pushToast({title: action === "pause" ? "Connection paused" : "Connection resumed",tone: "success",@@ -1034,7 +1076,9 @@ function Activity({disabled={lifecycle.isPending}onClick={() =>navigate(- `/apps/chat/connect?provider=${endpoint.provider}&purpose=chat&resume=${endpoint.id}${status === "draft" || status === "verifying" ? "" : "&reconnect=1"}`,+ 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"}`,)}>@@ -1067,6 +1111,12 @@ function Activity({<h3 className="text-sm font-semibold">Recent activity</h3>+ {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 && (<div className="flex items-center gap-2 py-5 text-sm text-muted-foreground">@@ -1122,7 +1172,7 @@ function Activity({</p>)}</div>- {isReplayEligible(item) && (+ {endpoint.provider !== "agentmail" && isReplayEligible(item) && (<Buttonsize="sm"variant="outline"@@ -1138,7 +1188,7 @@ function Activity({Replay</Button>)}- {isResolutionEligible(item) && (+ {endpoint.provider !== "agentmail" && isResolutionEligible(item) && (<Buttonsize="sm"variant="outline"diff --git a/ui/src/pages/apps/chat/EmailEndpointSetup.test.tsx b/ui/src/pages/apps/chat/EmailEndpointSetup.test.tsxnew file mode 100644index 0000000000..8789c9fada--- /dev/null+++ b/ui/src/pages/apps/chat/EmailEndpointSetup.test.tsx@@ -0,0 +1,604 @@+// @vitest-environment jsdom+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { MemoryRouter, useLocation } from "react-router-dom";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { ApiError } from "@/api/client";+import { EmailEndpointSetup } from "./EmailEndpointSetup";++const mocks = vi.hoisted(() => ({ companyId: "company" as string | null, listAgents: vi.fn(), connect: vi.fn(), credentials: vi.fn(), control: vi.fn(), inspectNew: vi.fn(), inspect: vi.fn(), checkAddress: vi.fn(), setup: vi.fn(), listInboxes: vi.fn(), listConnections: vi.fn(), getConnection: vi.fn(), putInstalls: vi.fn() }));+vi.mock("@/lib/router", async () => import("react-router-dom"));+vi.mock("@/context/CompanyContext", () => ({ useCompany: () => ({ selectedCompanyId: mocks.companyId }) }));+vi.mock("@/components/chat/ChatSetupNavigation", () => ({ ChatSetupNavigation: () => null }));+vi.mock("@/api/agents", () => ({ agentsApi: { list: mocks.listAgents } }));+vi.mock("@/api/tools", () => ({ toolsApi: { putConnectionInstalls: mocks.putInstalls, listConnections: mocks.listConnections, getConnection: mocks.getConnection } }));+vi.mock("@/api/email", () => ({ emailApi: { credentials: mocks.credentials, control: mocks.control, inspect: mocks.inspectNew, connect: mocks.connect, inspectSaved: mocks.inspect, checkAddress: mocks.checkAddress, setup: mocks.setup, list: mocks.listInboxes } }));++let container: HTMLDivElement;+let root: Root;+let client: QueryClient;+beforeEach(() => {+ vi.resetAllMocks();+ vi.stubGlobal("ResizeObserver", class { observe() {} unobserve() {} disconnect() {} });+ mocks.companyId = "company";+ sessionStorage.clear();+ mocks.listAgents.mockResolvedValue([{ id: "ralph", name: "Ralph", status: "idle", permissions: {} }]);+ mocks.credentials.mockResolvedValue([]);+ mocks.inspectNew.mockResolvedValue({ scope: { scope_type: "organization" }, inboxes: [], domains: [] });+ mocks.inspect.mockResolvedValue({ scope: { scope_type: "organization" }, inboxes: [], domains: [] });+ mocks.checkAddress.mockImplementation(async (_company, _connection, { username, domain }) => ({ address: `${username}@${domain}`, status: "unknown" }));+ mocks.listInboxes.mockResolvedValue([]);+ mocks.listConnections.mockResolvedValue({ connections: [] });+ mocks.connect.mockResolvedValue({ id: "account" });+ mocks.setup.mockResolvedValue({ id: "endpoint", address: "[email protected]", connectionId: "inbox" });+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});+afterEach(async () => {+ await act(async () => root.unmount());+ client?.clear();+ container.remove();+ vi.unstubAllGlobals();+ vi.useRealTimers();+});+function Location() { const location = useLocation(); return <output data-testid="location" data-search={location.search}>{location.pathname}</output>; }+async function mount(saved = true, waitForCompany = true, agentId = "ralph", search = "") {+ client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });+ await act(async () => root.render(<QueryClientProvider client={client}><MemoryRouter initialEntries={[+ `/apps/chat/connect?provider=agentmail&agentId=${agentId}${saved ? "&connectionId=account" : ""}${search}`,+ ]}><EmailEndpointSetup /><Location /></MemoryRouter></QueryClientProvider>));+ if (waitForCompany) await vi.waitFor(() => expect(container.textContent).toContain(agentId === "support" ? "Support" : "Ralph"));+}+function button(name: string) {+ const value = [...document.querySelectorAll("button")].find(button => button.textContent?.trim() === name);+ expect(value).toBeDefined();+ return value!;+}+async function click(name: string) {+ if (name === "Create email address") await vi.waitFor(() => expect(button(name).disabled).toBe(false));+ await act(async () => button(name).click());+}+async function fill(selector: string, value: string) {+ await act(async () => {+ const input = document.querySelector<HTMLInputElement>(selector)!;+ expect(input).not.toBeNull();+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);+ input.dispatchEvent(new Event("input", { bubbles: true }));+ });+}++describe("AgentMail two-step setup", () => {+ it("starts a fresh catalog connection without adopting a previous draft's key or email step", async () => {+ sessionStorage.setItem("paperclip.agentmail-setup:company:new:ralph", JSON.stringify({+ connectionId: "old-inbox-key", step: 1, agentId: "ralph", requestId: crypto.randomUUID(),+ addressMode: "existing", inboxId: "[email protected]",+ }));+ const setupId = crypto.randomUUID();+ await mount(false, true, "ralph", `&setupId=${setupId}`);+ expect(container.querySelector('input[type="password"]')).not.toBeNull();+ expect(mocks.inspect).not.toHaveBeenCalled();+ await fill('input[type="password"]', "organization-test-key");+ await click("Continue");+ await vi.waitFor(() => expect(container.querySelector("#email-name")).not.toBeNull());+ expect(mocks.connect).toHaveBeenCalledWith("company", expect.objectContaining({ idempotencyKey: setupId }));+ expect(container.textContent).toContain("How it Works");+ expect(container.querySelector('[data-testid="location"]')?.textContent).toBe("/apps/chat/connect");+ });++ it("resumes the catalog's exact reserved inbox with its original account and request ID", async () => {+ const requestId = crypto.randomUUID();+ mocks.listInboxes.mockResolvedValue([{+ id: requestId, connectionId: "inbox-connection", assignedAgentId: "ralph",+ address: "[email protected]", status: "draft", receiveMode: "websocket",+ }]);+ mocks.getConnection.mockResolvedValue({ config: { credentialConnectionId: "original-account" } });+ await mount(false, true, "", `&resume=${requestId}`);+ await vi.waitFor(() => expect(button("Finish connecting").disabled).toBe(false));+ expect(mocks.inspect).toHaveBeenCalledWith("company", "original-account");+ expect(container.textContent).toContain("[email protected]");+ expect(container.querySelector("#email-name")).toBeNull();+ await click("Finish connecting");+ expect(mocks.setup).toHaveBeenCalledWith("company", expect.objectContaining({+ idempotencyKey: requestId, credentialConnectionId: "original-account", inboxId: "[email protected]",+ }));+ expect(mocks.connect).not.toHaveBeenCalled();+ });++ it("blocks a missing resume target rather than creating another inbox", async () => {+ await mount(false, true, "ralph", `&resume=${crypto.randomUUID()}`);+ await vi.waitFor(() => expect(container.textContent).toContain("This email setup could not be found"));+ expect(button("Create email address").disabled).toBe(true);+ expect(mocks.connect).not.toHaveBeenCalled();+ expect(mocks.setup).not.toHaveBeenCalled();+ });++ it("honors Finish setup when an older client saved a replacement under the original resume key", async () => {+ const requestId = crypto.randomUUID();+ sessionStorage.setItem(`paperclip.agentmail-setup:company:${requestId}:ralph`, JSON.stringify({+ connectionId: "wrong-account", agentId: "someone-else", requestId: crypto.randomUUID(), username: "replacement",+ }));+ mocks.listInboxes.mockResolvedValue([{ id: requestId, connectionId: "original-inbox", assignedAgentId: "ralph", address: "[email protected]", status: "draft", receiveMode: "websocket" }]);+ mocks.getConnection.mockResolvedValue({ config: { credentialConnectionId: "original-account" } });+ await mount(false, true, "ralph", `&resume=${requestId}`);+ await vi.waitFor(() => expect(button("Finish connecting").disabled).toBe(false));+ await click("Finish connecting");+ expect(mocks.setup).toHaveBeenLastCalledWith("company", expect.objectContaining({+ credentialConnectionId: "original-account", inboxId: "[email protected]", assignedAgentId: "ralph", idempotencyKey: requestId,+ }));+ });++ it("returns Cancel to Connectors rather than the credential permissions page", async () => {+ await mount();+ await click("Cancel");+ expect(container.querySelector('[data-testid="location"]')?.textContent).toBe("/apps");+ });++ it.each(["Done", "Email settings"])("sends %s to its email destination after completion", async action => {+ await mount();+ await click("Continue");+ await click("Create email address");+ await vi.waitFor(() => expect(container.textContent).toContain("Your agent’s email is ready"));+ await click(action);+ expect(container.querySelector('[data-testid="location"]')?.textContent)+ .toBe(action === "Done" ? "/apps" : "/apps/chat/endpoint/settings");+ });++ it("suggests an accessible account key and opens the editable email form without saving another secret", async () => {+ mocks.credentials.mockResolvedValue([+ { id: "inbox-key", label: "Inbox key", scope: "inbox", createdAt: "2026-10-01T14:00:00Z" },+ { id: "organization-account", label: "AgentMail account key", scope: "organization", createdAt: "2026-09-30T14:00:00Z" },+ ]);+ mocks.inspect.mockResolvedValue({ scope: { scope_type: "organization" }, inboxes: [],+ domains: [{ domain: "paperclip.example", status: "VERIFIED" }] });+ await mount(false);+ await vi.waitFor(() => expect(container.querySelector<HTMLSelectElement>("select")?.value).toBe("organization-account"));+ expect(container.querySelector('input[type="password"]')).toBeNull();+ await click("Continue");+ await vi.waitFor(() => expect(container.querySelector<HTMLSelectElement>("#email-domain")?.value).toBe("paperclip.example"));+ await fill("#email-name", "ralph-mail");+ await click("Create email address");+ expect(mocks.setup).toHaveBeenCalledWith("company", expect.objectContaining({+ credentialConnectionId: "organization-account", username: "ralph-mail", domain: "paperclip.example",+ }));+ expect(mocks.connect).not.toHaveBeenCalled();+ expect(mocks.putInstalls).not.toHaveBeenCalled();+ });++ it.each(["alternate", ""])("preserves the selected key choice across refresh (%s)", async selection => {+ mocks.credentials.mockResolvedValue([+ { id: "preferred", label: "Preferred account", scope: "organization", createdAt: "2026-10-01T14:00:00Z" },+ { id: "alternate", label: "Other account", scope: "organization", createdAt: "2026-09-30T14:00:00Z" },+ ]);+ await mount(false);+ await vi.waitFor(() => expect(container.querySelector<HTMLSelectElement>("select")?.value).toBe("preferred"));+ await act(async () => {+ const picker = container.querySelector<HTMLSelectElement>("select")!;+ picker.value = selection; picker.dispatchEvent(new Event("change", { bubbles: true }));+ });+ await act(async () => root.unmount()); client.clear(); root = createRoot(container);+ await mount(false);+ await vi.waitFor(() => expect(container.querySelector<HTMLSelectElement>("select")?.value).toBe(selection));+ if (!selection) expect(container.querySelector('input[type="password"]')).not.toBeNull();+ else {+ await click("Continue");+ await vi.waitFor(() => expect(mocks.inspect).toHaveBeenCalledWith("company", "alternate"));+ }+ });++ it("does not replace a newly entered key when saved-key discovery finishes later", async () => {+ let resolve!: (options: unknown[]) => void;+ mocks.credentials.mockReturnValue(new Promise(value => { resolve = value; }));+ await mount(false);+ await fill('input[type="password"]', "new-account-key");+ await act(async () => resolve([{ id: "saved", label: "AgentMail account key", scope: "organization", createdAt: "2026-10-01T14:00:00Z" }]));+ await vi.waitFor(() => expect(container.querySelector("select")).not.toBeNull());+ expect(container.querySelector<HTMLSelectElement>("select")?.value).toBe("");+ expect(container.querySelector<HTMLInputElement>('input[type="password"]')?.value).toBe("new-account-key");+ await click("Continue");+ await vi.waitFor(() => expect(mocks.connect).toHaveBeenCalledWith("company", expect.objectContaining({ apiKey: "new-account-key" })));+ });++ it("catches a pasted inbox key before the email step and requires an explicit existing-inbox choice", async () => {+ mocks.inspectNew.mockResolvedValue({ scope: { scope_type: "inbox" }, inboxes: [{ inbox_id: "[email protected]" }], domains: [] });+ mocks.inspect.mockResolvedValue({ scope: { scope_type: "inbox" }, inboxes: [{ inbox_id: "[email protected]" }], domains: [] });+ await mount(false);+ await fill('input[type="password"]', "inbox-secret");+ await click("Continue");+ await vi.waitFor(() => expect(container.textContent).toContain("That key only connects [email protected]"));+ expect(container.querySelector("#email-existing")).toBeNull();+ expect(mocks.connect).not.toHaveBeenCalled();+ await click("Use the existing inbox instead");+ await click("Continue");+ await vi.waitFor(() => expect(container.querySelector("#email-existing")).not.toBeNull());+ await click("Connect email address");+ expect(mocks.setup).toHaveBeenCalledWith("company", expect.objectContaining({ inboxId: "[email protected]" }));+ });++ it("keeps an already reserved inbox tied to its original account", async () => {+ const requestId = crypto.randomUUID();+ sessionStorage.setItem("paperclip.agentmail-setup:company:account:ralph", JSON.stringify({+ connectionId: "account", agentId: "ralph", step: 1, requestId,+ }));+ mocks.inspect.mockResolvedValue({ scope: { scope_type: "inbox" }, inboxes: [{ inbox_id: "[email protected]" }], domains: [] });+ mocks.listInboxes.mockResolvedValue([{ id: requestId, assignedAgentId: "ralph", address: "[email protected]", status: "error" }]);+ await mount();+ await vi.waitFor(() => expect(container.textContent).toContain("This address was created in AgentMail"));+ expect(container.textContent).not.toContain("Change AgentMail account");+ await click("Finish connecting");+ await vi.waitFor(() => expect(mocks.setup).toHaveBeenCalledWith("company", expect.objectContaining({+ credentialConnectionId: "account", idempotencyKey: requestId, inboxId: "[email protected]",+ })));+ });++ it("recovers an old locked draft at the key choice, with a new setup identity", async () => {+ const originalRequestId = crypto.randomUUID();+ const draftKey = "paperclip.agentmail-setup:company:account:ralph";+ sessionStorage.setItem(draftKey, JSON.stringify({ connectionId: "account", agentId: "ralph", step: 1, requestId: originalRequestId }));+ mocks.inspect.mockImplementation(async (_company, id) => ({+ scope: { scope_type: id === "account" ? "inbox" : "organization" },+ inboxes: [{ inbox_id: "[email protected]" }], domains: [],+ }));+ mocks.connect.mockResolvedValue({ id: "replacement-account" });+ await mount();+ await vi.waitFor(() => expect(container.textContent).toContain("That key only connects"));+ await fill('input[type="password"]', "replacement-secret");+ expect(sessionStorage.getItem(draftKey)).not.toContain("replacement-secret");+ await click("Continue");+ await vi.waitFor(() => expect(container.querySelector("#email-name")).not.toBeNull());+ const replacementRequest = mocks.connect.mock.calls[0][1];+ expect(replacementRequest).toMatchObject({ apiKey: "replacement-secret", agentIds: ["ralph"], grantKind: "organization", allAgents: false });+ expect(replacementRequest.idempotencyKey).not.toBe(originalRequestId);+ const nextSearch = container.querySelector('[data-testid="location"]')!.getAttribute("data-search")!;+ await act(async () => root.unmount());+ client.clear(); root = createRoot(container);+ await mount(false, true, "ralph", nextSearch.replace(/^\?/, "&"));+ await click("Create email address");+ await vi.waitFor(() => expect(mocks.setup).toHaveBeenCalledWith("company", expect.objectContaining({+ credentialConnectionId: "replacement-account", idempotencyKey: replacementRequest.idempotencyKey, username: "ralph",+ })));+ expect(mocks.connect).toHaveBeenCalledTimes(1);+ });++ it.each([false, true])("preserves an account switch from a resumed unallocated draft across refresh (%s cleanup failure)", async cleanupFails => {+ const requestId = crypto.randomUUID();+ const draftKey = `paperclip.agentmail-setup:company:${requestId}:ralph`;+ sessionStorage.setItem(draftKey, JSON.stringify({+ connectionId: "account", agentId: "ralph", step: 1, requestId,+ }));+ mocks.listInboxes.mockResolvedValue([{ id: requestId, assignedAgentId: "ralph", address: null, status: "draft" }]);+ mocks.inspect.mockImplementation(async (_company, id) => ({ scope: { scope_type: id === "account" ? "inbox" : "organization" }, inboxes: [{ inbox_id: "[email protected]" }], domains: [] }));+ mocks.connect.mockResolvedValue({ id: "replacement" });+ mocks.control.mockImplementation(async () => {+ if (cleanupFails) throw new Error("Draft cleanup failed");+ mocks.listInboxes.mockResolvedValue([]);+ });+ await mount(true, true, "ralph", `&resume=${requestId}`);+ await vi.waitFor(() => expect(container.textContent).toContain("That key only connects"));+ await fill('input[type="password"]', "new-account-key");+ await click("Continue");+ await vi.waitFor(() => expect(mocks.control).toHaveBeenCalledWith(requestId, "remove"));+ if (cleanupFails) {+ await vi.waitFor(() => expect(container.textContent).toContain("Draft cleanup failed"));+ expect(mocks.connect).toHaveBeenCalledTimes(1);+ expect(JSON.parse(sessionStorage.getItem(draftKey)!).requestId).toBe(requestId);+ expect(container.querySelector('[data-testid="location"]')!.getAttribute("data-search")).toContain(`resume=${requestId}`);+ return;+ }+ await vi.waitFor(() => expect(container.querySelector("#email-name")).not.toBeNull());+ expect(mocks.connect.mock.invocationCallOrder[0]).toBeLessThan(mocks.control.mock.invocationCallOrder[0]);+ const nextSearch = container.querySelector('[data-testid="location"]')!.getAttribute("data-search")!;+ const nextId = new URLSearchParams(nextSearch).get("setupId")!;+ expect(nextId).not.toBe(requestId);+ expect(nextSearch).not.toContain("resume=");+ await act(async () => root.unmount());+ client.clear(); root = createRoot(container);+ await mount(false, true, "ralph", nextSearch.replace(/^\?/, "&"));+ await click("Create email address");+ expect(mocks.setup).toHaveBeenCalledWith("company", expect.objectContaining({ credentialConnectionId: "replacement", idempotencyKey: nextId, username: "ralph" }));+ });++ it("checks the initial address and debounces edits while ignoring stale responses", async () => {+ await mount();+ vi.useFakeTimers();+ await click("Continue");+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });+ expect(container.textContent).toContain("Checking address");+ expect(button("Create email address").disabled).toBe(true);+ await act(async () => { await vi.advanceTimersByTimeAsync(350); });+ expect(mocks.checkAddress).toHaveBeenLastCalledWith("company", "account", { username: "ralph", domain: "agentmail.to" }, expect.any(AbortSignal));+ let resolveOld!: (result: unknown) => void;+ mocks.checkAddress.mockImplementationOnce(() => new Promise(resolve => { resolveOld = resolve; }));+ await fill("#email-name", "ralph-old");+ await act(async () => { await vi.advanceTimersByTimeAsync(350); });+ const oldSignal = mocks.checkAddress.mock.calls[1][3] as AbortSignal;+ await fill("#email-name", "ralph-n");+ await act(async () => { await vi.advanceTimersByTimeAsync(200); });+ await fill("#email-name", "ralph-new");+ expect(oldSignal.aborted).toBe(true);+ await act(async () => { resolveOld({ address: "[email protected]", status: "taken" }); });+ expect(container.querySelector("#email-address-error")).toBeNull();+ await act(async () => { await vi.advanceTimersByTimeAsync(349); });+ expect(mocks.checkAddress).toHaveBeenCalledTimes(2);+ await act(async () => { await vi.advanceTimersByTimeAsync(1); });+ expect(mocks.checkAddress).toHaveBeenCalledTimes(3);+ expect(mocks.checkAddress.mock.calls[2][2].username).toBe("ralph-new");+ expect(container.textContent).toContain("confirms availability when you create");+ expect(container.textContent).not.toContain("is available");+ });++ it("offers clickable alternatives for a taken initial address and checks the selection", async () => {+ mocks.checkAddress.mockResolvedValueOnce({ address: "[email protected]", status: "taken" });+ await mount();+ await click("Continue");+ await vi.waitFor(() => expect(container.querySelector("#email-address-error")?.textContent).toContain("already in use"));+ expect(button("Create email address").disabled).toBe(true);+ await click("[email protected]");+ expect(container.querySelector<HTMLInputElement>("#email-name")?.value).toBe("ralph-agent");+ expect(container.querySelector("#email-address-error")).toBeNull();+ await vi.waitFor(() => expect(mocks.checkAddress).toHaveBeenLastCalledWith("company", "account", { username: "ralph-agent", domain: "agentmail.to" }, expect.any(AbortSignal)));+ expect(mocks.setup).not.toHaveBeenCalled();+ });++ it("defaults to a verified custom domain beside the name and preserves an explicit selection on reload", async () => {+ mocks.inspect.mockResolvedValue({ scope: { scope_type: "organization" }, inboxes: [], domains: [+ { domain_id: "pending", domain: "pending.example", status: "PENDING" },+ { domain_id: "custom", domain: "paperclip.example", status: "VERIFIED" },+ ] });+ await mount();+ await click("Continue");+ await vi.waitFor(() => expect(container.querySelector<HTMLSelectElement>("#email-domain")?.value).toBe("paperclip.example"));+ expect(container.querySelector("#email-domain")?.closest("details")).toBeNull();+ expect(container.querySelector('option[value="pending.example"]')).toBeNull();+ await act(async () => {+ const select = container.querySelector<HTMLSelectElement>("#email-domain")!;+ select.value = "agentmail.to";+ select.dispatchEvent(new Event("change", { bubbles: true }));+ });+ await vi.waitFor(() => expect(mocks.checkAddress).toHaveBeenLastCalledWith("company", "account", { username: "ralph", domain: "agentmail.to" }, expect.any(AbortSignal)));+ await act(async () => root.unmount());+ client.clear();+ root = createRoot(container);+ await mount();+ await vi.waitFor(() => expect(container.querySelector<HTMLSelectElement>("#email-domain")?.value).toBe("agentmail.to"));+ });++ it("shows lookup failures without mislabeling the address taken or blocking creation", async () => {+ mocks.checkAddress.mockRejectedValue(new Error("AgentMail is rate limiting requests."));+ await mount();+ await click("Continue");+ await vi.waitFor(() => expect(container.textContent).toContain("Could not check this address"));+ expect(container.querySelector("#email-address-error")).toBeNull();+ expect(button("Create email address").disabled).toBe(false);+ });+ it("restores saved progress after the company loads without overwriting the draft", async () => {+ const key = "paperclip.agentmail-setup:company:account:ralph";+ const requestId = crypto.randomUUID();+ const draft = JSON.stringify({ connectionId: "account", step: 1, agentId: "ralph", username: "ralph-team", requestId });+ sessionStorage.setItem(key, draft);+ mocks.companyId = null;+ await mount(true, false);+ expect(container.textContent).toContain("Loading email setup");+ expect(sessionStorage.getItem(key)).toBe(draft);+ mocks.companyId = "company";+ await mount();+ await vi.waitFor(() => expect(container.querySelector<HTMLInputElement>("#email-name")?.value).toBe("ralph-team"));+ await click("Create email address");+ await vi.waitFor(() => expect(mocks.setup).toHaveBeenCalledWith("company", expect.objectContaining({ username: "ralph-team", idempotencyKey: requestId })));+ });++ it("creates from the email field without a review step and keeps advanced settings collapsed", async () => {+ await mount();+ await click("Continue");+ await vi.waitFor(() => expect(container.querySelector<HTMLInputElement>("#email-name")?.value).toBe("ralph"));+ expect(container.querySelector("details")?.open).toBe(false);+ expect(container.textContent).not.toContain("Review email address");+ await click("Create email address");+ await vi.waitFor(() => expect(container.textContent).toContain("Your agent’s email is ready"));+ expect(mocks.connect).not.toHaveBeenCalled();+ expect(mocks.putInstalls).not.toHaveBeenCalled();+ expect(mocks.setup).toHaveBeenCalledWith("company", expect.objectContaining({ assignedAgentId: "ralph", username: "ralph", domain: "agentmail.to", receiveMode: "websocket" }));+ expect(sessionStorage.getItem("paperclip.agentmail-setup:company:account:ralph")).toBeNull();+ });++ it("shows a taken address beside the field, clears it on editing, and resumes the same request after reload", async () => {+ mocks.setup.mockRejectedValueOnce(new ApiError("This email address is already in use. Choose a different address.", 409, { code: "agentmail_address_taken" }));+ await mount();+ await click("Continue");+ await click("Create email address");+ await vi.waitFor(() => expect(container.querySelector("#email-name")?.getAttribute("aria-invalid")).toBe("true"));+ expect(container.querySelector("#email-address-error")?.textContent).toContain("already in use");+ expect(button("Create email address").disabled).toBe(true);+ const firstRequest = mocks.setup.mock.calls[0][1];+ await fill("#email-name", "");+ expect(container.querySelector<HTMLInputElement>("#email-name")?.value).toBe("");+ await fill("#email-name", "ralph-team");+ expect(container.querySelector("#email-address-error")).toBeNull();+ await act(async () => root.unmount());+ client.clear();+ root = createRoot(container);+ await mount();+ await vi.waitFor(() => expect(container.querySelector<HTMLInputElement>("#email-name")?.value).toBe("ralph-team"));+ await click("Create email address");+ await vi.waitFor(() => expect(mocks.setup).toHaveBeenCalledTimes(2));+ expect(mocks.setup.mock.calls[1][1]).toMatchObject({ username: "ralph-team", idempotencyKey: firstRequest.idempotencyKey });+ });++ it("asks for one API key with the direct link and saves the requested access defaults", async () => {+ await mount(false);+ expect(container.querySelector('a[href="https://console.agentmail.to/dashboard/api-keys"]')).not.toBeNull();+ expect(container.querySelectorAll('input[type="password"]')).toHaveLength(1);+ expect(container.querySelectorAll('input[type="radio"]')).toHaveLength(0);+ await fill('input[type="password"]', "private-test-key");+ expect(sessionStorage.getItem("paperclip.agentmail-setup:company:new:ralph")).not.toContain("private-test-key");+ await click("Continue");+ await vi.waitFor(() => expect(container.querySelector("#email-name")).not.toBeNull());+ expect(mocks.connect).toHaveBeenCalledWith("company", expect.objectContaining({ apiKey: "private-test-key", grantKind: "organization", allAgents: false, agentIds: ["ralph"] }));+ expect(container.querySelector('input[type="password"]')).toBeNull();+ expect(sessionStorage.getItem("paperclip.agentmail-setup:company:new:ralph")).not.toContain("private-test-key");+ });++ it("flags an address already present in the connected account before submission", async () => {+ mocks.inspect.mockResolvedValue({ scope: { scope_type: "organization" }, inboxes: [{ inbox_id: "[email protected]" }], domains: [] });+ await mount();+ await click("Continue");+ await vi.waitFor(() => expect(container.querySelector("#email-address-error")?.textContent).toContain("already in use"));+ expect(button("Create email address").disabled).toBe(true);+ expect(mocks.setup).not.toHaveBeenCalled();+ await click("Use an existing inbox");+ expect(container.querySelector("#email-existing")).not.toBeNull();+ });++ it("does not restore another requested agent's new-account draft", async () => {+ sessionStorage.setItem("paperclip.agentmail-setup:company:new:ralph", JSON.stringify({+ agentId: "ralph", step: 1, connectionId: "ralph-account", username: "ralph", requestId: crypto.randomUUID(),+ }));+ mocks.listAgents.mockResolvedValue([+ { id: "ralph", name: "Ralph", status: "idle", permissions: {} },+ { id: "support", name: "Support", status: "idle", permissions: {} },+ ]);+ await mount(false, true, "support");+ expect(container.querySelector('input[type="password"]')).not.toBeNull();+ await fill('input[type="password"]', "new-key");+ await click("Continue");+ await vi.waitFor(() => expect(container.querySelector<HTMLInputElement>("#email-name")?.value).toBe("support"));+ expect(mocks.connect).toHaveBeenCalledWith("company", expect.objectContaining({ agentIds: ["support"] }));+ expect(mocks.inspect).not.toHaveBeenCalledWith("company", "ralph-account");+ });++ it("submits the final agent with the original setup request after changing agents and reloading", async () => {+ mocks.listAgents.mockResolvedValue([+ { id: "ralph", name: "Ralph", status: "idle", permissions: {} },+ { id: "support", name: "Support", status: "idle", permissions: {} },+ ]);+ await mount(false);+ await fill('input[type="password"]', "new-key");+ await click("Continue");+ await vi.waitFor(() => expect(container.querySelector("#email-name")).not.toBeNull());+ await click("Back");+ await act(async () => container.querySelector<HTMLButtonElement>('#email-agent')!.click());+ await vi.waitFor(() => expect(document.querySelector('[aria-label="Select Support"]')).not.toBeNull());+ await act(async () => document.querySelector<HTMLElement>('[aria-label="Select Support"]')!.click());+ await act(async () => root.unmount());+ client.clear();+ root = createRoot(container);+ await mount(false, false);+ await vi.waitFor(() => expect(button("Continue").disabled).toBe(false));+ await click("Continue");+ await vi.waitFor(() => expect(container.querySelector<HTMLInputElement>("#email-name")?.value).toBe("support"));+ // Access is updated by email setup, without a separate agent-config permission.+ expect(mocks.putInstalls).not.toHaveBeenCalled();+ expect(mocks.connect).toHaveBeenCalledTimes(1);+ await click("Create email address");+ await vi.waitFor(() => expect(mocks.setup).toHaveBeenCalledWith("company", expect.objectContaining({ assignedAgentId: "support", idempotencyKey: mocks.connect.mock.calls[0][1].idempotencyKey })));+ });++ it.each(["new", "existing"])("resumes its allocated %s inbox after a provider failure and reload", async addressMode => {+ const requestId = crypto.randomUUID();+ sessionStorage.setItem("paperclip.agentmail-setup:company:account:ralph", JSON.stringify({+ connectionId: "account", agentId: "ralph", step: 1, username: "ralph", inboxId: "[email protected]", addressMode, requestId,+ }));+ const endpoint = { id: requestId, assignedAgentId: "ralph", address: "[email protected]", status: "draft" };+ // Creation succeeds before a later runtime-key request fails.+ mocks.setup.mockImplementationOnce(async () => {+ mocks.listInboxes.mockResolvedValue([endpoint]);+ mocks.inspect.mockResolvedValue({ scope: { scope_type: "organization" }, inboxes: [{ inbox_id: endpoint.address }], domains: [] });+ throw new ApiError("Could not create runtime key", 502, {});+ });+ await mount();+ await vi.waitFor(() => expect(button(addressMode === "new" ? "Create email address" : "Connect email address").disabled).toBe(false));+ await click(addressMode === "new" ? "Create email address" : "Connect email address");+ await vi.waitFor(() => expect(container.textContent).toContain("Could not create runtime key"));+ await vi.waitFor(() => expect(button("Finish connecting").disabled).toBe(false));+ await act(async () => root.unmount());+ client.clear();+ root = createRoot(container);+ await mount();+ await vi.waitFor(() => expect(button("Finish connecting").disabled).toBe(false));+ expect(container.querySelector("#email-address-error")).toBeNull();+ expect(container.textContent).toContain(endpoint.address);+ expect(container.querySelector("#email-name")).toBeNull();+ expect(container.querySelector("#email-existing")).toBeNull();+ await click("Back");+ expect(container.querySelector<HTMLButtonElement>('#email-agent')?.disabled).toBe(true);+ await click("Continue");+ await vi.waitFor(() => expect(button("Finish connecting").disabled).toBe(false));+ await click("Finish connecting");+ await vi.waitFor(() => expect(container.textContent).toContain("Your agent’s email is ready"));+ expect(mocks.setup).toHaveBeenLastCalledWith("company", expect.objectContaining({ inboxId: endpoint.address, assignedAgentId: "ralph", idempotencyKey: requestId }));+ });++ it("lets a failed setup choose another address without deleting or reusing its allocated inbox", async () => {+ const requestId = crypto.randomUUID();+ const draftKey = `paperclip.agentmail-setup:company:${requestId}:ralph`;+ sessionStorage.setItem(draftKey, JSON.stringify({ connectionId: "account", agentId: "ralph", step: 1, requestId }));+ mocks.listInboxes.mockResolvedValue([{ id: requestId, assignedAgentId: "ralph", address: "[email protected]", status: "draft" }]);+ mocks.inspect.mockResolvedValue({ scope: { scope_type: "organization" }, inboxes: [{ inbox_id: "[email protected]" }], domains: [{ domain_id: "custom", domain: "paperclip.example", status: "VERIFIED" }] });+ await mount(true, true, "ralph", `&resume=${requestId}`);+ await vi.waitFor(() => expect(button("Finish connecting").disabled).toBe(false));+ await click("Choose a different address");+ expect(container.querySelector<HTMLInputElement>("#email-name")?.readOnly).toBe(false);+ expect(container.querySelector<HTMLSelectElement>("#email-domain")?.disabled).toBe(false);+ expect(container.querySelector<HTMLSelectElement>("#email-domain")?.value).toBe("paperclip.example");+ await fill("#email-name", "another-address");+ const nextSearch = container.querySelector('[data-testid="location"]')!.getAttribute("data-search")!;+ const nextRequestId = new URLSearchParams(nextSearch).get("setupId")!;+ expect(nextRequestId).not.toBe(requestId);+ expect(JSON.parse(sessionStorage.getItem(draftKey)!).requestId).toBe(requestId);+ await act(async () => root.unmount());+ client.clear();+ root = createRoot(container);+ await mount(true, true, "ralph", `&setupId=${nextRequestId}`);+ await click("Create email address");+ expect(mocks.setup).toHaveBeenLastCalledWith("company", expect.objectContaining({+ username: "another-address", domain: "paperclip.example", idempotencyKey: nextRequestId,+ }));+ expect(mocks.control).not.toHaveBeenCalled();+ await act(async () => root.unmount());+ client.clear();+ root = createRoot(container);+ await mount(true, true, "ralph", `&resume=${requestId}`);+ await vi.waitFor(() => expect(button("Finish connecting").disabled).toBe(false));+ await click("Finish connecting");+ expect(mocks.setup).toHaveBeenLastCalledWith("company", expect.objectContaining({+ inboxId: "[email protected]", idempotencyKey: requestId,+ }));+ });++ it("does not treat another setup's allocated address as its own retry", async () => {+ mocks.inspect.mockResolvedValue({ scope: { scope_type: "organization" }, inboxes: [{ inbox_id: "[email protected]" }], domains: [] });+ mocks.listInboxes.mockResolvedValue([{ id: crypto.randomUUID(), assignedAgentId: "ralph", address: "[email protected]", status: "draft" }]);+ await mount();+ await click("Continue");+ await vi.waitFor(() => expect(container.querySelector("#email-address-error")?.textContent).toContain("already in use"));+ expect(button("Create email address").disabled).toBe(true);+ await click("Use an existing inbox");+ const option = container.querySelector<HTMLOptionElement>('option[value="[email protected]"]');+ expect(option?.disabled).toBe(true);+ expect(mocks.setup).not.toHaveBeenCalled();+ });++ it("retries loading setup progress without losing the entered key or reloading", async () => {+ mocks.listInboxes.mockRejectedValueOnce(new Error("Service unavailable"));+ await mount(false);+ await fill('input[type="password"]', "private-test-key");+ await vi.waitFor(() => expect(container.textContent).toContain("Could not load email setup progress"));+ expect(button("Continue").disabled).toBe(true);+ await click("Retry loading inboxes");+ await vi.waitFor(() => expect(button("Continue").disabled).toBe(false));+ expect(container.querySelector<HTMLInputElement>('input[type="password"]')?.value).toBe("private-test-key");+ await click("Continue");+ await vi.waitFor(() => expect(container.querySelector("#email-name")).not.toBeNull());+ expect(mocks.listInboxes).toHaveBeenCalledTimes(2);+ expect(mocks.putInstalls).not.toHaveBeenCalled();+ });++ it("preserves the existing low-trust work-boundary gate", async () => {+ mocks.listAgents.mockResolvedValue([{ id: "ralph", name: "Ralph", status: "idle", permissions: { trustPreset: "low_trust_review" } }]);+ await mount();+ expect(container.textContent).toContain("needs a work boundary");+ expect(button("Continue").disabled).toBe(true);+ expect(mocks.setup).not.toHaveBeenCalled();+ });+});diff --git a/ui/src/pages/apps/chat/EmailEndpointSetup.tsx b/ui/src/pages/apps/chat/EmailEndpointSetup.tsxindex 527d140313..a1d1654789 100644--- a/ui/src/pages/apps/chat/EmailEndpointSetup.tsx+++ b/ui/src/pages/apps/chat/EmailEndpointSetup.tsx@@ -1,11 +1,17 @@+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, useState } from "react";+import { useEffect, useRef, useState } from "react";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import {ArrowLeft,ArrowRight,Check,- AlertTriangle,+ Copy,+ ExternalLink,Mail,} from "lucide-react";import { useCompany } from "@/context/CompanyContext";@@ -18,11 +24,11 @@ import { emailApi } from "@/api/email";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";-import { RadioCardGroup } from "@/components/ui/radio-card";-import { Avatar, AvatarFallback } from "@/components/ui/avatar";-import { AgentIcon } from "@/components/AgentIconPicker";-import { SearchableSelect } from "@/components/SearchableSelect";-import { AccessStep } from "@/features/connections/ConnectionSetupFlow";+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 {@@ -46,524 +52,399 @@ import type {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 companyId = selectedCompanyId ?? "";- const [connectionId, setConnectionId] = useState(- params.get("connectionId") ?? "",- );- const [step, setStep] = useState(params.get("connectionId") ? 3 : 0);- const [agentId, setAgentId] = useState(params.get("agentId") ?? "");- const [grantKind, setGrantKind] = useState<"user" | "organization" | "agent">(- "user",- );- const [agentAccess, setAgentAccess] = useState<"specific" | "all">(- "specific",- );- const [agentIds, setAgentIds] = useState<Set<string>>(- new Set(params.get("agentId") ? [params.get("agentId")!] : []),- );+ 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 [requestId] = useState(() => crypto.randomUUID());- const [addressMode, setAddressMode] = useState("new");- const [inboxId, setInboxId] = useState("");- const [username, setUsername] = useState("");- const [domain, setDomain] = useState("agentmail.to");- const [mode, setMode] = useState<"websocket" | "webhook">("websocket");+ 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 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 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],+ const scoped = lowTrustBoundaryHasScope(getLowTrustBoundary(chosen?.permissions));+ const inspected = useQuery({ queryKey: ["email-credential-inspect", companyId, connectionId],queryFn: () => emailApi.inspectSaved(companyId, connectionId),- enabled: !!companyId && !!connectionId && step >= 3,+ 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,});- const inboxes = useQuery({- queryKey: ["email-inboxes", companyId],- queryFn: () => emailApi.list(companyId),- enabled: !!companyId,- });+ 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) {+ 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]);+ }, [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: () =>- emailApi.connect(companyId, {- apiKey,- grantKind: grantKind === "organization" ? "organization" : "user",- allAgents: agentAccess === "all",- agentIds: [...agentIds],- idempotencyKey: requestId,- }),- onSuccess: (result) => {+ 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("");- setConnectionId(result.id);- setStep(2);- void cache.invalidateQueries({- queryKey: queryKeys.tools.connections(companyId),- });+ 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); },});- const agentDetail = useQuery({- queryKey: queryKeys.agents.detail(agentId),- queryFn: () => agentsApi.get(agentId),- enabled: !!agentId && trustOpen,- });+ 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,- ),+ 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),- });+ void cache.invalidateQueries({ queryKey: queryKeys.agents.list(companyId) });},});const setup = useMutation({- mutationFn: () =>- emailApi.setup(companyId, {- assignedAgentId: agentId,- credentialConnectionId: connectionId,- ...(addressMode === "existing" ? { inboxId } : { username, domain }),- receiveMode: mode,- idempotencyKey: requestId,- }),+ 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.tools.connectionInstalls(connectionId),- });- setStep(6);+ 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 =- addressMode === "existing" ? inboxId : `${username}@${domain}`;- const labels =- step < 3- ? ["Access", "API key", "Connected"]- : ["Agent", "Email address", "Review"];- const current = step < 3 ? step : Math.min(step - 3, 2);- const error = connect.error ?? setup.error ?? inspected.error ?? agents.error;- const trustNotice = chosen && (- <div- className="space-y-3 rounded-lg border border-border bg-muted/30 p-4"- role={lowTrust && scoped ? "note" : "alert"}- >- <p className="flex items-center gap-2 text-sm font-medium">- {lowTrust && scoped ? (- <Check className="size-4" />- ) : (- <AlertTriangle className="size-4 text-(--status-agent-paused)" />- )}- {lowTrust- ? scoped- ? "Low-trust review configured"- : "Low trust needs a work boundary"- : `${chosen.name} is not a low-trust agent`}- </p>- <p className="text-sm text-muted-foreground">- {lowTrust- ? "Email tasks stay inside the configured project or root task boundary. Output is quarantined for trusted review."- : "Email can contain malicious instructions. We recommend Low-trust review to limit the agent’s access to Paperclip work."}- </p>- <p className="text-xs text-muted-foreground">Low-trust execution also requires isolated workspaces and an active sandbox environment in the agent’s runtime settings.</p>- <Button- size="sm"- variant="outline"- onClick={() => {- setPermissions(chosen.permissions);- setTrustOpen(true);- }}- >- {lowTrust ? "Review trust settings" : "Configure low trust"}+ 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>- );- return (- <div className="mx-auto max-w-3xl space-y-6 p-6">- <header className="flex items-center justify-between gap-3">- <h1 className="text-xl font-bold">- {step < 3- ? "Connect AgentMail"- : step === 6- ? "Your agent’s email is ready"- : "Give an agent an email address"}- </h1>- <Button- variant="ghost"- onClick={() =>- navigate(- connectionId ? `/apps/${connectionId}/permissions` : "/apps",- )- }- >- {step === 6 ? "Close" : "Cancel"}- </Button>- </header>- <ChatSetupNavigation- labels={labels}- step={current}- availableStep={current}- disabled={connect.isPending || setup.isPending || step === 2 || step === 6}- onSelect={(index) => setStep(step < 3 ? index : index + 3)}- />- {step === 0 && (- <AccessStep- companyId={companyId}- authKind="api_key"- grantKinds={["user", "organization"]}- grantKind={grantKind}- setGrantKind={setGrantKind}- installChoice={agentAccess}- setInstallChoice={setAgentAccess}- installAgentIds={agentIds}- setInstallAgentIds={setAgentIds}- onBack={() => navigate("/apps")}- onContinue={() => setStep(1)}- submitLabel="Continue"- />- )}- {step === 1 && (- <form- className="space-y-5"- onSubmit={(e) => {- e.preventDefault();- connect.mutate();- }}- >- <section className="space-y-4 rounded-xl border border-border p-6">- <h2 className="text-lg font-semibold">- Add your AgentMail API key- </h2>- <Label htmlFor="email-api-key">API key</Label>- <Input- id="email-api-key"- type="password"- autoComplete="off"- value={apiKey}- onChange={(e) => setApiKey(e.target.value)}- placeholder="Paste your AgentMail API key"- />- <a- href="https://console.agentmail.to"- target="_blank"- rel="noreferrer"- className="text-sm underline"- >- Get a key in AgentMail ↗- </a>- </section>- <div className="flex justify-between">- <Button type="button" variant="ghost" onClick={() => setStep(0)}>- Back- </Button>- <Button disabled={!apiKey.trim() || connect.isPending}>- {connect.isPending ? "Connecting…" : "Connect AgentMail"}- </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>- </form>- )}- {step === 2 && (- <section className="space-y-5 rounded-xl border border-border p-6">- <h2 className="text-lg font-semibold">AgentMail is connected</h2>- <p className="text-sm text-muted-foreground">- Next, give an agent an email address from Permissions.- </p>- <div className="flex justify-end">- <Button- onClick={() => navigate(`/apps/${connectionId}/permissions`)}- >- Open permissions <ArrowRight className="size-4" />- </Button>+ </> : <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>- </section>- )}- {step === 3 && (- <>- <section className="space-y-4 rounded-xl border border-border p-6">- <h2 className="text-lg font-semibold">- Who should handle this inbox?- </h2>- <p className="text-sm text-muted-foreground">- Incoming email will create tasks assigned to this agent.- </p>- <Label>Agent</Label>- <SearchableSelect- value={agentId}- placeholder="Choose an agent"- searchPlaceholder="Search all agents…"- emptyMessage="No agents found."- groups={[- {- id: "agents",- options: (agents.data ?? [])- .filter(- (a) =>- !["terminated", "pending_approval"].includes(a.status),- )- .map((a) => ({- key: a.id,- value: a.id,- label: a.name,- icon: a.icon,- })),- },- ]}- onValueChange={(id, option) => {- setAgentId(id);- setUsername(- option.label- .toLowerCase()- .replace(/[^a-z0-9._-]+/g, "-")- .slice(0, 64),- );- }}- renderValue={(option) =>- option && (- <span className="flex items-center gap-2">- <Avatar size="sm">- <AvatarFallback>- <AgentIcon icon={String(option.icon ?? "bot")} />- </AvatarFallback>- </Avatar>- {option.label}- </span>- )- }- />- <p className="text-xs text-muted-foreground">- Activating this inbox also adds the agent to this connection’s- allowed agents.- </p>- </section>- {trustNotice}- </>- )}- {step === 4 && (- <>- <section className="space-y-5 rounded-xl border border-border p-6">- <h2 className="text-lg font-semibold">- Choose {chosen?.name}’s email address- </h2>- <RadioCardGroup- ariaLabel="Email address source"- value={addressMode}- onValueChange={setAddressMode}- options={[- {- value: "new",- title: "Create a new address",- disabled: scopedKey,- },- { value: "existing", title: "Use an existing inbox" },- ]}- />- {addressMode === "new" ? (- <div className="space-y-2">- <Label htmlFor="email-name">Email address</Label>- <div className="flex items-center gap-2">- <Input- id="email-name"- value={username}- onChange={(e) => setUsername(e.target.value.toLowerCase())}- />- <span className="text-sm text-muted-foreground">- @{domain}- </span>- </div>- </div>- ) : (- <div className="space-y-2">- <Label htmlFor="email-existing">Available inbox</Label>- <select- id="email-existing"- className={selectClass}- value={inboxId}- onChange={(e) => setInboxId(e.target.value)}- >- <option value="">Choose an inbox</option>- {inspected.data?.inboxes.map((i) => (- <option- key={i.inbox_id}- disabled={inboxes.data?.some(- (e) =>- e.address === i.inbox_id && e.status !== "archived",- )}- value={i.inbox_id}- >- {i.inbox_id}- {inboxes.data?.some((e) => e.address === i.inbox_id)- ? " — already assigned"- : ""}- </option>- ))}- </select>- </div>- )}- <details className="border-t border-border pt-4">- <summary className="cursor-pointer text-sm text-muted-foreground">- Advanced options- </summary>- <div className="space-y-4 pt-4">- {addressMode === "new" && (- <>- <Label htmlFor="email-domain">Domain</Label>- <select- id="email-domain"- value={domain}- onChange={(e) => setDomain(e.target.value)}- className={selectClass}- >- <option>agentmail.to</option>- {inspected.data?.domains- .filter((d) => d.status === "VERIFIED")- .map((d) => (- <option key={d.domain_id}>{d.domain}</option>- ))}- </select>- <a- className="text-sm underline"- href="https://docs.agentmail.to/custom-domains"- target="_blank"- rel="noreferrer"- >- Set up a custom domain in AgentMail ↗- </a>- </>- )}- <Label htmlFor="email-mode">Receiving</Label>- <select- id="email-mode"- value={mode}- onChange={(e) => setMode(e.target.value as typeof mode)}- className={selectClass}- >- <option value="websocket">- Live connection — works locally- </option>- <option value="webhook">- Webhook — requires public HTTPS- </option>- </select>- </div>- </details>- </section><EmailSafetyNotice />- </>- )}- {step === 5 && (- <>- <EmailSafetyNotice />- {trustNotice}- <section className="space-y-4 rounded-xl border border-border p-6">- <h2 className="text-lg font-semibold">- Ready to start receiving email?- </h2>- <p className="text-lg font-semibold">{address}</p>- <p className="text-sm">- Assigned to {chosen?.name} ·{" "}- {mode === "websocket" ? "Live connection" : "Signed webhook"}- </p>- <p className="text-sm text-muted-foreground">- New conversations create tasks. Replies stay in the same task.- Task comments stay internal.- </p>- </section>- </>- )}- {step === 6 && (- <section className="space-y-5 rounded-xl border border-border p-6">- <p className="flex items-center gap-2 text-sm">- <Check className="size-4" />- Receiving email for {chosen?.name}- </p>- <p className="text-lg font-semibold">{setup.data?.address}</p>- <EmailSafetyNotice />- <Button onClick={() => navigate(`/apps/${connectionId}/permissions`)}>- Back to permissions- </Button>- </section>- )}- {step >= 3 && step <= 5 && (- <div className="flex justify-between border-t border-border pt-5">- <Button- variant="ghost"- onClick={() =>- step === 3- ? navigate(`/apps/${connectionId}/permissions`)- : setStep(step - 1)- }- >- <ArrowLeft className="size-4" />- Back- </Button>- <Button- disabled={- !chosen ||- (lowTrust && !scoped) ||- (step >= 4 &&- (!inspected.data ||- (addressMode === "existing"- ? !inboxId- : !/^[a-z0-9][a-z0-9._-]*$/.test(username)))) ||- setup.isPending- }- onClick={() => (step === 5 ? setup.mutate() : setStep(step + 1))}- >- {setup.isPending- ? "Activating…"- : step === 5- ? addressMode === "new"- ? "Create email address"- : "Connect email address"- : step === 4- ? "Review email address"- : "Continue"}- <ArrowRight className="size-4" />- </Button>+ <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>- )}- {error && (- <p role="alert" className="text-sm text-destructive">- {error.message}- </p>- )}+ </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>@@ -616,8 +497,7 @@ export function EmailEndpointSetup() {</DialogFooter></DialogContent></Dialog>- </div>- );+ </div>;}export function EmailConnectionInboxes({@@ -697,9 +577,11 @@ export function EmailConnectionInboxes({export function EmailEndpointSettings({endpointId,companyId,+ assignedAgentName,}: {endpointId: string;companyId: string;+ assignedAgentName: string;}) {const cache = useQueryClient();const query = useQuery({@@ -712,6 +594,10 @@ export function EmailEndpointSettings({);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" | "">("",);@@ -746,83 +632,118 @@ export function EmailEndpointSettings({</p>);return (- <div className="max-w-xl space-y-4">- <h1 className="text-xl font-bold">{inbox.address}</h1>- <p className="text-sm text-muted-foreground">- {inbox.status} ·{" "}- {inbox.receiveMode === "websocket" ? "Live connection" : "Webhook"}- </p>- <p className="text-sm text-muted-foreground">- Last mail check: {inbox.lastSyncAt ? new Date(inbox.lastSyncAt).toLocaleString() : "Not checked yet"}- </p>- <p className="text-sm">- Each email conversation is a task. Task comments stay internal; use- Email reply to send.- </p>- {inbox.lastError && (- <p role="alert" className="text-sm text-destructive">- {inbox.lastError}- </p>- )}- <div className="flex gap-2">- <Button- variant="outline"- disabled={control.isPending}- onClick={() =>- control.mutate(inbox.status === "active" ? "pause" : "resume")- }- >- {inbox.status === "active" ? "Pause" : "Resume"}- </Button>- <Button- variant="outline"- disabled={control.isPending}- onClick={() => control.mutate("remove")}- >- Disconnect inbox- </Button>- </div>- <div className="space-y-2">- <Label htmlFor="email-reconnect-key">- Reconnect this inbox with a new API key- </Label>- <Input- id="email-reconnect-key"- type="password"- autoComplete="off"- value={replacementKey}- onChange={(e) => setReplacementKey(e.target.value)}- />- <Label htmlFor="email-reconnect-mode">Receiving mode</Label>- <select- id="email-reconnect-mode"- className={selectClass}- 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>- <Button- variant="outline"- disabled={!replacementKey || reconnect.isPending}- onClick={() => reconnect.mutate()}- >- Reconnect inbox- </Button>- </div>- {reconnect.error && (- <p role="alert" className="text-sm text-destructive">- {reconnect.error.message}- </p>- )}- {control.error && (- <p role="alert" className="text-sm text-destructive">- {control.error.message}+ <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>);}diff --git a/ui/storybook/stories/agentmail-onboarding.stories.tsx b/ui/storybook/stories/agentmail-onboarding.stories.tsxindex 4e50ecf15a..30607a4528 100644--- a/ui/storybook/stories/agentmail-onboarding.stories.tsx+++ b/ui/storybook/stories/agentmail-onboarding.stories.tsx@@ -1,1283 +1,212 @@-import { useMemo, useState, type ReactNode } from "react";+import { useEffect, useState } from "react";import type { Meta, StoryObj } from "@storybook/react-vite";-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import {- AlertTriangle,- ArrowLeft,- ArrowRight,- Check,- ChevronRight,- Copy,- Mail,- Plus,- ShieldCheck,-} from "lucide-react";-import { expect, userEvent, within } from "storybook/test";-import { AccessStep } from "@/features/connections/ConnectionSetupFlow";-import { ConnectorCard } from "@/pages/apps/Browse";-import { AppLogo } from "@/pages/apps/AppLogo";-import { Button } from "@/components/ui/button";-import { SearchableSelect } from "@/components/SearchableSelect";-import { AgentIcon } from "@/components/AgentIconPicker";-import { Avatar, AvatarFallback } from "@/components/ui/avatar";-import type { AgentPermissions } from "@paperclipai/shared";-import { TrustPresetSection } from "@/components/TrustPresetSection";-import {- buildPermissionsForTrustPreset,- getTrustPreset,- getLowTrustBoundary,- lowTrustBoundaryHasScope,- setSingleLowTrustBoundaryTarget,-} from "@/lib/trust-policy-ui";-import {- Dialog,- DialogContent,- DialogHeader,- DialogTitle,- DialogDescription,- DialogFooter,-} from "@/components/ui/dialog";-import { Input } from "@/components/ui/input";-import { Label } from "@/components/ui/label";-import { RadioCardGroup } from "@/components/ui/radio-card";-import { queryKeys } from "@/lib/queryKeys";-import { cn } from "@/lib/utils";+import { expect, userEvent, waitFor, within } from "storybook/test";+import { EmailEndpointSetup } from "@/pages/apps/chat/EmailEndpointSetup";+import { ChatSetupSidebar } from "@/components/chat/ChatSetupNavigation";+import { ChatSetupSidebarProvider } from "@/context/ChatSetupSidebarContext";+import { useCompany } from "@/context/CompanyContext";+import { useLocation, useNavigate } from "@/lib/router";import { storybookAgents } from "../fixtures/paperclipData";-// An interactive design proposal. State is local: no credentials or inboxes are created.-type Screen =- | "catalog"- | "access"- | "key"- | "connected"- | "permissions"- | "agent"- | "address"- | "review"- | "ready";const COMPANY = "company-storybook";-const agents = storybookAgents.map((agent, i) => ({- ...agent,- name: ["Support", "Operations", "Research"][i] ?? agent.name,+const CONNECTION = "agentmail-storybook-account";+const OTHER_ACCOUNT = "agentmail-storybook-organization";+const ADDRESS_TAKEN = "This email address is already in use. Choose a different address.";+const agents = storybookAgents.map((agent, index) => ({+ ...agent, name: ["Ralph", "Support", "Research"][index] ?? agent.name,+ permissions: {},}));-const selectClass =- "w-full rounded-md border border-input bg-background px-3 py-2 text-sm";-const connectionSteps = ["Access", "API key", "Connected"];-const addressSteps = ["Agent", "Email address", "Review"];-function NumberedSteps({- labels,- current,- onBack,-}: {- labels: string[];- current: number;- onBack: (step: number) => void;-}) {- return (- <nav aria-label="Setup progress">- <ol className="flex gap-3 sm:gap-6">- {labels.map((label, i) => (- <li key={label} className="flex flex-1 items-center gap-2">- <button- type="button"- disabled={i > current}- onClick={() => i < current && onBack(i)}- aria-current={i === current ? "step" : undefined}- aria-label={`Step ${i + 1}: ${label}`}- className={cn(- "flex items-center gap-2 text-sm disabled:cursor-default",- i > current && "text-muted-foreground",- )}- >- <span- className={cn(- "flex size-7 shrink-0 items-center justify-center rounded-full border text-xs font-medium",- i <= current- ? "border-foreground bg-foreground text-background"- : "border-border",- )}- >- {i < current ? <Check className="size-3.5" /> : i + 1}- </span>- <span className={cn(i === current && "font-semibold")}>- {label}- </span>- </button>- {i < labels.length - 1 && (- <span className="hidden h-px flex-1 bg-border sm:block" />- )}- </li>- ))}- </ol>- </nav>- );-}-function Fact({ label, children }: { label: string; children: ReactNode }) {- return (- <div className="flex flex-wrap items-start justify-between gap-2 py-3">- <dt className="text-sm text-muted-foreground">{label}</dt>- <dd className="text-sm font-medium">{children}</dd>- </div>- );-}-function AgentMailJourney({- initial = "catalog",- existing = false,- advanced = false,- invalidKey = false,- senderStatus = "anyone",- trustDefault = "standard",- policyUnknown = false,-}: {- initial?: Screen;- existing?: boolean;- advanced?: boolean;- invalidKey?: boolean;- senderStatus?: "managed" | "anyone";- trustDefault?: "standard" | "low_trust_review" | "unscoped";- policyUnknown?: boolean;-}) {- const client = useMemo(() => {- const queryClient = new QueryClient({- defaultOptions: { queries: { staleTime: Infinity, retry: false } },- });- queryClient.setQueryData(queryKeys.agents.list(COMPANY), agents);- return queryClient;- }, []);- const initialPermissions = () =>- trustDefault === "standard"- ? buildPermissionsForTrustPreset({}, "standard")- : trustDefault === "unscoped"- ? buildPermissionsForTrustPreset({}, "low_trust_review")- : setSingleLowTrustBoundaryTarget(- buildPermissionsForTrustPreset({}, "low_trust_review"),- COMPANY,- { type: "project", id: "email-work" },- );- const [permissions, setPermissions] = useState<- Record<string, Partial<AgentPermissions>>- >(() =>- Object.fromEntries(agents.map((agent) => [agent.id, initialPermissions()])),- );- const [trustDialog, setTrustDialog] = useState(false);- const [draftPermissions, setDraftPermissions] = useState<- Partial<AgentPermissions>- >({});- const [screen, setScreen] = useState<Screen>(initial);- const [connected, setConnected] = useState(- !["catalog", "access", "key"].includes(initial),- );- const [humanAccess, setHumanAccess] = useState<- "user" | "organization" | "agent"- >("user");- const [agentAccess, setAgentAccess] = useState<"specific" | "all">(- "specific",- );- const [selectedAgents, setSelectedAgents] = useState(- new Set([agents[0]!.id]),- );- const [apiKey, setApiKey] = useState("");- const [error, setError] = useState(- invalidKey- ? "This key couldn’t be verified. Check that it’s an active AgentMail API key and try again."- : "",- );- const [agentId, setAgentId] = useState(agents[0]!.id);- const [addressMode, setAddressMode] = useState(existing ? "existing" : "new");- const [username, setUsername] = useState("support");- const [domain, setDomain] = useState("agentmail.to");- const [existingAddress, setExistingAddress] = useState(- "[email protected]",- );- const [receiveMode, setReceiveMode] = useState("websocket");- const [copied, setCopied] = useState(false);- const [hasInbox, setHasInbox] = useState(initial === "ready");- const chosenAgent = agents.find((agent) => agent.id === agentId) ?? agents[0];- const [addedAgentName, setAddedAgentName] = useState<string | null>(null);- const address =- addressMode === "existing" ? existingAddress : `${username}@${domain}`;- const wizard = ["agent", "address", "review"].includes(screen);- const agentPermissions = permissions[agentId];- const lowTrust = getTrustPreset(agentPermissions) === "low_trust_review";- const scoped = lowTrustBoundaryHasScope(- getLowTrustBoundary(agentPermissions),- );- const openTrust = () => {- setDraftPermissions(agentPermissions ?? {});- setTrustDialog(true);- };- const senderSummary = policyUnknown- ? "Not verified"- : senderStatus === "anyone"- ? "Unrestricted"- : "Managed in AgentMail";- const canActivate = !lowTrust || scoped;- const trustNotice = (- <div- className="space-y-3 rounded-lg border border-border bg-muted/30 p-4"- role={lowTrust && scoped ? undefined : "alert"}- >- <div className="flex items-start gap-2">- {lowTrust && scoped ? (- <ShieldCheck className="size-4 shrink-0" />- ) : (- <AlertTriangle className="size-4 shrink-0 text-(--status-agent-paused)" />- )}- <div className="space-y-1">- <p className="text-sm font-medium">- {lowTrust- ? scoped- ? "Low-trust review configured"- : "Low trust needs a work boundary"- : `${chosenAgent?.name} is not a low-trust agent`}- </p>- <p className="text-sm text-muted-foreground">- {lowTrust- ? scoped- ? "Email tasks must stay inside this agent’s configured work boundary. Output is quarantined for trusted review."- : "Choose a project or task boundary before activating email."- : "Email can contain malicious instructions. We recommend Low-trust review to limit the agent’s access to Paperclip work."}- </p>- </div>- </div>- <Button size="sm" variant="outline" onClick={openTrust}>- {lowTrust ? "Review trust settings" : "Configure low trust"}- </Button>- </div>- );- const inboxNotice = (- <div- className="space-y-3 rounded-lg border border-border bg-muted/30 p-4"- role={policyUnknown || senderStatus === "anyone" ? "alert" : undefined}- >- <div className="flex items-start gap-2">- {senderStatus === "managed" && !policyUnknown ? (- <ShieldCheck className="size-4 shrink-0" />- ) : (- <AlertTriangle className="size-4 shrink-0 text-(--status-agent-paused)" />- )}- <div className="space-y-1">- <p className="text-sm font-medium">- {policyUnknown- ? "Sender restrictions haven’t been verified"- : senderStatus === "anyone"- ? "Anyone can email this agent"- : "Sender restrictions are managed in AgentMail"}- </p>- <p className="text-sm text-muted-foreground">- {senderStatus === "anyone" || policyUnknown- ? "Unrestricted email can create tasks and trigger agent work. Set up an allowlist in AgentMail to limit who can contact this inbox."- : "Review your inbox’s allowlists and blocklists in AgentMail. Allowed email can still contain malicious instructions."}- </p>- <p className="text-xs text-muted-foreground">- AgentMail controls new messages and replies separately. Check both- lists.- </p>- </div>- </div>- <div className="flex flex-wrap items-center gap-4 text-sm">- <a- className="underline underline-offset-4"- href="https://console.agentmail.to"- target="_blank"- rel="noreferrer"- >- Open AgentMail ↗- </a>- <a- className="text-muted-foreground underline underline-offset-4"- href="https://docs.agentmail.to/knowledge-base/allowlists-blocklists"- target="_blank"- rel="noreferrer"- >- Set up allowlists ↗- </a>- </div>- </div>- );- const humanLabel =- humanAccess === "organization" ? "Any human in the organization" : "Just me";- const agentLabel =- agentAccess === "all"- ? "Any agent"- : agents- .filter((agent) => selectedAgents.has(agent.id))- .map((agent) => agent.name)- .join(", ");- const validAddress =- addressMode === "existing"- ? !!existingAddress- : /^[a-z0-9][a-z0-9._-]*$/.test(username);- const go = (next: Screen) => {- setError("");- setScreen(next);- };- const beginAddress = () => {- if (chosenAgent) {- setAgentId(chosenAgent.id);- setUsername(chosenAgent.name.toLowerCase());- }- go("agent");- };- const footer = (- back: Screen,- next: Screen,- label = "Continue",- disabled = false,- ) => (- <div className="flex items-center justify-between border-t border-border pt-5">- <Button variant="ghost" onClick={() => go(back)}>- <ArrowLeft className="size-4" />- Back- </Button>- <Button disabled={disabled} onClick={() => go(next)}>- {label}- <ArrowRight className="size-4" />- </Button>+// Render the production setup. Only the API is simulated; no real keys or inboxes.+function AgentMailJourney({ savedConnection = true }: { savedConnection?: boolean }) {+ const navigate = useNavigate();+ const { pathname } = useLocation();+ const { selectedCompanyId } = useCompany();+ const [ready, setReady] = useState(false);+ useEffect(() => {+ if (ready) return;+ navigate(`/apps/chat/connect?provider=agentmail${savedConnection ? `&connectionId=${CONNECTION}` : ""}`, { replace: true });+ setReady(true);+ }, [navigate, savedConnection, ready]);+ if (!ready || !selectedCompanyId) return null;+ if (!pathname.endsWith("/apps/chat/connect")) return <div className="p-6 text-sm">Setup complete.</div>;+ return <ChatSetupSidebarProvider>+ <div className="min-h-screen bg-background text-foreground md:flex">+ <div className="hidden w-60 shrink-0 md:block"><ChatSetupSidebar /></div>+ <main className="min-w-0 flex-1 py-6"><EmailEndpointSetup /></main></div>- );-- return (- <QueryClientProvider client={client}>- <div className="min-h-screen bg-background text-foreground">- <div className="flex flex-wrap items-center justify-between gap-2 border-b border-border bg-muted/30 px-6 py-3 text-xs text-muted-foreground">- <span>- Design preview · sample data · nothing is connected or sent- </span>- <Button- size="sm"- variant="ghost"- onClick={() => {- setConnected(false);- setHasInbox(false);- setScreen("catalog");- setError("");- setApiKey("");- setHumanAccess("user");- setAgentAccess("specific");- setSelectedAgents(new Set([agents[0]!.id]));- setAgentId(agents[0]!.id);- setUsername("support");- setAddressMode("new");- setDomain("agentmail.to");- setReceiveMode("websocket");- setExistingAddress("[email protected]");- setCopied(false);- setAddedAgentName(null);- setPermissions(- Object.fromEntries(- agents.map((agent) => [agent.id, initialPermissions()]),- ),- );- }}- >- Restart walkthrough- </Button>- </div>- <div className="mx-auto max-w-5xl space-y-8 p-6 sm:p-8">- <nav- aria-label="Breadcrumb"- className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground"- >- <button- onClick={() => go("catalog")}- className="hover:text-foreground"- >- Apps- </button>- {screen !== "catalog" && (- <>- <ChevronRight className="size-3.5" />- <button- onClick={() => connected && go("permissions")}- className="hover:text-foreground"- >- AgentMail- </button>- <ChevronRight className="size-3.5" />- <span className="text-foreground">- {wizard || screen === "ready"- ? "Email address"- : screen === "permissions"- ? "Permissions"- : "Connect"}- </span>- </>- )}- </nav>-- {screen === "catalog" ? (- <div className="space-y-6">- <header className="space-y-2">- <h1 className="text-xl font-bold">Apps</h1>- <p className="text-sm text-muted-foreground">- Connect the tools your people and agents use.- </p>- </header>- <div role="list" aria-label="Apps">- <ConnectorCard- row={{- key: "agentmail",- slug: "agentmail",- name: "AgentMail",- description:- "Give agents email addresses. Turn email conversations into tasks.",- brandKey: "agentmail",- entry: null,- applications: [],- connections: [],- chatEndpoints: [],- }}-- userProfileById={new Map()}- onNavigate={() => go(connected ? "permissions" : "access")}- onRequestRemove={() => {}}- chatConnectorsEnabled- />- </div>- </div>- ) : screen === "permissions" ? (- <div className="space-y-7">- <header className="flex items-center gap-3">- <AppLogo name="AgentMail" brandKey="agentmail" />- <div>- <h1 className="text-xl font-bold">AgentMail</h1>- <p className="flex items-center gap-1.5 text-xs text-muted-foreground">- <Check className="size-3.5" />- Connected · Company email- </p>- </div>- </header>- <div className="border-b border-border pb-3 text-sm font-semibold">- Permissions- </div>- <section className="flex flex-col items-start gap-5 rounded-xl border border-border p-6 sm:flex-row sm:items-center">- <div className="flex size-11 shrink-0 items-center justify-center rounded-lg bg-muted">- <Mail className="size-5" />- </div>- <div className="flex-1 space-y-1">- <h2 className="text-lg font-semibold">- {hasInbox- ? "Give another agent an inbox"- : "Your connection is ready. Give an agent an inbox."}- </h2>- <p className="text-sm text-muted-foreground">- Each agent gets an address. Each email conversation becomes- a task.- </p>- </div>- <Button- size="lg"- onClick={beginAddress}- disabled={!agents.length}- >- <Plus className="size-4" />- Give an agent an email address- </Button>- </section>- {hasInbox && (- <section className="space-y-3">- <h2 className="text-sm font-semibold">Email addresses</h2>- <div className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border p-4">- <div>- <p className="text-sm font-medium">{address}</p>- <p className="text-xs text-muted-foreground">- {chosenAgent?.name} ·{" "}- {receiveMode === "websocket"- ? "Live connection"- : "Webhook"}- </p>- </div>- <span className="flex items-center gap-1.5 text-sm">- <Check className="size-4" />- Receiving email- </span>- </div>- <dl className="divide-y divide-border">- <Fact label="New email from">{senderSummary}</Fact>- <Fact label="Agent trust">- {lowTrust ? "Low-trust review" : "Standard"}- </Fact>- </dl>- {inboxNotice}- {!lowTrust && trustNotice}- </section>- )}- <section className="space-y-4">- <div className="flex items-center justify-between">- <h2 className="text-sm font-semibold">Connection access</h2>- <Button- size="sm"- variant="outline"- onClick={() => go("access")}- >- Edit access- </Button>- </div>- <dl className="divide-y divide-border">- <Fact label="Humans">{humanLabel}</Fact>- <Fact label="Agents">- {agentLabel || "No agents selected"}- </Fact>- <Fact label="Credential">- AgentMail API key · Saved in vault- </Fact>- </dl>- </section>- </div>- ) : (- <div className="mx-auto max-w-2xl space-y-6">- <header className="flex items-start justify-between gap-4">- <div className="space-y-2">- <div className="flex items-center gap-3">- <AppLogo name="AgentMail" brandKey="agentmail" />- <h1 className="text-xl font-bold">- {wizard- ? "Give an agent an email address"- : screen === "ready"- ? "Your agent’s email is ready"- : "Connect AgentMail"}- </h1>- </div>- <p className="text-sm text-muted-foreground">- {wizard- ? "Using your saved AgentMail connection."- : screen === "ready"- ? "New email conversations will become tasks for your agent."- : "Connect once, then assign email addresses to your agents."}- </p>- </div>- <Button- variant="ghost"- size="sm"- onClick={() => go(connected ? "permissions" : "catalog")}- >- {screen === "ready" ? "Close" : "Cancel"}- </Button>- </header>- {wizard ? (- <NumberedSteps- labels={addressSteps}- current={["agent", "address", "review"].indexOf(screen)}- onBack={(i) =>- go((["agent", "address", "review"] as Screen[])[i]!)- }- />- ) : (- screen !== "ready" && (- <NumberedSteps- labels={connectionSteps}- current={["access", "key", "connected"].indexOf(screen)}- onBack={(i) => go(i === 0 ? "access" : "key")}- />- )- )}-- {screen === "access" && (- <AccessStep- companyId={COMPANY}- authKind="api_key"- grantKinds={["user", "organization"]}- grantKind={humanAccess}- setGrantKind={setHumanAccess}- installChoice={agentAccess}- setInstallChoice={setAgentAccess}- installAgentIds={selectedAgents}- setInstallAgentIds={setSelectedAgents}- submitLabel={connected ? "Save access" : "Continue"}- onBack={() => go(connected ? "permissions" : "catalog")}- onContinue={() => go(connected ? "permissions" : "key")}- />- )}- {screen === "key" && (- <form- className="space-y-6"- onSubmit={(e) => {- e.preventDefault();- if (!apiKey.trim()) {- setError("Enter an API key to continue.");- return;- }- if (apiKey.trim() === "invalid") {- setError(- "This key couldn’t be verified. Check that it’s an active AgentMail API key and try again.",- );- return;- }- setApiKey("");- setConnected(true);- go("connected");- }}- >- <section className="space-y-5 rounded-xl border border-border p-6">- <div className="space-y-1">- <h2 className="text-lg font-semibold">- Add your AgentMail API key- </h2>- </div>- <div className="space-y-2">- <Label htmlFor="preview-api-key">API key</Label>- <Input- id="preview-api-key"- type="password"- autoComplete="off"- placeholder="Paste your AgentMail API key"- value={apiKey}- onChange={(e) => {- setApiKey(e.target.value);- setError("");- }}- aria-invalid={!!error}- aria-describedby={- error ? "preview-key-error" : undefined- }- />- {error && (- <p- id="preview-key-error"- role="alert"- className="text-sm text-destructive"- >- {error}- </p>- )}- </div>- <a- className="text-sm underline underline-offset-4"- href="https://console.agentmail.to/dashboard/api-keys"- target="_blank"- rel="noreferrer"- >- Get a key in AgentMail ↗- </a>- </section>- <div className="flex items-center justify-between">- <Button- variant="ghost"- type="button"- onClick={() => go("access")}- >- <ArrowLeft className="size-4" />- Back- </Button>- <Button type="submit">- Connect AgentMail- <ArrowRight className="size-4" />- </Button>- </div>- </form>- )}- {screen === "connected" && (- <section className="space-y-6 rounded-xl border border-border p-6">- <div className="flex items-start gap-3">- <ShieldCheck className="size-6" />- <div className="space-y-1">- <h2 className="text-lg font-semibold">- AgentMail is connected- </h2>- <p className="text-sm text-muted-foreground">- Your credential is saved. Next, give an agent an email- address from Permissions.- </p>- </div>- </div>- <dl className="divide-y divide-border">- <Fact label="Humans">{humanLabel}</Fact>- <Fact label="Agents">{agentLabel}</Fact>- <Fact label="Email addresses">None assigned yet</Fact>- </dl>- <div className="flex justify-end">- <Button onClick={() => go("permissions")}>- Open permissions- <ArrowRight className="size-4" />- </Button>- </div>- </section>- )}- {screen === "agent" && (- <>- <section className="space-y-5 rounded-xl border border-border p-6">- <div className="space-y-1">- <h2 className="text-lg font-semibold">- Who should handle this inbox?- </h2>- <p className="text-sm text-muted-foreground">- Incoming email will create tasks assigned to this agent.- </p>- </div>- <div className="space-y-2">- <Label>Agent</Label>- <SearchableSelect- value={chosenAgent?.id ?? ""}- placeholder="Choose an agent"- searchPlaceholder="Search all agents…"- emptyMessage="No agents found."- groups={[- {- id: "agents",- options: agents.map((agent) => ({- key: agent.id,- value: agent.id,- label: agent.name,- icon: agent.icon,- })),- },- ]}- onValueChange={(value, option) => {- setAgentId(value);- setUsername(option.label.toLowerCase());- if (- agentAccess !== "all" &&- !selectedAgents.has(value)- ) {- setSelectedAgents(- (current) => new Set([...current, value]),- );- setAddedAgentName(option.label);- } else setAddedAgentName(null);- }}- renderValue={(option) =>- option && (- <span className="flex items-center gap-2">- <Avatar- size="sm"- role="img"- aria-label={`${option.label} avatar`}- >- <AvatarFallback>- <AgentIcon- icon={option.icon}- className="size-3.5"- />- </AvatarFallback>- </Avatar>- {option.label}- </span>- )- }- renderOption={(option) => (- <span className="flex items-center gap-2">- <Avatar size="sm">- <AvatarFallback>- <AgentIcon- icon={option.icon}- className="size-3.5"- />- </AvatarFallback>- </Avatar>- {option.label}- </span>- )}- />- </div>- <p- role={addedAgentName ? "status" : undefined}- className="text-xs text-muted-foreground"- >- {addedAgentName- ? `${addedAgentName} added to this connection’s allowed agents.`- : "Choosing an agent also gives them access to this connection."}- </p>- </section>- {trustNotice}- {footer(- "permissions",- "address",- "Continue",- !chosenAgent || (lowTrust && !scoped),- )}- </>- )}- {screen === "address" && (- <>- <section className="space-y-5 rounded-xl border border-border p-6">- <div className="space-y-1">- <h2 className="text-lg font-semibold">- Choose {chosenAgent?.name}’s email address- </h2>- <p className="text-sm text-muted-foreground">- Create an address or attach an inbox already in- AgentMail.- </p>- </div>- <RadioCardGroup- ariaLabel="Email address source"- value={addressMode}- onValueChange={setAddressMode}- className="sm:grid-cols-2"- options={[- {- value: "new",- title: "Create a new address",- description: "Ready to use. No domain setup.",- },- {- value: "existing",- title: "Use an existing inbox",- description: "Bring an address you already have.",- },- ]}- />- {addressMode === "new" ? (- <div className="space-y-2">- <Label htmlFor="preview-address-name">- Email address- </Label>- <div className="flex items-center overflow-hidden rounded-md border border-input focus-within:ring-1 focus-within:ring-ring">- <Input- id="preview-address-name"- value={username}- onChange={(e) =>- setUsername(e.target.value.toLowerCase())- }- className="min-w-0 border-0 shadow-none focus-visible:ring-0"- />- <span className="shrink-0 pr-3 text-sm text-muted-foreground">- @{domain}- </span>- </div>- <p className="text-xs text-muted-foreground">- Suggested from the agent’s name. You can change it.- </p>- </div>- ) : (- <div className="space-y-2">- <Label htmlFor="preview-existing-inbox">- Available inbox- </Label>- <select- className={selectClass}- id="preview-existing-inbox"- value={existingAddress}- onChange={(e) => setExistingAddress(e.target.value)}- >- <option>[email protected]</option>- <option>[email protected]</option>- <option disabled>- [email protected] — already assigned- </option>- </select>- <p className="text-xs text-muted-foreground">- Only unassigned inboxes accessible to this credential- are available.- </p>- </div>- )}- <details- open={advanced || undefined}- className="border-t border-border pt-4"- >- <summary className="cursor-pointer text-sm text-muted-foreground">- Advanced options- </summary>- <div className="space-y-5 pt-5">- {addressMode === "new" && (- <div className="space-y-2">- <Label htmlFor="preview-email-domain">Domain</Label>- <select- className={selectClass}- id="preview-email-domain"- value={domain}- onChange={(e) => setDomain(e.target.value)}- >- <option value="agentmail.to">- agentmail.to — ready to use- </option>- <option value="acme.example.test">- acme.example.test — verified- </option>- </select>- <a- className="text-xs text-muted-foreground underline underline-offset-4"- href="https://docs.agentmail.to/custom-domains"- target="_blank"- rel="noreferrer"- >- Set up another domain in AgentMail ↗- </a>- </div>- )}- <RadioCardGroup- ariaLabel="Receiving mode"- value={receiveMode}- onValueChange={setReceiveMode}- options={[- {- value: "websocket",- title: "Live connection (recommended)",- description:- "Works locally. No public URL needed.",- },- {- value: "webhook",- title: "Webhook",- description:- "For a Paperclip server with a public HTTPS address.",- },- ]}- />- {receiveMode === "webhook" && (- <p className="text-xs text-muted-foreground">- Paperclip registers and verifies the webhook at your- server’s public address. This preview assumes HTTPS- is configured.- </p>- )}- </div>- </details>- </section>- {inboxNotice}- {footer(- "agent",- "review",- "Review email address",- !validAddress,- )}- </>- )}- {screen === "review" && (- <>- {inboxNotice}- {trustNotice}- <section className="space-y-5 rounded-xl border border-border p-6">- <div className="space-y-1">- <h2 className="text-lg font-semibold">- Ready to start receiving email?- </h2>- <p className="text-sm text-muted-foreground">- {addressMode === "new"- ? "We’ll create this inbox in AgentMail and assign it to your agent."- : "We’ll attach this inbox to your agent. Existing mail stays in AgentMail."}- </p>- </div>- <div className="flex items-center gap-3 rounded-lg bg-muted/50 p-4">- <Mail className="size-5 shrink-0" />- <p className="break-all text-lg font-semibold">- {address}- </p>- </div>- <dl className="divide-y divide-border">- <Fact label="Assigned agent">{chosenAgent?.name}</Fact>- <Fact label="Connection">AgentMail · Company email</Fact>- <Fact label="New email from">{senderSummary}</Fact>-- <Fact label="Agent trust">- {lowTrust ? "Low-trust review" : "Standard"}- </Fact>- <Fact label="Receiving">- {receiveMode === "websocket"- ? "Live connection"- : "Signed webhook"}- </Fact>- </dl>- <div className="space-y-2 text-sm text-muted-foreground">- <p>- New conversations create tasks. Replies stay in the same- task.- </p>- <p>- Task comments stay internal. Sending email is an- explicit action.- </p>- <p>- Receiving starts now. Older mail is added only when- needed for a new reply.- </p>- </div>- </section>- <div className="flex items-center justify-between border-t border-border pt-5">- <Button variant="ghost" onClick={() => go("address")}>- <ArrowLeft className="size-4" />- Back- </Button>- <Button- disabled={!canActivate}- onClick={() => {- setHasInbox(true);- go("ready");- }}- >- {addressMode === "new"- ? "Create email address"- : "Connect email address"}- <ArrowRight className="size-4" />- </Button>- </div>- </>- )}- {screen === "ready" && (- <section className="space-y-6 rounded-xl border border-border p-6">- <div className="flex items-center gap-2 text-sm font-medium">- <Check className="size-5" />- Receiving email for {chosenAgent?.name}- </div>- {inboxNotice}- <p className="text-sm text-muted-foreground">- New email: {senderSummary} · Agent trust:{" "}- {lowTrust ? "Low-trust review" : "Standard"}- </p>- <div className="flex flex-wrap items-center justify-between gap-3 rounded-lg bg-muted/50 p-4">- <p className="break-all text-lg font-semibold">{address}</p>- <Button- variant="outline"- size="sm"- onClick={() => {- void navigator.clipboard- .writeText(address)- .then(() => setCopied(true));- }}- >- <Copy className="size-3.5" />- {copied ? "Copied" : "Copy address"}- </Button>- </div>- <div className="space-y-2">- <h2 className="text-sm font-semibold">- Try it with a test email- </h2>- <p className="text-sm text-muted-foreground">- Send a message from an allowed sender. A new task will- appear for {chosenAgent?.name}, ready for an explicit- email reply.- </p>- <p className="text-xs text-muted-foreground">- This is a design preview; this sample address hasn’t been- created.- </p>- </div>- <Button onClick={() => go("permissions")}>- Back to permissions- <ArrowRight className="size-4" />- </Button>- </section>- )}- </div>- )}- </div>- </div>- <Dialog open={trustDialog} onOpenChange={setTrustDialog}>- <DialogContent className="max-h-screen overflow-y-auto sm:max-w-2xl">- <DialogHeader>- <DialogTitle>Trust settings · {chosenAgent?.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={draftPermissions}- onChange={setDraftPermissions}- companyId={COMPANY}- projectCandidates={[{ id: "email-work", label: "Email work" }]}- issueCandidates={[]}- />- <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>- <DialogFooter>- <Button variant="ghost" onClick={() => setTrustDialog(false)}>- Cancel- </Button>- <Button- disabled={- getTrustPreset(draftPermissions) === "low_trust_review" &&- !lowTrustBoundaryHasScope(getLowTrustBoundary(draftPermissions))- }- onClick={() => {- setPermissions((current) => ({- ...current,- [agentId]: draftPermissions,- }));- setTrustDialog(false);- }}- >- Save trust settings- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- </QueryClientProvider>- );+ </ChatSetupSidebarProvider>;}+type Scenario = { noSavedKeys?: boolean; scopedKey?: boolean; missingBoundary?: boolean; denySetup?: boolean; initialTaken?: boolean; noCustomDomain?: boolean; checkFailed?: boolean };const meta = {title: "Connections/AgentMail setup",component: AgentMailJourney,parameters: { layout: "fullscreen" },- args: { initial: "catalog" },+ args: { savedConnection: true },+ beforeEach(context) {+ const scenario = (context.parameters.agentmailScenario ?? {}) as Scenario;+ sessionStorage.removeItem(`paperclip.agentmail-setup:${COMPANY}:${CONNECTION}:choose`);+ sessionStorage.removeItem(`paperclip.agentmail-setup:${COMPANY}:new:choose`);+ const fixtureAgents = agents.map(agent => ({ ...agent, permissions: scenario.missingBoundary ? { trustPreset: "low_trust_review" } : {} }));+ const original = window.fetch;+ window.fetch = async (input, init) => {+ const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url, location.origin);+ const method = init?.method ?? "GET";+ const body = init?.body ? JSON.parse(String(init.body)) : {};+ if (url.pathname === `/api/companies/${COMPANY}/agents`) return Response.json(fixtureAgents);+ if (url.pathname === `/api/companies/${COMPANY}/tools/connections`) return Response.json({ connections: [{+ id: OTHER_ACCOUNT, name: "AgentMail", status: "active", enabled: true,+ config: { provider: "agentmail", emailCredential: true }, createdAt: "2026-09-30T14:00:00Z",+ }] });+ const agent = fixtureAgents.find(agent => url.pathname === `/api/agents/${agent.id}` || url.pathname === `/api/agents/${agent.id}/permissions`);+ if (agent) {+ if (method === "PATCH") agent.permissions = body;+ return Response.json({ ...agent, access: { canAssignTasks: false } });+ }+ if (url.pathname.endsWith("/email/connections") && method === "GET") return Response.json(scenario.noSavedKeys ? [] : [+ { id: OTHER_ACCOUNT, label: "AgentMail account key", scope: "organization", createdAt: "2026-09-30T14:00:00Z" },+ { id: CONNECTION, label: scenario.scopedKey ? "AgentMail inbox key · [email protected]" : "AgentMail account key",+ scope: scenario.scopedKey ? "inbox" : "organization", createdAt: "2026-10-01T14:00:00Z" },+ ]);+ if (url.pathname.endsWith("/email/inspect") && body.apiKey === "invalid-key")+ return Response.json({ error: "AgentMail rejected the API key. Check it and try again." }, { status: 422 });+ if (url.pathname.endsWith("/email/connections") && method === "POST") {+ if (body.apiKey === "invalid-key") return Response.json({ error: "AgentMail rejected the API key. Check it and try again." }, { status: 422 });+ if (body.grantKind !== "organization" || body.allAgents !== false || body.agentIds.length !== 1) {+ return Response.json({ error: "Unexpected access defaults in preview." }, { status: 422 });+ }+ return Response.json({ id: CONNECTION }, { status: 201 });+ }+ if (url.pathname.endsWith("/email/inspect") || [CONNECTION, OTHER_ACCOUNT].some(id => url.pathname.endsWith(`/email/connections/${id}/inspect`))) {+ const restricted = scenario.scopedKey && url.pathname.includes(CONNECTION);+ return Response.json({+ scope: { scope_type: restricted ? "inbox" : "organization" },+ inboxes: restricted ? [{ inbox_id: "[email protected]" }] : [{ inbox_id: "[email protected]" }, { inbox_id: "[email protected]" }],+ domains: restricted || scenario.noCustomDomain ? [] : [{ domain_id: "custom-domain", domain: "paperclip.example", status: "VERIFIED" }],+ });+ }+ if ([CONNECTION, OTHER_ACCOUNT].some(id => url.pathname.endsWith(`/email/connections/${id}/check-address`))) {+ if (scenario.checkFailed) return Response.json({ error: "AgentMail is rate limiting requests. Wait a moment, then try again." }, { status: 429 });+ return Response.json({ address: `${body.username}@${body.domain}`,+ status: body.username === "taken" || (scenario.initialTaken && body.username === "ralph") ? "taken" : "unknown" });+ }+ if (url.pathname.endsWith("/email/inboxes")) {+ if (method === "GET") return Response.json([]);+ if (body.username === "taken") return Response.json({ error: ADDRESS_TAKEN, code: "agentmail_address_taken",+ details: { field: "username", providerStatus: 403, operation: "create_inbox" } }, { status: 409 });+ if (scenario.denySetup) return Response.json({ error: "AgentMail did not allow Paperclip to create the email address. Check your API key permissions and AgentMail account limits, then try again." }, { status: 422 });+ return Response.json({ id: body.idempotencyKey, connectionId: "storybook-inbox-connection", companyId: COMPANY,+ assignedAgentId: body.assignedAgentId, address: body.inboxId ?? `${body.username}@${body.domain}`, status: "active", receiveMode: body.receiveMode }, { status: 201 });+ }+ return original(input, init);+ };+ return () => { window.fetch = original; };+ },} satisfies Meta<typeof AgentMailJourney>;export default meta;type Story = StoryObj<typeof meta>;-export const Walkthrough: Story = { name: "Start here · Full walkthrough" };-export const CatalogCard: Story = { name: "01 · Apps catalog card" };-export const ConnectionAccess: Story = {- name: "02 · Humans and agents",- args: { initial: "access" },-};-export const ApiKey: Story = { name: "03 · API key", args: { initial: "key" } };-export const ConnectionReady: Story = {- name: "04 · Connection ready",- args: { initial: "connected" },-};-export const Permissions: Story = {- name: "05 · Permissions",- args: { initial: "permissions" },-};-export const ChooseAgent: Story = {- name: "06 · Choose an agent",- args: { initial: "agent" },-};-export const ChooseAddress: Story = {- name: "07 · Choose an address",- args: { initial: "address" },-};-export const ExistingInbox: Story = {- name: "07b · Attach existing inbox",- args: { initial: "address", existing: true },-};-export const AdvancedOptions: Story = {- name: "07c · Advanced options",- args: { initial: "address", advanced: true },-};-export const Review: Story = {- name: "08 · Review and activate",- args: { initial: "review" },-};-export const Ready: Story = {- name: "09 · Email address ready",- args: { initial: "ready" },-};-export const InvalidKey: Story = {- name: "Error · Invalid API key",- args: { initial: "key", invalidKey: true },-};-export const TestedWalkthrough: Story = {- name: "Verification · Complete journey",- play: async ({ canvasElement }) => {- const canvas = within(canvasElement);- await userEvent.click(- canvas.getByRole("button", { name: "Connect AgentMail" }),- );- await userEvent.click(canvas.getByRole("button", { name: "Continue" }));- await userEvent.type(- canvas.getByLabelText("API key", { exact: true }),- "sample-preview-key",- );- await userEvent.click(- canvas.getByRole("button", { name: "Connect AgentMail" }),- );- await userEvent.click(- canvas.getByRole("button", { name: "Open permissions" }),- );- await userEvent.click(- canvas.getByRole("button", { name: "Give an agent an email address" }),- );- await userEvent.click(canvas.getByRole("button", { name: "Continue" }));- await userEvent.click(- canvas.getByRole("button", { name: "Review email address" }),- );- await userEvent.click(- canvas.getByRole("button", { name: "Create email address" }),- );- await expect(- canvas.getByRole("heading", { name: "Your agent’s email is ready" }),- ).toBeVisible();- await userEvent.click(- canvas.getByRole("button", { name: "Back to permissions" }),- );- await expect(- canvas.getByText("Receiving email", { exact: true }),- ).toBeVisible();- },-};-export const SearchAllAgents: Story = {- name: "06b · Search and grant agent access",- args: { initial: "agent" },- play: async ({ canvasElement }) => {- const canvas = within(canvasElement);- await userEvent.click(canvas.getByRole("combobox"));- const page = within(canvasElement.ownerDocument.body);- await userEvent.type(- page.getByPlaceholderText("Search all agents…"),- "Research",- );- await userEvent.click(page.getByRole("option", { name: "Research" }));- await expect(canvas.getByRole("status")).toHaveTextContent(- "Research added to this connection’s allowed agents.",- );- await userEvent.click(canvas.getByRole("button", { name: "Cancel" }));- await expect(canvas.getByText("Support, Research")).toBeVisible();- },+const chooseAgent: NonNullable<Story["play"]> = async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const picker = await canvas.findByLabelText("Agent");+ await waitFor(() => expect(picker).toBeEnabled());+ await userEvent.click(picker);+ const page = within(canvasElement.ownerDocument.body);+ await userEvent.type(page.getByPlaceholderText("Filter agents"), "Ralph");+ await userEvent.click(await page.findByRole("button", { name: "Select Ralph" }));+};+const chooseAddress: NonNullable<Story["play"]> = async context => {+ await chooseAgent(context);+ const canvas = within(context.canvasElement);+ await waitFor(() => expect(canvas.getByRole("button", { name: "Continue" })).toBeEnabled());+ await userEvent.click(canvas.getByRole("button", { name: "Continue" }));+ await expect(await canvas.findByLabelText("Ralph’s email address")).toHaveValue("ralph");+};+const takenAddress: NonNullable<Story["play"]> = async context => {+ await chooseAddress(context);+ const canvas = within(context.canvasElement);+ await userEvent.clear(canvas.getByLabelText("Ralph’s email address"));+ await userEvent.type(canvas.getByLabelText("Ralph’s email address"), "taken");+ await expect(await canvas.findByRole("alert")).toHaveTextContent(ADDRESS_TAKEN);+ await expect(canvas.getByLabelText("Ralph’s email address")).toHaveAttribute("aria-invalid", "true");};-export const PublicInboxWarning: Story = {- name: "Controls · Public inbox warning",- args: { initial: "review", senderStatus: "anyone" },-};-export const LowTrustAgent: Story = {- name: "Controls · Low-trust agent",- args: { initial: "agent", trustDefault: "low_trust_review" },-};-export const MissingTrustBoundary: Story = {- name: "Controls · Low trust needs a boundary",- args: { initial: "agent", trustDefault: "unscoped" },-};-export const UnknownSenderPolicy: Story = {- name: "Controls · Could not verify restrictions",- args: { initial: "review", existing: true, policyUnknown: true },-};-export const ManagedSenderPolicy: Story = {- name: "Controls · Managed in AgentMail",- args: {- initial: "review",- senderStatus: "managed",- trustDefault: "low_trust_review",- },-};-export const VerifySenderControls: Story = {- name: "Verification · Email safety guidance",- args: { initial: "review" },- play: async ({ canvasElement }) => {- const canvas = within(canvasElement);- await expect(canvas.getByText("Anyone can email this agent")).toBeVisible();- await expect(- canvas.getByRole("link", { name: "Set up allowlists ↗" }),- ).toHaveAttribute(- "href",- "https://docs.agentmail.to/knowledge-base/allowlists-blocklists",- );- await expect(- canvas.getByText("Support is not a low-trust agent"),- ).toBeVisible();- await userEvent.click(- canvas.getByRole("button", { name: "Configure low trust" }),- );- const page = within(canvasElement.ownerDocument.body);- await expect(page.getByRole("dialog")).toBeVisible();- await expect(- page.getByText(- "Changes apply to all of this agent’s work. Use a dedicated email agent if its other tasks need broader access.",- ),- ).toBeVisible();- const dialog = within(page.getByRole("dialog"));- await userEvent.selectOptions(- dialog.getAllByRole("combobox")[0]!,- "low_trust_review",- );- await expect(- dialog.getByRole("button", { name: "Save trust settings" }),- ).toBeDisabled();- await userEvent.selectOptions(- dialog.getAllByRole("combobox")[2]!,- "email-work",- );- await userEvent.click(- dialog.getByRole("button", { name: "Save trust settings" }),- );- await expect(canvas.getByText("Low-trust review configured")).toBeVisible();- await expect(canvas.getByText("Anyone can email this agent")).toBeVisible();- },-};+export const Walkthrough: Story = { name: "Start here · Pick agent, pick email" };+export const ChooseAgent: Story = { name: "01 · Pick an agent" };+export const ChooseAddress: Story = { name: "02 · Pick their email", play: chooseAddress };+export const AddressTaken: Story = { name: "Error · Email address already in use", play: takenAddress };+export const InitialAddressTaken: Story = { name: "Initial name taken · Click an alternative", parameters: { agentmailScenario: { initialTaken: true } }, play: async context => {+ await chooseAddress(context);+ const canvas = within(context.canvasElement);+ await expect(await canvas.findByRole("alert")).toHaveTextContent(ADDRESS_TAKEN);+ await expect(canvas.getByRole("button", { name: "[email protected]" })).toBeVisible();+} };+export const SharedDomain: Story = { name: "No custom domain · Shared AgentMail domain", parameters: { agentmailScenario: { noCustomDomain: true } }, play: chooseAddress };+export const LookupUnavailable: Story = { name: "Address lookup temporarily unavailable", parameters: { agentmailScenario: { checkFailed: true } }, play: chooseAddress };+export const ExistingInbox: Story = { name: "Use an existing inbox", play: async context => {+ await chooseAddress(context);+ await userEvent.click(within(context.canvasElement).getByRole("button", { name: "Use an existing inbox" }));+} };+export const InboxScopedKey: Story = { name: "Inbox-only key · Choose an account key", args: { savedConnection: false },+ parameters: { agentmailScenario: { scopedKey: true } }, play: async context => {+ await chooseAgent(context);+ const canvas = within(context.canvasElement);+ await userEvent.selectOptions(await canvas.findByLabelText("API key"), CONNECTION);+ await userEvent.click(canvas.getByRole("button", { name: "Continue" }));+ await expect(await canvas.findByText(/That key only connects [email protected]/)).toBeVisible();+ await expect(canvas.queryByLabelText("Ralph’s email address")).not.toBeInTheDocument();+ } };+export const SwitchScopedAccount: Story = { name: "Inbox-only key · Switch to an editable address", args: { savedConnection: false },+ parameters: { agentmailScenario: { scopedKey: true } }, play: async context => {+ await InboxScopedKey.play!(context);+ const canvas = within(context.canvasElement);+ await userEvent.selectOptions(await canvas.findByLabelText("API key"), OTHER_ACCOUNT);+ await userEvent.click(canvas.getByRole("button", { name: "Continue" }));+ await waitFor(() => expect(canvas.getByLabelText("Email domain")).toHaveValue("paperclip.example"));+ await userEvent.clear(canvas.getByLabelText("Ralph’s email address"));+ await userEvent.type(canvas.getByLabelText("Ralph’s email address"), "ralph-mail");+ await expect(canvas.getByLabelText("Ralph’s email address")).toHaveValue("ralph-mail");+ } };+export const SavedApiKey: Story = { name: "Saved account key · Suggested automatically", args: { savedConnection: false }, play: chooseAddress };+export const AdvancedOptions: Story = { name: "Advanced · Email settings", play: async context => {+ await chooseAddress(context);+ await userEvent.click(within(context.canvasElement).getByText("Advanced options"));+} };+export const MissingTrustBoundary: Story = { name: "Existing low-trust agent · Work boundary required",+ parameters: { agentmailScenario: { missingBoundary: true } }, play: chooseAgent };+export const NewConnection: Story = { name: "First time · API key alongside the agent", args: { savedConnection: false }, parameters: { agentmailScenario: { noSavedKeys: true } } };+export const InvalidKey: Story = { name: "Error · Invalid API key", args: { savedConnection: false }, parameters: { agentmailScenario: { noSavedKeys: true } }, play: async context => {+ await chooseAgent(context);+ const canvas = within(context.canvasElement);+ await userEvent.type(canvas.getByLabelText("API key"), "invalid-key");+ await userEvent.click(canvas.getByRole("button", { name: "Continue" }));+ await expect(await canvas.findByRole("alert")).toHaveTextContent("AgentMail rejected the API key");+} };+export const ProviderDenied: Story = { name: "Error · Provider permission denied", parameters: { agentmailScenario: { denySetup: true } }, play: async context => {+ await chooseAddress(context);+ await waitFor(() => expect(within(context.canvasElement).getByRole("button", { name: "Create email address" })).toBeEnabled());+ await userEvent.click(within(context.canvasElement).getByRole("button", { name: "Create email address" }));+ await expect(await within(context.canvasElement).findByRole("alert")).toHaveTextContent("AgentMail did not allow");+} };+export const Ready: Story = { name: "Done · Email ready", play: async context => {+ await chooseAddress(context);+ const canvas = within(context.canvasElement);+ await waitFor(() => expect(canvas.getByRole("button", { name: "Create email address" })).toBeEnabled());+ await userEvent.click(canvas.getByRole("button", { name: "Create email address" }));+ await expect(await canvas.findByRole("heading", { name: "Your agent’s email is ready" })).toBeVisible();+} };+export const Mobile: Story = { name: "Mobile · Pick their email", globals: { viewport: { value: "mobile1", isRotated: false } }, parameters: { waitForViewport: true }, play: chooseAddress };+export const TestedWalkthrough: Story = { name: "Verification · Correct a taken address and finish", play: async context => {+ await takenAddress(context);+ const canvas = within(context.canvasElement);+ await userEvent.click(canvas.getByRole("button", { name: "[email protected]" }));+ await expect(canvas.getByLabelText("Ralph’s email address")).toHaveValue("taken-agent");+ await expect(canvas.queryByRole("alert")).not.toBeInTheDocument();+ await waitFor(() => expect(canvas.getByRole("button", { name: "Create email address" })).toBeEnabled());+ await userEvent.click(canvas.getByRole("button", { name: "Create email address" }));+ await expect(await canvas.findByRole("heading", { name: "Your agent’s email is ready" })).toBeVisible();+ await expect(canvas.getByText("[email protected]", { exact: true })).toBeVisible();+ await userEvent.click(canvas.getByRole("button", { name: "Done" }));+ await expect(await canvas.findByText("Setup complete.")).toBeVisible();+} };diff --git a/ui/storybook/stories/agentmail-settings.stories.tsx b/ui/storybook/stories/agentmail-settings.stories.tsxnew file mode 100644index 0000000000..0d22f49ddc--- /dev/null+++ b/ui/storybook/stories/agentmail-settings.stories.tsx@@ -0,0 +1,81 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { expect, userEvent, within } from "storybook/test";+import { EmailEndpointSettings } from "@/pages/apps/chat/EmailEndpointSetup";+import type { EmailEndpointSummary } from "@paperclipai/shared";++const COMPANY = "company-storybook";+const ENDPOINT = "agentmail-settings-preview";+const meta = {+ title: "Connections/AgentMail settings",+ component: EmailEndpointSettings,+ parameters: { layout: "padded" },+ args: { endpointId: ENDPOINT, companyId: COMPANY, assignedAgentName: "Ralph" },+ beforeEach(context) {+ let inbox: EmailEndpointSummary = {+ id: ENDPOINT, companyId: COMPANY, connectionId: "preview-account", assignedAgentId: "ralph",+ address: "[email protected]", status: "active", receiveMode: "websocket",+ lastSyncAt: "2026-10-02T12:40:00Z", lastError: null,+ ...context.parameters.inbox,+ };+ const original = window.fetch;+ window.fetch = async (input, init) => {+ const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url, location.origin);+ if (url.pathname === `/api/companies/${COMPANY}/email/inboxes`) return Response.json([inbox]);+ if (url.pathname === `/api/email/inboxes/${ENDPOINT}/control`) {+ const { action } = JSON.parse(String(init?.body));+ inbox = { ...inbox, status: action === "pause" ? "paused" : action === "remove" ? "archived" : "active" };+ return Response.json(inbox);+ }+ if (url.pathname === `/api/email/inboxes/${ENDPOINT}/reconnect`) {+ const { receiveMode } = JSON.parse(String(init?.body));+ inbox = { ...inbox, status: "active", receiveMode, lastError: null };+ return Response.json(inbox);+ }+ return original(input, init);+ };+ return () => { window.fetch = original; };+ },+} satisfies Meta<typeof EmailEndpointSettings>;+export default meta;+type Story = StoryObj<typeof meta>;++export const Receiving: Story = { play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const copyAddress = await canvas.findByRole("button", { name: "Copy email address" });+ await expect(copyAddress).toHaveTextContent("[email protected]");+ await expect(canvas.getByRole("link", { name: "View inbox" })).toHaveAttribute(+ "href", "https://console.agentmail.to/dashboard/inboxes/ralph%40paperclip.example");+} };+export const Paused: Story = { parameters: { inbox: { status: "paused" } }, play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(await canvas.findByRole("button", { name: "Resume" })).toBeVisible();+ await expect(canvas.queryByText(/Send an email to this address to start a task/)).not.toBeInTheDocument();+} };+export const AddressNotAssigned: Story = { parameters: { inbox: { status: "draft", address: null, lastSyncAt: null } }, play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(await canvas.findByRole("heading", { name: "Email inbox" })).toBeVisible();+ await expect(canvas.queryByRole("button", { name: "Copy email address" })).not.toBeInTheDocument();+ await expect(canvas.queryByRole("link", { name: "View inbox" })).not.toBeInTheDocument();+ await expect(canvas.queryByText(/Send an email to this address to start a task/)).not.toBeInTheDocument();+} };+export const NeedsAttention: Story = { parameters: { inbox: { status: "revoked", lastError: "AgentMail rejected the API key. Reconnect this inbox with a valid key." } }, play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(await canvas.findByText("Access revoked")).toBeVisible();+ await expect(canvas.queryByRole("button", { name: "Resume" })).not.toBeInTheDocument();+ await expect(canvas.getByLabelText("New API key")).toBeVisible();+} };+export const Webhook: Story = { parameters: { inbox: { receiveMode: "webhook", lastSyncAt: null } } };+export const LongAddress: Story = { parameters: { inbox: { address: "[email protected]" } } };+export const Mobile: Story = { globals: { viewport: { value: "mobile1", isRotated: false } }, parameters: { waitForViewport: true } };+export const Reconnect: Story = { play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await canvas.findByRole("heading", { name: "[email protected]" });+ const disclosure = canvas.getByText("Reconnect inbox", { selector: "summary" });+ await expect(canvas.queryByLabelText("New API key")).not.toBeVisible();+ await userEvent.click(disclosure);+ await expect(canvas.getByLabelText("New API key")).toBeVisible();+ await expect(canvas.getByRole("link", { name: /Get an AgentMail API key/ })).toHaveAttribute("href", "https://console.agentmail.to/dashboard/api-keys");+ await userEvent.type(canvas.getByLabelText("New API key"), "storybook-placeholder-key");+ await userEvent.click(canvas.getByRole("button", { name: "Reconnect inbox" }));+ await expect(await canvas.findByText("Inbox reconnected.")).toBeVisible();+} };diff --git a/ui/storybook/stories/in-feed-connections.stories.tsx b/ui/storybook/stories/in-feed-connections.stories.tsxindex 0f0df58c76..455c5c85e3 100644--- a/ui/storybook/stories/in-feed-connections.stories.tsx+++ b/ui/storybook/stories/in-feed-connections.stories.tsx@@ -31,7 +31,7 @@ const connection = {createdByAgentId: null, createdByUserId: "user-board", createdAt: new Date("2026-09-07"), updatedAt: new Date("2026-09-07"),} satisfies ToolConnection;-type Scenario = { ai?: boolean; missingAiAccount?: "anthropic" | "openai"; ownerOnly?: boolean; checking?: boolean; count?: number; loading?: boolean; loadError?: boolean; completeError?: boolean; submitting?: boolean; denied?: boolean };+type Scenario = { email?: boolean; ai?: boolean; missingAiAccount?: "anthropic" | "openai"; ownerOnly?: boolean; checking?: boolean; count?: number; loading?: boolean; loadError?: boolean; completeError?: boolean; submitting?: boolean; denied?: boolean };const meta: Meta = {title: "Connections/In-task connections",parameters: { layout: "padded" },@@ -45,7 +45,7 @@ const meta: Meta = {channel.on("unhandledErrorsWhilePlaying", reportPlayError);const original = window.fetch;const scenario = (parameters.connectionScenario ?? {}) as Scenario;- let current = structuredClone(scenario.missingAiAccount ? missingAiInteraction(scenario.missingAiAccount) : scenario.ai ? aiPending : pending);+ let current = structuredClone(scenario.email ? emailPending : scenario.missingAiAccount ? missingAiInteraction(scenario.missingAiAccount) : scenario.ai ? aiPending : pending);window.fetch = async (input, init) => {const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url, window.location.origin);if (scenario.missingAiAccount) {@@ -65,6 +65,14 @@ const meta: Meta = {apps: CONNECTABLE_APP_DEFINITIONS.filter((app) => ["notion", "github", "posthog", "zapier"].includes(app.slug)),capabilities: { canCreateOrganizationGrant: true, canSetCompanyInstall: true },});+ if (scenario.email && url.pathname.endsWith("/email/connections") && init?.method === "POST") {+ return scenario.completeError+ ? Response.json({ error: "This key could not be verified. Check it and try again." }, { status: 422 })+ : Response.json({ id: connection.id });+ }+ if (scenario.email && url.pathname.endsWith("/email/inboxes") && init?.method === "POST") {+ return Response.json({ connectionId: connection.id });+ }if (scenario.ai && url.pathname.endsWith("/ai-connections") && init?.method === "POST") return scenario.completeError? Response.json({ error: "This key could not be verified. Check it and try again." }, { status: 422 }): Response.json({ connectionId: aiAccount.id, grantId: aiAccount.grantId });@@ -76,12 +84,13 @@ const meta: Meta = {return Response.json({ version: 1, interaction: current, requestedAgentId: pending.payload.requestingAgentId,service: { service: "notion", name: "Notion", state: "available", methods: [] },...(scenario.ai ? { aiConnection: { provider: scenario.missingAiAccount ?? "openrouter", method: "api_key", mode: "responsible_user" }, ...(scenario.missingAiAccount ? {} : { aiRepair: { connection: aiAccount, canReconnect: !scenario.ownerOnly } }) } : {}),+ ...(scenario.email ? { emailSetup: { credentialConnectionId: null, readyConnectionId: null } } : {}),existingConnections: Array.from({ length: scenario.count ?? 0 }, (_, i) => ({ ...connection, id: `${connection.id.slice(0, -1)}${i}`, name: i ? "Team Notion workspace" : connection.name })),});}if (scenario.submitting) return new Promise<Response>(() => {});if (scenario.completeError || scenario.denied) return Response.json({ error: scenario.denied ? "You no longer have permission to share this connection." : "Connection has no permitted tools. Review action permissions and try again." }, { status: scenario.denied ? 403 : 409 });- if (url.pathname.endsWith("decline")) current = { ...declined, id: pending.id };+ if (url.pathname.endsWith("decline")) current = { ...declined, id: pending.id, payload: current.payload };else if (url.pathname.endsWith("complete")) current = { ...connected, id: pending.id, payload: current.payload };else if (url.pathname.endsWith("phase")) current = { ...current, payload: { ...current.payload, phase: "needs_retry" } };return Response.json(current);@@ -118,6 +127,30 @@ const reuse: Story["play"] = async (context) => {await userEvent.click(await within(document.body).findByRole("button", { name: /My Notion workspace/ }));};+const emailPending: ConnectionIntentInteraction = {+ ...pending,+ payload: { ...pending.payload, serviceSlug: "agentmail", serviceName: "AgentMail",+ serviceLogoUrl: "/brands/agentmail.svg", purpose: "channel" },+};+export const AgentMailInline = card(emailPending, { email: true });+export const AgentMailNarrow: Story = {+ ...AgentMailInline, globals: { viewport: { value: "mobile1", isRotated: false } },+};+const enterEmailKey: Story["play"] = async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await userEvent.type(await canvas.findByLabelText("API key"), "storybook-fixture-key");+ await userEvent.click(canvas.getByRole("button", { name: "Connect AgentMail" }));+};+export const AgentMailConnected: Story = {+ ...AgentMailInline,+ play: async context => {+ await enterEmailKey!(context);+ await expect(await within(context.canvasElement).findByText("AgentMail connected")).toBeVisible();+ },+};+export const AgentMailInvalidKey: Story = {+ ...card(emailPending, { email: true, completeError: true }), play: enterEmailKey,+};export const NewConnection = card();export const EligibleReuse = card(pending, { count: 1 });export const Authorizing = card(authorizing);diff --git a/ui/storybook/stories/primitives-coverage.stories.tsx b/ui/storybook/stories/primitives-coverage.stories.tsxindex f305ae9805..164f97f936 100644--- a/ui/storybook/stories/primitives-coverage.stories.tsx+++ b/ui/storybook/stories/primitives-coverage.stories.tsx@@ -84,6 +84,30 @@ export default meta;type Story = StoryObj<typeof meta>;+export const NativeSelects: Story = {+ render: () => <StoryFrame>+ <div className="grid max-w-3xl gap-6 md:grid-cols-2">+ {(["Default", "Disabled", "Long value", "Right to left"] as const).map(label => <label key={label} className="space-y-2 text-sm" dir={label === "Right to left" ? "rtl" : undefined}>+ <span className="block">{label}</span>+ <select className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm disabled:opacity-50" disabled={label === "Disabled"} defaultValue="live">+ <option value="live">{label === "Long value" ? "A longer selected value beside the inset caret" : "Live connection"}</option>+ <option value="webhook">Webhook</option>+ </select>+ </label>)}+ <label className="space-y-2 text-sm"><span className="block">Multiple selection</span>+ <select multiple className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" defaultValue={["live"]}>+ <option value="live">Live connection</option><option value="webhook">Webhook</option>+ </select>+ </label>+ <label className="space-y-2 text-sm"><span className="block">Listbox</span>+ <select size={3} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" defaultValue="live">+ <option value="live">Live connection</option><option value="webhook">Webhook</option>+ </select>+ </label>+ </div>+ </StoryFrame>,+};+function StoryFrame({ children }: { children: React.ReactNode }) {return (<div className="paperclip-story">